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