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