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