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