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