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