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