updates.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2002 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * This is the actual SILC server than handles everything relating to
22  * servicing the SILC connections. This is also a SILC router as a router
23  * is also normal server.
24  */
25 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
47
48 /* Allocates a new SILC server object. This has to be done before the server
49    can be used. After allocation one must call silc_server_init to initialize
50    the server. The new allocated server object is returned to the new_server
51    argument. */
52
53 int silc_server_alloc(SilcServer *new_server)
54 {
55   SilcServer server;
56
57   SILC_LOG_DEBUG(("Allocating new server object"));
58
59   server = silc_calloc(1, sizeof(*server));
60   server->server_type = SILC_SERVER;
61   server->standalone = TRUE;
62   server->local_list = silc_calloc(1, sizeof(*server->local_list));
63   server->global_list = silc_calloc(1, sizeof(*server->global_list));
64   server->pending_commands = silc_dlist_init();
65 #ifdef SILC_SIM
66   server->sim = silc_dlist_init();
67 #endif
68
69   *new_server = server;
70
71   return TRUE;
72 }
73
74 /* Free's the SILC server object. This is called at the very end before
75    the program ends. */
76
77 void silc_server_free(SilcServer server)
78 {
79   if (server) {
80 #ifdef SILC_SIM
81     SilcSim sim;
82
83     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84       silc_dlist_del(server->sim, sim);
85       silc_sim_free(sim);
86     }
87     silc_dlist_uninit(server->sim);
88 #endif
89
90     silc_server_config_unref(&server->config_ref);
91     if (server->rng)
92       silc_rng_free(server->rng);
93     if (server->pkcs)
94       silc_pkcs_free(server->pkcs);
95     if (server->public_key)
96       silc_pkcs_public_key_free(server->public_key);
97     if (server->private_key)
98       silc_pkcs_private_key_free(server->private_key);
99     if (server->pending_commands)
100       silc_dlist_uninit(server->pending_commands);
101     if (server->id_entry)
102       silc_idlist_del_server(server->local_list, server->id_entry);
103
104     silc_idcache_free(server->local_list->clients);
105     silc_idcache_free(server->local_list->servers);
106     silc_idcache_free(server->local_list->channels);
107     silc_idcache_free(server->global_list->clients);
108     silc_idcache_free(server->global_list->servers);
109     silc_idcache_free(server->global_list->channels);
110
111     silc_free(server->sockets);
112     silc_free(server);
113   }
114 }
115
116 /* Opens a listening port.
117    XXX This function will become more general and will support multiple
118    listening ports */
119
120 static bool silc_server_listen(SilcServer server, int *sock)
121 {
122
123   *sock = silc_net_create_server(server->config->server_info->port,
124                                 server->config->server_info->server_ip);
125   if (*sock < 0) {
126     SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
127                     server->config->server_info->server_ip,
128                     server->config->server_info->port));
129     return FALSE;
130   }
131   return TRUE;
132 }
133
134 /* Initializes the entire SILC server. This is called always before running
135    the server. This is called only once at the initialization of the program.
136    This binds the server to its listenning port. After this function returns
137    one should call silc_server_run to start the server. This returns TRUE
138    when everything is ok to run the server. Configuration file must be
139    read and parsed before calling this. */
140
141 bool silc_server_init(SilcServer server)
142 {
143   int sock;
144   SilcServerID *id;
145   SilcServerEntry id_entry;
146   SilcIDListPurge purge;
147   SilcSocketConnection newsocket = NULL;
148
149   SILC_LOG_DEBUG(("Initializing server"));
150   assert(server);
151   assert(server->config);
152
153   silc_server_config_ref(&server->config_ref, server->config, 
154                          server->config);
155
156   /* Set public and private keys */
157   if (!server->config->server_info ||
158       !server->config->server_info->public_key ||
159       !server->config->server_info->private_key) {
160     SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
161     return FALSE;
162   }
163
164   /* Steal public and private key from the config object */
165   server->public_key = server->config->server_info->public_key;
166   server->private_key = server->config->server_info->private_key;
167   server->config->server_info->public_key = NULL;
168   server->config->server_info->private_key = NULL;
169
170   /* Register all configured ciphers, PKCS and hash functions. */
171   if (!silc_server_config_register_ciphers(server))
172     silc_cipher_register_default();
173   if (!silc_server_config_register_pkcs(server))
174     silc_pkcs_register_default();
175   if (!silc_server_config_register_hashfuncs(server))
176     silc_hash_register_default();
177   if (!silc_server_config_register_hmacs(server))
178     silc_hmac_register_default();
179
180   /* Initialize random number generator for the server. */
181   server->rng = silc_rng_alloc();
182   silc_rng_init(server->rng);
183   silc_rng_global_init(server->rng);
184
185   /* Initialize hash functions for server to use */
186   silc_hash_alloc("md5", &server->md5hash);
187   silc_hash_alloc("sha1", &server->sha1hash);
188
189   /* Allocate PKCS context for local public and private keys */
190   if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
191     goto err;
192   silc_pkcs_public_key_set(server->pkcs, server->public_key);
193   silc_pkcs_private_key_set(server->pkcs, server->private_key);
194
195   /* Initialize the scheduler */
196   server->schedule = silc_schedule_init(server->config->param.connections_max);
197   if (!server->schedule)
198     goto err;
199
200   /* First, register log files configuration for error output */
201   silc_server_config_setlogfiles(server);
202
203   /* Initialize ID caches */
204   server->local_list->clients =
205     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
206   server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
207   server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
208
209   /* These are allocated for normal server as well as these hold some
210      global information that the server has fetched from its router. For
211      router these are used as they are supposed to be used on router. */
212   server->global_list->clients =
213     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
214   server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
215   server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
216
217   /* Create a listening server */
218   if (!silc_server_listen(server, &sock))
219     goto err;
220
221   /* Set socket to non-blocking mode */
222   silc_net_set_socket_nonblock(sock);
223   server->sock = sock;
224
225   /* Allocate the entire socket list that is used in server. Eventually
226      all connections will have entry in this table (it is a table of
227      pointers to the actual object that is allocated individually
228      later). */
229   server->sockets = silc_calloc(server->config->param.connections_max,
230                                 sizeof(*server->sockets));
231   if (!server->sockets)
232     goto err;
233
234   /* Add ourselves also to the socket table. The entry allocated above
235      is sent as argument for fast referencing in the future. */
236   silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
237   server->sockets[sock] = newsocket;
238
239   /* Perform name and address lookups to resolve the listenning address
240      and port. */
241   if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
242                                     &newsocket->ip)) {
243     if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
244         !newsocket->ip) {
245       SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
246                       newsocket->hostname ? newsocket->hostname :
247                       newsocket->ip ? newsocket->ip : ""));
248       server->stat.conn_failures++;
249       goto err;
250     }
251     if (!newsocket->hostname)
252       newsocket->hostname = strdup(newsocket->ip);
253   }
254   newsocket->port = silc_net_get_local_port(sock);
255
256   /* Create a Server ID for the server. */
257   silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
258   if (!id)
259     goto err;
260
261   server->id = id;
262   server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
263   server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
264   server->id_type = SILC_ID_SERVER;
265   server->server_name = server->config->server_info->server_name;
266   server->config->server_info->server_name = NULL;
267
268   /* Add ourselves to the server list. We don't have a router yet
269      beacuse we haven't established a route yet. It will be done later.
270      For now, NULL is sent as router. This allocates new entry to
271      the ID list. */
272   id_entry =
273     silc_idlist_add_server(server->local_list, strdup(server->server_name),
274                            server->server_type, server->id, NULL, NULL);
275   if (!id_entry) {
276     SILC_LOG_ERROR(("Could not add ourselves to cache"));
277     goto err;
278   }
279   id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
280   
281   /* Put the allocated socket pointer also to the entry allocated above
282      for fast back-referencing to the socket list. */
283   newsocket->user_data = (void *)id_entry;
284   id_entry->connection = (void *)newsocket;
285   server->id_entry = id_entry;
286
287   /* Register protocols */
288   silc_server_protocols_register();
289
290   /* Add the first task to the scheduler. This is task that is executed by
291      timeout. It expires as soon as the caller calls silc_server_run. This
292      task performs authentication protocol and key exchange with our
293      primary router. */
294   silc_schedule_task_add(server->schedule, sock,
295                          silc_server_connect_to_router,
296                          (void *)server, 0, 1,
297                          SILC_TASK_TIMEOUT,
298                          SILC_TASK_PRI_NORMAL);
299
300   /* Add listener task to the scheduler. This task receives new connections
301      to the server. This task remains on the queue until the end of the
302      program. */
303   silc_schedule_task_add(server->schedule, sock,
304                          silc_server_accept_new_connection,
305                          (void *)server, 0, 0,
306                          SILC_TASK_FD,
307                          SILC_TASK_PRI_NORMAL);
308   server->listenning = TRUE;
309
310   /* If server connections has been configured then we must be router as
311      normal server cannot have server connections, only router connections. */
312   if (server->config->servers) {
313     SilcServerConfigServer *ptr = server->config->servers;
314
315     server->server_type = SILC_ROUTER;
316     while (ptr) {
317       if (ptr->backup_router) {
318         server->server_type = SILC_BACKUP_ROUTER;
319         server->backup_router = TRUE;
320         server->id_entry->server_type = SILC_BACKUP_ROUTER;
321         break;
322       }
323       ptr = ptr->next;
324     }
325   }
326
327   /* Register the ID Cache purge task. This periodically purges the ID cache
328      and removes the expired cache entries. */
329
330   /* Clients local list */
331   purge = silc_calloc(1, sizeof(*purge));
332   purge->cache = server->local_list->clients;
333   purge->schedule = server->schedule;
334   purge->timeout = 600;
335   silc_schedule_task_add(purge->schedule, 0,
336                          silc_idlist_purge,
337                          (void *)purge, purge->timeout, 0,
338                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
339
340   /* Clients global list */
341   purge = silc_calloc(1, sizeof(*purge));
342   purge->cache = server->global_list->clients;
343   purge->schedule = server->schedule;
344   purge->timeout = 300;
345   silc_schedule_task_add(purge->schedule, 0,
346                          silc_idlist_purge,
347                          (void *)purge, purge->timeout, 0,
348                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
349
350   SILC_LOG_DEBUG(("Server initialized"));
351
352   /* We are done here, return succesfully */
353   return TRUE;
354
355  err:
356   silc_net_close_server(sock);
357   return FALSE;
358 }
359
360 /* This function basically reads the config file again and switches the config
361    object pointed by the server object. After that, we have to fix various
362    things such as the server_name and the listening ports.
363    Keep in mind that we no longer have the root privileges at this point. */
364
365 bool silc_server_rehash(SilcServer server)
366 {
367   SilcServerConfig newconfig;
368
369   /* Our old config is gone now. We'll unreference our reference made in
370      silc_server_init and then destroy it since we are destroying it 
371      underneath the application (layer which called silc_server_init). */
372   silc_server_config_unref(&server->config_ref);
373   silc_server_config_destroy(server->config);
374
375   /* Reset the logging system */
376   silc_log_quick = TRUE;
377   silc_log_flush_all();
378
379   /* Start the main rehash phase (read again the config file) */
380   SILC_LOG_INFO(("Rehashing server"));
381   newconfig = silc_server_config_alloc(server->config_file);
382   if (!newconfig) {
383     SILC_LOG_ERROR(("Rehash FAILED."));
384     return FALSE;
385   }
386
387   /* Take new config context */
388   server->config = newconfig;
389   silc_server_config_ref(&server->config_ref, server->config, server->config);
390
391   /* Set public and private keys */
392   if (!server->config->server_info ||
393       !server->config->server_info->public_key ||
394       !server->config->server_info->private_key) {
395     SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
396     return FALSE;
397   }
398
399   /* Fix the server_name field */
400   if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
401     /* We don't need any update */
402     silc_free(newconfig->server_info->server_name);
403     newconfig->server_info->server_name = NULL;
404   } else {
405     silc_free(server->server_name);
406     server->server_name = newconfig->server_info->server_name;
407     newconfig->server_info->server_name = NULL;
408
409     /* Update the idcache list with a fresh pointer */
410     silc_free(server->id_entry->server_name);
411     server->id_entry->server_name = strdup(server->server_name);
412     silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
413     silc_idcache_add(server->local_list->servers, 
414                      server->id_entry->server_name,
415                      server->id_entry->id, server->id_entry, 0, NULL);
416   }
417
418   silc_server_config_setlogfiles(server);
419
420   /* Change new key pair if necessary */
421   if (server->config->server_info->public_key &&
422       !silc_pkcs_public_key_compare(server->public_key,
423                                     server->config->server_info->public_key)) {
424     silc_pkcs_public_key_free(server->public_key);
425     silc_pkcs_private_key_free(server->private_key);
426     server->public_key = server->config->server_info->public_key;
427     server->private_key = server->config->server_info->private_key;
428     server->config->server_info->public_key = NULL;
429     server->config->server_info->private_key = NULL;
430
431     /* Allocate PKCS context for local public and private keys */
432     silc_pkcs_free(server->pkcs);
433     if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
434       return FALSE;
435     silc_pkcs_public_key_set(server->pkcs, server->public_key);
436     silc_pkcs_private_key_set(server->pkcs, server->private_key);
437   }
438
439   return TRUE;
440 }
441
442 /* Drop root privileges. If some system call fails, die. */
443
444 void silc_server_drop(SilcServer server)
445 {
446   /* Are we executing silcd as root or a regular user? */
447   if (geteuid()) {
448     SILC_LOG_DEBUG(("Server started as user"));
449   }
450   else {
451     struct passwd *pw;
452     struct group *gr;
453     char *user, *group;
454
455     SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
456
457     /* Get the values given for user and group in configuration file */
458     user = server->config->server_info->user;
459     group = server->config->server_info->group;
460
461     if (!user || !group) {
462       fprintf(stderr, "Error:"
463        "\tSILC server must not be run as root.  For the security of your\n"
464        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
465        "\tuser account.  Modify the ServerInfo configuration section to run\n"
466        "\tthe server as non-root user.\n");
467       exit(1);
468     }
469
470     /* Check whether the user/group does not begin with a number */
471     if (isdigit(user[0]) || isdigit(group[0])) {
472       SILC_LOG_DEBUG(("User and/or group starts with a number"));
473       fprintf(stderr, "Invalid user and/or group information\n");
474       fprintf(stderr, "Please assign them as names, not numbers\n");
475       exit(1);
476     }
477
478     if (!(pw = getpwnam(user))) {
479       fprintf(stderr, "Error: No such user %s found.\n", user);
480       exit(1);
481     }
482     if (!(gr = getgrnam(group))) {
483       fprintf(stderr, "Error: No such group %s found.\n", group);
484       exit(1);
485     }
486
487     /* Check whether user and/or group is set to root. If yes, exit
488        immediately. Otherwise, setgid and setuid server to user.group */
489     if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
490       fprintf(stderr, "Error:"
491        "\tSILC server must not be run as root.  For the security of your\n"
492        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
493        "\tuser account.  Modify the ServerInfo configuration section to run\n"
494        "\tthe server as non-root user.\n");
495       exit(1);
496     }
497
498     SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
499     if (setgid(gr->gr_gid) != 0) {
500       fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
501               group, gr->gr_gid);
502       exit(1);
503     }
504 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
505     SILC_LOG_DEBUG(("Removing supplementary groups"));
506     if (setgroups(0, NULL) != 0) {
507       fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
508       exit(1);
509     }
510     SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
511     if (initgroups(user, gr->gr_gid) != 0) {
512       fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
513               "Exiting.\n", user, gr->gr_gid);
514       exit(1);
515     }
516 #endif
517     SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
518     if (setuid(pw->pw_uid) != 0) {
519       fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
520               user, pw->pw_uid);
521       exit(1);
522     }
523   }
524 }
525
526 /* Fork server to background */
527
528 void silc_server_daemonise(SilcServer server)
529 {
530   int i;
531
532   SILC_LOG_DEBUG(("Forking SILC server to background"));
533
534   if ((i = fork()) < 0) {
535     fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
536     exit(1);
537   }
538
539   if (i) /* Kill the parent */
540     exit(0);
541
542   server->background = TRUE;
543   setsid();
544
545   /* XXX close stdin, stdout, stderr -- before this, check that all writes
546      to stderr are changed to SILC_SERVER_LOG_ERROR() */
547 }
548
549 /* The heart of the server. This runs the scheduler thus runs the server.
550    When this returns the server has been stopped and the program will
551    be terminated. */
552
553 void silc_server_run(SilcServer server)
554 {
555   SILC_LOG_INFO(("SILC Server started"));
556
557   /* Start the scheduler, the heart of the SILC server. When this returns
558      the program will be terminated. */
559   silc_schedule(server->schedule);
560 }
561
562 /* Stops the SILC server. This function is used to shutdown the server.
563    This is usually called after the scheduler has returned. After stopping
564    the server one should call silc_server_free. */
565
566 void silc_server_stop(SilcServer server)
567 {
568   SILC_LOG_DEBUG(("Stopping server"));
569
570   if (server->schedule) {
571     silc_schedule_stop(server->schedule);
572     silc_schedule_uninit(server->schedule);
573     server->schedule = NULL;
574   }
575
576   silc_server_protocols_unregister();
577
578   SILC_LOG_DEBUG(("Server stopped"));
579 }
580
581 /* Function that is called when the network connection to a router has
582    been established.  This will continue with the key exchange protocol
583    with the remote router. */
584
585 void silc_server_start_key_exchange(SilcServer server,
586                                     SilcServerConnection sconn,
587                                     int sock)
588 {
589   SilcSocketConnection newsocket;
590   SilcProtocol protocol;
591   SilcServerKEInternalContext *proto_ctx;
592   SilcServerConfigRouter *conn =
593     (SilcServerConfigRouter *) sconn->conn.ref_ptr;
594   void *context;
595
596   /* Cancel any possible retry timeouts */
597   silc_schedule_task_del_by_callback(server->schedule,
598                                      silc_server_connect_router);
599
600   /* Set socket options */
601   silc_net_set_socket_nonblock(sock);
602   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
603
604   /* Create socket connection for the connection. Even though we
605      know that we are connecting to a router we will mark the socket
606      to be unknown connection until we have executed authentication
607      protocol. */
608   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
609   server->sockets[sock] = newsocket;
610   newsocket->hostname = strdup(sconn->remote_host);
611   newsocket->ip = strdup(sconn->remote_host);
612   newsocket->port = sconn->remote_port;
613   sconn->sock = newsocket;
614
615   /* Allocate internal protocol context. This is sent as context
616      to the protocol. */
617   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
618   proto_ctx->server = (void *)server;
619   proto_ctx->context = (void *)sconn;
620   proto_ctx->sock = newsocket;
621   proto_ctx->rng = server->rng;
622   proto_ctx->responder = FALSE;
623
624   /* Set Key Exchange flags from configuration, but fall back to global
625      settings too. */
626   SILC_GET_SKE_FLAGS(conn, proto_ctx);
627   if (server->config->param.key_exchange_pfs)
628     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
629
630   /* Perform key exchange protocol. silc_server_connect_to_router_second
631      will be called after the protocol is finished. */
632   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
633                       &protocol, proto_ctx,
634                       silc_server_connect_to_router_second);
635   newsocket->protocol = protocol;
636
637   /* Register a timeout task that will be executed if the protocol
638      is not executed within set limit. */
639   proto_ctx->timeout_task =
640     silc_schedule_task_add(server->schedule, sock,
641                            silc_server_timeout_remote,
642                            server, server->config->key_exchange_timeout, 0,
643                            SILC_TASK_TIMEOUT,
644                            SILC_TASK_PRI_LOW);
645
646   /* Register the connection for network input and output. This sets
647      that scheduler will listen for incoming packets for this connection
648      and sets that outgoing packets may be sent to this connection as
649      well. However, this doesn't set the scheduler for outgoing traffic,
650      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
651      later when outgoing data is available. */
652   context = (void *)server;
653   SILC_REGISTER_CONNECTION_FOR_IO(sock);
654
655   /* Run the protocol */
656   silc_protocol_execute(protocol, server->schedule, 0, 0);
657 }
658
659 /* Timeout callback that will be called to retry connecting to remote
660    router. This is used by both normal and router server. This will wait
661    before retrying the connecting. The timeout is generated by exponential
662    backoff algorithm. */
663
664 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
665 {
666   SilcServerConnection sconn = (SilcServerConnection)context;
667   SilcServer server = sconn->server;
668   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
669   SilcServerConfigConnParams *param =
670                 (conn->param ? conn->param : &server->config->param);
671
672   SILC_LOG_INFO(("Retrying connecting to a router"));
673
674   /* Calculate next timeout */
675   if (sconn->retry_count >= 1) {
676     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
677     if (sconn->retry_timeout > param->reconnect_interval_max)
678       sconn->retry_timeout = param->reconnect_interval_max;
679   } else {
680     sconn->retry_timeout = param->reconnect_interval;
681   }
682   sconn->retry_count++;
683   sconn->retry_timeout = sconn->retry_timeout +
684     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
685
686   /* If we've reached max retry count, give up. */
687   if ((sconn->retry_count > param->reconnect_count) &&
688       !param->reconnect_keep_trying) {
689     SILC_LOG_ERROR(("Could not connect to router, giving up"));
690     silc_server_config_unref(&sconn->conn);
691     silc_free(sconn->remote_host);
692     silc_free(sconn->backup_replace_ip);
693     silc_free(sconn);
694     return;
695   }
696
697   /* We will lookup a fresh pointer later */
698   silc_server_config_unref(&sconn->conn);
699
700   /* Wait one before retrying */
701   silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
702                          context, sconn->retry_timeout, 0,
703                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
704 }
705
706 /* Generic routine to use connect to a router. */
707
708 SILC_TASK_CALLBACK(silc_server_connect_router)
709 {
710   SilcServerConnection sconn = (SilcServerConnection)context;
711   SilcServer server = sconn->server;
712   SilcServerConfigRouter *rconn;
713   int sock;
714
715   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
716                  (sconn->backup ? "backup router" : "router"),
717                  sconn->remote_host, sconn->remote_port));
718
719   server->router_connect = time(NULL);
720   rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
721                                               sconn->remote_port);
722   if (!rconn) {
723     SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
724                    (sconn->backup ? "backup router" : "router"),
725                    sconn->remote_host, sconn->remote_port));
726     silc_free(sconn->remote_host);
727     silc_free(sconn->backup_replace_ip);
728     silc_free(sconn);
729     return;
730   }
731   silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
732
733   /* Connect to remote host */
734   sock = silc_net_create_connection(server->config->server_info->server_ip,
735                                     sconn->remote_port,
736                                     sconn->remote_host);
737   if (sock < 0) {
738     SILC_LOG_ERROR(("Could not connect to router %s:%d",
739                     sconn->remote_host, sconn->remote_port));
740     if (!sconn->no_reconnect)
741       silc_schedule_task_add(server->schedule, 0,
742                              silc_server_connect_to_router_retry,
743                              context, 0, 1, SILC_TASK_TIMEOUT,
744                              SILC_TASK_PRI_NORMAL);
745     else
746       silc_server_config_unref(&sconn->conn);
747     return;
748   }
749
750   /* Continue with key exchange protocol */
751   silc_server_start_key_exchange(server, sconn, sock);
752 }
753
754 /* This function connects to our primary router or if we are a router this
755    establishes all our primary routes. This is called at the start of the
756    server to do authentication and key exchange with our router - called
757    from schedule. */
758
759 SILC_TASK_CALLBACK(silc_server_connect_to_router)
760 {
761   SilcServer server = (SilcServer)context;
762   SilcServerConnection sconn;
763   SilcServerConfigRouter *ptr;
764
765   SILC_LOG_DEBUG(("Connecting to router(s)"));
766
767   if (server->server_type == SILC_SERVER) {
768     SILC_LOG_DEBUG(("We are normal server"));
769   } else if (server->server_type == SILC_ROUTER) {
770     SILC_LOG_DEBUG(("We are router"));
771   } else {
772     SILC_LOG_DEBUG(("We are backup router/normal server"));
773   }
774
775   if (!server->config->routers) {
776     /* There wasn't a configured router, we will continue but we don't
777        have a connection to outside world.  We will be standalone server. */
778     SILC_LOG_DEBUG(("No router(s), server will be standalone"));
779     server->standalone = TRUE;
780     return;
781   }
782
783   /* Create the connections to all our routes */
784   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
785
786     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
787                     ptr->backup_router ? "Backup router" : "Router",
788                     ptr->initiator ? "Initiator" : "Responder",
789                     ptr->host, ptr->port));
790
791     if (ptr->initiator) {
792       /* Allocate connection object for hold connection specific stuff. */
793       sconn = silc_calloc(1, sizeof(*sconn));
794       sconn->server = server;
795       sconn->remote_host = strdup(ptr->host);
796       sconn->remote_port = ptr->port;
797       sconn->backup = ptr->backup_router;
798       if (sconn->backup) {
799         sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
800         sconn->backup_replace_port = ptr->backup_replace_port;
801       }
802
803       if (!server->router_conn && !sconn->backup)
804         server->router_conn = sconn;
805
806       silc_schedule_task_add(server->schedule, fd,
807                              silc_server_connect_router,
808                              (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
809                              SILC_TASK_PRI_NORMAL);
810     }
811   }
812 }
813
814 /* Second part of connecting to router(s). Key exchange protocol has been
815    executed and now we will execute authentication protocol. */
816
817 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
818 {
819   SilcProtocol protocol = (SilcProtocol)context;
820   SilcServerKEInternalContext *ctx =
821     (SilcServerKEInternalContext *)protocol->context;
822   SilcServer server = (SilcServer)ctx->server;
823   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
824   SilcSocketConnection sock = ctx->sock;
825   SilcServerConnAuthInternalContext *proto_ctx;
826   SilcServerConfigRouter *conn = NULL;
827
828   SILC_LOG_DEBUG(("Start"));
829
830   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
831       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
832     /* Error occured during protocol */
833     silc_protocol_free(protocol);
834     sock->protocol = NULL;
835     silc_ske_free_key_material(ctx->keymat);
836     if (ctx->packet)
837       silc_packet_context_free(ctx->packet);
838     if (ctx->ske)
839       silc_ske_free(ctx->ske);
840     silc_free(ctx->dest_id);
841     silc_free(ctx);
842     silc_server_config_unref(&sconn->conn);
843     silc_free(sconn->remote_host);
844     silc_free(sconn->backup_replace_ip);
845     silc_free(sconn);
846     silc_schedule_task_del_by_callback(server->schedule,
847                                        silc_server_failure_callback);
848     silc_server_disconnect_remote(server, sock, "Server closed connection: "
849                                   "Key exchange failed");
850     return;
851   }
852
853   /* We now have the key material as the result of the key exchange
854      protocol. Take the key material into use. Free the raw key material
855      as soon as we've set them into use. */
856   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
857                                         ctx->sock, ctx->keymat,
858                                         ctx->ske->prop->cipher,
859                                         ctx->ske->prop->pkcs,
860                                         ctx->ske->prop->hash,
861                                         ctx->ske->prop->hmac,
862                                         ctx->ske->prop->group,
863                                         ctx->responder)) {
864     silc_protocol_free(protocol);
865     sock->protocol = NULL;
866     silc_ske_free_key_material(ctx->keymat);
867     if (ctx->packet)
868       silc_packet_context_free(ctx->packet);
869     if (ctx->ske)
870       silc_ske_free(ctx->ske);
871     silc_free(ctx->dest_id);
872     silc_free(ctx);
873     silc_server_config_unref(&sconn->conn);
874     silc_free(sconn->remote_host);
875     silc_free(sconn->backup_replace_ip);
876     silc_free(sconn);
877     silc_schedule_task_del_by_callback(server->schedule,
878                                        silc_server_failure_callback);
879     silc_server_disconnect_remote(server, sock, "Server closed connection: "
880                                   "Key exchange failed");
881     return;
882   }
883   silc_ske_free_key_material(ctx->keymat);
884
885   /* Allocate internal context for the authentication protocol. This
886      is sent as context for the protocol. */
887   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
888   proto_ctx->server = (void *)server;
889   proto_ctx->context = (void *)sconn;
890   proto_ctx->sock = sock;
891   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
892   proto_ctx->dest_id_type = ctx->dest_id_type;
893   proto_ctx->dest_id = ctx->dest_id;
894
895   /* Resolve the authentication method used in this connection. Check if
896      we find a match from user configured connections */
897   if (!sconn->conn.ref_ptr)
898     conn = silc_server_config_find_router_conn(server, sock->hostname,
899                                                sock->port);
900   else
901     conn = sconn->conn.ref_ptr;
902
903   if (conn) {
904     /* Match found. Use the configured authentication method. Take only
905        the passphrase, since for public key auth we automatically use
906        our local key pair. */
907     if (conn->passphrase) {
908       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
909         proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
910       } else {
911         proto_ctx->auth_data = strdup(conn->passphrase);
912         proto_ctx->auth_data_len = strlen(conn->passphrase);
913         proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
914       }
915     } else if (conn->publickeys) {
916       proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
917     } else {
918       proto_ctx->auth_meth = SILC_AUTH_NONE;
919     }
920   } else {
921     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
922                     sock->hostname, sock->ip, sock->port));
923     silc_protocol_free(protocol);
924     sock->protocol = NULL;
925     if (ctx->packet)
926       silc_packet_context_free(ctx->packet);
927     if (ctx->ske)
928       silc_ske_free(ctx->ske);
929     silc_free(ctx->dest_id);
930     silc_free(ctx);
931     silc_server_config_unref(&sconn->conn);
932     silc_free(sconn->remote_host);
933     silc_free(sconn->backup_replace_ip);
934     silc_free(sconn);
935     silc_schedule_task_del_by_callback(server->schedule,
936                                        silc_server_failure_callback);
937     silc_server_disconnect_remote(server, sock, "Server closed connection: "
938                                   "Key exchange failed");
939     return;
940   }
941
942   /* Free old protocol as it is finished now */
943   silc_protocol_free(protocol);
944   if (ctx->packet)
945     silc_packet_context_free(ctx->packet);
946   silc_free(ctx);
947   sock->protocol = NULL;
948
949   /* Allocate the authentication protocol. This is allocated here
950      but we won't start it yet. We will be receiving party of this
951      protocol thus we will wait that connecting party will make
952      their first move. */
953   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
954                       &sock->protocol, proto_ctx,
955                       silc_server_connect_to_router_final);
956
957   /* Register timeout task. If the protocol is not executed inside
958      this timelimit the connection will be terminated. */
959   proto_ctx->timeout_task =
960     silc_schedule_task_add(server->schedule, sock->sock,
961                            silc_server_timeout_remote,
962                            (void *)server,
963                            server->config->conn_auth_timeout, 0,
964                            SILC_TASK_TIMEOUT,
965                            SILC_TASK_PRI_LOW);
966
967   /* Run the protocol */
968   silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
969 }
970
971 /* Finalizes the connection to router. Registers a server task to the
972    queue so that we can accept new connections. */
973
974 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
975 {
976   SilcProtocol protocol = (SilcProtocol)context;
977   SilcServerConnAuthInternalContext *ctx =
978     (SilcServerConnAuthInternalContext *)protocol->context;
979   SilcServer server = (SilcServer)ctx->server;
980   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
981   SilcSocketConnection sock = ctx->sock;
982   SilcServerEntry id_entry;
983   SilcBuffer packet;
984   SilcServerHBContext hb_context;
985   unsigned char *id_string;
986   SilcUInt32 id_len;
987   SilcIDListData idata;
988   SilcServerConfigRouter *conn = NULL;
989   SilcServerConfigConnParams *param = NULL;
990
991   SILC_LOG_DEBUG(("Start"));
992
993   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
994       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
995     /* Error occured during protocol */
996     silc_free(ctx->dest_id);
997     silc_server_disconnect_remote(server, sock, "Server closed connection: "
998                                   "Authentication failed");
999     goto out;
1000   }
1001
1002   /* Add a task to the queue. This task receives new connections to the
1003      server. This task remains on the queue until the end of the program. */
1004   if (!server->listenning && !sconn->backup) {
1005     silc_schedule_task_add(server->schedule, server->sock,
1006                            silc_server_accept_new_connection,
1007                            (void *)server, 0, 0,
1008                            SILC_TASK_FD,
1009                            SILC_TASK_PRI_NORMAL);
1010     server->listenning = TRUE;
1011   }
1012
1013   /* Send NEW_SERVER packet to the router. We will become registered
1014      to the SILC network after sending this packet. */
1015   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1016   id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1017   packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1018   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1019   silc_buffer_format(packet,
1020                      SILC_STR_UI_SHORT(id_len),
1021                      SILC_STR_UI_XNSTRING(id_string, id_len),
1022                      SILC_STR_UI_SHORT(strlen(server->server_name)),
1023                      SILC_STR_UI_XNSTRING(server->server_name,
1024                                           strlen(server->server_name)),
1025                      SILC_STR_END);
1026
1027   /* Send the packet */
1028   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1029                           packet->data, packet->len, TRUE);
1030   silc_buffer_free(packet);
1031   silc_free(id_string);
1032
1033   SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1034
1035   /* Check that we do not have this ID already */
1036   id_entry = silc_idlist_find_server_by_id(server->local_list,
1037                                            ctx->dest_id, TRUE, NULL);
1038   if (id_entry) {
1039     silc_idcache_del_by_context(server->local_list->servers, id_entry);
1040   } else {
1041     id_entry = silc_idlist_find_server_by_id(server->global_list,
1042                                              ctx->dest_id, TRUE, NULL);
1043     if (id_entry)
1044       silc_idcache_del_by_context(server->global_list->servers, id_entry);
1045   }
1046
1047   SILC_LOG_DEBUG(("New server id(%s)",
1048                   silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1049
1050   /* Add the connected router to global server list */
1051   id_entry = silc_idlist_add_server(server->global_list,
1052                                     strdup(sock->hostname),
1053                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
1054   if (!id_entry) {
1055     silc_free(ctx->dest_id);
1056     SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1057     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1058                                   "Authentication failed");
1059     goto out;
1060   }
1061
1062   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1063   silc_free(sock->user_data);
1064   sock->user_data = (void *)id_entry;
1065   sock->type = SILC_SOCKET_TYPE_ROUTER;
1066   idata = (SilcIDListData)sock->user_data;
1067   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1068
1069   conn = sconn->conn.ref_ptr;
1070   param = &server->config->param;
1071   if (conn && conn->param)
1072     param = conn->param;
1073
1074   /* Perform keepalive. The `hb_context' will be freed automatically
1075      when finally calling the silc_socket_free function. */
1076   hb_context = silc_calloc(1, sizeof(*hb_context));
1077   hb_context->server = server;
1078   silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1079                             silc_server_perform_heartbeat,
1080                             server->schedule);
1081
1082   /* Register re-key timeout */
1083   idata->rekey->timeout = param->key_exchange_rekey;
1084   idata->rekey->context = (void *)server;
1085   silc_schedule_task_add(server->schedule, sock->sock,
1086                          silc_server_rekey_callback,
1087                          (void *)sock, idata->rekey->timeout, 0,
1088                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1089
1090   if (!sconn->backup) {
1091     /* Mark this router our primary router if we're still standalone */
1092     if (server->standalone) {
1093       server->id_entry->router = id_entry;
1094       server->router = id_entry;
1095       server->standalone = FALSE;
1096
1097       /* If we are router then announce our possible servers. */
1098       if (server->server_type == SILC_ROUTER)
1099         silc_server_announce_servers(server, FALSE, 0,
1100                                      server->router->connection);
1101
1102       /* Announce our clients and channels to the router */
1103       silc_server_announce_clients(server, 0, server->router->connection);
1104       silc_server_announce_channels(server, 0, server->router->connection);
1105     }
1106   } else {
1107     /* Add this server to be our backup router */
1108     silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1109                            sconn->backup_replace_port, FALSE);
1110   }
1111
1112   sock->protocol = NULL;
1113
1114   /* Call the completion callback to indicate that we've connected to
1115      the router */
1116   if (sconn->callback)
1117     (*sconn->callback)(server, id_entry, sconn->callback_context);
1118
1119  out:
1120   /* Free the temporary connection data context */
1121   if (sconn) {
1122     silc_server_config_unref(&sconn->conn);
1123     silc_free(sconn->remote_host);
1124     silc_free(sconn->backup_replace_ip);
1125     silc_free(sconn);
1126   }
1127   if (sconn == server->router_conn)
1128     server->router_conn = NULL;
1129
1130   /* Free the protocol object */
1131   if (sock->protocol == protocol)
1132     sock->protocol = NULL;
1133   silc_protocol_free(protocol);
1134   if (ctx->packet)
1135     silc_packet_context_free(ctx->packet);
1136   if (ctx->ske)
1137     silc_ske_free(ctx->ske);
1138   if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1139     silc_free(ctx->auth_data);
1140   silc_free(ctx);
1141 }
1142
1143 /* Host lookup callback that is called after the incoming connection's
1144    IP and FQDN lookup is performed. This will actually check the acceptance
1145    of the incoming connection and will register the key exchange protocol
1146    for this connection. */
1147
1148 static void
1149 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1150                                          void *context)
1151 {
1152   SilcServer server = (SilcServer)context;
1153   SilcServerKEInternalContext *proto_ctx;
1154   SilcServerConfigClient *cconfig = NULL;
1155   SilcServerConfigServer *sconfig = NULL;
1156   SilcServerConfigRouter *rconfig = NULL;
1157   SilcServerConfigDeny *deny;
1158   int port;
1159
1160   SILC_LOG_DEBUG(("Start"));
1161
1162   /* Check whether we could resolve both IP and FQDN. */
1163   if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1164                     server->config->require_reverse_lookup)) {
1165     SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1166                     sock->hostname ? sock->hostname :
1167                     sock->ip ? sock->ip : ""));
1168     server->stat.conn_failures++;
1169     silc_server_disconnect_remote(server, sock,
1170                                   "Server closed connection: Unknown host");
1171     return;
1172   }
1173
1174   /* Register the connection for network input and output. This sets
1175      that scheduler will listen for incoming packets for this connection
1176      and sets that outgoing packets may be sent to this connection as well.
1177      However, this doesn't set the scheduler for outgoing traffic, it
1178      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1179      later when outgoing data is available. */
1180   SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1181
1182   SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1183                  sock->ip));
1184
1185   port = server->sockets[server->sock]->port; /* Listenning port */
1186
1187   /* Check whether this connection is denied to connect to us. */
1188   deny = silc_server_config_find_denied(server, sock->ip);
1189   if (!deny)
1190     deny = silc_server_config_find_denied(server, sock->hostname);
1191   if (deny) {
1192     /* The connection is denied */
1193     SILC_LOG_INFO(("Connection %s (%s) is denied",
1194                    sock->hostname, sock->ip));
1195     silc_server_disconnect_remote(server, sock, deny->reason ?
1196                                   deny->reason :
1197                                   "Server closed connection: "
1198                                   "Connection refused");
1199     server->stat.conn_failures++;
1200     return;
1201   }
1202
1203   /* Check whether we have configured this sort of connection at all. We
1204      have to check all configurations since we don't know what type of
1205      connection this is. */
1206   if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1207     cconfig = silc_server_config_find_client(server, sock->hostname);
1208   if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1209     sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1210   if (server->server_type == SILC_ROUTER) {
1211     if (!(rconfig = silc_server_config_find_router_conn(server,
1212                                                         sock->ip, port)))
1213       rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1214                                                     sock->port);
1215   }
1216   if (!cconfig && !sconfig && !rconfig) {
1217     SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1218                    sock->ip));
1219     silc_server_disconnect_remote(server, sock,
1220                                   "Server closed connection: "
1221                                   "Connection refused");
1222     server->stat.conn_failures++;
1223     return;
1224   }
1225
1226   /* The connection is allowed */
1227
1228   /* Allocate internal context for key exchange protocol. This is
1229      sent as context for the protocol. */
1230   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1231   proto_ctx->server = context;
1232   proto_ctx->sock = sock;
1233   proto_ctx->rng = server->rng;
1234   proto_ctx->responder = TRUE;
1235   silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1236   silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1237   silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1238
1239   /* Take flags for key exchange. Since we do not know what type of connection
1240      this is, we go through all found configurations and use the global ones
1241      as well. This will result always into strictest key exchange flags. */
1242   SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1243   SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1244   SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1245   if (server->config->param.key_exchange_pfs)
1246     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1247
1248   /* Prepare the connection for key exchange protocol. We allocate the
1249      protocol but will not start it yet. The connector will be the
1250      initiator of the protocol thus we will wait for initiation from
1251      there before we start the protocol. */
1252   server->stat.auth_attempts++;
1253   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1254                       &sock->protocol, proto_ctx,
1255                       silc_server_accept_new_connection_second);
1256
1257   /* Register a timeout task that will be executed if the connector
1258      will not start the key exchange protocol within specified timeout
1259      and the connection will be closed. */
1260   proto_ctx->timeout_task =
1261     silc_schedule_task_add(server->schedule, sock->sock,
1262                            silc_server_timeout_remote,
1263                            context, server->config->key_exchange_timeout, 0,
1264                            SILC_TASK_TIMEOUT,
1265                            SILC_TASK_PRI_LOW);
1266 }
1267
1268 /* Accepts new connections to the server. Accepting new connections are
1269    done in three parts to make it async. */
1270
1271 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1272 {
1273   SilcServer server = (SilcServer)context;
1274   SilcSocketConnection newsocket;
1275   int sock;
1276
1277   SILC_LOG_DEBUG(("Accepting new connection"));
1278
1279   server->stat.conn_attempts++;
1280
1281   sock = silc_net_accept_connection(server->sock);
1282   if (sock < 0) {
1283     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1284     server->stat.conn_failures++;
1285     return;
1286   }
1287
1288   /* Check for maximum allowed connections */
1289   if (sock > server->config->param.connections_max) {
1290     SILC_LOG_ERROR(("Refusing connection, server is full"));
1291     server->stat.conn_failures++;
1292     silc_net_close_connection(sock);
1293     return;
1294   }
1295
1296   /* Set socket options */
1297   silc_net_set_socket_nonblock(sock);
1298   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1299
1300   /* We don't create a ID yet, since we don't know what type of connection
1301      this is yet. But, we do add the connection to the socket table. */
1302   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1303   server->sockets[sock] = newsocket;
1304
1305   /* Perform asynchronous host lookup. This will lookup the IP and the
1306      FQDN of the remote connection. After the lookup is done the connection
1307      is accepted further. */
1308   silc_socket_host_lookup(newsocket, TRUE,
1309                           silc_server_accept_new_connection_lookup, context,
1310                           server->schedule);
1311 }
1312
1313 /* Second part of accepting new connection. Key exchange protocol has been
1314    performed and now it is time to do little connection authentication
1315    protocol to figure out whether this connection is client or server
1316    and whether it has right to access this server (especially server
1317    connections needs to be authenticated). */
1318
1319 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1320 {
1321   SilcProtocol protocol = (SilcProtocol)context;
1322   SilcServerKEInternalContext *ctx =
1323     (SilcServerKEInternalContext *)protocol->context;
1324   SilcServer server = (SilcServer)ctx->server;
1325   SilcSocketConnection sock = ctx->sock;
1326   SilcServerConnAuthInternalContext *proto_ctx;
1327
1328   SILC_LOG_DEBUG(("Start"));
1329
1330   if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1331       (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1332     /* Error occured during protocol */
1333     silc_protocol_free(protocol);
1334     sock->protocol = NULL;
1335     silc_ske_free_key_material(ctx->keymat);
1336     if (ctx->packet)
1337       silc_packet_context_free(ctx->packet);
1338     if (ctx->ske)
1339       silc_ske_free(ctx->ske);
1340     silc_free(ctx->dest_id);
1341     silc_server_config_unref(&ctx->cconfig);
1342     silc_server_config_unref(&ctx->sconfig);
1343     silc_server_config_unref(&ctx->rconfig);
1344     silc_free(ctx);
1345     silc_schedule_task_del_by_callback(server->schedule,
1346                                        silc_server_failure_callback);
1347     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1348                                   "Key exchange failed");
1349     server->stat.auth_failures++;
1350     return;
1351   }
1352
1353   /* We now have the key material as the result of the key exchange
1354      protocol. Take the key material into use. Free the raw key material
1355      as soon as we've set them into use. */
1356   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1357                                         ctx->sock, ctx->keymat,
1358                                         ctx->ske->prop->cipher,
1359                                         ctx->ske->prop->pkcs,
1360                                         ctx->ske->prop->hash,
1361                                         ctx->ske->prop->hmac,
1362                                         ctx->ske->prop->group,
1363                                         ctx->responder)) {
1364     silc_protocol_free(protocol);
1365     sock->protocol = NULL;
1366     silc_ske_free_key_material(ctx->keymat);
1367     if (ctx->packet)
1368       silc_packet_context_free(ctx->packet);
1369     if (ctx->ske)
1370       silc_ske_free(ctx->ske);
1371     silc_free(ctx->dest_id);
1372     silc_server_config_unref(&ctx->cconfig);
1373     silc_server_config_unref(&ctx->sconfig);
1374     silc_server_config_unref(&ctx->rconfig);
1375     silc_free(ctx);
1376     silc_schedule_task_del_by_callback(server->schedule,
1377                                        silc_server_failure_callback);
1378     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1379                                   "Key exchange failed");
1380     server->stat.auth_failures++;
1381     return;
1382   }
1383   silc_ske_free_key_material(ctx->keymat);
1384
1385   /* Allocate internal context for the authentication protocol. This
1386      is sent as context for the protocol. */
1387   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1388   proto_ctx->server = (void *)server;
1389   proto_ctx->sock = sock;
1390   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1391   proto_ctx->responder = TRUE;
1392   proto_ctx->dest_id_type = ctx->dest_id_type;
1393   proto_ctx->dest_id = ctx->dest_id;
1394   proto_ctx->cconfig = ctx->cconfig;
1395   proto_ctx->sconfig = ctx->sconfig;
1396   proto_ctx->rconfig = ctx->rconfig;
1397
1398   /* Free old protocol as it is finished now */
1399   silc_protocol_free(protocol);
1400   if (ctx->packet)
1401     silc_packet_context_free(ctx->packet);
1402   silc_free(ctx);
1403   sock->protocol = NULL;
1404
1405   /* Allocate the authentication protocol. This is allocated here
1406      but we won't start it yet. We will be receiving party of this
1407      protocol thus we will wait that connecting party will make
1408      their first move. */
1409   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1410                       &sock->protocol, proto_ctx,
1411                       silc_server_accept_new_connection_final);
1412
1413   /* Register timeout task. If the protocol is not executed inside
1414      this timelimit the connection will be terminated. */
1415   proto_ctx->timeout_task =
1416     silc_schedule_task_add(server->schedule, sock->sock,
1417                            silc_server_timeout_remote,
1418                            (void *)server,
1419                            server->config->conn_auth_timeout, 0,
1420                            SILC_TASK_TIMEOUT,
1421                            SILC_TASK_PRI_LOW);
1422 }
1423
1424 /* Final part of accepting new connection. The connection has now
1425    been authenticated and keys has been exchanged. We also know whether
1426    this is client or server connection. */
1427
1428 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1429 {
1430   SilcProtocol protocol = (SilcProtocol)context;
1431   SilcServerConnAuthInternalContext *ctx =
1432     (SilcServerConnAuthInternalContext *)protocol->context;
1433   SilcServer server = (SilcServer)ctx->server;
1434   SilcSocketConnection sock = ctx->sock;
1435   SilcServerHBContext hb_context;
1436   SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1437   void *id_entry;
1438   SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1439
1440   SILC_LOG_DEBUG(("Start"));
1441
1442   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1443       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1444     /* Error occured during protocol */
1445     silc_protocol_free(protocol);
1446     sock->protocol = NULL;
1447     if (ctx->packet)
1448       silc_packet_context_free(ctx->packet);
1449     if (ctx->ske)
1450       silc_ske_free(ctx->ske);
1451     silc_free(ctx->dest_id);
1452     silc_server_config_unref(&ctx->cconfig);
1453     silc_server_config_unref(&ctx->sconfig);
1454     silc_server_config_unref(&ctx->rconfig);
1455     silc_free(ctx);
1456     silc_schedule_task_del_by_callback(server->schedule,
1457                                        silc_server_failure_callback);
1458     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1459                                   "Authentication failed");
1460     server->stat.auth_failures++;
1461     return;
1462   }
1463
1464   entry->data.last_receive = time(NULL);
1465
1466   switch (ctx->conn_type) {
1467   case SILC_SOCKET_TYPE_CLIENT:
1468     {
1469       SilcClientEntry client;
1470       SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1471
1472       /* Verify whether this connection is after all allowed to connect */
1473       if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1474                                           &server->config->param,
1475                                           conn->param, ctx->ske)) {
1476         server->stat.auth_failures++;
1477         goto out;
1478       }
1479
1480       SILC_LOG_DEBUG(("Remote host is client"));
1481       SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1482                      sock->ip));
1483
1484       /* Add the client to the client ID cache. The nickname and Client ID
1485          and other information is created after we have received NEW_CLIENT
1486          packet from client. */
1487       client = silc_idlist_add_client(server->local_list,
1488                                       NULL, NULL, NULL, NULL, NULL, sock, 0);
1489       if (!client) {
1490         SILC_LOG_ERROR(("Could not add new client to cache"));
1491         silc_free(sock->user_data);
1492         silc_server_disconnect_remote(server, sock,
1493                                       "Server closed connection: "
1494                                       "Authentication failed");
1495         server->stat.auth_failures++;
1496         goto out;
1497       }
1498
1499       /* Statistics */
1500       server->stat.my_clients++;
1501       server->stat.clients++;
1502       if (server->server_type == SILC_ROUTER)
1503         server->stat.cell_clients++;
1504
1505       /* Get connection parameters */
1506       if (conn->param) {
1507         if (conn->param->keepalive_secs)
1508           hearbeat_timeout = conn->param->keepalive_secs;
1509       }
1510
1511       id_entry = (void *)client;
1512       break;
1513     }
1514   case SILC_SOCKET_TYPE_SERVER:
1515   case SILC_SOCKET_TYPE_ROUTER:
1516     {
1517       SilcServerEntry new_server;
1518       bool initiator = FALSE;
1519       bool backup_local = FALSE;
1520       bool backup_router = FALSE;
1521       char *backup_replace_ip = NULL;
1522       SilcUInt16 backup_replace_port = 0;
1523       SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1524       SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1525
1526       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1527         /* Verify whether this connection is after all allowed to connect */
1528         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1529                                             &server->config->param,
1530                                             rconn ? rconn->param : NULL,
1531                                             ctx->ske)) {
1532           server->stat.auth_failures++;
1533           goto out;
1534         }
1535
1536         if (rconn) {
1537           if (rconn->param) {
1538             if (rconn->param->keepalive_secs)
1539               hearbeat_timeout = rconn->param->keepalive_secs;
1540           }
1541
1542           initiator = rconn->initiator;
1543           backup_local = rconn->backup_local;
1544           backup_router = rconn->backup_router;
1545           backup_replace_ip = rconn->backup_replace_ip;
1546           backup_replace_port = rconn->backup_replace_port;
1547         }
1548       }
1549
1550       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1551         /* Verify whether this connection is after all allowed to connect */
1552         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1553                                             &server->config->param,
1554                                             sconn ? sconn->param : NULL,
1555                                             ctx->ske)) {
1556           server->stat.auth_failures++;
1557           goto out;
1558         }
1559         if (sconn) {
1560           if (sconn->param) {
1561             if (sconn->param->keepalive_secs)
1562               hearbeat_timeout = sconn->param->keepalive_secs;
1563           }
1564
1565           backup_router = sconn->backup_router;
1566         }
1567       }
1568
1569       SILC_LOG_DEBUG(("Remote host is %s",
1570                       ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1571                       "server" : (backup_router ?
1572                                   "backup router" : "router")));
1573       SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1574                      sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1575                      "server" : (backup_router ?
1576                                  "backup router" : "router")));
1577
1578       /* Add the server into server cache. The server name and Server ID
1579          is updated after we have received NEW_SERVER packet from the
1580          server. We mark ourselves as router for this server if we really
1581          are router. */
1582       new_server =
1583         silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1584                                 server->local_list : (backup_router ?
1585                                                       server->local_list :
1586                                                       server->global_list)),
1587                                NULL,
1588                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1589                                 SILC_SERVER : SILC_ROUTER),
1590                                NULL,
1591                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1592                                 server->id_entry : (backup_router ?
1593                                                     server->id_entry : NULL)),
1594                                sock);
1595       if (!new_server) {
1596         SILC_LOG_ERROR(("Could not add new server to cache"));
1597         silc_free(sock->user_data);
1598         silc_server_disconnect_remote(server, sock,
1599                                       "Server closed connection: "
1600                                       "Authentication failed");
1601         server->stat.auth_failures++;
1602         goto out;
1603       }
1604
1605       /* Statistics */
1606       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1607         server->stat.my_servers++;
1608       else
1609         server->stat.my_routers++;
1610       server->stat.servers++;
1611
1612       id_entry = (void *)new_server;
1613
1614       /* If the incoming connection is router and marked as backup router
1615          then add it to be one of our backups */
1616       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1617         silc_server_backup_add(server, new_server, backup_replace_ip,
1618                                backup_replace_port, backup_local);
1619
1620         /* Change it back to SERVER type since that's what it really is. */
1621         if (backup_local)
1622           ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1623
1624         new_server->server_type = SILC_BACKUP_ROUTER;
1625       }
1626
1627       /* Check whether this connection is to be our primary router connection
1628          if we do not already have the primary route. */
1629       if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1630         if (silc_server_config_is_primary_route(server) && !initiator)
1631           break;
1632
1633         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1634         server->standalone = FALSE;
1635         if (!server->id_entry->router) {
1636           server->id_entry->router = id_entry;
1637           server->router = id_entry;
1638         }
1639       }
1640
1641       break;
1642     }
1643   default:
1644     goto out;
1645     break;
1646   }
1647
1648   sock->type = ctx->conn_type;
1649
1650   /* Add the common data structure to the ID entry. */
1651   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1652
1653   /* Add to sockets internal pointer for fast referencing */
1654   silc_free(sock->user_data);
1655   sock->user_data = id_entry;
1656
1657   /* Connection has been fully established now. Everything is ok. */
1658   SILC_LOG_DEBUG(("New connection authenticated"));
1659
1660   /* Perform keepalive. The `hb_context' will be freed automatically
1661      when finally calling the silc_socket_free function. */
1662   hb_context = silc_calloc(1, sizeof(*hb_context));
1663   hb_context->server = server;
1664   silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1665                             silc_server_perform_heartbeat,
1666                             server->schedule);
1667
1668  out:
1669   silc_schedule_task_del_by_callback(server->schedule,
1670                                      silc_server_failure_callback);
1671   silc_protocol_free(protocol);
1672   if (ctx->packet)
1673     silc_packet_context_free(ctx->packet);
1674   if (ctx->ske)
1675     silc_ske_free(ctx->ske);
1676   silc_free(ctx->dest_id);
1677   silc_server_config_unref(&ctx->cconfig);
1678   silc_server_config_unref(&ctx->sconfig);
1679   silc_server_config_unref(&ctx->rconfig);
1680   silc_free(ctx);
1681   sock->protocol = NULL;
1682 }
1683
1684 /* This function is used to read packets from network and send packets to
1685    network. This is usually a generic task. */
1686
1687 SILC_TASK_CALLBACK(silc_server_packet_process)
1688 {
1689   SilcServer server = (SilcServer)context;
1690   SilcSocketConnection sock = server->sockets[fd];
1691   SilcIDListData idata;
1692   SilcCipher cipher = NULL;
1693   SilcHmac hmac = NULL;
1694   SilcUInt32 sequence = 0;
1695   int ret;
1696
1697   if (!sock)
1698     return;
1699
1700   SILC_LOG_DEBUG(("Processing packet"));
1701
1702   /* Packet sending */
1703
1704   if (type == SILC_TASK_WRITE) {
1705     /* Do not send data to disconnected connection */
1706     if (SILC_IS_DISCONNECTED(sock))
1707       return;
1708
1709     server->stat.packets_sent++;
1710
1711     /* Send the packet */
1712     ret = silc_packet_send(sock, TRUE);
1713
1714     /* If returned -2 could not write to connection now, will do
1715        it later. */
1716     if (ret == -2)
1717       return;
1718
1719     if (ret == -1) {
1720       SILC_LOG_ERROR(("Error sending packet to connection "
1721                       "%s:%d [%s]", sock->hostname, sock->port,
1722                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1723                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1724                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1725                        "Router")));
1726       return;
1727     }
1728
1729     /* The packet has been sent and now it is time to set the connection
1730        back to only for input. When there is again some outgoing data
1731        available for this connection it will be set for output as well.
1732        This call clears the output setting and sets it only for input. */
1733     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1734     SILC_UNSET_OUTBUF_PENDING(sock);
1735
1736     silc_buffer_clear(sock->outbuf);
1737     return;
1738   }
1739
1740   /* Packet receiving */
1741
1742   /* Read some data from connection */
1743   ret = silc_packet_receive(sock);
1744   if (ret < 0) {
1745
1746     if (ret == -1)
1747       SILC_LOG_ERROR(("Error receiving packet from connection "
1748                       "%s:%d [%s] %s", sock->hostname, sock->port,
1749                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1750                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1751                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1752                        "Router"), strerror(errno)));
1753     return;
1754   }
1755
1756   /* EOF */
1757   if (ret == 0) {
1758     SILC_LOG_DEBUG(("Read EOF"));
1759
1760     /* If connection is disconnecting already we will finally
1761        close the connection */
1762     if (SILC_IS_DISCONNECTING(sock)) {
1763       if (sock->user_data)
1764         silc_server_free_sock_user_data(server, sock, NULL);
1765       silc_server_close_connection(server, sock);
1766       return;
1767     }
1768
1769     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1770     SILC_SET_DISCONNECTING(sock);
1771
1772     if (sock->user_data) {
1773       char tmp[128];
1774       if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1775         silc_server_free_sock_user_data(server, sock, tmp);
1776       else
1777         silc_server_free_sock_user_data(server, sock, NULL);
1778     } else if (server->router_conn && server->router_conn->sock == sock &&
1779              !server->router && server->standalone)
1780       silc_schedule_task_add(server->schedule, 0,
1781                              silc_server_connect_to_router,
1782                              server, 1, 0,
1783                              SILC_TASK_TIMEOUT,
1784                              SILC_TASK_PRI_NORMAL);
1785
1786     silc_server_close_connection(server, sock);
1787     return;
1788   }
1789
1790   /* If connection is disconnecting or disconnected we will ignore
1791      what we read. */
1792   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1793     SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1794     return;
1795   }
1796
1797   server->stat.packets_received++;
1798
1799   /* Get keys and stuff from ID entry */
1800   idata = (SilcIDListData)sock->user_data;
1801   if (idata) {
1802     cipher = idata->receive_key;
1803     hmac = idata->hmac_receive;
1804     sequence = idata->psn_receive;
1805   }
1806
1807   /* Process the packet. This will call the parser that will then
1808      decrypt and parse the packet. */
1809   ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1810                                     TRUE : FALSE, cipher, hmac, sequence,
1811                                     silc_server_packet_parse, server);
1812
1813   /* If this socket connection is not authenticated yet and the packet
1814      processing failed we will drop the connection since it can be
1815      a malicious flooder. */
1816   if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1817       (!sock->protocol || sock->protocol->protocol->type ==
1818        SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1819     SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1820     SILC_SET_DISCONNECTING(sock);
1821
1822     if (sock->user_data)
1823       silc_server_free_sock_user_data(server, sock, NULL);
1824     silc_server_close_connection(server, sock);
1825   }
1826 }
1827
1828 /* Parses whole packet, received earlier. */
1829
1830 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1831 {
1832   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1833   SilcServer server = (SilcServer)parse_ctx->context;
1834   SilcSocketConnection sock = parse_ctx->sock;
1835   SilcPacketContext *packet = parse_ctx->packet;
1836   SilcIDListData idata = (SilcIDListData)sock->user_data;
1837   int ret;
1838
1839   SILC_LOG_DEBUG(("Start"));
1840
1841   /* Parse the packet */
1842   if (parse_ctx->normal)
1843     ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1844   else
1845     ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1846
1847   /* If entry is disabled ignore what we got. */
1848   if (ret != SILC_PACKET_RESUME_ROUTER &&
1849       idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1850     SILC_LOG_DEBUG(("Connection is disabled"));
1851     goto out;
1852   }
1853
1854   if (ret == SILC_PACKET_NONE)
1855     goto out;
1856
1857   /* Check that the the current client ID is same as in the client's packet. */
1858   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1859     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1860     if (client && client->id) {
1861       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1862                                 packet->src_id_type);
1863       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1864         silc_free(id);
1865         goto out;
1866       }
1867       silc_free(id);
1868     }
1869   }
1870
1871   if (server->server_type == SILC_ROUTER) {
1872     /* Route the packet if it is not destined to us. Other ID types but
1873        server are handled separately after processing them. */
1874     if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1875         packet->dst_id_type == SILC_ID_SERVER &&
1876         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1877         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1878
1879       /* Route the packet to fastest route for the destination ID */
1880       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1881                                 packet->dst_id_type);
1882       if (!id)
1883         goto out;
1884       silc_server_packet_route(server,
1885                                silc_server_route_get(server, id,
1886                                                      packet->dst_id_type),
1887                                packet);
1888       silc_free(id);
1889       goto out;
1890     }
1891   }
1892
1893   /* Parse the incoming packet type */
1894   silc_server_packet_parse_type(server, sock, packet);
1895
1896   if (server->server_type == SILC_ROUTER) {
1897     /* Broadcast packet if it is marked as broadcast packet and it is
1898        originated from router and we are router. */
1899     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1900         packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1901         !server->standalone) {
1902       /* Broadcast to our primary route */
1903       silc_server_packet_broadcast(server, server->router->connection, packet);
1904
1905       /* If we have backup routers then we need to feed all broadcast
1906          data to those servers. */
1907       silc_server_backup_broadcast(server, sock, packet);
1908     }
1909   }
1910
1911  out:
1912   silc_packet_context_free(packet);
1913   silc_free(parse_ctx);
1914 }
1915
1916 /* Parser callback called by silc_packet_receive_process. This merely
1917    registers timeout that will handle the actual parsing when appropriate. */
1918
1919 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1920                               void *context)
1921 {
1922   SilcServer server = (SilcServer)context;
1923   SilcSocketConnection sock = parser_context->sock;
1924   SilcIDListData idata = (SilcIDListData)sock->user_data;
1925
1926   if (idata)
1927     idata->psn_receive = parser_context->packet->sequence + 1;
1928
1929   /* If protocol for this connection is key exchange or rekey then we'll
1930      process all packets synchronously, since there might be packets in
1931      queue that we are not able to decrypt without first processing the
1932      packets before them. */
1933   if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1934        parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1935       (sock->protocol && sock->protocol->protocol &&
1936        (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1937         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1938     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1939                                   parser_context);
1940
1941     /* Reprocess data since we'll return FALSE here.  This is because
1942        the idata->receive_key might have become valid in the last packet
1943        and we want to call this processor with valid cipher. */
1944     if (idata)
1945       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1946                                   TRUE : FALSE, idata->receive_key,
1947                                   idata->hmac_receive, idata->psn_receive,
1948                                   silc_server_packet_parse, server);
1949     else
1950       silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1951                                   TRUE : FALSE, NULL, NULL, 0,
1952                                   silc_server_packet_parse, server);
1953     return FALSE;
1954   }
1955
1956   switch (sock->type) {
1957   case SILC_SOCKET_TYPE_UNKNOWN:
1958   case SILC_SOCKET_TYPE_CLIENT:
1959     /* Parse the packet with timeout */
1960     silc_schedule_task_add(server->schedule, sock->sock,
1961                            silc_server_packet_parse_real,
1962                            (void *)parser_context, 0, 100000,
1963                            SILC_TASK_TIMEOUT,
1964                            SILC_TASK_PRI_NORMAL);
1965     break;
1966   case SILC_SOCKET_TYPE_SERVER:
1967   case SILC_SOCKET_TYPE_ROUTER:
1968     /* Packets from servers are parsed immediately */
1969     silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1970                                   parser_context);
1971     break;
1972   default:
1973     return TRUE;
1974   }
1975
1976   return TRUE;
1977 }
1978
1979 /* Parses the packet type and calls what ever routines the packet type
1980    requires. This is done for all incoming packets. */
1981
1982 void silc_server_packet_parse_type(SilcServer server,
1983                                    SilcSocketConnection sock,
1984                                    SilcPacketContext *packet)
1985 {
1986   SilcPacketType type = packet->type;
1987   SilcIDListData idata = (SilcIDListData)sock->user_data;
1988
1989   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1990
1991   /* Parse the packet type */
1992   switch (type) {
1993   case SILC_PACKET_DISCONNECT:
1994     SILC_LOG_DEBUG(("Disconnect packet"));
1995     if (packet->flags & SILC_PACKET_FLAG_LIST)
1996       break;
1997     if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1998       /* Duplicate to null terminate the string. */
1999       char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
2000       SILC_LOG_ERROR(("%s", message));
2001       silc_free(message);
2002     }
2003     break;
2004
2005   case SILC_PACKET_SUCCESS:
2006     /*
2007      * Success received for something. For now we can have only
2008      * one protocol for connection executing at once hence this
2009      * success message is for whatever protocol is executing currently.
2010      */
2011     SILC_LOG_DEBUG(("Success packet"));
2012     if (packet->flags & SILC_PACKET_FLAG_LIST)
2013       break;
2014     if (sock->protocol)
2015       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2016     break;
2017
2018   case SILC_PACKET_FAILURE:
2019     /*
2020      * Failure received for something. For now we can have only
2021      * one protocol for connection executing at once hence this
2022      * failure message is for whatever protocol is executing currently.
2023      */
2024     SILC_LOG_DEBUG(("Failure packet"));
2025     if (packet->flags & SILC_PACKET_FLAG_LIST)
2026       break;
2027     if (sock->protocol) {
2028       SilcServerFailureContext f;
2029       f = silc_calloc(1, sizeof(*f));
2030       f->server = server;
2031       f->sock = sock;
2032
2033       /* We will wait 5 seconds to process this failure packet */
2034       silc_schedule_task_add(server->schedule, sock->sock,
2035                          silc_server_failure_callback, (void *)f, 5, 0,
2036                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2037     }
2038     break;
2039
2040   case SILC_PACKET_REJECT:
2041     SILC_LOG_DEBUG(("Reject packet"));
2042     if (packet->flags & SILC_PACKET_FLAG_LIST)
2043       break;
2044     return;
2045     break;
2046
2047   case SILC_PACKET_NOTIFY:
2048     /*
2049      * Received notify packet. Server can receive notify packets from
2050      * router. Server then relays the notify messages to clients if needed.
2051      */
2052     SILC_LOG_DEBUG(("Notify packet"));
2053     if (packet->flags & SILC_PACKET_FLAG_LIST)
2054       silc_server_notify_list(server, sock, packet);
2055     else
2056       silc_server_notify(server, sock, packet);
2057     break;
2058
2059     /*
2060      * Channel packets
2061      */
2062   case SILC_PACKET_CHANNEL_MESSAGE:
2063     /*
2064      * Received channel message. Channel messages are special packets
2065      * (although probably most common ones) thus they are handled
2066      * specially.
2067      */
2068     SILC_LOG_DEBUG(("Channel Message packet"));
2069     if (packet->flags & SILC_PACKET_FLAG_LIST)
2070       break;
2071     idata->last_receive = time(NULL);
2072     silc_server_channel_message(server, sock, packet);
2073     break;
2074
2075   case SILC_PACKET_CHANNEL_KEY:
2076     /*
2077      * Received key for channel. As channels are created by the router
2078      * the keys are as well. We will distribute the key to all of our
2079      * locally connected clients on the particular channel. Router
2080      * never receives this channel and thus is ignored.
2081      */
2082     SILC_LOG_DEBUG(("Channel Key packet"));
2083     if (packet->flags & SILC_PACKET_FLAG_LIST)
2084       break;
2085     silc_server_channel_key(server, sock, packet);
2086     break;
2087
2088     /*
2089      * Command packets
2090      */
2091   case SILC_PACKET_COMMAND:
2092     /*
2093      * Recived command. Processes the command request and allocates the
2094      * command context and calls the command.
2095      */
2096     SILC_LOG_DEBUG(("Command packet"));
2097     if (packet->flags & SILC_PACKET_FLAG_LIST)
2098       break;
2099     silc_server_command_process(server, sock, packet);
2100     break;
2101
2102   case SILC_PACKET_COMMAND_REPLY:
2103     /*
2104      * Received command reply packet. Received command reply to command. It
2105      * may be reply to command sent by us or reply to command sent by client
2106      * that we've routed further.
2107      */
2108     SILC_LOG_DEBUG(("Command Reply packet"));
2109     if (packet->flags & SILC_PACKET_FLAG_LIST)
2110       break;
2111     silc_server_command_reply(server, sock, packet);
2112     break;
2113
2114     /*
2115      * Private Message packets
2116      */
2117   case SILC_PACKET_PRIVATE_MESSAGE:
2118     /*
2119      * Received private message packet. The packet is coming from either
2120      * client or server.
2121      */
2122     SILC_LOG_DEBUG(("Private Message packet"));
2123     if (packet->flags & SILC_PACKET_FLAG_LIST)
2124       break;
2125     idata->last_receive = time(NULL);
2126     silc_server_private_message(server, sock, packet);
2127     break;
2128
2129   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2130     /*
2131      * Private message key packet.
2132      */
2133     if (packet->flags & SILC_PACKET_FLAG_LIST)
2134       break;
2135     silc_server_private_message_key(server, sock, packet);
2136     break;
2137
2138     /*
2139      * Key Exchange protocol packets
2140      */
2141   case SILC_PACKET_KEY_EXCHANGE:
2142     SILC_LOG_DEBUG(("KE packet"));
2143     if (packet->flags & SILC_PACKET_FLAG_LIST)
2144       break;
2145
2146     if (sock->protocol && sock->protocol->protocol &&
2147         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2148       SilcServerKEInternalContext *proto_ctx =
2149         (SilcServerKEInternalContext *)sock->protocol->context;
2150
2151       proto_ctx->packet = silc_packet_context_dup(packet);
2152
2153       /* Let the protocol handle the packet */
2154       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2155     } else {
2156       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2157                       "protocol active, packet dropped."));
2158     }
2159     break;
2160
2161   case SILC_PACKET_KEY_EXCHANGE_1:
2162     SILC_LOG_DEBUG(("KE 1 packet"));
2163     if (packet->flags & SILC_PACKET_FLAG_LIST)
2164       break;
2165
2166     if (sock->protocol && sock->protocol->protocol &&
2167         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2168          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2169
2170       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2171         SilcServerRekeyInternalContext *proto_ctx =
2172           (SilcServerRekeyInternalContext *)sock->protocol->context;
2173
2174         if (proto_ctx->packet)
2175           silc_packet_context_free(proto_ctx->packet);
2176
2177         proto_ctx->packet = silc_packet_context_dup(packet);
2178
2179         /* Let the protocol handle the packet */
2180         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2181       } else {
2182         SilcServerKEInternalContext *proto_ctx =
2183           (SilcServerKEInternalContext *)sock->protocol->context;
2184
2185         if (proto_ctx->packet)
2186           silc_packet_context_free(proto_ctx->packet);
2187
2188         proto_ctx->packet = silc_packet_context_dup(packet);
2189         proto_ctx->dest_id_type = packet->src_id_type;
2190         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2191                                             packet->src_id_type);
2192         if (!proto_ctx->dest_id)
2193           break;
2194
2195         /* Let the protocol handle the packet */
2196         silc_protocol_execute(sock->protocol, server->schedule,
2197                               0, 100000);
2198       }
2199     } else {
2200       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2201                       "protocol active, packet dropped."));
2202     }
2203     break;
2204
2205   case SILC_PACKET_KEY_EXCHANGE_2:
2206     SILC_LOG_DEBUG(("KE 2 packet"));
2207     if (packet->flags & SILC_PACKET_FLAG_LIST)
2208       break;
2209
2210     if (sock->protocol && sock->protocol->protocol &&
2211         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2212          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2213
2214       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2215         SilcServerRekeyInternalContext *proto_ctx =
2216           (SilcServerRekeyInternalContext *)sock->protocol->context;
2217
2218         if (proto_ctx->packet)
2219           silc_packet_context_free(proto_ctx->packet);
2220
2221         proto_ctx->packet = silc_packet_context_dup(packet);
2222
2223         /* Let the protocol handle the packet */
2224         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2225       } else {
2226         SilcServerKEInternalContext *proto_ctx =
2227           (SilcServerKEInternalContext *)sock->protocol->context;
2228
2229         if (proto_ctx->packet)
2230           silc_packet_context_free(proto_ctx->packet);
2231
2232         proto_ctx->packet = silc_packet_context_dup(packet);
2233         proto_ctx->dest_id_type = packet->src_id_type;
2234         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2235                                             packet->src_id_type);
2236         if (!proto_ctx->dest_id)
2237           break;
2238
2239         /* Let the protocol handle the packet */
2240         silc_protocol_execute(sock->protocol, server->schedule,
2241                               0, 100000);
2242       }
2243     } else {
2244       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2245                       "protocol active, packet dropped."));
2246     }
2247     break;
2248
2249   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2250     /*
2251      * Connection authentication request packet. When we receive this packet
2252      * we will send to the other end information about our mandatory
2253      * authentication method for the connection. This packet maybe received
2254      * at any time.
2255      */
2256     SILC_LOG_DEBUG(("Connection authentication request packet"));
2257     if (packet->flags & SILC_PACKET_FLAG_LIST)
2258       break;
2259     silc_server_connection_auth_request(server, sock, packet);
2260     break;
2261
2262     /*
2263      * Connection Authentication protocol packets
2264      */
2265   case SILC_PACKET_CONNECTION_AUTH:
2266     /* Start of the authentication protocol. We receive here the
2267        authentication data and will verify it. */
2268     SILC_LOG_DEBUG(("Connection auth packet"));
2269     if (packet->flags & SILC_PACKET_FLAG_LIST)
2270       break;
2271
2272     if (sock->protocol && sock->protocol->protocol->type
2273         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2274
2275       SilcServerConnAuthInternalContext *proto_ctx =
2276         (SilcServerConnAuthInternalContext *)sock->protocol->context;
2277
2278       proto_ctx->packet = silc_packet_context_dup(packet);
2279
2280       /* Let the protocol handle the packet */
2281       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2282     } else {
2283       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2284                       "protocol active, packet dropped."));
2285     }
2286     break;
2287
2288   case SILC_PACKET_NEW_ID:
2289     /*
2290      * Received New ID packet. This includes some new ID that has been
2291      * created. It may be for client, server or channel. This is the way
2292      * to distribute information about new registered entities in the
2293      * SILC network.
2294      */
2295     SILC_LOG_DEBUG(("New ID packet"));
2296     if (packet->flags & SILC_PACKET_FLAG_LIST)
2297       silc_server_new_id_list(server, sock, packet);
2298     else
2299       silc_server_new_id(server, sock, packet);
2300     break;
2301
2302   case SILC_PACKET_NEW_CLIENT:
2303     /*
2304      * Received new client packet. This includes client information that
2305      * we will use to create initial client ID. After creating new
2306      * ID we will send it to the client.
2307      */
2308     SILC_LOG_DEBUG(("New Client packet"));
2309     if (packet->flags & SILC_PACKET_FLAG_LIST)
2310       break;
2311     silc_server_new_client(server, sock, packet);
2312     break;
2313
2314   case SILC_PACKET_NEW_SERVER:
2315     /*
2316      * Received new server packet. This includes Server ID and some other
2317      * information that we may save. This is received after server has
2318      * connected to us.
2319      */
2320     SILC_LOG_DEBUG(("New Server packet"));
2321     if (packet->flags & SILC_PACKET_FLAG_LIST)
2322       break;
2323     silc_server_new_server(server, sock, packet);
2324     break;
2325
2326   case SILC_PACKET_NEW_CHANNEL:
2327     /*
2328      * Received new channel packet. Information about new channel in the
2329      * network are distributed using this packet.
2330      */
2331     SILC_LOG_DEBUG(("New Channel packet"));
2332     if (packet->flags & SILC_PACKET_FLAG_LIST)
2333       silc_server_new_channel_list(server, sock, packet);
2334     else
2335       silc_server_new_channel(server, sock, packet);
2336     break;
2337
2338   case SILC_PACKET_HEARTBEAT:
2339     /*
2340      * Received heartbeat.
2341      */
2342     SILC_LOG_DEBUG(("Heartbeat packet"));
2343     if (packet->flags & SILC_PACKET_FLAG_LIST)
2344       break;
2345     break;
2346
2347   case SILC_PACKET_KEY_AGREEMENT:
2348     /*
2349      * Received heartbeat.
2350      */
2351     SILC_LOG_DEBUG(("Key agreement packet"));
2352     if (packet->flags & SILC_PACKET_FLAG_LIST)
2353       break;
2354     silc_server_key_agreement(server, sock, packet);
2355     break;
2356
2357   case SILC_PACKET_REKEY:
2358     /*
2359      * Received re-key packet. The sender wants to regenerate the session
2360      * keys.
2361      */
2362     SILC_LOG_DEBUG(("Re-key packet"));
2363     if (packet->flags & SILC_PACKET_FLAG_LIST)
2364       break;
2365     silc_server_rekey(server, sock, packet);
2366     break;
2367
2368   case SILC_PACKET_REKEY_DONE:
2369     /*
2370      * The re-key is done.
2371      */
2372     SILC_LOG_DEBUG(("Re-key done packet"));
2373     if (packet->flags & SILC_PACKET_FLAG_LIST)
2374       break;
2375
2376     if (sock->protocol && sock->protocol->protocol &&
2377         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2378
2379       SilcServerRekeyInternalContext *proto_ctx =
2380         (SilcServerRekeyInternalContext *)sock->protocol->context;
2381
2382       if (proto_ctx->packet)
2383         silc_packet_context_free(proto_ctx->packet);
2384
2385       proto_ctx->packet = silc_packet_context_dup(packet);
2386
2387       /* Let the protocol handle the packet */
2388       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2389     } else {
2390       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2391                       "protocol active, packet dropped."));
2392     }
2393     break;
2394
2395   case SILC_PACKET_FTP:
2396     /* FTP packet */
2397     SILC_LOG_DEBUG(("FTP packet"));
2398     if (packet->flags & SILC_PACKET_FLAG_LIST)
2399       break;
2400     silc_server_ftp(server, sock, packet);
2401     break;
2402
2403   case SILC_PACKET_RESUME_ROUTER:
2404     /* Resume router packet received. This packet is received for backup
2405        router resuming protocol. */
2406     SILC_LOG_DEBUG(("Resume router packet"));
2407     if (packet->flags & SILC_PACKET_FLAG_LIST)
2408       break;
2409     silc_server_backup_resume_router(server, sock, packet);
2410     break;
2411
2412   default:
2413     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2414     break;
2415   }
2416
2417 }
2418
2419 /* Creates connection to a remote router. */
2420
2421 void silc_server_create_connection(SilcServer server,
2422                                    const char *remote_host, SilcUInt32 port)
2423 {
2424   SilcServerConnection sconn;
2425
2426   /* Allocate connection object for hold connection specific stuff. */
2427   sconn = silc_calloc(1, sizeof(*sconn));
2428   sconn->server = server;
2429   sconn->remote_host = strdup(remote_host);
2430   sconn->remote_port = port;
2431   sconn->no_reconnect = TRUE;
2432
2433   silc_schedule_task_add(server->schedule, 0,
2434                          silc_server_connect_router,
2435                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2436                          SILC_TASK_PRI_NORMAL);
2437 }
2438
2439 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2440 {
2441   silc_socket_free((SilcSocketConnection)context);
2442 }
2443
2444 /* Closes connection to socket connection */
2445
2446 void silc_server_close_connection(SilcServer server,
2447                                   SilcSocketConnection sock)
2448 {
2449   if (!server->sockets[sock->sock])
2450     return;
2451
2452   SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2453                   sock->port,
2454                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2455                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2456                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2457                    "Router")));
2458
2459   /* We won't listen for this connection anymore */
2460   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2461
2462   /* Unregister all tasks */
2463   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2464
2465   /* Close the actual connection */
2466   silc_net_close_connection(sock->sock);
2467   server->sockets[sock->sock] = NULL;
2468
2469   /* If sock->user_data is NULL then we'll check for active protocols
2470      here since the silc_server_free_sock_user_data has not been called
2471      for this connection. */
2472   if (!sock->user_data) {
2473     /* If any protocol is active cancel its execution. It will call
2474        the final callback which will finalize the disconnection. */
2475     if (sock->protocol) {
2476       silc_protocol_cancel(sock->protocol, server->schedule);
2477       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2478       silc_protocol_execute_final(sock->protocol, server->schedule);
2479       sock->protocol = NULL;
2480       return;
2481     }
2482   }
2483
2484   silc_schedule_task_add(server->schedule, 0,
2485                          silc_server_close_connection_final,
2486                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2487                          SILC_TASK_PRI_NORMAL);
2488 }
2489
2490 /* Sends disconnect message to remote connection and disconnects the
2491    connection. */
2492
2493 void silc_server_disconnect_remote(SilcServer server,
2494                                    SilcSocketConnection sock,
2495                                    const char *fmt, ...)
2496 {
2497   va_list ap;
2498   unsigned char buf[4096];
2499
2500   if (!sock)
2501     return;
2502
2503   memset(buf, 0, sizeof(buf));
2504   va_start(ap, fmt);
2505   vsprintf(buf, fmt, ap);
2506   va_end(ap);
2507
2508   SILC_LOG_DEBUG(("Disconnecting remote host"));
2509
2510   /* Notify remote end that the conversation is over. The notify message
2511      is tried to be sent immediately. */
2512   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2513                           buf, strlen(buf), TRUE);
2514   silc_server_packet_queue_purge(server, sock);
2515
2516   /* Mark the connection to be disconnected */
2517   SILC_SET_DISCONNECTED(sock);
2518   silc_server_close_connection(server, sock);
2519 }
2520
2521 typedef struct {
2522   SilcServer server;
2523   SilcClientEntry client;
2524 } *FreeClientInternal;
2525
2526 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2527 {
2528   FreeClientInternal i = (FreeClientInternal)context;
2529
2530   silc_idlist_del_data(i->client);
2531   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2532   silc_free(i);
2533 }
2534
2535 /* Frees client data and notifies about client's signoff. */
2536
2537 void silc_server_free_client_data(SilcServer server,
2538                                   SilcSocketConnection sock,
2539                                   SilcClientEntry client,
2540                                   int notify,
2541                                   const char *signoff)
2542 {
2543   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2544
2545   /* If there is pending outgoing data for the client then purge it
2546      to the network before removing the client entry. */
2547   silc_server_packet_queue_purge(server, sock);
2548
2549   if (!client->id)
2550     return;
2551
2552   /* Send SIGNOFF notify to routers. */
2553   if (notify && !server->standalone && server->router)
2554     silc_server_send_notify_signoff(server, server->router->connection,
2555                                     server->server_type == SILC_SERVER ?
2556                                     FALSE : TRUE, client->id, signoff);
2557
2558   /* Remove client from all channels */
2559   if (notify)
2560     silc_server_remove_from_channels(server, NULL, client,
2561                                      TRUE, (char *)signoff, TRUE);
2562   else
2563     silc_server_remove_from_channels(server, NULL, client,
2564                                      FALSE, NULL, FALSE);
2565
2566   /* Update statistics */
2567   server->stat.my_clients--;
2568   server->stat.clients--;
2569   if (server->server_type == SILC_ROUTER)
2570     server->stat.cell_clients--;
2571   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2572   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2573
2574   /* We will not delete the client entry right away. We will take it
2575      into history (for WHOWAS command) for 5 minutes */
2576   i->server = server;
2577   i->client = client;
2578   silc_schedule_task_add(server->schedule, 0,
2579                          silc_server_free_client_data_timeout,
2580                          (void *)i, 300, 0,
2581                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2582   client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2583   client->router = NULL;
2584   client->connection = NULL;
2585   client->mode = 0;
2586 }
2587
2588 /* Frees user_data pointer from socket connection object. This also sends
2589    appropriate notify packets to the network to inform about leaving
2590    entities. */
2591
2592 void silc_server_free_sock_user_data(SilcServer server,
2593                                      SilcSocketConnection sock,
2594                                      const char *signoff_message)
2595 {
2596   SILC_LOG_DEBUG(("Start"));
2597
2598   switch (sock->type) {
2599   case SILC_SOCKET_TYPE_CLIENT:
2600     {
2601       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2602       silc_server_free_client_data(server, sock, user_data, TRUE,
2603                                    signoff_message);
2604       break;
2605     }
2606   case SILC_SOCKET_TYPE_SERVER:
2607   case SILC_SOCKET_TYPE_ROUTER:
2608     {
2609       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2610       SilcServerEntry backup_router = NULL;
2611
2612       if (user_data->id)
2613         backup_router = silc_server_backup_get(server, user_data->id);
2614
2615       /* If this was our primary router connection then we're lost to
2616          the outside world. */
2617       if (server->router == user_data) {
2618         /* Check whether we have a backup router connection */
2619         if (!backup_router || backup_router == user_data) {
2620           silc_schedule_task_add(server->schedule, 0,
2621                                  silc_server_connect_to_router,
2622                                  server, 1, 0,
2623                                  SILC_TASK_TIMEOUT,
2624                                  SILC_TASK_PRI_NORMAL);
2625
2626           server->id_entry->router = NULL;
2627           server->router = NULL;
2628           server->standalone = TRUE;
2629           backup_router = NULL;
2630         } else {
2631           SILC_LOG_INFO(("New primary router is backup router %s",
2632                          backup_router->server_name));
2633           SILC_LOG_DEBUG(("New primary router is backup router %s",
2634                           backup_router->server_name));
2635           server->id_entry->router = backup_router;
2636           server->router = backup_router;
2637           server->router_connect = time(0);
2638           server->backup_primary = TRUE;
2639           if (server->server_type == SILC_BACKUP_ROUTER) {
2640             server->server_type = SILC_ROUTER;
2641
2642             /* We'll need to constantly try to reconnect to the primary
2643                router so that we'll see when it comes back online. */
2644             silc_server_backup_reconnect(server, sock->ip, sock->port,
2645                                          silc_server_backup_connected,
2646                                          NULL);
2647           }
2648
2649           /* Mark this connection as replaced */
2650           silc_server_backup_replaced_add(server, user_data->id,
2651                                           backup_router);
2652         }
2653       } else if (backup_router) {
2654         SILC_LOG_INFO(("Enabling the use of backup router %s",
2655                        backup_router->server_name));
2656         SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2657                         backup_router->server_name));
2658
2659         /* Mark this connection as replaced */
2660         silc_server_backup_replaced_add(server, user_data->id,
2661                                         backup_router);
2662       }
2663
2664       if (!backup_router) {
2665         /* Free all client entries that this server owns as they will
2666            become invalid now as well. */
2667         if (user_data->id)
2668           silc_server_remove_clients_by_server(server, user_data, TRUE);
2669         if (server->server_type == SILC_SERVER)
2670           silc_server_remove_channels_by_server(server, user_data);
2671       } else {
2672         /* Update the client entries of this server to the new backup
2673            router. This also removes the clients that *really* was owned
2674            by the primary router and went down with the router.  */
2675         silc_server_update_clients_by_server(server, user_data, backup_router,
2676                                              TRUE, TRUE);
2677         silc_server_update_servers_by_server(server, user_data, backup_router);
2678         if (server->server_type == SILC_SERVER)
2679           silc_server_update_channels_by_server(server, user_data,
2680                                                 backup_router);
2681       }
2682
2683       /* Free the server entry */
2684       silc_server_backup_del(server, user_data);
2685       silc_server_backup_replaced_del(server, user_data);
2686       silc_idlist_del_data(user_data);
2687       if (!silc_idlist_del_server(server->local_list, user_data))
2688         silc_idlist_del_server(server->global_list, user_data);
2689       server->stat.my_servers--;
2690       server->stat.servers--;
2691       if (server->server_type == SILC_ROUTER)
2692         server->stat.cell_servers--;
2693
2694       if (backup_router) {
2695         /* Announce all of our stuff that was created about 5 minutes ago.
2696            The backup router knows all the other stuff already. */
2697         if (server->server_type == SILC_ROUTER)
2698           silc_server_announce_servers(server, FALSE, time(0) - 300,
2699                                        backup_router->connection);
2700
2701         /* Announce our clients and channels to the router */
2702         silc_server_announce_clients(server, time(0) - 300,
2703                                      backup_router->connection);
2704         silc_server_announce_channels(server, time(0) - 300,
2705                                       backup_router->connection);
2706       }
2707       break;
2708     }
2709   default:
2710     {
2711       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2712
2713       silc_idlist_del_data(user_data);
2714       silc_free(user_data);
2715       break;
2716     }
2717   }
2718
2719   /* If any protocol is active cancel its execution */
2720   if (sock->protocol) {
2721     silc_protocol_cancel(sock->protocol, server->schedule);
2722     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2723     silc_protocol_execute_final(sock->protocol, server->schedule);
2724     sock->protocol = NULL;
2725   }
2726
2727   sock->user_data = NULL;
2728 }
2729
2730 /* Removes client from all channels it has joined. This is used when client
2731    connection is disconnected. If the client on a channel is last, the
2732    channel is removed as well. This sends the SIGNOFF notify types. */
2733
2734 void silc_server_remove_from_channels(SilcServer server,
2735                                       SilcSocketConnection sock,
2736                                       SilcClientEntry client,
2737                                       int notify,
2738                                       char *signoff_message,
2739                                       int keygen)
2740 {
2741   SilcChannelEntry channel;
2742   SilcChannelClientEntry chl;
2743   SilcHashTableList htl;
2744   SilcBuffer clidp;
2745
2746   SILC_LOG_DEBUG(("Start"));
2747
2748   if (!client || !client->id)
2749     return;
2750
2751   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2752
2753   /* Remove the client from all channels. The client is removed from
2754      the channels' user list. */
2755   silc_hash_table_list(client->channels, &htl);
2756   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2757     channel = chl->channel;
2758
2759     /* Remove channel from client's channel list */
2760     silc_hash_table_del(client->channels, channel);
2761
2762     /* Remove channel if there is no users anymore */
2763     if (server->server_type == SILC_ROUTER &&
2764         silc_hash_table_count(channel->user_list) < 2) {
2765       if (channel->rekey)
2766         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2767       if (silc_idlist_del_channel(server->local_list, channel))
2768         server->stat.my_channels--;
2769       else
2770         silc_idlist_del_channel(server->global_list, channel);
2771       continue;
2772     }
2773
2774     /* Remove client from channel's client list */
2775     silc_hash_table_del(channel->user_list, chl->client);
2776     channel->user_count--;
2777
2778     /* If there is no global users on the channel anymore mark the channel
2779        as local channel. Do not check if the removed client is local client. */
2780     if (server->server_type != SILC_ROUTER && channel->global_users &&
2781         chl->client->router && !silc_server_channel_has_global(channel))
2782       channel->global_users = FALSE;
2783
2784     silc_free(chl);
2785     server->stat.my_chanclients--;
2786
2787     /* If there is not at least one local user on the channel then we don't
2788        need the channel entry anymore, we can remove it safely. */
2789     if (server->server_type != SILC_ROUTER &&
2790         !silc_server_channel_has_local(channel)) {
2791       /* Notify about leaving client if this channel has global users. */
2792       if (notify && channel->global_users)
2793         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2794                                            SILC_NOTIFY_TYPE_SIGNOFF,
2795                                            signoff_message ? 2 : 1,
2796                                            clidp->data, clidp->len,
2797                                            signoff_message, signoff_message ?
2798                                            strlen(signoff_message) : 0);
2799
2800       if (channel->rekey)
2801         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2802
2803       if (channel->founder_key) {
2804         /* The founder auth data exists, do not remove the channel entry */
2805         SilcChannelClientEntry chl2;
2806         SilcHashTableList htl2;
2807
2808         channel->disabled = TRUE;
2809
2810         silc_hash_table_list(channel->user_list, &htl2);
2811         while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2812           silc_hash_table_del(chl2->client->channels, channel);
2813           silc_hash_table_del(channel->user_list, chl2->client);
2814           channel->user_count--;
2815           silc_free(chl2);
2816         }
2817         silc_hash_table_list_reset(&htl2);
2818         continue;
2819       }
2820
2821       /* Remove the channel entry */
2822       if (silc_idlist_del_channel(server->local_list, channel))
2823         server->stat.my_channels--;
2824       else
2825         silc_idlist_del_channel(server->global_list, channel);
2826       continue;
2827     }
2828
2829     /* Send notify to channel about client leaving SILC and thus
2830        the entire channel. */
2831     if (notify)
2832       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2833                                          SILC_NOTIFY_TYPE_SIGNOFF,
2834                                          signoff_message ? 2 : 1,
2835                                          clidp->data, clidp->len,
2836                                          signoff_message, signoff_message ?
2837                                          strlen(signoff_message) : 0);
2838
2839     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2840       /* Re-generate channel key */
2841       if (!silc_server_create_channel_key(server, channel, 0))
2842         goto out;
2843
2844       /* Send the channel key to the channel. The key of course is not sent
2845          to the client who was removed from the channel. */
2846       silc_server_send_channel_key(server, client->connection, channel,
2847                                    server->server_type == SILC_ROUTER ?
2848                                    FALSE : !server->standalone);
2849     }
2850   }
2851
2852  out:
2853   silc_hash_table_list_reset(&htl);
2854   silc_buffer_free(clidp);
2855 }
2856
2857 /* Removes client from one channel. This is used for example when client
2858    calls LEAVE command to remove itself from the channel. Returns TRUE
2859    if channel still exists and FALSE if the channel is removed when
2860    last client leaves the channel. If `notify' is FALSE notify messages
2861    are not sent. */
2862
2863 int silc_server_remove_from_one_channel(SilcServer server,
2864                                         SilcSocketConnection sock,
2865                                         SilcChannelEntry channel,
2866                                         SilcClientEntry client,
2867                                         int notify)
2868 {
2869   SilcChannelClientEntry chl;
2870   SilcBuffer clidp;
2871
2872   SILC_LOG_DEBUG(("Start"));
2873
2874   /* Get the entry to the channel, if this client is not on the channel
2875      then return Ok. */
2876   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2877     return TRUE;
2878
2879   /* Remove the client from the channel. The client is removed from
2880      the channel's user list. */
2881
2882   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2883
2884   /* Remove channel from client's channel list */
2885   silc_hash_table_del(client->channels, chl->channel);
2886
2887   /* Remove channel if there is no users anymore */
2888   if (server->server_type == SILC_ROUTER &&
2889       silc_hash_table_count(channel->user_list) < 2) {
2890     if (channel->rekey)
2891       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2892     if (silc_idlist_del_channel(server->local_list, channel))
2893       server->stat.my_channels--;
2894     else
2895       silc_idlist_del_channel(server->global_list, channel);
2896     silc_buffer_free(clidp);
2897     return FALSE;
2898   }
2899
2900   /* Remove client from channel's client list */
2901   silc_hash_table_del(channel->user_list, chl->client);
2902   channel->user_count--;
2903
2904   /* If there is no global users on the channel anymore mark the channel
2905      as local channel. Do not check if the client is local client. */
2906   if (server->server_type != SILC_ROUTER && channel->global_users &&
2907       chl->client->router && !silc_server_channel_has_global(channel))
2908     channel->global_users = FALSE;
2909
2910   silc_free(chl);
2911   server->stat.my_chanclients--;
2912
2913   /* If there is not at least one local user on the channel then we don't
2914      need the channel entry anymore, we can remove it safely. */
2915   if (server->server_type != SILC_ROUTER &&
2916       !silc_server_channel_has_local(channel)) {
2917     /* Notify about leaving client if this channel has global users. */
2918     if (notify && channel->global_users)
2919       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2920                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2921                                          clidp->data, clidp->len);
2922
2923     silc_buffer_free(clidp);
2924
2925     if (channel->rekey)
2926       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2927
2928     if (channel->founder_key) {
2929       /* The founder auth data exists, do not remove the channel entry */
2930       SilcChannelClientEntry chl2;
2931       SilcHashTableList htl2;
2932
2933       channel->disabled = TRUE;
2934
2935       silc_hash_table_list(channel->user_list, &htl2);
2936       while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2937         silc_hash_table_del(chl2->client->channels, channel);
2938         silc_hash_table_del(channel->user_list, chl2->client);
2939         channel->user_count--;
2940         silc_free(chl2);
2941       }
2942       silc_hash_table_list_reset(&htl2);
2943       return FALSE;
2944     }
2945
2946     /* Remove the channel entry */
2947     if (silc_idlist_del_channel(server->local_list, channel))
2948       server->stat.my_channels--;
2949     else
2950       silc_idlist_del_channel(server->global_list, channel);
2951     return FALSE;
2952   }
2953
2954   /* Send notify to channel about client leaving the channel */
2955   if (notify)
2956     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2957                                        SILC_NOTIFY_TYPE_LEAVE, 1,
2958                                        clidp->data, clidp->len);
2959
2960   silc_buffer_free(clidp);
2961   return TRUE;
2962 }
2963
2964 /* Timeout callback. This is called if connection is idle or for some
2965    other reason is not responding within some period of time. This
2966    disconnects the remote end. */
2967
2968 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2969 {
2970   SilcServer server = (SilcServer)context;
2971   SilcSocketConnection sock = server->sockets[fd];
2972
2973   SILC_LOG_DEBUG(("Start"));
2974
2975   if (!sock)
2976     return;
2977
2978   SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2979                   sock->hostname, sock->ip));
2980
2981   /* If we have protocol active we must assure that we call the protocol's
2982      final callback so that all the memory is freed. */
2983   if (sock->protocol) {
2984     silc_protocol_cancel(sock->protocol, server->schedule);
2985     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2986     silc_protocol_execute_final(sock->protocol, server->schedule);
2987     sock->protocol = NULL;
2988     return;
2989   }
2990
2991   if (sock->user_data)
2992     silc_server_free_sock_user_data(server, sock, NULL);
2993
2994   silc_server_disconnect_remote(server, sock, "Server closed connection: "
2995                                 "Connection timeout");
2996 }
2997
2998 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2999    function may be used only by router. In real SILC network all channels
3000    are created by routers thus this function is never used by normal
3001    server. */
3002
3003 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3004                                                 SilcServerID *router_id,
3005                                                 char *cipher,
3006                                                 char *hmac,
3007                                                 char *channel_name,
3008                                                 int broadcast)
3009 {
3010   SilcChannelID *channel_id;
3011   SilcChannelEntry entry;
3012   SilcCipher key;
3013   SilcHmac newhmac;
3014
3015   SILC_LOG_DEBUG(("Creating new channel"));
3016
3017   if (!cipher)
3018     cipher = SILC_DEFAULT_CIPHER;
3019   if (!hmac)
3020     hmac = SILC_DEFAULT_HMAC;
3021
3022   /* Allocate cipher */
3023   if (!silc_cipher_alloc(cipher, &key))
3024     return NULL;
3025
3026   /* Allocate hmac */
3027   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3028     silc_cipher_free(key);
3029     return NULL;
3030   }
3031
3032   channel_name = strdup(channel_name);
3033
3034   /* Create the channel ID */
3035   if (!silc_id_create_channel_id(server, router_id, server->rng,
3036                                  &channel_id)) {
3037     silc_free(channel_name);
3038     silc_cipher_free(key);
3039     silc_hmac_free(newhmac);
3040     return NULL;
3041   }
3042
3043   /* Create the channel */
3044   entry = silc_idlist_add_channel(server->local_list, channel_name,
3045                                   SILC_CHANNEL_MODE_NONE, channel_id,
3046                                   NULL, key, newhmac, 0);
3047   if (!entry) {
3048     silc_free(channel_name);
3049     silc_cipher_free(key);
3050     silc_hmac_free(newhmac);
3051     silc_free(channel_id);
3052     return NULL;
3053   }
3054
3055   entry->cipher = strdup(cipher);
3056   entry->hmac_name = strdup(hmac);
3057
3058   /* Now create the actual key material */
3059   if (!silc_server_create_channel_key(server, entry,
3060                                       silc_cipher_get_key_len(key) / 8)) {
3061     silc_idlist_del_channel(server->local_list, entry);
3062     return NULL;
3063   }
3064
3065   /* Notify other routers about the new channel. We send the packet
3066      to our primary route. */
3067   if (broadcast && server->standalone == FALSE)
3068     silc_server_send_new_channel(server, server->router->connection, TRUE,
3069                                  channel_name, entry->id,
3070                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3071                                  entry->mode);
3072
3073   server->stat.my_channels++;
3074
3075   return entry;
3076 }
3077
3078 /* Same as above but creates the channel with Channel ID `channel_id. */
3079
3080 SilcChannelEntry
3081 silc_server_create_new_channel_with_id(SilcServer server,
3082                                        char *cipher,
3083                                        char *hmac,
3084                                        char *channel_name,
3085                                        SilcChannelID *channel_id,
3086                                        int broadcast)
3087 {
3088   SilcChannelEntry entry;
3089   SilcCipher key;
3090   SilcHmac newhmac;
3091
3092   SILC_LOG_DEBUG(("Creating new channel"));
3093
3094   if (!cipher)
3095     cipher = SILC_DEFAULT_CIPHER;
3096   if (!hmac)
3097     hmac = SILC_DEFAULT_HMAC;
3098
3099   /* Allocate cipher */
3100   if (!silc_cipher_alloc(cipher, &key))
3101     return NULL;
3102
3103   /* Allocate hmac */
3104   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3105     silc_cipher_free(key);
3106     return NULL;
3107   }
3108
3109   channel_name = strdup(channel_name);
3110
3111   /* Create the channel */
3112   entry = silc_idlist_add_channel(server->local_list, channel_name,
3113                                   SILC_CHANNEL_MODE_NONE, channel_id,
3114                                   NULL, key, newhmac, 0);
3115   if (!entry) {
3116     silc_cipher_free(key);
3117     silc_hmac_free(newhmac);
3118     silc_free(channel_name);
3119     return NULL;
3120   }
3121
3122   /* Now create the actual key material */
3123   if (!silc_server_create_channel_key(server, entry,
3124                                       silc_cipher_get_key_len(key) / 8)) {
3125     silc_idlist_del_channel(server->local_list, entry);
3126     return NULL;
3127   }
3128
3129   /* Notify other routers about the new channel. We send the packet
3130      to our primary route. */
3131   if (broadcast && server->standalone == FALSE)
3132     silc_server_send_new_channel(server, server->router->connection, TRUE,
3133                                  channel_name, entry->id,
3134                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3135                                  entry->mode);
3136
3137   server->stat.my_channels++;
3138
3139   return entry;
3140 }
3141
3142 /* Channel's key re-key timeout callback. */
3143
3144 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3145 {
3146   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3147   SilcServer server = (SilcServer)rekey->context;
3148
3149   rekey->task = NULL;
3150
3151   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3152     return;
3153
3154   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3155 }
3156
3157 /* Generates new channel key. This is used to create the initial channel key
3158    but also to re-generate new key for channel. If `key_len' is provided
3159    it is the bytes of the key length. */
3160
3161 bool silc_server_create_channel_key(SilcServer server,
3162                                     SilcChannelEntry channel,
3163                                     SilcUInt32 key_len)
3164 {
3165   int i;
3166   unsigned char channel_key[32], hash[32];
3167   SilcUInt32 len;
3168
3169   SILC_LOG_DEBUG(("Generating channel key"));
3170
3171   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3172     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3173     return TRUE;
3174   }
3175
3176   if (!channel->channel_key)
3177     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3178       channel->channel_key = NULL;
3179       return FALSE;
3180     }
3181
3182   if (key_len)
3183     len = key_len;
3184   else if (channel->key_len)
3185     len = channel->key_len / 8;
3186   else
3187     len = silc_cipher_get_key_len(channel->channel_key) / 8;
3188
3189   /* Create channel key */
3190   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3191
3192   /* Set the key */
3193   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3194
3195   /* Remove old key if exists */
3196   if (channel->key) {
3197     memset(channel->key, 0, channel->key_len / 8);
3198     silc_free(channel->key);
3199   }
3200
3201   /* Save the key */
3202   channel->key_len = len * 8;
3203   channel->key = silc_memdup(channel_key, len);
3204   memset(channel_key, 0, sizeof(channel_key));
3205
3206   /* Generate HMAC key from the channel key data and set it */
3207   if (!channel->hmac)
3208     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3209   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3210   silc_hmac_set_key(channel->hmac, hash,
3211                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3212   memset(hash, 0, sizeof(hash));
3213
3214   if (server->server_type == SILC_ROUTER) {
3215     if (!channel->rekey)
3216       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3217     channel->rekey->context = (void *)server;
3218     channel->rekey->channel = channel;
3219     channel->rekey->key_len = key_len;
3220     if (channel->rekey->task)
3221       silc_schedule_task_del(server->schedule, channel->rekey->task);
3222
3223     channel->rekey->task =
3224       silc_schedule_task_add(server->schedule, 0,
3225                              silc_server_channel_key_rekey,
3226                              (void *)channel->rekey,
3227                              server->config->channel_rekey_secs, 0,
3228                              SILC_TASK_TIMEOUT,
3229                              SILC_TASK_PRI_NORMAL);
3230   }
3231
3232   return TRUE;
3233 }
3234
3235 /* Saves the channel key found in the encoded `key_payload' buffer. This
3236    function is used when we receive Channel Key Payload and also when we're
3237    processing JOIN command reply. Returns entry to the channel. */
3238
3239 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3240                                               SilcBuffer key_payload,
3241                                               SilcChannelEntry channel)
3242 {
3243   SilcChannelKeyPayload payload = NULL;
3244   SilcChannelID *id = NULL;
3245   unsigned char *tmp, hash[32];
3246   SilcUInt32 tmp_len;
3247   char *cipher;
3248
3249   SILC_LOG_DEBUG(("Start"));
3250
3251   /* Decode channel key payload */
3252   payload = silc_channel_key_payload_parse(key_payload->data,
3253                                            key_payload->len);
3254   if (!payload) {
3255     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3256     channel = NULL;
3257     goto out;
3258   }
3259
3260   /* Get the channel entry */
3261   if (!channel) {
3262
3263     /* Get channel ID */
3264     tmp = silc_channel_key_get_id(payload, &tmp_len);
3265     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3266     if (!id) {
3267       channel = NULL;
3268       goto out;
3269     }
3270
3271     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3272     if (!channel) {
3273       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3274       if (!channel) {
3275         SILC_LOG_ERROR(("Received key for non-existent channel %s",
3276                         silc_id_render(id, SILC_ID_CHANNEL)));
3277         goto out;
3278       }
3279     }
3280   }
3281
3282   tmp = silc_channel_key_get_key(payload, &tmp_len);
3283   if (!tmp) {
3284     channel = NULL;
3285     goto out;
3286   }
3287
3288   cipher = silc_channel_key_get_cipher(payload, NULL);
3289   if (!cipher) {
3290     channel = NULL;
3291     goto out;
3292   }
3293
3294   /* Remove old key if exists */
3295   if (channel->key) {
3296     memset(channel->key, 0, channel->key_len / 8);
3297     silc_free(channel->key);
3298     silc_cipher_free(channel->channel_key);
3299   }
3300
3301   /* Create new cipher */
3302   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3303     channel->channel_key = NULL;
3304     channel = NULL;
3305     goto out;
3306   }
3307
3308   if (channel->cipher)
3309     silc_free(channel->cipher);
3310   channel->cipher = strdup(cipher);
3311
3312   /* Save the key */
3313   channel->key_len = tmp_len * 8;
3314   channel->key = silc_memdup(tmp, tmp_len);
3315   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3316
3317   /* Generate HMAC key from the channel key data and set it */
3318   if (!channel->hmac)
3319     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3320   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3321   silc_hmac_set_key(channel->hmac, hash,
3322                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3323
3324   memset(hash, 0, sizeof(hash));
3325   memset(tmp, 0, tmp_len);
3326
3327   if (server->server_type == SILC_ROUTER) {
3328     if (!channel->rekey)
3329       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3330     channel->rekey->context = (void *)server;
3331     channel->rekey->channel = channel;
3332     if (channel->rekey->task)
3333       silc_schedule_task_del(server->schedule, channel->rekey->task);
3334
3335     channel->rekey->task =
3336       silc_schedule_task_add(server->schedule, 0,
3337                              silc_server_channel_key_rekey,
3338                              (void *)channel->rekey,
3339                              server->config->channel_rekey_secs, 0,
3340                              SILC_TASK_TIMEOUT,
3341                              SILC_TASK_PRI_NORMAL);
3342   }
3343
3344  out:
3345   silc_free(id);
3346   if (payload)
3347     silc_channel_key_payload_free(payload);
3348
3349   return channel;
3350 }
3351
3352 /* Heartbeat callback. This function is set as argument for the
3353    silc_socket_set_heartbeat function. The library will call this function
3354    at the set time interval. */
3355
3356 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3357                                    void *hb_context)
3358 {
3359   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3360
3361   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3362
3363   /* Send the heartbeat */
3364   silc_server_send_heartbeat(hb->server, sock);
3365 }
3366
3367 /* Returns assembled of all servers in the given ID list. The packet's
3368    form is dictated by the New ID payload. */
3369
3370 static void silc_server_announce_get_servers(SilcServer server,
3371                                              SilcServerEntry remote,
3372                                              SilcIDList id_list,
3373                                              SilcBuffer *servers,
3374                                              unsigned long creation_time)
3375 {
3376   SilcIDCacheList list;
3377   SilcIDCacheEntry id_cache;
3378   SilcServerEntry entry;
3379   SilcBuffer idp;
3380
3381   /* Go through all clients in the list */
3382   if (silc_idcache_get_all(id_list->servers, &list)) {
3383     if (silc_idcache_list_first(list, &id_cache)) {
3384       while (id_cache) {
3385         entry = (SilcServerEntry)id_cache->context;
3386
3387         /* Do not announce the one we've sending our announcements and
3388            do not announce ourself. Also check the creation time if it's
3389            provided. */
3390         if ((entry == remote) || (entry == server->id_entry) ||
3391             (creation_time && entry->data.created < creation_time)) {
3392           if (!silc_idcache_list_next(list, &id_cache))
3393             break;
3394           continue;
3395         }
3396
3397         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3398
3399         *servers = silc_buffer_realloc(*servers,
3400                                        (*servers ?
3401                                         (*servers)->truelen + idp->len :
3402                                         idp->len));
3403         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3404         silc_buffer_put(*servers, idp->data, idp->len);
3405         silc_buffer_pull(*servers, idp->len);
3406         silc_buffer_free(idp);
3407
3408         if (!silc_idcache_list_next(list, &id_cache))
3409           break;
3410       }
3411     }
3412
3413     silc_idcache_list_free(list);
3414   }
3415 }
3416
3417 static SilcBuffer
3418 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3419 {
3420   va_list ap;
3421   SilcBuffer p;
3422
3423   va_start(ap, argc);
3424   p = silc_notify_payload_encode(notify, argc, ap);
3425   va_end(ap);
3426
3427   return p;
3428 }
3429
3430 /* This function is used by router to announce existing servers to our
3431    primary router when we've connected to it. If `creation_time' is non-zero
3432    then only the servers that has been created after the `creation_time'
3433    will be announced. */
3434
3435 void silc_server_announce_servers(SilcServer server, bool global,
3436                                   unsigned long creation_time,
3437                                   SilcSocketConnection remote)
3438 {
3439   SilcBuffer servers = NULL;
3440
3441   SILC_LOG_DEBUG(("Announcing servers"));
3442
3443   /* Get servers in local list */
3444   silc_server_announce_get_servers(server, remote->user_data,
3445                                    server->local_list, &servers,
3446                                    creation_time);
3447
3448   if (global)
3449     /* Get servers in global list */
3450     silc_server_announce_get_servers(server, remote->user_data,
3451                                      server->global_list, &servers,
3452                                      creation_time);
3453
3454   if (servers) {
3455     silc_buffer_push(servers, servers->data - servers->head);
3456     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3457
3458     /* Send the packet */
3459     silc_server_packet_send(server, remote,
3460                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3461                             servers->data, servers->len, TRUE);
3462
3463     silc_buffer_free(servers);
3464   }
3465 }
3466
3467 /* Returns assembled packet of all clients in the given ID list. The
3468    packet's form is dictated by the New ID Payload. */
3469
3470 static void silc_server_announce_get_clients(SilcServer server,
3471                                              SilcIDList id_list,
3472                                              SilcBuffer *clients,
3473                                              SilcBuffer *umodes,
3474                                              unsigned long creation_time)
3475 {
3476   SilcIDCacheList list;
3477   SilcIDCacheEntry id_cache;
3478   SilcClientEntry client;
3479   SilcBuffer idp;
3480   SilcBuffer tmp;
3481   unsigned char mode[4];
3482
3483   /* Go through all clients in the list */
3484   if (silc_idcache_get_all(id_list->clients, &list)) {
3485     if (silc_idcache_list_first(list, &id_cache)) {
3486       while (id_cache) {
3487         client = (SilcClientEntry)id_cache->context;
3488
3489         if (creation_time && client->data.created < creation_time) {
3490           if (!silc_idcache_list_next(list, &id_cache))
3491             break;
3492           continue;
3493         }
3494
3495         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3496
3497         *clients = silc_buffer_realloc(*clients,
3498                                        (*clients ?
3499                                         (*clients)->truelen + idp->len :
3500                                         idp->len));
3501         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3502         silc_buffer_put(*clients, idp->data, idp->len);
3503         silc_buffer_pull(*clients, idp->len);
3504
3505         SILC_PUT32_MSB(client->mode, mode);
3506         tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3507                                                  2, idp->data, idp->len,
3508                                                  mode, 4);
3509         *umodes = silc_buffer_realloc(*umodes,
3510                                       (*umodes ?
3511                                        (*umodes)->truelen + tmp->len :
3512                                        tmp->len));
3513         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3514         silc_buffer_put(*umodes, tmp->data, tmp->len);
3515         silc_buffer_pull(*umodes, tmp->len);
3516         silc_buffer_free(tmp);
3517
3518         silc_buffer_free(idp);
3519
3520         if (!silc_idcache_list_next(list, &id_cache))
3521           break;
3522       }
3523     }
3524
3525     silc_idcache_list_free(list);
3526   }
3527 }
3528
3529 /* This function is used to announce our existing clients to our router
3530    when we've connected to it. If `creation_time' is non-zero then only
3531    the clients that has been created after the `creation_time' will be
3532    announced. */
3533
3534 void silc_server_announce_clients(SilcServer server,
3535                                   unsigned long creation_time,
3536                                   SilcSocketConnection remote)
3537 {
3538   SilcBuffer clients = NULL;
3539   SilcBuffer umodes = NULL;
3540
3541   SILC_LOG_DEBUG(("Announcing clients"));
3542
3543   /* Get clients in local list */
3544   silc_server_announce_get_clients(server, server->local_list,
3545                                    &clients, &umodes, creation_time);
3546
3547   /* As router we announce our global list as well */
3548   if (server->server_type == SILC_ROUTER)
3549     silc_server_announce_get_clients(server, server->global_list,
3550                                      &clients, &umodes, creation_time);
3551
3552   if (clients) {
3553     silc_buffer_push(clients, clients->data - clients->head);
3554     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3555
3556     /* Send the packet */
3557     silc_server_packet_send(server, remote,
3558                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3559                             clients->data, clients->len, TRUE);
3560
3561     silc_buffer_free(clients);
3562   }
3563
3564   if (umodes) {
3565     silc_buffer_push(umodes, umodes->data - umodes->head);
3566     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3567
3568     /* Send the packet */
3569     silc_server_packet_send(server, remote,
3570                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3571                             umodes->data, umodes->len, TRUE);
3572
3573     silc_buffer_free(umodes);
3574   }
3575 }
3576
3577 /* Returns channel's topic for announcing it */
3578
3579 void silc_server_announce_get_channel_topic(SilcServer server,
3580                                             SilcChannelEntry channel,
3581                                             SilcBuffer *topic)
3582 {
3583   SilcBuffer chidp;
3584
3585   if (channel->topic) {
3586     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3587     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3588                                                 chidp->data, chidp->len,
3589                                                 channel->topic,
3590                                                 strlen(channel->topic));
3591     silc_buffer_free(chidp);
3592   }
3593 }
3594
3595 /* Returns assembled packets for channel users of the `channel'. */
3596
3597 void silc_server_announce_get_channel_users(SilcServer server,
3598                                             SilcChannelEntry channel,
3599                                             SilcBuffer *channel_users,
3600                                             SilcBuffer *channel_users_modes)
3601 {
3602   SilcChannelClientEntry chl;
3603   SilcHashTableList htl;
3604   SilcBuffer chidp, clidp;
3605   SilcBuffer tmp;
3606   int len;
3607   unsigned char mode[4];
3608
3609   SILC_LOG_DEBUG(("Start"));
3610
3611   /* Now find all users on the channel */
3612   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3613   silc_hash_table_list(channel->user_list, &htl);
3614   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3615     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3616
3617     /* JOIN Notify */
3618     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3619                                              clidp->data, clidp->len,
3620                                              chidp->data, chidp->len);
3621     len = tmp->len;
3622     *channel_users =
3623       silc_buffer_realloc(*channel_users,
3624                           (*channel_users ?
3625                            (*channel_users)->truelen + len : len));
3626     silc_buffer_pull_tail(*channel_users,
3627                           ((*channel_users)->end -
3628                            (*channel_users)->data));
3629
3630     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3631     silc_buffer_pull(*channel_users, len);
3632     silc_buffer_free(tmp);
3633
3634     /* CUMODE notify for mode change on the channel */
3635     SILC_PUT32_MSB(chl->mode, mode);
3636     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3637                                              3, clidp->data, clidp->len,
3638                                              mode, 4,
3639                                              clidp->data, clidp->len);
3640     len = tmp->len;
3641     *channel_users_modes =
3642       silc_buffer_realloc(*channel_users_modes,
3643                           (*channel_users_modes ?
3644                            (*channel_users_modes)->truelen + len : len));
3645     silc_buffer_pull_tail(*channel_users_modes,
3646                           ((*channel_users_modes)->end -
3647                            (*channel_users_modes)->data));
3648
3649     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3650     silc_buffer_pull(*channel_users_modes, len);
3651     silc_buffer_free(tmp);
3652
3653     silc_buffer_free(clidp);
3654   }
3655   silc_hash_table_list_reset(&htl);
3656   silc_buffer_free(chidp);
3657 }
3658
3659 /* Returns assembled packets for all channels and users on those channels
3660    from the given ID List. The packets are in the form dictated by the
3661    New Channel and New Channel User payloads. */
3662
3663 void silc_server_announce_get_channels(SilcServer server,
3664                                        SilcIDList id_list,
3665                                        SilcBuffer *channels,
3666                                        SilcBuffer *channel_users,
3667                                        SilcBuffer **channel_users_modes,
3668                                        SilcUInt32 *channel_users_modes_c,
3669                                        SilcBuffer **channel_topics,
3670                                        SilcChannelID ***channel_ids,
3671                                        unsigned long creation_time)
3672 {
3673   SilcIDCacheList list;
3674   SilcIDCacheEntry id_cache;
3675   SilcChannelEntry channel;
3676   unsigned char *cid;
3677   SilcUInt32 id_len;
3678   SilcUInt16 name_len;
3679   int len;
3680   int i = *channel_users_modes_c;
3681   bool announce;
3682
3683   SILC_LOG_DEBUG(("Start"));
3684
3685   /* Go through all channels in the list */
3686   if (silc_idcache_get_all(id_list->channels, &list)) {
3687     if (silc_idcache_list_first(list, &id_cache)) {
3688       while (id_cache) {
3689         channel = (SilcChannelEntry)id_cache->context;
3690
3691         if (creation_time && channel->created < creation_time)
3692           announce = FALSE;
3693         else
3694           announce = TRUE;
3695
3696         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3697         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3698         name_len = strlen(channel->channel_name);
3699
3700         if (announce) {
3701           len = 4 + name_len + id_len + 4;
3702           *channels =
3703             silc_buffer_realloc(*channels,
3704                                 (*channels ? (*channels)->truelen +
3705                                  len : len));
3706           silc_buffer_pull_tail(*channels,
3707                                 ((*channels)->end - (*channels)->data));
3708           silc_buffer_format(*channels,
3709                              SILC_STR_UI_SHORT(name_len),
3710                              SILC_STR_UI_XNSTRING(channel->channel_name,
3711                                                   name_len),
3712                              SILC_STR_UI_SHORT(id_len),
3713                              SILC_STR_UI_XNSTRING(cid, id_len),
3714                              SILC_STR_UI_INT(channel->mode),
3715                              SILC_STR_END);
3716           silc_buffer_pull(*channels, len);
3717         }
3718
3719         /* Channel user modes */
3720         *channel_users_modes = silc_realloc(*channel_users_modes,
3721                                             sizeof(**channel_users_modes) *
3722                                             (i + 1));
3723         (*channel_users_modes)[i] = NULL;
3724         *channel_ids = silc_realloc(*channel_ids,
3725                                     sizeof(**channel_ids) * (i + 1));
3726         (*channel_ids)[i] = NULL;
3727         silc_server_announce_get_channel_users(server, channel,
3728                                                channel_users,
3729                                                &(*channel_users_modes)[i]);
3730         (*channel_ids)[i] = channel->id;
3731
3732         /* Channel's topic */
3733         *channel_topics = silc_realloc(*channel_topics,
3734                                        sizeof(**channel_topics) * (i + 1));
3735         (*channel_topics)[i] = NULL;
3736         silc_server_announce_get_channel_topic(server, channel,
3737                                                &(*channel_topics)[i]);
3738         i++;
3739
3740         if (!silc_idcache_list_next(list, &id_cache))
3741           break;
3742       }
3743
3744       *channel_users_modes_c += i;
3745     }
3746
3747     silc_idcache_list_free(list);
3748   }
3749 }
3750
3751 /* This function is used to announce our existing channels to our router
3752    when we've connected to it. This also announces the users on the
3753    channels to the router. If the `creation_time' is non-zero only the
3754    channels that was created after the `creation_time' are announced.
3755    Note that the channel users are still announced even if the `creation_time'
3756    was provided. */
3757
3758 void silc_server_announce_channels(SilcServer server,
3759                                    unsigned long creation_time,
3760                                    SilcSocketConnection remote)
3761 {
3762   SilcBuffer channels = NULL, channel_users = NULL;
3763   SilcBuffer *channel_users_modes = NULL;
3764   SilcBuffer *channel_topics = NULL;
3765   SilcUInt32 channel_users_modes_c = 0;
3766   SilcChannelID **channel_ids = NULL;
3767
3768   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3769
3770   /* Get channels and channel users in local list */
3771   silc_server_announce_get_channels(server, server->local_list,
3772                                     &channels, &channel_users,
3773                                     &channel_users_modes,
3774                                     &channel_users_modes_c,
3775                                     &channel_topics,
3776                                     &channel_ids, creation_time);
3777
3778   /* Get channels and channel users in global list */
3779   if (server->server_type != SILC_SERVER)
3780     silc_server_announce_get_channels(server, server->global_list,
3781                                       &channels, &channel_users,
3782                                       &channel_users_modes,
3783                                       &channel_users_modes_c,
3784                                       &channel_topics,
3785                                       &channel_ids, creation_time);
3786
3787   if (channels) {
3788     silc_buffer_push(channels, channels->data - channels->head);
3789     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3790
3791     /* Send the packet */
3792     silc_server_packet_send(server, remote,
3793                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3794                             channels->data, channels->len,
3795                             FALSE);
3796
3797     silc_buffer_free(channels);
3798   }
3799
3800   if (channel_users) {
3801     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3802     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3803                      channel_users->len);
3804
3805     /* Send the packet */
3806     silc_server_packet_send(server, remote,
3807                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3808                             channel_users->data, channel_users->len,
3809                             FALSE);
3810
3811     silc_buffer_free(channel_users);
3812   }
3813
3814   if (channel_users_modes) {
3815     int i;
3816
3817     for (i = 0; i < channel_users_modes_c; i++) {
3818       if (!channel_users_modes[i])
3819         continue;
3820       silc_buffer_push(channel_users_modes[i],
3821                        channel_users_modes[i]->data -
3822                        channel_users_modes[i]->head);
3823       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3824                        channel_users_modes[i]->len);
3825       silc_server_packet_send_dest(server, remote,
3826                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3827                                    channel_ids[i], SILC_ID_CHANNEL,
3828                                    channel_users_modes[i]->data,
3829                                    channel_users_modes[i]->len,
3830                                    FALSE);
3831       silc_buffer_free(channel_users_modes[i]);
3832     }
3833     silc_free(channel_users_modes);
3834   }
3835
3836   if (channel_topics) {
3837     int i;
3838
3839     for (i = 0; i < channel_users_modes_c; i++) {
3840       if (!channel_topics[i])
3841         continue;
3842
3843       silc_buffer_push(channel_topics[i],
3844                        channel_topics[i]->data -
3845                        channel_topics[i]->head);
3846       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3847                        channel_topics[i]->len);
3848       silc_server_packet_send_dest(server, remote,
3849                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3850                                    channel_ids[i], SILC_ID_CHANNEL,
3851                                    channel_topics[i]->data,
3852                                    channel_topics[i]->len,
3853                                    FALSE);
3854       silc_buffer_free(channel_topics[i]);
3855     }
3856     silc_free(channel_topics);
3857   }
3858
3859   silc_free(channel_ids);
3860 }
3861
3862 /* Failure timeout callback. If this is called then we will immediately
3863    process the received failure. We always process the failure with timeout
3864    since we do not want to blindly trust to received failure packets.
3865    This won't be called (the timeout is cancelled) if the failure was
3866    bogus (it is bogus if remote does not close the connection after sending
3867    the failure). */
3868
3869 SILC_TASK_CALLBACK(silc_server_failure_callback)
3870 {
3871   SilcServerFailureContext f = (SilcServerFailureContext)context;
3872
3873   if (f->sock->protocol) {
3874     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3875     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3876   }
3877
3878   silc_free(f);
3879 }
3880
3881 /* Assembles user list and users mode list from the `channel'. */
3882
3883 void silc_server_get_users_on_channel(SilcServer server,
3884                                       SilcChannelEntry channel,
3885                                       SilcBuffer *user_list,
3886                                       SilcBuffer *mode_list,
3887                                       SilcUInt32 *user_count)
3888 {
3889   SilcChannelClientEntry chl;
3890   SilcHashTableList htl;
3891   SilcBuffer client_id_list;
3892   SilcBuffer client_mode_list;
3893   SilcBuffer idp;
3894   SilcUInt32 list_count = 0, len = 0;
3895
3896   silc_hash_table_list(channel->user_list, &htl);
3897   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3898     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3899   silc_hash_table_list_reset(&htl);
3900
3901   client_id_list = silc_buffer_alloc(len);
3902   client_mode_list =
3903     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3904   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3905   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3906
3907   silc_hash_table_list(channel->user_list, &htl);
3908   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3909     /* Client ID */
3910     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3911     silc_buffer_put(client_id_list, idp->data, idp->len);
3912     silc_buffer_pull(client_id_list, idp->len);
3913     silc_buffer_free(idp);
3914
3915     /* Client's mode on channel */
3916     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3917     silc_buffer_pull(client_mode_list, 4);
3918
3919     list_count++;
3920   }
3921   silc_hash_table_list_reset(&htl);
3922   silc_buffer_push(client_id_list,
3923                    client_id_list->data - client_id_list->head);
3924   silc_buffer_push(client_mode_list,
3925                    client_mode_list->data - client_mode_list->head);
3926
3927   *user_list = client_id_list;
3928   *mode_list = client_mode_list;
3929   *user_count = list_count;
3930 }
3931
3932 /* Saves users and their modes to the `channel'. */
3933
3934 void silc_server_save_users_on_channel(SilcServer server,
3935                                        SilcSocketConnection sock,
3936                                        SilcChannelEntry channel,
3937                                        SilcClientID *noadd,
3938                                        SilcBuffer user_list,
3939                                        SilcBuffer mode_list,
3940                                        SilcUInt32 user_count)
3941 {
3942   int i;
3943   SilcUInt16 idp_len;
3944   SilcUInt32 mode;
3945   SilcClientID *client_id;
3946   SilcClientEntry client;
3947   SilcIDCacheEntry cache;
3948   bool global;
3949
3950   SILC_LOG_DEBUG(("Start"));
3951
3952   for (i = 0; i < user_count; i++) {
3953     /* Client ID */
3954     SILC_GET16_MSB(idp_len, user_list->data + 2);
3955     idp_len += 4;
3956     client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3957     silc_buffer_pull(user_list, idp_len);
3958     if (!client_id)
3959       continue;
3960
3961     /* Mode */
3962     SILC_GET32_MSB(mode, mode_list->data);
3963     silc_buffer_pull(mode_list, 4);
3964
3965     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3966       silc_free(client_id);
3967       continue;
3968     }
3969
3970     global = FALSE;
3971
3972     /* Check if we have this client cached already. */
3973     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3974                                            server->server_type, &cache);
3975     if (!client) {
3976       client = silc_idlist_find_client_by_id(server->global_list,
3977                                              client_id, server->server_type,
3978                                              &cache);
3979       global = TRUE;
3980     }
3981     if (!client) {
3982       /* If router did not find such Client ID in its lists then this must
3983          be bogus client or some router in the net is buggy. */
3984       if (server->server_type == SILC_ROUTER) {
3985         silc_free(client_id);
3986         continue;
3987       }
3988
3989       /* We don't have that client anywhere, add it. The client is added
3990          to global list since server didn't have it in the lists so it must be
3991          global. */
3992       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3993                                       silc_id_dup(client_id, SILC_ID_CLIENT),
3994                                       sock->user_data, NULL, 0);
3995       if (!client) {
3996         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3997         silc_free(client_id);
3998         continue;
3999       }
4000
4001       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4002     } else {
4003       /* Found, if it is from global list we'll assure that we won't
4004          expire it now that the entry is on channel. */
4005       if (global)
4006         cache->expire = 0;
4007     }
4008
4009     silc_free(client_id);
4010
4011     if (!silc_server_client_on_channel(client, channel, NULL)) {
4012       /* Client was not on the channel, add it. */
4013       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
4014       chl->client = client;
4015       chl->mode = mode;
4016       chl->channel = channel;
4017       silc_hash_table_add(channel->user_list, chl->client, chl);
4018       silc_hash_table_add(client->channels, chl->channel, chl);
4019       channel->user_count++;
4020     }
4021   }
4022 }
4023
4024 /* Lookups route to the client indicated by the `id_data'. The connection
4025    object and internal data object is returned. Returns NULL if route
4026    could not be found to the client. If the `client_id' is specified then
4027    it is used and the `id_data' is ignored. */
4028
4029 SilcSocketConnection silc_server_get_client_route(SilcServer server,
4030                                                   unsigned char *id_data,
4031                                                   SilcUInt32 id_len,
4032                                                   SilcClientID *client_id,
4033                                                   SilcIDListData *idata)
4034 {
4035   SilcClientID *id;
4036   SilcClientEntry client;
4037
4038   SILC_LOG_DEBUG(("Start"));
4039
4040   /* Decode destination Client ID */
4041   if (!client_id) {
4042     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4043     if (!id) {
4044       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4045       return NULL;
4046     }
4047   } else {
4048     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4049   }
4050
4051   /* If the destination belongs to our server we don't have to route
4052      the packet anywhere but to send it to the local destination. */
4053   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4054   if (client) {
4055     silc_free(id);
4056
4057     /* If we are router and the client has router then the client is in
4058        our cell but not directly connected to us. */
4059     if (server->server_type == SILC_ROUTER && client->router) {
4060       /* We are of course in this case the client's router thus the route
4061          to the client is the server who owns the client. So, we will send
4062          the packet to that server. */
4063       if (idata)
4064         *idata = (SilcIDListData)client->router;
4065       return client->router->connection;
4066     }
4067
4068     /* Seems that client really is directly connected to us */
4069     if (idata)
4070       *idata = (SilcIDListData)client;
4071     return client->connection;
4072   }
4073
4074   /* Destination belongs to someone not in this server. If we are normal
4075      server our action is to send the packet to our router. */
4076   if (server->server_type != SILC_ROUTER && !server->standalone) {
4077     silc_free(id);
4078     if (idata)
4079       *idata = (SilcIDListData)server->router;
4080     return server->router->connection;
4081   }
4082
4083   /* We are router and we will perform route lookup for the destination
4084      and send the packet to fastest route. */
4085   if (server->server_type == SILC_ROUTER && !server->standalone) {
4086     /* Check first that the ID is valid */
4087     client = silc_idlist_find_client_by_id(server->global_list, id,
4088                                            TRUE, NULL);
4089     if (client) {
4090       SilcSocketConnection dst_sock;
4091
4092       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4093
4094       silc_free(id);
4095       if (idata)
4096         *idata = (SilcIDListData)dst_sock->user_data;
4097       return dst_sock;
4098     }
4099   }
4100
4101   silc_free(id);
4102   return NULL;
4103 }
4104
4105 /* Encodes and returns channel list of channels the `client' has joined.
4106    Secret channels are not put to the list. */
4107
4108 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4109                                                SilcClientEntry client)
4110 {
4111   SilcBuffer buffer = NULL;
4112   SilcChannelEntry channel;
4113   SilcChannelClientEntry chl;
4114   SilcHashTableList htl;
4115   unsigned char *cid;
4116   SilcUInt32 id_len;
4117   SilcUInt16 name_len;
4118   int len;
4119
4120   silc_hash_table_list(client->channels, &htl);
4121   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4122     channel = chl->channel;
4123
4124     if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4125         channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4126       continue;
4127
4128     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4129     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4130     name_len = strlen(channel->channel_name);
4131
4132     len = 4 + name_len + id_len + 4;
4133     buffer = silc_buffer_realloc(buffer,
4134                                  (buffer ? (buffer)->truelen + len : len));
4135     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4136     silc_buffer_format(buffer,
4137                        SILC_STR_UI_SHORT(name_len),
4138                        SILC_STR_UI_XNSTRING(channel->channel_name,
4139                                             name_len),
4140                        SILC_STR_UI_SHORT(id_len),
4141                        SILC_STR_UI_XNSTRING(cid, id_len),
4142                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
4143                        SILC_STR_END);
4144     silc_buffer_pull(buffer, len);
4145     silc_free(cid);
4146   }
4147   silc_hash_table_list_reset(&htl);
4148
4149   if (buffer)
4150     silc_buffer_push(buffer, buffer->data - buffer->head);
4151
4152   return buffer;
4153 }
4154
4155 /* Finds client entry by Client ID and if it is not found then resolves
4156    it using WHOIS command. */
4157
4158 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4159                                                SilcClientID *client_id,
4160                                                bool *resolved)
4161 {
4162   SilcClientEntry client;
4163
4164   if (resolved)
4165     *resolved = FALSE;
4166
4167   client = silc_idlist_find_client_by_id(server->local_list, client_id,
4168                                          TRUE, NULL);
4169   if (!client) {
4170     client = silc_idlist_find_client_by_id(server->global_list,
4171                                            client_id, TRUE, NULL);
4172     if (!client && server->server_type == SILC_ROUTER)
4173       return NULL;
4174   }
4175
4176   if (!client && server->standalone)
4177     return NULL;
4178
4179   if (!client || !client->nickname || !client->username) {
4180     SilcBuffer buffer, idp;
4181
4182     client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4183     client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4184     client->resolve_cmd_ident = ++server->cmd_ident;
4185
4186     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4187     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4188                                             server->cmd_ident, 1,
4189                                             3, idp->data, idp->len);
4190     silc_server_packet_send(server, client ? client->router->connection :
4191                             server->router->connection,
4192                             SILC_PACKET_COMMAND, 0,
4193                             buffer->data, buffer->len, FALSE);
4194     silc_buffer_free(idp);
4195     silc_buffer_free(buffer);
4196
4197     if (resolved)
4198       *resolved = TRUE;
4199
4200     return NULL;
4201   }
4202
4203   return client;
4204 }
4205
4206 /* A timeout callback for the re-key. We will be the initiator of the
4207    re-key protocol. */
4208
4209 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4210 {
4211   SilcSocketConnection sock = (SilcSocketConnection)context;
4212   SilcIDListData idata = (SilcIDListData)sock->user_data;
4213   SilcServer server = (SilcServer)idata->rekey->context;
4214   SilcProtocol protocol;
4215   SilcServerRekeyInternalContext *proto_ctx;
4216
4217   SILC_LOG_DEBUG(("Start"));
4218
4219   /* Allocate internal protocol context. This is sent as context
4220      to the protocol. */
4221   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4222   proto_ctx->server = (void *)server;
4223   proto_ctx->sock = sock;
4224   proto_ctx->responder = FALSE;
4225   proto_ctx->pfs = idata->rekey->pfs;
4226
4227   /* Perform rekey protocol. Will call the final callback after the
4228      protocol is over. */
4229   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4230                       &protocol, proto_ctx, silc_server_rekey_final);
4231   sock->protocol = protocol;
4232
4233   /* Run the protocol */
4234   silc_protocol_execute(protocol, server->schedule, 0, 0);
4235
4236   /* Re-register re-key timeout */
4237   silc_schedule_task_add(server->schedule, sock->sock,
4238                          silc_server_rekey_callback,
4239                          context, idata->rekey->timeout, 0,
4240                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4241 }
4242
4243 /* The final callback for the REKEY protocol. This will actually take the
4244    new key material into use. */
4245
4246 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4247 {
4248   SilcProtocol protocol = (SilcProtocol)context;
4249   SilcServerRekeyInternalContext *ctx =
4250     (SilcServerRekeyInternalContext *)protocol->context;
4251   SilcServer server = (SilcServer)ctx->server;
4252   SilcSocketConnection sock = ctx->sock;
4253
4254   SILC_LOG_DEBUG(("Start"));
4255
4256   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4257       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4258     /* Error occured during protocol */
4259     SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4260     silc_protocol_cancel(protocol, server->schedule);
4261     silc_protocol_free(protocol);
4262     sock->protocol = NULL;
4263     if (ctx->packet)
4264       silc_packet_context_free(ctx->packet);
4265     if (ctx->ske)
4266       silc_ske_free(ctx->ske);
4267     silc_free(ctx);
4268     return;
4269   }
4270
4271   /* Purge the outgoing data queue to assure that all rekey packets really
4272      go to the network before we quit the protocol. */
4273   silc_server_packet_queue_purge(server, sock);
4274
4275   /* Cleanup */
4276   silc_protocol_free(protocol);
4277   sock->protocol = NULL;
4278   if (ctx->packet)
4279     silc_packet_context_free(ctx->packet);
4280   if (ctx->ske)
4281     silc_ske_free(ctx->ske);
4282   silc_free(ctx);
4283 }