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