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