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