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