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