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