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