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