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