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