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