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