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