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