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