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