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