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