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