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