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