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