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