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