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