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