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