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