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