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