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