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