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