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