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