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