tupdates
[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, port);
1045   if (!deny)
1046     deny = silc_server_config_find_denied(server, sock->hostname, port);
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
2646     /* If there is no global users on the channel anymore mark the channel
2647        as local channel. Do not check if the removed client is local client. */
2648     if (server->server_type != SILC_ROUTER && channel->global_users && 
2649         chl->client->router && !silc_server_channel_has_global(channel))
2650       channel->global_users = FALSE;
2651
2652     silc_free(chl);
2653     server->stat.my_chanclients--;
2654
2655     /* If there is not at least one local user on the channel then we don't
2656        need the channel entry anymore, we can remove it safely. */
2657     if (server->server_type != SILC_ROUTER &&
2658         !silc_server_channel_has_local(channel)) {
2659       /* Notify about leaving client if this channel has global users. */
2660       if (notify && channel->global_users)
2661         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2662                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2663                                            signoff_message ? 2 : 1,
2664                                            clidp->data, clidp->len,
2665                                            signoff_message, signoff_message ?
2666                                            strlen(signoff_message) : 0);
2667
2668       if (channel->rekey)
2669         silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2670
2671       if (channel->founder_key) {
2672         /* The founder auth data exists, do not remove the channel entry */
2673         SilcChannelClientEntry chl2;
2674         SilcHashTableList htl2;
2675
2676         channel->disabled = TRUE;
2677
2678         silc_hash_table_list(channel->user_list, &htl2);
2679         while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2680           silc_hash_table_del(chl2->client->channels, channel);
2681           silc_hash_table_del(channel->user_list, chl2->client);
2682           silc_free(chl2);
2683         }
2684         silc_hash_table_list_reset(&htl2);
2685         continue;
2686       }
2687
2688       /* Remove the channel entry */
2689       if (silc_idlist_del_channel(server->local_list, channel))
2690         server->stat.my_channels--;
2691       else 
2692         silc_idlist_del_channel(server->global_list, channel);
2693       continue;
2694     }
2695
2696     /* Send notify to channel about client leaving SILC and thus
2697        the entire channel. */
2698     if (notify)
2699       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2700                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2701                                          signoff_message ? 2 : 1,
2702                                          clidp->data, clidp->len,
2703                                          signoff_message, signoff_message ?
2704                                          strlen(signoff_message) : 0);
2705
2706     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2707       /* Re-generate channel key */
2708       if (!silc_server_create_channel_key(server, channel, 0))
2709         goto out;
2710       
2711       /* Send the channel key to the channel. The key of course is not sent
2712          to the client who was removed from the channel. */
2713       silc_server_send_channel_key(server, client->connection, channel, 
2714                                    server->server_type == SILC_ROUTER ? 
2715                                    FALSE : !server->standalone);
2716     }
2717   }
2718
2719  out:
2720   silc_hash_table_list_reset(&htl);
2721   silc_buffer_free(clidp);
2722 }
2723
2724 /* Removes client from one channel. This is used for example when client
2725    calls LEAVE command to remove itself from the channel. Returns TRUE
2726    if channel still exists and FALSE if the channel is removed when
2727    last client leaves the channel. If `notify' is FALSE notify messages
2728    are not sent. */
2729
2730 int silc_server_remove_from_one_channel(SilcServer server, 
2731                                         SilcSocketConnection sock,
2732                                         SilcChannelEntry channel,
2733                                         SilcClientEntry client,
2734                                         int notify)
2735 {
2736   SilcChannelClientEntry chl;
2737   SilcBuffer clidp;
2738
2739   SILC_LOG_DEBUG(("Start"));
2740
2741   /* Get the entry to the channel, if this client is not on the channel
2742      then return Ok. */
2743   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2744     return TRUE;
2745
2746   /* Remove the client from the channel. The client is removed from
2747      the channel's user list. */
2748
2749   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2750
2751   /* Remove channel from client's channel list */
2752   silc_hash_table_del(client->channels, chl->channel);
2753
2754   /* Remove channel if there is no users anymore */
2755   if (server->server_type == SILC_ROUTER &&
2756       silc_hash_table_count(channel->user_list) < 2) {
2757     if (channel->rekey)
2758       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2759     if (silc_idlist_del_channel(server->local_list, channel))
2760       server->stat.my_channels--;
2761     else 
2762       silc_idlist_del_channel(server->global_list, channel);
2763     silc_buffer_free(clidp);
2764     return FALSE;
2765   }
2766
2767   /* Remove client from channel's client list */
2768   silc_hash_table_del(channel->user_list, chl->client);
2769   
2770   /* If there is no global users on the channel anymore mark the channel
2771      as local channel. Do not check if the client is local client. */
2772   if (server->server_type != SILC_ROUTER && channel->global_users &&
2773       chl->client->router && !silc_server_channel_has_global(channel))
2774     channel->global_users = FALSE;
2775
2776   silc_free(chl);
2777   server->stat.my_chanclients--;
2778
2779   /* If there is not at least one local user on the channel then we don't
2780      need the channel entry anymore, we can remove it safely. */
2781   if (server->server_type != SILC_ROUTER &&
2782       !silc_server_channel_has_local(channel)) {
2783     /* Notify about leaving client if this channel has global users. */
2784     if (notify && channel->global_users)
2785       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2786                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2787                                          clidp->data, clidp->len);
2788     
2789     silc_buffer_free(clidp);
2790     
2791     if (channel->rekey)
2792       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2793
2794     if (channel->founder_key) {
2795       /* The founder auth data exists, do not remove the channel entry */
2796       SilcChannelClientEntry chl2;
2797       SilcHashTableList htl2;
2798       
2799       channel->disabled = TRUE;
2800       
2801       silc_hash_table_list(channel->user_list, &htl2);
2802       while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2803         silc_hash_table_del(chl2->client->channels, channel);
2804         silc_hash_table_del(channel->user_list, chl2->client);
2805         silc_free(chl2);
2806       }
2807       silc_hash_table_list_reset(&htl2);
2808       return FALSE;
2809     }
2810
2811     /* Remove the channel entry */
2812     if (silc_idlist_del_channel(server->local_list, channel))
2813       server->stat.my_channels--;
2814     else 
2815       silc_idlist_del_channel(server->global_list, channel);
2816     return FALSE;
2817   }
2818
2819   /* Send notify to channel about client leaving the channel */
2820   if (notify)
2821     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2822                                        SILC_NOTIFY_TYPE_LEAVE, 1,
2823                                        clidp->data, clidp->len);
2824
2825   silc_buffer_free(clidp);
2826   return TRUE;
2827 }
2828
2829 /* Timeout callback. This is called if connection is idle or for some
2830    other reason is not responding within some period of time. This 
2831    disconnects the remote end. */
2832
2833 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2834 {
2835   SilcServer server = (SilcServer)context;
2836   SilcSocketConnection sock = server->sockets[fd];
2837
2838   SILC_LOG_DEBUG(("Start"));
2839
2840   if (!sock)
2841     return;
2842
2843   /* If we have protocol active we must assure that we call the protocol's
2844      final callback so that all the memory is freed. */
2845   if (sock->protocol) {
2846     silc_protocol_cancel(sock->protocol, server->schedule);
2847     sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2848     silc_protocol_execute_final(sock->protocol, server->schedule);
2849     sock->protocol = NULL;
2850     return;
2851   }
2852
2853   if (sock->user_data)
2854     silc_server_free_sock_user_data(server, sock, NULL);
2855
2856   silc_server_disconnect_remote(server, sock, "Server closed connection: "
2857                                 "Connection timeout");
2858 }
2859
2860 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2861    function may be used only by router. In real SILC network all channels
2862    are created by routers thus this function is never used by normal
2863    server. */
2864
2865 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2866                                                 SilcServerID *router_id,
2867                                                 char *cipher, 
2868                                                 char *hmac,
2869                                                 char *channel_name,
2870                                                 int broadcast)
2871 {
2872   SilcChannelID *channel_id;
2873   SilcChannelEntry entry;
2874   SilcCipher key;
2875   SilcHmac newhmac;
2876
2877   SILC_LOG_DEBUG(("Creating new channel"));
2878
2879   if (!cipher)
2880     cipher = SILC_DEFAULT_CIPHER;
2881   if (!hmac)
2882     hmac = SILC_DEFAULT_HMAC;
2883
2884   /* Allocate cipher */
2885   if (!silc_cipher_alloc(cipher, &key))
2886     return NULL;
2887
2888   /* Allocate hmac */
2889   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2890     silc_cipher_free(key);
2891     return NULL;
2892   }
2893
2894   channel_name = strdup(channel_name);
2895
2896   /* Create the channel ID */
2897   if (!silc_id_create_channel_id(server, router_id, server->rng, 
2898                                  &channel_id)) {
2899     silc_free(channel_name);
2900     silc_cipher_free(key);
2901     silc_hmac_free(newhmac);
2902     return NULL;
2903   }
2904
2905   /* Create the channel */
2906   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2907                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2908                                   NULL, key, newhmac, 0);
2909   if (!entry) {
2910     silc_free(channel_name);
2911     silc_cipher_free(key);
2912     silc_hmac_free(newhmac);
2913     silc_free(channel_id);
2914     return NULL;
2915   }
2916
2917   entry->cipher = strdup(cipher);
2918   entry->hmac_name = strdup(hmac);
2919
2920   /* Now create the actual key material */
2921   if (!silc_server_create_channel_key(server, entry, 
2922                                       silc_cipher_get_key_len(key) / 8)) {
2923     silc_idlist_del_channel(server->local_list, entry);
2924     return NULL;
2925   }
2926
2927   /* Notify other routers about the new channel. We send the packet
2928      to our primary route. */
2929   if (broadcast && server->standalone == FALSE)
2930     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2931                                  channel_name, entry->id, 
2932                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2933                                  entry->mode);
2934
2935   server->stat.my_channels++;
2936
2937   return entry;
2938 }
2939
2940 /* Same as above but creates the channel with Channel ID `channel_id. */
2941
2942 SilcChannelEntry 
2943 silc_server_create_new_channel_with_id(SilcServer server, 
2944                                        char *cipher, 
2945                                        char *hmac,
2946                                        char *channel_name,
2947                                        SilcChannelID *channel_id,
2948                                        int broadcast)
2949 {
2950   SilcChannelEntry entry;
2951   SilcCipher key;
2952   SilcHmac newhmac;
2953
2954   SILC_LOG_DEBUG(("Creating new channel"));
2955
2956   if (!cipher)
2957     cipher = SILC_DEFAULT_CIPHER;
2958   if (!hmac)
2959     hmac = SILC_DEFAULT_HMAC;
2960
2961   /* Allocate cipher */
2962   if (!silc_cipher_alloc(cipher, &key))
2963     return NULL;
2964
2965   /* Allocate hmac */
2966   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2967     silc_cipher_free(key);
2968     return NULL;
2969   }
2970
2971   channel_name = strdup(channel_name);
2972
2973   /* Create the channel */
2974   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2975                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2976                                   NULL, key, newhmac, 0);
2977   if (!entry) {
2978     silc_cipher_free(key);
2979     silc_hmac_free(newhmac);
2980     silc_free(channel_name);
2981     return NULL;
2982   }
2983
2984   /* Now create the actual key material */
2985   if (!silc_server_create_channel_key(server, entry, 
2986                                       silc_cipher_get_key_len(key) / 8)) {
2987     silc_idlist_del_channel(server->local_list, entry);
2988     return NULL;
2989   }
2990
2991   /* Notify other routers about the new channel. We send the packet
2992      to our primary route. */
2993   if (broadcast && server->standalone == FALSE)
2994     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2995                                  channel_name, entry->id, 
2996                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2997                                  entry->mode);
2998
2999   server->stat.my_channels++;
3000
3001   return entry;
3002 }
3003
3004 /* Channel's key re-key timeout callback. */
3005
3006 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3007 {
3008   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3009   SilcServer server = (SilcServer)rekey->context;
3010
3011   rekey->task = NULL;
3012
3013   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3014     return;
3015
3016   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3017 }
3018
3019 /* Generates new channel key. This is used to create the initial channel key
3020    but also to re-generate new key for channel. If `key_len' is provided
3021    it is the bytes of the key length. */
3022
3023 bool silc_server_create_channel_key(SilcServer server, 
3024                                     SilcChannelEntry channel,
3025                                     uint32 key_len)
3026 {
3027   int i;
3028   unsigned char channel_key[32], hash[32];
3029   uint32 len;
3030
3031   SILC_LOG_DEBUG(("Generating channel key"));
3032
3033   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3034     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3035     return TRUE;
3036   }
3037
3038   if (!channel->channel_key)
3039     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3040       channel->channel_key = NULL;
3041       return FALSE;
3042     }
3043
3044   if (key_len)
3045     len = key_len;
3046   else if (channel->key_len)
3047     len = channel->key_len / 8;
3048   else
3049     len = silc_cipher_get_key_len(channel->channel_key) / 8;
3050
3051   /* Create channel key */
3052   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3053   
3054   /* Set the key */
3055   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3056
3057   /* Remove old key if exists */
3058   if (channel->key) {
3059     memset(channel->key, 0, channel->key_len / 8);
3060     silc_free(channel->key);
3061   }
3062
3063   /* Save the key */
3064   channel->key_len = len * 8;
3065   channel->key = silc_calloc(len, sizeof(*channel->key));
3066   memcpy(channel->key, channel_key, len);
3067   memset(channel_key, 0, sizeof(channel_key));
3068
3069   /* Generate HMAC key from the channel key data and set it */
3070   if (!channel->hmac)
3071     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3072   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3073   silc_hmac_set_key(channel->hmac, hash, 
3074                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3075   memset(hash, 0, sizeof(hash));
3076
3077   if (server->server_type == SILC_ROUTER) {
3078     if (!channel->rekey)
3079       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3080     channel->rekey->context = (void *)server;
3081     channel->rekey->channel = channel;
3082     channel->rekey->key_len = key_len;
3083     if (channel->rekey->task)
3084       silc_schedule_task_del(server->schedule, channel->rekey->task);
3085
3086     channel->rekey->task = 
3087       silc_schedule_task_add(server->schedule, 0, 
3088                              silc_server_channel_key_rekey,
3089                              (void *)channel->rekey, 
3090                              server->config->channel_rekey_secs, 0,
3091                              SILC_TASK_TIMEOUT,
3092                              SILC_TASK_PRI_NORMAL);
3093   }
3094
3095   return TRUE;
3096 }
3097
3098 /* Saves the channel key found in the encoded `key_payload' buffer. This 
3099    function is used when we receive Channel Key Payload and also when we're
3100    processing JOIN command reply. Returns entry to the channel. */
3101
3102 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3103                                               SilcBuffer key_payload,
3104                                               SilcChannelEntry channel)
3105 {
3106   SilcChannelKeyPayload payload = NULL;
3107   SilcChannelID *id = NULL;
3108   unsigned char *tmp, hash[32];
3109   uint32 tmp_len;
3110   char *cipher;
3111
3112   SILC_LOG_DEBUG(("Start"));
3113
3114   /* Decode channel key payload */
3115   payload = silc_channel_key_payload_parse(key_payload->data, 
3116                                            key_payload->len);
3117   if (!payload) {
3118     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3119     channel = NULL;
3120     goto out;
3121   }
3122
3123   /* Get the channel entry */
3124   if (!channel) {
3125
3126     /* Get channel ID */
3127     tmp = silc_channel_key_get_id(payload, &tmp_len);
3128     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3129     if (!id) {
3130       channel = NULL;
3131       goto out;
3132     }
3133
3134     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3135     if (!channel) {
3136       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3137       if (!channel) {
3138         SILC_LOG_ERROR(("Received key for non-existent channel %s",
3139                         silc_id_render(id, SILC_ID_CHANNEL)));
3140         goto out;
3141       }
3142     }
3143   }
3144
3145   tmp = silc_channel_key_get_key(payload, &tmp_len);
3146   if (!tmp) {
3147     channel = NULL;
3148     goto out;
3149   }
3150
3151   cipher = silc_channel_key_get_cipher(payload, NULL);
3152   if (!cipher) {
3153     channel = NULL;
3154     goto out;
3155   }
3156
3157   /* Remove old key if exists */
3158   if (channel->key) {
3159     memset(channel->key, 0, channel->key_len / 8);
3160     silc_free(channel->key);
3161     silc_cipher_free(channel->channel_key);
3162   }
3163
3164   /* Create new cipher */
3165   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3166     channel->channel_key = NULL;
3167     channel = NULL;
3168     goto out;
3169   }
3170
3171   if (channel->cipher)
3172     silc_free(channel->cipher);
3173   channel->cipher = strdup(cipher);
3174
3175   /* Save the key */
3176   channel->key_len = tmp_len * 8;
3177   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3178   memcpy(channel->key, tmp, tmp_len);
3179   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3180
3181   /* Generate HMAC key from the channel key data and set it */
3182   if (!channel->hmac)
3183     silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3184   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3185   silc_hmac_set_key(channel->hmac, hash, 
3186                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3187
3188   memset(hash, 0, sizeof(hash));
3189   memset(tmp, 0, tmp_len);
3190
3191   if (server->server_type == SILC_ROUTER) {
3192     if (!channel->rekey)
3193       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3194     channel->rekey->context = (void *)server;
3195     channel->rekey->channel = channel;
3196     if (channel->rekey->task)
3197       silc_schedule_task_del(server->schedule, channel->rekey->task);
3198
3199     channel->rekey->task = 
3200       silc_schedule_task_add(server->schedule, 0, 
3201                              silc_server_channel_key_rekey,
3202                              (void *)channel->rekey, 
3203                              server->config->channel_rekey_secs, 0,
3204                              SILC_TASK_TIMEOUT,
3205                              SILC_TASK_PRI_NORMAL);
3206   }
3207
3208  out:
3209   silc_free(id);
3210   if (payload)
3211     silc_channel_key_payload_free(payload);
3212
3213   return channel;
3214 }
3215
3216 /* Heartbeat callback. This function is set as argument for the
3217    silc_socket_set_heartbeat function. The library will call this function
3218    at the set time interval. */
3219
3220 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3221                                    void *hb_context)
3222 {
3223   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3224
3225   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3226
3227   /* Send the heartbeat */
3228   silc_server_send_heartbeat(hb->server, sock);
3229 }
3230
3231 /* Returns assembled of all servers in the given ID list. The packet's
3232    form is dictated by the New ID payload. */
3233
3234 static void silc_server_announce_get_servers(SilcServer server,
3235                                              SilcServerEntry remote,
3236                                              SilcIDList id_list,
3237                                              SilcBuffer *servers,
3238                                              unsigned long creation_time)
3239 {
3240   SilcIDCacheList list;
3241   SilcIDCacheEntry id_cache;
3242   SilcServerEntry entry;
3243   SilcBuffer idp;
3244
3245   /* Go through all clients in the list */
3246   if (silc_idcache_get_all(id_list->servers, &list)) {
3247     if (silc_idcache_list_first(list, &id_cache)) {
3248       while (id_cache) {
3249         entry = (SilcServerEntry)id_cache->context;
3250
3251         /* Do not announce the one we've sending our announcements and
3252            do not announce ourself. Also check the creation time if it's
3253            provided. */
3254         if ((entry == remote) || (entry == server->id_entry) ||
3255             (creation_time && entry->data.created < creation_time)) {
3256           if (!silc_idcache_list_next(list, &id_cache))
3257             break;
3258           continue;
3259         }
3260
3261         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3262
3263         *servers = silc_buffer_realloc(*servers, 
3264                                        (*servers ? 
3265                                         (*servers)->truelen + idp->len : 
3266                                         idp->len));
3267         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3268         silc_buffer_put(*servers, idp->data, idp->len);
3269         silc_buffer_pull(*servers, idp->len);
3270         silc_buffer_free(idp);
3271
3272         if (!silc_idcache_list_next(list, &id_cache))
3273           break;
3274       }
3275     }
3276
3277     silc_idcache_list_free(list);
3278   }
3279 }
3280
3281 static SilcBuffer 
3282 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3283 {
3284   va_list ap;
3285   SilcBuffer p;
3286
3287   va_start(ap, argc);
3288   p = silc_notify_payload_encode(notify, argc, ap);
3289   va_end(ap);
3290  
3291   return p;
3292 }
3293
3294 /* This function is used by router to announce existing servers to our
3295    primary router when we've connected to it. If `creation_time' is non-zero
3296    then only the servers that has been created after the `creation_time'
3297    will be announced. */
3298
3299 void silc_server_announce_servers(SilcServer server, bool global,
3300                                   unsigned long creation_time,
3301                                   SilcSocketConnection remote)
3302 {
3303   SilcBuffer servers = NULL;
3304
3305   SILC_LOG_DEBUG(("Announcing servers"));
3306
3307   /* Get servers in local list */
3308   silc_server_announce_get_servers(server, remote->user_data,
3309                                    server->local_list, &servers,
3310                                    creation_time);
3311
3312   if (global)
3313     /* Get servers in global list */
3314     silc_server_announce_get_servers(server, remote->user_data,
3315                                      server->global_list, &servers,
3316                                      creation_time);
3317
3318   if (servers) {
3319     silc_buffer_push(servers, servers->data - servers->head);
3320     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3321
3322     /* Send the packet */
3323     silc_server_packet_send(server, remote,
3324                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3325                             servers->data, servers->len, TRUE);
3326
3327     silc_buffer_free(servers);
3328   }
3329 }
3330
3331 /* Returns assembled packet of all clients in the given ID list. The
3332    packet's form is dictated by the New ID Payload. */
3333
3334 static void silc_server_announce_get_clients(SilcServer server,
3335                                              SilcIDList id_list,
3336                                              SilcBuffer *clients,
3337                                              SilcBuffer *umodes,
3338                                              unsigned long creation_time)
3339 {
3340   SilcIDCacheList list;
3341   SilcIDCacheEntry id_cache;
3342   SilcClientEntry client;
3343   SilcBuffer idp;
3344   SilcBuffer tmp;
3345   unsigned char mode[4];
3346
3347   /* Go through all clients in the list */
3348   if (silc_idcache_get_all(id_list->clients, &list)) {
3349     if (silc_idcache_list_first(list, &id_cache)) {
3350       while (id_cache) {
3351         client = (SilcClientEntry)id_cache->context;
3352
3353         if (creation_time && client->data.created < creation_time) {
3354           if (!silc_idcache_list_next(list, &id_cache))
3355             break;
3356           continue;
3357         }
3358
3359         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3360
3361         *clients = silc_buffer_realloc(*clients, 
3362                                        (*clients ? 
3363                                         (*clients)->truelen + idp->len : 
3364                                         idp->len));
3365         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3366         silc_buffer_put(*clients, idp->data, idp->len);
3367         silc_buffer_pull(*clients, idp->len);
3368
3369         SILC_PUT32_MSB(client->mode, mode);
3370         tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3371                                                  2, idp->data, idp->len,
3372                                                  mode, 4);
3373         *umodes = silc_buffer_realloc(*umodes, 
3374                                       (*umodes ? 
3375                                        (*umodes)->truelen + tmp->len :  
3376                                        tmp->len));
3377         silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3378         silc_buffer_put(*umodes, tmp->data, tmp->len);
3379         silc_buffer_pull(*umodes, tmp->len);
3380         silc_buffer_free(tmp);
3381
3382         silc_buffer_free(idp);
3383
3384         if (!silc_idcache_list_next(list, &id_cache))
3385           break;
3386       }
3387     }
3388
3389     silc_idcache_list_free(list);
3390   }
3391 }
3392
3393 /* This function is used to announce our existing clients to our router
3394    when we've connected to it. If `creation_time' is non-zero then only
3395    the clients that has been created after the `creation_time' will be
3396    announced. */
3397
3398 void silc_server_announce_clients(SilcServer server,
3399                                   unsigned long creation_time,
3400                                   SilcSocketConnection remote)
3401 {
3402   SilcBuffer clients = NULL;
3403   SilcBuffer umodes = NULL;
3404
3405   SILC_LOG_DEBUG(("Announcing clients"));
3406
3407   /* Get clients in local list */
3408   silc_server_announce_get_clients(server, server->local_list,
3409                                    &clients, &umodes, creation_time);
3410
3411   /* As router we announce our global list as well */
3412   if (server->server_type == SILC_ROUTER)
3413     silc_server_announce_get_clients(server, server->global_list,
3414                                      &clients, &umodes, creation_time);
3415
3416   if (clients) {
3417     silc_buffer_push(clients, clients->data - clients->head);
3418     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3419
3420     /* Send the packet */
3421     silc_server_packet_send(server, remote,
3422                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3423                             clients->data, clients->len, TRUE);
3424
3425     silc_buffer_free(clients);
3426   }
3427
3428   if (umodes) {
3429     silc_buffer_push(umodes, umodes->data - umodes->head);
3430     SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3431
3432     /* Send the packet */
3433     silc_server_packet_send(server, remote,
3434                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3435                             umodes->data, umodes->len, TRUE);
3436
3437     silc_buffer_free(umodes);
3438   }
3439 }
3440
3441 /* Returns channel's topic for announcing it */
3442
3443 void silc_server_announce_get_channel_topic(SilcServer server,
3444                                             SilcChannelEntry channel,
3445                                             SilcBuffer *topic)
3446 {
3447   SilcBuffer chidp;
3448
3449   if (channel->topic) {
3450     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3451     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3452                                                 chidp->data, chidp->len,
3453                                                 channel->topic, 
3454                                                 strlen(channel->topic));
3455     silc_buffer_free(chidp);
3456   }
3457 }
3458
3459 /* Returns assembled packets for channel users of the `channel'. */
3460
3461 void silc_server_announce_get_channel_users(SilcServer server,
3462                                             SilcChannelEntry channel,
3463                                             SilcBuffer *channel_users,
3464                                             SilcBuffer *channel_users_modes)
3465 {
3466   SilcChannelClientEntry chl;
3467   SilcHashTableList htl;
3468   SilcBuffer chidp, clidp;
3469   SilcBuffer tmp;
3470   int len;
3471   unsigned char mode[4];
3472
3473   SILC_LOG_DEBUG(("Start"));
3474
3475   /* Now find all users on the channel */
3476   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3477   silc_hash_table_list(channel->user_list, &htl);
3478   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3479     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3480
3481     /* JOIN Notify */
3482     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2, 
3483                                              clidp->data, clidp->len,
3484                                              chidp->data, chidp->len);
3485     len = tmp->len;
3486     *channel_users = 
3487       silc_buffer_realloc(*channel_users, 
3488                           (*channel_users ? 
3489                            (*channel_users)->truelen + len : len));
3490     silc_buffer_pull_tail(*channel_users, 
3491                           ((*channel_users)->end - 
3492                            (*channel_users)->data));
3493     
3494     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3495     silc_buffer_pull(*channel_users, len);
3496     silc_buffer_free(tmp);
3497
3498     /* CUMODE notify for mode change on the channel */
3499     SILC_PUT32_MSB(chl->mode, mode);
3500     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE, 
3501                                              3, clidp->data, clidp->len,
3502                                              mode, 4,
3503                                              clidp->data, clidp->len);
3504     len = tmp->len;
3505     *channel_users_modes = 
3506       silc_buffer_realloc(*channel_users_modes, 
3507                           (*channel_users_modes ? 
3508                            (*channel_users_modes)->truelen + len : len));
3509     silc_buffer_pull_tail(*channel_users_modes, 
3510                           ((*channel_users_modes)->end - 
3511                            (*channel_users_modes)->data));
3512     
3513     silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3514     silc_buffer_pull(*channel_users_modes, len);
3515     silc_buffer_free(tmp);
3516
3517     silc_buffer_free(clidp);
3518   }
3519   silc_hash_table_list_reset(&htl);
3520   silc_buffer_free(chidp);
3521 }
3522
3523 /* Returns assembled packets for all channels and users on those channels
3524    from the given ID List. The packets are in the form dictated by the
3525    New Channel and New Channel User payloads. */
3526
3527 void silc_server_announce_get_channels(SilcServer server,
3528                                        SilcIDList id_list,
3529                                        SilcBuffer *channels,
3530                                        SilcBuffer *channel_users,
3531                                        SilcBuffer **channel_users_modes,
3532                                        uint32 *channel_users_modes_c,
3533                                        SilcBuffer **channel_topics,
3534                                        SilcChannelID ***channel_ids,
3535                                        unsigned long creation_time)
3536 {
3537   SilcIDCacheList list;
3538   SilcIDCacheEntry id_cache;
3539   SilcChannelEntry channel;
3540   unsigned char *cid;
3541   uint32 id_len;
3542   uint16 name_len;
3543   int len;
3544   int i = *channel_users_modes_c;
3545   bool announce;
3546
3547   SILC_LOG_DEBUG(("Start"));
3548
3549   /* Go through all channels in the list */
3550   if (silc_idcache_get_all(id_list->channels, &list)) {
3551     if (silc_idcache_list_first(list, &id_cache)) {
3552       while (id_cache) {
3553         channel = (SilcChannelEntry)id_cache->context;
3554
3555         if (creation_time && channel->created < creation_time)
3556           announce = FALSE;
3557         else
3558           announce = TRUE;
3559
3560         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3561         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3562         name_len = strlen(channel->channel_name);
3563
3564         if (announce) {
3565           len = 4 + name_len + id_len + 4;
3566           *channels = 
3567             silc_buffer_realloc(*channels, 
3568                                 (*channels ? (*channels)->truelen + 
3569                                  len : len));
3570           silc_buffer_pull_tail(*channels, 
3571                                 ((*channels)->end - (*channels)->data));
3572           silc_buffer_format(*channels,
3573                              SILC_STR_UI_SHORT(name_len),
3574                              SILC_STR_UI_XNSTRING(channel->channel_name, 
3575                                                   name_len),
3576                              SILC_STR_UI_SHORT(id_len),
3577                              SILC_STR_UI_XNSTRING(cid, id_len),
3578                              SILC_STR_UI_INT(channel->mode),
3579                              SILC_STR_END);
3580           silc_buffer_pull(*channels, len);
3581         }
3582
3583         /* Channel user modes */
3584         *channel_users_modes = silc_realloc(*channel_users_modes,
3585                                             sizeof(**channel_users_modes) * 
3586                                             (i + 1));
3587         (*channel_users_modes)[i] = NULL;
3588         *channel_ids = silc_realloc(*channel_ids, 
3589                                     sizeof(**channel_ids) * (i + 1));
3590         (*channel_ids)[i] = NULL;
3591         silc_server_announce_get_channel_users(server, channel,
3592                                                channel_users,
3593                                                &(*channel_users_modes)[i]);
3594         (*channel_ids)[i] = channel->id;
3595
3596         /* Channel's topic */
3597         *channel_topics = silc_realloc(*channel_topics,
3598                                        sizeof(**channel_topics) * (i + 1));
3599         (*channel_topics)[i] = NULL;
3600         silc_server_announce_get_channel_topic(server, channel,
3601                                                &(*channel_topics)[i]);
3602         i++;
3603
3604         if (!silc_idcache_list_next(list, &id_cache))
3605           break;
3606       }
3607
3608       *channel_users_modes_c += i;
3609     }
3610
3611     silc_idcache_list_free(list);
3612   }
3613 }
3614
3615 /* This function is used to announce our existing channels to our router
3616    when we've connected to it. This also announces the users on the
3617    channels to the router. If the `creation_time' is non-zero only the
3618    channels that was created after the `creation_time' are announced.
3619    Note that the channel users are still announced even if the `creation_time'
3620    was provided. */
3621
3622 void silc_server_announce_channels(SilcServer server,
3623                                    unsigned long creation_time,
3624                                    SilcSocketConnection remote)
3625 {
3626   SilcBuffer channels = NULL, channel_users = NULL;
3627   SilcBuffer *channel_users_modes = NULL;
3628   SilcBuffer *channel_topics = NULL;
3629   uint32 channel_users_modes_c = 0;
3630   SilcChannelID **channel_ids = NULL;
3631
3632   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3633
3634   /* Get channels and channel users in local list */
3635   silc_server_announce_get_channels(server, server->local_list,
3636                                     &channels, &channel_users,
3637                                     &channel_users_modes,
3638                                     &channel_users_modes_c,
3639                                     &channel_topics,
3640                                     &channel_ids, creation_time);
3641
3642   /* Get channels and channel users in global list */
3643   if (server->server_type != SILC_SERVER)
3644     silc_server_announce_get_channels(server, server->global_list,
3645                                       &channels, &channel_users,
3646                                       &channel_users_modes,
3647                                       &channel_users_modes_c,
3648                                       &channel_topics,
3649                                       &channel_ids, creation_time);
3650
3651   if (channels) {
3652     silc_buffer_push(channels, channels->data - channels->head);
3653     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3654
3655     /* Send the packet */
3656     silc_server_packet_send(server, remote,
3657                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3658                             channels->data, channels->len,
3659                             FALSE);
3660
3661     silc_buffer_free(channels);
3662   }
3663
3664   if (channel_users) {
3665     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3666     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
3667                      channel_users->len);
3668
3669     /* Send the packet */
3670     silc_server_packet_send(server, remote,
3671                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3672                             channel_users->data, channel_users->len,
3673                             FALSE);
3674
3675     silc_buffer_free(channel_users);
3676   }
3677
3678   if (channel_users_modes) {
3679     int i;
3680
3681     for (i = 0; i < channel_users_modes_c; i++) {
3682       if (!channel_users_modes[i])
3683         continue;
3684       silc_buffer_push(channel_users_modes[i], 
3685                        channel_users_modes[i]->data - 
3686                        channel_users_modes[i]->head);
3687       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data, 
3688                        channel_users_modes[i]->len);
3689       silc_server_packet_send_dest(server, remote,
3690                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3691                                    channel_ids[i], SILC_ID_CHANNEL,
3692                                    channel_users_modes[i]->data, 
3693                                    channel_users_modes[i]->len,
3694                                    FALSE);
3695       silc_buffer_free(channel_users_modes[i]);
3696     }
3697     silc_free(channel_users_modes);
3698   }
3699
3700   if (channel_topics) {
3701     int i;
3702
3703     for (i = 0; i < channel_users_modes_c; i++) {
3704       if (!channel_topics[i])
3705         continue;
3706
3707       silc_buffer_push(channel_topics[i], 
3708                        channel_topics[i]->data - 
3709                        channel_topics[i]->head);
3710       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data, 
3711                        channel_topics[i]->len);
3712       silc_server_packet_send_dest(server, remote,
3713                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3714                                    channel_ids[i], SILC_ID_CHANNEL,
3715                                    channel_topics[i]->data, 
3716                                    channel_topics[i]->len,
3717                                    FALSE);
3718       silc_buffer_free(channel_topics[i]);
3719     }
3720     silc_free(channel_topics);
3721   }
3722
3723   silc_free(channel_ids);
3724 }
3725
3726 /* Failure timeout callback. If this is called then we will immediately
3727    process the received failure. We always process the failure with timeout
3728    since we do not want to blindly trust to received failure packets. 
3729    This won't be called (the timeout is cancelled) if the failure was
3730    bogus (it is bogus if remote does not close the connection after sending
3731    the failure). */
3732
3733 SILC_TASK_CALLBACK(silc_server_failure_callback)
3734 {
3735   SilcServerFailureContext f = (SilcServerFailureContext)context;
3736
3737   if (f->sock->protocol) {
3738     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3739     silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3740   }
3741
3742   silc_free(f);
3743 }
3744
3745 /* Assembles user list and users mode list from the `channel'. */
3746
3747 void silc_server_get_users_on_channel(SilcServer server,
3748                                       SilcChannelEntry channel,
3749                                       SilcBuffer *user_list,
3750                                       SilcBuffer *mode_list,
3751                                       uint32 *user_count)
3752 {
3753   SilcChannelClientEntry chl;
3754   SilcHashTableList htl;
3755   SilcBuffer client_id_list;
3756   SilcBuffer client_mode_list;
3757   SilcBuffer idp;
3758   uint32 list_count = 0, len = 0;
3759
3760   silc_hash_table_list(channel->user_list, &htl);
3761   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3762     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3763   silc_hash_table_list_reset(&htl);
3764
3765   client_id_list = silc_buffer_alloc(len);
3766   client_mode_list = 
3767     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3768   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3769   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3770
3771   silc_hash_table_list(channel->user_list, &htl);
3772   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3773     /* Client ID */
3774     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3775     silc_buffer_put(client_id_list, idp->data, idp->len);
3776     silc_buffer_pull(client_id_list, idp->len);
3777     silc_buffer_free(idp);
3778
3779     /* Client's mode on channel */
3780     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3781     silc_buffer_pull(client_mode_list, 4);
3782
3783     list_count++;
3784   }
3785   silc_hash_table_list_reset(&htl);
3786   silc_buffer_push(client_id_list, 
3787                    client_id_list->data - client_id_list->head);
3788   silc_buffer_push(client_mode_list, 
3789                    client_mode_list->data - client_mode_list->head);
3790
3791   *user_list = client_id_list;
3792   *mode_list = client_mode_list;
3793   *user_count = list_count;
3794 }
3795
3796 /* Saves users and their modes to the `channel'. */
3797
3798 void silc_server_save_users_on_channel(SilcServer server,
3799                                        SilcSocketConnection sock,
3800                                        SilcChannelEntry channel,
3801                                        SilcClientID *noadd,
3802                                        SilcBuffer user_list,
3803                                        SilcBuffer mode_list,
3804                                        uint32 user_count)
3805 {
3806   int i;
3807   uint16 idp_len;
3808   uint32 mode;
3809   SilcClientID *client_id;
3810   SilcClientEntry client;
3811   SilcIDCacheEntry cache;
3812   bool global;
3813
3814   SILC_LOG_DEBUG(("Start"));
3815
3816   for (i = 0; i < user_count; i++) {
3817     /* Client ID */
3818     SILC_GET16_MSB(idp_len, user_list->data + 2);
3819     idp_len += 4;
3820     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3821     silc_buffer_pull(user_list, idp_len);
3822     if (!client_id)
3823       continue;
3824
3825     /* Mode */
3826     SILC_GET32_MSB(mode, mode_list->data);
3827     silc_buffer_pull(mode_list, 4);
3828
3829     if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3830       silc_free(client_id);
3831       continue;
3832     }
3833
3834     global = FALSE;
3835     
3836     /* Check if we have this client cached already. */
3837     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3838                                            server->server_type, &cache);
3839     if (!client) {
3840       client = silc_idlist_find_client_by_id(server->global_list, 
3841                                              client_id, server->server_type,
3842                                              &cache);
3843       global = TRUE;
3844     }
3845     if (!client) {
3846       /* If router did not find such Client ID in its lists then this must
3847          be bogus client or some router in the net is buggy. */
3848       if (server->server_type == SILC_ROUTER) {
3849         silc_free(client_id);
3850         continue;
3851       }
3852
3853       /* We don't have that client anywhere, add it. The client is added
3854          to global list since server didn't have it in the lists so it must be 
3855          global. */
3856       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3857                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3858                                       sock->user_data, NULL, 0);
3859       if (!client) {
3860         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3861         silc_free(client_id);
3862         continue;
3863       }
3864
3865       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3866     } else {
3867       /* Found, if it is from global list we'll assure that we won't
3868          expire it now that the entry is on channel. */
3869       if (global)
3870         cache->expire = 0;
3871     }
3872
3873     silc_free(client_id);
3874
3875     if (!silc_server_client_on_channel(client, channel)) {
3876       /* Client was not on the channel, add it. */
3877       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3878       chl->client = client;
3879       chl->mode = mode;
3880       chl->channel = channel;
3881       silc_hash_table_add(channel->user_list, chl->client, chl);
3882       silc_hash_table_add(client->channels, chl->channel, chl);
3883     }
3884   }
3885 }
3886
3887 /* Lookups route to the client indicated by the `id_data'. The connection
3888    object and internal data object is returned. Returns NULL if route
3889    could not be found to the client. If the `client_id' is specified then
3890    it is used and the `id_data' is ignored. */
3891
3892 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3893                                                   unsigned char *id_data,
3894                                                   uint32 id_len,
3895                                                   SilcClientID *client_id,
3896                                                   SilcIDListData *idata)
3897 {
3898   SilcClientID *id;
3899   SilcClientEntry client;
3900
3901   SILC_LOG_DEBUG(("Start"));
3902
3903   /* Decode destination Client ID */
3904   if (!client_id) {
3905     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3906     if (!id) {
3907       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3908       return NULL;
3909     }
3910   } else {
3911     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3912   }
3913
3914   /* If the destination belongs to our server we don't have to route
3915      the packet anywhere but to send it to the local destination. */
3916   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3917   if (client) {
3918     silc_free(id);
3919
3920     /* If we are router and the client has router then the client is in
3921        our cell but not directly connected to us. */
3922     if (server->server_type == SILC_ROUTER && client->router) {
3923       /* We are of course in this case the client's router thus the route
3924          to the client is the server who owns the client. So, we will send
3925          the packet to that server. */
3926       if (idata)
3927         *idata = (SilcIDListData)client->router;
3928       return client->router->connection;
3929     }
3930
3931     /* Seems that client really is directly connected to us */
3932     if (idata)
3933       *idata = (SilcIDListData)client;
3934     return client->connection;
3935   }
3936
3937   /* Destination belongs to someone not in this server. If we are normal
3938      server our action is to send the packet to our router. */
3939   if (server->server_type != SILC_ROUTER && !server->standalone) {
3940     silc_free(id);
3941     if (idata)
3942       *idata = (SilcIDListData)server->router;
3943     return server->router->connection;
3944   }
3945
3946   /* We are router and we will perform route lookup for the destination 
3947      and send the packet to fastest route. */
3948   if (server->server_type == SILC_ROUTER && !server->standalone) {
3949     /* Check first that the ID is valid */
3950     client = silc_idlist_find_client_by_id(server->global_list, id, 
3951                                            TRUE, NULL);
3952     if (client) {
3953       SilcSocketConnection dst_sock;
3954
3955       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3956
3957       silc_free(id);
3958       if (idata)
3959         *idata = (SilcIDListData)dst_sock->user_data;
3960       return dst_sock;
3961     }
3962   }
3963
3964   silc_free(id);
3965   return NULL;
3966 }
3967
3968 /* Encodes and returns channel list of channels the `client' has joined.
3969    Secret channels are not put to the list. */
3970
3971 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3972                                                SilcClientEntry client)
3973 {
3974   SilcBuffer buffer = NULL;
3975   SilcChannelEntry channel;
3976   SilcChannelClientEntry chl;
3977   SilcHashTableList htl;
3978   unsigned char *cid;
3979   uint32 id_len;
3980   uint16 name_len;
3981   int len;
3982
3983   silc_hash_table_list(client->channels, &htl);
3984   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3985     channel = chl->channel;
3986
3987     if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3988         channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3989       continue;
3990
3991     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3992     id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3993     name_len = strlen(channel->channel_name);
3994     
3995     len = 4 + name_len + id_len + 4;
3996     buffer = silc_buffer_realloc(buffer, 
3997                                  (buffer ? (buffer)->truelen + len : len));
3998     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3999     silc_buffer_format(buffer,
4000                        SILC_STR_UI_SHORT(name_len),
4001                        SILC_STR_UI_XNSTRING(channel->channel_name, 
4002                                             name_len),
4003                        SILC_STR_UI_SHORT(id_len),
4004                        SILC_STR_UI_XNSTRING(cid, id_len),
4005                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
4006                        SILC_STR_END);
4007     silc_buffer_pull(buffer, len);
4008     silc_free(cid);
4009   }
4010   silc_hash_table_list_reset(&htl);
4011
4012   if (buffer)
4013     silc_buffer_push(buffer, buffer->data - buffer->head);
4014
4015   return buffer;
4016 }
4017
4018 /* Finds client entry by Client ID and if it is not found then resolves
4019    it using WHOIS command. */
4020
4021 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4022                                                SilcClientID *client_id,
4023                                                bool *resolved)
4024 {
4025   SilcClientEntry client;
4026
4027   if (resolved)
4028     *resolved = FALSE;
4029
4030   client = silc_idlist_find_client_by_id(server->local_list, client_id,
4031                                          TRUE, NULL);
4032   if (!client) {
4033     client = silc_idlist_find_client_by_id(server->global_list, 
4034                                            client_id, TRUE, NULL);
4035     if (!client && server->server_type == SILC_ROUTER)
4036       return NULL;
4037   }
4038
4039   if (!client && server->standalone)
4040     return NULL;
4041
4042   if (!client || !client->nickname || !client->username) {
4043     SilcBuffer buffer, idp;
4044
4045     client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4046     client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4047     client->resolve_cmd_ident = ++server->cmd_ident;
4048
4049     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4050     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4051                                             server->cmd_ident, 1,
4052                                             3, idp->data, idp->len);
4053     silc_server_packet_send(server, client ? client->router->connection :
4054                             server->router->connection,
4055                             SILC_PACKET_COMMAND, 0,
4056                             buffer->data, buffer->len, FALSE);
4057     silc_buffer_free(idp);
4058     silc_buffer_free(buffer);
4059
4060     if (resolved)
4061       *resolved = TRUE;
4062
4063     return NULL;
4064   }
4065
4066   return client;
4067 }
4068
4069 /* A timeout callback for the re-key. We will be the initiator of the
4070    re-key protocol. */
4071
4072 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4073 {
4074   SilcSocketConnection sock = (SilcSocketConnection)context;
4075   SilcIDListData idata = (SilcIDListData)sock->user_data;
4076   SilcServer server = (SilcServer)idata->rekey->context;
4077   SilcProtocol protocol;
4078   SilcServerRekeyInternalContext *proto_ctx;
4079
4080   SILC_LOG_DEBUG(("Start"));
4081
4082   /* Allocate internal protocol context. This is sent as context
4083      to the protocol. */
4084   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4085   proto_ctx->server = (void *)server;
4086   proto_ctx->sock = sock;
4087   proto_ctx->responder = FALSE;
4088   proto_ctx->pfs = idata->rekey->pfs;
4089       
4090   /* Perform rekey protocol. Will call the final callback after the
4091      protocol is over. */
4092   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
4093                       &protocol, proto_ctx, silc_server_rekey_final);
4094   sock->protocol = protocol;
4095       
4096   /* Run the protocol */
4097   silc_protocol_execute(protocol, server->schedule, 0, 0);
4098
4099   /* Re-register re-key timeout */
4100   silc_schedule_task_add(server->schedule, sock->sock, 
4101                          silc_server_rekey_callback,
4102                          context, idata->rekey->timeout, 0,
4103                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4104 }
4105
4106 /* The final callback for the REKEY protocol. This will actually take the
4107    new key material into use. */
4108
4109 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4110 {
4111   SilcProtocol protocol = (SilcProtocol)context;
4112   SilcServerRekeyInternalContext *ctx =
4113     (SilcServerRekeyInternalContext *)protocol->context;
4114   SilcServer server = (SilcServer)ctx->server;
4115   SilcSocketConnection sock = ctx->sock;
4116
4117   SILC_LOG_DEBUG(("Start"));
4118
4119   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4120       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4121     /* Error occured during protocol */
4122     SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4123     silc_protocol_cancel(protocol, server->schedule);
4124     silc_protocol_free(protocol);
4125     sock->protocol = NULL;
4126     if (ctx->packet)
4127       silc_packet_context_free(ctx->packet);
4128     if (ctx->ske)
4129       silc_ske_free(ctx->ske);
4130     silc_free(ctx);
4131     return;
4132   }
4133
4134   /* Purge the outgoing data queue to assure that all rekey packets really
4135      go to the network before we quit the protocol. */
4136   silc_server_packet_queue_purge(server, sock);
4137
4138   /* Cleanup */
4139   silc_protocol_free(protocol);
4140   sock->protocol = NULL;
4141   if (ctx->packet)
4142     silc_packet_context_free(ctx->packet);
4143   if (ctx->ske)
4144     silc_ske_free(ctx->ske);
4145   silc_free(ctx);
4146 }