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