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