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