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