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