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