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