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