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