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