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