f3022c2dd544006ecd398a6a42f01c465e408e38
[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.status |= SILC_IDLIST_STATUS_REGISTERED;
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->status |= SILC_IDLIST_STATUS_REGISTERED;
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   SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1219   void *id_entry = NULL;
1220
1221   SILC_LOG_DEBUG(("Start"));
1222
1223   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1224       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1225     /* Error occured during protocol */
1226     silc_protocol_free(protocol);
1227     sock->protocol = NULL;
1228     if (ctx->packet)
1229       silc_packet_context_free(ctx->packet);
1230     if (ctx->ske)
1231       silc_ske_free(ctx->ske);
1232     if (ctx->dest_id)
1233       silc_free(ctx->dest_id);
1234     silc_free(ctx);
1235     if (sock)
1236       sock->protocol = NULL;
1237     silc_schedule_task_del_by_callback(server->schedule,
1238                                      silc_server_failure_callback);
1239     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1240                                   "Authentication failed");
1241     server->stat.auth_failures++;
1242     return;
1243   }
1244
1245   entry->data.last_receive = time(NULL);
1246
1247   switch (ctx->conn_type) {
1248   case SILC_SOCKET_TYPE_CLIENT:
1249     {
1250       SilcClientEntry client;
1251
1252       SILC_LOG_DEBUG(("Remote host is client"));
1253       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1254                      sock->ip));
1255
1256       /* Add the client to the client ID cache. The nickname and Client ID
1257          and other information is created after we have received NEW_CLIENT
1258          packet from client. */
1259       client = silc_idlist_add_client(server->local_list, 
1260                                       NULL, NULL, NULL, NULL, NULL, sock);
1261       if (!client) {
1262         SILC_LOG_ERROR(("Could not add new client to cache"));
1263         silc_free(sock->user_data);
1264         silc_server_disconnect_remote(server, sock, 
1265                                       "Server closed connection: "
1266                                       "Authentication failed");
1267         server->stat.auth_failures++;
1268         goto out;
1269       }
1270
1271       /* Statistics */
1272       server->stat.my_clients++;
1273       server->stat.clients++;
1274       if (server->server_type == SILC_ROUTER)
1275         server->stat.cell_clients++;
1276
1277       id_entry = (void *)client;
1278       break;
1279     }
1280   case SILC_SOCKET_TYPE_SERVER:
1281   case SILC_SOCKET_TYPE_ROUTER:
1282     {
1283       SilcServerEntry new_server;
1284       SilcServerConfigSectionServerConnection *conn = 
1285         ctx->conn_type == SILC_SOCKET_TYPE_SERVER ? 
1286         ctx->sconfig : ctx->rconfig;
1287
1288       SILC_LOG_DEBUG(("Remote host is %s", 
1289                       ctx->conn_type == SILC_SOCKET_TYPE_SERVER ? 
1290                       "server" : "router"));
1291       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1292                      sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ? 
1293                      "server" : "router"));
1294
1295       /* Add the server into server cache. The server name and Server ID
1296          is updated after we have received NEW_SERVER packet from the
1297          server. We mark ourselves as router for this server if we really
1298          are router. */
1299       new_server = 
1300         silc_idlist_add_server(server->local_list, NULL,
1301                                ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1302                                SILC_SERVER : SILC_ROUTER, NULL, 
1303                                ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1304                                server->id_entry : NULL, sock);
1305       if (!new_server) {
1306         SILC_LOG_ERROR(("Could not add new server to cache"));
1307         silc_free(sock->user_data);
1308         silc_server_disconnect_remote(server, sock, 
1309                                       "Server closed connection: "
1310                                       "Authentication failed");
1311         server->stat.auth_failures++;
1312         goto out;
1313       }
1314
1315       /* Statistics */
1316       if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1317         server->stat.my_servers++;
1318       else
1319         server->stat.my_routers++;
1320       server->stat.servers++;
1321
1322       id_entry = (void *)new_server;
1323
1324       /* Check whether this connection is to be our primary router connection
1325          if we dont' already have the primary route. */
1326       if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1327         if (silc_server_config_is_primary_route(server->config) &&
1328             !conn->initiator)
1329           break;
1330
1331         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1332         server->standalone = FALSE;
1333         if (!server->id_entry->router) {
1334           server->id_entry->router = id_entry;
1335           server->router = id_entry;
1336         }
1337       }
1338
1339       break;
1340     }
1341   default:
1342     break;
1343   }
1344
1345   sock->type = ctx->conn_type;
1346
1347   /* Add the common data structure to the ID entry. */
1348   if (id_entry)
1349     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1350       
1351   /* Add to sockets internal pointer for fast referencing */
1352   silc_free(sock->user_data);
1353   sock->user_data = id_entry;
1354
1355   /* Connection has been fully established now. Everything is ok. */
1356   SILC_LOG_DEBUG(("New connection authenticated"));
1357
1358   /* Perform keepalive. The `hb_context' will be freed automatically
1359      when finally calling the silc_socket_free function. XXX hardcoded 
1360      timeout!! */
1361   hb_context = silc_calloc(1, sizeof(*hb_context));
1362   hb_context->server = server;
1363   silc_socket_set_heartbeat(sock, 600, hb_context,
1364                             silc_server_perform_heartbeat,
1365                             server->schedule);
1366
1367  out:
1368   silc_schedule_task_del_by_callback(server->schedule,
1369                                      silc_server_failure_callback);
1370   silc_protocol_free(protocol);
1371   if (ctx->packet)
1372     silc_packet_context_free(ctx->packet);
1373   if (ctx->ske)
1374     silc_ske_free(ctx->ske);
1375   if (ctx->dest_id)
1376     silc_free(ctx->dest_id);
1377   silc_free(ctx);
1378   sock->protocol = NULL;
1379 }
1380
1381 /* This function is used to read packets from network and send packets to
1382    network. This is usually a generic task. */
1383
1384 SILC_TASK_CALLBACK(silc_server_packet_process)
1385 {
1386   SilcServer server = (SilcServer)context;
1387   SilcSocketConnection sock = server->sockets[fd];
1388   SilcIDListData idata;
1389   SilcCipher cipher = NULL;
1390   SilcHmac hmac = NULL;
1391   int ret;
1392
1393   if (!sock)
1394     return;
1395
1396   SILC_LOG_DEBUG(("Processing packet"));
1397
1398   /* Packet sending */
1399
1400   if (type == SILC_TASK_WRITE) {
1401     /* Do not send data to disconnected connection */
1402     if (SILC_IS_DISCONNECTED(sock))
1403       return;
1404
1405     server->stat.packets_sent++;
1406
1407     if (sock->outbuf->data - sock->outbuf->head)
1408      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1409
1410     /* Send the packet */
1411     ret = silc_packet_send(sock, TRUE);
1412
1413     /* If returned -2 could not write to connection now, will do
1414        it later. */
1415     if (ret == -2)
1416       return;
1417
1418     if (ret == -1) {
1419       SILC_LOG_ERROR(("Error sending packet to connection "
1420                       "%s:%d [%s]", sock->hostname, sock->port,  
1421                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1422                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1423                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1424                        "Router")));
1425       return;
1426     }
1427     
1428     /* The packet has been sent and now it is time to set the connection
1429        back to only for input. When there is again some outgoing data 
1430        available for this connection it will be set for output as well. 
1431        This call clears the output setting and sets it only for input. */
1432     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1433     SILC_UNSET_OUTBUF_PENDING(sock);
1434
1435     silc_buffer_clear(sock->outbuf);
1436     return;
1437   }
1438
1439   /* Packet receiving */
1440
1441   /* Read some data from connection */
1442   ret = silc_packet_receive(sock);
1443   if (ret < 0) {
1444
1445     if (ret == -1)
1446       SILC_LOG_ERROR(("Error receiving packet from connection "
1447                       "%s:%d [%s]", sock->hostname, sock->port,  
1448                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1449                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1450                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1451                        "Router")));
1452     return;
1453   }    
1454
1455   /* EOF */
1456   if (ret == 0) {
1457     SILC_LOG_DEBUG(("Read EOF"));
1458       
1459     /* If connection is disconnecting already we will finally
1460        close the connection */
1461     if (SILC_IS_DISCONNECTING(sock)) {
1462       if (sock->user_data)
1463         silc_server_free_sock_user_data(server, sock);
1464       silc_server_close_connection(server, sock);
1465       return;
1466     }
1467       
1468     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1469     SILC_SET_DISCONNECTING(sock);
1470
1471     /* If the closed connection was our primary router connection the
1472        start re-connecting phase. */
1473     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1474         sock == server->router->connection)
1475       silc_schedule_task_add(server->schedule, 0, 
1476                              silc_server_connect_to_router,
1477                              context, 1, 0,
1478                              SILC_TASK_TIMEOUT,
1479                              SILC_TASK_PRI_NORMAL);
1480
1481     if (sock->user_data)
1482       silc_server_free_sock_user_data(server, sock);
1483     silc_server_close_connection(server, sock);
1484     return;
1485   }
1486
1487   /* If connection is disconnecting or disconnected we will ignore
1488      what we read. */
1489   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1490     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1491     return;
1492   }
1493
1494   server->stat.packets_received++;
1495
1496   /* Get keys and stuff from ID entry */
1497   idata = (SilcIDListData)sock->user_data;
1498   if (idata) {
1499     cipher = idata->receive_key;
1500     hmac = idata->hmac_receive;
1501   }
1502  
1503   /* Process the packet. This will call the parser that will then
1504      decrypt and parse the packet. */
1505   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1506                               server);
1507 }
1508
1509 /* Callback function that the silc_packet_decrypt will call to make the
1510    decision whether the packet is normal or special packet. We will 
1511    return TRUE if it is normal and FALSE if it is special */
1512
1513 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1514                                             SilcBuffer buffer,
1515                                             SilcPacketContext *packet,
1516                                             void *context)
1517 {
1518   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1519   SilcServer server = (SilcServer)parse_ctx->context;
1520
1521   /* Packet is normal packet, if: 
1522
1523      1) packet is private message packet and does not have private key set
1524      2) is other packet than channel message packet
1525      3) is channel message packet and remote is router and we are router 
1526
1527      all other packets are special packets 
1528   */
1529
1530   if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1531       (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1532     return FALSE;
1533
1534   if (packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1535       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1536        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1537        server->server_type == SILC_ROUTER))
1538     return TRUE;
1539
1540   return FALSE;
1541 }
1542   
1543 /* Parses whole packet, received earlier. */
1544
1545 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1546 {
1547   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1548   SilcServer server = (SilcServer)parse_ctx->context;
1549   SilcSocketConnection sock = parse_ctx->sock;
1550   SilcPacketContext *packet = parse_ctx->packet;
1551   SilcIDListData idata = (SilcIDListData)sock->user_data;
1552   int ret;
1553
1554   SILC_LOG_DEBUG(("Start"));
1555
1556   /* Decrypt the received packet */
1557   ret = silc_packet_decrypt(idata ? idata->receive_key : NULL, 
1558                             idata ? idata->hmac_receive : NULL, 
1559                             packet->buffer, packet,
1560                             silc_server_packet_decrypt_check, parse_ctx);
1561   if (ret < 0) {
1562     SILC_LOG_WARNING(("Packet decryption failed for connection "
1563                       "%s:%d [%s]", sock->hostname, sock->port,  
1564                       (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1565                        sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1566                        sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1567                        "Router")));
1568     goto out;
1569   }
1570
1571   if (ret == 0) {
1572     /* Parse the packet. Packet type is returned. */
1573     ret = silc_packet_parse(packet);
1574   } else {
1575     /* Parse the packet header in special way as this is "special"
1576        packet type. */
1577     ret = silc_packet_parse_special(packet);
1578   }
1579
1580   if (ret == SILC_PACKET_NONE)
1581     goto out;
1582
1583   /* Check that the the current client ID is same as in the client's packet. */
1584   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1585     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1586     if (client && client->id) {
1587       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1588                                 packet->src_id_type);
1589       if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1590         silc_free(id);
1591         goto out;
1592       }
1593       silc_free(id);
1594     }
1595   }
1596
1597   if (server->server_type == SILC_ROUTER) {
1598     /* Route the packet if it is not destined to us. Other ID types but
1599        server are handled separately after processing them. */
1600     if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1601         packet->dst_id_type == SILC_ID_SERVER && 
1602         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1603         memcmp(packet->dst_id, server->id_string, packet->dst_id_len)) {
1604       
1605       /* Route the packet to fastest route for the destination ID */
1606       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1607                                 packet->dst_id_type);
1608       if (!id)
1609         goto out;
1610       silc_server_packet_route(server,
1611                                silc_server_route_get(server, id,
1612                                                      packet->dst_id_type),
1613                                packet);
1614       silc_free(id);
1615       goto out;
1616     }
1617   }
1618
1619   /* Parse the incoming packet type */
1620   silc_server_packet_parse_type(server, sock, packet);
1621
1622   if (server->server_type == SILC_ROUTER) {
1623     /* Broadcast packet if it is marked as broadcast packet and it is
1624        originated from router and we are router. */
1625     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1626         packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1627         !server->standalone) {
1628       silc_server_packet_broadcast(server, server->router->connection, packet);
1629     }
1630   }
1631
1632  out:
1633   /*  silc_buffer_clear(sock->inbuf); */
1634   silc_packet_context_free(packet);
1635   silc_free(parse_ctx);
1636 }
1637
1638 /* Parser callback called by silc_packet_receive_process. This merely
1639    registers timeout that will handle the actual parsing when appropriate. */
1640
1641 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1642 {
1643   SilcServer server = (SilcServer)parser_context->context;
1644   SilcSocketConnection sock = parser_context->sock;
1645
1646   switch (sock->type) {
1647   case SILC_SOCKET_TYPE_UNKNOWN:
1648   case SILC_SOCKET_TYPE_CLIENT:
1649     /* Parse the packet with timeout */
1650     silc_schedule_task_add(server->schedule, sock->sock,
1651                            silc_server_packet_parse_real,
1652                            (void *)parser_context, 0, 100000,
1653                            SILC_TASK_TIMEOUT,
1654                            SILC_TASK_PRI_NORMAL);
1655     break;
1656   case SILC_SOCKET_TYPE_SERVER:
1657   case SILC_SOCKET_TYPE_ROUTER:
1658     /* Packets from servers are parsed as soon as possible */
1659     silc_schedule_task_add(server->schedule, sock->sock,
1660                            silc_server_packet_parse_real,
1661                            (void *)parser_context, 0, 1,
1662                            SILC_TASK_TIMEOUT,
1663                            SILC_TASK_PRI_NORMAL);
1664     break;
1665   default:
1666     return;
1667   }
1668 }
1669
1670 /* Parses the packet type and calls what ever routines the packet type
1671    requires. This is done for all incoming packets. */
1672
1673 void silc_server_packet_parse_type(SilcServer server, 
1674                                    SilcSocketConnection sock,
1675                                    SilcPacketContext *packet)
1676 {
1677   SilcPacketType type = packet->type;
1678   SilcIDListData idata = (SilcIDListData)sock->user_data;
1679
1680   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1681
1682   /* Parse the packet type */
1683   switch (type) {
1684   case SILC_PACKET_DISCONNECT:
1685     SILC_LOG_DEBUG(("Disconnect packet"));
1686     if (packet->flags & SILC_PACKET_FLAG_LIST)
1687       break;
1688     break;
1689
1690   case SILC_PACKET_SUCCESS:
1691     /*
1692      * Success received for something. For now we can have only
1693      * one protocol for connection executing at once hence this
1694      * success message is for whatever protocol is executing currently.
1695      */
1696     SILC_LOG_DEBUG(("Success packet"));
1697     if (packet->flags & SILC_PACKET_FLAG_LIST)
1698       break;
1699     if (sock->protocol)
1700       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1701     break;
1702
1703   case SILC_PACKET_FAILURE:
1704     /*
1705      * Failure received for something. For now we can have only
1706      * one protocol for connection executing at once hence this
1707      * failure message is for whatever protocol is executing currently.
1708      */
1709     SILC_LOG_DEBUG(("Failure packet"));
1710     if (packet->flags & SILC_PACKET_FLAG_LIST)
1711       break;
1712     if (sock->protocol) {
1713       SilcServerFailureContext f;
1714       f = silc_calloc(1, sizeof(*f));
1715       f->server = server;
1716       f->sock = sock;
1717       
1718       /* We will wait 5 seconds to process this failure packet */
1719       silc_schedule_task_add(server->schedule, sock->sock,
1720                          silc_server_failure_callback, (void *)f, 5, 0,
1721                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1722     }
1723     break;
1724
1725   case SILC_PACKET_REJECT:
1726     SILC_LOG_DEBUG(("Reject packet"));
1727     if (packet->flags & SILC_PACKET_FLAG_LIST)
1728       break;
1729     return;
1730     break;
1731
1732   case SILC_PACKET_NOTIFY:
1733     /*
1734      * Received notify packet. Server can receive notify packets from
1735      * router. Server then relays the notify messages to clients if needed.
1736      */
1737     SILC_LOG_DEBUG(("Notify packet"));
1738     if (packet->flags & SILC_PACKET_FLAG_LIST)
1739       silc_server_notify_list(server, sock, packet);
1740     else
1741       silc_server_notify(server, sock, packet);
1742     break;
1743
1744     /* 
1745      * Channel packets
1746      */
1747   case SILC_PACKET_CHANNEL_MESSAGE:
1748     /*
1749      * Received channel message. Channel messages are special packets
1750      * (although probably most common ones) thus they are handled
1751      * specially.
1752      */
1753     SILC_LOG_DEBUG(("Channel Message packet"));
1754     if (packet->flags & SILC_PACKET_FLAG_LIST)
1755       break;
1756     idata->last_receive = time(NULL);
1757     silc_server_channel_message(server, sock, packet);
1758     break;
1759
1760   case SILC_PACKET_CHANNEL_KEY:
1761     /*
1762      * Received key for channel. As channels are created by the router
1763      * the keys are as well. We will distribute the key to all of our
1764      * locally connected clients on the particular channel. Router
1765      * never receives this channel and thus is ignored.
1766      */
1767     SILC_LOG_DEBUG(("Channel Key packet"));
1768     if (packet->flags & SILC_PACKET_FLAG_LIST)
1769       break;
1770     silc_server_channel_key(server, sock, packet);
1771     break;
1772
1773     /*
1774      * Command packets
1775      */
1776   case SILC_PACKET_COMMAND:
1777     /*
1778      * Recived command. Processes the command request and allocates the
1779      * command context and calls the command.
1780      */
1781     SILC_LOG_DEBUG(("Command packet"));
1782     if (packet->flags & SILC_PACKET_FLAG_LIST)
1783       break;
1784     silc_server_command_process(server, sock, packet);
1785     break;
1786
1787   case SILC_PACKET_COMMAND_REPLY:
1788     /*
1789      * Received command reply packet. Received command reply to command. It
1790      * may be reply to command sent by us or reply to command sent by client
1791      * that we've routed further.
1792      */
1793     SILC_LOG_DEBUG(("Command Reply packet"));
1794     if (packet->flags & SILC_PACKET_FLAG_LIST)
1795       break;
1796     silc_server_command_reply(server, sock, packet);
1797     break;
1798
1799     /*
1800      * Private Message packets
1801      */
1802   case SILC_PACKET_PRIVATE_MESSAGE:
1803     /*
1804      * Received private message packet. The packet is coming from either
1805      * client or server.
1806      */
1807     SILC_LOG_DEBUG(("Private Message packet"));
1808     if (packet->flags & SILC_PACKET_FLAG_LIST)
1809       break;
1810     idata->last_receive = time(NULL);
1811     silc_server_private_message(server, sock, packet);
1812     break;
1813
1814   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1815     /*
1816      * Private message key packet.
1817      */
1818     if (packet->flags & SILC_PACKET_FLAG_LIST)
1819       break;
1820     silc_server_private_message_key(server, sock, packet);
1821     break;
1822
1823     /*
1824      * Key Exchange protocol packets
1825      */
1826   case SILC_PACKET_KEY_EXCHANGE:
1827     SILC_LOG_DEBUG(("KE packet"));
1828     if (packet->flags & SILC_PACKET_FLAG_LIST)
1829       break;
1830
1831     if (sock->protocol && sock->protocol->protocol &&
1832         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1833
1834       SilcServerKEInternalContext *proto_ctx = 
1835         (SilcServerKEInternalContext *)sock->protocol->context;
1836
1837       proto_ctx->packet = silc_packet_context_dup(packet);
1838
1839       /* Let the protocol handle the packet */
1840       silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
1841     } else {
1842       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1843                       "protocol active, packet dropped."));
1844     }
1845     break;
1846
1847   case SILC_PACKET_KEY_EXCHANGE_1:
1848     SILC_LOG_DEBUG(("KE 1 packet"));
1849     if (packet->flags & SILC_PACKET_FLAG_LIST)
1850       break;
1851
1852     if (sock->protocol && sock->protocol->protocol &&
1853         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1854          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1855
1856       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1857         SilcServerRekeyInternalContext *proto_ctx = 
1858           (SilcServerRekeyInternalContext *)sock->protocol->context;
1859         
1860         if (proto_ctx->packet)
1861           silc_packet_context_free(proto_ctx->packet);
1862         
1863         proto_ctx->packet = silc_packet_context_dup(packet);
1864
1865         /* Let the protocol handle the packet */
1866         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1867       } else {
1868         SilcServerKEInternalContext *proto_ctx = 
1869           (SilcServerKEInternalContext *)sock->protocol->context;
1870         
1871         if (proto_ctx->packet)
1872           silc_packet_context_free(proto_ctx->packet);
1873         
1874         proto_ctx->packet = silc_packet_context_dup(packet);
1875         proto_ctx->dest_id_type = packet->src_id_type;
1876         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1877                                             packet->src_id_type);
1878         if (!proto_ctx->dest_id)
1879           break;
1880
1881         /* Let the protocol handle the packet */
1882         silc_protocol_execute(sock->protocol, server->schedule, 
1883                               0, 100000);
1884       }
1885     } else {
1886       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1887                       "protocol active, packet dropped."));
1888     }
1889     break;
1890
1891   case SILC_PACKET_KEY_EXCHANGE_2:
1892     SILC_LOG_DEBUG(("KE 2 packet"));
1893     if (packet->flags & SILC_PACKET_FLAG_LIST)
1894       break;
1895
1896     if (sock->protocol && sock->protocol->protocol &&
1897         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1898          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1899
1900       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1901         SilcServerRekeyInternalContext *proto_ctx = 
1902           (SilcServerRekeyInternalContext *)sock->protocol->context;
1903         
1904         if (proto_ctx->packet)
1905           silc_packet_context_free(proto_ctx->packet);
1906         
1907         proto_ctx->packet = silc_packet_context_dup(packet);
1908
1909         /* Let the protocol handle the packet */
1910         silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1911       } else {
1912         SilcServerKEInternalContext *proto_ctx = 
1913           (SilcServerKEInternalContext *)sock->protocol->context;
1914         
1915         if (proto_ctx->packet)
1916           silc_packet_context_free(proto_ctx->packet);
1917         
1918         proto_ctx->packet = silc_packet_context_dup(packet);
1919         proto_ctx->dest_id_type = packet->src_id_type;
1920         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1921                                             packet->src_id_type);
1922         if (!proto_ctx->dest_id)
1923           break;
1924
1925         /* Let the protocol handle the packet */
1926         silc_protocol_execute(sock->protocol, server->schedule, 
1927                               0, 100000);
1928       }
1929     } else {
1930       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1931                       "protocol active, packet dropped."));
1932     }
1933     break;
1934
1935   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1936     /*
1937      * Connection authentication request packet. When we receive this packet
1938      * we will send to the other end information about our mandatory
1939      * authentication method for the connection. This packet maybe received
1940      * at any time. 
1941      */
1942     SILC_LOG_DEBUG(("Connection authentication request packet"));
1943     if (packet->flags & SILC_PACKET_FLAG_LIST)
1944       break;
1945     silc_server_connection_auth_request(server, sock, packet);
1946     break;
1947
1948     /*
1949      * Connection Authentication protocol packets
1950      */
1951   case SILC_PACKET_CONNECTION_AUTH:
1952     /* Start of the authentication protocol. We receive here the 
1953        authentication data and will verify it. */
1954     SILC_LOG_DEBUG(("Connection auth packet"));
1955     if (packet->flags & SILC_PACKET_FLAG_LIST)
1956       break;
1957
1958     if (sock->protocol && sock->protocol->protocol->type 
1959         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1960
1961       SilcServerConnAuthInternalContext *proto_ctx = 
1962         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1963
1964       proto_ctx->packet = silc_packet_context_dup(packet);
1965
1966       /* Let the protocol handle the packet */
1967       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1968     } else {
1969       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1970                       "protocol active, packet dropped."));
1971     }
1972     break;
1973
1974   case SILC_PACKET_NEW_ID:
1975     /*
1976      * Received New ID packet. This includes some new ID that has been
1977      * created. It may be for client, server or channel. This is the way
1978      * to distribute information about new registered entities in the
1979      * SILC network.
1980      */
1981     SILC_LOG_DEBUG(("New ID packet"));
1982     if (packet->flags & SILC_PACKET_FLAG_LIST)
1983       silc_server_new_id_list(server, sock, packet);
1984     else
1985       silc_server_new_id(server, sock, packet);
1986     break;
1987
1988   case SILC_PACKET_NEW_CLIENT:
1989     /*
1990      * Received new client packet. This includes client information that
1991      * we will use to create initial client ID. After creating new
1992      * ID we will send it to the client.
1993      */
1994     SILC_LOG_DEBUG(("New Client packet"));
1995     if (packet->flags & SILC_PACKET_FLAG_LIST)
1996       break;
1997     silc_server_new_client(server, sock, packet);
1998     break;
1999
2000   case SILC_PACKET_NEW_SERVER:
2001     /*
2002      * Received new server packet. This includes Server ID and some other
2003      * information that we may save. This is received after server has 
2004      * connected to us.
2005      */
2006     SILC_LOG_DEBUG(("New Server packet"));
2007     if (packet->flags & SILC_PACKET_FLAG_LIST)
2008       break;
2009     silc_server_new_server(server, sock, packet);
2010     break;
2011
2012   case SILC_PACKET_NEW_CHANNEL:
2013     /*
2014      * Received new channel packet. Information about new channel in the
2015      * network are distributed using this packet.
2016      */
2017     SILC_LOG_DEBUG(("New Channel packet"));
2018     if (packet->flags & SILC_PACKET_FLAG_LIST)
2019       silc_server_new_channel_list(server, sock, packet);
2020     else
2021       silc_server_new_channel(server, sock, packet);
2022     break;
2023
2024   case SILC_PACKET_HEARTBEAT:
2025     /*
2026      * Received heartbeat.
2027      */
2028     SILC_LOG_DEBUG(("Heartbeat packet"));
2029     if (packet->flags & SILC_PACKET_FLAG_LIST)
2030       break;
2031     break;
2032
2033   case SILC_PACKET_KEY_AGREEMENT:
2034     /*
2035      * Received heartbeat.
2036      */
2037     SILC_LOG_DEBUG(("Key agreement packet"));
2038     if (packet->flags & SILC_PACKET_FLAG_LIST)
2039       break;
2040     silc_server_key_agreement(server, sock, packet);
2041     break;
2042
2043   case SILC_PACKET_REKEY:
2044     /*
2045      * Received re-key packet. The sender wants to regenerate the session
2046      * keys.
2047      */
2048     SILC_LOG_DEBUG(("Re-key packet"));
2049     if (packet->flags & SILC_PACKET_FLAG_LIST)
2050       break;
2051     silc_server_rekey(server, sock, packet);
2052     break;
2053
2054   case SILC_PACKET_REKEY_DONE:
2055     /*
2056      * The re-key is done.
2057      */
2058     SILC_LOG_DEBUG(("Re-key done packet"));
2059     if (packet->flags & SILC_PACKET_FLAG_LIST)
2060       break;
2061
2062     if (sock->protocol && sock->protocol->protocol &&
2063         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2064
2065       SilcServerRekeyInternalContext *proto_ctx = 
2066         (SilcServerRekeyInternalContext *)sock->protocol->context;
2067
2068       if (proto_ctx->packet)
2069         silc_packet_context_free(proto_ctx->packet);
2070
2071       proto_ctx->packet = silc_packet_context_dup(packet);
2072
2073       /* Let the protocol handle the packet */
2074       silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2075     } else {
2076       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2077                       "protocol active, packet dropped."));
2078     }
2079     break;
2080
2081   default:
2082     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2083     break;
2084   }
2085   
2086 }
2087
2088 /* Creates connection to a remote router. */
2089
2090 void silc_server_create_connection(SilcServer server,
2091                                    char *remote_host, uint32 port)
2092 {
2093   SilcServerConnection sconn;
2094
2095   /* Allocate connection object for hold connection specific stuff. */
2096   sconn = silc_calloc(1, sizeof(*sconn));
2097   sconn->server = server;
2098   sconn->remote_host = strdup(remote_host);
2099   sconn->remote_port = port;
2100
2101   silc_schedule_task_add(server->schedule, 0, 
2102                          silc_server_connect_router,
2103                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
2104                          SILC_TASK_PRI_NORMAL);
2105 }
2106
2107 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2108 {
2109   silc_socket_free((SilcSocketConnection)context);
2110 }
2111
2112 /* Closes connection to socket connection */
2113
2114 void silc_server_close_connection(SilcServer server,
2115                                   SilcSocketConnection sock)
2116 {
2117   SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2118                   sock->port,
2119                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2120                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2121                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2122                    "Router")));
2123
2124   /* We won't listen for this connection anymore */
2125   silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2126
2127   /* Unregister all tasks */
2128   silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2129
2130   /* Close the actual connection */
2131   silc_net_close_connection(sock->sock);
2132   server->sockets[sock->sock] = NULL;
2133
2134   /* If sock->user_data is NULL then we'll check for active protocols
2135      here since the silc_server_free_sock_user_data has not been called
2136      for this connection. */
2137   if (!sock->user_data) {
2138     /* If any protocol is active cancel its execution. It will call
2139        the final callback which will finalize the disconnection. */
2140     if (sock->protocol) {
2141       silc_protocol_cancel(sock->protocol, server->schedule);
2142       sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2143       silc_protocol_execute_final(sock->protocol, server->schedule);
2144       sock->protocol = NULL;
2145       return;
2146     }
2147   }
2148
2149   silc_schedule_task_add(server->schedule, 0, 
2150                          silc_server_close_connection_final,
2151                          (void *)sock, 0, 1, SILC_TASK_TIMEOUT, 
2152                          SILC_TASK_PRI_NORMAL);
2153 }
2154
2155 /* Sends disconnect message to remote connection and disconnects the 
2156    connection. */
2157
2158 void silc_server_disconnect_remote(SilcServer server,
2159                                    SilcSocketConnection sock,
2160                                    const char *fmt, ...)
2161 {
2162   va_list ap;
2163   unsigned char buf[4096];
2164
2165   if (!sock)
2166     return;
2167
2168   memset(buf, 0, sizeof(buf));
2169   va_start(ap, fmt);
2170   vsprintf(buf, fmt, ap);
2171   va_end(ap);
2172
2173   SILC_LOG_DEBUG(("Disconnecting remote host"));
2174
2175   /* Notify remote end that the conversation is over. The notify message
2176      is tried to be sent immediately. */
2177   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
2178                           buf, strlen(buf), TRUE);
2179
2180   /* Mark the connection to be disconnected */
2181   SILC_SET_DISCONNECTED(sock);
2182   silc_server_close_connection(server, sock);
2183 }
2184
2185 typedef struct {
2186   SilcServer server;
2187   SilcClientEntry client;
2188 } *FreeClientInternal;
2189
2190 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2191 {
2192   FreeClientInternal i = (FreeClientInternal)context;
2193
2194   silc_idlist_del_data(i->client);
2195   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2196   silc_free(i);
2197 }
2198
2199 /* Frees client data and notifies about client's signoff. */
2200
2201 void silc_server_free_client_data(SilcServer server, 
2202                                   SilcSocketConnection sock,
2203                                   SilcClientEntry client, 
2204                                   int notify,
2205                                   char *signoff)
2206 {
2207   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2208
2209   /* If there is pending outgoing data for the client then purge it
2210      to the network before removing the client entry. */
2211   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
2212       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2213     server->stat.packets_sent++;
2214
2215     if (sock->outbuf->data - sock->outbuf->head)
2216      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2217
2218     silc_packet_send(sock, TRUE);
2219
2220     SILC_SET_CONNECTION_FOR_INPUT(server->schedule, sock->sock);
2221     SILC_UNSET_OUTBUF_PENDING(sock);
2222     silc_buffer_clear(sock->outbuf);
2223   }
2224
2225   /* Send SIGNOFF notify to routers. */
2226   if (notify && !server->standalone && server->router)
2227     silc_server_send_notify_signoff(server, server->router->connection,
2228                                     server->server_type == SILC_SERVER ?
2229                                     FALSE : TRUE, client->id, signoff);
2230
2231   /* Remove client from all channels */
2232   if (notify)
2233     silc_server_remove_from_channels(server, NULL, client, 
2234                                      TRUE, signoff, TRUE);
2235   else
2236     silc_server_remove_from_channels(server, NULL, client, 
2237                                      FALSE, NULL, FALSE);
2238
2239   /* We will not delete the client entry right away. We will take it
2240      into history (for WHOWAS command) for 5 minutes */
2241   i->server = server;
2242   i->client = client;
2243   silc_schedule_task_add(server->schedule, 0, 
2244                          silc_server_free_client_data_timeout,
2245                          (void *)i, 300, 0,
2246                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2247   client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2248   client->router = NULL;
2249   client->connection = NULL;
2250
2251   /* Free the client entry and everything in it */
2252   server->stat.my_clients--;
2253   server->stat.clients--;
2254   if (server->server_type == SILC_ROUTER)
2255     server->stat.cell_clients--;
2256 }
2257
2258 /* Frees user_data pointer from socket connection object. This also sends
2259    appropriate notify packets to the network to inform about leaving
2260    entities. */
2261
2262 void silc_server_free_sock_user_data(SilcServer server, 
2263                                      SilcSocketConnection sock)
2264 {
2265   SILC_LOG_DEBUG(("Start"));
2266
2267   switch (sock->type) {
2268   case SILC_SOCKET_TYPE_CLIENT:
2269     {
2270       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2271       silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2272       break;
2273     }
2274   case SILC_SOCKET_TYPE_SERVER:
2275   case SILC_SOCKET_TYPE_ROUTER:
2276     {
2277       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2278
2279       /* Free all client entries that this server owns as they will
2280          become invalid now as well. */
2281       if (user_data->id)
2282         silc_server_remove_clients_by_server(server, user_data, TRUE);
2283
2284       /* If this was our primary router connection then we're lost to
2285          the outside world. */
2286       if (server->router == user_data) {
2287         server->id_entry->router = NULL;
2288         server->router = NULL;
2289         server->standalone = TRUE;
2290       }
2291
2292       /* Free the server entry */
2293       silc_idlist_del_data(user_data);
2294       silc_idlist_del_server(server->local_list, user_data);
2295       server->stat.my_servers--;
2296       server->stat.servers--;
2297       if (server->server_type == SILC_ROUTER)
2298         server->stat.cell_servers--;
2299       break;
2300     }
2301   default:
2302     {
2303       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2304
2305       silc_idlist_del_data(user_data);
2306       silc_free(user_data);
2307       break;
2308     }
2309   }
2310
2311   /* If any protocol is active cancel its execution */
2312   if (sock->protocol) {
2313     silc_protocol_cancel(sock->protocol, server->schedule);
2314     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2315     silc_protocol_execute_final(sock->protocol, server->schedule);
2316     sock->protocol = NULL;
2317   }
2318
2319   sock->user_data = NULL;
2320 }
2321
2322 /* Removes the client from channels and possibly removes the channels
2323    as well.  After removing those channels that exist, their channel
2324    keys are regnerated. This is called only by the function
2325    silc_server_remove_clients_by_server. */
2326
2327 static void silc_server_remove_clients_channels(SilcServer server, 
2328                                                 SilcSocketConnection sock,
2329                                                 SilcClientEntry client,
2330                                                 SilcHashTable channels)
2331 {
2332   SilcChannelEntry channel;
2333   SilcChannelClientEntry chl;
2334   SilcHashTableList htl;
2335   SilcBuffer clidp;
2336
2337   SILC_LOG_DEBUG(("Start"));
2338
2339   if (!client || !client->id)
2340     return;
2341
2342   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2343
2344   /* Remove the client from all channels. The client is removed from
2345      the channels' user list. */
2346   silc_hash_table_list(client->channels, &htl);
2347   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2348     channel = chl->channel;
2349
2350     /* Remove channel from client's channel list */
2351     silc_hash_table_del(client->channels, channel);
2352
2353     /* Remove channel if there is no users anymore */
2354     if (server->server_type == SILC_ROUTER &&
2355         silc_hash_table_count(channel->user_list) < 2) {
2356
2357       if (silc_hash_table_find(channels, channel, NULL, NULL))
2358         silc_hash_table_del(channels, channel);
2359
2360       if (channel->rekey)
2361         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2362
2363       if (!silc_idlist_del_channel(server->local_list, channel))
2364         silc_idlist_del_channel(server->global_list, channel);
2365       server->stat.my_channels--;
2366       continue;
2367     }
2368
2369     /* Remove client from channel's client list */
2370     silc_hash_table_del(channel->user_list, chl->client);
2371     silc_free(chl);
2372     server->stat.my_chanclients--;
2373
2374     /* If there is no global users on the channel anymore mark the channel
2375        as local channel. Do not check if the removed client is local client. */
2376     if (server->server_type == SILC_SERVER && channel->global_users && 
2377         chl->client->router && !silc_server_channel_has_global(channel))
2378       channel->global_users = FALSE;
2379
2380     /* If there is not at least one local user on the channel then we don't
2381        need the channel entry anymore, we can remove it safely. */
2382     if (server->server_type == SILC_SERVER &&
2383         !silc_server_channel_has_local(channel)) {
2384
2385       if (silc_hash_table_find(channels, channel, NULL, NULL))
2386         silc_hash_table_del(channels, channel);
2387
2388       if (channel->rekey)
2389         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2390
2391       if (channel->founder_key) {
2392         /* The founder auth data exists, do not remove the channel entry */
2393         SilcChannelClientEntry chl2;
2394         SilcHashTableList htl2;
2395
2396         channel->id = NULL;
2397
2398         silc_hash_table_list(channel->user_list, &htl2);
2399         while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2400           silc_hash_table_del(chl2->client->channels, channel);
2401           silc_hash_table_del(channel->user_list, chl2->client);
2402           silc_free(chl2);
2403         }
2404         continue;
2405       }
2406
2407       /* Remove the channel entry */
2408       if (!silc_idlist_del_channel(server->local_list, channel))
2409         silc_idlist_del_channel(server->global_list, channel);
2410       server->stat.my_channels--;
2411       continue;
2412     }
2413
2414     /* Add the channel to the the channels list to regenerate the 
2415        channel key */
2416     if (!silc_hash_table_find(channels, channel, NULL, NULL))
2417       silc_hash_table_add(channels, channel, channel);
2418   }
2419
2420   silc_buffer_free(clidp);
2421 }
2422
2423 /* This function is used to remove all client entries by the server `entry'.
2424    This is called when the connection is lost to the server. In this case
2425    we must invalidate all the client entries owned by the server `entry'. 
2426    If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2427    distributed to our local clients. */
2428
2429 int silc_server_remove_clients_by_server(SilcServer server, 
2430                                          SilcServerEntry entry,
2431                                          int server_signoff)
2432 {
2433   SilcIDCacheList list = NULL;
2434   SilcIDCacheEntry id_cache = NULL;
2435   SilcClientEntry client = NULL;
2436   SilcBuffer idp;
2437   SilcClientEntry *clients = NULL;
2438   uint32 clients_c = 0;
2439   unsigned char **argv = NULL;
2440   uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2441   SilcHashTableList htl;
2442   SilcChannelEntry channel;
2443   SilcHashTable channels;
2444   int i;
2445
2446   SILC_LOG_DEBUG(("Start"));
2447
2448   /* Allocate the hash table that holds the channels that require
2449      channel key re-generation after we've removed this server's clients
2450      from the channels. */
2451   channels = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL, NULL,
2452                                    NULL, NULL, TRUE);
2453
2454   if (server_signoff) {
2455     idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2456     argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2457     argv_lens = silc_realloc(argv_lens,  sizeof(*argv_lens) * (argc + 1));
2458     argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2459     argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2460     memcpy(argv[argc], idp->data, idp->len);
2461     argv_lens[argc] = idp->len;
2462     argv_types[argc] = argc + 1;
2463     argc++;
2464     silc_buffer_free(idp);
2465   }
2466
2467   if (silc_idcache_get_all(server->local_list->clients, &list)) {
2468
2469     if (silc_idcache_list_first(list, &id_cache)) {
2470       while (id_cache) {
2471         client = (SilcClientEntry)id_cache->context;
2472         if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2473           if (!silc_idcache_list_next(list, &id_cache))
2474             break;
2475           else
2476             continue;
2477         }
2478
2479         if (client->router != entry) {
2480           if (server_signoff && client->connection) {
2481             clients = silc_realloc(clients, 
2482                                    sizeof(*clients) * (clients_c + 1));
2483             clients[clients_c] = client;
2484             clients_c++;
2485           }
2486
2487           if (!silc_idcache_list_next(list, &id_cache))
2488             break;
2489           else
2490             continue;
2491         }
2492
2493         if (server_signoff) {
2494           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2495           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2496           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2497                                    (argc + 1));
2498           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2499                                     (argc + 1));
2500           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2501           memcpy(argv[argc], idp->data, idp->len);
2502           argv_lens[argc] = idp->len;
2503           argv_types[argc] = argc + 1;
2504           argc++;
2505           silc_buffer_free(idp);
2506         }
2507
2508         /* Remove the client entry */
2509         silc_server_remove_clients_channels(server, NULL, client, channels);
2510         silc_idlist_del_client(server->local_list, client);
2511
2512         if (!silc_idcache_list_next(list, &id_cache))
2513           break;
2514       }
2515     }
2516     silc_idcache_list_free(list);
2517   }
2518   
2519   if (silc_idcache_get_all(server->global_list->clients, &list)) {
2520
2521     if (silc_idcache_list_first(list, &id_cache)) {
2522       while (id_cache) {
2523         client = (SilcClientEntry)id_cache->context;
2524         if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2525           if (!silc_idcache_list_next(list, &id_cache))
2526             break;
2527           else
2528             continue;
2529         }
2530         
2531         if (client->router != entry) {
2532           if (server_signoff && client->connection) {
2533             clients = silc_realloc(clients, 
2534                                    sizeof(*clients) * (clients_c + 1));
2535             clients[clients_c] = client;
2536             clients_c++;
2537           }
2538
2539           if (!silc_idcache_list_next(list, &id_cache))
2540             break;
2541           else
2542             continue;
2543         }
2544
2545         if (server_signoff) {
2546           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2547           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2548           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2549                                    (argc + 1));
2550           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2551                                     (argc + 1));
2552           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2553           memcpy(argv[argc], idp->data, idp->len);
2554           argv_lens[argc] = idp->len;
2555           argv_types[argc] = argc + 1;
2556           argc++;
2557           silc_buffer_free(idp);
2558         }
2559
2560         /* Remove the client entry */
2561         silc_server_remove_clients_channels(server, NULL, client, channels);
2562         silc_idlist_del_client(server->global_list, client);
2563
2564         if (!silc_idcache_list_next(list, &id_cache))
2565           break;
2566       }
2567     }
2568     silc_idcache_list_free(list);
2569   }
2570
2571   /* Send the SERVER_SIGNOFF notify */
2572   if (server_signoff) {
2573     SilcBuffer args;
2574
2575     /* Send SERVER_SIGNOFF notify to our primary router */
2576     if (!server->standalone && server->router &&
2577         server->router != entry) {
2578       args = silc_argument_payload_encode(1, argv, argv_lens,
2579                                           argv_types);
2580       silc_server_send_notify_args(server, 
2581                                    server->router->connection,
2582                                    server->server_type == SILC_SERVER ? 
2583                                    FALSE : TRUE, 
2584                                    SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2585                                    argc, args);
2586       silc_buffer_free(args);
2587     }
2588
2589     args = silc_argument_payload_encode(argc, argv, argv_lens,
2590                                         argv_types);
2591     /* Send to local clients */
2592     for (i = 0; i < clients_c; i++) {
2593       silc_server_send_notify_args(server, clients[i]->connection,
2594                                    FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2595                                    argc, args);
2596     }
2597
2598     silc_free(clients);
2599     silc_buffer_free(args);
2600     for (i = 0; i < argc; i++)
2601       silc_free(argv[i]);
2602     silc_free(argv);
2603     silc_free(argv_lens);
2604     silc_free(argv_types);
2605   }
2606
2607   /* We must now re-generate the channel key for all channels that had
2608      this server's client(s) on the channel. As they left the channel we
2609      must re-generate the channel key. */
2610   silc_hash_table_list(channels, &htl);
2611   while (silc_hash_table_get(&htl, NULL, (void *)&channel)) {
2612     if (!silc_server_create_channel_key(server, channel, 0))
2613       return FALSE;
2614
2615     /* Do not send the channel key if private channel key mode is set */
2616     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
2617       continue;
2618
2619     silc_server_send_channel_key(server, NULL, channel, 
2620                                  server->server_type == SILC_ROUTER ? 
2621                                  FALSE : !server->standalone);
2622   }
2623   silc_hash_table_free(channels);
2624
2625   return TRUE;
2626 }
2627
2628 /* Checks whether given channel has global users.  If it does this returns
2629    TRUE and FALSE if there is only locally connected clients on the channel. */
2630
2631 int silc_server_channel_has_global(SilcChannelEntry channel)
2632 {
2633   SilcChannelClientEntry chl;
2634   SilcHashTableList htl;
2635
2636   silc_hash_table_list(channel->user_list, &htl);
2637   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2638     if (chl->client->router)
2639       return TRUE;
2640   }
2641
2642   return FALSE;
2643 }
2644
2645 /* Checks whether given channel has locally connected users.  If it does this
2646    returns TRUE and FALSE if there is not one locally connected client. */
2647
2648 int silc_server_channel_has_local(SilcChannelEntry channel)
2649 {
2650   SilcChannelClientEntry chl;
2651   SilcHashTableList htl;
2652
2653   silc_hash_table_list(channel->user_list, &htl);
2654   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2655     if (!chl->client->router)
2656       return TRUE;
2657   }
2658
2659   return FALSE;
2660 }
2661
2662 /* Removes client from all channels it has joined. This is used when client
2663    connection is disconnected. If the client on a channel is last, the
2664    channel is removed as well. This sends the SIGNOFF notify types. */
2665
2666 void silc_server_remove_from_channels(SilcServer server, 
2667                                       SilcSocketConnection sock,
2668                                       SilcClientEntry client,
2669                                       int notify,
2670                                       char *signoff_message,
2671                                       int keygen)
2672 {
2673   SilcChannelEntry channel;
2674   SilcChannelClientEntry chl;
2675   SilcHashTableList htl;
2676   SilcBuffer clidp;
2677
2678   SILC_LOG_DEBUG(("Start"));
2679
2680   if (!client || !client->id)
2681     return;
2682
2683   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2684
2685   /* Remove the client from all channels. The client is removed from
2686      the channels' user list. */
2687   silc_hash_table_list(client->channels, &htl);
2688   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2689     channel = chl->channel;
2690
2691     /* Remove channel from client's channel list */
2692     silc_hash_table_del(client->channels, channel);
2693
2694     /* Remove channel if there is no users anymore */
2695     if (server->server_type == SILC_ROUTER &&
2696         silc_hash_table_count(channel->user_list) < 2) {
2697       if (channel->rekey)
2698         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2699       if (!silc_idlist_del_channel(server->local_list, channel))
2700         silc_idlist_del_channel(server->global_list, channel);
2701       server->stat.my_channels--;
2702       continue;
2703     }
2704
2705     /* Remove client from channel's client list */
2706     silc_hash_table_del(channel->user_list, chl->client);
2707     silc_free(chl);
2708     server->stat.my_chanclients--;
2709
2710     /* If there is no global users on the channel anymore mark the channel
2711        as local channel. Do not check if the removed client is local client. */
2712     if (server->server_type == SILC_SERVER && channel->global_users && 
2713         chl->client->router && !silc_server_channel_has_global(channel))
2714       channel->global_users = FALSE;
2715
2716     /* If there is not at least one local user on the channel then we don't
2717        need the channel entry anymore, we can remove it safely. */
2718     if (server->server_type == SILC_SERVER &&
2719         !silc_server_channel_has_local(channel)) {
2720       /* Notify about leaving client if this channel has global users. */
2721       if (notify && channel->global_users)
2722         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2723                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2724                                            signoff_message ? 2 : 1,
2725                                            clidp->data, clidp->len,
2726                                            signoff_message, signoff_message ?
2727                                            strlen(signoff_message) : 0);
2728
2729       if (channel->rekey)
2730         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2731
2732       if (channel->founder_key) {
2733         /* The founder auth data exists, do not remove the channel entry */
2734         SilcChannelClientEntry chl2;
2735         SilcHashTableList htl2;
2736
2737         channel->id = NULL;
2738
2739         silc_hash_table_list(channel->user_list, &htl2);
2740         while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2741           silc_hash_table_del(chl2->client->channels, channel);
2742           silc_hash_table_del(channel->user_list, chl2->client);
2743           silc_free(chl2);
2744         }
2745         continue;
2746       }
2747
2748       /* Remove the channel entry */
2749       if (!silc_idlist_del_channel(server->local_list, channel))
2750         silc_idlist_del_channel(server->global_list, channel);
2751       server->stat.my_channels--;
2752       continue;
2753     }
2754
2755     /* Send notify to channel about client leaving SILC and thus
2756        the entire channel. */
2757     if (notify)
2758       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2759                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2760                                          signoff_message ? 2 : 1,
2761                                          clidp->data, clidp->len,
2762                                          signoff_message, signoff_message ?
2763                                          strlen(signoff_message) : 0);
2764
2765     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2766       /* Re-generate channel key */
2767       if (!silc_server_create_channel_key(server, channel, 0))
2768         return;
2769       
2770       /* Send the channel key to the channel. The key of course is not sent
2771          to the client who was removed from the channel. */
2772       silc_server_send_channel_key(server, client->connection, channel, 
2773                                    server->server_type == SILC_ROUTER ? 
2774                                    FALSE : !server->standalone);
2775     }
2776   }
2777
2778   silc_buffer_free(clidp);
2779 }
2780
2781 /* Removes client from one channel. This is used for example when client
2782    calls LEAVE command to remove itself from the channel. Returns TRUE
2783    if channel still exists and FALSE if the channel is removed when
2784    last client leaves the channel. If `notify' is FALSE notify messages
2785    are not sent. */
2786
2787 int silc_server_remove_from_one_channel(SilcServer server, 
2788                                         SilcSocketConnection sock,
2789                                         SilcChannelEntry channel,
2790                                         SilcClientEntry client,
2791                                         int notify)
2792 {
2793   SilcChannelClientEntry chl;
2794   SilcBuffer clidp;
2795
2796   SILC_LOG_DEBUG(("Start"));
2797
2798   /* Get the entry to the channel, if this client is not on the channel
2799      then return Ok. */
2800   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2801     return TRUE;
2802
2803   /* Remove the client from the channel. The client is removed from
2804      the channel's user list. */
2805
2806   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2807
2808   /* Remove channel from client's channel list */
2809   silc_hash_table_del(client->channels, chl->channel);
2810
2811   /* Remove channel if there is no users anymore */
2812   if (server->server_type == SILC_ROUTER &&
2813       silc_hash_table_count(channel->user_list) < 2) {
2814     if (channel->rekey)
2815       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2816     if (!silc_idlist_del_channel(server->local_list, channel))
2817       silc_idlist_del_channel(server->global_list, channel);
2818     silc_buffer_free(clidp);
2819     server->stat.my_channels--;
2820     return FALSE;
2821   }
2822
2823   /* Remove client from channel's client list */
2824   silc_hash_table_del(channel->user_list, chl->client);
2825   silc_free(chl);
2826   server->stat.my_chanclients--;
2827   
2828   /* If there is no global users on the channel anymore mark the channel
2829      as local channel. Do not check if the client is local client. */
2830   if (server->server_type == SILC_SERVER && channel->global_users &&
2831       chl->client->router && !silc_server_channel_has_global(channel))
2832     channel->global_users = FALSE;
2833
2834   /* If there is not at least one local user on the channel then we don't
2835      need the channel entry anymore, we can remove it safely. */
2836   if (server->server_type == SILC_SERVER &&
2837       !silc_server_channel_has_local(channel)) {
2838     /* Notify about leaving client if this channel has global users. */
2839     if (notify && channel->global_users)
2840       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2841                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2842                                          clidp->data, clidp->len);
2843     
2844     silc_buffer_free(clidp);
2845     
2846     if (channel->rekey)
2847       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2848
2849     if (channel->founder_key) {
2850       /* The founder auth data exists, do not remove the channel entry */
2851       SilcChannelClientEntry chl2;
2852       SilcHashTableList htl2;
2853       
2854       channel->id = NULL;
2855       
2856       silc_hash_table_list(channel->user_list, &htl2);
2857       while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2858         silc_hash_table_del(chl2->client->channels, channel);
2859         silc_hash_table_del(channel->user_list, chl2->client);
2860         silc_free(chl2);
2861       }
2862       return FALSE;
2863     }
2864
2865     /* Remove the channel entry */
2866     if (!silc_idlist_del_channel(server->local_list, channel))
2867       silc_idlist_del_channel(server->global_list, channel);
2868     server->stat.my_channels--;
2869     return FALSE;
2870   }
2871
2872   /* Send notify to channel about client leaving the channel */
2873   if (notify)
2874     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2875                                        SILC_NOTIFY_TYPE_LEAVE, 1,
2876                                        clidp->data, clidp->len);
2877
2878   silc_buffer_free(clidp);
2879   return TRUE;
2880 }
2881
2882 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2883    This works because we assure that the user list on the channel is
2884    always in up to date thus we can only check the channel list from 
2885    `client' which is faster than checking the user list from `channel'. */
2886
2887 int silc_server_client_on_channel(SilcClientEntry client,
2888                                   SilcChannelEntry channel)
2889 {
2890   if (!client || !channel)
2891     return FALSE;
2892
2893   if (silc_hash_table_find(client->channels, channel, NULL, NULL))
2894     return TRUE;
2895
2896   return FALSE;
2897 }
2898
2899 /* Timeout callback. This is called if connection is idle or for some
2900    other reason is not responding within some period of time. This 
2901    disconnects the remote end. */
2902
2903 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2904 {
2905   SilcServer server = (SilcServer)context;
2906   SilcSocketConnection sock = server->sockets[fd];
2907
2908   SILC_LOG_DEBUG(("Start"));
2909
2910   if (!sock)
2911     return;
2912
2913   /* If we have protocol active we must assure that we call the protocol's
2914      final callback so that all the memory is freed. */
2915   if (sock->protocol) {
2916     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2917     silc_protocol_execute_final(sock->protocol, server->schedule);
2918     return;
2919   }
2920
2921   if (sock->user_data)
2922     silc_server_free_sock_user_data(server, sock);
2923
2924   silc_server_disconnect_remote(server, sock, "Server closed connection: "
2925                                 "Connection timeout");
2926 }
2927
2928 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2929    function may be used only by router. In real SILC network all channels
2930    are created by routers thus this function is never used by normal
2931    server. */
2932
2933 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2934                                                 SilcServerID *router_id,
2935                                                 char *cipher, 
2936                                                 char *hmac,
2937                                                 char *channel_name,
2938                                                 int broadcast)
2939 {
2940   SilcChannelID *channel_id;
2941   SilcChannelEntry entry;
2942   SilcCipher key;
2943   SilcHmac newhmac;
2944
2945   SILC_LOG_DEBUG(("Creating new channel"));
2946
2947   if (!cipher)
2948     cipher = SILC_DEFAULT_CIPHER;
2949   if (!hmac)
2950     hmac = SILC_DEFAULT_HMAC;
2951
2952   /* Allocate cipher */
2953   if (!silc_cipher_alloc(cipher, &key))
2954     return NULL;
2955
2956   /* Allocate hmac */
2957   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2958     silc_cipher_free(key);
2959     return NULL;
2960   }
2961
2962   channel_name = strdup(channel_name);
2963
2964   /* Create the channel */
2965   if (!silc_id_create_channel_id(server, router_id, server->rng, 
2966                                  &channel_id)) {
2967     silc_free(channel_name);
2968     silc_cipher_free(key);
2969     silc_hmac_free(newhmac);
2970     return NULL;
2971   }
2972   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2973                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2974                                   NULL, key, newhmac);
2975   if (!entry) {
2976     silc_free(channel_name);
2977     silc_cipher_free(key);
2978     silc_hmac_free(newhmac);
2979     return NULL;
2980   }
2981
2982   entry->cipher = strdup(cipher);
2983   entry->hmac_name = strdup(hmac);
2984
2985   /* Now create the actual key material */
2986   if (!silc_server_create_channel_key(server, entry, 
2987                                       silc_cipher_get_key_len(key) / 8)) {
2988     silc_free(channel_name);
2989     silc_cipher_free(key);
2990     silc_hmac_free(newhmac);
2991     silc_free(entry->cipher);
2992     silc_free(entry->hmac_name);
2993     return NULL;
2994   }
2995
2996   /* Notify other routers about the new channel. We send the packet
2997      to our primary route. */
2998   if (broadcast && server->standalone == FALSE)
2999     silc_server_send_new_channel(server, server->router->connection, TRUE, 
3000                                  channel_name, entry->id, 
3001                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3002                                  entry->mode);
3003
3004   server->stat.my_channels++;
3005
3006   return entry;
3007 }
3008
3009 /* Same as above but creates the channel with Channel ID `channel_id. */
3010
3011 SilcChannelEntry 
3012 silc_server_create_new_channel_with_id(SilcServer server, 
3013                                        char *cipher, 
3014                                        char *hmac,
3015                                        char *channel_name,
3016                                        SilcChannelID *channel_id,
3017                                        int broadcast)
3018 {
3019   SilcChannelEntry entry;
3020   SilcCipher key;
3021   SilcHmac newhmac;
3022
3023   SILC_LOG_DEBUG(("Creating new channel"));
3024
3025   if (!cipher)
3026     cipher = SILC_DEFAULT_CIPHER;
3027   if (!hmac)
3028     hmac = SILC_DEFAULT_HMAC;
3029
3030   /* Allocate cipher */
3031   if (!silc_cipher_alloc(cipher, &key))
3032     return NULL;
3033
3034   /* Allocate hmac */
3035   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3036     silc_cipher_free(key);
3037     return NULL;
3038   }
3039
3040   channel_name = strdup(channel_name);
3041
3042   /* Create the channel */
3043   entry = silc_idlist_add_channel(server->local_list, channel_name, 
3044                                   SILC_CHANNEL_MODE_NONE, channel_id, 
3045                                   NULL, key, newhmac);
3046   if (!entry) {
3047     silc_free(channel_name);
3048     return NULL;
3049   }
3050
3051   /* Now create the actual key material */
3052   if (!silc_server_create_channel_key(server, entry, 
3053                                       silc_cipher_get_key_len(key) / 8)) {
3054     silc_free(channel_name);
3055     return NULL;
3056   }
3057
3058   /* Notify other routers about the new channel. We send the packet
3059      to our primary route. */
3060   if (broadcast && server->standalone == FALSE)
3061     silc_server_send_new_channel(server, server->router->connection, TRUE, 
3062                                  channel_name, entry->id, 
3063                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3064                                  entry->mode);
3065
3066   server->stat.my_channels++;
3067
3068   return entry;
3069 }
3070
3071 /* Channel's key re-key timeout callback. */
3072
3073 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3074 {
3075   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3076   SilcServer server = (SilcServer)rekey->context;
3077
3078   rekey->task = NULL;
3079
3080   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3081     return;
3082
3083   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3084 }
3085
3086 /* Generates new channel key. This is used to create the initial channel key
3087    but also to re-generate new key for channel. If `key_len' is provided
3088    it is the bytes of the key length. */
3089
3090 bool silc_server_create_channel_key(SilcServer server, 
3091                                     SilcChannelEntry channel,
3092                                     uint32 key_len)
3093 {
3094   int i;
3095   unsigned char channel_key[32], hash[32];
3096   uint32 len;
3097
3098   SILC_LOG_DEBUG(("Generating channel key"));
3099
3100   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3101     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3102     return TRUE;
3103   }
3104
3105   if (!channel->channel_key)
3106     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key))
3107       return FALSE;
3108
3109   if (key_len)
3110     len = key_len;
3111   else if (channel->key_len)
3112     len = channel->key_len / 8;
3113   else
3114     len = silc_cipher_get_key_len(channel->channel_key) / 8;
3115
3116   /* Create channel key */
3117   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3118   
3119   /* Set the key */
3120   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3121
3122   /* Remove old key if exists */
3123   if (channel->key) {
3124     memset(channel->key, 0, channel->key_len / 8);
3125     silc_free(channel->key);
3126   }
3127
3128   /* Save the key */
3129   channel->key_len = len * 8;
3130   channel->key = silc_calloc(len, sizeof(*channel->key));
3131   memcpy(channel->key, channel_key, len);
3132   memset(channel_key, 0, sizeof(channel_key));
3133
3134   /* Generate HMAC key from the channel key data and set it */
3135   if (!channel->hmac)
3136     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3137   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
3138   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3139   memset(hash, 0, sizeof(hash));
3140
3141   if (server->server_type == SILC_ROUTER) {
3142     if (!channel->rekey)
3143       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3144     channel->rekey->context = (void *)server;
3145     channel->rekey->channel = channel;
3146     channel->rekey->key_len = key_len;
3147     if (channel->rekey->task)
3148       silc_schedule_task_del(server->schedule, channel->rekey->task);
3149
3150     channel->rekey->task = 
3151       silc_schedule_task_add(server->schedule, 0, 
3152                              silc_server_channel_key_rekey,
3153                              (void *)channel->rekey, 3600, 0,
3154                              SILC_TASK_TIMEOUT,
3155                              SILC_TASK_PRI_NORMAL);
3156   }
3157
3158   return TRUE;
3159 }
3160
3161 /* Saves the channel key found in the encoded `key_payload' buffer. This 
3162    function is used when we receive Channel Key Payload and also when we're
3163    processing JOIN command reply. Returns entry to the channel. */
3164
3165 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3166                                               SilcBuffer key_payload,
3167                                               SilcChannelEntry channel)
3168 {
3169   SilcChannelKeyPayload payload = NULL;
3170   SilcChannelID *id = NULL;
3171   unsigned char *tmp, hash[32];
3172   uint32 tmp_len;
3173   char *cipher;
3174
3175   SILC_LOG_DEBUG(("Start"));
3176
3177   /* Decode channel key payload */
3178   payload = silc_channel_key_payload_parse(key_payload);
3179   if (!payload) {
3180     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
3181     channel = NULL;
3182     goto out;
3183   }
3184
3185   /* Get the channel entry */
3186   if (!channel) {
3187
3188     /* Get channel ID */
3189     tmp = silc_channel_key_get_id(payload, &tmp_len);
3190     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3191     if (!id) {
3192       channel = NULL;
3193       goto out;
3194     }
3195
3196     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3197     if (!channel) {
3198       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3199       if (!channel) {
3200         SILC_LOG_ERROR(("Received key for non-existent channel"));
3201         goto out;
3202       }
3203     }
3204   }
3205
3206   tmp = silc_channel_key_get_key(payload, &tmp_len);
3207   if (!tmp) {
3208     channel = NULL;
3209     goto out;
3210   }
3211
3212   cipher = silc_channel_key_get_cipher(payload, NULL);
3213   if (!cipher) {
3214     channel = NULL;
3215     goto out;
3216   }
3217
3218   /* Remove old key if exists */
3219   if (channel->key) {
3220     memset(channel->key, 0, channel->key_len / 8);
3221     silc_free(channel->key);
3222     silc_cipher_free(channel->channel_key);
3223   }
3224
3225   /* Create new cipher */
3226   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3227     channel = NULL;
3228     goto out;
3229   }
3230
3231   if (channel->cipher)
3232     silc_free(channel->cipher);
3233   channel->cipher = strdup(cipher);
3234
3235   /* Save the key */
3236   channel->key_len = tmp_len * 8;
3237   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3238   memcpy(channel->key, tmp, tmp_len);
3239   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3240
3241   /* Generate HMAC key from the channel key data and set it */
3242   if (!channel->hmac)
3243     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3244   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3245   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3246
3247   memset(hash, 0, sizeof(hash));
3248   memset(tmp, 0, tmp_len);
3249
3250   if (server->server_type == SILC_ROUTER) {
3251     if (!channel->rekey)
3252       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3253     channel->rekey->context = (void *)server;
3254     channel->rekey->channel = channel;
3255     if (channel->rekey->task)
3256       silc_schedule_task_del(server->schedule, channel->rekey->task);
3257
3258     channel->rekey->task = 
3259       silc_schedule_task_add(server->schedule, 0, 
3260                              silc_server_channel_key_rekey,
3261                              (void *)channel->rekey, 3600, 0,
3262                              SILC_TASK_TIMEOUT,
3263                              SILC_TASK_PRI_NORMAL);
3264   }
3265
3266  out:
3267   silc_free(id);
3268   if (payload)
3269     silc_channel_key_payload_free(payload);
3270
3271   return channel;
3272 }
3273
3274 /* Heartbeat callback. This function is set as argument for the
3275    silc_socket_set_heartbeat function. The library will call this function
3276    at the set time interval. */
3277
3278 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3279                                    void *hb_context)
3280 {
3281   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3282
3283   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3284                   sock->ip));
3285
3286   /* Send the heartbeat */
3287   silc_server_send_heartbeat(hb->server, sock);
3288 }
3289
3290 /* Returns assembled of all servers in the given ID list. The packet's
3291    form is dictated by the New ID payload. */
3292
3293 static void silc_server_announce_get_servers(SilcServer server,
3294                                              SilcServerEntry remote,
3295                                              SilcIDList id_list,
3296                                              SilcBuffer *servers)
3297 {
3298   SilcIDCacheList list;
3299   SilcIDCacheEntry id_cache;
3300   SilcServerEntry entry;
3301   SilcBuffer idp;
3302
3303   /* Go through all clients in the list */
3304   if (silc_idcache_get_all(id_list->servers, &list)) {
3305     if (silc_idcache_list_first(list, &id_cache)) {
3306       while (id_cache) {
3307         entry = (SilcServerEntry)id_cache->context;
3308
3309         /* Do not announce the one we've sending our announcements and
3310            do not announce ourself. */
3311         if (entry == remote || entry == server->id_entry) {
3312           if (!silc_idcache_list_next(list, &id_cache))
3313             break;
3314           continue;
3315         }
3316
3317         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3318
3319         *servers = silc_buffer_realloc(*servers, 
3320                                        (*servers ? 
3321                                         (*servers)->truelen + idp->len : 
3322                                         idp->len));
3323         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3324         silc_buffer_put(*servers, idp->data, idp->len);
3325         silc_buffer_pull(*servers, idp->len);
3326         silc_buffer_free(idp);
3327
3328         if (!silc_idcache_list_next(list, &id_cache))
3329           break;
3330       }
3331     }
3332
3333     silc_idcache_list_free(list);
3334   }
3335 }
3336
3337 /* This function is used by router to announce existing servers to our
3338    primary router when we've connected to it. */
3339
3340 void silc_server_announce_servers(SilcServer server)
3341 {
3342   SilcBuffer servers = NULL;
3343
3344   SILC_LOG_DEBUG(("Announcing servers"));
3345
3346   /* Get servers in local list */
3347   silc_server_announce_get_servers(server, server->router,
3348                                    server->local_list, &servers);
3349
3350   /* Get servers in global list */
3351   silc_server_announce_get_servers(server, server->router,
3352                                    server->global_list, &servers);
3353
3354   if (servers) {
3355     silc_buffer_push(servers, servers->data - servers->head);
3356     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3357
3358     /* Send the packet */
3359     silc_server_packet_send(server, server->router->connection,
3360                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3361                             servers->data, servers->len, TRUE);
3362
3363     silc_buffer_free(servers);
3364   }
3365 }
3366
3367 /* Returns assembled packet of all clients in the given ID list. The
3368    packet's form is dictated by the New ID Payload. */
3369
3370 static void silc_server_announce_get_clients(SilcServer server,
3371                                              SilcIDList id_list,
3372                                              SilcBuffer *clients)
3373 {
3374   SilcIDCacheList list;
3375   SilcIDCacheEntry id_cache;
3376   SilcClientEntry client;
3377   SilcBuffer idp;
3378
3379   /* Go through all clients in the list */
3380   if (silc_idcache_get_all(id_list->clients, &list)) {
3381     if (silc_idcache_list_first(list, &id_cache)) {
3382       while (id_cache) {
3383         client = (SilcClientEntry)id_cache->context;
3384
3385         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3386
3387         *clients = silc_buffer_realloc(*clients, 
3388                                        (*clients ? 
3389                                         (*clients)->truelen + idp->len : 
3390                                         idp->len));
3391         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3392         silc_buffer_put(*clients, idp->data, idp->len);
3393         silc_buffer_pull(*clients, idp->len);
3394         silc_buffer_free(idp);
3395
3396         if (!silc_idcache_list_next(list, &id_cache))
3397           break;
3398       }
3399     }
3400
3401     silc_idcache_list_free(list);
3402   }
3403 }
3404
3405 /* This function is used to announce our existing clients to our router
3406    when we've connected to it. */
3407
3408 void silc_server_announce_clients(SilcServer server)
3409 {
3410   SilcBuffer clients = NULL;
3411
3412   SILC_LOG_DEBUG(("Announcing clients"));
3413
3414   /* Get clients in local list */
3415   silc_server_announce_get_clients(server, server->local_list,
3416                                    &clients);
3417
3418   /* As router we announce our global list as well */
3419   if (server->server_type == SILC_ROUTER)
3420     silc_server_announce_get_clients(server, server->global_list,
3421                                      &clients);
3422
3423   if (clients) {
3424     silc_buffer_push(clients, clients->data - clients->head);
3425     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3426
3427     /* Send the packet */
3428     silc_server_packet_send(server, server->router->connection,
3429                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3430                             clients->data, clients->len, TRUE);
3431
3432     silc_buffer_free(clients);
3433   }
3434 }
3435
3436 static SilcBuffer 
3437 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3438 {
3439   va_list ap;
3440   SilcBuffer p;
3441
3442   va_start(ap, argc);
3443   p = silc_notify_payload_encode(notify, argc, ap);
3444   va_end(ap);
3445  
3446   return p;
3447 }
3448
3449 /* Returns assembled packets for channel users of the `channel'. */
3450
3451 void silc_server_announce_get_channel_users(SilcServer server,
3452                                             SilcChannelEntry channel,
3453                                             SilcBuffer *channel_users,
3454                                             SilcBuffer *channel_users_modes)
3455 {
3456   SilcChannelClientEntry chl;
3457   SilcHashTableList htl;
3458   SilcBuffer chidp, clidp;
3459   SilcBuffer tmp;
3460   int len;
3461   unsigned char mode[4];
3462
3463   SILC_LOG_DEBUG(("Start"));
3464
3465   /* Now find all users on the channel */
3466   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3467   silc_hash_table_list(channel->user_list, &htl);
3468   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3469     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3470
3471     /* JOIN Notify */
3472     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2, 
3473                                              clidp->data, clidp->len,
3474                                              chidp->data, chidp->len);
3475     len = tmp->len;
3476     *channel_users = 
3477       silc_buffer_realloc(*channel_users, 
3478                           (*channel_users ? 
3479                            (*channel_users)->truelen + len : len));
3480     silc_buffer_pull_tail(*channel_users, 
3481                           ((*channel_users)->end - 
3482                            (*channel_users)->data));
3483     
3484     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3485     silc_buffer_pull(*channel_users, len);
3486     silc_buffer_free(tmp);
3487
3488     /* CUMODE notify for mode change on the channel */
3489     SILC_PUT32_MSB(chl->mode, mode);
3490     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE, 
3491                                              3, clidp->data, clidp->len,
3492                                              mode, 4,
3493                                              clidp->data, clidp->len);
3494     len = tmp->len;
3495     *channel_users_modes = 
3496       silc_buffer_realloc(*channel_users_modes, 
3497                           (*channel_users_modes ? 
3498                            (*channel_users_modes)->truelen + len : len));
3499     silc_buffer_pull_tail(*channel_users_modes, 
3500                           ((*channel_users_modes)->end - 
3501                            (*channel_users_modes)->data));
3502     
3503     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3504     silc_buffer_pull(*channel_users_modes, len);
3505     silc_buffer_free(tmp);
3506
3507     silc_buffer_free(clidp);
3508   }
3509   silc_buffer_free(chidp);
3510 }
3511
3512 /* Returns assembled packets for all channels and users on those channels
3513    from the given ID List. The packets are in the form dictated by the
3514    New Channel and New Channel User payloads. */
3515
3516 void silc_server_announce_get_channels(SilcServer server,
3517                                        SilcIDList id_list,
3518                                        SilcBuffer *channels,
3519                                        SilcBuffer *channel_users,
3520                                        SilcBuffer **channel_users_modes,
3521                                        uint32 *channel_users_modes_c,
3522                                        SilcChannelID ***channel_ids)
3523 {
3524   SilcIDCacheList list;
3525   SilcIDCacheEntry id_cache;
3526   SilcChannelEntry channel;
3527   unsigned char *cid;
3528   uint32 id_len;
3529   uint16 name_len;
3530   int len;
3531   int i = *channel_users_modes_c;
3532
3533   SILC_LOG_DEBUG(("Start"));
3534
3535   /* Go through all channels in the list */
3536   if (silc_idcache_get_all(id_list->channels, &list)) {
3537     if (silc_idcache_list_first(list, &id_cache)) {
3538       while (id_cache) {
3539         channel = (SilcChannelEntry)id_cache->context;
3540         
3541         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3542         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3543         name_len = strlen(channel->channel_name);
3544
3545         len = 4 + name_len + id_len + 4;
3546         *channels = 
3547           silc_buffer_realloc(*channels, 
3548                               (*channels ? (*channels)->truelen + len : len));
3549         silc_buffer_pull_tail(*channels, 
3550                               ((*channels)->end - (*channels)->data));
3551         silc_buffer_format(*channels,
3552                            SILC_STR_UI_SHORT(name_len),
3553                            SILC_STR_UI_XNSTRING(channel->channel_name, 
3554                                                 name_len),
3555                            SILC_STR_UI_SHORT(id_len),
3556                            SILC_STR_UI_XNSTRING(cid, id_len),
3557                            SILC_STR_UI_INT(channel->mode),
3558                            SILC_STR_END);
3559         silc_buffer_pull(*channels, len);
3560
3561         *channel_users_modes = silc_realloc(*channel_users_modes,
3562                                             sizeof(**channel_users_modes) * 
3563                                             (i + 1));
3564         (*channel_users_modes)[i] = NULL;
3565         *channel_ids = silc_realloc(*channel_ids, 
3566                                     sizeof(**channel_ids) * (i + 1));
3567         (*channel_ids)[i] = NULL;
3568         silc_server_announce_get_channel_users(server, channel,
3569                                                channel_users,
3570                                                channel_users_modes[i]);
3571         (*channel_ids)[i] = channel->id;
3572         i++;
3573
3574         if (!silc_idcache_list_next(list, &id_cache))
3575           break;
3576       }
3577
3578       *channel_users_modes_c += i;
3579     }
3580
3581     silc_idcache_list_free(list);
3582   }
3583 }
3584
3585 /* This function is used to announce our existing channels to our router
3586    when we've connected to it. This also announces the users on the
3587    channels to the router. */
3588
3589 void silc_server_announce_channels(SilcServer server)
3590 {
3591   SilcBuffer channels = NULL, channel_users = NULL;
3592   SilcBuffer *channel_users_modes = NULL;
3593   uint32 channel_users_modes_c = 0;
3594   SilcChannelID **channel_ids = NULL;
3595
3596   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3597
3598   /* Get channels and channel users in local list */
3599   silc_server_announce_get_channels(server, server->local_list,
3600                                     &channels, &channel_users,
3601                                     &channel_users_modes,
3602                                     &channel_users_modes_c,
3603                                     &channel_ids);
3604
3605   /* Get channels and channel users in global list */
3606   silc_server_announce_get_channels(server, server->global_list,
3607                                     &channels, &channel_users,
3608                                     &channel_users_modes,
3609                                     &channel_users_modes_c,
3610                                     &channel_ids);
3611
3612   if (channels) {
3613     silc_buffer_push(channels, channels->data - channels->head);
3614     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3615
3616     /* Send the packet */
3617     silc_server_packet_send(server, server->router->connection,
3618                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3619                             channels->data, channels->len,
3620                             FALSE);
3621
3622     silc_buffer_free(channels);
3623   }
3624
3625   if (channel_users) {
3626     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3627     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
3628                      channel_users->len);
3629
3630     /* Send the packet */
3631     silc_server_packet_send(server, server->router->connection,
3632                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3633                             channel_users->data, channel_users->len,
3634                             FALSE);
3635
3636     silc_buffer_free(channel_users);
3637   }
3638
3639   if (channel_users_modes) {
3640     int i;
3641
3642     for (i = 0; i < channel_users_modes_c; i++) {
3643       silc_buffer_push(channel_users_modes[i], 
3644                        channel_users_modes[i]->data - 
3645                        channel_users_modes[i]->head);
3646       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data, 
3647                        channel_users_modes[i]->len);
3648       silc_server_packet_send_dest(server, server->router->connection,
3649                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3650                                    channel_ids[i], SILC_ID_CHANNEL,
3651                                    channel_users_modes[i]->data, 
3652                                    channel_users_modes[i]->len,
3653                                    FALSE);
3654       silc_buffer_free(channel_users_modes[i]);
3655     }
3656     silc_free(channel_users_modes);
3657     silc_free(channel_ids);
3658   }
3659 }
3660
3661 /* Failure timeout callback. If this is called then we will immediately
3662    process the received failure. We always process the failure with timeout
3663    since we do not want to blindly trust to received failure packets. 
3664    This won't be called (the timeout is cancelled) if the failure was
3665    bogus (it is bogus if remote does not close the connection after sending
3666    the failure). */
3667
3668 SILC_TASK_CALLBACK(silc_server_failure_callback)
3669 {
3670   SilcServerFailureContext f = (SilcServerFailureContext)context;
3671
3672   if (f->sock->protocol) {
3673     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3674     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3675   }
3676
3677   silc_free(f);
3678 }
3679
3680 /* Assembles user list and users mode list from the `channel'. */
3681
3682 void silc_server_get_users_on_channel(SilcServer server,
3683                                       SilcChannelEntry channel,
3684                                       SilcBuffer *user_list,
3685                                       SilcBuffer *mode_list,
3686                                       uint32 *user_count)
3687 {
3688   SilcChannelClientEntry chl;
3689   SilcHashTableList htl;
3690   SilcBuffer client_id_list;
3691   SilcBuffer client_mode_list;
3692   SilcBuffer idp;
3693   uint32 list_count = 0, len = 0;
3694
3695   silc_hash_table_list(channel->user_list, &htl);
3696   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3697     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3698
3699   client_id_list = silc_buffer_alloc(len);
3700   client_mode_list = 
3701     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3702   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3703   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3704
3705   silc_hash_table_list(channel->user_list, &htl);
3706   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3707     /* Client ID */
3708     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3709     silc_buffer_put(client_id_list, idp->data, idp->len);
3710     silc_buffer_pull(client_id_list, idp->len);
3711     silc_buffer_free(idp);
3712
3713     /* Client's mode on channel */
3714     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3715     silc_buffer_pull(client_mode_list, 4);
3716
3717     list_count++;
3718   }
3719   silc_buffer_push(client_id_list, 
3720                    client_id_list->data - client_id_list->head);
3721   silc_buffer_push(client_mode_list, 
3722                    client_mode_list->data - client_mode_list->head);
3723
3724   *user_list = client_id_list;
3725   *mode_list = client_mode_list;
3726   *user_count = list_count;
3727 }
3728
3729 /* Saves users and their modes to the `channel'. */
3730
3731 void silc_server_save_users_on_channel(SilcServer server,
3732                                        SilcSocketConnection sock,
3733                                        SilcChannelEntry channel,
3734                                        SilcClientID *noadd,
3735                                        SilcBuffer user_list,
3736                                        SilcBuffer mode_list,
3737                                        uint32 user_count)
3738 {
3739   int i;
3740
3741   for (i = 0; i < user_count; i++) {
3742     uint16 idp_len;
3743     uint32 mode;
3744     SilcClientID *client_id;
3745     SilcClientEntry client;
3746
3747     /* Client ID */
3748     SILC_GET16_MSB(idp_len, user_list->data + 2);
3749     idp_len += 4;
3750     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3751     silc_buffer_pull(user_list, idp_len);
3752     if (!client_id)
3753       continue;
3754
3755     /* Mode */
3756     SILC_GET32_MSB(mode, mode_list->data);
3757     silc_buffer_pull(mode_list, 4);
3758
3759     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3760       silc_free(client_id);
3761       continue;
3762     }
3763     
3764     /* Check if we have this client cached already. */
3765     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3766                                            server->server_type, NULL);
3767     if (!client)
3768       client = silc_idlist_find_client_by_id(server->global_list, 
3769                                              client_id, server->server_type,
3770                                              NULL);
3771     if (!client) {
3772       /* If router did not find such Client ID in its lists then this must
3773          be bogus client or some router in the net is buggy. */
3774       if (server->server_type == SILC_ROUTER) {
3775         silc_free(client_id);
3776         continue;
3777       }
3778
3779       /* We don't have that client anywhere, add it. The client is added
3780          to global list since server didn't have it in the lists so it must be 
3781          global. */
3782       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3783                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3784                                       sock->user_data, NULL);
3785       if (!client) {
3786         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3787         silc_free(client_id);
3788         continue;
3789       }
3790
3791       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3792     }
3793
3794     silc_free(client_id);
3795
3796     if (!silc_server_client_on_channel(client, channel)) {
3797       /* Client was not on the channel, add it. */
3798       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3799       chl->client = client;
3800       chl->mode = mode;
3801       chl->channel = channel;
3802       silc_hash_table_add(channel->user_list, chl->client, chl);
3803       silc_hash_table_add(client->channels, chl->channel, chl);
3804     }
3805   }
3806 }
3807
3808 /* Lookups route to the client indicated by the `id_data'. The connection
3809    object and internal data object is returned. Returns NULL if route
3810    could not be found to the client. If the `client_id' is specified then
3811    it is used and the `id_data' is ignored. */
3812
3813 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3814                                                   unsigned char *id_data,
3815                                                   uint32 id_len,
3816                                                   SilcClientID *client_id,
3817                                                   SilcIDListData *idata)
3818 {
3819   SilcClientID *id;
3820   SilcClientEntry client;
3821
3822   SILC_LOG_DEBUG(("Start"));
3823
3824   /* Decode destination Client ID */
3825   if (!client_id) {
3826     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3827     if (!id) {
3828       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3829       return NULL;
3830     }
3831   } else {
3832     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3833   }
3834
3835   /* If the destination belongs to our server we don't have to route
3836      the packet anywhere but to send it to the local destination. */
3837   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3838   if (client) {
3839     silc_free(id);
3840
3841     /* If we are router and the client has router then the client is in
3842        our cell but not directly connected to us. */
3843     if (server->server_type == SILC_ROUTER && client->router) {
3844       /* We are of course in this case the client's router thus the route
3845          to the client is the server who owns the client. So, we will send
3846          the packet to that server. */
3847       if (idata)
3848         *idata = (SilcIDListData)client->router;
3849       return client->router->connection;
3850     }
3851
3852     /* Seems that client really is directly connected to us */
3853     if (idata)
3854       *idata = (SilcIDListData)client;
3855     return client->connection;
3856   }
3857
3858   /* Destination belongs to someone not in this server. If we are normal
3859      server our action is to send the packet to our router. */
3860   if (server->server_type == SILC_SERVER && !server->standalone) {
3861     silc_free(id);
3862     if (idata)
3863       *idata = (SilcIDListData)server->router;
3864     return server->router->connection;
3865   }
3866
3867   /* We are router and we will perform route lookup for the destination 
3868      and send the packet to fastest route. */
3869   if (server->server_type == SILC_ROUTER && !server->standalone) {
3870     /* Check first that the ID is valid */
3871     client = silc_idlist_find_client_by_id(server->global_list, id, 
3872                                            TRUE, NULL);
3873     if (client) {
3874       SilcSocketConnection dst_sock;
3875
3876       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3877
3878       silc_free(id);
3879       if (idata)
3880         *idata = (SilcIDListData)dst_sock->user_data;
3881       return dst_sock;
3882     }
3883   }
3884
3885   silc_free(id);
3886   return NULL;
3887 }
3888
3889 /* Encodes and returns channel list of channels the `client' has joined.
3890    Secret channels are not put to the list. */
3891
3892 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3893                                                SilcClientEntry client)
3894 {
3895   SilcBuffer buffer = NULL;
3896   SilcChannelEntry channel;
3897   SilcChannelClientEntry chl;
3898   SilcHashTableList htl;
3899   unsigned char *cid;
3900   uint32 id_len;
3901   uint16 name_len;
3902   int len;
3903
3904   silc_hash_table_list(client->channels, &htl);
3905   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3906     channel = chl->channel;
3907
3908     if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3909         channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3910       continue;
3911
3912     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3913     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3914     name_len = strlen(channel->channel_name);
3915     
3916     len = 4 + name_len + id_len + 4;
3917     buffer = silc_buffer_realloc(buffer, 
3918                                  (buffer ? (buffer)->truelen + len : len));
3919     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3920     silc_buffer_format(buffer,
3921                        SILC_STR_UI_SHORT(name_len),
3922                        SILC_STR_UI_XNSTRING(channel->channel_name, 
3923                                             name_len),
3924                        SILC_STR_UI_SHORT(id_len),
3925                        SILC_STR_UI_XNSTRING(cid, id_len),
3926                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
3927                        SILC_STR_END);
3928     silc_buffer_pull(buffer, len);
3929     silc_free(cid);
3930   }
3931
3932   if (buffer)
3933     silc_buffer_push(buffer, buffer->data - buffer->head);
3934
3935   return buffer;
3936 }
3937
3938 /* Finds client entry by Client ID and if it is not found then resolves
3939    it using WHOIS command. */
3940
3941 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3942                                                SilcClientID *client_id)
3943 {
3944   SilcClientEntry client;
3945
3946   client = silc_idlist_find_client_by_id(server->local_list, client_id,
3947                                          TRUE, NULL);
3948   if (!client) {
3949     client = silc_idlist_find_client_by_id(server->global_list, 
3950                                            client_id, TRUE, NULL);
3951     if (!client && server->server_type == SILC_ROUTER)
3952       return NULL;
3953   }
3954
3955   if (!client && server->standalone)
3956     return NULL;
3957
3958   if (!client || !client->nickname || !client->username) {
3959     SilcBuffer buffer, idp;
3960
3961     client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
3962     client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
3963     client->resolve_cmd_ident = ++server->cmd_ident;
3964
3965     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3966     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3967                                             server->cmd_ident, 1,
3968                                             3, idp->data, idp->len);
3969     silc_server_packet_send(server, client ? client->router->connection :
3970                             server->router->connection,
3971                             SILC_PACKET_COMMAND, 0,
3972                             buffer->data, buffer->len, FALSE);
3973     silc_buffer_free(idp);
3974     silc_buffer_free(buffer);
3975     return NULL;
3976   }
3977
3978   return client;
3979 }
3980
3981 /* A timeout callback for the re-key. We will be the initiator of the
3982    re-key protocol. */
3983
3984 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3985 {
3986   SilcSocketConnection sock = (SilcSocketConnection)context;
3987   SilcIDListData idata = (SilcIDListData)sock->user_data;
3988   SilcServer server = (SilcServer)idata->rekey->context;
3989   SilcProtocol protocol;
3990   SilcServerRekeyInternalContext *proto_ctx;
3991
3992   SILC_LOG_DEBUG(("Start"));
3993
3994   /* Allocate internal protocol context. This is sent as context
3995      to the protocol. */
3996   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3997   proto_ctx->server = (void *)server;
3998   proto_ctx->sock = sock;
3999   proto_ctx->responder = FALSE;
4000   proto_ctx->pfs = idata->rekey->pfs;
4001       
4002   /* Perform rekey protocol. Will call the final callback after the
4003      protocol is over. */
4004   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
4005                       &protocol, proto_ctx, silc_server_rekey_final);
4006   sock->protocol = protocol;
4007       
4008   /* Run the protocol */
4009   silc_protocol_execute(protocol, server->schedule, 0, 0);
4010
4011   /* Re-register re-key timeout */
4012   silc_schedule_task_add(server->schedule, sock->sock, 
4013                          silc_server_rekey_callback,
4014                          context, idata->rekey->timeout, 0,
4015                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4016 }
4017
4018 /* The final callback for the REKEY protocol. This will actually take the
4019    new key material into use. */
4020
4021 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4022 {
4023   SilcProtocol protocol = (SilcProtocol)context;
4024   SilcServerRekeyInternalContext *ctx =
4025     (SilcServerRekeyInternalContext *)protocol->context;
4026   SilcServer server = (SilcServer)ctx->server;
4027   SilcSocketConnection sock = ctx->sock;
4028
4029   SILC_LOG_DEBUG(("Start"));
4030
4031   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4032        protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4033     /* Error occured during protocol */
4034     silc_protocol_cancel(protocol, server->schedule);
4035     silc_protocol_free(protocol);
4036     sock->protocol = NULL;
4037     if (ctx->packet)
4038       silc_packet_context_free(ctx->packet);
4039     if (ctx->ske)
4040       silc_ske_free(ctx->ske);
4041     silc_free(ctx);
4042     return;
4043   }
4044
4045   /* Cleanup */
4046   silc_protocol_free(protocol);
4047   sock->protocol = NULL;
4048   if (ctx->packet)
4049     silc_packet_context_free(ctx->packet);
4050   if (ctx->ske)
4051     silc_ske_free(ctx->ske);
4052   silc_free(ctx);
4053 }