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