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