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