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