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