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