Fixed GCC-3.3.2 related compilation warnings.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2003 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; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /*
20  * This is the actual SILC server than handles everything relating to
21  * servicing the SILC connections. This is also a SILC router as a router
22  * is also normal server.
23  */
24 /* $Id$ */
25
26 #include "serverincludes.h"
27 #include "server_internal.h"
28
29 /* Static prototypes */
30 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
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_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_close_connection_final);
41 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
42 SILC_TASK_CALLBACK(silc_server_timeout_remote);
43 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
44 SILC_TASK_CALLBACK(silc_server_get_stats);
45
46 /* Allocates a new SILC server object. This has to be done before the server
47    can be used. After allocation one must call silc_server_init to initialize
48    the server. The new allocated server object is returned to the new_server
49    argument. */
50
51 int silc_server_alloc(SilcServer *new_server)
52 {
53   SilcServer server;
54
55   SILC_LOG_DEBUG(("Allocating new server object"));
56
57   server = silc_calloc(1, sizeof(*server));
58   server->server_type = SILC_SERVER;
59   server->standalone = TRUE;
60   server->local_list = silc_calloc(1, sizeof(*server->local_list));
61   server->global_list = silc_calloc(1, sizeof(*server->global_list));
62   server->pending_commands = silc_dlist_init();
63 #ifdef SILC_SIM
64   server->sim = silc_dlist_init();
65 #endif
66
67   *new_server = server;
68
69   return TRUE;
70 }
71
72 /* Free's the SILC server object. This is called at the very end before
73    the program ends. */
74
75 void silc_server_free(SilcServer server)
76 {
77   SilcIDCacheList list;
78   SilcIDCacheEntry cache;
79
80   if (!server)
81     return;
82
83 #ifdef SILC_SIM
84   {
85     SilcSim sim;
86     silc_dlist_start(server->sim);
87     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88       silc_dlist_del(server->sim, sim);
89       silc_sim_close(sim);
90       silc_sim_free(sim);
91     }
92     silc_dlist_uninit(server->sim);
93   }
94 #endif
95
96   silc_server_backup_free(server);
97   silc_server_config_unref(&server->config_ref);
98   if (server->rng)
99     silc_rng_free(server->rng);
100   if (server->pkcs)
101     silc_pkcs_free(server->pkcs);
102   if (server->public_key)
103     silc_pkcs_public_key_free(server->public_key);
104   if (server->private_key)
105     silc_pkcs_private_key_free(server->private_key);
106   if (server->pending_commands)
107     silc_dlist_uninit(server->pending_commands);
108   if (server->id_entry)
109     silc_idlist_del_server(server->local_list, server->id_entry);
110
111   /* Delete all channels */
112   list = NULL;
113   if (silc_idcache_get_all(server->local_list->channels, &list) &&
114       silc_idcache_list_first(list, &cache)) {
115     silc_idlist_del_channel(server->local_list, cache->context);
116     while (silc_idcache_list_next(list, &cache))
117       silc_idlist_del_channel(server->local_list, cache->context);
118   }
119   if (list)
120     silc_idcache_list_free(list);
121   list = NULL;
122   if (silc_idcache_get_all(server->global_list->channels, &list) &&
123       silc_idcache_list_first(list, &cache)) {
124     silc_idlist_del_channel(server->global_list, cache->context);
125     while (silc_idcache_list_next(list, &cache))
126       silc_idlist_del_channel(server->global_list, cache->context);
127   }
128   if (list)
129     silc_idcache_list_free(list);
130
131   /* Delete all clients */
132   list = NULL;
133   if (silc_idcache_get_all(server->local_list->clients, &list) &&
134       silc_idcache_list_first(list, &cache)) {
135     silc_idlist_del_client(server->local_list, cache->context);
136     while (silc_idcache_list_next(list, &cache))
137       silc_idlist_del_client(server->local_list, cache->context);
138   }
139   if (list)
140     silc_idcache_list_free(list);
141   list = NULL;
142   if (silc_idcache_get_all(server->global_list->clients, &list) &&
143       silc_idcache_list_first(list, &cache)) {
144     silc_idlist_del_client(server->global_list, cache->context);
145     while (silc_idcache_list_next(list, &cache))
146       silc_idlist_del_client(server->global_list, cache->context);
147   }
148   if (list)
149     silc_idcache_list_free(list);
150
151   if (server->pk_hash)
152     silc_hash_table_free(server->pk_hash);
153
154   /* Delete all servers */
155   list = NULL;
156   if (silc_idcache_get_all(server->local_list->servers, &list) &&
157       silc_idcache_list_first(list, &cache)) {
158     silc_idlist_del_server(server->local_list, cache->context);
159     while (silc_idcache_list_next(list, &cache))
160       silc_idlist_del_server(server->local_list, cache->context);
161   }
162   if (list)
163     silc_idcache_list_free(list);
164   list = NULL;
165   if (silc_idcache_get_all(server->global_list->servers, &list) &&
166       silc_idcache_list_first(list, &cache)) {
167     silc_idlist_del_server(server->global_list, cache->context);
168     while (silc_idcache_list_next(list, &cache))
169       silc_idlist_del_server(server->global_list, cache->context);
170   }
171   if (list)
172     silc_idcache_list_free(list);
173
174   silc_idcache_free(server->local_list->clients);
175   silc_idcache_free(server->local_list->servers);
176   silc_idcache_free(server->local_list->channels);
177   silc_idcache_free(server->global_list->clients);
178   silc_idcache_free(server->global_list->servers);
179   silc_idcache_free(server->global_list->channels);
180   silc_hash_table_free(server->watcher_list);
181
182   silc_hash_free(server->md5hash);
183   silc_hash_free(server->sha1hash);
184   silc_hmac_unregister_all();
185   silc_hash_unregister_all();
186   silc_cipher_unregister_all();
187   silc_pkcs_unregister_all();
188
189   silc_free(server->local_list);
190   silc_free(server->global_list);
191   silc_free(server->server_name);
192   silc_free(server->id_string);
193   silc_free(server->purge_i);
194   silc_free(server->purge_g);
195   silc_free(server);
196 }
197
198 /* Creates a new server listener. */
199
200 static bool silc_server_listen(SilcServer server, const char *server_ip,
201                                SilcUInt16 port, int *sock)
202 {
203   *sock = silc_net_create_server(port, server_ip);
204   if (*sock < 0) {
205     SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
206                         server_ip, port));
207     return FALSE;
208   }
209   return TRUE;
210 }
211
212 /* Adds a secondary listener. */
213
214 bool silc_server_init_secondary(SilcServer server)
215 {
216   int sock = 0, sock_list[server->config->param.connections_max];
217   SilcSocketConnection newsocket = NULL;
218   SilcServerConfigServerInfoInterface *interface;
219
220   for (interface = server->config->server_info->secondary; interface;
221         interface = interface->next, sock++) {
222
223     if (!silc_server_listen(server,
224         interface->server_ip, interface->port, &sock_list[sock]))
225       goto err;
226
227     /* Set socket to non-blocking mode */
228     silc_net_set_socket_nonblock(sock_list[sock]);
229
230     /* Add ourselves also to the socket table. The entry allocated above
231        is sent as argument for fast referencing in the future. */
232     silc_socket_alloc(sock_list[sock],
233                       SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
234     server->sockets[sock_list[sock]] = newsocket;
235     SILC_SET_LISTENER(newsocket);
236
237     /* Perform name and address lookups to resolve the listenning address
238        and port. */
239     if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
240                             &newsocket->ip)) {
241       if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
242         !newsocket->ip) {
243         SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
244                       newsocket->hostname ? newsocket->hostname :
245                       newsocket->ip ? newsocket->ip : ""));
246         server->stat.conn_failures++;
247         goto err;
248       }
249       if (!newsocket->hostname)
250         newsocket->hostname = strdup(newsocket->ip);
251     }
252     newsocket->port = silc_net_get_local_port(sock);
253
254     newsocket->user_data = (void *)server->id_entry;
255     silc_schedule_task_add(server->schedule, sock_list[sock],
256                            silc_server_accept_new_connection,
257                            (void *)server, 0, 0,
258                            SILC_TASK_FD,
259                            SILC_TASK_PRI_NORMAL);
260   }
261
262   return TRUE;
263
264  err:
265   do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
266   return FALSE;
267 }
268
269 /* Initializes the entire SILC server. This is called always before running
270    the server. This is called only once at the initialization of the program.
271    This binds the server to its listenning port. After this function returns
272    one should call silc_server_run to start the server. This returns TRUE
273    when everything is ok to run the server. Configuration file must be
274    read and parsed before calling this. */
275
276 bool silc_server_init(SilcServer server)
277 {
278   int sock;
279   SilcServerID *id;
280   SilcServerEntry id_entry;
281   SilcIDListPurge purge;
282   SilcSocketConnection newsocket = NULL;
283
284   SILC_LOG_DEBUG(("Initializing server"));
285
286   server->starttime = time(NULL);
287
288   /* Take config object for us */
289   silc_server_config_ref(&server->config_ref, server->config,
290                          server->config);
291
292 #ifdef SILC_DEBUG
293   /* Set debugging on if configured */
294   if (server->config->debug_string) {
295     silc_debug = TRUE;
296     silc_log_set_debug_string(server->config->debug_string);
297   }
298 #endif /* SILC_DEBUG */
299
300   /* Steal public and private key from the config object */
301   server->public_key = server->config->server_info->public_key;
302   server->private_key = server->config->server_info->private_key;
303   server->config->server_info->public_key = NULL;
304   server->config->server_info->private_key = NULL;
305
306   /* Register all configured ciphers, PKCS and hash functions. */
307   if (!silc_server_config_register_ciphers(server))
308     silc_cipher_register_default();
309   if (!silc_server_config_register_pkcs(server))
310     silc_pkcs_register_default();
311   if (!silc_server_config_register_hashfuncs(server))
312     silc_hash_register_default();
313   if (!silc_server_config_register_hmacs(server))
314     silc_hmac_register_default();
315
316   /* Initialize random number generator for the server. */
317   server->rng = silc_rng_alloc();
318   silc_rng_init(server->rng);
319   silc_rng_global_init(server->rng);
320
321   /* Initialize hash functions for server to use */
322   silc_hash_alloc("md5", &server->md5hash);
323   silc_hash_alloc("sha1", &server->sha1hash);
324
325   /* Allocate PKCS context for local public and private keys */
326   if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
327     goto err;
328   silc_pkcs_public_key_set(server->pkcs, server->public_key);
329   silc_pkcs_private_key_set(server->pkcs, server->private_key);
330
331   /* Initialize the scheduler */
332   server->schedule = silc_schedule_init(server->config->param.connections_max,
333                                         server);
334   if (!server->schedule)
335     goto err;
336
337   /* First, register log files configuration for error output */
338   silc_server_config_setlogfiles(server);
339
340   /* Initialize ID caches */
341   server->local_list->clients =
342     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
343   server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
344   server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
345
346   /* These are allocated for normal server as well as these hold some
347      global information that the server has fetched from its router. For
348      router these are used as they are supposed to be used on router. */
349   server->global_list->clients =
350     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
351   server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
352   server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
353
354   /* Init watcher list */
355   server->watcher_list =
356     silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
357                           silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
358                           NULL, NULL, TRUE);
359   if (!server->watcher_list)
360     goto err;
361
362   /* Init public key list */
363   server->pk_hash =
364     silc_hash_table_alloc(0, silc_hash_public_key, NULL,
365                           silc_hash_public_key_compare, NULL,
366                           NULL, NULL, TRUE);
367
368   if (!server->pk_hash)
369     goto err;
370
371   /* Create a listening server */
372   if (!silc_server_listen(server,
373                 server->config->server_info->primary == NULL ? NULL :
374                         server->config->server_info->primary->server_ip,
375                 server->config->server_info->primary == NULL ? 0 :
376                         server->config->server_info->primary->port,
377                 &sock))
378     goto err;
379
380   /* Set socket to non-blocking mode */
381   silc_net_set_socket_nonblock(sock);
382   server->sock = sock;
383
384   /* Allocate the entire socket list that is used in server. Eventually
385      all connections will have entry in this table (it is a table of
386      pointers to the actual object that is allocated individually
387      later). */
388   server->sockets = silc_calloc(server->config->param.connections_max,
389                                 sizeof(*server->sockets));
390   if (!server->sockets)
391     goto err;
392
393   /* Add ourselves also to the socket table. The entry allocated above
394      is sent as argument for fast referencing in the future. */
395   silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
396   server->sockets[sock] = newsocket;
397   SILC_SET_LISTENER(newsocket);
398
399   /* Perform name and address lookups to resolve the listenning address
400      and port. */
401   if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
402                                     &newsocket->ip)) {
403     if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
404         !newsocket->ip) {
405       SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
406                       newsocket->hostname ? newsocket->hostname :
407                       newsocket->ip ? newsocket->ip : ""));
408       server->stat.conn_failures++;
409       goto err;
410     }
411     if (!newsocket->hostname)
412       newsocket->hostname = strdup(newsocket->ip);
413   }
414   newsocket->port = silc_net_get_local_port(sock);
415
416   /* Create a Server ID for the server. */
417   silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
418   if (!id)
419     goto err;
420
421   server->id = id;
422   server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
423   server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
424   server->server_name = server->config->server_info->server_name;
425   server->config->server_info->server_name = NULL;
426
427   /* Add ourselves to the server list. We don't have a router yet
428      beacuse we haven't established a route yet. It will be done later.
429      For now, NULL is sent as router. This allocates new entry to
430      the ID list. */
431   id_entry =
432     silc_idlist_add_server(server->local_list, strdup(server->server_name),
433                            server->server_type, server->id, NULL, NULL);
434   if (!id_entry) {
435     SILC_LOG_ERROR(("Could not add ourselves to cache"));
436     goto err;
437   }
438   id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
439
440   /* Put the allocated socket pointer also to the entry allocated above
441      for fast back-referencing to the socket list. */
442   newsocket->user_data = (void *)id_entry;
443   id_entry->connection = (void *)newsocket;
444   server->id_entry = id_entry;
445
446   /* Register protocols */
447   silc_server_protocols_register();
448
449   /* Create connections to configured routers. */
450   silc_server_create_connections(server);
451
452   /* Add listener task to the scheduler. This task receives new connections
453      to the server. This task remains on the queue until the end of the
454      program. */
455   silc_schedule_task_add(server->schedule, sock,
456                          silc_server_accept_new_connection,
457                          (void *)server, 0, 0,
458                          SILC_TASK_FD,
459                          SILC_TASK_PRI_NORMAL);
460
461   if (silc_server_init_secondary(server) == FALSE)
462     goto err;
463
464   server->listenning = TRUE;
465
466   /* If server connections has been configured then we must be router as
467      normal server cannot have server connections, only router connections. */
468   if (server->config->servers) {
469     SilcServerConfigServer *ptr = server->config->servers;
470
471     server->server_type = SILC_ROUTER;
472     while (ptr) {
473       if (ptr->backup_router) {
474         server->server_type = SILC_BACKUP_ROUTER;
475         server->backup_router = TRUE;
476         server->id_entry->server_type = SILC_BACKUP_ROUTER;
477         break;
478       }
479       ptr = ptr->next;
480     }
481   }
482
483   /* Register the ID Cache purge task. This periodically purges the ID cache
484      and removes the expired cache entries. */
485
486   /* Clients local list */
487   server->purge_i = purge = silc_calloc(1, sizeof(*purge));
488   purge->cache = server->local_list->clients;
489   purge->timeout = 600;
490   silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
491                          (void *)purge, purge->timeout, 0,
492                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
493
494   /* Clients global list */
495   server->purge_g = purge = silc_calloc(1, sizeof(*purge));
496   purge->cache = server->global_list->clients;
497   purge->timeout = 300;
498   silc_schedule_task_add(server->schedule, 0, silc_idlist_purge,
499                          (void *)purge, purge->timeout, 0,
500                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
501
502   /* If we are normal server we'll retrieve network statisticial information
503      once in a while from the router. */
504   if (server->server_type != SILC_ROUTER)
505     silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
506                            server, 10, 0, SILC_TASK_TIMEOUT,
507                            SILC_TASK_PRI_LOW);
508
509   if (server->server_type == SILC_ROUTER)
510     server->stat.routers++;
511
512   SILC_LOG_DEBUG(("Server initialized"));
513
514   /* We are done here, return succesfully */
515   return TRUE;
516
517  err:
518   silc_server_config_unref(&server->config_ref);
519   silc_net_close_server(sock);
520   return FALSE;
521 }
522
523 /* Task callback to close a socket connection after rehash */
524
525 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
526 {
527   SilcServer server = context;
528   SilcSocketConnection sock = server->sockets[fd];
529
530   if (!sock)
531     return;
532
533   SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
534                  sock->hostname, sock->port,
535                  (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
536                   sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
537                   sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
538                   "Router")));
539   silc_schedule_task_del_by_context(server->schedule, sock);
540   silc_server_disconnect_remote(server, sock,
541                                 SILC_STATUS_ERR_BANNED_FROM_SERVER,
542                                 "This connection is removed from "
543                                 "configuration");
544   if (sock->user_data)
545     silc_server_free_sock_user_data(server, sock, NULL);
546 }
547
548 /* This function basically reads the config file again and switches the config
549    object pointed by the server object. After that, we have to fix various
550    things such as the server_name and the listening ports.
551    Keep in mind that we no longer have the root privileges at this point. */
552
553 bool silc_server_rehash(SilcServer server)
554 {
555   SilcServerConfig newconfig;
556
557   SILC_LOG_INFO(("Rehashing server"));
558
559   /* Reset the logging system */
560   silc_log_quick = TRUE;
561   silc_log_flush_all();
562
563   /* Start the main rehash phase (read again the config file) */
564   newconfig = silc_server_config_alloc(server->config_file);
565   if (!newconfig) {
566     SILC_LOG_ERROR(("Rehash FAILED."));
567     return FALSE;
568   }
569
570   /* Reinit scheduler if necessary */
571   if (newconfig->param.connections_max > server->config->param.connections_max)
572     if (!silc_schedule_reinit(server->schedule,
573                               newconfig->param.connections_max))
574       return FALSE;
575
576   /* Fix the server_name field */
577   if (strcmp(server->server_name, newconfig->server_info->server_name)) {
578     silc_free(server->server_name);
579     server->server_name = newconfig->server_info->server_name;
580     newconfig->server_info->server_name = NULL;
581
582     /* Update the idcache list with a fresh pointer */
583     silc_free(server->id_entry->server_name);
584     server->id_entry->server_name = strdup(server->server_name);
585     if (!silc_idcache_del_by_context(server->local_list->servers,
586                                      server->id_entry))
587       return FALSE;
588     if (!silc_idcache_add(server->local_list->servers,
589                           server->id_entry->server_name,
590                           server->id_entry->id, server->id_entry, 0, NULL))
591       return FALSE;
592   }
593
594   /* Set logging */
595   silc_server_config_setlogfiles(server);
596
597   /* Change new key pair if necessary */
598   if (newconfig->server_info->public_key &&
599       !silc_pkcs_public_key_compare(server->public_key,
600                                     newconfig->server_info->public_key)) {
601     silc_pkcs_public_key_free(server->public_key);
602     silc_pkcs_private_key_free(server->private_key);
603     server->public_key = newconfig->server_info->public_key;
604     server->private_key = newconfig->server_info->private_key;
605     newconfig->server_info->public_key = NULL;
606     newconfig->server_info->private_key = NULL;
607
608     /* Allocate PKCS context for local public and private keys */
609     silc_pkcs_free(server->pkcs);
610     if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
611       return FALSE;
612     silc_pkcs_public_key_set(server->pkcs, server->public_key);
613     silc_pkcs_private_key_set(server->pkcs, server->private_key);
614   }
615
616   /* Check for unconfigured server and router connections and close
617      connections that were unconfigured. */
618
619   if (server->config->routers) {
620     SilcServerConfigRouter *ptr;
621     SilcServerConfigRouter *newptr;
622     bool found;
623
624     for (ptr = server->config->routers; ptr; ptr = ptr->next) {
625       found = FALSE;
626
627       /* Check whether new config has this one too */
628       for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
629         if (silc_string_compare(newptr->host, ptr->host) &&
630             newptr->port == ptr->port &&
631             newptr->initiator == ptr->initiator) {
632           found = TRUE;
633           break;
634         }
635       }
636
637       if (!found && ptr->host) {
638         /* Remove this connection */
639         SilcSocketConnection sock;
640         sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
641                                                ptr->host, ptr->port);
642         if (sock && !SILC_IS_LISTENER(sock))
643           silc_schedule_task_add(server->schedule, sock->sock,
644                                  silc_server_rehash_close_connection,
645                                  server, 0, 1, SILC_TASK_TIMEOUT,
646                                  SILC_TASK_PRI_NORMAL);
647       }
648     }
649   }
650
651   if (server->config->servers) {
652     SilcServerConfigServer *ptr;
653     SilcServerConfigServer *newptr;
654     bool found;
655
656     for (ptr = server->config->servers; ptr; ptr = ptr->next) {
657       found = FALSE;
658
659       /* Check whether new config has this one too */
660       for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
661         if (silc_string_compare(newptr->host, ptr->host)) {
662           found = TRUE;
663           break;
664         }
665       }
666
667       if (!found && ptr->host) {
668         /* Remove this connection */
669         SilcSocketConnection sock;
670         sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
671                                                ptr->host, 0);
672         if (sock && !SILC_IS_LISTENER(sock))
673           silc_schedule_task_add(server->schedule, sock->sock,
674                                  silc_server_rehash_close_connection,
675                                  server, 0, 1, SILC_TASK_TIMEOUT,
676                                  SILC_TASK_PRI_NORMAL);
677       }
678     }
679   }
680
681   if (server->config->clients) {
682     SilcServerConfigClient *ptr;
683     SilcServerConfigClient *newptr;
684     bool found;
685
686     for (ptr = server->config->clients; ptr; ptr = ptr->next) {
687       found = FALSE;
688
689       /* Check whether new config has this one too */
690       for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
691         if (silc_string_compare(newptr->host, ptr->host)) {
692           found = TRUE;
693           break;
694         }
695       }
696
697       if (!found && ptr->host) {
698         /* Remove this connection */
699         SilcSocketConnection sock;
700         sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_CLIENT,
701                                                ptr->host, 0);
702         if (sock)
703           silc_schedule_task_add(server->schedule, sock->sock,
704                                  silc_server_rehash_close_connection,
705                                  server, 0, 1, SILC_TASK_TIMEOUT,
706                                  SILC_TASK_PRI_NORMAL);
707       }
708     }
709   }
710
711   /* Create connections after rehash */
712   silc_server_create_connections(server);
713
714   /* Check whether our router status has changed */
715   if (newconfig->servers) {
716     SilcServerConfigServer *ptr = newconfig->servers;
717
718     server->server_type = SILC_ROUTER;
719     while (ptr) {
720       if (ptr->backup_router) {
721         server->server_type = SILC_BACKUP_ROUTER;
722         server->backup_router = TRUE;
723         server->id_entry->server_type = SILC_BACKUP_ROUTER;
724         break;
725       }
726       ptr = ptr->next;
727     }
728   }
729
730   /* Our old config is gone now. We'll unreference our reference made in
731      silc_server_init and then destroy it since we are destroying it
732      underneath the application (layer which called silc_server_init). */
733   silc_server_config_unref(&server->config_ref);
734   silc_server_config_destroy(server->config);
735
736   /* Take new config context */
737   server->config = newconfig;
738   silc_server_config_ref(&server->config_ref, server->config, server->config);
739
740 #ifdef SILC_DEBUG
741   /* Set debugging on if configured */
742   if (server->config->debug_string) {
743     silc_debug = TRUE;
744     silc_log_set_debug_string(server->config->debug_string);
745   } else {
746     silc_debug = FALSE;
747   }
748 #endif /* SILC_DEBUG */
749
750   SILC_LOG_DEBUG(("Server rehashed"));
751
752   return TRUE;
753 }
754
755 /* The heart of the server. This runs the scheduler thus runs the server.
756    When this returns the server has been stopped and the program will
757    be terminated. */
758
759 void silc_server_run(SilcServer server)
760 {
761   SILC_LOG_INFO(("SILC Server started"));
762
763   /* Start the scheduler, the heart of the SILC server. When this returns
764      the program will be terminated. */
765   silc_schedule(server->schedule);
766 }
767
768 /* Stops the SILC server. This function is used to shutdown the server.
769    This is usually called after the scheduler has returned. After stopping
770    the server one should call silc_server_free. */
771
772 void silc_server_stop(SilcServer server)
773 {
774   SILC_LOG_INFO(("SILC Server shutting down"));
775
776   if (server->schedule) {
777     int i;
778
779     server->server_shutdown = TRUE;
780
781     /* Close all connections */
782     for (i = 0; i < server->config->param.connections_max; i++) {
783       if (!server->sockets[i])
784         continue;
785       if (!SILC_IS_LISTENER(server->sockets[i])) {
786         SilcSocketConnection sock = server->sockets[i];
787         SilcIDListData idata = sock->user_data;
788
789         if (idata)
790           idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
791
792         silc_schedule_task_del_by_context(server->schedule,
793                                           server->sockets[i]);
794         silc_schedule_task_del_by_fd(server->schedule,
795                                      server->sockets[i]->sock);
796         silc_server_disconnect_remote(server, server->sockets[i],
797                                       SILC_STATUS_OK,
798                                       "Server is shutting down");
799         if (server->sockets[i]) {
800           if (sock->user_data)
801             silc_server_free_sock_user_data(server, sock,
802                                             "Server is shutting down");
803           silc_socket_free(sock);
804         }
805       } else {
806         silc_socket_free(server->sockets[i]);
807         server->sockets[i] = NULL;
808       }
809     }
810
811     /* We are not connected to network anymore */
812     server->standalone = TRUE;
813
814     silc_schedule_stop(server->schedule);
815     silc_schedule_uninit(server->schedule);
816     server->schedule = NULL;
817
818     silc_free(server->sockets);
819     server->sockets = NULL;
820   }
821
822   silc_server_protocols_unregister();
823
824   SILC_LOG_DEBUG(("Server stopped"));
825 }
826
827 /* Function that is called when the network connection to a router has
828    been established.  This will continue with the key exchange protocol
829    with the remote router. */
830
831 void silc_server_start_key_exchange(SilcServer server,
832                                     SilcServerConnection sconn,
833                                     int sock)
834 {
835   SilcSocketConnection newsocket;
836   SilcProtocol protocol;
837   SilcServerKEInternalContext *proto_ctx;
838   SilcServerConfigRouter *conn =
839     (SilcServerConfigRouter *) sconn->conn.ref_ptr;
840   void *context;
841
842   /* Cancel any possible retry timeouts */
843   silc_schedule_task_del_by_callback(server->schedule,
844                                      silc_server_connect_to_router_retry);
845
846   /* Set socket options */
847   silc_net_set_socket_nonblock(sock);
848   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
849
850   /* Create socket connection for the connection. Even though we
851      know that we are connecting to a router we will mark the socket
852      to be unknown connection until we have executed authentication
853      protocol. */
854   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
855   server->sockets[sock] = newsocket;
856   newsocket->hostname = strdup(sconn->remote_host);
857   newsocket->ip = strdup(sconn->remote_host);
858   newsocket->port = sconn->remote_port;
859   sconn->sock = newsocket;
860
861   /* Allocate internal protocol context. This is sent as context
862      to the protocol. */
863   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
864   proto_ctx->server = (void *)server;
865   proto_ctx->context = (void *)sconn;
866   proto_ctx->sock = newsocket;
867   proto_ctx->rng = server->rng;
868   proto_ctx->responder = FALSE;
869
870   /* Set Key Exchange flags from configuration, but fall back to global
871      settings too. */
872   SILC_GET_SKE_FLAGS(conn, proto_ctx);
873   if (server->config->param.key_exchange_pfs)
874     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
875
876   /* Perform key exchange protocol. silc_server_connect_to_router_second
877      will be called after the protocol is finished. */
878   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
879                       &protocol, proto_ctx,
880                       silc_server_connect_to_router_second);
881   newsocket->protocol = protocol;
882
883   /* Register a timeout task that will be executed if the protocol
884      is not executed within set limit. */
885   proto_ctx->timeout_task =
886     silc_schedule_task_add(server->schedule, sock,
887                            silc_server_timeout_remote,
888                            server, server->config->key_exchange_timeout, 0,
889                            SILC_TASK_TIMEOUT,
890                            SILC_TASK_PRI_LOW);
891
892   /* Register the connection for network input and output. This sets
893      that scheduler will listen for incoming packets for this connection
894      and sets that outgoing packets may be sent to this connection as
895      well. However, this doesn't set the scheduler for outgoing traffic,
896      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
897      later when outgoing data is available. */
898   context = (void *)server;
899   SILC_REGISTER_CONNECTION_FOR_IO(sock);
900
901   /* Run the protocol */
902   silc_protocol_execute(protocol, server->schedule, 0, 0);
903 }
904
905 /* Timeout callback that will be called to retry connecting to remote
906    router. This is used by both normal and router server. This will wait
907    before retrying the connecting. The timeout is generated by exponential
908    backoff algorithm. */
909
910 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
911 {
912   SilcServer server = app_context;
913   SilcServerConnection sconn = (SilcServerConnection)context;
914   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
915   SilcServerConfigConnParams *param =
916                 (conn->param ? conn->param : &server->config->param);
917
918   /* Don't retry if we are shutting down. */
919   if (server->server_shutdown) {
920     silc_server_config_unref(&sconn->conn);
921     silc_free(sconn->remote_host);
922     silc_free(sconn->backup_replace_ip);
923     silc_free(sconn);
924     return;
925   }
926
927   SILC_LOG_INFO(("Retrying connecting to a router"));
928
929   /* Calculate next timeout */
930   if (sconn->retry_count >= 1) {
931     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
932     if (sconn->retry_timeout > param->reconnect_interval_max)
933       sconn->retry_timeout = param->reconnect_interval_max;
934   } else {
935     sconn->retry_timeout = param->reconnect_interval;
936   }
937   sconn->retry_count++;
938   sconn->retry_timeout = sconn->retry_timeout +
939     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
940
941   /* If we've reached max retry count, give up. */
942   if ((sconn->retry_count > param->reconnect_count) &&
943       !param->reconnect_keep_trying) {
944     SILC_LOG_ERROR(("Could not connect to router, giving up"));
945     silc_server_config_unref(&sconn->conn);
946     silc_free(sconn->remote_host);
947     silc_free(sconn->backup_replace_ip);
948     silc_free(sconn);
949     return;
950   }
951
952   SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
953                   sconn->retry_timeout));
954
955   /* We will lookup a fresh pointer later */
956   silc_server_config_unref(&sconn->conn);
957
958   /* Wait one before retrying */
959   silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
960                          context, sconn->retry_timeout, 0,
961                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
962 }
963
964 /* Generic routine to use connect to a router. */
965
966 SILC_TASK_CALLBACK(silc_server_connect_router)
967 {
968   SilcServer server = app_context;
969   SilcServerConnection sconn = (SilcServerConnection)context;
970   SilcServerConfigRouter *rconn;
971   int sock;
972
973   /* Don't connect if we are shutting down. */
974   if (server->server_shutdown) {
975     silc_free(sconn->remote_host);
976     silc_free(sconn->backup_replace_ip);
977     silc_free(sconn);
978     return;
979   }
980
981   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
982                  (sconn->backup ? "backup router" : "router"),
983                  sconn->remote_host, sconn->remote_port));
984
985   server->router_connect = time(NULL);
986   rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
987                                               sconn->remote_port);
988   if (!rconn) {
989     SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
990                    (sconn->backup ? "backup router" : "router"),
991                    sconn->remote_host, sconn->remote_port));
992     silc_free(sconn->remote_host);
993     silc_free(sconn->backup_replace_ip);
994     silc_free(sconn);
995     return;
996   }
997   silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
998
999   /* Connect to remote host */
1000   sock = silc_net_create_connection(
1001                  (!server->config->server_info->primary ? NULL :
1002                   server->config->server_info->primary->server_ip),
1003                  sconn->remote_port, sconn->remote_host);
1004   if (sock < 0) {
1005     SILC_LOG_ERROR(("Could not connect to router %s:%d",
1006                     sconn->remote_host, sconn->remote_port));
1007     if (!sconn->no_reconnect)
1008       silc_schedule_task_add(server->schedule, 0,
1009                              silc_server_connect_to_router_retry,
1010                              context, 0, 1, SILC_TASK_TIMEOUT,
1011                              SILC_TASK_PRI_NORMAL);
1012     else {
1013       silc_server_config_unref(&sconn->conn);
1014       silc_free(sconn->remote_host);
1015       silc_free(sconn->backup_replace_ip);
1016       silc_free(sconn);
1017     }
1018     return;
1019   }
1020
1021   /* Continue with key exchange protocol */
1022   silc_server_start_key_exchange(server, sconn, sock);
1023 }
1024
1025 /* This function connects to our primary router or if we are a router this
1026    establishes all our primary routes. This is called at the start of the
1027    server to do authentication and key exchange with our router - called
1028    from schedule. */
1029
1030 SILC_TASK_CALLBACK_GLOBAL(silc_server_connect_to_router)
1031 {
1032   SilcServer server = (SilcServer)context;
1033   SilcServerConnection sconn;
1034   SilcServerConfigRouter *ptr;
1035
1036   /* Don't connect if we are shutting down. */
1037   if (server->server_shutdown)
1038     return;
1039
1040   SILC_LOG_DEBUG(("We are %s",
1041                   (server->server_type == SILC_SERVER ?
1042                    "normal server" : server->server_type == SILC_ROUTER ?
1043                    "router" : "backup router/normal server")));
1044
1045   if (!server->config->routers) {
1046     /* There wasn't a configured router, we will continue but we don't
1047        have a connection to outside world.  We will be standalone server. */
1048     SILC_LOG_DEBUG(("No router(s), we are standalone"));
1049     server->standalone = TRUE;
1050     return;
1051   }
1052
1053   /* Cancel any possible retry timeouts */
1054   silc_schedule_task_del_by_callback(server->schedule,
1055                                      silc_server_connect_router);
1056   silc_schedule_task_del_by_callback(server->schedule,
1057                                      silc_server_connect_to_router_retry);
1058
1059   /* Create the connections to all our routes */
1060   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1061
1062     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1063                     ptr->backup_router ? "Backup router" : "Router",
1064                     ptr->initiator ? "Initiator" : "Responder",
1065                     ptr->host, ptr->port));
1066
1067     if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1068         ptr->initiator == FALSE && !server->backup_router &&
1069         !silc_server_config_get_backup_router(server))
1070       server->wait_backup = TRUE;
1071
1072     if (ptr->initiator) {
1073       /* Check whether we are connecting or connected to this host already */
1074       if (silc_server_num_sockets_by_remote(server,
1075                                             silc_net_is_ip(ptr->host) ?
1076                                             ptr->host : NULL,
1077                                             silc_net_is_ip(ptr->host) ?
1078                                             NULL : ptr->host, ptr->port,
1079                                             SILC_SOCKET_TYPE_ROUTER)) {
1080         SILC_LOG_DEBUG(("We are already connected to this router"));
1081
1082         /* If we don't have primary router and this connection is our
1083            primary router we are in desync.  Reconnect to the primary. */
1084         if (server->standalone && !server->router) {
1085           SilcServerConfigRouter *primary =
1086             silc_server_config_get_primary_router(server);
1087           if (primary == ptr) {
1088             SilcSocketConnection sock =
1089               silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
1090                                               ptr->host, ptr->port);
1091             if (sock) {
1092               server->backup_noswitch = TRUE;
1093               if (sock->user_data)
1094                 silc_server_free_sock_user_data(server, sock, NULL);
1095               silc_server_disconnect_remote(server, sock, 0, NULL);
1096               server->backup_noswitch = FALSE;
1097               SILC_LOG_DEBUG(("Reconnecting to primary router"));
1098             } else {
1099               continue;
1100             }
1101           } else {
1102             continue;
1103           }
1104         } else {
1105           continue;
1106         }
1107       }
1108       if (silc_server_num_sockets_by_remote(server,
1109                                             silc_net_is_ip(ptr->host) ?
1110                                             ptr->host : NULL,
1111                                             silc_net_is_ip(ptr->host) ?
1112                                             NULL : ptr->host, ptr->port,
1113                                             SILC_SOCKET_TYPE_UNKNOWN)) {
1114         SILC_LOG_DEBUG(("We are already connecting to this router"));
1115         continue;
1116       }
1117
1118       /* Allocate connection object for hold connection specific stuff. */
1119       sconn = silc_calloc(1, sizeof(*sconn));
1120       sconn->remote_host = strdup(ptr->host);
1121       sconn->remote_port = ptr->port;
1122       sconn->backup = ptr->backup_router;
1123       if (sconn->backup) {
1124         sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1125         sconn->backup_replace_port = ptr->backup_replace_port;
1126       }
1127
1128       if (!server->router_conn && !sconn->backup)
1129         server->router_conn = sconn;
1130
1131       silc_schedule_task_add(server->schedule, 0,
1132                              silc_server_connect_router,
1133                              (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
1134                              SILC_TASK_PRI_NORMAL);
1135     }
1136   }
1137 }
1138
1139 /* Second part of connecting to router(s). Key exchange protocol has been
1140    executed and now we will execute authentication protocol. */
1141
1142 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
1143 {
1144   SilcProtocol protocol = (SilcProtocol)context;
1145   SilcServerKEInternalContext *ctx =
1146     (SilcServerKEInternalContext *)protocol->context;
1147   SilcServer server = (SilcServer)ctx->server;
1148   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1149   SilcSocketConnection sock = ctx->sock;
1150   SilcServerConnAuthInternalContext *proto_ctx;
1151   SilcServerConfigRouter *conn = NULL;
1152
1153   SILC_LOG_DEBUG(("Start"));
1154
1155   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1156       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1157     /* Error occured during protocol */
1158     silc_protocol_free(protocol);
1159     sock->protocol = NULL;
1160     silc_ske_free_key_material(ctx->keymat);
1161     if (ctx->packet)
1162       silc_packet_context_free(ctx->packet);
1163     if (ctx->ske)
1164       silc_ske_free(ctx->ske);
1165     silc_free(ctx->dest_id);
1166     silc_free(ctx);
1167     silc_server_disconnect_remote(server, sock,
1168                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1169
1170     /* Try reconnecting if configuration wants it */
1171     if (!sconn->no_reconnect) {
1172       silc_schedule_task_add(server->schedule, 0,
1173                              silc_server_connect_to_router_retry,
1174                              sconn, 0, 1, SILC_TASK_TIMEOUT,
1175                              SILC_TASK_PRI_NORMAL);
1176       return;
1177     }
1178
1179     /* Call completion to indicate error */
1180     if (sconn->callback)
1181       (*sconn->callback)(server, NULL, sconn->callback_context);
1182
1183     silc_server_config_unref(&sconn->conn);
1184     silc_free(sconn->remote_host);
1185     silc_free(sconn->backup_replace_ip);
1186     silc_free(sconn);
1187     return;
1188   }
1189
1190   /* We now have the key material as the result of the key exchange
1191      protocol. Take the key material into use. Free the raw key material
1192      as soon as we've set them into use. */
1193   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1194                                         ctx->sock, ctx->keymat,
1195                                         ctx->ske->prop->cipher,
1196                                         ctx->ske->prop->pkcs,
1197                                         ctx->ske->prop->hash,
1198                                         ctx->ske->prop->hmac,
1199                                         ctx->ske->prop->group,
1200                                         ctx->responder)) {
1201     silc_protocol_free(protocol);
1202     sock->protocol = NULL;
1203     silc_ske_free_key_material(ctx->keymat);
1204     if (ctx->packet)
1205       silc_packet_context_free(ctx->packet);
1206     if (ctx->ske)
1207       silc_ske_free(ctx->ske);
1208     silc_free(ctx->dest_id);
1209     silc_free(ctx);
1210     silc_server_disconnect_remote(server, sock,
1211                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1212
1213     /* Try reconnecting if configuration wants it */
1214     if (!sconn->no_reconnect) {
1215       silc_schedule_task_add(server->schedule, 0,
1216                              silc_server_connect_to_router_retry,
1217                              sconn, 0, 1, SILC_TASK_TIMEOUT,
1218                              SILC_TASK_PRI_NORMAL);
1219       return;
1220     }
1221
1222     /* Call completion to indicate error */
1223     if (sconn->callback)
1224       (*sconn->callback)(server, NULL, sconn->callback_context);
1225
1226     silc_server_config_unref(&sconn->conn);
1227     silc_free(sconn->remote_host);
1228     silc_free(sconn->backup_replace_ip);
1229     silc_free(sconn);
1230     return;
1231   }
1232   silc_ske_free_key_material(ctx->keymat);
1233
1234   /* Allocate internal context for the authentication protocol. This
1235      is sent as context for the protocol. */
1236   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1237   proto_ctx->server = (void *)server;
1238   proto_ctx->context = (void *)sconn;
1239   proto_ctx->sock = sock;
1240   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
1241   proto_ctx->dest_id_type = ctx->dest_id_type;
1242   proto_ctx->dest_id = ctx->dest_id;
1243
1244   /* Resolve the authentication method used in this connection. Check if
1245      we find a match from user configured connections */
1246   if (!sconn->conn.ref_ptr)
1247     conn = silc_server_config_find_router_conn(server, sock->hostname,
1248                                                sock->port);
1249   else
1250     conn = sconn->conn.ref_ptr;
1251
1252   if (conn) {
1253     /* Match found. Use the configured authentication method. Take only
1254        the passphrase, since for public key auth we automatically use
1255        our local key pair. */
1256     if (conn->passphrase) {
1257       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1258         proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1259       } else {
1260         proto_ctx->auth_data = strdup(conn->passphrase);
1261         proto_ctx->auth_data_len = strlen(conn->passphrase);
1262         proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1263       }
1264     } else if (conn->publickeys) {
1265       proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1266     } else {
1267       proto_ctx->auth_meth = SILC_AUTH_NONE;
1268     }
1269   } else {
1270     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1271                     sock->hostname, sock->ip, sock->port));
1272     silc_protocol_free(protocol);
1273     sock->protocol = NULL;
1274     if (ctx->packet)
1275       silc_packet_context_free(ctx->packet);
1276     if (ctx->ske)
1277       silc_ske_free(ctx->ske);
1278     silc_free(ctx->dest_id);
1279     silc_free(ctx);
1280     silc_server_config_unref(&sconn->conn);
1281     silc_free(sconn->remote_host);
1282     silc_free(sconn->backup_replace_ip);
1283     silc_free(sconn);
1284     silc_server_disconnect_remote(server, sock,
1285                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1286     return;
1287   }
1288
1289   /* Free old protocol as it is finished now */
1290   silc_protocol_free(protocol);
1291   if (ctx->packet)
1292     silc_packet_context_free(ctx->packet);
1293   silc_free(ctx);
1294   sock->protocol = NULL;
1295
1296   /* Allocate the authentication protocol. This is allocated here
1297      but we won't start it yet. We will be receiving party of this
1298      protocol thus we will wait that connecting party will make
1299      their first move. */
1300   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1301                       &sock->protocol, proto_ctx,
1302                       silc_server_connect_to_router_final);
1303
1304   /* Register timeout task. If the protocol is not executed inside
1305      this timelimit the connection will be terminated. */
1306   proto_ctx->timeout_task =
1307     silc_schedule_task_add(server->schedule, sock->sock,
1308                            silc_server_timeout_remote,
1309                            (void *)server,
1310                            server->config->conn_auth_timeout, 0,
1311                            SILC_TASK_TIMEOUT,
1312                            SILC_TASK_PRI_LOW);
1313
1314   /* Run the protocol */
1315   silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1316 }
1317
1318 /* Finalizes the connection to router. Registers a server task to the
1319    queue so that we can accept new connections. */
1320
1321 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1322 {
1323   SilcProtocol protocol = (SilcProtocol)context;
1324   SilcServerConnAuthInternalContext *ctx =
1325     (SilcServerConnAuthInternalContext *)protocol->context;
1326   SilcServer server = (SilcServer)ctx->server;
1327   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1328   SilcSocketConnection sock = ctx->sock;
1329   SilcServerEntry id_entry = NULL;
1330   SilcBuffer packet;
1331   unsigned char *id_string;
1332   SilcUInt32 id_len;
1333   SilcIDListData idata;
1334   SilcServerConfigRouter *conn = NULL;
1335   SilcServerConfigConnParams *param = NULL;
1336
1337   SILC_LOG_DEBUG(("Start"));
1338
1339   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1340       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1341     /* Error occured during protocol */
1342     silc_free(ctx->dest_id);
1343     sock->protocol = NULL;
1344     silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1345                                   NULL);
1346     sock->protocol = protocol;
1347
1348     /* Try reconnecting if configuration wants it */
1349     if (!sconn->no_reconnect) {
1350       silc_schedule_task_add(server->schedule, 0,
1351                              silc_server_connect_to_router_retry,
1352                              sconn, 0, 1, SILC_TASK_TIMEOUT,
1353                              SILC_TASK_PRI_NORMAL);
1354       goto out2;
1355     }
1356
1357     goto out;
1358   }
1359
1360   /* Add a task to the queue. This task receives new connections to the
1361      server. This task remains on the queue until the end of the program. */
1362   if (!server->listenning && !sconn->backup) {
1363     silc_schedule_task_add(server->schedule, server->sock,
1364                            silc_server_accept_new_connection,
1365                            (void *)server, 0, 0,
1366                            SILC_TASK_FD,
1367                            SILC_TASK_PRI_NORMAL);
1368     server->listenning = TRUE;
1369   }
1370
1371   /* Send NEW_SERVER packet to the router. We will become registered
1372      to the SILC network after sending this packet. */
1373   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1374   id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1375   packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1376   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1377   silc_buffer_format(packet,
1378                      SILC_STR_UI_SHORT(id_len),
1379                      SILC_STR_UI_XNSTRING(id_string, id_len),
1380                      SILC_STR_UI_SHORT(strlen(server->server_name)),
1381                      SILC_STR_UI_XNSTRING(server->server_name,
1382                                           strlen(server->server_name)),
1383                      SILC_STR_END);
1384
1385   /* Send the packet */
1386   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1387                           packet->data, packet->len, TRUE);
1388   silc_buffer_free(packet);
1389   silc_free(id_string);
1390
1391   SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1392
1393   /* Check that we do not have this ID already */
1394   id_entry = silc_idlist_find_server_by_id(server->local_list,
1395                                            ctx->dest_id, TRUE, NULL);
1396   if (id_entry) {
1397     silc_idcache_del_by_context(server->local_list->servers, id_entry);
1398   } else {
1399     id_entry = silc_idlist_find_server_by_id(server->global_list,
1400                                              ctx->dest_id, TRUE, NULL);
1401     if (id_entry)
1402       silc_idcache_del_by_context(server->global_list->servers, id_entry);
1403   }
1404
1405   SILC_LOG_DEBUG(("New server id(%s)",
1406                   silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1407
1408   /* Add the connected router to global server list.  Router is sent
1409      as NULL since it's local to us. */
1410   id_entry = silc_idlist_add_server(server->global_list,
1411                                     strdup(sock->hostname),
1412                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
1413   if (!id_entry) {
1414     silc_free(ctx->dest_id);
1415     SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1416     sock->protocol = NULL;
1417     silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1418                                   NULL);
1419     sock->protocol = protocol;
1420     goto out;
1421   }
1422
1423   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1424   silc_free(sock->user_data);
1425   sock->user_data = (void *)id_entry;
1426   sock->type = SILC_SOCKET_TYPE_ROUTER;
1427   idata = (SilcIDListData)sock->user_data;
1428   idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1429                     SILC_IDLIST_STATUS_LOCAL);
1430
1431   conn = sconn->conn.ref_ptr;
1432   param = &server->config->param;
1433   if (conn && conn->param)
1434     param = conn->param;
1435
1436   /* Perform keepalive. */
1437   silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1438                             silc_server_perform_heartbeat,
1439                             server->schedule);
1440
1441   /* Register re-key timeout */
1442   idata->rekey->timeout = param->key_exchange_rekey;
1443   silc_schedule_task_add(server->schedule, sock->sock,
1444                          silc_server_rekey_callback,
1445                          (void *)sock, idata->rekey->timeout, 0,
1446                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1447
1448   if (!sconn->backup) {
1449     /* Mark this router our primary router if we're still standalone */
1450     if (server->standalone) {
1451       SILC_LOG_DEBUG(("This connection is our primary router"));
1452       server->id_entry->router = id_entry;
1453       server->router = id_entry;
1454       server->router->server_type = SILC_ROUTER;
1455       server->standalone = FALSE;
1456       server->backup_primary = FALSE;
1457
1458       /* Announce data if we are not backup router (unless not as primary
1459          currently).  Backup router announces later at the end of
1460          resuming protocol. */
1461       if (server->backup_router && server->server_type == SILC_ROUTER) {
1462         SILC_LOG_DEBUG(("Announce data after resume protocol"));
1463       } else {
1464         /* If we are router then announce our possible servers.  Backup
1465            router announces also global servers. */
1466         if (server->server_type == SILC_ROUTER)
1467           silc_server_announce_servers(server,
1468                                        server->backup_router ? TRUE : FALSE,
1469                                        0, SILC_PRIMARY_ROUTE(server));
1470
1471         /* Announce our clients and channels to the router */
1472         silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1473         silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1474       }
1475
1476       /* If we are backup router then this primary router is whom we are
1477          backing up. */
1478       if (server->server_type == SILC_BACKUP_ROUTER)
1479         silc_server_backup_add(server, server->id_entry, sock->ip,
1480                                sconn->remote_port, TRUE);
1481     }
1482   } else {
1483     /* Add this server to be our backup router */
1484     id_entry->server_type = SILC_BACKUP_ROUTER;
1485     silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1486                            sconn->backup_replace_port, FALSE);
1487   }
1488
1489   sock->protocol = NULL;
1490
1491  out:
1492   /* Call the completion callback to indicate that we've connected to
1493      the router */
1494   if (sconn && sconn->callback)
1495     (*sconn->callback)(server, id_entry, sconn->callback_context);
1496
1497   /* Free the temporary connection data context */
1498   if (sconn) {
1499     silc_server_config_unref(&sconn->conn);
1500     silc_free(sconn->remote_host);
1501     silc_free(sconn->backup_replace_ip);
1502     silc_free(sconn);
1503   }
1504   if (sconn == server->router_conn)
1505     server->router_conn = NULL;
1506
1507  out2:
1508   /* Free the protocol object */
1509   if (sock->protocol == protocol)
1510     sock->protocol = NULL;
1511   silc_protocol_free(protocol);
1512   if (ctx->packet)
1513     silc_packet_context_free(ctx->packet);
1514   if (ctx->ske)
1515     silc_ske_free(ctx->ske);
1516   if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1517     silc_free(ctx->auth_data);
1518   silc_free(ctx);
1519 }
1520
1521 /* Host lookup callback that is called after the incoming connection's
1522    IP and FQDN lookup is performed. This will actually check the acceptance
1523    of the incoming connection and will register the key exchange protocol
1524    for this connection. */
1525
1526 static void
1527 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1528                                          void *context)
1529 {
1530   SilcServerKEInternalContext *proto_ctx =
1531     (SilcServerKEInternalContext *)context;
1532   SilcServer server = (SilcServer)proto_ctx->server;
1533   SilcServerConfigClient *cconfig = NULL;
1534   SilcServerConfigServer *sconfig = NULL;
1535   SilcServerConfigRouter *rconfig = NULL;
1536   SilcServerConfigDeny *deny;
1537   int port;
1538
1539   /* Check whether we could resolve both IP and FQDN. */
1540   if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1541                     server->config->require_reverse_lookup)) {
1542     SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1543                     sock->hostname ? sock->hostname :
1544                     sock->ip ? sock->ip : ""));
1545     server->stat.conn_failures++;
1546     silc_server_disconnect_remote(server, sock,
1547                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1548                                   "Unknown host or IP");
1549     silc_free(proto_ctx);
1550     return;
1551   }
1552
1553   /* Register the connection for network input and output. This sets
1554      that scheduler will listen for incoming packets for this connection
1555      and sets that outgoing packets may be sent to this connection as well.
1556      However, this doesn't set the scheduler for outgoing traffic, it
1557      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1558      later when outgoing data is available. */
1559   context = (void *)server;
1560   SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1561
1562   SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1563                  sock->ip));
1564
1565   /* Listenning port */
1566   if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1567     silc_server_disconnect_remote(server, sock,
1568                                   SILC_STATUS_ERR_RESOURCE_LIMIT,
1569                                   "Connection refused");
1570     server->stat.conn_failures++;
1571     silc_free(proto_ctx);
1572     return;
1573   }
1574   port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1575
1576   /* Check whether this connection is denied to connect to us. */
1577   deny = silc_server_config_find_denied(server, sock->ip);
1578   if (!deny)
1579     deny = silc_server_config_find_denied(server, sock->hostname);
1580   if (deny) {
1581     /* The connection is denied */
1582     SILC_LOG_INFO(("Connection %s (%s) is denied",
1583                    sock->hostname, sock->ip));
1584     silc_server_disconnect_remote(server, sock,
1585                                   SILC_STATUS_ERR_BANNED_FROM_SERVER,
1586                                   deny->reason);
1587     server->stat.conn_failures++;
1588     silc_free(proto_ctx);
1589     return;
1590   }
1591
1592   /* Check whether we have configured this sort of connection at all. We
1593      have to check all configurations since we don't know what type of
1594      connection this is. */
1595   if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1596     cconfig = silc_server_config_find_client(server, sock->hostname);
1597   if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1598     sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1599   if (server->server_type == SILC_ROUTER) {
1600     if (!(rconfig = silc_server_config_find_router_conn(server,
1601                                                         sock->ip, sock->port)))
1602       rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1603                                                     sock->port);
1604   }
1605   if (!cconfig && !sconfig && !rconfig) {
1606     SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1607                    sock->ip));
1608     silc_server_disconnect_remote(server, sock,
1609                                   SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1610     server->stat.conn_failures++;
1611     silc_free(proto_ctx);
1612     return;
1613   }
1614
1615   /* The connection is allowed */
1616
1617   /* Set internal context for key exchange protocol. This is
1618      sent as context for the protocol. */
1619   proto_ctx->sock = sock;
1620   proto_ctx->rng = server->rng;
1621   proto_ctx->responder = TRUE;
1622   silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1623   silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1624   silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1625
1626   /* Take flags for key exchange. Since we do not know what type of connection
1627      this is, we go through all found configurations and use the global ones
1628      as well. This will result always into strictest key exchange flags. */
1629   SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1630   SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1631   SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1632   if (server->config->param.key_exchange_pfs)
1633     proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1634
1635   /* Prepare the connection for key exchange protocol. We allocate the
1636      protocol but will not start it yet. The connector will be the
1637      initiator of the protocol thus we will wait for initiation from
1638      there before we start the protocol. */
1639   server->stat.auth_attempts++;
1640   SILC_LOG_DEBUG(("Starting key exchange protocol"));
1641   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1642                       &sock->protocol, proto_ctx,
1643                       silc_server_accept_new_connection_second);
1644
1645   /* Register a timeout task that will be executed if the connector
1646      will not start the key exchange protocol within specified timeout
1647      and the connection will be closed. */
1648   proto_ctx->timeout_task =
1649     silc_schedule_task_add(server->schedule, sock->sock,
1650                            silc_server_timeout_remote,
1651                            (void *)server,
1652                            server->config->key_exchange_timeout, 0,
1653                            SILC_TASK_TIMEOUT,
1654                            SILC_TASK_PRI_LOW);
1655 }
1656
1657 /* Accepts new connections to the server. Accepting new connections are
1658    done in three parts to make it async. */
1659
1660 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1661 {
1662   SilcServer server = (SilcServer)context;
1663   SilcSocketConnection newsocket;
1664   SilcServerKEInternalContext *proto_ctx;
1665   int sock;
1666
1667   SILC_LOG_DEBUG(("Accepting new connection"));
1668
1669   server->stat.conn_attempts++;
1670
1671   sock = silc_net_accept_connection(fd);
1672   if (sock < 0) {
1673     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1674     server->stat.conn_failures++;
1675     return;
1676   }
1677
1678   /* Check for maximum allowed connections */
1679   if (sock > server->config->param.connections_max) {
1680     SILC_LOG_ERROR(("Refusing connection, server is full"));
1681     server->stat.conn_failures++;
1682     silc_net_close_connection(sock);
1683     return;
1684   }
1685
1686   /* Set socket options */
1687   silc_net_set_socket_nonblock(sock);
1688   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1689
1690   /* We don't create a ID yet, since we don't know what type of connection
1691      this is yet. But, we do add the connection to the socket table. */
1692   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1693   server->sockets[sock] = newsocket;
1694
1695   /* Perform asynchronous host lookup. This will lookup the IP and the
1696      FQDN of the remote connection. After the lookup is done the connection
1697      is accepted further. */
1698   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1699   proto_ctx->server = server;
1700   proto_ctx->context = (void *)fd;
1701   silc_socket_host_lookup(newsocket, TRUE,
1702                           silc_server_accept_new_connection_lookup,
1703                           (void *)proto_ctx, server->schedule);
1704 }
1705
1706 /* Second part of accepting new connection. Key exchange protocol has been
1707    performed and now it is time to do little connection authentication
1708    protocol to figure out whether this connection is client or server
1709    and whether it has right to access this server (especially server
1710    connections needs to be authenticated). */
1711
1712 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1713 {
1714   SilcProtocol protocol = (SilcProtocol)context;
1715   SilcServerKEInternalContext *ctx =
1716     (SilcServerKEInternalContext *)protocol->context;
1717   SilcServer server = (SilcServer)ctx->server;
1718   SilcSocketConnection sock = ctx->sock;
1719   SilcServerConnAuthInternalContext *proto_ctx;
1720
1721   SILC_LOG_DEBUG(("Start"));
1722
1723   if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1724       (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1725     /* Error occured during protocol */
1726     SILC_LOG_DEBUG(("Error in key exchange protocol"));
1727     silc_protocol_free(protocol);
1728     sock->protocol = NULL;
1729     silc_ske_free_key_material(ctx->keymat);
1730     if (ctx->packet)
1731       silc_packet_context_free(ctx->packet);
1732     if (ctx->ske)
1733       silc_ske_free(ctx->ske);
1734     silc_free(ctx->dest_id);
1735     silc_server_config_unref(&ctx->cconfig);
1736     silc_server_config_unref(&ctx->sconfig);
1737     silc_server_config_unref(&ctx->rconfig);
1738     silc_free(ctx);
1739
1740     if (!SILC_IS_DISCONNECTING(sock)) {
1741       SILC_LOG_INFO(("Key exchange failed for %s:%d [%s]", sock->hostname,
1742                      sock->port,
1743                      (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1744                       sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1745                       sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1746                       "Router")));
1747       silc_server_disconnect_remote(server, sock,
1748                                     SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1749                                     NULL);
1750     }
1751
1752     server->stat.auth_failures++;
1753     return;
1754   }
1755
1756   /* We now have the key material as the result of the key exchange
1757      protocol. Take the key material into use. Free the raw key material
1758      as soon as we've set them into use. */
1759   if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1760                                         ctx->sock, ctx->keymat,
1761                                         ctx->ske->prop->cipher,
1762                                         ctx->ske->prop->pkcs,
1763                                         ctx->ske->prop->hash,
1764                                         ctx->ske->prop->hmac,
1765                                         ctx->ske->prop->group,
1766                                         ctx->responder)) {
1767     SILC_LOG_ERROR(("Error setting key material in use"));
1768     silc_protocol_free(protocol);
1769     sock->protocol = NULL;
1770     silc_ske_free_key_material(ctx->keymat);
1771     if (ctx->packet)
1772       silc_packet_context_free(ctx->packet);
1773     if (ctx->ske)
1774       silc_ske_free(ctx->ske);
1775     silc_free(ctx->dest_id);
1776     silc_server_config_unref(&ctx->cconfig);
1777     silc_server_config_unref(&ctx->sconfig);
1778     silc_server_config_unref(&ctx->rconfig);
1779     silc_free(ctx);
1780     silc_server_disconnect_remote(server, sock,
1781                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1782     server->stat.auth_failures++;
1783     return;
1784   }
1785   silc_ske_free_key_material(ctx->keymat);
1786
1787   /* Allocate internal context for the authentication protocol. This
1788      is sent as context for the protocol. */
1789   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1790   proto_ctx->server = (void *)server;
1791   proto_ctx->sock = sock;
1792   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1793   proto_ctx->responder = TRUE;
1794   proto_ctx->dest_id_type = ctx->dest_id_type;
1795   proto_ctx->dest_id = ctx->dest_id;
1796   proto_ctx->cconfig = ctx->cconfig;
1797   proto_ctx->sconfig = ctx->sconfig;
1798   proto_ctx->rconfig = ctx->rconfig;
1799
1800   /* Free old protocol as it is finished now */
1801   silc_protocol_free(protocol);
1802   if (ctx->packet)
1803     silc_packet_context_free(ctx->packet);
1804   silc_free(ctx);
1805   sock->protocol = NULL;
1806
1807   /* Allocate the authentication protocol. This is allocated here
1808      but we won't start it yet. We will be receiving party of this
1809      protocol thus we will wait that connecting party will make
1810      their first move. */
1811   SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1812   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1813                       &sock->protocol, proto_ctx,
1814                       silc_server_accept_new_connection_final);
1815
1816   /* Register timeout task. If the protocol is not executed inside
1817      this timelimit the connection will be terminated. */
1818   proto_ctx->timeout_task =
1819     silc_schedule_task_add(server->schedule, sock->sock,
1820                            silc_server_timeout_remote,
1821                            (void *)server,
1822                            server->config->conn_auth_timeout, 0,
1823                            SILC_TASK_TIMEOUT,
1824                            SILC_TASK_PRI_LOW);
1825 }
1826
1827 /* After this is called, server don't wait for backup router anymore.
1828    This gets called automatically even after we have backup router
1829    connection established. */
1830
1831 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1832 {
1833   SilcServer server = context;
1834   server->wait_backup = FALSE;
1835 }
1836
1837 /* Final part of accepting new connection. The connection has now
1838    been authenticated and keys has been exchanged. We also know whether
1839    this is client or server connection. */
1840
1841 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1842 {
1843   SilcProtocol protocol = (SilcProtocol)context;
1844   SilcServerConnAuthInternalContext *ctx =
1845     (SilcServerConnAuthInternalContext *)protocol->context;
1846   SilcServer server = (SilcServer)ctx->server;
1847   SilcSocketConnection sock = ctx->sock;
1848   SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1849   void *id_entry;
1850   SilcServerConfigConnParams *param = &server->config->param;
1851
1852   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1853       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1854     /* Error occured during protocol */
1855     SILC_LOG_DEBUG(("Error during authentication protocol"));
1856     silc_protocol_free(protocol);
1857     sock->protocol = NULL;
1858     if (ctx->packet)
1859       silc_packet_context_free(ctx->packet);
1860     if (ctx->ske)
1861       silc_ske_free(ctx->ske);
1862     silc_free(ctx->dest_id);
1863     silc_server_config_unref(&ctx->cconfig);
1864     silc_server_config_unref(&ctx->sconfig);
1865     silc_server_config_unref(&ctx->rconfig);
1866     silc_free(ctx);
1867
1868     if (!SILC_IS_DISCONNECTING(sock)) {
1869       SILC_LOG_INFO(("Authentication failed for %s:%d [%s]", sock->hostname,
1870                      sock->port,
1871                      (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1872                       sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1873                       sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1874                       "Router")));
1875       silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1876                                     NULL);
1877     }
1878     server->stat.auth_failures++;
1879     return;
1880   }
1881
1882   entry->data.last_receive = time(NULL);
1883
1884   switch (ctx->conn_type) {
1885   case SILC_SOCKET_TYPE_CLIENT:
1886     {
1887       SilcClientEntry client;
1888       SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1889
1890       /* Verify whether this connection is after all allowed to connect */
1891       if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1892                                           &server->config->param,
1893                                           conn->param, ctx->ske)) {
1894         server->stat.auth_failures++;
1895         goto out;
1896       }
1897
1898       /* If we are primary router and we have backup router configured
1899          but it has not connected to use yet, do not accept any other
1900          connection. */
1901       if (server->wait_backup && server->server_type == SILC_ROUTER &&
1902           !server->backup_router) {
1903         SilcServerConfigRouter *router;
1904         router = silc_server_config_get_backup_router(server);
1905         if (router && strcmp(server->config->server_info->primary->server_ip,
1906                              sock->ip) &&
1907             silc_server_find_socket_by_host(server,
1908                                             SILC_SOCKET_TYPE_SERVER,
1909                                             router->backup_replace_ip, 0)) {
1910           SILC_LOG_INFO(("Will not accept connections because we do "
1911                          "not have backup router connection established"));
1912           sock->protocol = NULL;
1913           silc_server_disconnect_remote(server, sock,
1914                                         SILC_STATUS_ERR_PERM_DENIED,
1915                                         "We do not have connection to backup "
1916                                         "router established, try later");
1917           silc_free(sock->user_data);
1918           server->stat.auth_failures++;
1919
1920           /* From here on, wait 10 seconds for the backup router to appear. */
1921           silc_schedule_task_add(server->schedule, 0,
1922                                  silc_server_backup_router_wait,
1923                                  (void *)server, 10, 0,
1924                                  SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1925           goto out;
1926         }
1927       }
1928
1929       SILC_LOG_DEBUG(("Remote host is client"));
1930       SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1931                      sock->ip));
1932
1933       /* Add the client to the client ID cache. The nickname and Client ID
1934          and other information is created after we have received NEW_CLIENT
1935          packet from client. */
1936       client = silc_idlist_add_client(server->local_list,
1937                                       NULL, NULL, NULL, NULL, NULL, sock, 0);
1938       if (!client) {
1939         SILC_LOG_ERROR(("Could not add new client to cache"));
1940         silc_free(sock->user_data);
1941         sock->protocol = NULL;
1942         silc_server_disconnect_remote(server, sock,
1943                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
1944         server->stat.auth_failures++;
1945         goto out;
1946       }
1947       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1948
1949       /* Statistics */
1950       server->stat.my_clients++;
1951       server->stat.clients++;
1952       server->stat.cell_clients++;
1953
1954       /* Get connection parameters */
1955       if (conn->param) {
1956         param = conn->param;
1957
1958         if (!param->keepalive_secs)
1959           param->keepalive_secs = server->config->param.keepalive_secs;
1960
1961         if (!param->qos && server->config->param.qos) {
1962           param->qos = server->config->param.qos;
1963           param->qos_rate_limit = server->config->param.qos_rate_limit;
1964           param->qos_bytes_limit = server->config->param.qos_bytes_limit;
1965           param->qos_limit_sec = server->config->param.qos_limit_sec;
1966           param->qos_limit_usec = server->config->param.qos_limit_usec;
1967         }
1968
1969         /* Check if to be anonymous connection */
1970         if (param->anonymous)
1971           client->mode |= SILC_UMODE_ANONYMOUS;
1972       }
1973
1974       /* Add public key to hash list (for whois using attributes) */
1975       silc_hash_table_add(server->pk_hash,
1976                           entry->data.public_key, client);
1977
1978       id_entry = (void *)client;
1979       break;
1980     }
1981   case SILC_SOCKET_TYPE_SERVER:
1982   case SILC_SOCKET_TYPE_ROUTER:
1983     {
1984       SilcServerEntry new_server;
1985       bool initiator = FALSE;
1986       bool backup_local = FALSE;
1987       bool backup_router = FALSE;
1988       char *backup_replace_ip = NULL;
1989       SilcUInt16 backup_replace_port = 0;
1990       SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1991       SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1992
1993       /* If we are backup router and this is incoming server connection
1994          and we do not have connection to primary router, do not allow
1995          the connection. */
1996       if (server->server_type == SILC_BACKUP_ROUTER &&
1997           ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1998           !SILC_PRIMARY_ROUTE(server)) {
1999         SILC_LOG_INFO(("Will not accept server connection because we do "
2000                        "not have primary router connection established"));
2001         sock->protocol = NULL;
2002         silc_server_disconnect_remote(server, sock,
2003                                       SILC_STATUS_ERR_PERM_DENIED,
2004                                       "We do not have connection to primary "
2005                                       "router established, try later");
2006         silc_free(sock->user_data);
2007         server->stat.auth_failures++;
2008         goto out;
2009       }
2010
2011       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2012         /* Verify whether this connection is after all allowed to connect */
2013         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2014                                             &server->config->param,
2015                                             rconn ? rconn->param : NULL,
2016                                             ctx->ske)) {
2017           silc_free(sock->user_data);
2018           server->stat.auth_failures++;
2019           goto out;
2020         }
2021
2022         if (rconn) {
2023           if (rconn->param) {
2024             param = rconn->param;
2025
2026             if (!param->keepalive_secs)
2027               param->keepalive_secs = server->config->param.keepalive_secs;
2028
2029             if (!param->qos && server->config->param.qos) {
2030               param->qos = server->config->param.qos;
2031               param->qos_rate_limit = server->config->param.qos_rate_limit;
2032               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2033               param->qos_limit_sec = server->config->param.qos_limit_sec;
2034               param->qos_limit_usec = server->config->param.qos_limit_usec;
2035             }
2036           }
2037
2038           initiator = rconn->initiator;
2039           backup_local = rconn->backup_local;
2040           backup_router = rconn->backup_router;
2041           backup_replace_ip = rconn->backup_replace_ip;
2042           backup_replace_port = rconn->backup_replace_port;
2043         }
2044       }
2045
2046       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2047         /* Verify whether this connection is after all allowed to connect */
2048         if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
2049                                             &server->config->param,
2050                                             sconn ? sconn->param : NULL,
2051                                             ctx->ske)) {
2052           silc_free(sock->user_data);
2053           server->stat.auth_failures++;
2054           goto out;
2055         }
2056         if (sconn) {
2057           if (sconn->param) {
2058             param = sconn->param;
2059
2060             if (!param->keepalive_secs)
2061               param->keepalive_secs = server->config->param.keepalive_secs;
2062
2063             if (!param->qos && server->config->param.qos) {
2064               param->qos = server->config->param.qos;
2065               param->qos_rate_limit = server->config->param.qos_rate_limit;
2066               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2067               param->qos_limit_sec = server->config->param.qos_limit_sec;
2068               param->qos_limit_usec = server->config->param.qos_limit_usec;
2069             }
2070           }
2071
2072           backup_router = sconn->backup_router;
2073         }
2074       }
2075
2076       /* If we are primary router and we have backup router configured
2077          but it has not connected to use yet, do not accept any other
2078          connection. */
2079       if (server->wait_backup && server->server_type == SILC_ROUTER &&
2080           !server->backup_router && !backup_router) {
2081         SilcServerConfigRouter *router;
2082         router = silc_server_config_get_backup_router(server);
2083         if (router && strcmp(server->config->server_info->primary->server_ip,
2084                              sock->ip) &&
2085             silc_server_find_socket_by_host(server,
2086                                             SILC_SOCKET_TYPE_SERVER,
2087                                             router->backup_replace_ip, 0)) {
2088           SILC_LOG_INFO(("Will not accept connections because we do "
2089                          "not have backup router connection established"));
2090           sock->protocol = NULL;
2091           silc_server_disconnect_remote(server, sock,
2092                                         SILC_STATUS_ERR_PERM_DENIED,
2093                                         "We do not have connection to backup "
2094                                         "router established, try later");
2095           silc_free(sock->user_data);
2096           server->stat.auth_failures++;
2097
2098           /* From here on, wait 10 seconds for the backup router to appear. */
2099           silc_schedule_task_add(server->schedule, 0,
2100                                  silc_server_backup_router_wait,
2101                                  (void *)server, 10, 0,
2102                                  SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2103           goto out;
2104         }
2105       }
2106
2107       SILC_LOG_DEBUG(("Remote host is %s",
2108                       ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2109                       "server" : (backup_router ?
2110                                   "backup router" : "router")));
2111       SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
2112                      sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2113                      "server" : (backup_router ?
2114                                  "backup router" : "router")));
2115
2116       /* Add the server into server cache. The server name and Server ID
2117          is updated after we have received NEW_SERVER packet from the
2118          server. We mark ourselves as router for this server if we really
2119          are router. */
2120       new_server =
2121         silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2122                                 server->local_list : (backup_router ?
2123                                                       server->local_list :
2124                                                       server->global_list)),
2125                                NULL,
2126                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2127                                 SILC_SERVER : SILC_ROUTER),
2128                                NULL,
2129                                (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
2130                                 server->id_entry : (backup_router ?
2131                                                     server->id_entry : NULL)),
2132                                sock);
2133       if (!new_server) {
2134         SILC_LOG_ERROR(("Could not add new server to cache"));
2135         silc_free(sock->user_data);
2136         sock->protocol = NULL;
2137         silc_server_disconnect_remote(server, sock,
2138                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
2139         server->stat.auth_failures++;
2140         goto out;
2141       }
2142       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2143
2144       id_entry = (void *)new_server;
2145
2146       /* If the incoming connection is router and marked as backup router
2147          then add it to be one of our backups */
2148       if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
2149         /* Change it back to SERVER type since that's what it really is. */
2150         if (backup_local)
2151           ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
2152         new_server->server_type = SILC_BACKUP_ROUTER;
2153
2154         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2155                                ("Backup router %s is now online",
2156                                 sock->hostname));
2157
2158         /* Remove the backup waiting with timeout */
2159         silc_schedule_task_add(server->schedule, 0,
2160                                silc_server_backup_router_wait,
2161                                (void *)server, 5, 0,
2162                                SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2163       }
2164
2165       /* Statistics */
2166       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
2167         server->stat.my_servers++;
2168       } else {
2169         server->stat.my_routers++;
2170         server->stat.routers++;
2171       }
2172       server->stat.servers++;
2173
2174       /* Check whether this connection is to be our primary router connection
2175          if we do not already have the primary route. */
2176       if (!backup_router &&
2177           server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
2178         if (silc_server_config_is_primary_route(server) && !initiator)
2179           break;
2180
2181         SILC_LOG_DEBUG(("We are not standalone server anymore"));
2182         server->standalone = FALSE;
2183         if (!server->id_entry->router) {
2184           server->id_entry->router = id_entry;
2185           server->router = id_entry;
2186         }
2187       }
2188
2189       break;
2190     }
2191   default:
2192     goto out;
2193     break;
2194   }
2195
2196   sock->type = ctx->conn_type;
2197
2198   /* Add the common data structure to the ID entry. */
2199   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
2200
2201   /* Add to sockets internal pointer for fast referencing */
2202   silc_free(sock->user_data);
2203   sock->user_data = id_entry;
2204
2205   /* Connection has been fully established now. Everything is ok. */
2206   SILC_LOG_DEBUG(("New connection authenticated"));
2207
2208   /* Perform keepalive. */
2209   if (param->keepalive_secs)
2210     silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2211                               silc_server_perform_heartbeat,
2212                               server->schedule);
2213
2214   /* Perform Quality of Service */
2215   if (param->qos)
2216     silc_socket_set_qos(sock, param->qos_rate_limit, param->qos_bytes_limit,
2217                         param->qos_limit_sec, param->qos_limit_usec,
2218                         server->schedule);
2219
2220  out:
2221   if (sock->protocol == protocol)
2222     silc_protocol_free(protocol);
2223   if (ctx->packet)
2224     silc_packet_context_free(ctx->packet);
2225   if (ctx->ske)
2226     silc_ske_free(ctx->ske);
2227   silc_free(ctx->dest_id);
2228   silc_server_config_unref(&ctx->cconfig);
2229   silc_server_config_unref(&ctx->sconfig);
2230   silc_server_config_unref(&ctx->rconfig);
2231   silc_free(ctx);
2232   sock->protocol = NULL;
2233 }
2234
2235 /* This function is used to read packets from network and send packets to
2236    network. This is usually a generic task. */
2237
2238 SILC_TASK_CALLBACK(silc_server_packet_process)
2239 {
2240   SilcServer server = (SilcServer)context;
2241   SilcSocketConnection sock = server->sockets[fd];
2242   SilcIDListData idata;
2243   SilcCipher cipher = NULL;
2244   SilcHmac hmac = NULL;
2245   SilcUInt32 sequence = 0;
2246   bool local_is_router;
2247   int ret;
2248
2249   if (!sock) {
2250     SILC_LOG_DEBUG(("Unknown socket connection"));
2251     return;
2252   }
2253
2254   /* Packet sending */
2255
2256   if (type == SILC_TASK_WRITE) {
2257     /* Do not send data to disconnected connection */
2258     if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2259       SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2260       SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2261       SILC_UNSET_OUTBUF_PENDING(sock);
2262       silc_buffer_clear(sock->outbuf);
2263       return;
2264     }
2265
2266     server->stat.packets_sent++;
2267
2268     /* Send the packet */
2269     ret = silc_packet_send(sock, TRUE);
2270
2271     /* If returned -2 could not write to connection now, will do
2272        it later. */
2273     if (ret == -2)
2274       return;
2275
2276     /* The packet has been sent and now it is time to set the connection
2277        back to only for input. When there is again some outgoing data
2278        available for this connection it will be set for output as well.
2279        This call clears the output setting and sets it only for input. */
2280     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2281     SILC_UNSET_OUTBUF_PENDING(sock);
2282     silc_buffer_clear(sock->outbuf);
2283
2284     if (ret == -1) {
2285       SILC_LOG_ERROR(("Error sending packet to connection "
2286                       "%s:%d [%s]", sock->hostname, sock->port,
2287                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2288                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2289                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2290                        "Router")));
2291
2292       if (sock->user_data)
2293         silc_server_free_sock_user_data(server, sock, NULL);
2294       SILC_SET_DISCONNECTING(sock);
2295       silc_server_close_connection(server, sock);
2296     }
2297     return;
2298   }
2299
2300   /* Packet receiving */
2301
2302   /* Read some data from connection */
2303   ret = silc_packet_receive(sock);
2304   if (ret < 0) {
2305
2306     if (ret == -1) {
2307       SILC_LOG_ERROR(("Error receiving packet from connection "
2308                       "%s:%d [%s] %s", sock->hostname, sock->port,
2309                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2310                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2311                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2312                        "Router"), strerror(errno)));
2313
2314       if (sock->user_data)
2315         silc_server_free_sock_user_data(server, sock, NULL);
2316       SILC_SET_DISCONNECTING(sock);
2317       silc_server_close_connection(server, sock);
2318     }
2319     return;
2320   }
2321
2322   /* EOF */
2323   if (ret == 0) {
2324     SILC_LOG_DEBUG(("Read EOF"));
2325
2326     /* If connection is disconnecting already we will finally
2327        close the connection */
2328     if (SILC_IS_DISCONNECTING(sock)) {
2329       if (sock->user_data)
2330         silc_server_free_sock_user_data(server, sock, NULL);
2331       silc_server_close_connection(server, sock);
2332       return;
2333     }
2334
2335     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2336
2337     if (sock->user_data) {
2338       char tmp[128];
2339
2340       /* If backup disconnected then mark that resuming willl not be allowed */
2341       if (server->server_type == SILC_ROUTER && !server->backup_router &&
2342           sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2343         SilcServerEntry server_entry = sock->user_data;
2344         if (server_entry->server_type == SILC_BACKUP_ROUTER)
2345           server->backup_closed = TRUE;
2346       }
2347
2348       if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2349         silc_server_free_sock_user_data(server, sock, tmp);
2350       else
2351         silc_server_free_sock_user_data(server, sock, NULL);
2352     } else if (server->router_conn && server->router_conn->sock == sock &&
2353                !server->router && server->standalone) {
2354       silc_server_create_connections(server);
2355     }
2356
2357     SILC_SET_DISCONNECTING(sock);
2358     silc_server_close_connection(server, sock);
2359     return;
2360   }
2361
2362   /* If connection is disconnecting or disconnected we will ignore
2363      what we read. */
2364   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2365     SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2366     return;
2367   }
2368
2369   /* Get keys and stuff from ID entry */
2370   idata = (SilcIDListData)sock->user_data;
2371   if (idata) {
2372     cipher = idata->receive_key;
2373     hmac = idata->hmac_receive;
2374     sequence = idata->psn_receive;
2375   }
2376
2377   /* Then, process the packet. This will call the parser that will then
2378      decrypt and parse the packet. */
2379
2380   local_is_router = (server->server_type == SILC_ROUTER);
2381
2382   /* If socket connection is our primary, we are backup and we are doing
2383      backup resuming, we won't process the packet as being a router
2384      (affects channel message decryption). */
2385   if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2386       SILC_PRIMARY_ROUTE(server) == sock)
2387     local_is_router = FALSE;
2388
2389   ret = silc_packet_receive_process(sock, local_is_router,
2390                                     cipher, hmac, sequence,
2391                                     silc_server_packet_parse, server);
2392
2393   /* If processing failed the connection is closed. */
2394   if (!ret) {
2395     /* On packet processing errors we may close our primary router
2396        connection but won't become primary router if we are the backup
2397        since this is local error condition. */
2398     if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2399       server->backup_noswitch = TRUE;
2400
2401     if (sock->user_data)
2402       silc_server_free_sock_user_data(server, sock, NULL);
2403     SILC_SET_DISCONNECTING(sock);
2404     silc_server_close_connection(server, sock);
2405   }
2406 }
2407
2408 /* Parses whole packet, received earlier. */
2409
2410 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2411 {
2412   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2413   SilcServer server = (SilcServer)parse_ctx->context;
2414   SilcSocketConnection sock = parse_ctx->sock;
2415   SilcPacketContext *packet = parse_ctx->packet;
2416   SilcIDListData idata = (SilcIDListData)sock->user_data;
2417   int ret;
2418
2419   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2420     SILC_LOG_DEBUG(("Connection is disconnected"));
2421     goto out;
2422   }
2423
2424   server->stat.packets_received++;
2425
2426   /* Parse the packet */
2427   if (parse_ctx->normal)
2428     ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2429   else
2430     ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2431
2432   /* If entry is disabled ignore what we got. */
2433   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2434       ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2435       ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2436     SILC_LOG_DEBUG(("Connection is disabled"));
2437     goto out;
2438   }
2439
2440   if (ret == SILC_PACKET_NONE) {
2441     SILC_LOG_DEBUG(("Error parsing packet"));
2442     goto out;
2443   }
2444
2445   /* Check that the the current client ID is same as in the client's packet. */
2446   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2447     SilcClientEntry client = (SilcClientEntry)sock->user_data;
2448     if (client && client->id && packet->src_id) {
2449       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2450                                 packet->src_id_type);
2451       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2452         silc_free(id);
2453         SILC_LOG_DEBUG(("Packet source is not same as sender"));
2454         goto out;
2455       }
2456       silc_free(id);
2457     }
2458   }
2459
2460   if (server->server_type == SILC_ROUTER) {
2461     /* Route the packet if it is not destined to us. Other ID types but
2462        server are handled separately after processing them. */
2463     if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2464         packet->dst_id_type == SILC_ID_SERVER &&
2465         sock->type != SILC_SOCKET_TYPE_CLIENT &&
2466         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2467
2468       /* Route the packet to fastest route for the destination ID */
2469       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2470                                 packet->dst_id_type);
2471       if (!id)
2472         goto out;
2473       silc_server_packet_route(server,
2474                                silc_server_route_get(server, id,
2475                                                      packet->dst_id_type),
2476                                packet);
2477       silc_free(id);
2478       goto out;
2479     }
2480   }
2481
2482   /* Parse the incoming packet type */
2483   silc_server_packet_parse_type(server, sock, packet);
2484
2485   /* Broadcast packet if it is marked as broadcast packet and it is
2486      originated from router and we are router. */
2487   if (server->server_type == SILC_ROUTER &&
2488       sock->type == SILC_SOCKET_TYPE_ROUTER &&
2489       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2490     /* Broadcast to our primary route */
2491     silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2492
2493     /* If we have backup routers then we need to feed all broadcast
2494        data to those servers. */
2495     silc_server_backup_broadcast(server, sock, packet);
2496   }
2497
2498  out:
2499   silc_packet_context_free(packet);
2500   silc_free(parse_ctx);
2501 }
2502
2503 /* Parser callback called by silc_packet_receive_process. This merely
2504    registers timeout that will handle the actual parsing when appropriate. */
2505
2506 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2507                               void *context)
2508 {
2509   SilcServer server = (SilcServer)context;
2510   SilcSocketConnection sock = parser_context->sock;
2511   SilcIDListData idata = (SilcIDListData)sock->user_data;
2512   bool ret;
2513
2514   if (idata)
2515     idata->psn_receive = parser_context->packet->sequence + 1;
2516
2517   /* If protocol for this connection is key exchange or rekey then we'll
2518      process all packets synchronously, since there might be packets in
2519      queue that we are not able to decrypt without first processing the
2520      packets before them. */
2521   if (sock->protocol && sock->protocol->protocol &&
2522       (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2523        sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2524     silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2525                                   parser_context);
2526
2527     if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2528       SILC_LOG_DEBUG(("Connection is disconnected"));
2529       return FALSE;
2530     }
2531
2532     /* Reprocess data since we'll return FALSE here.  This is because
2533        the idata->receive_key might have become valid in the last packet
2534        and we want to call this processor with valid cipher. */
2535     if (idata)
2536       ret = silc_packet_receive_process(
2537                                   sock, server->server_type == SILC_ROUTER,
2538                                   idata->receive_key,
2539                                   idata->hmac_receive, idata->psn_receive,
2540                                   silc_server_packet_parse, server);
2541     else
2542       ret = silc_packet_receive_process(
2543                                   sock, server->server_type == SILC_ROUTER,
2544                                   NULL, NULL, 0,
2545                                   silc_server_packet_parse, server);
2546
2547     if (!ret) {
2548       /* On packet processing errors we may close our primary router
2549          connection but won't become primary router if we are the backup
2550          since this is local error condition. */
2551       if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2552         server->backup_noswitch = TRUE;
2553
2554       if (sock->user_data)
2555         silc_server_free_sock_user_data(server, sock, NULL);
2556       SILC_SET_DISCONNECTING(sock);
2557       silc_server_close_connection(server, sock);
2558     }
2559
2560     return FALSE;
2561   }
2562
2563   switch (sock->type) {
2564   case SILC_SOCKET_TYPE_UNKNOWN:
2565   case SILC_SOCKET_TYPE_CLIENT:
2566     /* Parse the packet with timeout */
2567     silc_schedule_task_add(server->schedule, sock->sock,
2568                            silc_server_packet_parse_real,
2569                            (void *)parser_context, 0, 100000,
2570                            SILC_TASK_TIMEOUT,
2571                            SILC_TASK_PRI_NORMAL);
2572     break;
2573   case SILC_SOCKET_TYPE_SERVER:
2574   case SILC_SOCKET_TYPE_ROUTER:
2575     /* Packets from servers are parsed immediately */
2576     silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2577                                   parser_context);
2578     break;
2579   }
2580
2581   return TRUE;
2582 }
2583
2584 /* Parses the packet type and calls what ever routines the packet type
2585    requires. This is done for all incoming packets. */
2586
2587 void silc_server_packet_parse_type(SilcServer server,
2588                                    SilcSocketConnection sock,
2589                                    SilcPacketContext *packet)
2590 {
2591   SilcPacketType type = packet->type;
2592   SilcIDListData idata = (SilcIDListData)sock->user_data;
2593
2594   SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2595                   silc_get_packet_name(type), packet->flags));
2596
2597   /* Parse the packet type */
2598   switch (type) {
2599   case SILC_PACKET_DISCONNECT:
2600     {
2601       SilcStatus status;
2602       char *message = NULL;
2603
2604       if (packet->flags & SILC_PACKET_FLAG_LIST)
2605         break;
2606       if (packet->buffer->len < 1)
2607         break;
2608
2609       status = (SilcStatus)packet->buffer->data[0];
2610       if (packet->buffer->len > 1 &&
2611           silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2612         message = silc_memdup(packet->buffer->data + 1,
2613                               packet->buffer->len - 1);
2614
2615       SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2616                      sock->ip, sock->hostname,
2617                      silc_get_status_message(status), status,
2618                      message ? message : ""));
2619       silc_free(message);
2620
2621       /* Do not switch to backup in case of error */
2622       server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2623
2624       /* If backup disconnected then mark that resuming willl not be allowed */
2625       if (server->server_type == SILC_ROUTER && !server->backup_router &&
2626           sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2627         SilcServerEntry server_entry = sock->user_data;
2628         if (server_entry->server_type == SILC_BACKUP_ROUTER)
2629           server->backup_closed = TRUE;
2630       }
2631
2632       /* Handle the disconnection from our end too */
2633       if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2634         silc_server_free_sock_user_data(server, sock, NULL);
2635       SILC_SET_DISCONNECTING(sock);
2636       silc_server_close_connection(server, sock);
2637       server->backup_noswitch = FALSE;
2638     }
2639     break;
2640
2641   case SILC_PACKET_SUCCESS:
2642     /*
2643      * Success received for something. For now we can have only
2644      * one protocol for connection executing at once hence this
2645      * success message is for whatever protocol is executing currently.
2646      */
2647     if (packet->flags & SILC_PACKET_FLAG_LIST)
2648       break;
2649     if (sock->protocol)
2650       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2651     break;
2652
2653   case SILC_PACKET_FAILURE:
2654     /*
2655      * Failure received for something. For now we can have only
2656      * one protocol for connection executing at once hence this
2657      * failure message is for whatever protocol is executing currently.
2658      */
2659     if (packet->flags & SILC_PACKET_FLAG_LIST)
2660       break;
2661
2662     /* Check for failure START_USE from backup router */
2663     if (server->server_type == SILC_SERVER &&
2664         server->backup_primary && packet->buffer->len == 4) {
2665       SilcUInt32 type;
2666       SILC_GET32_MSB(type, packet->buffer->data);
2667       if (type == SILC_SERVER_BACKUP_START_USE) {
2668         /* Attempt to reconnect to primary */
2669         SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2670
2671         /* Default action is to disconnect from backup and reconnect to
2672            primary.  Since this failure can happen during switching to
2673            backup (backup might have not noticed the primary going down yet),
2674            we will wait a while and keep sending START_USE to backup.
2675            Only after that we'll give up. */
2676         if (server->router == sock->user_data &&
2677             (time(0) - server->router_connect) < 30) {
2678           SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2679           silc_server_backup_send_start_use(server, sock, FALSE);
2680           break;
2681         }
2682
2683         /* If backup is our primary, disconnect now. */
2684         if (server->router == sock->user_data) {
2685           if (sock->user_data)
2686             silc_server_free_sock_user_data(server, sock, NULL);
2687           SILC_SET_DISCONNECTING(sock);
2688           silc_server_close_connection(server, sock);
2689         }
2690
2691         /* Reconnect */
2692         silc_server_create_connections(server);
2693       }
2694     }
2695
2696     /* Execute protocol */
2697     if (sock->protocol) {
2698       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2699       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2700       break;
2701     }
2702     break;
2703
2704   case SILC_PACKET_REJECT:
2705     if (packet->flags & SILC_PACKET_FLAG_LIST)
2706       break;
2707     return;
2708     break;
2709
2710   case SILC_PACKET_NOTIFY:
2711     /*
2712      * Received notify packet. Server can receive notify packets from
2713      * router. Server then relays the notify messages to clients if needed.
2714      */
2715     if (packet->flags & SILC_PACKET_FLAG_LIST)
2716       silc_server_notify_list(server, sock, packet);
2717     else
2718       silc_server_notify(server, sock, packet);
2719     break;
2720
2721     /*
2722      * Channel packets
2723      */
2724   case SILC_PACKET_CHANNEL_MESSAGE:
2725     /*
2726      * Received channel message. Channel messages are special packets
2727      * (although probably most common ones) thus they are handled
2728      * specially.
2729      */
2730     if (packet->flags & SILC_PACKET_FLAG_LIST)
2731       break;
2732     idata->last_receive = time(NULL);
2733     silc_server_channel_message(server, sock, packet);
2734     break;
2735
2736   case SILC_PACKET_CHANNEL_KEY:
2737     /*
2738      * Received key for channel. As channels are created by the router
2739      * the keys are as well. We will distribute the key to all of our
2740      * locally connected clients on the particular channel. Router
2741      * never receives this channel and thus is ignored.
2742      */
2743     if (packet->flags & SILC_PACKET_FLAG_LIST)
2744       break;
2745     silc_server_channel_key(server, sock, packet);
2746     break;
2747
2748     /*
2749      * Command packets
2750      */
2751   case SILC_PACKET_COMMAND:
2752     /*
2753      * Recived command. Processes the command request and allocates the
2754      * command context and calls the command.
2755      */
2756     if (packet->flags & SILC_PACKET_FLAG_LIST)
2757       break;
2758     silc_server_command_process(server, sock, packet);
2759     break;
2760
2761   case SILC_PACKET_COMMAND_REPLY:
2762     /*
2763      * Received command reply packet. Received command reply to command. It
2764      * may be reply to command sent by us or reply to command sent by client
2765      * that we've routed further.
2766      */
2767     if (packet->flags & SILC_PACKET_FLAG_LIST)
2768       break;
2769     silc_server_command_reply(server, sock, packet);
2770     break;
2771
2772     /*
2773      * Private Message packets
2774      */
2775   case SILC_PACKET_PRIVATE_MESSAGE:
2776     /*
2777      * Received private message packet. The packet is coming from either
2778      * client or server.
2779      */
2780     if (packet->flags & SILC_PACKET_FLAG_LIST)
2781       break;
2782     idata->last_receive = time(NULL);
2783     silc_server_private_message(server, sock, packet);
2784     break;
2785
2786   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2787     /*
2788      * Private message key packet.
2789      */
2790     if (packet->flags & SILC_PACKET_FLAG_LIST)
2791       break;
2792     silc_server_private_message_key(server, sock, packet);
2793     break;
2794
2795     /*
2796      * Key Exchange protocol packets
2797      */
2798   case SILC_PACKET_KEY_EXCHANGE:
2799     if (packet->flags & SILC_PACKET_FLAG_LIST)
2800       break;
2801
2802     if (sock->protocol && sock->protocol->protocol &&
2803         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2804       SilcServerKEInternalContext *proto_ctx =
2805         (SilcServerKEInternalContext *)sock->protocol->context;
2806
2807       proto_ctx->packet = silc_packet_context_dup(packet);
2808
2809       /* Let the protocol handle the packet */
2810       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2811     } else {
2812       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2813                       "protocol active (%s:%d [%s]).", sock->hostname,
2814                       sock->port,
2815                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2816                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2817                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2818                        "Router")));
2819     }
2820     break;
2821
2822   case SILC_PACKET_KEY_EXCHANGE_1:
2823     if (packet->flags & SILC_PACKET_FLAG_LIST)
2824       break;
2825
2826     if (sock->protocol && sock->protocol->protocol &&
2827         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2828          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2829
2830       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2831         SilcServerRekeyInternalContext *proto_ctx =
2832           (SilcServerRekeyInternalContext *)sock->protocol->context;
2833
2834         if (proto_ctx->packet)
2835           silc_packet_context_free(proto_ctx->packet);
2836
2837         proto_ctx->packet = silc_packet_context_dup(packet);
2838
2839         /* Let the protocol handle the packet */
2840         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2841       } else {
2842         SilcServerKEInternalContext *proto_ctx =
2843           (SilcServerKEInternalContext *)sock->protocol->context;
2844
2845         if (proto_ctx->packet)
2846           silc_packet_context_free(proto_ctx->packet);
2847
2848         proto_ctx->packet = silc_packet_context_dup(packet);
2849         proto_ctx->dest_id_type = packet->src_id_type;
2850         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2851                                             packet->src_id_type);
2852         if (!proto_ctx->dest_id)
2853           break;
2854
2855         /* Let the protocol handle the packet */
2856         silc_protocol_execute(sock->protocol, server->schedule,
2857                               0, 100000);
2858       }
2859     } else {
2860       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2861                       "protocol active (%s:%d [%s]).", sock->hostname,
2862                       sock->port,
2863                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2864                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2865                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2866                        "Router")));
2867     }
2868     break;
2869
2870   case SILC_PACKET_KEY_EXCHANGE_2:
2871     if (packet->flags & SILC_PACKET_FLAG_LIST)
2872       break;
2873
2874     if (sock->protocol && sock->protocol->protocol &&
2875         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2876          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2877
2878       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2879         SilcServerRekeyInternalContext *proto_ctx =
2880           (SilcServerRekeyInternalContext *)sock->protocol->context;
2881
2882         if (proto_ctx->packet)
2883           silc_packet_context_free(proto_ctx->packet);
2884
2885         proto_ctx->packet = silc_packet_context_dup(packet);
2886
2887         /* Let the protocol handle the packet */
2888         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2889       } else {
2890         SilcServerKEInternalContext *proto_ctx =
2891           (SilcServerKEInternalContext *)sock->protocol->context;
2892
2893         if (proto_ctx->packet)
2894           silc_packet_context_free(proto_ctx->packet);
2895
2896         proto_ctx->packet = silc_packet_context_dup(packet);
2897         proto_ctx->dest_id_type = packet->src_id_type;
2898         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2899                                             packet->src_id_type);
2900         if (!proto_ctx->dest_id)
2901           break;
2902
2903         /* Let the protocol handle the packet */
2904         silc_protocol_execute(sock->protocol, server->schedule,
2905                               0, 100000);
2906       }
2907     } else {
2908       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2909                       "protocol active (%s:%d [%s]).", sock->hostname,
2910                       sock->port,
2911                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2912                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2913                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2914                        "Router")));
2915     }
2916     break;
2917
2918   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2919     /*
2920      * Connection authentication request packet. When we receive this packet
2921      * we will send to the other end information about our mandatory
2922      * authentication method for the connection. This packet maybe received
2923      * at any time.
2924      */
2925     if (packet->flags & SILC_PACKET_FLAG_LIST)
2926       break;
2927     silc_server_connection_auth_request(server, sock, packet);
2928     break;
2929
2930     /*
2931      * Connection Authentication protocol packets
2932      */
2933   case SILC_PACKET_CONNECTION_AUTH:
2934     /* Start of the authentication protocol. We receive here the
2935        authentication data and will verify it. */
2936     if (packet->flags & SILC_PACKET_FLAG_LIST)
2937       break;
2938
2939     if (sock->protocol && sock->protocol->protocol->type
2940         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2941
2942       SilcServerConnAuthInternalContext *proto_ctx =
2943         (SilcServerConnAuthInternalContext *)sock->protocol->context;
2944
2945       proto_ctx->packet = silc_packet_context_dup(packet);
2946
2947       /* Let the protocol handle the packet */
2948       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2949     } else {
2950       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2951                       "protocol active (%s:%d [%s]).", sock->hostname,
2952                       sock->port,
2953                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2954                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2955                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2956                        "Router")));
2957     }
2958     break;
2959
2960   case SILC_PACKET_NEW_ID:
2961     /*
2962      * Received New ID packet. This includes some new ID that has been
2963      * created. It may be for client, server or channel. This is the way
2964      * to distribute information about new registered entities in the
2965      * SILC network.
2966      */
2967     if (packet->flags & SILC_PACKET_FLAG_LIST)
2968       silc_server_new_id_list(server, sock, packet);
2969     else
2970       silc_server_new_id(server, sock, packet);
2971     break;
2972
2973   case SILC_PACKET_NEW_CLIENT:
2974     /*
2975      * Received new client packet. This includes client information that
2976      * we will use to create initial client ID. After creating new
2977      * ID we will send it to the client.
2978      */
2979     if (packet->flags & SILC_PACKET_FLAG_LIST)
2980       break;
2981     silc_server_new_client(server, sock, packet);
2982     break;
2983
2984   case SILC_PACKET_NEW_SERVER:
2985     /*
2986      * Received new server packet. This includes Server ID and some other
2987      * information that we may save. This is received after server has
2988      * connected to us.
2989      */
2990     if (packet->flags & SILC_PACKET_FLAG_LIST)
2991       break;
2992     silc_server_new_server(server, sock, packet);
2993     break;
2994
2995   case SILC_PACKET_NEW_CHANNEL:
2996     /*
2997      * Received new channel packet. Information about new channel in the
2998      * network are distributed using this packet.
2999      */
3000     if (packet->flags & SILC_PACKET_FLAG_LIST)
3001       silc_server_new_channel_list(server, sock, packet);
3002     else
3003       silc_server_new_channel(server, sock, packet);
3004     break;
3005
3006   case SILC_PACKET_HEARTBEAT:
3007     /*
3008      * Received heartbeat.
3009      */
3010     if (packet->flags & SILC_PACKET_FLAG_LIST)
3011       break;
3012     break;
3013
3014   case SILC_PACKET_KEY_AGREEMENT:
3015     /*
3016      * Received heartbeat.
3017      */
3018     if (packet->flags & SILC_PACKET_FLAG_LIST)
3019       break;
3020     silc_server_key_agreement(server, sock, packet);
3021     break;
3022
3023   case SILC_PACKET_REKEY:
3024     /*
3025      * Received re-key packet. The sender wants to regenerate the session
3026      * keys.
3027      */
3028     if (packet->flags & SILC_PACKET_FLAG_LIST)
3029       break;
3030     silc_server_rekey(server, sock, packet);
3031     break;
3032
3033   case SILC_PACKET_REKEY_DONE:
3034     /*
3035      * The re-key is done.
3036      */
3037     if (packet->flags & SILC_PACKET_FLAG_LIST)
3038       break;
3039
3040     if (sock->protocol && sock->protocol->protocol &&
3041         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3042
3043       SilcServerRekeyInternalContext *proto_ctx =
3044         (SilcServerRekeyInternalContext *)sock->protocol->context;
3045
3046       if (proto_ctx->packet)
3047         silc_packet_context_free(proto_ctx->packet);
3048
3049       proto_ctx->packet = silc_packet_context_dup(packet);
3050
3051       /* Let the protocol handle the packet */
3052       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3053     } else {
3054       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3055                       "protocol active (%s:%d [%s]).", sock->hostname,
3056                       sock->port,
3057                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3058                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3059                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3060                        "Router")));
3061     }
3062     break;
3063
3064   case SILC_PACKET_FTP:
3065     /* FTP packet */
3066     if (packet->flags & SILC_PACKET_FLAG_LIST)
3067       break;
3068     silc_server_ftp(server, sock, packet);
3069     break;
3070
3071   case SILC_PACKET_RESUME_CLIENT:
3072     /* Resume client */
3073     if (packet->flags & SILC_PACKET_FLAG_LIST)
3074       break;
3075     silc_server_resume_client(server, sock, packet);
3076     break;
3077
3078   case SILC_PACKET_RESUME_ROUTER:
3079     /* Resume router packet received. This packet is received for backup
3080        router resuming protocol. */
3081     if (packet->flags & SILC_PACKET_FLAG_LIST)
3082       break;
3083     silc_server_backup_resume_router(server, sock, packet);
3084     break;
3085
3086   default:
3087     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3088     break;
3089   }
3090 }
3091
3092 /* Creates connection to a remote router. */
3093
3094 void silc_server_create_connection(SilcServer server,
3095                                    const char *remote_host, SilcUInt32 port)
3096 {
3097   SilcServerConnection sconn;
3098
3099   /* Allocate connection object for hold connection specific stuff. */
3100   sconn = silc_calloc(1, sizeof(*sconn));
3101   sconn->remote_host = strdup(remote_host);
3102   sconn->remote_port = port;
3103   sconn->no_reconnect = TRUE;
3104
3105   silc_schedule_task_add(server->schedule, 0,
3106                          silc_server_connect_router,
3107                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3108                          SILC_TASK_PRI_NORMAL);
3109 }
3110
3111 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3112 {
3113   SilcServer server = app_context;
3114   SilcSocketConnection sock = context;
3115
3116   SILC_LOG_DEBUG(("Deleting socket %p", sock));
3117
3118   /* Close the actual connection */
3119   silc_net_close_connection(sock->sock);
3120   server->sockets[sock->sock] = NULL;
3121
3122   /* We won't listen for this connection anymore */
3123   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3124   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3125
3126   silc_socket_free(sock);
3127 }
3128
3129 /* Closes connection to socket connection */
3130
3131 void silc_server_close_connection(SilcServer server,
3132                                   SilcSocketConnection sock)
3133 {
3134   char tmp[128];
3135
3136   if (SILC_IS_DISCONNECTED(sock)) {
3137     silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3138     silc_schedule_task_add(server->schedule, sock->sock,
3139                            silc_server_close_connection_final,
3140                            (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3141                            SILC_TASK_PRI_NORMAL);
3142     server->sockets[sock->sock] = NULL;
3143     return;
3144   }
3145
3146   /* If any protocol is active cancel its execution. It will call
3147      the final callback which will finalize the disconnection. */
3148   if (sock->protocol && sock->protocol->protocol &&
3149       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3150     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3151     silc_protocol_cancel(sock->protocol, server->schedule);
3152     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3153     silc_protocol_execute_final(sock->protocol, server->schedule);
3154     sock->protocol = NULL;
3155     return;
3156   }
3157
3158   memset(tmp, 0, sizeof(tmp));
3159   silc_socket_get_error(sock, tmp, sizeof(tmp));
3160   SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3161                  sock->port,
3162                  (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3163                   sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3164                   sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3165                   "Router"), tmp[0] ? tmp : ""));
3166
3167   SILC_SET_DISCONNECTED(sock);
3168   silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3169   silc_schedule_task_add(server->schedule, sock->sock,
3170                          silc_server_close_connection_final,
3171                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3172                          SILC_TASK_PRI_NORMAL);
3173   server->sockets[sock->sock] = NULL;
3174 }
3175
3176 /* Sends disconnect message to remote connection and disconnects the
3177    connection.  NOTE: If this is called from protocol callback
3178    then sock->protocol must be set NULL before calling this, since
3179    this routine dispatches protocol callbacks too. */
3180
3181 void silc_server_disconnect_remote(SilcServer server,
3182                                    SilcSocketConnection sock,
3183                                    SilcStatus status, ...)
3184 {
3185   va_list ap;
3186   unsigned char buf[512];
3187   SilcBuffer buffer;
3188   char *cp;
3189   int len;
3190
3191   if (!sock)
3192     return;
3193
3194   if (SILC_IS_DISCONNECTING(sock)) {
3195     SILC_SET_DISCONNECTED(sock);
3196     silc_server_close_connection(server, sock);
3197     return;
3198   }
3199
3200   memset(buf, 0, sizeof(buf));
3201   va_start(ap, status);
3202   cp = va_arg(ap, char *);
3203   if (cp) {
3204     vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3205     cp = buf;
3206   }
3207   va_end(ap);
3208
3209   SILC_LOG_DEBUG(("Disconnecting remote host"));
3210
3211   /* Notify remote end that the conversation is over. The notify message
3212      is tried to be sent immediately. */
3213
3214   len = 1;
3215   if (cp)
3216     len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3217
3218   buffer = silc_buffer_alloc_size(len);
3219   if (!buffer)
3220     goto out;
3221
3222   buffer->data[0] = status;
3223   if (cp)
3224     silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3225                      buffer->len - 1);
3226   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3227                           buffer->data, buffer->len, TRUE);
3228   silc_buffer_free(buffer);
3229
3230  out:
3231   silc_server_packet_queue_purge(server, sock);
3232
3233   /* Mark the connection to be disconnected */
3234   SILC_SET_DISCONNECTING(sock);
3235   silc_server_close_connection(server, sock);
3236 }
3237
3238 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3239 {
3240   SilcServer server = app_context;
3241   SilcClientEntry client = context;
3242
3243   assert(!silc_hash_table_count(client->channels));
3244
3245   silc_idlist_del_data(client);
3246   silc_idcache_purge_by_context(server->local_list->clients, client);
3247 }
3248
3249 /* Frees client data and notifies about client's signoff. */
3250
3251 void silc_server_free_client_data(SilcServer server,
3252                                   SilcSocketConnection sock,
3253                                   SilcClientEntry client,
3254                                   int notify,
3255                                   const char *signoff)
3256 {
3257   SILC_LOG_DEBUG(("Freeing client data"));
3258
3259   /* If there is pending outgoing data for the client then purge it
3260      to the network before removing the client entry. */
3261   silc_server_packet_queue_purge(server, sock);
3262
3263   if (client->id) {
3264     /* Check if anyone is watching this nickname */
3265     if (server->server_type == SILC_ROUTER)
3266       silc_server_check_watcher_list(server, client, NULL,
3267                                      SILC_NOTIFY_TYPE_SIGNOFF);
3268
3269     /* Send SIGNOFF notify to routers. */
3270     if (notify)
3271       silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3272                                       SILC_BROADCAST(server), client->id,
3273                                       signoff);
3274   }
3275
3276   /* Remove client from all channels */
3277   if (notify)
3278     silc_server_remove_from_channels(server, NULL, client,
3279                                      TRUE, (char *)signoff, TRUE, FALSE);
3280   else
3281     silc_server_remove_from_channels(server, NULL, client,
3282                                      FALSE, NULL, FALSE, FALSE);
3283
3284   /* Remove this client from watcher list if it is */
3285   silc_server_del_from_watcher_list(server, client);
3286
3287   /* Remove this client from the public key hash list */
3288   if (client->data.public_key)
3289     silc_hash_table_del_by_context(server->pk_hash,
3290                                    client->data.public_key, client);
3291
3292   /* Update statistics */
3293   server->stat.my_clients--;
3294   server->stat.clients--;
3295   if (server->stat.cell_clients)
3296     server->stat.cell_clients--;
3297   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3298   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3299   silc_schedule_task_del_by_context(server->schedule, client);
3300
3301   /* We will not delete the client entry right away. We will take it
3302      into history (for WHOWAS command) for 5 minutes, unless we're
3303      shutting down server. */
3304   if (!server->server_shutdown) {
3305     silc_schedule_task_add(server->schedule, 0,
3306                            silc_server_free_client_data_timeout,
3307                            client, 300, 0,
3308                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3309     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3310     client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3311     client->mode = 0;
3312     client->router = NULL;
3313     client->connection = NULL;
3314   } else {
3315     /* Delete directly since we're shutting down server */
3316     silc_idlist_del_data(client);
3317     silc_idlist_del_client(server->local_list, client);
3318   }
3319 }
3320
3321 /* Frees user_data pointer from socket connection object. This also sends
3322    appropriate notify packets to the network to inform about leaving
3323    entities. */
3324
3325 void silc_server_free_sock_user_data(SilcServer server,
3326                                      SilcSocketConnection sock,
3327                                      const char *signoff_message)
3328 {
3329
3330   /* If any protocol is active cancel its execution */
3331   if (sock->protocol && sock->protocol->protocol &&
3332       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3333     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3334     silc_protocol_cancel(sock->protocol, server->schedule);
3335     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3336     silc_protocol_execute_final(sock->protocol, server->schedule);
3337     sock->protocol = NULL;
3338   }
3339
3340   switch (sock->type) {
3341   case SILC_SOCKET_TYPE_CLIENT:
3342     {
3343       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3344       silc_server_free_client_data(server, sock, user_data, TRUE,
3345                                    signoff_message);
3346       break;
3347     }
3348   case SILC_SOCKET_TYPE_SERVER:
3349   case SILC_SOCKET_TYPE_ROUTER:
3350     {
3351       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3352       SilcServerEntry backup_router = NULL;
3353
3354       SILC_LOG_DEBUG(("Freeing server data"));
3355
3356       if (user_data->id)
3357         backup_router = silc_server_backup_get(server, user_data->id);
3358
3359       if (!server->backup_router && server->server_type == SILC_ROUTER &&
3360           backup_router == server->id_entry &&
3361           sock->type != SILC_SOCKET_TYPE_ROUTER)
3362         backup_router = NULL;
3363
3364       if (server->server_shutdown || server->backup_noswitch)
3365         backup_router = NULL;
3366
3367       /* If this was our primary router connection then we're lost to
3368          the outside world. */
3369       if (server->router == user_data) {
3370         /* Check whether we have a backup router connection */
3371         if (!backup_router || backup_router == user_data) {
3372           if (!server->no_reconnect)
3373             silc_server_create_connections(server);
3374           server->id_entry->router = NULL;
3375           server->router = NULL;
3376           server->standalone = TRUE;
3377           server->backup_primary = FALSE;
3378           backup_router = NULL;
3379         } else {
3380           if (server->id_entry != backup_router) {
3381             SILC_LOG_INFO(("New primary router is backup router %s",
3382                            backup_router->server_name));
3383             server->id_entry->router = backup_router;
3384             server->router = backup_router;
3385             server->router_connect = time(0);
3386             server->backup_primary = TRUE;
3387             backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3388
3389             /* Send START_USE to backup router to indicate we have switched */
3390             silc_server_backup_send_start_use(server,
3391                                               backup_router->connection,
3392                                               FALSE);
3393           } else {
3394             SILC_LOG_INFO(("We are now new primary router in this cell"));
3395             server->id_entry->router = NULL;
3396             server->router = NULL;
3397             server->standalone = TRUE;
3398           }
3399
3400           /* We stop here to take a breath */
3401           sleep(2);
3402
3403           if (server->backup_router) {
3404             server->server_type = SILC_ROUTER;
3405
3406             /* We'll need to constantly try to reconnect to the primary
3407                router so that we'll see when it comes back online. */
3408             silc_server_backup_reconnect(server, sock->ip, sock->port,
3409                                          silc_server_backup_connected,
3410                                          NULL);
3411           }
3412
3413           /* Mark this connection as replaced */
3414           silc_server_backup_replaced_add(server, user_data->id,
3415                                           backup_router);
3416         }
3417       } else if (backup_router) {
3418         SILC_LOG_INFO(("Enabling the use of backup router %s",
3419                        backup_router->server_name));
3420
3421         /* Mark this connection as replaced */
3422         silc_server_backup_replaced_add(server, user_data->id,
3423                                         backup_router);
3424       } else if (server->server_type == SILC_SERVER &&
3425                  sock->type == SILC_SOCKET_TYPE_ROUTER) {
3426         /* Reconnect to the router (backup) */
3427         if (!server->no_reconnect)
3428           silc_server_create_connections(server);
3429       }
3430
3431       if (user_data->server_name)
3432         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3433                                ("Server %s signoff", user_data->server_name));
3434
3435       if (!backup_router) {
3436         /* Remove all servers that are originated from this server, and
3437            remove the clients of those servers too. */
3438         silc_server_remove_servers_by_server(server, user_data, TRUE);
3439
3440 #if 0
3441         /* Remove the clients that this server owns as they will become
3442            invalid now too.  For backup router the server is actually
3443            coming from the primary router, so mark that as the owner
3444            of this entry. */
3445         if (server->server_type == SILC_BACKUP_ROUTER &&
3446             sock->type == SILC_SOCKET_TYPE_SERVER)
3447           silc_server_remove_clients_by_server(server, server->router,
3448                                                user_data, TRUE);
3449         else
3450 #endif
3451           silc_server_remove_clients_by_server(server, user_data,
3452                                                user_data, TRUE);
3453
3454         /* Remove channels owned by this server */
3455         if (server->server_type == SILC_SERVER)
3456           silc_server_remove_channels_by_server(server, user_data);
3457       } else {
3458         /* Enable local server connections that may be disabled */
3459         silc_server_local_servers_toggle_enabled(server, TRUE);
3460
3461         /* Update the client entries of this server to the new backup
3462            router.  If we are the backup router we also resolve the real
3463            servers for the clients.  After updating is over this also
3464            removes the clients that this server explicitly owns. */
3465         silc_server_update_clients_by_server(server, user_data,
3466                                              backup_router, TRUE);
3467
3468         /* If we are router and just lost our primary router (now standlaone)
3469            we remove everything that was behind it, since we don't know
3470            any better. */
3471         if (server->server_type == SILC_ROUTER && server->standalone)
3472           /* Remove all servers that are originated from this server, and
3473              remove the clients of those servers too. */
3474           silc_server_remove_servers_by_server(server, user_data, TRUE);
3475
3476         /* Finally remove the clients that are explicitly owned by this
3477            server.  They go down with the server. */
3478         silc_server_remove_clients_by_server(server, user_data,
3479                                              user_data, TRUE);
3480
3481         /* Update our server cache to use the new backup router too. */
3482         silc_server_update_servers_by_server(server, user_data, backup_router);
3483         if (server->server_type == SILC_SERVER)
3484           silc_server_update_channels_by_server(server, user_data,
3485                                                 backup_router);
3486
3487         /* Send notify about primary router going down to local operators */
3488         if (server->backup_router)
3489           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3490                                  SILC_NOTIFY_TYPE_NONE,
3491                                  ("%s switched to backup router %s "
3492                                   "(we are primary router now)",
3493                                   server->server_name, server->server_name));
3494         else if (server->router)
3495           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3496                                  SILC_NOTIFY_TYPE_NONE,
3497                                  ("%s switched to backup router %s",
3498                                   server->server_name,
3499                                   server->router->server_name));
3500       }
3501       server->backup_noswitch = FALSE;
3502
3503       /* Free the server entry */
3504       silc_server_backup_del(server, user_data);
3505       silc_server_backup_replaced_del(server, user_data);
3506       silc_idlist_del_data(user_data);
3507       if (!silc_idlist_del_server(server->local_list, user_data))
3508         silc_idlist_del_server(server->global_list, user_data);
3509       if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3510         server->stat.my_servers--;
3511       } else {
3512         server->stat.my_routers--;
3513         server->stat.routers--;
3514       }
3515       server->stat.servers--;
3516       if (server->server_type == SILC_ROUTER)
3517         server->stat.cell_servers--;
3518
3519       if (backup_router && backup_router != server->id_entry) {
3520         /* Announce all of our stuff that was created about 5 minutes ago.
3521            The backup router knows all the other stuff already. */
3522         if (server->server_type == SILC_ROUTER)
3523           silc_server_announce_servers(server, FALSE, time(0) - 300,
3524                                        backup_router->connection);
3525
3526         /* Announce our clients and channels to the router */
3527         silc_server_announce_clients(server, time(0) - 300,
3528                                      backup_router->connection);
3529         silc_server_announce_channels(server, time(0) - 300,
3530                                       backup_router->connection);
3531       }
3532       break;
3533     }
3534   default:
3535     {
3536       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3537
3538       SILC_LOG_DEBUG(("Freeing unknown connection data"));
3539
3540       silc_idlist_del_data(user_data);
3541       silc_free(user_data);
3542       break;
3543     }
3544   }
3545
3546   sock->user_data = NULL;
3547 }
3548
3549 /* Removes client from all channels it has joined. This is used when client
3550    connection is disconnected. If the client on a channel is last, the
3551    channel is removed as well. This sends the SIGNOFF notify types. */
3552
3553 void silc_server_remove_from_channels(SilcServer server,
3554                                       SilcSocketConnection sock,
3555                                       SilcClientEntry client,
3556                                       bool notify,
3557                                       const char *signoff_message,
3558                                       bool keygen,
3559                                       bool killed)
3560 {
3561   SilcChannelEntry channel;
3562   SilcChannelClientEntry chl;
3563   SilcHashTableList htl;
3564   SilcBuffer clidp = NULL;
3565
3566   if (!client)
3567     return;
3568
3569   if (notify && !client->id)
3570     notify = FALSE;
3571
3572   SILC_LOG_DEBUG(("Removing client %s from joined channels",
3573                   notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3574
3575   if (notify) {
3576     clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3577     if (!clidp)
3578       notify = FALSE;
3579   }
3580
3581   /* Remove the client from all channels. The client is removed from
3582      the channels' user list. */
3583   silc_hash_table_list(client->channels, &htl);
3584   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3585     channel = chl->channel;
3586
3587     /* Remove channel if this is last client leaving the channel, unless
3588        the channel is permanent. */
3589     if (server->server_type != SILC_SERVER &&
3590         silc_hash_table_count(channel->user_list) < 2) {
3591       silc_server_channel_delete(server, channel);
3592       continue;
3593     }
3594
3595     silc_hash_table_del(client->channels, channel);
3596     silc_hash_table_del(channel->user_list, client);
3597     channel->user_count--;
3598
3599     /* If there is no global users on the channel anymore mark the channel
3600        as local channel. Do not check if the removed client is local client. */
3601     if (server->server_type == SILC_SERVER && channel->global_users &&
3602         chl->client->router && !silc_server_channel_has_global(channel))
3603       channel->global_users = FALSE;
3604
3605     memset(chl, 'A', sizeof(*chl));
3606     silc_free(chl);
3607
3608     /* Update statistics */
3609     if (SILC_IS_LOCAL(client))
3610       server->stat.my_chanclients--;
3611     if (server->server_type == SILC_ROUTER) {
3612       server->stat.cell_chanclients--;
3613       server->stat.chanclients--;
3614     }
3615
3616     /* If there is not at least one local user on the channel then we don't
3617        need the channel entry anymore, we can remove it safely, unless the
3618        channel is permanent channel */
3619     if (server->server_type == SILC_SERVER &&
3620         !silc_server_channel_has_local(channel)) {
3621       /* Notify about leaving client if this channel has global users. */
3622       if (notify && channel->global_users)
3623         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3624                                            SILC_NOTIFY_TYPE_SIGNOFF,
3625                                            signoff_message ? 2 : 1,
3626                                            clidp->data, clidp->len,
3627                                            signoff_message, signoff_message ?
3628                                            strlen(signoff_message) : 0);
3629
3630       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3631       silc_server_channel_delete(server, channel);
3632       continue;
3633     }
3634
3635     /* Send notify to channel about client leaving SILC and channel too */
3636     if (notify)
3637       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3638                                          SILC_NOTIFY_TYPE_SIGNOFF,
3639                                          signoff_message ? 2 : 1,
3640                                          clidp->data, clidp->len,
3641                                          signoff_message, signoff_message ?
3642                                          strlen(signoff_message) : 0);
3643
3644     if (killed && clidp) {
3645       /* Remove the client from channel's invite list */
3646       if (channel->invite_list &&
3647           silc_hash_table_count(channel->invite_list)) {
3648         SilcBuffer ab;
3649         SilcArgumentPayload iargs;
3650         ab = silc_argument_payload_encode_one(NULL, clidp->data,
3651                                               clidp->len, 3);
3652         iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3653         silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3654         silc_buffer_free(ab);
3655         silc_argument_payload_free(iargs);
3656       }
3657     }
3658
3659     /* Don't create keys if we are shutting down */
3660     if (server->server_shutdown)
3661       continue;
3662
3663     /* Re-generate channel key if needed */
3664     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3665       if (!silc_server_create_channel_key(server, channel, 0))
3666         continue;
3667
3668       /* Send the channel key to the channel. The key of course is not sent
3669          to the client who was removed from the channel. */
3670       silc_server_send_channel_key(server, client->connection, channel,
3671                                    server->server_type == SILC_ROUTER ?
3672                                    FALSE : !server->standalone);
3673     }
3674   }
3675
3676   silc_hash_table_list_reset(&htl);
3677   if (clidp)
3678     silc_buffer_free(clidp);
3679 }
3680
3681 /* Removes client from one channel. This is used for example when client
3682    calls LEAVE command to remove itself from the channel. Returns TRUE
3683    if channel still exists and FALSE if the channel is removed when
3684    last client leaves the channel. If `notify' is FALSE notify messages
3685    are not sent. */
3686
3687 bool silc_server_remove_from_one_channel(SilcServer server,
3688                                          SilcSocketConnection sock,
3689                                          SilcChannelEntry channel,
3690                                          SilcClientEntry client,
3691                                          bool notify)
3692 {
3693   SilcChannelClientEntry chl;
3694   SilcBuffer clidp;
3695
3696   SILC_LOG_DEBUG(("Removing %s from channel %s",
3697                   silc_id_render(client->id, SILC_ID_CLIENT),
3698                   channel->channel_name));
3699
3700   /* Get the entry to the channel, if this client is not on the channel
3701      then return Ok. */
3702   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3703     return TRUE;
3704
3705   /* Remove channel if this is last client leaving the channel, unless
3706      the channel is permanent. */
3707   if (server->server_type != SILC_SERVER &&
3708       silc_hash_table_count(channel->user_list) < 2) {
3709     silc_server_channel_delete(server, channel);
3710     return FALSE;
3711   }
3712
3713   silc_hash_table_del(client->channels, channel);
3714   silc_hash_table_del(channel->user_list, client);
3715   channel->user_count--;
3716
3717   /* If there is no global users on the channel anymore mark the channel
3718      as local channel. Do not check if the client is local client. */
3719   if (server->server_type == SILC_SERVER && channel->global_users &&
3720       chl->client->router && !silc_server_channel_has_global(channel))
3721     channel->global_users = FALSE;
3722
3723   memset(chl, 'O', sizeof(*chl));
3724   silc_free(chl);
3725
3726   /* Update statistics */
3727   if (SILC_IS_LOCAL(client))
3728     server->stat.my_chanclients--;
3729   if (server->server_type == SILC_ROUTER) {
3730     server->stat.cell_chanclients--;
3731     server->stat.chanclients--;
3732   }
3733
3734   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3735   if (!clidp)
3736     notify = FALSE;
3737
3738   /* If there is not at least one local user on the channel then we don't
3739      need the channel entry anymore, we can remove it safely, unless the
3740      channel is permanent channel */
3741   if (server->server_type == SILC_SERVER &&
3742       !silc_server_channel_has_local(channel)) {
3743     /* Notify about leaving client if this channel has global users. */
3744     if (notify && channel->global_users)
3745       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3746                                          SILC_NOTIFY_TYPE_LEAVE, 1,
3747                                          clidp->data, clidp->len);
3748
3749     silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3750     silc_server_channel_delete(server, channel);
3751     silc_buffer_free(clidp);
3752     return FALSE;
3753   }
3754
3755   /* Send notify to channel about client leaving the channel */
3756   if (notify)
3757     silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3758                                        SILC_NOTIFY_TYPE_LEAVE, 1,
3759                                        clidp->data, clidp->len);
3760
3761   silc_buffer_free(clidp);
3762   return TRUE;
3763 }
3764
3765 /* Timeout callback. This is called if connection is idle or for some
3766    other reason is not responding within some period of time. This
3767    disconnects the remote end. */
3768
3769 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3770 {
3771   SilcServer server = (SilcServer)context;
3772   SilcSocketConnection sock = server->sockets[fd];
3773   SilcProtocolType protocol = 0;
3774
3775   SILC_LOG_DEBUG(("Start"));
3776
3777   if (!sock)
3778     return;
3779
3780   SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3781                   sock->hostname, sock->ip));
3782
3783   /* If we have protocol active we must assure that we call the protocol's
3784      final callback so that all the memory is freed. */
3785   if (sock->protocol && sock->protocol->protocol &&
3786       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3787     protocol = sock->protocol->protocol->type;
3788     silc_protocol_cancel(sock->protocol, server->schedule);
3789     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3790     silc_protocol_execute_final(sock->protocol, server->schedule);
3791     sock->protocol = NULL;
3792     return;
3793   }
3794
3795   silc_server_disconnect_remote(server, sock,
3796                                 protocol ==
3797                                 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3798                                 SILC_STATUS_ERR_AUTH_FAILED :
3799                                 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3800                                 "Connection timeout");
3801
3802   if (sock->user_data)
3803     silc_server_free_sock_user_data(server, sock, NULL);
3804 }
3805
3806 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3807    function may be used only by router. In real SILC network all channels
3808    are created by routers thus this function is never used by normal
3809    server. */
3810
3811 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3812                                                 SilcServerID *router_id,
3813                                                 char *cipher,
3814                                                 char *hmac,
3815                                                 char *channel_name,
3816                                                 int broadcast)
3817 {
3818   SilcChannelID *channel_id;
3819   SilcChannelEntry entry;
3820   SilcCipher key;
3821   SilcHmac newhmac;
3822
3823   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3824
3825   if (!cipher)
3826     cipher = SILC_DEFAULT_CIPHER;
3827   if (!hmac)
3828     hmac = SILC_DEFAULT_HMAC;
3829
3830   /* Allocate cipher */
3831   if (!silc_cipher_alloc(cipher, &key))
3832     return NULL;
3833
3834   /* Allocate hmac */
3835   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3836     silc_cipher_free(key);
3837     return NULL;
3838   }
3839
3840   channel_name = strdup(channel_name);
3841
3842   /* Create the channel ID */
3843   if (!silc_id_create_channel_id(server, router_id, server->rng,
3844                                  &channel_id)) {
3845     silc_free(channel_name);
3846     silc_cipher_free(key);
3847     silc_hmac_free(newhmac);
3848     return NULL;
3849   }
3850
3851   /* Create the channel */
3852   entry = silc_idlist_add_channel(server->local_list, channel_name,
3853                                   SILC_CHANNEL_MODE_NONE, channel_id,
3854                                   NULL, key, newhmac, 0);
3855   if (!entry) {
3856     silc_free(channel_name);
3857     silc_cipher_free(key);
3858     silc_hmac_free(newhmac);
3859     silc_free(channel_id);
3860     return NULL;
3861   }
3862
3863   entry->cipher = strdup(cipher);
3864   entry->hmac_name = strdup(hmac);
3865
3866   /* Now create the actual key material */
3867   if (!silc_server_create_channel_key(server, entry,
3868                                       silc_cipher_get_key_len(key) / 8)) {
3869     silc_idlist_del_channel(server->local_list, entry);
3870     return NULL;
3871   }
3872
3873   /* Notify other routers about the new channel. We send the packet
3874      to our primary route. */
3875   if (broadcast)
3876     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3877                                  channel_name, entry->id,
3878                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3879                                  entry->mode);
3880
3881   /* Distribute to backup routers */
3882   if (broadcast && server->server_type == SILC_ROUTER) {
3883     SilcBuffer packet;
3884     unsigned char *cid;
3885     SilcUInt32 name_len = strlen(channel_name);
3886     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3887     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3888
3889     packet = silc_channel_payload_encode(channel_name, name_len,
3890                                          cid, channel_id_len, entry->mode);
3891     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3892                             packet->data, packet->len, FALSE, TRUE);
3893     silc_free(cid);
3894     silc_buffer_free(packet);
3895   }
3896
3897   server->stat.my_channels++;
3898   if (server->server_type == SILC_ROUTER) {
3899     server->stat.channels++;
3900     server->stat.cell_channels++;
3901     entry->users_resolved = TRUE;
3902   }
3903
3904   return entry;
3905 }
3906
3907 /* Same as above but creates the channel with Channel ID `channel_id. */
3908
3909 SilcChannelEntry
3910 silc_server_create_new_channel_with_id(SilcServer server,
3911                                        char *cipher,
3912                                        char *hmac,
3913                                        char *channel_name,
3914                                        SilcChannelID *channel_id,
3915                                        int broadcast)
3916 {
3917   SilcChannelEntry entry;
3918   SilcCipher key;
3919   SilcHmac newhmac;
3920
3921   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3922
3923   if (!cipher)
3924     cipher = SILC_DEFAULT_CIPHER;
3925   if (!hmac)
3926     hmac = SILC_DEFAULT_HMAC;
3927
3928   /* Allocate cipher */
3929   if (!silc_cipher_alloc(cipher, &key))
3930     return NULL;
3931
3932   /* Allocate hmac */
3933   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3934     silc_cipher_free(key);
3935     return NULL;
3936   }
3937
3938   channel_name = strdup(channel_name);
3939
3940   /* Create the channel */
3941   entry = silc_idlist_add_channel(server->local_list, channel_name,
3942                                   SILC_CHANNEL_MODE_NONE, channel_id,
3943                                   NULL, key, newhmac, 0);
3944   if (!entry) {
3945     silc_cipher_free(key);
3946     silc_hmac_free(newhmac);
3947     silc_free(channel_name);
3948     return NULL;
3949   }
3950
3951   /* Now create the actual key material */
3952   if (!silc_server_create_channel_key(server, entry,
3953                                       silc_cipher_get_key_len(key) / 8)) {
3954     silc_idlist_del_channel(server->local_list, entry);
3955     return NULL;
3956   }
3957
3958   /* Notify other routers about the new channel. We send the packet
3959      to our primary route. */
3960   if (broadcast)
3961     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3962                                  channel_name, entry->id,
3963                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3964                                  entry->mode);
3965
3966   /* Distribute to backup routers */
3967   if (broadcast && server->server_type == SILC_ROUTER) {
3968     SilcBuffer packet;
3969     unsigned char *cid;
3970     SilcUInt32 name_len = strlen(channel_name);
3971     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3972     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3973
3974     packet = silc_channel_payload_encode(channel_name, name_len,
3975                                          cid, channel_id_len, entry->mode);
3976     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3977                             packet->data, packet->len, FALSE, TRUE);
3978     silc_free(cid);
3979     silc_buffer_free(packet);
3980   }
3981
3982   server->stat.my_channels++;
3983   if (server->server_type == SILC_ROUTER) {
3984     server->stat.channels++;
3985     server->stat.cell_channels++;
3986     entry->users_resolved = TRUE;
3987   }
3988
3989   return entry;
3990 }
3991
3992 /* Channel's key re-key timeout callback. */
3993
3994 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3995 {
3996   SilcServer server = app_context;
3997   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3998
3999   rekey->task = NULL;
4000
4001   /* Return now if we are shutting down */
4002   if (server->server_shutdown)
4003     return;
4004
4005   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4006     return;
4007
4008   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4009 }
4010
4011 /* Generates new channel key. This is used to create the initial channel key
4012    but also to re-generate new key for channel. If `key_len' is provided
4013    it is the bytes of the key length. */
4014
4015 bool silc_server_create_channel_key(SilcServer server,
4016                                     SilcChannelEntry channel,
4017                                     SilcUInt32 key_len)
4018 {
4019   int i;
4020   unsigned char channel_key[32], hash[32];
4021   SilcUInt32 len;
4022
4023   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4024     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4025     return TRUE;
4026   }
4027
4028   SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4029
4030   if (!channel->channel_key)
4031     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4032       channel->channel_key = NULL;
4033       return FALSE;
4034     }
4035
4036   if (key_len)
4037     len = key_len;
4038   else if (channel->key_len)
4039     len = channel->key_len / 8;
4040   else
4041     len = silc_cipher_get_key_len(channel->channel_key) / 8;
4042
4043   /* Create channel key */
4044   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4045
4046   /* Set the key */
4047   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4048
4049   /* Remove old key if exists */
4050   if (channel->key) {
4051     memset(channel->key, 0, channel->key_len / 8);
4052     silc_free(channel->key);
4053   }
4054
4055   /* Save the key */
4056   channel->key_len = len * 8;
4057   channel->key = silc_memdup(channel_key, len);
4058   memset(channel_key, 0, sizeof(channel_key));
4059
4060   /* Generate HMAC key from the channel key data and set it */
4061   if (!channel->hmac)
4062     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4063       memset(channel->key, 0, channel->key_len / 8);
4064       silc_free(channel->key);
4065       channel->channel_key = NULL;
4066       return FALSE;
4067     }
4068   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4069   silc_hmac_set_key(channel->hmac, hash,
4070                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4071   memset(hash, 0, sizeof(hash));
4072
4073   if (server->server_type == SILC_ROUTER) {
4074     if (!channel->rekey)
4075       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4076     channel->rekey->channel = channel;
4077     channel->rekey->key_len = key_len;
4078     if (channel->rekey->task)
4079       silc_schedule_task_del(server->schedule, channel->rekey->task);
4080
4081     channel->rekey->task =
4082       silc_schedule_task_add(server->schedule, 0,
4083                              silc_server_channel_key_rekey,
4084                              (void *)channel->rekey,
4085                              server->config->channel_rekey_secs, 0,
4086                              SILC_TASK_TIMEOUT,
4087                              SILC_TASK_PRI_NORMAL);
4088   }
4089
4090   return TRUE;
4091 }
4092
4093 /* Saves the channel key found in the encoded `key_payload' buffer. This
4094    function is used when we receive Channel Key Payload and also when we're
4095    processing JOIN command reply. Returns entry to the channel. */
4096
4097 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4098                                               SilcBuffer key_payload,
4099                                               SilcChannelEntry channel)
4100 {
4101   SilcChannelKeyPayload payload = NULL;
4102   SilcChannelID *id = NULL;
4103   unsigned char *tmp, hash[32];
4104   SilcUInt32 tmp_len;
4105   char *cipher;
4106
4107   /* Decode channel key payload */
4108   payload = silc_channel_key_payload_parse(key_payload->data,
4109                                            key_payload->len);
4110   if (!payload) {
4111     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4112     channel = NULL;
4113     goto out;
4114   }
4115
4116   /* Get the channel entry */
4117   if (!channel) {
4118
4119     /* Get channel ID */
4120     tmp = silc_channel_key_get_id(payload, &tmp_len);
4121     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4122     if (!id) {
4123       channel = NULL;
4124       goto out;
4125     }
4126
4127     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4128     if (!channel) {
4129       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4130       if (!channel) {
4131         if (server->server_type == SILC_ROUTER)
4132           SILC_LOG_ERROR(("Received key for non-existent channel %s",
4133                           silc_id_render(id, SILC_ID_CHANNEL)));
4134         goto out;
4135       }
4136     }
4137   }
4138
4139   SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4140
4141   tmp = silc_channel_key_get_key(payload, &tmp_len);
4142   if (!tmp) {
4143     channel = NULL;
4144     goto out;
4145   }
4146
4147   cipher = silc_channel_key_get_cipher(payload, NULL);
4148   if (!cipher) {
4149     channel = NULL;
4150     goto out;
4151   }
4152
4153   /* Remove old key if exists */
4154   if (channel->key) {
4155     memset(channel->key, 0, channel->key_len / 8);
4156     silc_free(channel->key);
4157     silc_cipher_free(channel->channel_key);
4158   }
4159
4160   /* Create new cipher */
4161   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4162     channel->channel_key = NULL;
4163     channel = NULL;
4164     goto out;
4165   }
4166
4167   if (channel->cipher)
4168     silc_free(channel->cipher);
4169   channel->cipher = strdup(cipher);
4170
4171   /* Save the key */
4172   channel->key_len = tmp_len * 8;
4173   channel->key = silc_memdup(tmp, tmp_len);
4174   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4175
4176   /* Generate HMAC key from the channel key data and set it */
4177   if (!channel->hmac)
4178     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4179       memset(channel->key, 0, channel->key_len / 8);
4180       silc_free(channel->key);
4181       channel->channel_key = NULL;
4182       return FALSE;
4183     }
4184   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4185   silc_hmac_set_key(channel->hmac, hash,
4186                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4187
4188   memset(hash, 0, sizeof(hash));
4189   memset(tmp, 0, tmp_len);
4190
4191   if (server->server_type == SILC_ROUTER) {
4192     if (!channel->rekey)
4193       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4194     channel->rekey->channel = channel;
4195     if (channel->rekey->task)
4196       silc_schedule_task_del(server->schedule, channel->rekey->task);
4197
4198     channel->rekey->task =
4199       silc_schedule_task_add(server->schedule, 0,
4200                              silc_server_channel_key_rekey,
4201                              (void *)channel->rekey,
4202                              server->config->channel_rekey_secs, 0,
4203                              SILC_TASK_TIMEOUT,
4204                              SILC_TASK_PRI_NORMAL);
4205   }
4206
4207  out:
4208   silc_free(id);
4209   if (payload)
4210     silc_channel_key_payload_free(payload);
4211
4212   return channel;
4213 }
4214
4215 /* Heartbeat callback. This function is set as argument for the
4216    silc_socket_set_heartbeat function. The library will call this function
4217    at the set time interval. */
4218
4219 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4220                                    void *hb_context)
4221 {
4222   SilcServer server = hb_context;
4223
4224   SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4225                  sock->port, sock->ip));
4226
4227   /* Send the heartbeat */
4228   silc_server_send_heartbeat(server, sock);
4229 }
4230
4231 /* Returns assembled of all servers in the given ID list. The packet's
4232    form is dictated by the New ID payload. */
4233
4234 static void silc_server_announce_get_servers(SilcServer server,
4235                                              SilcServerEntry remote,
4236                                              SilcIDList id_list,
4237                                              SilcBuffer *servers,
4238                                              unsigned long creation_time)
4239 {
4240   SilcIDCacheList list;
4241   SilcIDCacheEntry id_cache;
4242   SilcServerEntry entry;
4243   SilcBuffer idp;
4244
4245   /* Go through all clients in the list */
4246   if (silc_idcache_get_all(id_list->servers, &list)) {
4247     if (silc_idcache_list_first(list, &id_cache)) {
4248       while (id_cache) {
4249         entry = (SilcServerEntry)id_cache->context;
4250
4251         /* Do not announce the one we've sending our announcements and
4252            do not announce ourself. Also check the creation time if it's
4253            provided. */
4254         if ((entry == remote) || (entry == server->id_entry) ||
4255             (creation_time && entry->data.created < creation_time)) {
4256           if (!silc_idcache_list_next(list, &id_cache))
4257             break;
4258           continue;
4259         }
4260
4261         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4262
4263         *servers = silc_buffer_realloc(*servers,
4264                                        (*servers ?
4265                                         (*servers)->truelen + idp->len :
4266                                         idp->len));
4267         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4268         silc_buffer_put(*servers, idp->data, idp->len);
4269         silc_buffer_pull(*servers, idp->len);
4270         silc_buffer_free(idp);
4271
4272         if (!silc_idcache_list_next(list, &id_cache))
4273           break;
4274       }
4275     }
4276
4277     silc_idcache_list_free(list);
4278   }
4279 }
4280
4281 static SilcBuffer
4282 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4283 {
4284   va_list ap;
4285   SilcBuffer p;
4286
4287   va_start(ap, argc);
4288   p = silc_notify_payload_encode(notify, argc, ap);
4289   va_end(ap);
4290
4291   return p;
4292 }
4293
4294 /* This function is used by router to announce existing servers to our
4295    primary router when we've connected to it. If `creation_time' is non-zero
4296    then only the servers that has been created after the `creation_time'
4297    will be announced. */
4298
4299 void silc_server_announce_servers(SilcServer server, bool global,
4300                                   unsigned long creation_time,
4301                                   SilcSocketConnection remote)
4302 {
4303   SilcBuffer servers = NULL;
4304
4305   SILC_LOG_DEBUG(("Announcing servers"));
4306
4307   /* Get servers in local list */
4308   silc_server_announce_get_servers(server, remote->user_data,
4309                                    server->local_list, &servers,
4310                                    creation_time);
4311
4312   if (global)
4313     /* Get servers in global list */
4314     silc_server_announce_get_servers(server, remote->user_data,
4315                                      server->global_list, &servers,
4316                                      creation_time);
4317
4318   if (servers) {
4319     silc_buffer_push(servers, servers->data - servers->head);
4320     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4321
4322     /* Send the packet */
4323     silc_server_packet_send(server, remote,
4324                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4325                             servers->data, servers->len, TRUE);
4326
4327     silc_buffer_free(servers);
4328   }
4329 }
4330
4331 /* Returns assembled packet of all clients in the given ID list. The
4332    packet's form is dictated by the New ID Payload. */
4333
4334 static void silc_server_announce_get_clients(SilcServer server,
4335                                              SilcIDList id_list,
4336                                              SilcBuffer *clients,
4337                                              SilcBuffer *umodes,
4338                                              unsigned long creation_time)
4339 {
4340   SilcIDCacheList list;
4341   SilcIDCacheEntry id_cache;
4342   SilcClientEntry client;
4343   SilcBuffer idp;
4344   SilcBuffer tmp;
4345   unsigned char mode[4];
4346
4347   /* Go through all clients in the list */
4348   if (silc_idcache_get_all(id_list->clients, &list)) {
4349     if (silc_idcache_list_first(list, &id_cache)) {
4350       while (id_cache) {
4351         client = (SilcClientEntry)id_cache->context;
4352
4353         if (creation_time && client->data.created < creation_time) {
4354           if (!silc_idcache_list_next(list, &id_cache))
4355             break;
4356           continue;
4357         }
4358         if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4359             !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4360           if (!silc_idcache_list_next(list, &id_cache))
4361             break;
4362           continue;
4363         }
4364
4365         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4366
4367         *clients = silc_buffer_realloc(*clients,
4368                                        (*clients ?
4369                                         (*clients)->truelen + idp->len :
4370                                         idp->len));
4371         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4372         silc_buffer_put(*clients, idp->data, idp->len);
4373         silc_buffer_pull(*clients, idp->len);
4374
4375         SILC_PUT32_MSB(client->mode, mode);
4376         tmp =
4377           silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4378                                              2, idp->data, idp->len,
4379                                              mode, 4);
4380         *umodes = silc_buffer_realloc(*umodes,
4381                                       (*umodes ?
4382                                        (*umodes)->truelen + tmp->len :
4383                                        tmp->len));
4384         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4385         silc_buffer_put(*umodes, tmp->data, tmp->len);
4386         silc_buffer_pull(*umodes, tmp->len);
4387         silc_buffer_free(tmp);
4388
4389         silc_buffer_free(idp);
4390
4391         if (!silc_idcache_list_next(list, &id_cache))
4392           break;
4393       }
4394     }
4395
4396     silc_idcache_list_free(list);
4397   }
4398 }
4399
4400 /* This function is used to announce our existing clients to our router
4401    when we've connected to it. If `creation_time' is non-zero then only
4402    the clients that has been created after the `creation_time' will be
4403    announced. */
4404
4405 void silc_server_announce_clients(SilcServer server,
4406                                   unsigned long creation_time,
4407                                   SilcSocketConnection remote)
4408 {
4409   SilcBuffer clients = NULL;
4410   SilcBuffer umodes = NULL;
4411
4412   SILC_LOG_DEBUG(("Announcing clients"));
4413
4414   /* Get clients in local list */
4415   silc_server_announce_get_clients(server, server->local_list,
4416                                    &clients, &umodes, creation_time);
4417
4418   /* As router we announce our global list as well */
4419   if (server->server_type == SILC_ROUTER)
4420     silc_server_announce_get_clients(server, server->global_list,
4421                                      &clients, &umodes, creation_time);
4422
4423   if (clients) {
4424     silc_buffer_push(clients, clients->data - clients->head);
4425     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4426
4427     /* Send the packet */
4428     silc_server_packet_send(server, remote,
4429                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4430                             clients->data, clients->len, TRUE);
4431
4432     silc_buffer_free(clients);
4433   }
4434
4435   if (umodes) {
4436     silc_buffer_push(umodes, umodes->data - umodes->head);
4437     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4438
4439     /* Send the packet */
4440     silc_server_packet_send(server, remote,
4441                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4442                             umodes->data, umodes->len, TRUE);
4443
4444     silc_buffer_free(umodes);
4445   }
4446 }
4447
4448 /* Returns channel's topic for announcing it */
4449
4450 void silc_server_announce_get_channel_topic(SilcServer server,
4451                                             SilcChannelEntry channel,
4452                                             SilcBuffer *topic)
4453 {
4454   SilcBuffer chidp;
4455
4456   if (channel->topic) {
4457     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4458     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4459                                                 chidp->data, chidp->len,
4460                                                 channel->topic,
4461                                                 strlen(channel->topic));
4462     silc_buffer_free(chidp);
4463   }
4464 }
4465
4466 /* Returns channel's invite and ban lists */
4467
4468 void silc_server_announce_get_inviteban(SilcServer server,
4469                                         SilcChannelEntry channel,
4470                                         SilcBuffer *invite,
4471                                         SilcBuffer *ban)
4472 {
4473   SilcBuffer list, idp, idp2, tmp2;
4474   SilcUInt32 type;
4475   SilcHashTableList htl;
4476   const unsigned char a[1] = { 0x03 };
4477
4478   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4479
4480   /* Encode invite list */
4481   if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4482     list = silc_buffer_alloc_size(2);
4483     type = silc_hash_table_count(channel->invite_list);
4484     SILC_PUT16_MSB(type, list->data);
4485     silc_hash_table_list(channel->invite_list, &htl);
4486     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4487       list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4488                                               type);
4489     silc_hash_table_list_reset(&htl);
4490
4491     idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4492     *invite =
4493       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4494                                          idp->data, idp->len,
4495                                          channel->channel_name,
4496                                          strlen(channel->channel_name),
4497                                          idp2->data, idp2->len,
4498                                          a, 1,
4499                                          list->data, list->len);
4500     silc_buffer_free(idp2);
4501     silc_buffer_free(list);
4502   }
4503
4504   /* Encode ban list */
4505   if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4506     list = silc_buffer_alloc_size(2);
4507     type = silc_hash_table_count(channel->ban_list);
4508     SILC_PUT16_MSB(type, list->data);
4509     silc_hash_table_list(channel->ban_list, &htl);
4510     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4511       list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4512                                               type);
4513     silc_hash_table_list_reset(&htl);
4514
4515     *ban =
4516       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4517                                          idp->data, idp->len,
4518                                          a, 1,
4519                                          list->data, list->len);
4520     silc_buffer_free(list);
4521   }
4522
4523   silc_buffer_free(idp);
4524 }
4525
4526 /* Returns assembled packets for channel users of the `channel'. */
4527
4528 void silc_server_announce_get_channel_users(SilcServer server,
4529                                             SilcChannelEntry channel,
4530                                             SilcBuffer *channel_modes,
4531                                             SilcBuffer *channel_users,
4532                                             SilcBuffer *channel_users_modes)
4533 {
4534   SilcChannelClientEntry chl;
4535   SilcHashTableList htl;
4536   SilcBuffer chidp, clidp, csidp;
4537   SilcBuffer tmp, fkey = NULL, chpklist;
4538   int len;
4539   unsigned char mode[4];
4540   char *hmac;
4541
4542   SILC_LOG_DEBUG(("Start"));
4543
4544   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4545   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4546   chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4547
4548   /* CMODE notify */
4549   SILC_PUT32_MSB(channel->mode, mode);
4550   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4551   if (channel->founder_key)
4552     fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4553   tmp =
4554     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4555                                        7, csidp->data, csidp->len,
4556                                        mode, sizeof(mode),
4557                                        NULL, 0,
4558                                        hmac, hmac ? strlen(hmac) : 0,
4559                                        channel->passphrase,
4560                                        channel->passphrase ?
4561                                        strlen(channel->passphrase) : 0,
4562                                        fkey ? fkey->data : NULL,
4563                                        fkey ? fkey->len : 0,
4564                                        chpklist ? chpklist->data : NULL,
4565                                        chpklist ? chpklist->len : 0);
4566   len = tmp->len;
4567   *channel_modes =
4568     silc_buffer_realloc(*channel_modes,
4569                         (*channel_modes ?
4570                          (*channel_modes)->truelen + len : len));
4571   silc_buffer_pull_tail(*channel_modes,
4572                         ((*channel_modes)->end -
4573                          (*channel_modes)->data));
4574   silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4575   silc_buffer_pull(*channel_modes, len);
4576   silc_buffer_free(tmp);
4577   silc_buffer_free(fkey);
4578   fkey = NULL;
4579
4580   /* Now find all users on the channel */
4581   silc_hash_table_list(channel->user_list, &htl);
4582   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4583     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4584
4585     /* JOIN Notify */
4586     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4587                                              clidp->data, clidp->len,
4588                                              chidp->data, chidp->len);
4589     len = tmp->len;
4590     *channel_users =
4591       silc_buffer_realloc(*channel_users,
4592                           (*channel_users ?
4593                            (*channel_users)->truelen + len : len));
4594     silc_buffer_pull_tail(*channel_users,
4595                           ((*channel_users)->end -
4596                            (*channel_users)->data));
4597
4598     silc_buffer_put(*channel_users, tmp->data, tmp->len);
4599     silc_buffer_pull(*channel_users, len);
4600     silc_buffer_free(tmp);
4601
4602     /* CUMODE notify for mode change on the channel */
4603     SILC_PUT32_MSB(chl->mode, mode);
4604     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4605       fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4606     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4607                                              4, csidp->data, csidp->len,
4608                                              mode, sizeof(mode),
4609                                              clidp->data, clidp->len,
4610                                              fkey ? fkey->data : NULL,
4611                                              fkey ? fkey->len : 0);
4612     len = tmp->len;
4613     *channel_users_modes =
4614       silc_buffer_realloc(*channel_users_modes,
4615                           (*channel_users_modes ?
4616                            (*channel_users_modes)->truelen + len : len));
4617     silc_buffer_pull_tail(*channel_users_modes,
4618                           ((*channel_users_modes)->end -
4619                            (*channel_users_modes)->data));
4620
4621     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4622     silc_buffer_pull(*channel_users_modes, len);
4623     silc_buffer_free(tmp);
4624     silc_buffer_free(fkey);
4625     fkey = NULL;
4626     silc_buffer_free(clidp);
4627   }
4628   silc_hash_table_list_reset(&htl);
4629   silc_buffer_free(chidp);
4630   silc_buffer_free(csidp);
4631 }
4632
4633 /* Returns assembled packets for all channels and users on those channels
4634    from the given ID List. The packets are in the form dictated by the
4635    New Channel and New Channel User payloads. */
4636
4637 void silc_server_announce_get_channels(SilcServer server,
4638                                        SilcIDList id_list,
4639                                        SilcBuffer *channels,
4640                                        SilcBuffer **channel_modes,
4641                                        SilcBuffer *channel_users,
4642                                        SilcBuffer **channel_users_modes,
4643                                        SilcUInt32 *channel_users_modes_c,
4644                                        SilcBuffer **channel_topics,
4645                                        SilcBuffer **channel_invites,
4646                                        SilcBuffer **channel_bans,
4647                                        SilcChannelID ***channel_ids,
4648                                        unsigned long creation_time)
4649 {
4650   SilcIDCacheList list;
4651   SilcIDCacheEntry id_cache;
4652   SilcChannelEntry channel;
4653   unsigned char *cid;
4654   SilcUInt32 id_len;
4655   SilcUInt16 name_len;
4656   int len;
4657   int i = *channel_users_modes_c;
4658   bool announce;
4659
4660   SILC_LOG_DEBUG(("Start"));
4661
4662   /* Go through all channels in the list */
4663   if (silc_idcache_get_all(id_list->channels, &list)) {
4664     if (silc_idcache_list_first(list, &id_cache)) {
4665       while (id_cache) {
4666         channel = (SilcChannelEntry)id_cache->context;
4667
4668         if (creation_time && channel->created < creation_time)
4669           announce = FALSE;
4670         else
4671           announce = TRUE;
4672
4673         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4674         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4675         name_len = strlen(channel->channel_name);
4676
4677         if (announce) {
4678           len = 4 + name_len + id_len + 4;
4679           *channels =
4680             silc_buffer_realloc(*channels,
4681                                 (*channels ? (*channels)->truelen +
4682                                  len : len));
4683           silc_buffer_pull_tail(*channels,
4684                                 ((*channels)->end - (*channels)->data));
4685           silc_buffer_format(*channels,
4686                              SILC_STR_UI_SHORT(name_len),
4687                              SILC_STR_UI_XNSTRING(channel->channel_name,
4688                                                   name_len),
4689                              SILC_STR_UI_SHORT(id_len),
4690                              SILC_STR_UI_XNSTRING(cid, id_len),
4691                              SILC_STR_UI_INT(channel->mode),
4692                              SILC_STR_END);
4693           silc_buffer_pull(*channels, len);
4694         }
4695
4696         if (creation_time && channel->updated < creation_time)
4697           announce = FALSE;
4698         else
4699           announce = TRUE;
4700
4701         if (announce) {
4702           /* Channel user modes */
4703           *channel_users_modes = silc_realloc(*channel_users_modes,
4704                                               sizeof(**channel_users_modes) *
4705                                               (i + 1));
4706           (*channel_users_modes)[i] = NULL;
4707           *channel_modes = silc_realloc(*channel_modes,
4708                                         sizeof(**channel_modes) * (i + 1));
4709           (*channel_modes)[i] = NULL;
4710           *channel_ids = silc_realloc(*channel_ids,
4711                                       sizeof(**channel_ids) * (i + 1));
4712           (*channel_ids)[i] = NULL;
4713           silc_server_announce_get_channel_users(server, channel,
4714                                                  &(*channel_modes)[i],
4715                                                  channel_users,
4716                                                  &(*channel_users_modes)[i]);
4717           (*channel_ids)[i] = channel->id;
4718
4719           /* Channel's topic */
4720           *channel_topics = silc_realloc(*channel_topics,
4721                                          sizeof(**channel_topics) * (i + 1));
4722           (*channel_topics)[i] = NULL;
4723           silc_server_announce_get_channel_topic(server, channel,
4724                                                  &(*channel_topics)[i]);
4725
4726           /* Channel's invite and ban list */
4727           *channel_invites = silc_realloc(*channel_invites,
4728                                           sizeof(**channel_invites) * (i + 1));
4729           (*channel_invites)[i] = NULL;
4730           *channel_bans = silc_realloc(*channel_bans,
4731                                        sizeof(**channel_bans) * (i + 1));
4732           (*channel_bans)[i] = NULL;
4733           silc_server_announce_get_inviteban(server, channel,
4734                                              &(*channel_invites)[i],
4735                                              &(*channel_bans)[i]);
4736
4737           (*channel_users_modes_c)++;
4738           silc_free(cid);
4739
4740           i++;
4741         }
4742
4743         if (!silc_idcache_list_next(list, &id_cache))
4744           break;
4745       }
4746     }
4747
4748     silc_idcache_list_free(list);
4749   }
4750 }
4751
4752 /* This function is used to announce our existing channels to our router
4753    when we've connected to it. This also announces the users on the
4754    channels to the router. If the `creation_time' is non-zero only the
4755    channels that was created after the `creation_time' are announced.
4756    Note that the channel users are still announced even if the `creation_time'
4757    was provided. */
4758
4759 void silc_server_announce_channels(SilcServer server,
4760                                    unsigned long creation_time,
4761                                    SilcSocketConnection remote)
4762 {
4763   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4764   SilcBuffer *channel_users_modes = NULL;
4765   SilcBuffer *channel_topics = NULL;
4766   SilcBuffer *channel_invites = NULL;
4767   SilcBuffer *channel_bans = NULL;
4768   SilcUInt32 channel_users_modes_c = 0;
4769   SilcChannelID **channel_ids = NULL;
4770
4771   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4772
4773   /* Get channels and channel users in local list */
4774   silc_server_announce_get_channels(server, server->local_list,
4775                                     &channels, &channel_modes,
4776                                     &channel_users,
4777                                     &channel_users_modes,
4778                                     &channel_users_modes_c,
4779                                     &channel_topics,
4780                                     &channel_invites,
4781                                     &channel_bans,
4782                                     &channel_ids, creation_time);
4783
4784   /* Get channels and channel users in global list */
4785   if (server->server_type != SILC_SERVER)
4786     silc_server_announce_get_channels(server, server->global_list,
4787                                       &channels, &channel_modes,
4788                                       &channel_users,
4789                                       &channel_users_modes,
4790                                       &channel_users_modes_c,
4791                                       &channel_topics,
4792                                       &channel_invites,
4793                                       &channel_bans,
4794                                       &channel_ids, creation_time);
4795
4796   if (channels) {
4797     silc_buffer_push(channels, channels->data - channels->head);
4798     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4799
4800     /* Send the packet */
4801     silc_server_packet_send(server, remote,
4802                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4803                             channels->data, channels->len,
4804                             FALSE);
4805
4806     silc_buffer_free(channels);
4807   }
4808
4809   if (channel_users) {
4810     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4811     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4812                      channel_users->len);
4813
4814     /* Send the packet */
4815     silc_server_packet_send(server, remote,
4816                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4817                             channel_users->data, channel_users->len,
4818                             FALSE);
4819
4820     silc_buffer_free(channel_users);
4821   }
4822
4823   if (channel_modes) {
4824     int i;
4825
4826     for (i = 0; i < channel_users_modes_c; i++) {
4827       if (!channel_modes[i])
4828         continue;
4829       silc_buffer_push(channel_modes[i],
4830                        channel_modes[i]->data -
4831                        channel_modes[i]->head);
4832       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4833                        channel_modes[i]->len);
4834       silc_server_packet_send_dest(server, remote,
4835                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4836                                    channel_ids[i], SILC_ID_CHANNEL,
4837                                    channel_modes[i]->data,
4838                                    channel_modes[i]->len,
4839                                    FALSE);
4840       silc_buffer_free(channel_modes[i]);
4841     }
4842     silc_free(channel_modes);
4843   }
4844
4845   if (channel_users_modes) {
4846     int i;
4847
4848     for (i = 0; i < channel_users_modes_c; i++) {
4849       if (!channel_users_modes[i])
4850         continue;
4851       silc_buffer_push(channel_users_modes[i],
4852                        channel_users_modes[i]->data -
4853                        channel_users_modes[i]->head);
4854       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4855                        channel_users_modes[i]->len);
4856       silc_server_packet_send_dest(server, remote,
4857                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4858                                    channel_ids[i], SILC_ID_CHANNEL,
4859                                    channel_users_modes[i]->data,
4860                                    channel_users_modes[i]->len,
4861                                    FALSE);
4862       silc_buffer_free(channel_users_modes[i]);
4863     }
4864     silc_free(channel_users_modes);
4865   }
4866
4867   if (channel_topics) {
4868     int i;
4869
4870     for (i = 0; i < channel_users_modes_c; i++) {
4871       if (!channel_topics[i])
4872         continue;
4873
4874       silc_buffer_push(channel_topics[i],
4875                        channel_topics[i]->data -
4876                        channel_topics[i]->head);
4877       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4878                        channel_topics[i]->len);
4879       silc_server_packet_send_dest(server, remote,
4880                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4881                                    channel_ids[i], SILC_ID_CHANNEL,
4882                                    channel_topics[i]->data,
4883                                    channel_topics[i]->len,
4884                                    FALSE);
4885       silc_buffer_free(channel_topics[i]);
4886     }
4887     silc_free(channel_topics);
4888   }
4889
4890   if (channel_invites) {
4891     int i;
4892
4893     for (i = 0; i < channel_users_modes_c; i++) {
4894       if (!channel_invites[i])
4895         continue;
4896
4897       silc_buffer_push(channel_invites[i],
4898                        channel_invites[i]->data -
4899                        channel_invites[i]->head);
4900       SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4901                        channel_invites[i]->len);
4902       silc_server_packet_send_dest(server, remote,
4903                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4904                                    channel_ids[i], SILC_ID_CHANNEL,
4905                                    channel_invites[i]->data,
4906                                    channel_invites[i]->len,
4907                                    FALSE);
4908       silc_buffer_free(channel_invites[i]);
4909     }
4910     silc_free(channel_invites);
4911   }
4912
4913   if (channel_bans) {
4914     int i;
4915
4916     for (i = 0; i < channel_users_modes_c; i++) {
4917       if (!channel_bans[i])
4918         continue;
4919
4920       silc_buffer_push(channel_bans[i],
4921                        channel_bans[i]->data -
4922                        channel_bans[i]->head);
4923       SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4924                        channel_bans[i]->len);
4925       silc_server_packet_send_dest(server, remote,
4926                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4927                                    channel_ids[i], SILC_ID_CHANNEL,
4928                                    channel_bans[i]->data,
4929                                    channel_bans[i]->len,
4930                                    FALSE);
4931       silc_buffer_free(channel_bans[i]);
4932     }
4933     silc_free(channel_bans);
4934   }
4935
4936   silc_free(channel_ids);
4937 }
4938
4939 /* Assembles user list and users mode list from the `channel'. */
4940
4941 bool silc_server_get_users_on_channel(SilcServer server,
4942                                       SilcChannelEntry channel,
4943                                       SilcBuffer *user_list,
4944                                       SilcBuffer *mode_list,
4945                                       SilcUInt32 *user_count)
4946 {
4947   SilcChannelClientEntry chl;
4948   SilcHashTableList htl;
4949   SilcBuffer client_id_list;
4950   SilcBuffer client_mode_list;
4951   SilcBuffer idp;
4952   SilcUInt32 list_count = 0, len = 0;
4953
4954   if (!silc_hash_table_count(channel->user_list))
4955     return FALSE;
4956
4957   silc_hash_table_list(channel->user_list, &htl);
4958   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4959     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4960   silc_hash_table_list_reset(&htl);
4961
4962   client_id_list = silc_buffer_alloc(len);
4963   client_mode_list =
4964     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4965   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4966   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4967
4968   silc_hash_table_list(channel->user_list, &htl);
4969   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4970     /* Client ID */
4971     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4972     silc_buffer_put(client_id_list, idp->data, idp->len);
4973     silc_buffer_pull(client_id_list, idp->len);
4974     silc_buffer_free(idp);
4975
4976     /* Client's mode on channel */
4977     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4978     silc_buffer_pull(client_mode_list, 4);
4979
4980     list_count++;
4981   }
4982   silc_hash_table_list_reset(&htl);
4983   silc_buffer_push(client_id_list,
4984                    client_id_list->data - client_id_list->head);
4985   silc_buffer_push(client_mode_list,
4986                    client_mode_list->data - client_mode_list->head);
4987
4988   *user_list = client_id_list;
4989   *mode_list = client_mode_list;
4990   *user_count = list_count;
4991   return TRUE;
4992 }
4993
4994 /* Saves users and their modes to the `channel'. */
4995
4996 void silc_server_save_users_on_channel(SilcServer server,
4997                                        SilcSocketConnection sock,
4998                                        SilcChannelEntry channel,
4999                                        SilcClientID *noadd,
5000                                        SilcBuffer user_list,
5001                                        SilcBuffer mode_list,
5002                                        SilcUInt32 user_count)
5003 {
5004   int i;
5005   SilcUInt16 idp_len;
5006   SilcUInt32 mode;
5007   SilcClientID *client_id;
5008   SilcClientEntry client;
5009   SilcIDCacheEntry cache;
5010   SilcChannelClientEntry chl;
5011
5012   SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5013                   channel->channel_name));
5014
5015   for (i = 0; i < user_count; i++) {
5016     /* Client ID */
5017     SILC_GET16_MSB(idp_len, user_list->data + 2);
5018     idp_len += 4;
5019     client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5020     silc_buffer_pull(user_list, idp_len);
5021     if (!client_id)
5022       continue;
5023
5024     /* Mode */
5025     SILC_GET32_MSB(mode, mode_list->data);
5026     silc_buffer_pull(mode_list, 4);
5027
5028     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5029       silc_free(client_id);
5030       continue;
5031     }
5032
5033     cache = NULL;
5034
5035     /* Check if we have this client cached already. */
5036     client = silc_idlist_find_client_by_id(server->local_list, client_id,
5037                                            server->server_type, &cache);
5038     if (!client)
5039       client = silc_idlist_find_client_by_id(server->global_list,
5040                                              client_id, server->server_type,
5041                                              &cache);
5042     if (!client) {
5043       /* If router did not find such Client ID in its lists then this must
5044          be bogus client or some router in the net is buggy. */
5045       if (server->server_type != SILC_SERVER) {
5046         silc_free(client_id);
5047         continue;
5048       }
5049
5050       /* We don't have that client anywhere, add it. The client is added
5051          to global list since server didn't have it in the lists so it must be
5052          global. */
5053       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5054                                       silc_id_dup(client_id, SILC_ID_CLIENT),
5055                                       sock->user_data, NULL, 0);
5056       if (!client) {
5057         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5058         silc_free(client_id);
5059         continue;
5060       }
5061
5062       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5063     }
5064
5065     if (cache)
5066       cache->expire = 0;
5067     silc_free(client_id);
5068
5069     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5070       SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5071                       "%s", channel->channel_name));
5072       continue;
5073     }
5074
5075     if (!silc_server_client_on_channel(client, channel, &chl)) {
5076       /* Client was not on the channel, add it. */
5077       chl = silc_calloc(1, sizeof(*chl));
5078       chl->client = client;
5079       chl->mode = mode;
5080       chl->channel = channel;
5081       silc_hash_table_add(channel->user_list, chl->client, chl);
5082       silc_hash_table_add(client->channels, chl->channel, chl);
5083       channel->user_count++;
5084     } else {
5085       /* Update mode */
5086       chl->mode = mode;
5087     }
5088   }
5089 }
5090
5091 /* Saves channels and channels user modes to the `client'.  Removes
5092    the client from those channels that are not sent in the list but
5093    it has joined. */
5094
5095 void silc_server_save_user_channels(SilcServer server,
5096                                     SilcSocketConnection sock,
5097                                     SilcClientEntry client,
5098                                     SilcBuffer channels,
5099                                     SilcBuffer channels_user_modes)
5100 {
5101   SilcDList ch;
5102   SilcUInt32 *chumodes;
5103   SilcChannelPayload entry;
5104   SilcChannelEntry channel;
5105   SilcChannelID *channel_id;
5106   SilcChannelClientEntry chl;
5107   SilcHashTable ht = NULL;
5108   SilcHashTableList htl;
5109   char *name;
5110   int i = 0;
5111
5112   if (!channels || !channels_user_modes ||
5113       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5114     goto out;
5115
5116   ch = silc_channel_payload_parse_list(channels->data, channels->len);
5117   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5118                                &chumodes)) {
5119     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5120                                NULL, NULL, NULL, TRUE);
5121     silc_dlist_start(ch);
5122     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5123       /* Check if we have this channel, and add it if we don't have it.
5124          Also add the client on the channel unless it is there already. */
5125       channel_id = silc_channel_get_id_parse(entry);
5126       channel = silc_idlist_find_channel_by_id(server->local_list,
5127                                                channel_id, NULL);
5128       if (!channel)
5129         channel = silc_idlist_find_channel_by_id(server->global_list,
5130                                                  channel_id, NULL);
5131       if (!channel) {
5132         if (server->server_type != SILC_SERVER) {
5133           silc_free(channel_id);
5134           i++;
5135           continue;
5136         }
5137
5138         /* We don't have that channel anywhere, add it. */
5139         name = silc_channel_get_name(entry, NULL);
5140         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5141                                           channel_id, server->router,
5142                                           NULL, NULL, 0);
5143         if (!channel) {
5144           silc_free(channel_id);
5145           i++;
5146           continue;
5147         }
5148         channel_id = NULL;
5149       }
5150
5151       channel->mode = silc_channel_get_mode(entry);
5152
5153       /* Add the client on the channel */
5154       if (!silc_server_client_on_channel(client, channel, &chl)) {
5155         chl = silc_calloc(1, sizeof(*chl));
5156         chl->client = client;
5157         chl->mode = chumodes[i++];
5158         chl->channel = channel;
5159         silc_hash_table_add(channel->user_list, chl->client, chl);
5160         silc_hash_table_add(client->channels, chl->channel, chl);
5161         channel->user_count++;
5162       } else {
5163         /* Update mode */
5164         chl->mode = chumodes[i++];
5165       }
5166
5167       silc_hash_table_add(ht, channel, channel);
5168       silc_free(channel_id);
5169     }
5170     silc_channel_payload_list_free(ch);
5171     silc_free(chumodes);
5172   }
5173
5174  out:
5175   /* Go through the list again and remove client from channels that
5176      are no part of the list. */
5177   if (ht) {
5178     silc_hash_table_list(client->channels, &htl);
5179     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5180       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5181         silc_hash_table_del(chl->channel->user_list, chl->client);
5182         silc_hash_table_del(chl->client->channels, chl->channel);
5183         silc_free(chl);
5184       }
5185     }
5186     silc_hash_table_list_reset(&htl);
5187     silc_hash_table_free(ht);
5188   } else {
5189     silc_hash_table_list(client->channels, &htl);
5190     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5191       silc_hash_table_del(chl->channel->user_list, chl->client);
5192       silc_hash_table_del(chl->client->channels, chl->channel);
5193       silc_free(chl);
5194     }
5195     silc_hash_table_list_reset(&htl);
5196   }
5197 }
5198
5199 /* Lookups route to the client indicated by the `id_data'. The connection
5200    object and internal data object is returned. Returns NULL if route
5201    could not be found to the client. If the `client_id' is specified then
5202    it is used and the `id_data' is ignored. */
5203
5204 SilcSocketConnection
5205 silc_server_get_client_route(SilcServer server,
5206                              unsigned char *id_data,
5207                              SilcUInt32 id_len,
5208                              SilcClientID *client_id,
5209                              SilcIDListData *idata,
5210                              SilcClientEntry *client_entry)
5211 {
5212   SilcClientID *id;
5213   SilcClientEntry client;
5214
5215   SILC_LOG_DEBUG(("Start"));
5216
5217   if (client_entry)
5218     *client_entry = NULL;
5219
5220   /* Decode destination Client ID */
5221   if (!client_id) {
5222     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5223     if (!id) {
5224       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5225       return NULL;
5226     }
5227   } else {
5228     id = silc_id_dup(client_id, SILC_ID_CLIENT);
5229   }
5230
5231   /* If the destination belongs to our server we don't have to route
5232      the packet anywhere but to send it to the local destination. */
5233   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5234   if (client) {
5235     silc_free(id);
5236
5237     /* If we are router and the client has router then the client is in
5238        our cell but not directly connected to us. */
5239     if (server->server_type == SILC_ROUTER && client->router) {
5240       /* We are of course in this case the client's router thus the route
5241          to the client is the server who owns the client. So, we will send
5242          the packet to that server. */
5243       if (idata)
5244         *idata = (SilcIDListData)client->router;
5245       return client->router->connection;
5246     }
5247
5248     /* Seems that client really is directly connected to us */
5249     if (idata)
5250       *idata = (SilcIDListData)client;
5251     if (client_entry)
5252       *client_entry = client;
5253     return client->connection;
5254   }
5255
5256   /* Destination belongs to someone not in this server. If we are normal
5257      server our action is to send the packet to our router. */
5258   if (server->server_type != SILC_ROUTER && !server->standalone) {
5259     silc_free(id);
5260     if (idata)
5261       *idata = (SilcIDListData)server->router;
5262     return SILC_PRIMARY_ROUTE(server);
5263   }
5264
5265   /* We are router and we will perform route lookup for the destination
5266      and send the packet to fastest route. */
5267   if (server->server_type == SILC_ROUTER && !server->standalone) {
5268     /* Check first that the ID is valid */
5269     client = silc_idlist_find_client_by_id(server->global_list, id,
5270                                            TRUE, NULL);
5271     if (client) {
5272       SilcSocketConnection dst_sock;
5273
5274       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5275
5276       silc_free(id);
5277       if (idata)
5278         *idata = (SilcIDListData)dst_sock->user_data;
5279       return dst_sock;
5280     }
5281   }
5282
5283   silc_free(id);
5284   return NULL;
5285 }
5286
5287 /* Encodes and returns channel list of channels the `client' has joined.
5288    Secret channels are not put to the list. */
5289
5290 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5291                                                SilcClientEntry client,
5292                                                bool get_private,
5293                                                bool get_secret,
5294                                                SilcBuffer *user_mode_list)
5295 {
5296   SilcBuffer buffer = NULL;
5297   SilcChannelEntry channel;
5298   SilcChannelClientEntry chl;
5299   SilcHashTableList htl;
5300   unsigned char *cid;
5301   SilcUInt32 id_len;
5302   SilcUInt16 name_len;
5303   int len;
5304
5305   if (user_mode_list)
5306     *user_mode_list = NULL;
5307
5308   silc_hash_table_list(client->channels, &htl);
5309   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5310     channel = chl->channel;
5311
5312     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5313       continue;
5314     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5315       continue;
5316
5317     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5318     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5319     name_len = strlen(channel->channel_name);
5320
5321     len = 4 + name_len + id_len + 4;
5322     buffer = silc_buffer_realloc(buffer,
5323                                  (buffer ? buffer->truelen + len : len));
5324     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5325     silc_buffer_format(buffer,
5326                        SILC_STR_UI_SHORT(name_len),
5327                        SILC_STR_UI_XNSTRING(channel->channel_name,
5328                                             name_len),
5329                        SILC_STR_UI_SHORT(id_len),
5330                        SILC_STR_UI_XNSTRING(cid, id_len),
5331                        SILC_STR_UI_INT(chl->channel->mode),
5332                        SILC_STR_END);
5333     silc_buffer_pull(buffer, len);
5334     silc_free(cid);
5335
5336     if (user_mode_list) {
5337       *user_mode_list = silc_buffer_realloc(*user_mode_list,
5338                                             (*user_mode_list ?
5339                                              (*user_mode_list)->truelen + 4 :
5340                                              4));
5341       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5342                                               (*user_mode_list)->data));
5343       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5344       silc_buffer_pull(*user_mode_list, 4);
5345     }
5346   }
5347   silc_hash_table_list_reset(&htl);
5348
5349   if (buffer)
5350     silc_buffer_push(buffer, buffer->data - buffer->head);
5351   if (user_mode_list && *user_mode_list)
5352     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5353                                        (*user_mode_list)->head));
5354
5355   return buffer;
5356 }
5357
5358 /* Timeout callback for unsuccessful rekey.  The rekey did not go through
5359    for some reason. */
5360
5361 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5362 {
5363   SilcServerRekeyInternalContext *ctx = context;
5364   SilcServer server = app_context;
5365   SilcSocketConnection sock = ctx->sock;
5366
5367   SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5368                   sock->hostname, sock->port,
5369                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5370                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5371                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5372                    "Router")));
5373
5374   SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5375                     sock->hostname, sock->port,
5376                     (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5377                      sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5378                      sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5379                      "Router")));
5380
5381   if (sock->protocol) {
5382     silc_protocol_cancel(sock->protocol, server->schedule);
5383     silc_protocol_free(sock->protocol);
5384     sock->protocol = NULL;
5385   }
5386   if (ctx->packet)
5387     silc_packet_context_free(ctx->packet);
5388   if (ctx->ske)
5389     silc_ske_free(ctx->ske);
5390   silc_socket_free(sock);
5391   silc_free(ctx);
5392
5393   /* Disconnect since we failed to rekey, the keys are probably wrong. */
5394   silc_server_disconnect_remote(server, sock,
5395                                 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5396
5397   /* Reconnect */
5398   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5399     silc_server_create_connections(server);
5400 }
5401
5402 /* A timeout callback for the re-key. We will be the initiator of the
5403    re-key protocol. */
5404
5405 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5406 {
5407   SilcServer server = app_context;
5408   SilcSocketConnection sock = (SilcSocketConnection)context;
5409   SilcIDListData idata = (SilcIDListData)sock->user_data;
5410   SilcProtocol protocol;
5411   SilcServerRekeyInternalContext *proto_ctx;
5412
5413   if (!idata)
5414     return;
5415
5416   /* Do not execute rekey with disabled connections, as it would not
5417      go through anyway. */
5418   if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5419     return;
5420
5421   /* If rekey protocol is active already wait for it to finish */
5422   if (sock->protocol && sock->protocol->protocol &&
5423       sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5424     return;
5425
5426   /* If any other protocol is active do not start this protocol yet. */
5427   if (sock->protocol) {
5428     SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5429     silc_schedule_task_add(server->schedule, sock->sock,
5430                            silc_server_rekey_callback,
5431                            sock, 60, 0, SILC_TASK_TIMEOUT,
5432                            SILC_TASK_PRI_NORMAL);
5433     return;
5434   }
5435
5436   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5437                   sock->hostname, sock->port,
5438                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5439                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5440                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5441                    "Router")));
5442
5443   /* Allocate internal protocol context. This is sent as context
5444      to the protocol. */
5445   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5446   proto_ctx->server = (void *)server;
5447   proto_ctx->sock = silc_socket_dup(sock);
5448   proto_ctx->responder = FALSE;
5449   proto_ctx->pfs = idata->rekey->pfs;
5450
5451   /* Perform rekey protocol. Will call the final callback after the
5452      protocol is over. */
5453   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5454                       &protocol, proto_ctx, silc_server_rekey_final);
5455   sock->protocol = protocol;
5456
5457   /* Register timeout callback in case the rekey does not go through. */
5458   proto_ctx->timeout_task =
5459     silc_schedule_task_add(server->schedule, sock->sock,
5460                            silc_server_rekey_timeout,
5461                            proto_ctx,
5462                            (idata->rekey->timeout >
5463                             server->config->key_exchange_timeout ?
5464                             idata->rekey->timeout :
5465                             server->config->key_exchange_timeout * 4), 0,
5466                            SILC_TASK_TIMEOUT,
5467                            SILC_TASK_PRI_LOW);
5468
5469   /* Run the protocol */
5470   silc_protocol_execute(protocol, server->schedule, 0, 0);
5471 }
5472
5473 /* The final callback for the REKEY protocol. This will actually take the
5474    new key material into use. */
5475
5476 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5477 {
5478   SilcProtocol protocol = (SilcProtocol)context;
5479   SilcServerRekeyInternalContext *ctx =
5480     (SilcServerRekeyInternalContext *)protocol->context;
5481   SilcServer server = (SilcServer)ctx->server;
5482   SilcSocketConnection sock = ctx->sock;
5483   SilcIDListData idata = (SilcIDListData)sock->user_data;
5484
5485   if (ctx->timeout_task)
5486     silc_schedule_task_del(server->schedule, ctx->timeout_task);
5487
5488   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5489       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5490     /* Error occured during protocol */
5491     SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5492                     "%s (%s)", sock->hostname, sock->ip));
5493     silc_protocol_cancel(protocol, server->schedule);
5494     silc_protocol_free(protocol);
5495     sock->protocol = NULL;
5496     if (ctx->packet)
5497       silc_packet_context_free(ctx->packet);
5498     if (ctx->ske)
5499       silc_ske_free(ctx->ske);
5500     silc_socket_free(sock);
5501     silc_free(ctx);
5502     silc_server_disconnect_remote(server, sock,
5503                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5504
5505     /* Reconnect */
5506     if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5507       silc_server_create_connections(server);
5508     return;
5509   }
5510
5511   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5512                   sock->hostname, sock->port,
5513                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5514                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5515                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5516                    "Router")));
5517
5518   /* Purge the outgoing data queue to assure that all rekey packets really
5519      go to the network before we quit the protocol. */
5520   silc_server_packet_queue_purge(server, sock);
5521
5522   /* Re-register re-key timeout */
5523   if (ctx->responder == FALSE)
5524     silc_schedule_task_add(server->schedule, sock->sock,
5525                            silc_server_rekey_callback,
5526                            sock, idata->rekey->timeout, 0,
5527                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5528
5529   /* Cleanup */
5530   silc_protocol_free(protocol);
5531   sock->protocol = NULL;
5532   if (ctx->packet)
5533     silc_packet_context_free(ctx->packet);
5534   if (ctx->ske)
5535     silc_ske_free(ctx->ske);
5536   silc_socket_free(sock);
5537   silc_free(ctx);
5538 }
5539
5540 /* Task callback used to retrieve network statistical information from
5541    router server once in a while. */
5542
5543 SILC_TASK_CALLBACK(silc_server_get_stats)
5544 {
5545   SilcServer server = (SilcServer)context;
5546   SilcBuffer idp, packet;
5547
5548   if (!server->standalone) {
5549     SILC_LOG_DEBUG(("Retrieving stats from router"));
5550     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5551     packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5552                                             ++server->cmd_ident, 1,
5553                                             1, idp->data, idp->len);
5554     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5555                             SILC_PACKET_COMMAND, 0, packet->data,
5556                             packet->len, FALSE);
5557     silc_buffer_free(packet);
5558     silc_buffer_free(idp);
5559   }
5560
5561   silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5562                          server, 120, 0, SILC_TASK_TIMEOUT,
5563                          SILC_TASK_PRI_LOW);
5564 }