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