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