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