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