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