06372f04a245931e3a0640c470eb918ce66abfa5
[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 20 seconds for the backup router to appear. */
1921           silc_schedule_task_add(server->schedule, 0,
1922                                  silc_server_backup_router_wait,
1923                                  (void *)server, 20, 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 20 seconds for the backup router to appear. */
2099           silc_schedule_task_add(server->schedule, 0,
2100                                  silc_server_backup_router_wait,
2101                                  (void *)server, 20, 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         /* If backup then mark that resuming will not be allowed */
2294         if (server->server_type == SILC_ROUTER && !server->backup_router &&
2295             sock->type == SILC_SOCKET_TYPE_SERVER) {
2296           SilcServerEntry server_entry = sock->user_data;
2297           if (server_entry->server_type == SILC_BACKUP_ROUTER)
2298             server->backup_closed = TRUE;
2299         }
2300
2301         silc_server_free_sock_user_data(server, sock, NULL);
2302       }
2303       SILC_SET_DISCONNECTING(sock);
2304       silc_server_close_connection(server, sock);
2305     }
2306     return;
2307   }
2308
2309   /* Packet receiving */
2310
2311   /* Read some data from connection */
2312   ret = silc_packet_receive(sock);
2313   if (ret < 0) {
2314
2315     if (ret == -1) {
2316       SILC_LOG_ERROR(("Error receiving packet from connection "
2317                       "%s:%d [%s] %s", sock->hostname, sock->port,
2318                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2319                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2320                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2321                        "Router"), strerror(errno)));
2322
2323       if (sock->user_data) {
2324         /* If backup then mark that resuming will not be allowed */
2325         if (server->server_type == SILC_ROUTER && !server->backup_router &&
2326             sock->type == SILC_SOCKET_TYPE_SERVER) {
2327           SilcServerEntry server_entry = sock->user_data;
2328           if (server_entry->server_type == SILC_BACKUP_ROUTER)
2329             server->backup_closed = TRUE;
2330         }
2331
2332         silc_server_free_sock_user_data(server, sock, NULL);
2333       }
2334       SILC_SET_DISCONNECTING(sock);
2335       silc_server_close_connection(server, sock);
2336     }
2337     return;
2338   }
2339
2340   /* EOF */
2341   if (ret == 0) {
2342     SILC_LOG_DEBUG(("Read EOF"));
2343
2344     /* If connection is disconnecting already we will finally
2345        close the connection */
2346     if (SILC_IS_DISCONNECTING(sock)) {
2347       if (sock->user_data)
2348         silc_server_free_sock_user_data(server, sock, NULL);
2349       silc_server_close_connection(server, sock);
2350       return;
2351     }
2352
2353     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2354
2355     if (sock->user_data) {
2356       char tmp[128];
2357
2358       /* If backup disconnected then mark that resuming will not be allowed */
2359       if (server->server_type == SILC_ROUTER && !server->backup_router &&
2360           sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2361         SilcServerEntry server_entry = sock->user_data;
2362         if (server_entry->server_type == SILC_BACKUP_ROUTER)
2363           server->backup_closed = TRUE;
2364       }
2365
2366       if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2367         silc_server_free_sock_user_data(server, sock, tmp);
2368       else
2369         silc_server_free_sock_user_data(server, sock, NULL);
2370     } else if (server->router_conn && server->router_conn->sock == sock &&
2371                !server->router && server->standalone) {
2372       silc_server_create_connections(server);
2373     }
2374
2375     SILC_SET_DISCONNECTING(sock);
2376     silc_server_close_connection(server, sock);
2377     return;
2378   }
2379
2380   /* If connection is disconnecting or disconnected we will ignore
2381      what we read. */
2382   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2383     SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2384     return;
2385   }
2386
2387   /* Get keys and stuff from ID entry */
2388   idata = (SilcIDListData)sock->user_data;
2389   if (idata) {
2390     cipher = idata->receive_key;
2391     hmac = idata->hmac_receive;
2392     sequence = idata->psn_receive;
2393   }
2394
2395   /* Then, process the packet. This will call the parser that will then
2396      decrypt and parse the packet. */
2397
2398   local_is_router = (server->server_type == SILC_ROUTER);
2399
2400   /* If socket connection is our primary, we are backup and we are doing
2401      backup resuming, we won't process the packet as being a router
2402      (affects channel message decryption). */
2403   if (server->backup_router && SILC_SERVER_IS_BACKUP(sock) &&
2404       SILC_PRIMARY_ROUTE(server) == sock)
2405     local_is_router = FALSE;
2406
2407   ret = silc_packet_receive_process(sock, local_is_router,
2408                                     cipher, hmac, sequence,
2409                                     silc_server_packet_parse, server);
2410
2411   /* If processing failed the connection is closed. */
2412   if (!ret) {
2413     /* On packet processing errors we may close our primary router
2414        connection but won't become primary router if we are the backup
2415        since this is local error condition. */
2416     if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2417       server->backup_noswitch = TRUE;
2418
2419     if (sock->user_data) {
2420       /* If we are router and backup errorred then mark that resuming
2421          will not be allowed */
2422       if (server->server_type == SILC_ROUTER && !server->backup_router &&
2423           sock->type == SILC_SOCKET_TYPE_SERVER) {
2424         SilcServerEntry server_entry = sock->user_data;
2425         if (server_entry->server_type == SILC_BACKUP_ROUTER)
2426           server->backup_closed = TRUE;
2427       }
2428
2429       silc_server_free_sock_user_data(server, sock, NULL);
2430     }
2431     SILC_SET_DISCONNECTING(sock);
2432     silc_server_close_connection(server, sock);
2433   }
2434 }
2435
2436 /* Parses whole packet, received earlier. */
2437
2438 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2439 {
2440   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2441   SilcServer server = (SilcServer)parse_ctx->context;
2442   SilcSocketConnection sock = parse_ctx->sock;
2443   SilcPacketContext *packet = parse_ctx->packet;
2444   SilcIDListData idata = (SilcIDListData)sock->user_data;
2445   int ret;
2446
2447   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2448     SILC_LOG_DEBUG(("Connection is disconnected"));
2449     goto out;
2450   }
2451
2452   server->stat.packets_received++;
2453
2454   /* Parse the packet */
2455   if (parse_ctx->normal)
2456     ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2457   else
2458     ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2459
2460   /* If entry is disabled ignore what we got. */
2461   if (idata && idata->status & SILC_IDLIST_STATUS_DISABLED &&
2462       ret != SILC_PACKET_HEARTBEAT && ret != SILC_PACKET_RESUME_ROUTER &&
2463       ret != SILC_PACKET_REKEY && ret != SILC_PACKET_REKEY_DONE) {
2464     SILC_LOG_DEBUG(("Connection is disabled"));
2465     goto out;
2466   }
2467
2468   if (ret == SILC_PACKET_NONE) {
2469     SILC_LOG_DEBUG(("Error parsing packet"));
2470     goto out;
2471   }
2472
2473   /* Check that the the current client ID is same as in the client's packet. */
2474   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2475     SilcClientEntry client = (SilcClientEntry)sock->user_data;
2476     if (client && client->id && packet->src_id) {
2477       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2478                                 packet->src_id_type);
2479       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2480         silc_free(id);
2481         SILC_LOG_DEBUG(("Packet source is not same as sender"));
2482         goto out;
2483       }
2484       silc_free(id);
2485     }
2486   }
2487
2488   if (server->server_type == SILC_ROUTER) {
2489     /* Route the packet if it is not destined to us. Other ID types but
2490        server are handled separately after processing them. */
2491     if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2492         packet->dst_id_type == SILC_ID_SERVER &&
2493         sock->type != SILC_SOCKET_TYPE_CLIENT &&
2494         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2495
2496       /* Route the packet to fastest route for the destination ID */
2497       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2498                                 packet->dst_id_type);
2499       if (!id)
2500         goto out;
2501       silc_server_packet_route(server,
2502                                silc_server_route_get(server, id,
2503                                                      packet->dst_id_type),
2504                                packet);
2505       silc_free(id);
2506       goto out;
2507     }
2508   }
2509
2510   /* Parse the incoming packet type */
2511   silc_server_packet_parse_type(server, sock, packet);
2512
2513   /* Broadcast packet if it is marked as broadcast packet and it is
2514      originated from router and we are router. */
2515   if (server->server_type == SILC_ROUTER &&
2516       sock->type == SILC_SOCKET_TYPE_ROUTER &&
2517       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2518     /* Broadcast to our primary route */
2519     silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2520
2521     /* If we have backup routers then we need to feed all broadcast
2522        data to those servers. */
2523     silc_server_backup_broadcast(server, sock, packet);
2524   }
2525
2526  out:
2527   silc_packet_context_free(packet);
2528   silc_free(parse_ctx);
2529 }
2530
2531 /* Parser callback called by silc_packet_receive_process. This merely
2532    registers timeout that will handle the actual parsing when appropriate. */
2533
2534 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2535                               void *context)
2536 {
2537   SilcServer server = (SilcServer)context;
2538   SilcSocketConnection sock = parser_context->sock;
2539   SilcIDListData idata = (SilcIDListData)sock->user_data;
2540   bool ret;
2541
2542   if (idata)
2543     idata->psn_receive = parser_context->packet->sequence + 1;
2544
2545   /* If protocol for this connection is key exchange or rekey then we'll
2546      process all packets synchronously, since there might be packets in
2547      queue that we are not able to decrypt without first processing the
2548      packets before them. */
2549   if (sock->protocol && sock->protocol->protocol &&
2550       (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2551        sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2552     silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2553                                   parser_context);
2554
2555     if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2556       SILC_LOG_DEBUG(("Connection is disconnected"));
2557       return FALSE;
2558     }
2559
2560     /* Reprocess data since we'll return FALSE here.  This is because
2561        the idata->receive_key might have become valid in the last packet
2562        and we want to call this processor with valid cipher. */
2563     if (idata)
2564       ret = silc_packet_receive_process(
2565                                   sock, server->server_type == SILC_ROUTER,
2566                                   idata->receive_key,
2567                                   idata->hmac_receive, idata->psn_receive,
2568                                   silc_server_packet_parse, server);
2569     else
2570       ret = silc_packet_receive_process(
2571                                   sock, server->server_type == SILC_ROUTER,
2572                                   NULL, NULL, 0,
2573                                   silc_server_packet_parse, server);
2574
2575     if (!ret) {
2576       /* On packet processing errors we may close our primary router
2577          connection but won't become primary router if we are the backup
2578          since this is local error condition. */
2579       if (SILC_PRIMARY_ROUTE(server) == sock && server->backup_router)
2580         server->backup_noswitch = TRUE;
2581
2582       if (sock->user_data)
2583         silc_server_free_sock_user_data(server, sock, NULL);
2584       SILC_SET_DISCONNECTING(sock);
2585       silc_server_close_connection(server, sock);
2586     }
2587
2588     return FALSE;
2589   }
2590
2591   switch (sock->type) {
2592   case SILC_SOCKET_TYPE_UNKNOWN:
2593   case SILC_SOCKET_TYPE_CLIENT:
2594     /* Parse the packet with timeout */
2595     silc_schedule_task_add(server->schedule, sock->sock,
2596                            silc_server_packet_parse_real,
2597                            (void *)parser_context, 0, 100000,
2598                            SILC_TASK_TIMEOUT,
2599                            SILC_TASK_PRI_NORMAL);
2600     break;
2601   case SILC_SOCKET_TYPE_SERVER:
2602   case SILC_SOCKET_TYPE_ROUTER:
2603     /* Packets from servers are parsed immediately */
2604     silc_server_packet_parse_real(server->schedule, server, 0, sock->sock,
2605                                   parser_context);
2606     break;
2607   }
2608
2609   return TRUE;
2610 }
2611
2612 /* Parses the packet type and calls what ever routines the packet type
2613    requires. This is done for all incoming packets. */
2614
2615 void silc_server_packet_parse_type(SilcServer server,
2616                                    SilcSocketConnection sock,
2617                                    SilcPacketContext *packet)
2618 {
2619   SilcPacketType type = packet->type;
2620   SilcIDListData idata = (SilcIDListData)sock->user_data;
2621
2622   SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2623                   silc_get_packet_name(type), packet->flags));
2624
2625   /* Parse the packet type */
2626   switch (type) {
2627   case SILC_PACKET_DISCONNECT:
2628     {
2629       SilcStatus status;
2630       char *message = NULL;
2631
2632       if (packet->flags & SILC_PACKET_FLAG_LIST)
2633         break;
2634       if (packet->buffer->len < 1)
2635         break;
2636
2637       status = (SilcStatus)packet->buffer->data[0];
2638       if (packet->buffer->len > 1 &&
2639           silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2640         message = silc_memdup(packet->buffer->data + 1,
2641                               packet->buffer->len - 1);
2642
2643       SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2644                      sock->ip, sock->hostname,
2645                      silc_get_status_message(status), status,
2646                      message ? message : ""));
2647       silc_free(message);
2648
2649       /* Do not switch to backup in case of error */
2650       server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
2651
2652       /* If backup disconnected then mark that resuming will not be allowed */
2653       if (server->server_type == SILC_ROUTER && !server->backup_router &&
2654           sock->type == SILC_SOCKET_TYPE_SERVER && sock->user_data) {
2655         SilcServerEntry server_entry = sock->user_data;
2656         if (server_entry->server_type == SILC_BACKUP_ROUTER)
2657           server->backup_closed = TRUE;
2658       }
2659
2660       /* Handle the disconnection from our end too */
2661       if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2662         silc_server_free_sock_user_data(server, sock, NULL);
2663       SILC_SET_DISCONNECTING(sock);
2664       silc_server_close_connection(server, sock);
2665       server->backup_noswitch = FALSE;
2666     }
2667     break;
2668
2669   case SILC_PACKET_SUCCESS:
2670     /*
2671      * Success received for something. For now we can have only
2672      * one protocol for connection executing at once hence this
2673      * success message is for whatever protocol is executing currently.
2674      */
2675     if (packet->flags & SILC_PACKET_FLAG_LIST)
2676       break;
2677     if (sock->protocol)
2678       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2679     break;
2680
2681   case SILC_PACKET_FAILURE:
2682     /*
2683      * Failure received for something. For now we can have only
2684      * one protocol for connection executing at once hence this
2685      * failure message is for whatever protocol is executing currently.
2686      */
2687     if (packet->flags & SILC_PACKET_FLAG_LIST)
2688       break;
2689
2690     /* Check for failure START_USE from backup router */
2691     if (server->server_type == SILC_SERVER &&
2692         server->backup_primary && packet->buffer->len == 4) {
2693       SilcUInt32 type;
2694       SILC_GET32_MSB(type, packet->buffer->data);
2695       if (type == SILC_SERVER_BACKUP_START_USE) {
2696         /* Attempt to reconnect to primary */
2697         SILC_LOG_DEBUG(("Received failed START_USE from backup %s", sock->ip));
2698
2699         /* Default action is to disconnect from backup and reconnect to
2700            primary.  Since this failure can happen during switching to
2701            backup (backup might have not noticed the primary going down yet),
2702            we will wait a while and keep sending START_USE to backup.
2703            Only after that we'll give up. */
2704         if (server->router == sock->user_data &&
2705             (time(0) - server->router_connect) < 30) {
2706           SILC_LOG_DEBUG(("Resending START_USE to backup router"));
2707           silc_server_backup_send_start_use(server, sock, FALSE);
2708           break;
2709         }
2710
2711         /* If backup is our primary, disconnect now. */
2712         if (server->router == sock->user_data) {
2713           if (sock->user_data)
2714             silc_server_free_sock_user_data(server, sock, NULL);
2715           SILC_SET_DISCONNECTING(sock);
2716           silc_server_close_connection(server, sock);
2717         }
2718
2719         /* Reconnect */
2720         silc_server_create_connections(server);
2721       }
2722     }
2723
2724     /* Execute protocol */
2725     if (sock->protocol) {
2726       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
2727       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2728       break;
2729     }
2730     break;
2731
2732   case SILC_PACKET_REJECT:
2733     if (packet->flags & SILC_PACKET_FLAG_LIST)
2734       break;
2735     return;
2736     break;
2737
2738   case SILC_PACKET_NOTIFY:
2739     /*
2740      * Received notify packet. Server can receive notify packets from
2741      * router. Server then relays the notify messages to clients if needed.
2742      */
2743     if (packet->flags & SILC_PACKET_FLAG_LIST)
2744       silc_server_notify_list(server, sock, packet);
2745     else
2746       silc_server_notify(server, sock, packet);
2747     break;
2748
2749     /*
2750      * Channel packets
2751      */
2752   case SILC_PACKET_CHANNEL_MESSAGE:
2753     /*
2754      * Received channel message. Channel messages are special packets
2755      * (although probably most common ones) thus they are handled
2756      * specially.
2757      */
2758     if (packet->flags & SILC_PACKET_FLAG_LIST)
2759       break;
2760     idata->last_receive = time(NULL);
2761     silc_server_channel_message(server, sock, packet);
2762     break;
2763
2764   case SILC_PACKET_CHANNEL_KEY:
2765     /*
2766      * Received key for channel. As channels are created by the router
2767      * the keys are as well. We will distribute the key to all of our
2768      * locally connected clients on the particular channel. Router
2769      * never receives this channel and thus is ignored.
2770      */
2771     if (packet->flags & SILC_PACKET_FLAG_LIST)
2772       break;
2773     silc_server_channel_key(server, sock, packet);
2774     break;
2775
2776     /*
2777      * Command packets
2778      */
2779   case SILC_PACKET_COMMAND:
2780     /*
2781      * Recived command. Processes the command request and allocates the
2782      * command context and calls the command.
2783      */
2784     if (packet->flags & SILC_PACKET_FLAG_LIST)
2785       break;
2786     silc_server_command_process(server, sock, packet);
2787     break;
2788
2789   case SILC_PACKET_COMMAND_REPLY:
2790     /*
2791      * Received command reply packet. Received command reply to command. It
2792      * may be reply to command sent by us or reply to command sent by client
2793      * that we've routed further.
2794      */
2795     if (packet->flags & SILC_PACKET_FLAG_LIST)
2796       break;
2797     silc_server_command_reply(server, sock, packet);
2798     break;
2799
2800     /*
2801      * Private Message packets
2802      */
2803   case SILC_PACKET_PRIVATE_MESSAGE:
2804     /*
2805      * Received private message packet. The packet is coming from either
2806      * client or server.
2807      */
2808     if (packet->flags & SILC_PACKET_FLAG_LIST)
2809       break;
2810     idata->last_receive = time(NULL);
2811     silc_server_private_message(server, sock, packet);
2812     break;
2813
2814   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2815     /*
2816      * Private message key packet.
2817      */
2818     if (packet->flags & SILC_PACKET_FLAG_LIST)
2819       break;
2820     silc_server_private_message_key(server, sock, packet);
2821     break;
2822
2823     /*
2824      * Key Exchange protocol packets
2825      */
2826   case SILC_PACKET_KEY_EXCHANGE:
2827     if (packet->flags & SILC_PACKET_FLAG_LIST)
2828       break;
2829
2830     if (sock->protocol && sock->protocol->protocol &&
2831         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2832       SilcServerKEInternalContext *proto_ctx =
2833         (SilcServerKEInternalContext *)sock->protocol->context;
2834
2835       proto_ctx->packet = silc_packet_context_dup(packet);
2836
2837       /* Let the protocol handle the packet */
2838       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2839     } else {
2840       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2841                       "protocol active (%s:%d [%s]).", sock->hostname,
2842                       sock->port,
2843                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2844                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2845                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2846                        "Router")));
2847     }
2848     break;
2849
2850   case SILC_PACKET_KEY_EXCHANGE_1:
2851     if (packet->flags & SILC_PACKET_FLAG_LIST)
2852       break;
2853
2854     if (sock->protocol && sock->protocol->protocol &&
2855         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2856          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2857
2858       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2859         SilcServerRekeyInternalContext *proto_ctx =
2860           (SilcServerRekeyInternalContext *)sock->protocol->context;
2861
2862         if (proto_ctx->packet)
2863           silc_packet_context_free(proto_ctx->packet);
2864
2865         proto_ctx->packet = silc_packet_context_dup(packet);
2866
2867         /* Let the protocol handle the packet */
2868         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2869       } else {
2870         SilcServerKEInternalContext *proto_ctx =
2871           (SilcServerKEInternalContext *)sock->protocol->context;
2872
2873         if (proto_ctx->packet)
2874           silc_packet_context_free(proto_ctx->packet);
2875
2876         proto_ctx->packet = silc_packet_context_dup(packet);
2877         proto_ctx->dest_id_type = packet->src_id_type;
2878         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2879                                             packet->src_id_type);
2880         if (!proto_ctx->dest_id)
2881           break;
2882
2883         /* Let the protocol handle the packet */
2884         silc_protocol_execute(sock->protocol, server->schedule,
2885                               0, 100000);
2886       }
2887     } else {
2888       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2889                       "protocol active (%s:%d [%s]).", sock->hostname,
2890                       sock->port,
2891                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2892                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2893                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2894                        "Router")));
2895     }
2896     break;
2897
2898   case SILC_PACKET_KEY_EXCHANGE_2:
2899     if (packet->flags & SILC_PACKET_FLAG_LIST)
2900       break;
2901
2902     if (sock->protocol && sock->protocol->protocol &&
2903         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2904          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2905
2906       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2907         SilcServerRekeyInternalContext *proto_ctx =
2908           (SilcServerRekeyInternalContext *)sock->protocol->context;
2909
2910         if (proto_ctx->packet)
2911           silc_packet_context_free(proto_ctx->packet);
2912
2913         proto_ctx->packet = silc_packet_context_dup(packet);
2914
2915         /* Let the protocol handle the packet */
2916         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2917       } else {
2918         SilcServerKEInternalContext *proto_ctx =
2919           (SilcServerKEInternalContext *)sock->protocol->context;
2920
2921         if (proto_ctx->packet)
2922           silc_packet_context_free(proto_ctx->packet);
2923
2924         proto_ctx->packet = silc_packet_context_dup(packet);
2925         proto_ctx->dest_id_type = packet->src_id_type;
2926         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2927                                             packet->src_id_type);
2928         if (!proto_ctx->dest_id)
2929           break;
2930
2931         /* Let the protocol handle the packet */
2932         silc_protocol_execute(sock->protocol, server->schedule,
2933                               0, 100000);
2934       }
2935     } else {
2936       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2937                       "protocol active (%s:%d [%s]).", sock->hostname,
2938                       sock->port,
2939                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2940                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2941                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2942                        "Router")));
2943     }
2944     break;
2945
2946   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2947     /*
2948      * Connection authentication request packet. When we receive this packet
2949      * we will send to the other end information about our mandatory
2950      * authentication method for the connection. This packet maybe received
2951      * at any time.
2952      */
2953     if (packet->flags & SILC_PACKET_FLAG_LIST)
2954       break;
2955     silc_server_connection_auth_request(server, sock, packet);
2956     break;
2957
2958     /*
2959      * Connection Authentication protocol packets
2960      */
2961   case SILC_PACKET_CONNECTION_AUTH:
2962     /* Start of the authentication protocol. We receive here the
2963        authentication data and will verify it. */
2964     if (packet->flags & SILC_PACKET_FLAG_LIST)
2965       break;
2966
2967     if (sock->protocol && sock->protocol->protocol->type
2968         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2969
2970       SilcServerConnAuthInternalContext *proto_ctx =
2971         (SilcServerConnAuthInternalContext *)sock->protocol->context;
2972
2973       proto_ctx->packet = silc_packet_context_dup(packet);
2974
2975       /* Let the protocol handle the packet */
2976       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2977     } else {
2978       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2979                       "protocol active (%s:%d [%s]).", sock->hostname,
2980                       sock->port,
2981                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2982                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2983                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2984                        "Router")));
2985     }
2986     break;
2987
2988   case SILC_PACKET_NEW_ID:
2989     /*
2990      * Received New ID packet. This includes some new ID that has been
2991      * created. It may be for client, server or channel. This is the way
2992      * to distribute information about new registered entities in the
2993      * SILC network.
2994      */
2995     if (packet->flags & SILC_PACKET_FLAG_LIST)
2996       silc_server_new_id_list(server, sock, packet);
2997     else
2998       silc_server_new_id(server, sock, packet);
2999     break;
3000
3001   case SILC_PACKET_NEW_CLIENT:
3002     /*
3003      * Received new client packet. This includes client information that
3004      * we will use to create initial client ID. After creating new
3005      * ID we will send it to the client.
3006      */
3007     if (packet->flags & SILC_PACKET_FLAG_LIST)
3008       break;
3009     silc_server_new_client(server, sock, packet);
3010     break;
3011
3012   case SILC_PACKET_NEW_SERVER:
3013     /*
3014      * Received new server packet. This includes Server ID and some other
3015      * information that we may save. This is received after server has
3016      * connected to us.
3017      */
3018     if (packet->flags & SILC_PACKET_FLAG_LIST)
3019       break;
3020     silc_server_new_server(server, sock, packet);
3021     break;
3022
3023   case SILC_PACKET_NEW_CHANNEL:
3024     /*
3025      * Received new channel packet. Information about new channel in the
3026      * network are distributed using this packet.
3027      */
3028     if (packet->flags & SILC_PACKET_FLAG_LIST)
3029       silc_server_new_channel_list(server, sock, packet);
3030     else
3031       silc_server_new_channel(server, sock, packet);
3032     break;
3033
3034   case SILC_PACKET_HEARTBEAT:
3035     /*
3036      * Received heartbeat.
3037      */
3038     if (packet->flags & SILC_PACKET_FLAG_LIST)
3039       break;
3040     break;
3041
3042   case SILC_PACKET_KEY_AGREEMENT:
3043     /*
3044      * Received heartbeat.
3045      */
3046     if (packet->flags & SILC_PACKET_FLAG_LIST)
3047       break;
3048     silc_server_key_agreement(server, sock, packet);
3049     break;
3050
3051   case SILC_PACKET_REKEY:
3052     /*
3053      * Received re-key packet. The sender wants to regenerate the session
3054      * keys.
3055      */
3056     if (packet->flags & SILC_PACKET_FLAG_LIST)
3057       break;
3058     silc_server_rekey(server, sock, packet);
3059     break;
3060
3061   case SILC_PACKET_REKEY_DONE:
3062     /*
3063      * The re-key is done.
3064      */
3065     if (packet->flags & SILC_PACKET_FLAG_LIST)
3066       break;
3067
3068     if (sock->protocol && sock->protocol->protocol &&
3069         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
3070
3071       SilcServerRekeyInternalContext *proto_ctx =
3072         (SilcServerRekeyInternalContext *)sock->protocol->context;
3073
3074       if (proto_ctx->packet)
3075         silc_packet_context_free(proto_ctx->packet);
3076
3077       proto_ctx->packet = silc_packet_context_dup(packet);
3078
3079       /* Let the protocol handle the packet */
3080       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
3081     } else {
3082       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
3083                       "protocol active (%s:%d [%s]).", sock->hostname,
3084                       sock->port,
3085                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3086                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3087                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3088                        "Router")));
3089     }
3090     break;
3091
3092   case SILC_PACKET_FTP:
3093     /* FTP packet */
3094     if (packet->flags & SILC_PACKET_FLAG_LIST)
3095       break;
3096     silc_server_ftp(server, sock, packet);
3097     break;
3098
3099   case SILC_PACKET_RESUME_CLIENT:
3100     /* Resume client */
3101     if (packet->flags & SILC_PACKET_FLAG_LIST)
3102       break;
3103     silc_server_resume_client(server, sock, packet);
3104     break;
3105
3106   case SILC_PACKET_RESUME_ROUTER:
3107     /* Resume router packet received. This packet is received for backup
3108        router resuming protocol. */
3109     if (packet->flags & SILC_PACKET_FLAG_LIST)
3110       break;
3111     silc_server_backup_resume_router(server, sock, packet);
3112     break;
3113
3114   default:
3115     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
3116     break;
3117   }
3118 }
3119
3120 /* Creates connection to a remote router. */
3121
3122 void silc_server_create_connection(SilcServer server,
3123                                    const char *remote_host, SilcUInt32 port)
3124 {
3125   SilcServerConnection sconn;
3126
3127   /* Allocate connection object for hold connection specific stuff. */
3128   sconn = silc_calloc(1, sizeof(*sconn));
3129   sconn->remote_host = strdup(remote_host);
3130   sconn->remote_port = port;
3131   sconn->no_reconnect = TRUE;
3132
3133   silc_schedule_task_add(server->schedule, 0,
3134                          silc_server_connect_router,
3135                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
3136                          SILC_TASK_PRI_NORMAL);
3137 }
3138
3139 SILC_TASK_CALLBACK(silc_server_close_connection_final)
3140 {
3141   SilcServer server = app_context;
3142   SilcSocketConnection sock = context;
3143
3144   SILC_LOG_DEBUG(("Deleting socket %p", sock));
3145
3146   /* Close the actual connection */
3147   silc_net_close_connection(sock->sock);
3148   server->sockets[sock->sock] = NULL;
3149
3150   /* We won't listen for this connection anymore */
3151   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3152   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
3153
3154   silc_socket_free(sock);
3155 }
3156
3157 /* Closes connection to socket connection */
3158
3159 void silc_server_close_connection(SilcServer server,
3160                                   SilcSocketConnection sock)
3161 {
3162   char tmp[128];
3163
3164   if (SILC_IS_DISCONNECTED(sock)) {
3165     silc_schedule_task_del_by_fd(server->schedule, sock->sock);
3166     silc_schedule_task_add(server->schedule, sock->sock,
3167                            silc_server_close_connection_final,
3168                            (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3169                            SILC_TASK_PRI_NORMAL);
3170     server->sockets[sock->sock] = NULL;
3171     return;
3172   }
3173
3174   /* If any protocol is active cancel its execution. It will call
3175      the final callback which will finalize the disconnection. */
3176   if (sock->protocol && sock->protocol->protocol &&
3177       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3178     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3179     silc_protocol_cancel(sock->protocol, server->schedule);
3180     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3181     silc_protocol_execute_final(sock->protocol, server->schedule);
3182     sock->protocol = NULL;
3183     return;
3184   }
3185
3186   memset(tmp, 0, sizeof(tmp));
3187   silc_socket_get_error(sock, tmp, sizeof(tmp));
3188   SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
3189                  sock->port,
3190                  (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
3191                   sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
3192                   sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
3193                   "Router"), tmp[0] ? tmp : ""));
3194
3195   SILC_SET_DISCONNECTED(sock);
3196   silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
3197   silc_schedule_task_add(server->schedule, sock->sock,
3198                          silc_server_close_connection_final,
3199                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
3200                          SILC_TASK_PRI_NORMAL);
3201   server->sockets[sock->sock] = NULL;
3202 }
3203
3204 /* Sends disconnect message to remote connection and disconnects the
3205    connection.  NOTE: If this is called from protocol callback
3206    then sock->protocol must be set NULL before calling this, since
3207    this routine dispatches protocol callbacks too. */
3208
3209 void silc_server_disconnect_remote(SilcServer server,
3210                                    SilcSocketConnection sock,
3211                                    SilcStatus status, ...)
3212 {
3213   va_list ap;
3214   unsigned char buf[512];
3215   SilcBuffer buffer;
3216   char *cp;
3217   int len;
3218
3219   if (!sock)
3220     return;
3221
3222   if (SILC_IS_DISCONNECTING(sock)) {
3223     SILC_SET_DISCONNECTED(sock);
3224     silc_server_close_connection(server, sock);
3225     return;
3226   }
3227
3228   memset(buf, 0, sizeof(buf));
3229   va_start(ap, status);
3230   cp = va_arg(ap, char *);
3231   if (cp) {
3232     vsnprintf(buf, sizeof(buf) - 1, cp, ap);
3233     cp = buf;
3234   }
3235   va_end(ap);
3236
3237   SILC_LOG_DEBUG(("Disconnecting remote host"));
3238
3239   /* Notify remote end that the conversation is over. The notify message
3240      is tried to be sent immediately. */
3241
3242   len = 1;
3243   if (cp)
3244     len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
3245
3246   buffer = silc_buffer_alloc_size(len);
3247   if (!buffer)
3248     goto out;
3249
3250   buffer->data[0] = status;
3251   if (cp)
3252     silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
3253                      buffer->len - 1);
3254   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
3255                           buffer->data, buffer->len, TRUE);
3256   silc_buffer_free(buffer);
3257
3258  out:
3259   silc_server_packet_queue_purge(server, sock);
3260
3261   /* Mark the connection to be disconnected */
3262   SILC_SET_DISCONNECTING(sock);
3263   silc_server_close_connection(server, sock);
3264 }
3265
3266 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
3267 {
3268   SilcServer server = app_context;
3269   SilcClientEntry client = context;
3270
3271   assert(!silc_hash_table_count(client->channels));
3272
3273   silc_idlist_del_data(client);
3274   silc_idcache_purge_by_context(server->local_list->clients, client);
3275 }
3276
3277 /* Frees client data and notifies about client's signoff. */
3278
3279 void silc_server_free_client_data(SilcServer server,
3280                                   SilcSocketConnection sock,
3281                                   SilcClientEntry client,
3282                                   int notify,
3283                                   const char *signoff)
3284 {
3285   SILC_LOG_DEBUG(("Freeing client data"));
3286
3287   /* If there is pending outgoing data for the client then purge it
3288      to the network before removing the client entry. */
3289   silc_server_packet_queue_purge(server, sock);
3290
3291   if (client->id) {
3292     /* Check if anyone is watching this nickname */
3293     if (server->server_type == SILC_ROUTER)
3294       silc_server_check_watcher_list(server, client, NULL,
3295                                      SILC_NOTIFY_TYPE_SIGNOFF);
3296
3297     /* Send SIGNOFF notify to routers. */
3298     if (notify)
3299       silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
3300                                       SILC_BROADCAST(server), client->id,
3301                                       signoff);
3302   }
3303
3304   /* Remove client from all channels */
3305   if (notify)
3306     silc_server_remove_from_channels(server, NULL, client,
3307                                      TRUE, (char *)signoff, TRUE, FALSE);
3308   else
3309     silc_server_remove_from_channels(server, NULL, client,
3310                                      FALSE, NULL, FALSE, FALSE);
3311
3312   /* Remove this client from watcher list if it is */
3313   silc_server_del_from_watcher_list(server, client);
3314
3315   /* Remove this client from the public key hash list */
3316   if (client->data.public_key)
3317     silc_hash_table_del_by_context(server->pk_hash,
3318                                    client->data.public_key, client);
3319
3320   /* Update statistics */
3321   server->stat.my_clients--;
3322   server->stat.clients--;
3323   if (server->stat.cell_clients)
3324     server->stat.cell_clients--;
3325   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
3326   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
3327   silc_schedule_task_del_by_context(server->schedule, client);
3328
3329   /* We will not delete the client entry right away. We will take it
3330      into history (for WHOWAS command) for 5 minutes, unless we're
3331      shutting down server. */
3332   if (!server->server_shutdown) {
3333     silc_schedule_task_add(server->schedule, 0,
3334                            silc_server_free_client_data_timeout,
3335                            client, 300, 0,
3336                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
3337     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
3338     client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3339     client->mode = 0;
3340     client->router = NULL;
3341     client->connection = NULL;
3342   } else {
3343     /* Delete directly since we're shutting down server */
3344     silc_idlist_del_data(client);
3345     silc_idlist_del_client(server->local_list, client);
3346   }
3347 }
3348
3349 /* Frees user_data pointer from socket connection object. This also sends
3350    appropriate notify packets to the network to inform about leaving
3351    entities. */
3352
3353 void silc_server_free_sock_user_data(SilcServer server,
3354                                      SilcSocketConnection sock,
3355                                      const char *signoff_message)
3356 {
3357
3358   /* If any protocol is active cancel its execution */
3359   if (sock->protocol && sock->protocol->protocol &&
3360       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3361     SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3362     silc_protocol_cancel(sock->protocol, server->schedule);
3363     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3364     silc_protocol_execute_final(sock->protocol, server->schedule);
3365     sock->protocol = NULL;
3366   }
3367
3368   switch (sock->type) {
3369   case SILC_SOCKET_TYPE_CLIENT:
3370     {
3371       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3372       silc_server_free_client_data(server, sock, user_data, TRUE,
3373                                    signoff_message);
3374       break;
3375     }
3376   case SILC_SOCKET_TYPE_SERVER:
3377   case SILC_SOCKET_TYPE_ROUTER:
3378     {
3379       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3380       SilcServerEntry backup_router = NULL;
3381
3382       SILC_LOG_DEBUG(("Freeing server data"));
3383
3384       if (user_data->id)
3385         backup_router = silc_server_backup_get(server, user_data->id);
3386
3387       if (!server->backup_router && server->server_type == SILC_ROUTER &&
3388           backup_router == server->id_entry &&
3389           sock->type != SILC_SOCKET_TYPE_ROUTER)
3390         backup_router = NULL;
3391
3392       if (server->server_shutdown || server->backup_noswitch)
3393         backup_router = NULL;
3394
3395       /* If this was our primary router connection then we're lost to
3396          the outside world. */
3397       if (server->router == user_data) {
3398         /* Check whether we have a backup router connection */
3399         if (!backup_router || backup_router == user_data) {
3400           if (!server->no_reconnect)
3401             silc_server_create_connections(server);
3402           server->id_entry->router = NULL;
3403           server->router = NULL;
3404           server->standalone = TRUE;
3405           server->backup_primary = FALSE;
3406           backup_router = NULL;
3407         } else {
3408           if (server->id_entry != backup_router) {
3409             SILC_LOG_INFO(("New primary router is backup router %s",
3410                            backup_router->server_name));
3411             server->id_entry->router = backup_router;
3412             server->router = backup_router;
3413             server->router_connect = time(0);
3414             server->backup_primary = TRUE;
3415             backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3416
3417             /* Send START_USE to backup router to indicate we have switched */
3418             silc_server_backup_send_start_use(server,
3419                                               backup_router->connection,
3420                                               FALSE);
3421           } else {
3422             SILC_LOG_INFO(("We are now new primary router in this cell"));
3423             server->id_entry->router = NULL;
3424             server->router = NULL;
3425             server->standalone = TRUE;
3426           }
3427
3428           /* We stop here to take a breath */
3429           sleep(2);
3430
3431           if (server->backup_router) {
3432             server->server_type = SILC_ROUTER;
3433
3434             /* We'll need to constantly try to reconnect to the primary
3435                router so that we'll see when it comes back online. */
3436             silc_server_backup_reconnect(server, sock->ip, sock->port,
3437                                          silc_server_backup_connected,
3438                                          NULL);
3439           }
3440
3441           /* Mark this connection as replaced */
3442           silc_server_backup_replaced_add(server, user_data->id,
3443                                           backup_router);
3444         }
3445       } else if (backup_router) {
3446         SILC_LOG_INFO(("Enabling the use of backup router %s",
3447                        backup_router->server_name));
3448
3449         /* Mark this connection as replaced */
3450         silc_server_backup_replaced_add(server, user_data->id,
3451                                         backup_router);
3452       } else if (server->server_type == SILC_SERVER &&
3453                  sock->type == SILC_SOCKET_TYPE_ROUTER) {
3454         /* Reconnect to the router (backup) */
3455         if (!server->no_reconnect)
3456           silc_server_create_connections(server);
3457       }
3458
3459       if (user_data->server_name)
3460         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3461                                ("Server %s signoff", user_data->server_name));
3462
3463       if (!backup_router) {
3464         /* Remove all servers that are originated from this server, and
3465            remove the clients of those servers too. */
3466         silc_server_remove_servers_by_server(server, user_data, TRUE);
3467
3468 #if 0
3469         /* Remove the clients that this server owns as they will become
3470            invalid now too.  For backup router the server is actually
3471            coming from the primary router, so mark that as the owner
3472            of this entry. */
3473         if (server->server_type == SILC_BACKUP_ROUTER &&
3474             sock->type == SILC_SOCKET_TYPE_SERVER)
3475           silc_server_remove_clients_by_server(server, server->router,
3476                                                user_data, TRUE);
3477         else
3478 #endif
3479           silc_server_remove_clients_by_server(server, user_data,
3480                                                user_data, TRUE);
3481
3482         /* Remove channels owned by this server */
3483         if (server->server_type == SILC_SERVER)
3484           silc_server_remove_channels_by_server(server, user_data);
3485       } else {
3486         /* Enable local server connections that may be disabled */
3487         silc_server_local_servers_toggle_enabled(server, TRUE);
3488
3489         /* Update the client entries of this server to the new backup
3490            router.  If we are the backup router we also resolve the real
3491            servers for the clients.  After updating is over this also
3492            removes the clients that this server explicitly owns. */
3493         silc_server_update_clients_by_server(server, user_data,
3494                                              backup_router, TRUE);
3495
3496         /* If we are router and just lost our primary router (now standlaone)
3497            we remove everything that was behind it, since we don't know
3498            any better. */
3499         if (server->server_type == SILC_ROUTER && server->standalone)
3500           /* Remove all servers that are originated from this server, and
3501              remove the clients of those servers too. */
3502           silc_server_remove_servers_by_server(server, user_data, TRUE);
3503
3504         /* Finally remove the clients that are explicitly owned by this
3505            server.  They go down with the server. */
3506         silc_server_remove_clients_by_server(server, user_data,
3507                                              user_data, TRUE);
3508
3509         /* Update our server cache to use the new backup router too. */
3510         silc_server_update_servers_by_server(server, user_data, backup_router);
3511         if (server->server_type == SILC_SERVER)
3512           silc_server_update_channels_by_server(server, user_data,
3513                                                 backup_router);
3514
3515         /* Send notify about primary router going down to local operators */
3516         if (server->backup_router)
3517           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3518                                  SILC_NOTIFY_TYPE_NONE,
3519                                  ("%s switched to backup router %s "
3520                                   "(we are primary router now)",
3521                                   server->server_name, server->server_name));
3522         else if (server->router)
3523           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3524                                  SILC_NOTIFY_TYPE_NONE,
3525                                  ("%s switched to backup router %s",
3526                                   server->server_name,
3527                                   server->router->server_name));
3528       }
3529       server->backup_noswitch = FALSE;
3530
3531       /* Free the server entry */
3532       silc_server_backup_del(server, user_data);
3533       silc_server_backup_replaced_del(server, user_data);
3534       silc_idlist_del_data(user_data);
3535       if (!silc_idlist_del_server(server->local_list, user_data))
3536         silc_idlist_del_server(server->global_list, user_data);
3537       if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3538         server->stat.my_servers--;
3539       } else {
3540         server->stat.my_routers--;
3541         server->stat.routers--;
3542       }
3543       server->stat.servers--;
3544       if (server->server_type == SILC_ROUTER)
3545         server->stat.cell_servers--;
3546
3547       if (backup_router && backup_router != server->id_entry) {
3548         /* Announce all of our stuff that was created about 5 minutes ago.
3549            The backup router knows all the other stuff already. */
3550         if (server->server_type == SILC_ROUTER)
3551           silc_server_announce_servers(server, FALSE, time(0) - 300,
3552                                        backup_router->connection);
3553
3554         /* Announce our clients and channels to the router */
3555         silc_server_announce_clients(server, time(0) - 300,
3556                                      backup_router->connection);
3557         silc_server_announce_channels(server, time(0) - 300,
3558                                       backup_router->connection);
3559       }
3560       break;
3561     }
3562   default:
3563     {
3564       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3565
3566       SILC_LOG_DEBUG(("Freeing unknown connection data"));
3567
3568       silc_idlist_del_data(user_data);
3569       silc_free(user_data);
3570       break;
3571     }
3572   }
3573
3574   sock->user_data = NULL;
3575 }
3576
3577 /* Removes client from all channels it has joined. This is used when client
3578    connection is disconnected. If the client on a channel is last, the
3579    channel is removed as well. This sends the SIGNOFF notify types. */
3580
3581 void silc_server_remove_from_channels(SilcServer server,
3582                                       SilcSocketConnection sock,
3583                                       SilcClientEntry client,
3584                                       bool notify,
3585                                       const char *signoff_message,
3586                                       bool keygen,
3587                                       bool killed)
3588 {
3589   SilcChannelEntry channel;
3590   SilcChannelClientEntry chl;
3591   SilcHashTableList htl;
3592   SilcBuffer clidp = NULL;
3593
3594   if (!client)
3595     return;
3596
3597   if (notify && !client->id)
3598     notify = FALSE;
3599
3600   SILC_LOG_DEBUG(("Removing client %s from joined channels",
3601                   notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3602
3603   if (notify) {
3604     clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3605     if (!clidp)
3606       notify = FALSE;
3607   }
3608
3609   /* Remove the client from all channels. The client is removed from
3610      the channels' user list. */
3611   silc_hash_table_list(client->channels, &htl);
3612   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3613     channel = chl->channel;
3614
3615     /* Remove channel if this is last client leaving the channel, unless
3616        the channel is permanent. */
3617     if (server->server_type != SILC_SERVER &&
3618         silc_hash_table_count(channel->user_list) < 2) {
3619       silc_server_channel_delete(server, channel);
3620       continue;
3621     }
3622
3623     silc_hash_table_del(client->channels, channel);
3624     silc_hash_table_del(channel->user_list, client);
3625     channel->user_count--;
3626
3627     /* If there is no global users on the channel anymore mark the channel
3628        as local channel. Do not check if the removed client is local client. */
3629     if (server->server_type == SILC_SERVER && channel->global_users &&
3630         chl->client->router && !silc_server_channel_has_global(channel))
3631       channel->global_users = FALSE;
3632
3633     memset(chl, 'A', sizeof(*chl));
3634     silc_free(chl);
3635
3636     /* Update statistics */
3637     if (SILC_IS_LOCAL(client))
3638       server->stat.my_chanclients--;
3639     if (server->server_type == SILC_ROUTER) {
3640       server->stat.cell_chanclients--;
3641       server->stat.chanclients--;
3642     }
3643
3644     /* If there is not at least one local user on the channel then we don't
3645        need the channel entry anymore, we can remove it safely, unless the
3646        channel is permanent channel */
3647     if (server->server_type == SILC_SERVER &&
3648         !silc_server_channel_has_local(channel)) {
3649       /* Notify about leaving client if this channel has global users. */
3650       if (notify && channel->global_users)
3651         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3652                                            SILC_NOTIFY_TYPE_SIGNOFF,
3653                                            signoff_message ? 2 : 1,
3654                                            clidp->data, clidp->len,
3655                                            signoff_message, signoff_message ?
3656                                            strlen(signoff_message) : 0);
3657
3658       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3659       silc_server_channel_delete(server, channel);
3660       continue;
3661     }
3662
3663     /* Send notify to channel about client leaving SILC and channel too */
3664     if (notify)
3665       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3666                                          SILC_NOTIFY_TYPE_SIGNOFF,
3667                                          signoff_message ? 2 : 1,
3668                                          clidp->data, clidp->len,
3669                                          signoff_message, signoff_message ?
3670                                          strlen(signoff_message) : 0);
3671
3672     if (killed && clidp) {
3673       /* Remove the client from channel's invite list */
3674       if (channel->invite_list &&
3675           silc_hash_table_count(channel->invite_list)) {
3676         SilcBuffer ab;
3677         SilcArgumentPayload iargs;
3678         ab = silc_argument_payload_encode_one(NULL, clidp->data,
3679                                               clidp->len, 3);
3680         iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
3681         silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3682         silc_buffer_free(ab);
3683         silc_argument_payload_free(iargs);
3684       }
3685     }
3686
3687     /* Don't create keys if we are shutting down */
3688     if (server->server_shutdown)
3689       continue;
3690
3691     /* Re-generate channel key if needed */
3692     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3693       if (!silc_server_create_channel_key(server, channel, 0))
3694         continue;
3695
3696       /* Send the channel key to the channel. The key of course is not sent
3697          to the client who was removed from the channel. */
3698       silc_server_send_channel_key(server, client->connection, channel,
3699                                    server->server_type == SILC_ROUTER ?
3700                                    FALSE : !server->standalone);
3701     }
3702   }
3703
3704   silc_hash_table_list_reset(&htl);
3705   if (clidp)
3706     silc_buffer_free(clidp);
3707 }
3708
3709 /* Removes client from one channel. This is used for example when client
3710    calls LEAVE command to remove itself from the channel. Returns TRUE
3711    if channel still exists and FALSE if the channel is removed when
3712    last client leaves the channel. If `notify' is FALSE notify messages
3713    are not sent. */
3714
3715 bool silc_server_remove_from_one_channel(SilcServer server,
3716                                          SilcSocketConnection sock,
3717                                          SilcChannelEntry channel,
3718                                          SilcClientEntry client,
3719                                          bool notify)
3720 {
3721   SilcChannelClientEntry chl;
3722   SilcBuffer clidp;
3723
3724   SILC_LOG_DEBUG(("Removing %s from channel %s",
3725                   silc_id_render(client->id, SILC_ID_CLIENT),
3726                   channel->channel_name));
3727
3728   /* Get the entry to the channel, if this client is not on the channel
3729      then return Ok. */
3730   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3731     return TRUE;
3732
3733   /* Remove channel if this is last client leaving the channel, unless
3734      the channel is permanent. */
3735   if (server->server_type != SILC_SERVER &&
3736       silc_hash_table_count(channel->user_list) < 2) {
3737     silc_server_channel_delete(server, channel);
3738     return FALSE;
3739   }
3740
3741   silc_hash_table_del(client->channels, channel);
3742   silc_hash_table_del(channel->user_list, client);
3743   channel->user_count--;
3744
3745   /* If there is no global users on the channel anymore mark the channel
3746      as local channel. Do not check if the client is local client. */
3747   if (server->server_type == SILC_SERVER && channel->global_users &&
3748       chl->client->router && !silc_server_channel_has_global(channel))
3749     channel->global_users = FALSE;
3750
3751   memset(chl, 'O', sizeof(*chl));
3752   silc_free(chl);
3753
3754   /* Update statistics */
3755   if (SILC_IS_LOCAL(client))
3756     server->stat.my_chanclients--;
3757   if (server->server_type == SILC_ROUTER) {
3758     server->stat.cell_chanclients--;
3759     server->stat.chanclients--;
3760   }
3761
3762   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3763   if (!clidp)
3764     notify = FALSE;
3765
3766   /* If there is not at least one local user on the channel then we don't
3767      need the channel entry anymore, we can remove it safely, unless the
3768      channel is permanent channel */
3769   if (server->server_type == SILC_SERVER &&
3770       !silc_server_channel_has_local(channel)) {
3771     /* Notify about leaving client if this channel has global users. */
3772     if (notify && channel->global_users)
3773       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3774                                          SILC_NOTIFY_TYPE_LEAVE, 1,
3775                                          clidp->data, clidp->len);
3776
3777     silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3778     silc_server_channel_delete(server, channel);
3779     silc_buffer_free(clidp);
3780     return FALSE;
3781   }
3782
3783   /* Send notify to channel about client leaving the channel */
3784   if (notify)
3785     silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3786                                        SILC_NOTIFY_TYPE_LEAVE, 1,
3787                                        clidp->data, clidp->len);
3788
3789   silc_buffer_free(clidp);
3790   return TRUE;
3791 }
3792
3793 /* Timeout callback. This is called if connection is idle or for some
3794    other reason is not responding within some period of time. This
3795    disconnects the remote end. */
3796
3797 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3798 {
3799   SilcServer server = (SilcServer)context;
3800   SilcSocketConnection sock = server->sockets[fd];
3801   SilcProtocolType protocol = 0;
3802
3803   SILC_LOG_DEBUG(("Start"));
3804
3805   if (!sock)
3806     return;
3807
3808   SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3809                   sock->hostname, sock->ip));
3810
3811   /* If we have protocol active we must assure that we call the protocol's
3812      final callback so that all the memory is freed. */
3813   if (sock->protocol && sock->protocol->protocol &&
3814       sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
3815     protocol = sock->protocol->protocol->type;
3816     silc_protocol_cancel(sock->protocol, server->schedule);
3817     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3818     silc_protocol_execute_final(sock->protocol, server->schedule);
3819     sock->protocol = NULL;
3820     return;
3821   }
3822
3823   silc_server_disconnect_remote(server, sock,
3824                                 protocol ==
3825                                 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3826                                 SILC_STATUS_ERR_AUTH_FAILED :
3827                                 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3828                                 "Connection timeout");
3829
3830   if (sock->user_data)
3831     silc_server_free_sock_user_data(server, sock, NULL);
3832 }
3833
3834 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3835    function may be used only by router. In real SILC network all channels
3836    are created by routers thus this function is never used by normal
3837    server. */
3838
3839 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3840                                                 SilcServerID *router_id,
3841                                                 char *cipher,
3842                                                 char *hmac,
3843                                                 char *channel_name,
3844                                                 int broadcast)
3845 {
3846   SilcChannelID *channel_id;
3847   SilcChannelEntry entry;
3848   SilcCipher key;
3849   SilcHmac newhmac;
3850
3851   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3852
3853   if (!cipher)
3854     cipher = SILC_DEFAULT_CIPHER;
3855   if (!hmac)
3856     hmac = SILC_DEFAULT_HMAC;
3857
3858   /* Allocate cipher */
3859   if (!silc_cipher_alloc(cipher, &key))
3860     return NULL;
3861
3862   /* Allocate hmac */
3863   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3864     silc_cipher_free(key);
3865     return NULL;
3866   }
3867
3868   channel_name = strdup(channel_name);
3869
3870   /* Create the channel ID */
3871   if (!silc_id_create_channel_id(server, router_id, server->rng,
3872                                  &channel_id)) {
3873     silc_free(channel_name);
3874     silc_cipher_free(key);
3875     silc_hmac_free(newhmac);
3876     return NULL;
3877   }
3878
3879   /* Create the channel */
3880   entry = silc_idlist_add_channel(server->local_list, channel_name,
3881                                   SILC_CHANNEL_MODE_NONE, channel_id,
3882                                   NULL, key, newhmac, 0);
3883   if (!entry) {
3884     silc_free(channel_name);
3885     silc_cipher_free(key);
3886     silc_hmac_free(newhmac);
3887     silc_free(channel_id);
3888     return NULL;
3889   }
3890
3891   entry->cipher = strdup(cipher);
3892   entry->hmac_name = strdup(hmac);
3893
3894   /* Now create the actual key material */
3895   if (!silc_server_create_channel_key(server, entry,
3896                                       silc_cipher_get_key_len(key) / 8)) {
3897     silc_idlist_del_channel(server->local_list, entry);
3898     return NULL;
3899   }
3900
3901   /* Notify other routers about the new channel. We send the packet
3902      to our primary route. */
3903   if (broadcast)
3904     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3905                                  channel_name, entry->id,
3906                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3907                                  entry->mode);
3908
3909   /* Distribute to backup routers */
3910   if (broadcast && server->server_type == SILC_ROUTER) {
3911     SilcBuffer packet;
3912     unsigned char *cid;
3913     SilcUInt32 name_len = strlen(channel_name);
3914     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3915     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3916
3917     packet = silc_channel_payload_encode(channel_name, name_len,
3918                                          cid, channel_id_len, entry->mode);
3919     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3920                             packet->data, packet->len, FALSE, TRUE);
3921     silc_free(cid);
3922     silc_buffer_free(packet);
3923   }
3924
3925   server->stat.my_channels++;
3926   if (server->server_type == SILC_ROUTER) {
3927     server->stat.channels++;
3928     server->stat.cell_channels++;
3929     entry->users_resolved = TRUE;
3930   }
3931
3932   return entry;
3933 }
3934
3935 /* Same as above but creates the channel with Channel ID `channel_id. */
3936
3937 SilcChannelEntry
3938 silc_server_create_new_channel_with_id(SilcServer server,
3939                                        char *cipher,
3940                                        char *hmac,
3941                                        char *channel_name,
3942                                        SilcChannelID *channel_id,
3943                                        int broadcast)
3944 {
3945   SilcChannelEntry entry;
3946   SilcCipher key;
3947   SilcHmac newhmac;
3948
3949   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3950
3951   if (!cipher)
3952     cipher = SILC_DEFAULT_CIPHER;
3953   if (!hmac)
3954     hmac = SILC_DEFAULT_HMAC;
3955
3956   /* Allocate cipher */
3957   if (!silc_cipher_alloc(cipher, &key))
3958     return NULL;
3959
3960   /* Allocate hmac */
3961   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3962     silc_cipher_free(key);
3963     return NULL;
3964   }
3965
3966   channel_name = strdup(channel_name);
3967
3968   /* Create the channel */
3969   entry = silc_idlist_add_channel(server->local_list, channel_name,
3970                                   SILC_CHANNEL_MODE_NONE, channel_id,
3971                                   NULL, key, newhmac, 0);
3972   if (!entry) {
3973     silc_cipher_free(key);
3974     silc_hmac_free(newhmac);
3975     silc_free(channel_name);
3976     return NULL;
3977   }
3978
3979   /* Now create the actual key material */
3980   if (!silc_server_create_channel_key(server, entry,
3981                                       silc_cipher_get_key_len(key) / 8)) {
3982     silc_idlist_del_channel(server->local_list, entry);
3983     return NULL;
3984   }
3985
3986   /* Notify other routers about the new channel. We send the packet
3987      to our primary route. */
3988   if (broadcast)
3989     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3990                                  channel_name, entry->id,
3991                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3992                                  entry->mode);
3993
3994   /* Distribute to backup routers */
3995   if (broadcast && server->server_type == SILC_ROUTER) {
3996     SilcBuffer packet;
3997     unsigned char *cid;
3998     SilcUInt32 name_len = strlen(channel_name);
3999     SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
4000     cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
4001
4002     packet = silc_channel_payload_encode(channel_name, name_len,
4003                                          cid, channel_id_len, entry->mode);
4004     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
4005                             packet->data, packet->len, FALSE, TRUE);
4006     silc_free(cid);
4007     silc_buffer_free(packet);
4008   }
4009
4010   server->stat.my_channels++;
4011   if (server->server_type == SILC_ROUTER) {
4012     server->stat.channels++;
4013     server->stat.cell_channels++;
4014     entry->users_resolved = TRUE;
4015   }
4016
4017   return entry;
4018 }
4019
4020 /* Channel's key re-key timeout callback. */
4021
4022 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
4023 {
4024   SilcServer server = app_context;
4025   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
4026
4027   rekey->task = NULL;
4028
4029   /* Return now if we are shutting down */
4030   if (server->server_shutdown)
4031     return;
4032
4033   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
4034     return;
4035
4036   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
4037 }
4038
4039 /* Generates new channel key. This is used to create the initial channel key
4040    but also to re-generate new key for channel. If `key_len' is provided
4041    it is the bytes of the key length. */
4042
4043 bool silc_server_create_channel_key(SilcServer server,
4044                                     SilcChannelEntry channel,
4045                                     SilcUInt32 key_len)
4046 {
4047   int i;
4048   unsigned char channel_key[32], hash[32];
4049   SilcUInt32 len;
4050
4051   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
4052     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
4053     return TRUE;
4054   }
4055
4056   SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
4057
4058   if (!channel->channel_key)
4059     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
4060       channel->channel_key = NULL;
4061       return FALSE;
4062     }
4063
4064   if (key_len)
4065     len = key_len;
4066   else if (channel->key_len)
4067     len = channel->key_len / 8;
4068   else
4069     len = silc_cipher_get_key_len(channel->channel_key) / 8;
4070
4071   /* Create channel key */
4072   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
4073
4074   /* Set the key */
4075   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
4076
4077   /* Remove old key if exists */
4078   if (channel->key) {
4079     memset(channel->key, 0, channel->key_len / 8);
4080     silc_free(channel->key);
4081   }
4082
4083   /* Save the key */
4084   channel->key_len = len * 8;
4085   channel->key = silc_memdup(channel_key, len);
4086   memset(channel_key, 0, sizeof(channel_key));
4087
4088   /* Generate HMAC key from the channel key data and set it */
4089   if (!channel->hmac)
4090     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4091       memset(channel->key, 0, channel->key_len / 8);
4092       silc_free(channel->key);
4093       channel->channel_key = NULL;
4094       return FALSE;
4095     }
4096   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
4097   silc_hmac_set_key(channel->hmac, hash,
4098                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4099   memset(hash, 0, sizeof(hash));
4100
4101   if (server->server_type == SILC_ROUTER) {
4102     if (!channel->rekey)
4103       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4104     channel->rekey->channel = channel;
4105     channel->rekey->key_len = key_len;
4106     if (channel->rekey->task)
4107       silc_schedule_task_del(server->schedule, channel->rekey->task);
4108
4109     channel->rekey->task =
4110       silc_schedule_task_add(server->schedule, 0,
4111                              silc_server_channel_key_rekey,
4112                              (void *)channel->rekey,
4113                              server->config->channel_rekey_secs, 0,
4114                              SILC_TASK_TIMEOUT,
4115                              SILC_TASK_PRI_NORMAL);
4116   }
4117
4118   return TRUE;
4119 }
4120
4121 /* Saves the channel key found in the encoded `key_payload' buffer. This
4122    function is used when we receive Channel Key Payload and also when we're
4123    processing JOIN command reply. Returns entry to the channel. */
4124
4125 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
4126                                               SilcBuffer key_payload,
4127                                               SilcChannelEntry channel)
4128 {
4129   SilcChannelKeyPayload payload = NULL;
4130   SilcChannelID *id = NULL;
4131   unsigned char *tmp, hash[32];
4132   SilcUInt32 tmp_len;
4133   char *cipher;
4134
4135   /* Decode channel key payload */
4136   payload = silc_channel_key_payload_parse(key_payload->data,
4137                                            key_payload->len);
4138   if (!payload) {
4139     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
4140     channel = NULL;
4141     goto out;
4142   }
4143
4144   /* Get the channel entry */
4145   if (!channel) {
4146
4147     /* Get channel ID */
4148     tmp = silc_channel_key_get_id(payload, &tmp_len);
4149     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
4150     if (!id) {
4151       channel = NULL;
4152       goto out;
4153     }
4154
4155     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
4156     if (!channel) {
4157       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
4158       if (!channel) {
4159         if (server->server_type == SILC_ROUTER)
4160           SILC_LOG_ERROR(("Received key for non-existent channel %s",
4161                           silc_id_render(id, SILC_ID_CHANNEL)));
4162         goto out;
4163       }
4164     }
4165   }
4166
4167   SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
4168
4169   tmp = silc_channel_key_get_key(payload, &tmp_len);
4170   if (!tmp) {
4171     channel = NULL;
4172     goto out;
4173   }
4174
4175   cipher = silc_channel_key_get_cipher(payload, NULL);
4176   if (!cipher) {
4177     channel = NULL;
4178     goto out;
4179   }
4180
4181   /* Remove old key if exists */
4182   if (channel->key) {
4183     memset(channel->key, 0, channel->key_len / 8);
4184     silc_free(channel->key);
4185     silc_cipher_free(channel->channel_key);
4186   }
4187
4188   /* Create new cipher */
4189   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
4190     channel->channel_key = NULL;
4191     channel = NULL;
4192     goto out;
4193   }
4194
4195   if (channel->cipher)
4196     silc_free(channel->cipher);
4197   channel->cipher = strdup(cipher);
4198
4199   /* Save the key */
4200   channel->key_len = tmp_len * 8;
4201   channel->key = silc_memdup(tmp, tmp_len);
4202   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
4203
4204   /* Generate HMAC key from the channel key data and set it */
4205   if (!channel->hmac)
4206     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
4207       memset(channel->key, 0, channel->key_len / 8);
4208       silc_free(channel->key);
4209       channel->channel_key = NULL;
4210       return FALSE;
4211     }
4212   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
4213   silc_hmac_set_key(channel->hmac, hash,
4214                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
4215
4216   memset(hash, 0, sizeof(hash));
4217   memset(tmp, 0, tmp_len);
4218
4219   if (server->server_type == SILC_ROUTER) {
4220     if (!channel->rekey)
4221       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
4222     channel->rekey->channel = channel;
4223     if (channel->rekey->task)
4224       silc_schedule_task_del(server->schedule, channel->rekey->task);
4225
4226     channel->rekey->task =
4227       silc_schedule_task_add(server->schedule, 0,
4228                              silc_server_channel_key_rekey,
4229                              (void *)channel->rekey,
4230                              server->config->channel_rekey_secs, 0,
4231                              SILC_TASK_TIMEOUT,
4232                              SILC_TASK_PRI_NORMAL);
4233   }
4234
4235  out:
4236   silc_free(id);
4237   if (payload)
4238     silc_channel_key_payload_free(payload);
4239
4240   return channel;
4241 }
4242
4243 /* Heartbeat callback. This function is set as argument for the
4244    silc_socket_set_heartbeat function. The library will call this function
4245    at the set time interval. */
4246
4247 void silc_server_perform_heartbeat(SilcSocketConnection sock,
4248                                    void *hb_context)
4249 {
4250   SilcServer server = hb_context;
4251
4252   SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
4253                  sock->port, sock->ip));
4254
4255   /* Send the heartbeat */
4256   silc_server_send_heartbeat(server, sock);
4257 }
4258
4259 /* Returns assembled of all servers in the given ID list. The packet's
4260    form is dictated by the New ID payload. */
4261
4262 static void silc_server_announce_get_servers(SilcServer server,
4263                                              SilcServerEntry remote,
4264                                              SilcIDList id_list,
4265                                              SilcBuffer *servers,
4266                                              unsigned long creation_time)
4267 {
4268   SilcIDCacheList list;
4269   SilcIDCacheEntry id_cache;
4270   SilcServerEntry entry;
4271   SilcBuffer idp;
4272
4273   /* Go through all clients in the list */
4274   if (silc_idcache_get_all(id_list->servers, &list)) {
4275     if (silc_idcache_list_first(list, &id_cache)) {
4276       while (id_cache) {
4277         entry = (SilcServerEntry)id_cache->context;
4278
4279         /* Do not announce the one we've sending our announcements and
4280            do not announce ourself. Also check the creation time if it's
4281            provided. */
4282         if ((entry == remote) || (entry == server->id_entry) ||
4283             (creation_time && entry->data.created < creation_time)) {
4284           if (!silc_idcache_list_next(list, &id_cache))
4285             break;
4286           continue;
4287         }
4288
4289         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
4290
4291         *servers = silc_buffer_realloc(*servers,
4292                                        (*servers ?
4293                                         (*servers)->truelen + idp->len :
4294                                         idp->len));
4295         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
4296         silc_buffer_put(*servers, idp->data, idp->len);
4297         silc_buffer_pull(*servers, idp->len);
4298         silc_buffer_free(idp);
4299
4300         if (!silc_idcache_list_next(list, &id_cache))
4301           break;
4302       }
4303     }
4304
4305     silc_idcache_list_free(list);
4306   }
4307 }
4308
4309 static SilcBuffer
4310 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
4311 {
4312   va_list ap;
4313   SilcBuffer p;
4314
4315   va_start(ap, argc);
4316   p = silc_notify_payload_encode(notify, argc, ap);
4317   va_end(ap);
4318
4319   return p;
4320 }
4321
4322 /* This function is used by router to announce existing servers to our
4323    primary router when we've connected to it. If `creation_time' is non-zero
4324    then only the servers that has been created after the `creation_time'
4325    will be announced. */
4326
4327 void silc_server_announce_servers(SilcServer server, bool global,
4328                                   unsigned long creation_time,
4329                                   SilcSocketConnection remote)
4330 {
4331   SilcBuffer servers = NULL;
4332
4333   SILC_LOG_DEBUG(("Announcing servers"));
4334
4335   /* Get servers in local list */
4336   silc_server_announce_get_servers(server, remote->user_data,
4337                                    server->local_list, &servers,
4338                                    creation_time);
4339
4340   if (global)
4341     /* Get servers in global list */
4342     silc_server_announce_get_servers(server, remote->user_data,
4343                                      server->global_list, &servers,
4344                                      creation_time);
4345
4346   if (servers) {
4347     silc_buffer_push(servers, servers->data - servers->head);
4348     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
4349
4350     /* Send the packet */
4351     silc_server_packet_send(server, remote,
4352                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4353                             servers->data, servers->len, TRUE);
4354
4355     silc_buffer_free(servers);
4356   }
4357 }
4358
4359 /* Returns assembled packet of all clients in the given ID list. The
4360    packet's form is dictated by the New ID Payload. */
4361
4362 static void silc_server_announce_get_clients(SilcServer server,
4363                                              SilcIDList id_list,
4364                                              SilcBuffer *clients,
4365                                              SilcBuffer *umodes,
4366                                              unsigned long creation_time)
4367 {
4368   SilcIDCacheList list;
4369   SilcIDCacheEntry id_cache;
4370   SilcClientEntry client;
4371   SilcBuffer idp;
4372   SilcBuffer tmp;
4373   unsigned char mode[4];
4374
4375   /* Go through all clients in the list */
4376   if (silc_idcache_get_all(id_list->clients, &list)) {
4377     if (silc_idcache_list_first(list, &id_cache)) {
4378       while (id_cache) {
4379         client = (SilcClientEntry)id_cache->context;
4380
4381         if (creation_time && client->data.created < creation_time) {
4382           if (!silc_idcache_list_next(list, &id_cache))
4383             break;
4384           continue;
4385         }
4386         if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
4387             !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
4388           if (!silc_idcache_list_next(list, &id_cache))
4389             break;
4390           continue;
4391         }
4392
4393         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4394
4395         *clients = silc_buffer_realloc(*clients,
4396                                        (*clients ?
4397                                         (*clients)->truelen + idp->len :
4398                                         idp->len));
4399         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4400         silc_buffer_put(*clients, idp->data, idp->len);
4401         silc_buffer_pull(*clients, idp->len);
4402
4403         SILC_PUT32_MSB(client->mode, mode);
4404         tmp =
4405           silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4406                                              2, idp->data, idp->len,
4407                                              mode, 4);
4408         *umodes = silc_buffer_realloc(*umodes,
4409                                       (*umodes ?
4410                                        (*umodes)->truelen + tmp->len :
4411                                        tmp->len));
4412         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4413         silc_buffer_put(*umodes, tmp->data, tmp->len);
4414         silc_buffer_pull(*umodes, tmp->len);
4415         silc_buffer_free(tmp);
4416
4417         silc_buffer_free(idp);
4418
4419         if (!silc_idcache_list_next(list, &id_cache))
4420           break;
4421       }
4422     }
4423
4424     silc_idcache_list_free(list);
4425   }
4426 }
4427
4428 /* This function is used to announce our existing clients to our router
4429    when we've connected to it. If `creation_time' is non-zero then only
4430    the clients that has been created after the `creation_time' will be
4431    announced. */
4432
4433 void silc_server_announce_clients(SilcServer server,
4434                                   unsigned long creation_time,
4435                                   SilcSocketConnection remote)
4436 {
4437   SilcBuffer clients = NULL;
4438   SilcBuffer umodes = NULL;
4439
4440   SILC_LOG_DEBUG(("Announcing clients"));
4441
4442   /* Get clients in local list */
4443   silc_server_announce_get_clients(server, server->local_list,
4444                                    &clients, &umodes, creation_time);
4445
4446   /* As router we announce our global list as well */
4447   if (server->server_type == SILC_ROUTER)
4448     silc_server_announce_get_clients(server, server->global_list,
4449                                      &clients, &umodes, creation_time);
4450
4451   if (clients) {
4452     silc_buffer_push(clients, clients->data - clients->head);
4453     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4454
4455     /* Send the packet */
4456     silc_server_packet_send(server, remote,
4457                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4458                             clients->data, clients->len, TRUE);
4459
4460     silc_buffer_free(clients);
4461   }
4462
4463   if (umodes) {
4464     silc_buffer_push(umodes, umodes->data - umodes->head);
4465     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4466
4467     /* Send the packet */
4468     silc_server_packet_send(server, remote,
4469                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4470                             umodes->data, umodes->len, TRUE);
4471
4472     silc_buffer_free(umodes);
4473   }
4474 }
4475
4476 /* Returns channel's topic for announcing it */
4477
4478 void silc_server_announce_get_channel_topic(SilcServer server,
4479                                             SilcChannelEntry channel,
4480                                             SilcBuffer *topic)
4481 {
4482   SilcBuffer chidp;
4483
4484   if (channel->topic) {
4485     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4486     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4487                                                 chidp->data, chidp->len,
4488                                                 channel->topic,
4489                                                 strlen(channel->topic));
4490     silc_buffer_free(chidp);
4491   }
4492 }
4493
4494 /* Returns channel's invite and ban lists */
4495
4496 void silc_server_announce_get_inviteban(SilcServer server,
4497                                         SilcChannelEntry channel,
4498                                         SilcBuffer *invite,
4499                                         SilcBuffer *ban)
4500 {
4501   SilcBuffer list, idp, idp2, tmp2;
4502   SilcUInt32 type;
4503   SilcHashTableList htl;
4504   const unsigned char a[1] = { 0x03 };
4505
4506   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4507
4508   /* Encode invite list */
4509   if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4510     list = silc_buffer_alloc_size(2);
4511     type = silc_hash_table_count(channel->invite_list);
4512     SILC_PUT16_MSB(type, list->data);
4513     silc_hash_table_list(channel->invite_list, &htl);
4514     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4515       list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4516                                               type);
4517     silc_hash_table_list_reset(&htl);
4518
4519     idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4520     *invite =
4521       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4522                                          idp->data, idp->len,
4523                                          channel->channel_name,
4524                                          strlen(channel->channel_name),
4525                                          idp2->data, idp2->len,
4526                                          a, 1,
4527                                          list->data, list->len);
4528     silc_buffer_free(idp2);
4529     silc_buffer_free(list);
4530   }
4531
4532   /* Encode ban list */
4533   if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4534     list = silc_buffer_alloc_size(2);
4535     type = silc_hash_table_count(channel->ban_list);
4536     SILC_PUT16_MSB(type, list->data);
4537     silc_hash_table_list(channel->ban_list, &htl);
4538     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4539       list = silc_argument_payload_encode_one(list, tmp2->data, tmp2->len,
4540                                               type);
4541     silc_hash_table_list_reset(&htl);
4542
4543     *ban =
4544       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4545                                          idp->data, idp->len,
4546                                          a, 1,
4547                                          list->data, list->len);
4548     silc_buffer_free(list);
4549   }
4550
4551   silc_buffer_free(idp);
4552 }
4553
4554 /* Returns assembled packets for channel users of the `channel'. */
4555
4556 void silc_server_announce_get_channel_users(SilcServer server,
4557                                             SilcChannelEntry channel,
4558                                             SilcBuffer *channel_modes,
4559                                             SilcBuffer *channel_users,
4560                                             SilcBuffer *channel_users_modes)
4561 {
4562   SilcChannelClientEntry chl;
4563   SilcHashTableList htl;
4564   SilcBuffer chidp, clidp, csidp;
4565   SilcBuffer tmp, fkey = NULL, chpklist;
4566   int len;
4567   unsigned char mode[4];
4568   char *hmac;
4569
4570   SILC_LOG_DEBUG(("Start"));
4571
4572   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4573   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4574   chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4575
4576   /* CMODE notify */
4577   SILC_PUT32_MSB(channel->mode, mode);
4578   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4579   if (channel->founder_key)
4580     fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4581   tmp =
4582     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4583                                        7, csidp->data, csidp->len,
4584                                        mode, sizeof(mode),
4585                                        NULL, 0,
4586                                        hmac, hmac ? strlen(hmac) : 0,
4587                                        channel->passphrase,
4588                                        channel->passphrase ?
4589                                        strlen(channel->passphrase) : 0,
4590                                        fkey ? fkey->data : NULL,
4591                                        fkey ? fkey->len : 0,
4592                                        chpklist ? chpklist->data : NULL,
4593                                        chpklist ? chpklist->len : 0);
4594   len = tmp->len;
4595   *channel_modes =
4596     silc_buffer_realloc(*channel_modes,
4597                         (*channel_modes ?
4598                          (*channel_modes)->truelen + len : len));
4599   silc_buffer_pull_tail(*channel_modes,
4600                         ((*channel_modes)->end -
4601                          (*channel_modes)->data));
4602   silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4603   silc_buffer_pull(*channel_modes, len);
4604   silc_buffer_free(tmp);
4605   silc_buffer_free(fkey);
4606   fkey = NULL;
4607
4608   /* Now find all users on the channel */
4609   silc_hash_table_list(channel->user_list, &htl);
4610   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4611     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4612
4613     /* JOIN Notify */
4614     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4615                                              clidp->data, clidp->len,
4616                                              chidp->data, chidp->len);
4617     len = tmp->len;
4618     *channel_users =
4619       silc_buffer_realloc(*channel_users,
4620                           (*channel_users ?
4621                            (*channel_users)->truelen + len : len));
4622     silc_buffer_pull_tail(*channel_users,
4623                           ((*channel_users)->end -
4624                            (*channel_users)->data));
4625
4626     silc_buffer_put(*channel_users, tmp->data, tmp->len);
4627     silc_buffer_pull(*channel_users, len);
4628     silc_buffer_free(tmp);
4629
4630     /* CUMODE notify for mode change on the channel */
4631     SILC_PUT32_MSB(chl->mode, mode);
4632     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4633       fkey = silc_pkcs_public_key_payload_encode(channel->founder_key);
4634     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4635                                              4, csidp->data, csidp->len,
4636                                              mode, sizeof(mode),
4637                                              clidp->data, clidp->len,
4638                                              fkey ? fkey->data : NULL,
4639                                              fkey ? fkey->len : 0);
4640     len = tmp->len;
4641     *channel_users_modes =
4642       silc_buffer_realloc(*channel_users_modes,
4643                           (*channel_users_modes ?
4644                            (*channel_users_modes)->truelen + len : len));
4645     silc_buffer_pull_tail(*channel_users_modes,
4646                           ((*channel_users_modes)->end -
4647                            (*channel_users_modes)->data));
4648
4649     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4650     silc_buffer_pull(*channel_users_modes, len);
4651     silc_buffer_free(tmp);
4652     silc_buffer_free(fkey);
4653     fkey = NULL;
4654     silc_buffer_free(clidp);
4655   }
4656   silc_hash_table_list_reset(&htl);
4657   silc_buffer_free(chidp);
4658   silc_buffer_free(csidp);
4659 }
4660
4661 /* Returns assembled packets for all channels and users on those channels
4662    from the given ID List. The packets are in the form dictated by the
4663    New Channel and New Channel User payloads. */
4664
4665 void silc_server_announce_get_channels(SilcServer server,
4666                                        SilcIDList id_list,
4667                                        SilcBuffer *channels,
4668                                        SilcBuffer **channel_modes,
4669                                        SilcBuffer *channel_users,
4670                                        SilcBuffer **channel_users_modes,
4671                                        SilcUInt32 *channel_users_modes_c,
4672                                        SilcBuffer **channel_topics,
4673                                        SilcBuffer **channel_invites,
4674                                        SilcBuffer **channel_bans,
4675                                        SilcChannelID ***channel_ids,
4676                                        unsigned long creation_time)
4677 {
4678   SilcIDCacheList list;
4679   SilcIDCacheEntry id_cache;
4680   SilcChannelEntry channel;
4681   unsigned char *cid;
4682   SilcUInt32 id_len;
4683   SilcUInt16 name_len;
4684   int len;
4685   int i = *channel_users_modes_c;
4686   bool announce;
4687
4688   SILC_LOG_DEBUG(("Start"));
4689
4690   /* Go through all channels in the list */
4691   if (silc_idcache_get_all(id_list->channels, &list)) {
4692     if (silc_idcache_list_first(list, &id_cache)) {
4693       while (id_cache) {
4694         channel = (SilcChannelEntry)id_cache->context;
4695
4696         if (creation_time && channel->created < creation_time)
4697           announce = FALSE;
4698         else
4699           announce = TRUE;
4700
4701         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4702         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4703         name_len = strlen(channel->channel_name);
4704
4705         if (announce) {
4706           len = 4 + name_len + id_len + 4;
4707           *channels =
4708             silc_buffer_realloc(*channels,
4709                                 (*channels ? (*channels)->truelen +
4710                                  len : len));
4711           silc_buffer_pull_tail(*channels,
4712                                 ((*channels)->end - (*channels)->data));
4713           silc_buffer_format(*channels,
4714                              SILC_STR_UI_SHORT(name_len),
4715                              SILC_STR_UI_XNSTRING(channel->channel_name,
4716                                                   name_len),
4717                              SILC_STR_UI_SHORT(id_len),
4718                              SILC_STR_UI_XNSTRING(cid, id_len),
4719                              SILC_STR_UI_INT(channel->mode),
4720                              SILC_STR_END);
4721           silc_buffer_pull(*channels, len);
4722         }
4723
4724         if (creation_time && channel->updated < creation_time)
4725           announce = FALSE;
4726         else
4727           announce = TRUE;
4728
4729         if (announce) {
4730           /* Channel user modes */
4731           *channel_users_modes = silc_realloc(*channel_users_modes,
4732                                               sizeof(**channel_users_modes) *
4733                                               (i + 1));
4734           (*channel_users_modes)[i] = NULL;
4735           *channel_modes = silc_realloc(*channel_modes,
4736                                         sizeof(**channel_modes) * (i + 1));
4737           (*channel_modes)[i] = NULL;
4738           *channel_ids = silc_realloc(*channel_ids,
4739                                       sizeof(**channel_ids) * (i + 1));
4740           (*channel_ids)[i] = NULL;
4741           silc_server_announce_get_channel_users(server, channel,
4742                                                  &(*channel_modes)[i],
4743                                                  channel_users,
4744                                                  &(*channel_users_modes)[i]);
4745           (*channel_ids)[i] = channel->id;
4746
4747           /* Channel's topic */
4748           *channel_topics = silc_realloc(*channel_topics,
4749                                          sizeof(**channel_topics) * (i + 1));
4750           (*channel_topics)[i] = NULL;
4751           silc_server_announce_get_channel_topic(server, channel,
4752                                                  &(*channel_topics)[i]);
4753
4754           /* Channel's invite and ban list */
4755           *channel_invites = silc_realloc(*channel_invites,
4756                                           sizeof(**channel_invites) * (i + 1));
4757           (*channel_invites)[i] = NULL;
4758           *channel_bans = silc_realloc(*channel_bans,
4759                                        sizeof(**channel_bans) * (i + 1));
4760           (*channel_bans)[i] = NULL;
4761           silc_server_announce_get_inviteban(server, channel,
4762                                              &(*channel_invites)[i],
4763                                              &(*channel_bans)[i]);
4764
4765           (*channel_users_modes_c)++;
4766           silc_free(cid);
4767
4768           i++;
4769         }
4770
4771         if (!silc_idcache_list_next(list, &id_cache))
4772           break;
4773       }
4774     }
4775
4776     silc_idcache_list_free(list);
4777   }
4778 }
4779
4780 /* This function is used to announce our existing channels to our router
4781    when we've connected to it. This also announces the users on the
4782    channels to the router. If the `creation_time' is non-zero only the
4783    channels that was created after the `creation_time' are announced.
4784    Note that the channel users are still announced even if the `creation_time'
4785    was provided. */
4786
4787 void silc_server_announce_channels(SilcServer server,
4788                                    unsigned long creation_time,
4789                                    SilcSocketConnection remote)
4790 {
4791   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4792   SilcBuffer *channel_users_modes = NULL;
4793   SilcBuffer *channel_topics = NULL;
4794   SilcBuffer *channel_invites = NULL;
4795   SilcBuffer *channel_bans = NULL;
4796   SilcUInt32 channel_users_modes_c = 0;
4797   SilcChannelID **channel_ids = NULL;
4798
4799   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4800
4801   /* Get channels and channel users in local list */
4802   silc_server_announce_get_channels(server, server->local_list,
4803                                     &channels, &channel_modes,
4804                                     &channel_users,
4805                                     &channel_users_modes,
4806                                     &channel_users_modes_c,
4807                                     &channel_topics,
4808                                     &channel_invites,
4809                                     &channel_bans,
4810                                     &channel_ids, creation_time);
4811
4812   /* Get channels and channel users in global list */
4813   if (server->server_type != SILC_SERVER)
4814     silc_server_announce_get_channels(server, server->global_list,
4815                                       &channels, &channel_modes,
4816                                       &channel_users,
4817                                       &channel_users_modes,
4818                                       &channel_users_modes_c,
4819                                       &channel_topics,
4820                                       &channel_invites,
4821                                       &channel_bans,
4822                                       &channel_ids, creation_time);
4823
4824   if (channels) {
4825     silc_buffer_push(channels, channels->data - channels->head);
4826     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4827
4828     /* Send the packet */
4829     silc_server_packet_send(server, remote,
4830                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4831                             channels->data, channels->len,
4832                             FALSE);
4833
4834     silc_buffer_free(channels);
4835   }
4836
4837   if (channel_users) {
4838     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4839     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4840                      channel_users->len);
4841
4842     /* Send the packet */
4843     silc_server_packet_send(server, remote,
4844                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4845                             channel_users->data, channel_users->len,
4846                             FALSE);
4847
4848     silc_buffer_free(channel_users);
4849   }
4850
4851   if (channel_modes) {
4852     int i;
4853
4854     for (i = 0; i < channel_users_modes_c; i++) {
4855       if (!channel_modes[i])
4856         continue;
4857       silc_buffer_push(channel_modes[i],
4858                        channel_modes[i]->data -
4859                        channel_modes[i]->head);
4860       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4861                        channel_modes[i]->len);
4862       silc_server_packet_send_dest(server, remote,
4863                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4864                                    channel_ids[i], SILC_ID_CHANNEL,
4865                                    channel_modes[i]->data,
4866                                    channel_modes[i]->len,
4867                                    FALSE);
4868       silc_buffer_free(channel_modes[i]);
4869     }
4870     silc_free(channel_modes);
4871   }
4872
4873   if (channel_users_modes) {
4874     int i;
4875
4876     for (i = 0; i < channel_users_modes_c; i++) {
4877       if (!channel_users_modes[i])
4878         continue;
4879       silc_buffer_push(channel_users_modes[i],
4880                        channel_users_modes[i]->data -
4881                        channel_users_modes[i]->head);
4882       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4883                        channel_users_modes[i]->len);
4884       silc_server_packet_send_dest(server, remote,
4885                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4886                                    channel_ids[i], SILC_ID_CHANNEL,
4887                                    channel_users_modes[i]->data,
4888                                    channel_users_modes[i]->len,
4889                                    FALSE);
4890       silc_buffer_free(channel_users_modes[i]);
4891     }
4892     silc_free(channel_users_modes);
4893   }
4894
4895   if (channel_topics) {
4896     int i;
4897
4898     for (i = 0; i < channel_users_modes_c; i++) {
4899       if (!channel_topics[i])
4900         continue;
4901
4902       silc_buffer_push(channel_topics[i],
4903                        channel_topics[i]->data -
4904                        channel_topics[i]->head);
4905       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4906                        channel_topics[i]->len);
4907       silc_server_packet_send_dest(server, remote,
4908                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4909                                    channel_ids[i], SILC_ID_CHANNEL,
4910                                    channel_topics[i]->data,
4911                                    channel_topics[i]->len,
4912                                    FALSE);
4913       silc_buffer_free(channel_topics[i]);
4914     }
4915     silc_free(channel_topics);
4916   }
4917
4918   if (channel_invites) {
4919     int i;
4920
4921     for (i = 0; i < channel_users_modes_c; i++) {
4922       if (!channel_invites[i])
4923         continue;
4924
4925       silc_buffer_push(channel_invites[i],
4926                        channel_invites[i]->data -
4927                        channel_invites[i]->head);
4928       SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4929                        channel_invites[i]->len);
4930       silc_server_packet_send_dest(server, remote,
4931                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4932                                    channel_ids[i], SILC_ID_CHANNEL,
4933                                    channel_invites[i]->data,
4934                                    channel_invites[i]->len,
4935                                    FALSE);
4936       silc_buffer_free(channel_invites[i]);
4937     }
4938     silc_free(channel_invites);
4939   }
4940
4941   if (channel_bans) {
4942     int i;
4943
4944     for (i = 0; i < channel_users_modes_c; i++) {
4945       if (!channel_bans[i])
4946         continue;
4947
4948       silc_buffer_push(channel_bans[i],
4949                        channel_bans[i]->data -
4950                        channel_bans[i]->head);
4951       SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4952                        channel_bans[i]->len);
4953       silc_server_packet_send_dest(server, remote,
4954                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4955                                    channel_ids[i], SILC_ID_CHANNEL,
4956                                    channel_bans[i]->data,
4957                                    channel_bans[i]->len,
4958                                    FALSE);
4959       silc_buffer_free(channel_bans[i]);
4960     }
4961     silc_free(channel_bans);
4962   }
4963
4964   silc_free(channel_ids);
4965 }
4966
4967 /* Assembles user list and users mode list from the `channel'. */
4968
4969 bool silc_server_get_users_on_channel(SilcServer server,
4970                                       SilcChannelEntry channel,
4971                                       SilcBuffer *user_list,
4972                                       SilcBuffer *mode_list,
4973                                       SilcUInt32 *user_count)
4974 {
4975   SilcChannelClientEntry chl;
4976   SilcHashTableList htl;
4977   SilcBuffer client_id_list;
4978   SilcBuffer client_mode_list;
4979   SilcBuffer idp;
4980   SilcUInt32 list_count = 0, len = 0;
4981
4982   if (!silc_hash_table_count(channel->user_list))
4983     return FALSE;
4984
4985   silc_hash_table_list(channel->user_list, &htl);
4986   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4987     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4988   silc_hash_table_list_reset(&htl);
4989
4990   client_id_list = silc_buffer_alloc(len);
4991   client_mode_list =
4992     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4993   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4994   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4995
4996   silc_hash_table_list(channel->user_list, &htl);
4997   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4998     /* Client ID */
4999     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
5000     silc_buffer_put(client_id_list, idp->data, idp->len);
5001     silc_buffer_pull(client_id_list, idp->len);
5002     silc_buffer_free(idp);
5003
5004     /* Client's mode on channel */
5005     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
5006     silc_buffer_pull(client_mode_list, 4);
5007
5008     list_count++;
5009   }
5010   silc_hash_table_list_reset(&htl);
5011   silc_buffer_push(client_id_list,
5012                    client_id_list->data - client_id_list->head);
5013   silc_buffer_push(client_mode_list,
5014                    client_mode_list->data - client_mode_list->head);
5015
5016   *user_list = client_id_list;
5017   *mode_list = client_mode_list;
5018   *user_count = list_count;
5019   return TRUE;
5020 }
5021
5022 /* Saves users and their modes to the `channel'. */
5023
5024 void silc_server_save_users_on_channel(SilcServer server,
5025                                        SilcSocketConnection sock,
5026                                        SilcChannelEntry channel,
5027                                        SilcClientID *noadd,
5028                                        SilcBuffer user_list,
5029                                        SilcBuffer mode_list,
5030                                        SilcUInt32 user_count)
5031 {
5032   int i;
5033   SilcUInt16 idp_len;
5034   SilcUInt32 mode;
5035   SilcClientID *client_id;
5036   SilcClientEntry client;
5037   SilcIDCacheEntry cache;
5038   SilcChannelClientEntry chl;
5039
5040   SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
5041                   channel->channel_name));
5042
5043   for (i = 0; i < user_count; i++) {
5044     /* Client ID */
5045     SILC_GET16_MSB(idp_len, user_list->data + 2);
5046     idp_len += 4;
5047     client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
5048     silc_buffer_pull(user_list, idp_len);
5049     if (!client_id)
5050       continue;
5051
5052     /* Mode */
5053     SILC_GET32_MSB(mode, mode_list->data);
5054     silc_buffer_pull(mode_list, 4);
5055
5056     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
5057       silc_free(client_id);
5058       continue;
5059     }
5060
5061     cache = NULL;
5062
5063     /* Check if we have this client cached already. */
5064     client = silc_idlist_find_client_by_id(server->local_list, client_id,
5065                                            server->server_type, &cache);
5066     if (!client)
5067       client = silc_idlist_find_client_by_id(server->global_list,
5068                                              client_id, server->server_type,
5069                                              &cache);
5070     if (!client) {
5071       /* If router did not find such Client ID in its lists then this must
5072          be bogus client or some router in the net is buggy. */
5073       if (server->server_type != SILC_SERVER) {
5074         silc_free(client_id);
5075         continue;
5076       }
5077
5078       /* We don't have that client anywhere, add it. The client is added
5079          to global list since server didn't have it in the lists so it must be
5080          global. */
5081       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
5082                                       silc_id_dup(client_id, SILC_ID_CLIENT),
5083                                       sock->user_data, NULL, 0);
5084       if (!client) {
5085         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
5086         silc_free(client_id);
5087         continue;
5088       }
5089
5090       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
5091     }
5092
5093     if (cache)
5094       cache->expire = 0;
5095     silc_free(client_id);
5096
5097     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
5098       SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
5099                       "%s", channel->channel_name));
5100       continue;
5101     }
5102
5103     if (!silc_server_client_on_channel(client, channel, &chl)) {
5104       /* Client was not on the channel, add it. */
5105       chl = silc_calloc(1, sizeof(*chl));
5106       chl->client = client;
5107       chl->mode = mode;
5108       chl->channel = channel;
5109       silc_hash_table_add(channel->user_list, chl->client, chl);
5110       silc_hash_table_add(client->channels, chl->channel, chl);
5111       channel->user_count++;
5112     } else {
5113       /* Update mode */
5114       chl->mode = mode;
5115     }
5116   }
5117 }
5118
5119 /* Saves channels and channels user modes to the `client'.  Removes
5120    the client from those channels that are not sent in the list but
5121    it has joined. */
5122
5123 void silc_server_save_user_channels(SilcServer server,
5124                                     SilcSocketConnection sock,
5125                                     SilcClientEntry client,
5126                                     SilcBuffer channels,
5127                                     SilcBuffer channels_user_modes)
5128 {
5129   SilcDList ch;
5130   SilcUInt32 *chumodes;
5131   SilcChannelPayload entry;
5132   SilcChannelEntry channel;
5133   SilcChannelID *channel_id;
5134   SilcChannelClientEntry chl;
5135   SilcHashTable ht = NULL;
5136   SilcHashTableList htl;
5137   char *name;
5138   int i = 0;
5139
5140   if (!channels || !channels_user_modes ||
5141       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
5142     goto out;
5143
5144   ch = silc_channel_payload_parse_list(channels->data, channels->len);
5145   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
5146                                &chumodes)) {
5147     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
5148                                NULL, NULL, NULL, TRUE);
5149     silc_dlist_start(ch);
5150     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
5151       /* Check if we have this channel, and add it if we don't have it.
5152          Also add the client on the channel unless it is there already. */
5153       channel_id = silc_channel_get_id_parse(entry);
5154       channel = silc_idlist_find_channel_by_id(server->local_list,
5155                                                channel_id, NULL);
5156       if (!channel)
5157         channel = silc_idlist_find_channel_by_id(server->global_list,
5158                                                  channel_id, NULL);
5159       if (!channel) {
5160         if (server->server_type != SILC_SERVER) {
5161           silc_free(channel_id);
5162           i++;
5163           continue;
5164         }
5165
5166         /* We don't have that channel anywhere, add it. */
5167         name = silc_channel_get_name(entry, NULL);
5168         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
5169                                           channel_id, server->router,
5170                                           NULL, NULL, 0);
5171         if (!channel) {
5172           silc_free(channel_id);
5173           i++;
5174           continue;
5175         }
5176         channel_id = NULL;
5177       }
5178
5179       channel->mode = silc_channel_get_mode(entry);
5180
5181       /* Add the client on the channel */
5182       if (!silc_server_client_on_channel(client, channel, &chl)) {
5183         chl = silc_calloc(1, sizeof(*chl));
5184         chl->client = client;
5185         chl->mode = chumodes[i++];
5186         chl->channel = channel;
5187         silc_hash_table_add(channel->user_list, chl->client, chl);
5188         silc_hash_table_add(client->channels, chl->channel, chl);
5189         channel->user_count++;
5190       } else {
5191         /* Update mode */
5192         chl->mode = chumodes[i++];
5193       }
5194
5195       silc_hash_table_add(ht, channel, channel);
5196       silc_free(channel_id);
5197     }
5198     silc_channel_payload_list_free(ch);
5199     silc_free(chumodes);
5200   }
5201
5202  out:
5203   /* Go through the list again and remove client from channels that
5204      are no part of the list. */
5205   if (ht) {
5206     silc_hash_table_list(client->channels, &htl);
5207     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5208       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
5209         silc_hash_table_del(chl->channel->user_list, chl->client);
5210         silc_hash_table_del(chl->client->channels, chl->channel);
5211         silc_free(chl);
5212       }
5213     }
5214     silc_hash_table_list_reset(&htl);
5215     silc_hash_table_free(ht);
5216   } else {
5217     silc_hash_table_list(client->channels, &htl);
5218     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5219       silc_hash_table_del(chl->channel->user_list, chl->client);
5220       silc_hash_table_del(chl->client->channels, chl->channel);
5221       silc_free(chl);
5222     }
5223     silc_hash_table_list_reset(&htl);
5224   }
5225 }
5226
5227 /* Lookups route to the client indicated by the `id_data'. The connection
5228    object and internal data object is returned. Returns NULL if route
5229    could not be found to the client. If the `client_id' is specified then
5230    it is used and the `id_data' is ignored. */
5231
5232 SilcSocketConnection
5233 silc_server_get_client_route(SilcServer server,
5234                              unsigned char *id_data,
5235                              SilcUInt32 id_len,
5236                              SilcClientID *client_id,
5237                              SilcIDListData *idata,
5238                              SilcClientEntry *client_entry)
5239 {
5240   SilcClientID *id;
5241   SilcClientEntry client;
5242
5243   SILC_LOG_DEBUG(("Start"));
5244
5245   if (client_entry)
5246     *client_entry = NULL;
5247
5248   /* Decode destination Client ID */
5249   if (!client_id) {
5250     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
5251     if (!id) {
5252       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
5253       return NULL;
5254     }
5255   } else {
5256     id = silc_id_dup(client_id, SILC_ID_CLIENT);
5257   }
5258
5259   /* If the destination belongs to our server we don't have to route
5260      the packet anywhere but to send it to the local destination. */
5261   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
5262   if (client) {
5263     silc_free(id);
5264
5265     /* If we are router and the client has router then the client is in
5266        our cell but not directly connected to us. */
5267     if (server->server_type == SILC_ROUTER && client->router) {
5268       /* We are of course in this case the client's router thus the route
5269          to the client is the server who owns the client. So, we will send
5270          the packet to that server. */
5271       if (idata)
5272         *idata = (SilcIDListData)client->router;
5273       return client->router->connection;
5274     }
5275
5276     /* Seems that client really is directly connected to us */
5277     if (idata)
5278       *idata = (SilcIDListData)client;
5279     if (client_entry)
5280       *client_entry = client;
5281     return client->connection;
5282   }
5283
5284   /* Destination belongs to someone not in this server. If we are normal
5285      server our action is to send the packet to our router. */
5286   if (server->server_type != SILC_ROUTER && !server->standalone) {
5287     silc_free(id);
5288     if (idata)
5289       *idata = (SilcIDListData)server->router;
5290     return SILC_PRIMARY_ROUTE(server);
5291   }
5292
5293   /* We are router and we will perform route lookup for the destination
5294      and send the packet to fastest route. */
5295   if (server->server_type == SILC_ROUTER && !server->standalone) {
5296     /* Check first that the ID is valid */
5297     client = silc_idlist_find_client_by_id(server->global_list, id,
5298                                            TRUE, NULL);
5299     if (client) {
5300       SilcSocketConnection dst_sock;
5301
5302       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
5303
5304       silc_free(id);
5305       if (idata)
5306         *idata = (SilcIDListData)dst_sock->user_data;
5307       return dst_sock;
5308     }
5309   }
5310
5311   silc_free(id);
5312   return NULL;
5313 }
5314
5315 /* Encodes and returns channel list of channels the `client' has joined.
5316    Secret channels are not put to the list. */
5317
5318 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5319                                                SilcClientEntry client,
5320                                                bool get_private,
5321                                                bool get_secret,
5322                                                SilcBuffer *user_mode_list)
5323 {
5324   SilcBuffer buffer = NULL;
5325   SilcChannelEntry channel;
5326   SilcChannelClientEntry chl;
5327   SilcHashTableList htl;
5328   unsigned char *cid;
5329   SilcUInt32 id_len;
5330   SilcUInt16 name_len;
5331   int len;
5332
5333   if (user_mode_list)
5334     *user_mode_list = NULL;
5335
5336   silc_hash_table_list(client->channels, &htl);
5337   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5338     channel = chl->channel;
5339
5340     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5341       continue;
5342     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5343       continue;
5344
5345     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
5346     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
5347     name_len = strlen(channel->channel_name);
5348
5349     len = 4 + name_len + id_len + 4;
5350     buffer = silc_buffer_realloc(buffer,
5351                                  (buffer ? buffer->truelen + len : len));
5352     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5353     silc_buffer_format(buffer,
5354                        SILC_STR_UI_SHORT(name_len),
5355                        SILC_STR_UI_XNSTRING(channel->channel_name,
5356                                             name_len),
5357                        SILC_STR_UI_SHORT(id_len),
5358                        SILC_STR_UI_XNSTRING(cid, id_len),
5359                        SILC_STR_UI_INT(chl->channel->mode),
5360                        SILC_STR_END);
5361     silc_buffer_pull(buffer, len);
5362     silc_free(cid);
5363
5364     if (user_mode_list) {
5365       *user_mode_list = silc_buffer_realloc(*user_mode_list,
5366                                             (*user_mode_list ?
5367                                              (*user_mode_list)->truelen + 4 :
5368                                              4));
5369       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5370                                               (*user_mode_list)->data));
5371       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5372       silc_buffer_pull(*user_mode_list, 4);
5373     }
5374   }
5375   silc_hash_table_list_reset(&htl);
5376
5377   if (buffer)
5378     silc_buffer_push(buffer, buffer->data - buffer->head);
5379   if (user_mode_list && *user_mode_list)
5380     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5381                                        (*user_mode_list)->head));
5382
5383   return buffer;
5384 }
5385
5386 /* Timeout callback for unsuccessful rekey.  The rekey did not go through
5387    for some reason. */
5388
5389 SILC_TASK_CALLBACK(silc_server_rekey_timeout)
5390 {
5391   SilcServerRekeyInternalContext *ctx = context;
5392   SilcServer server = app_context;
5393   SilcSocketConnection sock = ctx->sock;
5394
5395   SILC_LOG_DEBUG(("Timeout occurred in rekey protocol with %s:%d [%s]",
5396                   sock->hostname, sock->port,
5397                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5398                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5399                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5400                    "Router")));
5401
5402   SILC_LOG_WARNING(("Timeout occurred in rekey protocol with %s:%d [%s]",
5403                     sock->hostname, sock->port,
5404                     (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5405                      sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5406                      sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5407                      "Router")));
5408
5409   if (sock->protocol) {
5410     silc_protocol_cancel(sock->protocol, server->schedule);
5411     silc_protocol_free(sock->protocol);
5412     sock->protocol = NULL;
5413   }
5414   if (ctx->packet)
5415     silc_packet_context_free(ctx->packet);
5416   if (ctx->ske)
5417     silc_ske_free(ctx->ske);
5418   silc_socket_free(sock);
5419   silc_free(ctx);
5420
5421   /* Disconnect since we failed to rekey, the keys are probably wrong. */
5422   silc_server_disconnect_remote(server, sock,
5423                                 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5424
5425   /* Reconnect */
5426   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5427     silc_server_create_connections(server);
5428 }
5429
5430 /* A timeout callback for the re-key. We will be the initiator of the
5431    re-key protocol. */
5432
5433 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_callback)
5434 {
5435   SilcServer server = app_context;
5436   SilcSocketConnection sock = (SilcSocketConnection)context;
5437   SilcIDListData idata = (SilcIDListData)sock->user_data;
5438   SilcProtocol protocol;
5439   SilcServerRekeyInternalContext *proto_ctx;
5440
5441   if (!idata)
5442     return;
5443
5444   /* Do not execute rekey with disabled connections, as it would not
5445      go through anyway. */
5446   if (idata->status & SILC_IDLIST_STATUS_DISABLED)
5447     return;
5448
5449   /* If rekey protocol is active already wait for it to finish */
5450   if (sock->protocol && sock->protocol->protocol &&
5451       sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)
5452     return;
5453
5454   /* If any other protocol is active do not start this protocol yet. */
5455   if (sock->protocol) {
5456     SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
5457     silc_schedule_task_add(server->schedule, sock->sock,
5458                            silc_server_rekey_callback,
5459                            sock, 60, 0, SILC_TASK_TIMEOUT,
5460                            SILC_TASK_PRI_NORMAL);
5461     return;
5462   }
5463
5464   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
5465                   sock->hostname, sock->port,
5466                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5467                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5468                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5469                    "Router")));
5470
5471   /* Allocate internal protocol context. This is sent as context
5472      to the protocol. */
5473   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
5474   proto_ctx->server = (void *)server;
5475   proto_ctx->sock = silc_socket_dup(sock);
5476   proto_ctx->responder = FALSE;
5477   proto_ctx->pfs = idata->rekey->pfs;
5478
5479   /* Perform rekey protocol. Will call the final callback after the
5480      protocol is over. */
5481   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
5482                       &protocol, proto_ctx, silc_server_rekey_final);
5483   sock->protocol = protocol;
5484
5485   /* Register timeout callback in case the rekey does not go through. */
5486   proto_ctx->timeout_task =
5487     silc_schedule_task_add(server->schedule, sock->sock,
5488                            silc_server_rekey_timeout,
5489                            proto_ctx,
5490                            (idata->rekey->timeout >
5491                             server->config->key_exchange_timeout ?
5492                             idata->rekey->timeout :
5493                             server->config->key_exchange_timeout * 4), 0,
5494                            SILC_TASK_TIMEOUT,
5495                            SILC_TASK_PRI_LOW);
5496
5497   /* Run the protocol */
5498   silc_protocol_execute(protocol, server->schedule, 0, 0);
5499 }
5500
5501 /* The final callback for the REKEY protocol. This will actually take the
5502    new key material into use. */
5503
5504 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
5505 {
5506   SilcProtocol protocol = (SilcProtocol)context;
5507   SilcServerRekeyInternalContext *ctx =
5508     (SilcServerRekeyInternalContext *)protocol->context;
5509   SilcServer server = (SilcServer)ctx->server;
5510   SilcSocketConnection sock = ctx->sock;
5511   SilcIDListData idata = (SilcIDListData)sock->user_data;
5512
5513   if (ctx->timeout_task)
5514     silc_schedule_task_del(server->schedule, ctx->timeout_task);
5515
5516   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
5517       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
5518     /* Error occured during protocol */
5519     SILC_LOG_ERROR(("Error occurred during rekey protocol with "
5520                     "%s (%s)", sock->hostname, sock->ip));
5521     silc_protocol_cancel(protocol, server->schedule);
5522     silc_protocol_free(protocol);
5523     sock->protocol = NULL;
5524     if (ctx->packet)
5525       silc_packet_context_free(ctx->packet);
5526     if (ctx->ske)
5527       silc_ske_free(ctx->ske);
5528     silc_socket_free(sock);
5529     silc_free(ctx);
5530     silc_server_disconnect_remote(server, sock,
5531                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
5532
5533     /* Reconnect */
5534     if (sock->type != SILC_SOCKET_TYPE_CLIENT)
5535       silc_server_create_connections(server);
5536     return;
5537   }
5538
5539   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
5540                   sock->hostname, sock->port,
5541                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
5542                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
5543                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
5544                    "Router")));
5545
5546   /* Purge the outgoing data queue to assure that all rekey packets really
5547      go to the network before we quit the protocol. */
5548   silc_server_packet_queue_purge(server, sock);
5549
5550   /* Re-register re-key timeout */
5551   if (ctx->responder == FALSE)
5552     silc_schedule_task_add(server->schedule, sock->sock,
5553                            silc_server_rekey_callback,
5554                            sock, idata->rekey->timeout, 0,
5555                            SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
5556
5557   /* Cleanup */
5558   silc_protocol_free(protocol);
5559   sock->protocol = NULL;
5560   if (ctx->packet)
5561     silc_packet_context_free(ctx->packet);
5562   if (ctx->ske)
5563     silc_ske_free(ctx->ske);
5564   silc_socket_free(sock);
5565   silc_free(ctx);
5566 }
5567
5568 /* Task callback used to retrieve network statistical information from
5569    router server once in a while. */
5570
5571 SILC_TASK_CALLBACK(silc_server_get_stats)
5572 {
5573   SilcServer server = (SilcServer)context;
5574   SilcBuffer idp, packet;
5575
5576   if (!server->standalone) {
5577     SILC_LOG_DEBUG(("Retrieving stats from router"));
5578     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5579     packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5580                                             ++server->cmd_ident, 1,
5581                                             1, idp->data, idp->len);
5582     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5583                             SILC_PACKET_COMMAND, 0, packet->data,
5584                             packet->len, FALSE);
5585     silc_buffer_free(packet);
5586     silc_buffer_free(idp);
5587   }
5588
5589   silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5590                          server, 120, 0, SILC_TASK_TIMEOUT,
5591                          SILC_TASK_PRI_LOW);
5592 }