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