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