5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
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.
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.
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.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
90 silc_server_config_unref(&server->config_ref);
92 silc_rng_free(server->rng);
94 silc_pkcs_free(server->pkcs);
95 if (server->public_key)
96 silc_pkcs_public_key_free(server->public_key);
97 if (server->private_key)
98 silc_pkcs_private_key_free(server->private_key);
99 if (server->pending_commands)
100 silc_dlist_uninit(server->pending_commands);
101 if (server->id_entry)
102 silc_idlist_del_server(server->local_list, server->id_entry);
104 silc_idcache_free(server->local_list->clients);
105 silc_idcache_free(server->local_list->servers);
106 silc_idcache_free(server->local_list->channels);
107 silc_idcache_free(server->global_list->clients);
108 silc_idcache_free(server->global_list->servers);
109 silc_idcache_free(server->global_list->channels);
111 silc_free(server->sockets);
116 /* Opens a listening port.
117 XXX This function will become more general and will support multiple
120 static bool silc_server_listen(SilcServer server, int *sock)
123 *sock = silc_net_create_server(server->config->server_info->port,
124 server->config->server_info->server_ip);
126 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
127 server->config->server_info->server_ip,
128 server->config->server_info->port));
134 /* Initializes the entire SILC server. This is called always before running
135 the server. This is called only once at the initialization of the program.
136 This binds the server to its listenning port. After this function returns
137 one should call silc_server_run to start the server. This returns TRUE
138 when everything is ok to run the server. Configuration file must be
139 read and parsed before calling this. */
141 bool silc_server_init(SilcServer server)
145 SilcServerEntry id_entry;
146 SilcIDListPurge purge;
147 SilcSocketConnection newsocket = NULL;
149 SILC_LOG_DEBUG(("Initializing server"));
151 /* Take config object for us */
152 silc_server_config_ref(&server->config_ref, server->config,
155 /* Steal public and private key from the config object */
156 server->public_key = server->config->server_info->public_key;
157 server->private_key = server->config->server_info->private_key;
158 server->config->server_info->public_key = NULL;
159 server->config->server_info->private_key = NULL;
161 /* Register all configured ciphers, PKCS and hash functions. */
162 if (!silc_server_config_register_ciphers(server))
163 silc_cipher_register_default();
164 if (!silc_server_config_register_pkcs(server))
165 silc_pkcs_register_default();
166 if (!silc_server_config_register_hashfuncs(server))
167 silc_hash_register_default();
168 if (!silc_server_config_register_hmacs(server))
169 silc_hmac_register_default();
171 /* Initialize random number generator for the server. */
172 server->rng = silc_rng_alloc();
173 silc_rng_init(server->rng);
174 silc_rng_global_init(server->rng);
176 /* Initialize hash functions for server to use */
177 silc_hash_alloc("md5", &server->md5hash);
178 silc_hash_alloc("sha1", &server->sha1hash);
180 /* Allocate PKCS context for local public and private keys */
181 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
183 silc_pkcs_public_key_set(server->pkcs, server->public_key);
184 silc_pkcs_private_key_set(server->pkcs, server->private_key);
186 /* Initialize the scheduler */
187 server->schedule = silc_schedule_init(server->config->param.connections_max);
188 if (!server->schedule)
191 /* First, register log files configuration for error output */
192 silc_server_config_setlogfiles(server);
194 /* Initialize ID caches */
195 server->local_list->clients =
196 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
197 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
198 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
200 /* These are allocated for normal server as well as these hold some
201 global information that the server has fetched from its router. For
202 router these are used as they are supposed to be used on router. */
203 server->global_list->clients =
204 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
205 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
206 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
208 /* Create a listening server */
209 if (!silc_server_listen(server, &sock))
212 /* Set socket to non-blocking mode */
213 silc_net_set_socket_nonblock(sock);
216 /* Allocate the entire socket list that is used in server. Eventually
217 all connections will have entry in this table (it is a table of
218 pointers to the actual object that is allocated individually
220 server->sockets = silc_calloc(server->config->param.connections_max,
221 sizeof(*server->sockets));
222 if (!server->sockets)
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
234 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
257 server->config->server_info->server_name = NULL;
259 /* Add ourselves to the server list. We don't have a router yet
260 beacuse we haven't established a route yet. It will be done later.
261 For now, NULL is sent as router. This allocates new entry to
264 silc_idlist_add_server(server->local_list, strdup(server->server_name),
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
278 /* Register protocols */
279 silc_server_protocols_register();
281 /* Add the first task to the scheduler. This is task that is executed by
282 timeout. It expires as soon as the caller calls silc_server_run. This
283 task performs authentication protocol and key exchange with our
285 silc_schedule_task_add(server->schedule, 0,
286 silc_server_connect_to_router,
287 (void *)server, 0, 1,
289 SILC_TASK_PRI_NORMAL);
291 /* Add listener task to the scheduler. This task receives new connections
292 to the server. This task remains on the queue until the end of the
294 silc_schedule_task_add(server->schedule, sock,
295 silc_server_accept_new_connection,
296 (void *)server, 0, 0,
298 SILC_TASK_PRI_NORMAL);
299 server->listenning = TRUE;
301 /* If server connections has been configured then we must be router as
302 normal server cannot have server connections, only router connections. */
303 if (server->config->servers) {
304 SilcServerConfigServer *ptr = server->config->servers;
306 server->server_type = SILC_ROUTER;
308 if (ptr->backup_router) {
309 server->server_type = SILC_BACKUP_ROUTER;
310 server->backup_router = TRUE;
311 server->id_entry->server_type = SILC_BACKUP_ROUTER;
318 /* Register the ID Cache purge task. This periodically purges the ID cache
319 and removes the expired cache entries. */
321 /* Clients local list */
322 purge = silc_calloc(1, sizeof(*purge));
323 purge->cache = server->local_list->clients;
324 purge->schedule = server->schedule;
325 purge->timeout = 600;
326 silc_schedule_task_add(purge->schedule, 0,
328 (void *)purge, purge->timeout, 0,
329 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
331 /* Clients global list */
332 purge = silc_calloc(1, sizeof(*purge));
333 purge->cache = server->global_list->clients;
334 purge->schedule = server->schedule;
335 purge->timeout = 300;
336 silc_schedule_task_add(purge->schedule, 0,
338 (void *)purge, purge->timeout, 0,
339 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
341 SILC_LOG_DEBUG(("Server initialized"));
343 /* We are done here, return succesfully */
347 silc_server_config_unref(&server->config_ref);
348 silc_net_close_server(sock);
352 /* This function basically reads the config file again and switches the config
353 object pointed by the server object. After that, we have to fix various
354 things such as the server_name and the listening ports.
355 Keep in mind that we no longer have the root privileges at this point. */
357 bool silc_server_rehash(SilcServer server)
359 SilcServerConfig newconfig;
361 SILC_LOG_INFO(("Rehashing server"));
363 /* Reset the logging system */
364 silc_log_quick = TRUE;
365 silc_log_flush_all();
367 /* Start the main rehash phase (read again the config file) */
368 newconfig = silc_server_config_alloc(server->config_file);
370 SILC_LOG_ERROR(("Rehash FAILED."));
374 /* Reinit scheduler if necessary */
375 if (newconfig->param.connections_max > server->config->param.connections_max)
376 if (!silc_schedule_reinit(server->schedule,
377 newconfig->param.connections_max))
380 /* Fix the server_name field */
381 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
382 silc_free(server->server_name);
383 server->server_name = newconfig->server_info->server_name;
384 newconfig->server_info->server_name = NULL;
386 /* Update the idcache list with a fresh pointer */
387 silc_free(server->id_entry->server_name);
388 server->id_entry->server_name = strdup(server->server_name);
389 if (!silc_idcache_del_by_context(server->local_list->servers,
392 if (!silc_idcache_add(server->local_list->servers,
393 server->id_entry->server_name,
394 server->id_entry->id, server->id_entry, 0, NULL))
399 silc_server_config_setlogfiles(server);
401 /* Change new key pair if necessary */
402 if (newconfig->server_info->public_key &&
403 !silc_pkcs_public_key_compare(server->public_key,
404 newconfig->server_info->public_key)) {
405 silc_pkcs_public_key_free(server->public_key);
406 silc_pkcs_private_key_free(server->private_key);
407 server->public_key = newconfig->server_info->public_key;
408 server->private_key = newconfig->server_info->private_key;
409 newconfig->server_info->public_key = NULL;
410 newconfig->server_info->private_key = NULL;
412 /* Allocate PKCS context for local public and private keys */
413 silc_pkcs_free(server->pkcs);
414 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
416 silc_pkcs_public_key_set(server->pkcs, server->public_key);
417 silc_pkcs_private_key_set(server->pkcs, server->private_key);
420 /* Go through all configured routers after rehash */
421 silc_schedule_task_add(server->schedule, 0,
422 silc_server_connect_to_router,
423 (void *)server, 0, 1,
425 SILC_TASK_PRI_NORMAL);
427 /* Check whether our router status has changed */
428 if (newconfig->servers) {
429 SilcServerConfigServer *ptr = newconfig->servers;
431 server->server_type = SILC_ROUTER;
433 if (ptr->backup_router) {
434 server->server_type = SILC_BACKUP_ROUTER;
435 server->backup_router = TRUE;
436 server->id_entry->server_type = SILC_BACKUP_ROUTER;
443 /* Our old config is gone now. We'll unreference our reference made in
444 silc_server_init and then destroy it since we are destroying it
445 underneath the application (layer which called silc_server_init). */
446 silc_server_config_unref(&server->config_ref);
447 silc_server_config_destroy(server->config);
449 /* Take new config context */
450 server->config = newconfig;
451 silc_server_config_ref(&server->config_ref, server->config, server->config);
453 SILC_LOG_DEBUG(("Server rehashed"));
458 /* The heart of the server. This runs the scheduler thus runs the server.
459 When this returns the server has been stopped and the program will
462 void silc_server_run(SilcServer server)
464 SILC_LOG_INFO(("SILC Server started"));
466 /* Start the scheduler, the heart of the SILC server. When this returns
467 the program will be terminated. */
468 silc_schedule(server->schedule);
471 /* Stops the SILC server. This function is used to shutdown the server.
472 This is usually called after the scheduler has returned. After stopping
473 the server one should call silc_server_free. */
475 void silc_server_stop(SilcServer server)
477 SILC_LOG_DEBUG(("Stopping server"));
479 if (server->schedule) {
480 silc_schedule_stop(server->schedule);
481 silc_schedule_uninit(server->schedule);
482 server->schedule = NULL;
485 silc_server_protocols_unregister();
487 SILC_LOG_DEBUG(("Server stopped"));
490 /* Function that is called when the network connection to a router has
491 been established. This will continue with the key exchange protocol
492 with the remote router. */
494 void silc_server_start_key_exchange(SilcServer server,
495 SilcServerConnection sconn,
498 SilcSocketConnection newsocket;
499 SilcProtocol protocol;
500 SilcServerKEInternalContext *proto_ctx;
501 SilcServerConfigRouter *conn =
502 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
505 /* Cancel any possible retry timeouts */
506 silc_schedule_task_del_by_callback(server->schedule,
507 silc_server_connect_router);
509 /* Set socket options */
510 silc_net_set_socket_nonblock(sock);
511 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
513 /* Create socket connection for the connection. Even though we
514 know that we are connecting to a router we will mark the socket
515 to be unknown connection until we have executed authentication
517 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
518 server->sockets[sock] = newsocket;
519 newsocket->hostname = strdup(sconn->remote_host);
520 newsocket->ip = strdup(sconn->remote_host);
521 newsocket->port = sconn->remote_port;
522 sconn->sock = newsocket;
524 /* Allocate internal protocol context. This is sent as context
526 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
527 proto_ctx->server = (void *)server;
528 proto_ctx->context = (void *)sconn;
529 proto_ctx->sock = newsocket;
530 proto_ctx->rng = server->rng;
531 proto_ctx->responder = FALSE;
533 /* Set Key Exchange flags from configuration, but fall back to global
535 SILC_GET_SKE_FLAGS(conn, proto_ctx);
536 if (server->config->param.key_exchange_pfs)
537 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
539 /* Perform key exchange protocol. silc_server_connect_to_router_second
540 will be called after the protocol is finished. */
541 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
542 &protocol, proto_ctx,
543 silc_server_connect_to_router_second);
544 newsocket->protocol = protocol;
546 /* Register a timeout task that will be executed if the protocol
547 is not executed within set limit. */
548 proto_ctx->timeout_task =
549 silc_schedule_task_add(server->schedule, sock,
550 silc_server_timeout_remote,
551 server, server->config->key_exchange_timeout, 0,
555 /* Register the connection for network input and output. This sets
556 that scheduler will listen for incoming packets for this connection
557 and sets that outgoing packets may be sent to this connection as
558 well. However, this doesn't set the scheduler for outgoing traffic,
559 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
560 later when outgoing data is available. */
561 context = (void *)server;
562 SILC_REGISTER_CONNECTION_FOR_IO(sock);
564 /* Run the protocol */
565 silc_protocol_execute(protocol, server->schedule, 0, 0);
568 /* Timeout callback that will be called to retry connecting to remote
569 router. This is used by both normal and router server. This will wait
570 before retrying the connecting. The timeout is generated by exponential
571 backoff algorithm. */
573 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
575 SilcServerConnection sconn = (SilcServerConnection)context;
576 SilcServer server = sconn->server;
577 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
578 SilcServerConfigConnParams *param =
579 (conn->param ? conn->param : &server->config->param);
581 SILC_LOG_INFO(("Retrying connecting to a router"));
583 /* Calculate next timeout */
584 if (sconn->retry_count >= 1) {
585 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
586 if (sconn->retry_timeout > param->reconnect_interval_max)
587 sconn->retry_timeout = param->reconnect_interval_max;
589 sconn->retry_timeout = param->reconnect_interval;
591 sconn->retry_count++;
592 sconn->retry_timeout = sconn->retry_timeout +
593 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
595 /* If we've reached max retry count, give up. */
596 if ((sconn->retry_count > param->reconnect_count) &&
597 !param->reconnect_keep_trying) {
598 SILC_LOG_ERROR(("Could not connect to router, giving up"));
599 silc_server_config_unref(&sconn->conn);
600 silc_free(sconn->remote_host);
601 silc_free(sconn->backup_replace_ip);
606 /* We will lookup a fresh pointer later */
607 silc_server_config_unref(&sconn->conn);
609 /* Wait one before retrying */
610 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
611 context, sconn->retry_timeout, 0,
612 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
615 /* Generic routine to use connect to a router. */
617 SILC_TASK_CALLBACK(silc_server_connect_router)
619 SilcServerConnection sconn = (SilcServerConnection)context;
620 SilcServer server = sconn->server;
621 SilcServerConfigRouter *rconn;
624 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
625 (sconn->backup ? "backup router" : "router"),
626 sconn->remote_host, sconn->remote_port));
628 server->router_connect = time(NULL);
629 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
632 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
633 (sconn->backup ? "backup router" : "router"),
634 sconn->remote_host, sconn->remote_port));
635 silc_free(sconn->remote_host);
636 silc_free(sconn->backup_replace_ip);
640 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
642 /* Connect to remote host */
643 sock = silc_net_create_connection(server->config->server_info->server_ip,
647 SILC_LOG_ERROR(("Could not connect to router %s:%d",
648 sconn->remote_host, sconn->remote_port));
649 if (!sconn->no_reconnect)
650 silc_schedule_task_add(server->schedule, 0,
651 silc_server_connect_to_router_retry,
652 context, 0, 1, SILC_TASK_TIMEOUT,
653 SILC_TASK_PRI_NORMAL);
655 silc_server_config_unref(&sconn->conn);
659 /* Continue with key exchange protocol */
660 silc_server_start_key_exchange(server, sconn, sock);
663 /* This function connects to our primary router or if we are a router this
664 establishes all our primary routes. This is called at the start of the
665 server to do authentication and key exchange with our router - called
668 SILC_TASK_CALLBACK(silc_server_connect_to_router)
670 SilcServer server = (SilcServer)context;
671 SilcServerConnection sconn;
672 SilcServerConfigRouter *ptr;
674 SILC_LOG_DEBUG(("Connecting to router(s)"));
676 if (server->server_type == SILC_SERVER) {
677 SILC_LOG_DEBUG(("We are normal server"));
678 } else if (server->server_type == SILC_ROUTER) {
679 SILC_LOG_DEBUG(("We are router"));
681 SILC_LOG_DEBUG(("We are backup router/normal server"));
684 if (!server->config->routers) {
685 /* There wasn't a configured router, we will continue but we don't
686 have a connection to outside world. We will be standalone server. */
687 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
688 server->standalone = TRUE;
692 /* Cancel any possible retry timeouts */
693 silc_schedule_task_del_by_callback(server->schedule,
694 silc_server_connect_router);
695 silc_schedule_task_del_by_callback(server->schedule,
696 silc_server_connect_to_router_retry);
698 /* Create the connections to all our routes */
699 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
701 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
702 ptr->backup_router ? "Backup router" : "Router",
703 ptr->initiator ? "Initiator" : "Responder",
704 ptr->host, ptr->port));
706 if (ptr->initiator) {
707 /* Check whether we are connected to this host already */
708 if (silc_server_num_sockets_by_remote(server,
709 silc_net_is_ip(ptr->host) ?
711 silc_net_is_ip(ptr->host) ?
712 NULL : ptr->host, ptr->port,
713 SILC_SOCKET_TYPE_ROUTER)) {
714 SILC_LOG_DEBUG(("We are already connected to this router"));
718 /* Allocate connection object for hold connection specific stuff. */
719 sconn = silc_calloc(1, sizeof(*sconn));
720 sconn->server = server;
721 sconn->remote_host = strdup(ptr->host);
722 sconn->remote_port = ptr->port;
723 sconn->backup = ptr->backup_router;
725 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
726 sconn->backup_replace_port = ptr->backup_replace_port;
729 if (!server->router_conn && !sconn->backup)
730 server->router_conn = sconn;
732 silc_schedule_task_add(server->schedule, 0,
733 silc_server_connect_router,
734 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
735 SILC_TASK_PRI_NORMAL);
740 /* Second part of connecting to router(s). Key exchange protocol has been
741 executed and now we will execute authentication protocol. */
743 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
745 SilcProtocol protocol = (SilcProtocol)context;
746 SilcServerKEInternalContext *ctx =
747 (SilcServerKEInternalContext *)protocol->context;
748 SilcServer server = (SilcServer)ctx->server;
749 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
750 SilcSocketConnection sock = ctx->sock;
751 SilcServerConnAuthInternalContext *proto_ctx;
752 SilcServerConfigRouter *conn = NULL;
754 SILC_LOG_DEBUG(("Start"));
756 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
757 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
758 /* Error occured during protocol */
759 silc_protocol_free(protocol);
760 sock->protocol = NULL;
761 silc_ske_free_key_material(ctx->keymat);
763 silc_packet_context_free(ctx->packet);
765 silc_ske_free(ctx->ske);
766 silc_free(ctx->dest_id);
768 silc_server_config_unref(&sconn->conn);
769 silc_free(sconn->remote_host);
770 silc_free(sconn->backup_replace_ip);
772 silc_schedule_task_del_by_callback(server->schedule,
773 silc_server_failure_callback);
774 silc_server_disconnect_remote(server, sock, "Server closed connection: "
775 "Key exchange failed");
779 /* We now have the key material as the result of the key exchange
780 protocol. Take the key material into use. Free the raw key material
781 as soon as we've set them into use. */
782 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
783 ctx->sock, ctx->keymat,
784 ctx->ske->prop->cipher,
785 ctx->ske->prop->pkcs,
786 ctx->ske->prop->hash,
787 ctx->ske->prop->hmac,
788 ctx->ske->prop->group,
790 silc_protocol_free(protocol);
791 sock->protocol = NULL;
792 silc_ske_free_key_material(ctx->keymat);
794 silc_packet_context_free(ctx->packet);
796 silc_ske_free(ctx->ske);
797 silc_free(ctx->dest_id);
799 silc_server_config_unref(&sconn->conn);
800 silc_free(sconn->remote_host);
801 silc_free(sconn->backup_replace_ip);
803 silc_schedule_task_del_by_callback(server->schedule,
804 silc_server_failure_callback);
805 silc_server_disconnect_remote(server, sock, "Server closed connection: "
806 "Key exchange failed");
809 silc_ske_free_key_material(ctx->keymat);
811 /* Allocate internal context for the authentication protocol. This
812 is sent as context for the protocol. */
813 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
814 proto_ctx->server = (void *)server;
815 proto_ctx->context = (void *)sconn;
816 proto_ctx->sock = sock;
817 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
818 proto_ctx->dest_id_type = ctx->dest_id_type;
819 proto_ctx->dest_id = ctx->dest_id;
821 /* Resolve the authentication method used in this connection. Check if
822 we find a match from user configured connections */
823 if (!sconn->conn.ref_ptr)
824 conn = silc_server_config_find_router_conn(server, sock->hostname,
827 conn = sconn->conn.ref_ptr;
830 /* Match found. Use the configured authentication method. Take only
831 the passphrase, since for public key auth we automatically use
832 our local key pair. */
833 if (conn->passphrase) {
834 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
835 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
837 proto_ctx->auth_data = strdup(conn->passphrase);
838 proto_ctx->auth_data_len = strlen(conn->passphrase);
839 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
841 } else if (conn->publickeys) {
842 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
844 proto_ctx->auth_meth = SILC_AUTH_NONE;
847 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
848 sock->hostname, sock->ip, sock->port));
849 silc_protocol_free(protocol);
850 sock->protocol = NULL;
852 silc_packet_context_free(ctx->packet);
854 silc_ske_free(ctx->ske);
855 silc_free(ctx->dest_id);
857 silc_server_config_unref(&sconn->conn);
858 silc_free(sconn->remote_host);
859 silc_free(sconn->backup_replace_ip);
861 silc_schedule_task_del_by_callback(server->schedule,
862 silc_server_failure_callback);
863 silc_server_disconnect_remote(server, sock, "Server closed connection: "
864 "Key exchange failed");
868 /* Free old protocol as it is finished now */
869 silc_protocol_free(protocol);
871 silc_packet_context_free(ctx->packet);
873 sock->protocol = NULL;
875 /* Allocate the authentication protocol. This is allocated here
876 but we won't start it yet. We will be receiving party of this
877 protocol thus we will wait that connecting party will make
879 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
880 &sock->protocol, proto_ctx,
881 silc_server_connect_to_router_final);
883 /* Register timeout task. If the protocol is not executed inside
884 this timelimit the connection will be terminated. */
885 proto_ctx->timeout_task =
886 silc_schedule_task_add(server->schedule, sock->sock,
887 silc_server_timeout_remote,
889 server->config->conn_auth_timeout, 0,
893 /* Run the protocol */
894 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
897 /* Finalizes the connection to router. Registers a server task to the
898 queue so that we can accept new connections. */
900 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
902 SilcProtocol protocol = (SilcProtocol)context;
903 SilcServerConnAuthInternalContext *ctx =
904 (SilcServerConnAuthInternalContext *)protocol->context;
905 SilcServer server = (SilcServer)ctx->server;
906 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
907 SilcSocketConnection sock = ctx->sock;
908 SilcServerEntry id_entry;
910 SilcServerHBContext hb_context;
911 unsigned char *id_string;
913 SilcIDListData idata;
914 SilcServerConfigRouter *conn = NULL;
915 SilcServerConfigConnParams *param = NULL;
917 SILC_LOG_DEBUG(("Start"));
919 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
920 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
921 /* Error occured during protocol */
922 silc_free(ctx->dest_id);
923 silc_server_disconnect_remote(server, sock, "Server closed connection: "
924 "Authentication failed");
928 /* Add a task to the queue. This task receives new connections to the
929 server. This task remains on the queue until the end of the program. */
930 if (!server->listenning && !sconn->backup) {
931 silc_schedule_task_add(server->schedule, server->sock,
932 silc_server_accept_new_connection,
933 (void *)server, 0, 0,
935 SILC_TASK_PRI_NORMAL);
936 server->listenning = TRUE;
939 /* Send NEW_SERVER packet to the router. We will become registered
940 to the SILC network after sending this packet. */
941 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
942 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
943 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
944 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
945 silc_buffer_format(packet,
946 SILC_STR_UI_SHORT(id_len),
947 SILC_STR_UI_XNSTRING(id_string, id_len),
948 SILC_STR_UI_SHORT(strlen(server->server_name)),
949 SILC_STR_UI_XNSTRING(server->server_name,
950 strlen(server->server_name)),
953 /* Send the packet */
954 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
955 packet->data, packet->len, TRUE);
956 silc_buffer_free(packet);
957 silc_free(id_string);
959 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
961 /* Check that we do not have this ID already */
962 id_entry = silc_idlist_find_server_by_id(server->local_list,
963 ctx->dest_id, TRUE, NULL);
965 silc_idcache_del_by_context(server->local_list->servers, id_entry);
967 id_entry = silc_idlist_find_server_by_id(server->global_list,
968 ctx->dest_id, TRUE, NULL);
970 silc_idcache_del_by_context(server->global_list->servers, id_entry);
973 SILC_LOG_DEBUG(("New server id(%s)",
974 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
976 /* Add the connected router to global server list */
977 id_entry = silc_idlist_add_server(server->global_list,
978 strdup(sock->hostname),
979 SILC_ROUTER, ctx->dest_id, NULL, sock);
981 silc_free(ctx->dest_id);
982 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
983 silc_server_disconnect_remote(server, sock, "Server closed connection: "
984 "Authentication failed");
988 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
989 silc_free(sock->user_data);
990 sock->user_data = (void *)id_entry;
991 sock->type = SILC_SOCKET_TYPE_ROUTER;
992 idata = (SilcIDListData)sock->user_data;
993 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
995 conn = sconn->conn.ref_ptr;
996 param = &server->config->param;
997 if (conn && conn->param)
1000 /* Perform keepalive. The `hb_context' will be freed automatically
1001 when finally calling the silc_socket_free function. */
1002 hb_context = silc_calloc(1, sizeof(*hb_context));
1003 hb_context->server = server;
1004 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1005 silc_server_perform_heartbeat,
1008 /* Register re-key timeout */
1009 idata->rekey->timeout = param->key_exchange_rekey;
1010 idata->rekey->context = (void *)server;
1011 silc_schedule_task_add(server->schedule, sock->sock,
1012 silc_server_rekey_callback,
1013 (void *)sock, idata->rekey->timeout, 0,
1014 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1016 if (!sconn->backup) {
1017 /* Mark this router our primary router if we're still standalone */
1018 if (server->standalone) {
1019 server->id_entry->router = id_entry;
1020 server->router = id_entry;
1021 server->standalone = FALSE;
1023 /* If we are router then announce our possible servers. */
1024 if (server->server_type == SILC_ROUTER)
1025 silc_server_announce_servers(server, FALSE, 0,
1026 server->router->connection);
1028 /* Announce our clients and channels to the router */
1029 silc_server_announce_clients(server, 0, server->router->connection);
1030 silc_server_announce_channels(server, 0, server->router->connection);
1033 /* Add this server to be our backup router */
1034 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1035 sconn->backup_replace_port, FALSE);
1038 sock->protocol = NULL;
1040 /* Call the completion callback to indicate that we've connected to
1042 if (sconn->callback)
1043 (*sconn->callback)(server, id_entry, sconn->callback_context);
1046 /* Free the temporary connection data context */
1048 silc_server_config_unref(&sconn->conn);
1049 silc_free(sconn->remote_host);
1050 silc_free(sconn->backup_replace_ip);
1053 if (sconn == server->router_conn)
1054 server->router_conn = NULL;
1056 /* Free the protocol object */
1057 if (sock->protocol == protocol)
1058 sock->protocol = NULL;
1059 silc_protocol_free(protocol);
1061 silc_packet_context_free(ctx->packet);
1063 silc_ske_free(ctx->ske);
1064 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1065 silc_free(ctx->auth_data);
1069 /* Host lookup callback that is called after the incoming connection's
1070 IP and FQDN lookup is performed. This will actually check the acceptance
1071 of the incoming connection and will register the key exchange protocol
1072 for this connection. */
1075 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1078 SilcServer server = (SilcServer)context;
1079 SilcServerKEInternalContext *proto_ctx;
1080 SilcServerConfigClient *cconfig = NULL;
1081 SilcServerConfigServer *sconfig = NULL;
1082 SilcServerConfigRouter *rconfig = NULL;
1083 SilcServerConfigDeny *deny;
1086 SILC_LOG_DEBUG(("Start"));
1088 /* Check whether we could resolve both IP and FQDN. */
1089 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1090 server->config->require_reverse_lookup)) {
1091 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1092 sock->hostname ? sock->hostname :
1093 sock->ip ? sock->ip : ""));
1094 server->stat.conn_failures++;
1095 silc_server_disconnect_remote(server, sock,
1096 "Server closed connection: Unknown host");
1100 /* Register the connection for network input and output. This sets
1101 that scheduler will listen for incoming packets for this connection
1102 and sets that outgoing packets may be sent to this connection as well.
1103 However, this doesn't set the scheduler for outgoing traffic, it
1104 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1105 later when outgoing data is available. */
1106 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1108 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1111 port = server->sockets[server->sock]->port; /* Listenning port */
1113 /* Check whether this connection is denied to connect to us. */
1114 deny = silc_server_config_find_denied(server, sock->ip);
1116 deny = silc_server_config_find_denied(server, sock->hostname);
1118 /* The connection is denied */
1119 SILC_LOG_INFO(("Connection %s (%s) is denied",
1120 sock->hostname, sock->ip));
1121 silc_server_disconnect_remote(server, sock, deny->reason ?
1123 "Server closed connection: "
1124 "Connection refused");
1125 server->stat.conn_failures++;
1129 /* Check whether we have configured this sort of connection at all. We
1130 have to check all configurations since we don't know what type of
1131 connection this is. */
1132 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1133 cconfig = silc_server_config_find_client(server, sock->hostname);
1134 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1135 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1136 if (server->server_type == SILC_ROUTER) {
1137 if (!(rconfig = silc_server_config_find_router_conn(server,
1139 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1142 if (!cconfig && !sconfig && !rconfig) {
1143 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1145 silc_server_disconnect_remote(server, sock,
1146 "Server closed connection: "
1147 "Connection refused");
1148 server->stat.conn_failures++;
1152 /* The connection is allowed */
1154 /* Allocate internal context for key exchange protocol. This is
1155 sent as context for the protocol. */
1156 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1157 proto_ctx->server = context;
1158 proto_ctx->sock = sock;
1159 proto_ctx->rng = server->rng;
1160 proto_ctx->responder = TRUE;
1161 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1162 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1163 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1165 /* Take flags for key exchange. Since we do not know what type of connection
1166 this is, we go through all found configurations and use the global ones
1167 as well. This will result always into strictest key exchange flags. */
1168 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1169 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1170 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1171 if (server->config->param.key_exchange_pfs)
1172 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1174 /* Prepare the connection for key exchange protocol. We allocate the
1175 protocol but will not start it yet. The connector will be the
1176 initiator of the protocol thus we will wait for initiation from
1177 there before we start the protocol. */
1178 server->stat.auth_attempts++;
1179 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1180 &sock->protocol, proto_ctx,
1181 silc_server_accept_new_connection_second);
1183 /* Register a timeout task that will be executed if the connector
1184 will not start the key exchange protocol within specified timeout
1185 and the connection will be closed. */
1186 proto_ctx->timeout_task =
1187 silc_schedule_task_add(server->schedule, sock->sock,
1188 silc_server_timeout_remote,
1189 context, server->config->key_exchange_timeout, 0,
1194 /* Accepts new connections to the server. Accepting new connections are
1195 done in three parts to make it async. */
1197 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1199 SilcServer server = (SilcServer)context;
1200 SilcSocketConnection newsocket;
1203 SILC_LOG_DEBUG(("Accepting new connection"));
1205 server->stat.conn_attempts++;
1207 sock = silc_net_accept_connection(server->sock);
1209 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1210 server->stat.conn_failures++;
1214 /* Check for maximum allowed connections */
1215 if (sock > server->config->param.connections_max) {
1216 SILC_LOG_ERROR(("Refusing connection, server is full"));
1217 server->stat.conn_failures++;
1218 silc_net_close_connection(sock);
1222 /* Set socket options */
1223 silc_net_set_socket_nonblock(sock);
1224 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1226 /* We don't create a ID yet, since we don't know what type of connection
1227 this is yet. But, we do add the connection to the socket table. */
1228 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1229 server->sockets[sock] = newsocket;
1231 /* Perform asynchronous host lookup. This will lookup the IP and the
1232 FQDN of the remote connection. After the lookup is done the connection
1233 is accepted further. */
1234 silc_socket_host_lookup(newsocket, TRUE,
1235 silc_server_accept_new_connection_lookup, context,
1239 /* Second part of accepting new connection. Key exchange protocol has been
1240 performed and now it is time to do little connection authentication
1241 protocol to figure out whether this connection is client or server
1242 and whether it has right to access this server (especially server
1243 connections needs to be authenticated). */
1245 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1247 SilcProtocol protocol = (SilcProtocol)context;
1248 SilcServerKEInternalContext *ctx =
1249 (SilcServerKEInternalContext *)protocol->context;
1250 SilcServer server = (SilcServer)ctx->server;
1251 SilcSocketConnection sock = ctx->sock;
1252 SilcServerConnAuthInternalContext *proto_ctx;
1254 SILC_LOG_DEBUG(("Start"));
1256 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1257 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1258 /* Error occured during protocol */
1259 silc_protocol_free(protocol);
1260 sock->protocol = NULL;
1261 silc_ske_free_key_material(ctx->keymat);
1263 silc_packet_context_free(ctx->packet);
1265 silc_ske_free(ctx->ske);
1266 silc_free(ctx->dest_id);
1267 silc_server_config_unref(&ctx->cconfig);
1268 silc_server_config_unref(&ctx->sconfig);
1269 silc_server_config_unref(&ctx->rconfig);
1271 silc_schedule_task_del_by_callback(server->schedule,
1272 silc_server_failure_callback);
1273 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1274 "Key exchange failed");
1275 server->stat.auth_failures++;
1279 /* We now have the key material as the result of the key exchange
1280 protocol. Take the key material into use. Free the raw key material
1281 as soon as we've set them into use. */
1282 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1283 ctx->sock, ctx->keymat,
1284 ctx->ske->prop->cipher,
1285 ctx->ske->prop->pkcs,
1286 ctx->ske->prop->hash,
1287 ctx->ske->prop->hmac,
1288 ctx->ske->prop->group,
1290 silc_protocol_free(protocol);
1291 sock->protocol = NULL;
1292 silc_ske_free_key_material(ctx->keymat);
1294 silc_packet_context_free(ctx->packet);
1296 silc_ske_free(ctx->ske);
1297 silc_free(ctx->dest_id);
1298 silc_server_config_unref(&ctx->cconfig);
1299 silc_server_config_unref(&ctx->sconfig);
1300 silc_server_config_unref(&ctx->rconfig);
1302 silc_schedule_task_del_by_callback(server->schedule,
1303 silc_server_failure_callback);
1304 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1305 "Key exchange failed");
1306 server->stat.auth_failures++;
1309 silc_ske_free_key_material(ctx->keymat);
1311 /* Allocate internal context for the authentication protocol. This
1312 is sent as context for the protocol. */
1313 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1314 proto_ctx->server = (void *)server;
1315 proto_ctx->sock = sock;
1316 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1317 proto_ctx->responder = TRUE;
1318 proto_ctx->dest_id_type = ctx->dest_id_type;
1319 proto_ctx->dest_id = ctx->dest_id;
1320 proto_ctx->cconfig = ctx->cconfig;
1321 proto_ctx->sconfig = ctx->sconfig;
1322 proto_ctx->rconfig = ctx->rconfig;
1324 /* Free old protocol as it is finished now */
1325 silc_protocol_free(protocol);
1327 silc_packet_context_free(ctx->packet);
1329 sock->protocol = NULL;
1331 /* Allocate the authentication protocol. This is allocated here
1332 but we won't start it yet. We will be receiving party of this
1333 protocol thus we will wait that connecting party will make
1334 their first move. */
1335 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1336 &sock->protocol, proto_ctx,
1337 silc_server_accept_new_connection_final);
1339 /* Register timeout task. If the protocol is not executed inside
1340 this timelimit the connection will be terminated. */
1341 proto_ctx->timeout_task =
1342 silc_schedule_task_add(server->schedule, sock->sock,
1343 silc_server_timeout_remote,
1345 server->config->conn_auth_timeout, 0,
1350 /* Final part of accepting new connection. The connection has now
1351 been authenticated and keys has been exchanged. We also know whether
1352 this is client or server connection. */
1354 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1356 SilcProtocol protocol = (SilcProtocol)context;
1357 SilcServerConnAuthInternalContext *ctx =
1358 (SilcServerConnAuthInternalContext *)protocol->context;
1359 SilcServer server = (SilcServer)ctx->server;
1360 SilcSocketConnection sock = ctx->sock;
1361 SilcServerHBContext hb_context;
1362 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1364 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1366 SILC_LOG_DEBUG(("Start"));
1368 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1369 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1370 /* Error occured during protocol */
1371 silc_protocol_free(protocol);
1372 sock->protocol = NULL;
1374 silc_packet_context_free(ctx->packet);
1376 silc_ske_free(ctx->ske);
1377 silc_free(ctx->dest_id);
1378 silc_server_config_unref(&ctx->cconfig);
1379 silc_server_config_unref(&ctx->sconfig);
1380 silc_server_config_unref(&ctx->rconfig);
1382 silc_schedule_task_del_by_callback(server->schedule,
1383 silc_server_failure_callback);
1384 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1385 "Authentication failed");
1386 server->stat.auth_failures++;
1390 entry->data.last_receive = time(NULL);
1392 switch (ctx->conn_type) {
1393 case SILC_SOCKET_TYPE_CLIENT:
1395 SilcClientEntry client;
1396 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1398 /* Verify whether this connection is after all allowed to connect */
1399 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1400 &server->config->param,
1401 conn->param, ctx->ske)) {
1402 server->stat.auth_failures++;
1406 SILC_LOG_DEBUG(("Remote host is client"));
1407 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1410 /* Add the client to the client ID cache. The nickname and Client ID
1411 and other information is created after we have received NEW_CLIENT
1412 packet from client. */
1413 client = silc_idlist_add_client(server->local_list,
1414 NULL, NULL, NULL, NULL, NULL, sock, 0);
1416 SILC_LOG_ERROR(("Could not add new client to cache"));
1417 silc_free(sock->user_data);
1418 silc_server_disconnect_remote(server, sock,
1419 "Server closed connection: "
1420 "Authentication failed");
1421 server->stat.auth_failures++;
1426 server->stat.my_clients++;
1427 server->stat.clients++;
1428 if (server->server_type == SILC_ROUTER)
1429 server->stat.cell_clients++;
1431 /* Get connection parameters */
1433 if (conn->param->keepalive_secs)
1434 hearbeat_timeout = conn->param->keepalive_secs;
1437 id_entry = (void *)client;
1440 case SILC_SOCKET_TYPE_SERVER:
1441 case SILC_SOCKET_TYPE_ROUTER:
1443 SilcServerEntry new_server;
1444 bool initiator = FALSE;
1445 bool backup_local = FALSE;
1446 bool backup_router = FALSE;
1447 char *backup_replace_ip = NULL;
1448 SilcUInt16 backup_replace_port = 0;
1449 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1450 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1452 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1453 /* Verify whether this connection is after all allowed to connect */
1454 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1455 &server->config->param,
1456 rconn ? rconn->param : NULL,
1458 server->stat.auth_failures++;
1464 if (rconn->param->keepalive_secs)
1465 hearbeat_timeout = rconn->param->keepalive_secs;
1468 initiator = rconn->initiator;
1469 backup_local = rconn->backup_local;
1470 backup_router = rconn->backup_router;
1471 backup_replace_ip = rconn->backup_replace_ip;
1472 backup_replace_port = rconn->backup_replace_port;
1476 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1477 /* Verify whether this connection is after all allowed to connect */
1478 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1479 &server->config->param,
1480 sconn ? sconn->param : NULL,
1482 server->stat.auth_failures++;
1487 if (sconn->param->keepalive_secs)
1488 hearbeat_timeout = sconn->param->keepalive_secs;
1491 backup_router = sconn->backup_router;
1495 SILC_LOG_DEBUG(("Remote host is %s",
1496 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1497 "server" : (backup_router ?
1498 "backup router" : "router")));
1499 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1500 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1501 "server" : (backup_router ?
1502 "backup router" : "router")));
1504 /* Add the server into server cache. The server name and Server ID
1505 is updated after we have received NEW_SERVER packet from the
1506 server. We mark ourselves as router for this server if we really
1509 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1510 server->local_list : (backup_router ?
1511 server->local_list :
1512 server->global_list)),
1514 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1515 SILC_SERVER : SILC_ROUTER),
1517 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1518 server->id_entry : (backup_router ?
1519 server->id_entry : NULL)),
1522 SILC_LOG_ERROR(("Could not add new server to cache"));
1523 silc_free(sock->user_data);
1524 silc_server_disconnect_remote(server, sock,
1525 "Server closed connection: "
1526 "Authentication failed");
1527 server->stat.auth_failures++;
1532 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1533 server->stat.my_servers++;
1535 server->stat.my_routers++;
1536 server->stat.servers++;
1538 id_entry = (void *)new_server;
1540 /* If the incoming connection is router and marked as backup router
1541 then add it to be one of our backups */
1542 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1543 silc_server_backup_add(server, new_server, backup_replace_ip,
1544 backup_replace_port, backup_local);
1546 /* Change it back to SERVER type since that's what it really is. */
1548 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1550 new_server->server_type = SILC_BACKUP_ROUTER;
1553 /* Check whether this connection is to be our primary router connection
1554 if we do not already have the primary route. */
1555 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1556 if (silc_server_config_is_primary_route(server) && !initiator)
1559 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1560 server->standalone = FALSE;
1561 if (!server->id_entry->router) {
1562 server->id_entry->router = id_entry;
1563 server->router = id_entry;
1574 sock->type = ctx->conn_type;
1576 /* Add the common data structure to the ID entry. */
1577 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1579 /* Add to sockets internal pointer for fast referencing */
1580 silc_free(sock->user_data);
1581 sock->user_data = id_entry;
1583 /* Connection has been fully established now. Everything is ok. */
1584 SILC_LOG_DEBUG(("New connection authenticated"));
1586 /* Perform keepalive. The `hb_context' will be freed automatically
1587 when finally calling the silc_socket_free function. */
1588 hb_context = silc_calloc(1, sizeof(*hb_context));
1589 hb_context->server = server;
1590 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1591 silc_server_perform_heartbeat,
1595 silc_schedule_task_del_by_callback(server->schedule,
1596 silc_server_failure_callback);
1597 silc_protocol_free(protocol);
1599 silc_packet_context_free(ctx->packet);
1601 silc_ske_free(ctx->ske);
1602 silc_free(ctx->dest_id);
1603 silc_server_config_unref(&ctx->cconfig);
1604 silc_server_config_unref(&ctx->sconfig);
1605 silc_server_config_unref(&ctx->rconfig);
1607 sock->protocol = NULL;
1610 /* This function is used to read packets from network and send packets to
1611 network. This is usually a generic task. */
1613 SILC_TASK_CALLBACK(silc_server_packet_process)
1615 SilcServer server = (SilcServer)context;
1616 SilcSocketConnection sock = server->sockets[fd];
1617 SilcIDListData idata;
1618 SilcCipher cipher = NULL;
1619 SilcHmac hmac = NULL;
1620 SilcUInt32 sequence = 0;
1626 SILC_LOG_DEBUG(("Processing packet"));
1628 /* Packet sending */
1630 if (type == SILC_TASK_WRITE) {
1631 /* Do not send data to disconnected connection */
1632 if (SILC_IS_DISCONNECTED(sock))
1635 server->stat.packets_sent++;
1637 /* Send the packet */
1638 ret = silc_packet_send(sock, TRUE);
1640 /* If returned -2 could not write to connection now, will do
1646 SILC_LOG_ERROR(("Error sending packet to connection "
1647 "%s:%d [%s]", sock->hostname, sock->port,
1648 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1649 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1650 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1655 /* The packet has been sent and now it is time to set the connection
1656 back to only for input. When there is again some outgoing data
1657 available for this connection it will be set for output as well.
1658 This call clears the output setting and sets it only for input. */
1659 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1660 SILC_UNSET_OUTBUF_PENDING(sock);
1662 silc_buffer_clear(sock->outbuf);
1666 /* Packet receiving */
1668 /* Read some data from connection */
1669 ret = silc_packet_receive(sock);
1673 SILC_LOG_ERROR(("Error receiving packet from connection "
1674 "%s:%d [%s] %s", sock->hostname, sock->port,
1675 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1676 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1677 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1678 "Router"), strerror(errno)));
1684 SILC_LOG_DEBUG(("Read EOF"));
1686 /* If connection is disconnecting already we will finally
1687 close the connection */
1688 if (SILC_IS_DISCONNECTING(sock)) {
1689 if (sock->user_data)
1690 silc_server_free_sock_user_data(server, sock, NULL);
1691 silc_server_close_connection(server, sock);
1695 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1696 SILC_SET_DISCONNECTING(sock);
1698 if (sock->user_data) {
1700 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1701 silc_server_free_sock_user_data(server, sock, tmp);
1703 silc_server_free_sock_user_data(server, sock, NULL);
1704 } else if (server->router_conn && server->router_conn->sock == sock &&
1705 !server->router && server->standalone)
1706 silc_schedule_task_add(server->schedule, 0,
1707 silc_server_connect_to_router,
1710 SILC_TASK_PRI_NORMAL);
1712 silc_server_close_connection(server, sock);
1716 /* If connection is disconnecting or disconnected we will ignore
1718 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1719 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1723 server->stat.packets_received++;
1725 /* Get keys and stuff from ID entry */
1726 idata = (SilcIDListData)sock->user_data;
1728 cipher = idata->receive_key;
1729 hmac = idata->hmac_receive;
1730 sequence = idata->psn_receive;
1733 /* Process the packet. This will call the parser that will then
1734 decrypt and parse the packet. */
1735 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1736 TRUE : FALSE, cipher, hmac, sequence,
1737 silc_server_packet_parse, server);
1739 /* If this socket connection is not authenticated yet and the packet
1740 processing failed we will drop the connection since it can be
1741 a malicious flooder. */
1742 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1743 (!sock->protocol || sock->protocol->protocol->type ==
1744 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1745 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1746 SILC_SET_DISCONNECTING(sock);
1748 if (sock->user_data)
1749 silc_server_free_sock_user_data(server, sock, NULL);
1750 silc_server_close_connection(server, sock);
1754 /* Parses whole packet, received earlier. */
1756 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1758 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1759 SilcServer server = (SilcServer)parse_ctx->context;
1760 SilcSocketConnection sock = parse_ctx->sock;
1761 SilcPacketContext *packet = parse_ctx->packet;
1762 SilcIDListData idata = (SilcIDListData)sock->user_data;
1765 SILC_LOG_DEBUG(("Start"));
1767 /* Parse the packet */
1768 if (parse_ctx->normal)
1769 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1771 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1773 /* If entry is disabled ignore what we got. */
1774 if (ret != SILC_PACKET_RESUME_ROUTER &&
1775 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1776 SILC_LOG_DEBUG(("Connection is disabled"));
1780 if (ret == SILC_PACKET_NONE)
1783 /* Check that the the current client ID is same as in the client's packet. */
1784 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1785 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1786 if (client && client->id) {
1787 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1788 packet->src_id_type);
1789 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1797 if (server->server_type == SILC_ROUTER) {
1798 /* Route the packet if it is not destined to us. Other ID types but
1799 server are handled separately after processing them. */
1800 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1801 packet->dst_id_type == SILC_ID_SERVER &&
1802 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1803 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1805 /* Route the packet to fastest route for the destination ID */
1806 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1807 packet->dst_id_type);
1810 silc_server_packet_route(server,
1811 silc_server_route_get(server, id,
1812 packet->dst_id_type),
1819 /* Parse the incoming packet type */
1820 silc_server_packet_parse_type(server, sock, packet);
1822 if (server->server_type == SILC_ROUTER) {
1823 /* Broadcast packet if it is marked as broadcast packet and it is
1824 originated from router and we are router. */
1825 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1826 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1827 !server->standalone) {
1828 /* Broadcast to our primary route */
1829 silc_server_packet_broadcast(server, server->router->connection, packet);
1831 /* If we have backup routers then we need to feed all broadcast
1832 data to those servers. */
1833 silc_server_backup_broadcast(server, sock, packet);
1838 silc_packet_context_free(packet);
1839 silc_free(parse_ctx);
1842 /* Parser callback called by silc_packet_receive_process. This merely
1843 registers timeout that will handle the actual parsing when appropriate. */
1845 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1848 SilcServer server = (SilcServer)context;
1849 SilcSocketConnection sock = parser_context->sock;
1850 SilcIDListData idata = (SilcIDListData)sock->user_data;
1853 idata->psn_receive = parser_context->packet->sequence + 1;
1855 /* If protocol for this connection is key exchange or rekey then we'll
1856 process all packets synchronously, since there might be packets in
1857 queue that we are not able to decrypt without first processing the
1858 packets before them. */
1859 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1860 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1861 (sock->protocol && sock->protocol->protocol &&
1862 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1863 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1864 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1867 /* Reprocess data since we'll return FALSE here. This is because
1868 the idata->receive_key might have become valid in the last packet
1869 and we want to call this processor with valid cipher. */
1871 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1872 TRUE : FALSE, idata->receive_key,
1873 idata->hmac_receive, idata->psn_receive,
1874 silc_server_packet_parse, server);
1876 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1877 TRUE : FALSE, NULL, NULL, 0,
1878 silc_server_packet_parse, server);
1882 switch (sock->type) {
1883 case SILC_SOCKET_TYPE_UNKNOWN:
1884 case SILC_SOCKET_TYPE_CLIENT:
1885 /* Parse the packet with timeout */
1886 silc_schedule_task_add(server->schedule, sock->sock,
1887 silc_server_packet_parse_real,
1888 (void *)parser_context, 0, 100000,
1890 SILC_TASK_PRI_NORMAL);
1892 case SILC_SOCKET_TYPE_SERVER:
1893 case SILC_SOCKET_TYPE_ROUTER:
1894 /* Packets from servers are parsed immediately */
1895 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1905 /* Parses the packet type and calls what ever routines the packet type
1906 requires. This is done for all incoming packets. */
1908 void silc_server_packet_parse_type(SilcServer server,
1909 SilcSocketConnection sock,
1910 SilcPacketContext *packet)
1912 SilcPacketType type = packet->type;
1913 SilcIDListData idata = (SilcIDListData)sock->user_data;
1915 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1917 /* Parse the packet type */
1919 case SILC_PACKET_DISCONNECT:
1920 SILC_LOG_DEBUG(("Disconnect packet"));
1921 if (packet->flags & SILC_PACKET_FLAG_LIST)
1923 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1924 /* Duplicate to null terminate the string. */
1925 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1926 SILC_LOG_ERROR(("%s", message));
1931 case SILC_PACKET_SUCCESS:
1933 * Success received for something. For now we can have only
1934 * one protocol for connection executing at once hence this
1935 * success message is for whatever protocol is executing currently.
1937 SILC_LOG_DEBUG(("Success packet"));
1938 if (packet->flags & SILC_PACKET_FLAG_LIST)
1941 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1944 case SILC_PACKET_FAILURE:
1946 * Failure received for something. For now we can have only
1947 * one protocol for connection executing at once hence this
1948 * failure message is for whatever protocol is executing currently.
1950 SILC_LOG_DEBUG(("Failure packet"));
1951 if (packet->flags & SILC_PACKET_FLAG_LIST)
1953 if (sock->protocol) {
1954 SilcServerFailureContext f;
1955 f = silc_calloc(1, sizeof(*f));
1959 /* We will wait 5 seconds to process this failure packet */
1960 silc_schedule_task_add(server->schedule, sock->sock,
1961 silc_server_failure_callback, (void *)f, 5, 0,
1962 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1966 case SILC_PACKET_REJECT:
1967 SILC_LOG_DEBUG(("Reject packet"));
1968 if (packet->flags & SILC_PACKET_FLAG_LIST)
1973 case SILC_PACKET_NOTIFY:
1975 * Received notify packet. Server can receive notify packets from
1976 * router. Server then relays the notify messages to clients if needed.
1978 SILC_LOG_DEBUG(("Notify packet"));
1979 if (packet->flags & SILC_PACKET_FLAG_LIST)
1980 silc_server_notify_list(server, sock, packet);
1982 silc_server_notify(server, sock, packet);
1988 case SILC_PACKET_CHANNEL_MESSAGE:
1990 * Received channel message. Channel messages are special packets
1991 * (although probably most common ones) thus they are handled
1994 SILC_LOG_DEBUG(("Channel Message packet"));
1995 if (packet->flags & SILC_PACKET_FLAG_LIST)
1997 idata->last_receive = time(NULL);
1998 silc_server_channel_message(server, sock, packet);
2001 case SILC_PACKET_CHANNEL_KEY:
2003 * Received key for channel. As channels are created by the router
2004 * the keys are as well. We will distribute the key to all of our
2005 * locally connected clients on the particular channel. Router
2006 * never receives this channel and thus is ignored.
2008 SILC_LOG_DEBUG(("Channel Key packet"));
2009 if (packet->flags & SILC_PACKET_FLAG_LIST)
2011 silc_server_channel_key(server, sock, packet);
2017 case SILC_PACKET_COMMAND:
2019 * Recived command. Processes the command request and allocates the
2020 * command context and calls the command.
2022 SILC_LOG_DEBUG(("Command packet"));
2023 if (packet->flags & SILC_PACKET_FLAG_LIST)
2025 silc_server_command_process(server, sock, packet);
2028 case SILC_PACKET_COMMAND_REPLY:
2030 * Received command reply packet. Received command reply to command. It
2031 * may be reply to command sent by us or reply to command sent by client
2032 * that we've routed further.
2034 SILC_LOG_DEBUG(("Command Reply packet"));
2035 if (packet->flags & SILC_PACKET_FLAG_LIST)
2037 silc_server_command_reply(server, sock, packet);
2041 * Private Message packets
2043 case SILC_PACKET_PRIVATE_MESSAGE:
2045 * Received private message packet. The packet is coming from either
2048 SILC_LOG_DEBUG(("Private Message packet"));
2049 if (packet->flags & SILC_PACKET_FLAG_LIST)
2051 idata->last_receive = time(NULL);
2052 silc_server_private_message(server, sock, packet);
2055 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2057 * Private message key packet.
2059 if (packet->flags & SILC_PACKET_FLAG_LIST)
2061 silc_server_private_message_key(server, sock, packet);
2065 * Key Exchange protocol packets
2067 case SILC_PACKET_KEY_EXCHANGE:
2068 SILC_LOG_DEBUG(("KE packet"));
2069 if (packet->flags & SILC_PACKET_FLAG_LIST)
2072 if (sock->protocol && sock->protocol->protocol &&
2073 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2074 SilcServerKEInternalContext *proto_ctx =
2075 (SilcServerKEInternalContext *)sock->protocol->context;
2077 proto_ctx->packet = silc_packet_context_dup(packet);
2079 /* Let the protocol handle the packet */
2080 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2082 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2083 "protocol active, packet dropped."));
2087 case SILC_PACKET_KEY_EXCHANGE_1:
2088 SILC_LOG_DEBUG(("KE 1 packet"));
2089 if (packet->flags & SILC_PACKET_FLAG_LIST)
2092 if (sock->protocol && sock->protocol->protocol &&
2093 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2094 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2096 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2097 SilcServerRekeyInternalContext *proto_ctx =
2098 (SilcServerRekeyInternalContext *)sock->protocol->context;
2100 if (proto_ctx->packet)
2101 silc_packet_context_free(proto_ctx->packet);
2103 proto_ctx->packet = silc_packet_context_dup(packet);
2105 /* Let the protocol handle the packet */
2106 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2108 SilcServerKEInternalContext *proto_ctx =
2109 (SilcServerKEInternalContext *)sock->protocol->context;
2111 if (proto_ctx->packet)
2112 silc_packet_context_free(proto_ctx->packet);
2114 proto_ctx->packet = silc_packet_context_dup(packet);
2115 proto_ctx->dest_id_type = packet->src_id_type;
2116 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2117 packet->src_id_type);
2118 if (!proto_ctx->dest_id)
2121 /* Let the protocol handle the packet */
2122 silc_protocol_execute(sock->protocol, server->schedule,
2126 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2127 "protocol active, packet dropped."));
2131 case SILC_PACKET_KEY_EXCHANGE_2:
2132 SILC_LOG_DEBUG(("KE 2 packet"));
2133 if (packet->flags & SILC_PACKET_FLAG_LIST)
2136 if (sock->protocol && sock->protocol->protocol &&
2137 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2138 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2140 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2141 SilcServerRekeyInternalContext *proto_ctx =
2142 (SilcServerRekeyInternalContext *)sock->protocol->context;
2144 if (proto_ctx->packet)
2145 silc_packet_context_free(proto_ctx->packet);
2147 proto_ctx->packet = silc_packet_context_dup(packet);
2149 /* Let the protocol handle the packet */
2150 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2152 SilcServerKEInternalContext *proto_ctx =
2153 (SilcServerKEInternalContext *)sock->protocol->context;
2155 if (proto_ctx->packet)
2156 silc_packet_context_free(proto_ctx->packet);
2158 proto_ctx->packet = silc_packet_context_dup(packet);
2159 proto_ctx->dest_id_type = packet->src_id_type;
2160 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2161 packet->src_id_type);
2162 if (!proto_ctx->dest_id)
2165 /* Let the protocol handle the packet */
2166 silc_protocol_execute(sock->protocol, server->schedule,
2170 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2171 "protocol active, packet dropped."));
2175 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2177 * Connection authentication request packet. When we receive this packet
2178 * we will send to the other end information about our mandatory
2179 * authentication method for the connection. This packet maybe received
2182 SILC_LOG_DEBUG(("Connection authentication request packet"));
2183 if (packet->flags & SILC_PACKET_FLAG_LIST)
2185 silc_server_connection_auth_request(server, sock, packet);
2189 * Connection Authentication protocol packets
2191 case SILC_PACKET_CONNECTION_AUTH:
2192 /* Start of the authentication protocol. We receive here the
2193 authentication data and will verify it. */
2194 SILC_LOG_DEBUG(("Connection auth packet"));
2195 if (packet->flags & SILC_PACKET_FLAG_LIST)
2198 if (sock->protocol && sock->protocol->protocol->type
2199 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2201 SilcServerConnAuthInternalContext *proto_ctx =
2202 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2204 proto_ctx->packet = silc_packet_context_dup(packet);
2206 /* Let the protocol handle the packet */
2207 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2209 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2210 "protocol active, packet dropped."));
2214 case SILC_PACKET_NEW_ID:
2216 * Received New ID packet. This includes some new ID that has been
2217 * created. It may be for client, server or channel. This is the way
2218 * to distribute information about new registered entities in the
2221 SILC_LOG_DEBUG(("New ID packet"));
2222 if (packet->flags & SILC_PACKET_FLAG_LIST)
2223 silc_server_new_id_list(server, sock, packet);
2225 silc_server_new_id(server, sock, packet);
2228 case SILC_PACKET_NEW_CLIENT:
2230 * Received new client packet. This includes client information that
2231 * we will use to create initial client ID. After creating new
2232 * ID we will send it to the client.
2234 SILC_LOG_DEBUG(("New Client packet"));
2235 if (packet->flags & SILC_PACKET_FLAG_LIST)
2237 silc_server_new_client(server, sock, packet);
2240 case SILC_PACKET_NEW_SERVER:
2242 * Received new server packet. This includes Server ID and some other
2243 * information that we may save. This is received after server has
2246 SILC_LOG_DEBUG(("New Server packet"));
2247 if (packet->flags & SILC_PACKET_FLAG_LIST)
2249 silc_server_new_server(server, sock, packet);
2252 case SILC_PACKET_NEW_CHANNEL:
2254 * Received new channel packet. Information about new channel in the
2255 * network are distributed using this packet.
2257 SILC_LOG_DEBUG(("New Channel packet"));
2258 if (packet->flags & SILC_PACKET_FLAG_LIST)
2259 silc_server_new_channel_list(server, sock, packet);
2261 silc_server_new_channel(server, sock, packet);
2264 case SILC_PACKET_HEARTBEAT:
2266 * Received heartbeat.
2268 SILC_LOG_DEBUG(("Heartbeat packet"));
2269 if (packet->flags & SILC_PACKET_FLAG_LIST)
2273 case SILC_PACKET_KEY_AGREEMENT:
2275 * Received heartbeat.
2277 SILC_LOG_DEBUG(("Key agreement packet"));
2278 if (packet->flags & SILC_PACKET_FLAG_LIST)
2280 silc_server_key_agreement(server, sock, packet);
2283 case SILC_PACKET_REKEY:
2285 * Received re-key packet. The sender wants to regenerate the session
2288 SILC_LOG_DEBUG(("Re-key packet"));
2289 if (packet->flags & SILC_PACKET_FLAG_LIST)
2291 silc_server_rekey(server, sock, packet);
2294 case SILC_PACKET_REKEY_DONE:
2296 * The re-key is done.
2298 SILC_LOG_DEBUG(("Re-key done packet"));
2299 if (packet->flags & SILC_PACKET_FLAG_LIST)
2302 if (sock->protocol && sock->protocol->protocol &&
2303 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2305 SilcServerRekeyInternalContext *proto_ctx =
2306 (SilcServerRekeyInternalContext *)sock->protocol->context;
2308 if (proto_ctx->packet)
2309 silc_packet_context_free(proto_ctx->packet);
2311 proto_ctx->packet = silc_packet_context_dup(packet);
2313 /* Let the protocol handle the packet */
2314 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2316 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2317 "protocol active, packet dropped."));
2321 case SILC_PACKET_FTP:
2323 SILC_LOG_DEBUG(("FTP packet"));
2324 if (packet->flags & SILC_PACKET_FLAG_LIST)
2326 silc_server_ftp(server, sock, packet);
2329 case SILC_PACKET_RESUME_ROUTER:
2330 /* Resume router packet received. This packet is received for backup
2331 router resuming protocol. */
2332 SILC_LOG_DEBUG(("Resume router packet"));
2333 if (packet->flags & SILC_PACKET_FLAG_LIST)
2335 silc_server_backup_resume_router(server, sock, packet);
2339 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2345 /* Creates connection to a remote router. */
2347 void silc_server_create_connection(SilcServer server,
2348 const char *remote_host, SilcUInt32 port)
2350 SilcServerConnection sconn;
2352 /* Allocate connection object for hold connection specific stuff. */
2353 sconn = silc_calloc(1, sizeof(*sconn));
2354 sconn->server = server;
2355 sconn->remote_host = strdup(remote_host);
2356 sconn->remote_port = port;
2357 sconn->no_reconnect = TRUE;
2359 silc_schedule_task_add(server->schedule, 0,
2360 silc_server_connect_router,
2361 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2362 SILC_TASK_PRI_NORMAL);
2365 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2367 silc_socket_free((SilcSocketConnection)context);
2370 /* Closes connection to socket connection */
2372 void silc_server_close_connection(SilcServer server,
2373 SilcSocketConnection sock)
2375 if (!server->sockets[sock->sock])
2378 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2380 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2381 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2382 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2385 /* We won't listen for this connection anymore */
2386 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2388 /* Unregister all tasks */
2389 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2391 /* Close the actual connection */
2392 silc_net_close_connection(sock->sock);
2393 server->sockets[sock->sock] = NULL;
2395 /* If sock->user_data is NULL then we'll check for active protocols
2396 here since the silc_server_free_sock_user_data has not been called
2397 for this connection. */
2398 if (!sock->user_data) {
2399 /* If any protocol is active cancel its execution. It will call
2400 the final callback which will finalize the disconnection. */
2401 if (sock->protocol) {
2402 silc_protocol_cancel(sock->protocol, server->schedule);
2403 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2404 silc_protocol_execute_final(sock->protocol, server->schedule);
2405 sock->protocol = NULL;
2410 silc_schedule_task_add(server->schedule, 0,
2411 silc_server_close_connection_final,
2412 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2413 SILC_TASK_PRI_NORMAL);
2416 /* Sends disconnect message to remote connection and disconnects the
2419 void silc_server_disconnect_remote(SilcServer server,
2420 SilcSocketConnection sock,
2421 const char *fmt, ...)
2424 unsigned char buf[4096];
2429 memset(buf, 0, sizeof(buf));
2431 vsprintf(buf, fmt, ap);
2434 SILC_LOG_DEBUG(("Disconnecting remote host"));
2436 /* Notify remote end that the conversation is over. The notify message
2437 is tried to be sent immediately. */
2438 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2439 buf, strlen(buf), TRUE);
2440 silc_server_packet_queue_purge(server, sock);
2442 /* Mark the connection to be disconnected */
2443 SILC_SET_DISCONNECTED(sock);
2444 silc_server_close_connection(server, sock);
2449 SilcClientEntry client;
2450 } *FreeClientInternal;
2452 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2454 FreeClientInternal i = (FreeClientInternal)context;
2456 silc_idlist_del_data(i->client);
2457 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2461 /* Frees client data and notifies about client's signoff. */
2463 void silc_server_free_client_data(SilcServer server,
2464 SilcSocketConnection sock,
2465 SilcClientEntry client,
2467 const char *signoff)
2469 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2471 /* If there is pending outgoing data for the client then purge it
2472 to the network before removing the client entry. */
2473 silc_server_packet_queue_purge(server, sock);
2478 /* Send SIGNOFF notify to routers. */
2479 if (notify && !server->standalone && server->router)
2480 silc_server_send_notify_signoff(server, server->router->connection,
2481 server->server_type == SILC_SERVER ?
2482 FALSE : TRUE, client->id, signoff);
2484 /* Remove client from all channels */
2486 silc_server_remove_from_channels(server, NULL, client,
2487 TRUE, (char *)signoff, TRUE);
2489 silc_server_remove_from_channels(server, NULL, client,
2490 FALSE, NULL, FALSE);
2492 /* Update statistics */
2493 server->stat.my_clients--;
2494 server->stat.clients--;
2495 if (server->server_type == SILC_ROUTER)
2496 server->stat.cell_clients--;
2497 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2498 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2500 /* We will not delete the client entry right away. We will take it
2501 into history (for WHOWAS command) for 5 minutes */
2504 silc_schedule_task_add(server->schedule, 0,
2505 silc_server_free_client_data_timeout,
2507 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2508 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2509 client->router = NULL;
2510 client->connection = NULL;
2514 /* Frees user_data pointer from socket connection object. This also sends
2515 appropriate notify packets to the network to inform about leaving
2518 void silc_server_free_sock_user_data(SilcServer server,
2519 SilcSocketConnection sock,
2520 const char *signoff_message)
2522 SILC_LOG_DEBUG(("Start"));
2524 switch (sock->type) {
2525 case SILC_SOCKET_TYPE_CLIENT:
2527 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2528 silc_server_free_client_data(server, sock, user_data, TRUE,
2532 case SILC_SOCKET_TYPE_SERVER:
2533 case SILC_SOCKET_TYPE_ROUTER:
2535 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2536 SilcServerEntry backup_router = NULL;
2539 backup_router = silc_server_backup_get(server, user_data->id);
2541 /* If this was our primary router connection then we're lost to
2542 the outside world. */
2543 if (server->router == user_data) {
2544 /* Check whether we have a backup router connection */
2545 if (!backup_router || backup_router == user_data) {
2546 silc_schedule_task_add(server->schedule, 0,
2547 silc_server_connect_to_router,
2550 SILC_TASK_PRI_NORMAL);
2552 server->id_entry->router = NULL;
2553 server->router = NULL;
2554 server->standalone = TRUE;
2555 backup_router = NULL;
2557 SILC_LOG_INFO(("New primary router is backup router %s",
2558 backup_router->server_name));
2559 SILC_LOG_DEBUG(("New primary router is backup router %s",
2560 backup_router->server_name));
2561 server->id_entry->router = backup_router;
2562 server->router = backup_router;
2563 server->router_connect = time(0);
2564 server->backup_primary = TRUE;
2565 if (server->server_type == SILC_BACKUP_ROUTER) {
2566 server->server_type = SILC_ROUTER;
2568 /* We'll need to constantly try to reconnect to the primary
2569 router so that we'll see when it comes back online. */
2570 silc_server_backup_reconnect(server, sock->ip, sock->port,
2571 silc_server_backup_connected,
2575 /* Mark this connection as replaced */
2576 silc_server_backup_replaced_add(server, user_data->id,
2579 } else if (backup_router) {
2580 SILC_LOG_INFO(("Enabling the use of backup router %s",
2581 backup_router->server_name));
2582 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2583 backup_router->server_name));
2585 /* Mark this connection as replaced */
2586 silc_server_backup_replaced_add(server, user_data->id,
2590 if (!backup_router) {
2591 /* Free all client entries that this server owns as they will
2592 become invalid now as well. */
2594 silc_server_remove_clients_by_server(server, user_data, TRUE);
2595 if (server->server_type == SILC_SERVER)
2596 silc_server_remove_channels_by_server(server, user_data);
2598 /* Update the client entries of this server to the new backup
2599 router. This also removes the clients that *really* was owned
2600 by the primary router and went down with the router. */
2601 silc_server_update_clients_by_server(server, user_data, backup_router,
2603 silc_server_update_servers_by_server(server, user_data, backup_router);
2604 if (server->server_type == SILC_SERVER)
2605 silc_server_update_channels_by_server(server, user_data,
2609 /* Free the server entry */
2610 silc_server_backup_del(server, user_data);
2611 silc_server_backup_replaced_del(server, user_data);
2612 silc_idlist_del_data(user_data);
2613 if (!silc_idlist_del_server(server->local_list, user_data))
2614 silc_idlist_del_server(server->global_list, user_data);
2615 server->stat.my_servers--;
2616 server->stat.servers--;
2617 if (server->server_type == SILC_ROUTER)
2618 server->stat.cell_servers--;
2620 if (backup_router) {
2621 /* Announce all of our stuff that was created about 5 minutes ago.
2622 The backup router knows all the other stuff already. */
2623 if (server->server_type == SILC_ROUTER)
2624 silc_server_announce_servers(server, FALSE, time(0) - 300,
2625 backup_router->connection);
2627 /* Announce our clients and channels to the router */
2628 silc_server_announce_clients(server, time(0) - 300,
2629 backup_router->connection);
2630 silc_server_announce_channels(server, time(0) - 300,
2631 backup_router->connection);
2637 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2639 silc_idlist_del_data(user_data);
2640 silc_free(user_data);
2645 /* If any protocol is active cancel its execution */
2646 if (sock->protocol) {
2647 silc_protocol_cancel(sock->protocol, server->schedule);
2648 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2649 silc_protocol_execute_final(sock->protocol, server->schedule);
2650 sock->protocol = NULL;
2653 sock->user_data = NULL;
2656 /* Removes client from all channels it has joined. This is used when client
2657 connection is disconnected. If the client on a channel is last, the
2658 channel is removed as well. This sends the SIGNOFF notify types. */
2660 void silc_server_remove_from_channels(SilcServer server,
2661 SilcSocketConnection sock,
2662 SilcClientEntry client,
2664 char *signoff_message,
2667 SilcChannelEntry channel;
2668 SilcChannelClientEntry chl;
2669 SilcHashTableList htl;
2672 SILC_LOG_DEBUG(("Start"));
2674 if (!client || !client->id)
2677 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2679 /* Remove the client from all channels. The client is removed from
2680 the channels' user list. */
2681 silc_hash_table_list(client->channels, &htl);
2682 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2683 channel = chl->channel;
2685 /* Remove channel from client's channel list */
2686 silc_hash_table_del(client->channels, channel);
2688 /* Remove channel if there is no users anymore */
2689 if (server->server_type == SILC_ROUTER &&
2690 silc_hash_table_count(channel->user_list) < 2) {
2692 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2693 if (silc_idlist_del_channel(server->local_list, channel))
2694 server->stat.my_channels--;
2696 silc_idlist_del_channel(server->global_list, channel);
2700 /* Remove client from channel's client list */
2701 silc_hash_table_del(channel->user_list, chl->client);
2702 channel->user_count--;
2704 /* If there is no global users on the channel anymore mark the channel
2705 as local channel. Do not check if the removed client is local client. */
2706 if (server->server_type != SILC_ROUTER && channel->global_users &&
2707 chl->client->router && !silc_server_channel_has_global(channel))
2708 channel->global_users = FALSE;
2711 server->stat.my_chanclients--;
2713 /* If there is not at least one local user on the channel then we don't
2714 need the channel entry anymore, we can remove it safely. */
2715 if (server->server_type != SILC_ROUTER &&
2716 !silc_server_channel_has_local(channel)) {
2717 /* Notify about leaving client if this channel has global users. */
2718 if (notify && channel->global_users)
2719 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2720 SILC_NOTIFY_TYPE_SIGNOFF,
2721 signoff_message ? 2 : 1,
2722 clidp->data, clidp->len,
2723 signoff_message, signoff_message ?
2724 strlen(signoff_message) : 0);
2727 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2729 if (channel->founder_key) {
2730 /* The founder auth data exists, do not remove the channel entry */
2731 SilcChannelClientEntry chl2;
2732 SilcHashTableList htl2;
2734 channel->disabled = TRUE;
2736 silc_hash_table_list(channel->user_list, &htl2);
2737 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2738 silc_hash_table_del(chl2->client->channels, channel);
2739 silc_hash_table_del(channel->user_list, chl2->client);
2740 channel->user_count--;
2743 silc_hash_table_list_reset(&htl2);
2747 /* Remove the channel entry */
2748 if (silc_idlist_del_channel(server->local_list, channel))
2749 server->stat.my_channels--;
2751 silc_idlist_del_channel(server->global_list, channel);
2755 /* Send notify to channel about client leaving SILC and thus
2756 the entire channel. */
2758 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2759 SILC_NOTIFY_TYPE_SIGNOFF,
2760 signoff_message ? 2 : 1,
2761 clidp->data, clidp->len,
2762 signoff_message, signoff_message ?
2763 strlen(signoff_message) : 0);
2765 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2766 /* Re-generate channel key */
2767 if (!silc_server_create_channel_key(server, channel, 0))
2770 /* Send the channel key to the channel. The key of course is not sent
2771 to the client who was removed from the channel. */
2772 silc_server_send_channel_key(server, client->connection, channel,
2773 server->server_type == SILC_ROUTER ?
2774 FALSE : !server->standalone);
2779 silc_hash_table_list_reset(&htl);
2780 silc_buffer_free(clidp);
2783 /* Removes client from one channel. This is used for example when client
2784 calls LEAVE command to remove itself from the channel. Returns TRUE
2785 if channel still exists and FALSE if the channel is removed when
2786 last client leaves the channel. If `notify' is FALSE notify messages
2789 int silc_server_remove_from_one_channel(SilcServer server,
2790 SilcSocketConnection sock,
2791 SilcChannelEntry channel,
2792 SilcClientEntry client,
2795 SilcChannelClientEntry chl;
2798 SILC_LOG_DEBUG(("Start"));
2800 /* Get the entry to the channel, if this client is not on the channel
2802 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2805 /* Remove the client from the channel. The client is removed from
2806 the channel's user list. */
2808 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2810 /* Remove channel from client's channel list */
2811 silc_hash_table_del(client->channels, chl->channel);
2813 /* Remove channel if there is no users anymore */
2814 if (server->server_type == SILC_ROUTER &&
2815 silc_hash_table_count(channel->user_list) < 2) {
2817 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2818 if (silc_idlist_del_channel(server->local_list, channel))
2819 server->stat.my_channels--;
2821 silc_idlist_del_channel(server->global_list, channel);
2822 silc_buffer_free(clidp);
2826 /* Remove client from channel's client list */
2827 silc_hash_table_del(channel->user_list, chl->client);
2828 channel->user_count--;
2830 /* If there is no global users on the channel anymore mark the channel
2831 as local channel. Do not check if the client is local client. */
2832 if (server->server_type != SILC_ROUTER && channel->global_users &&
2833 chl->client->router && !silc_server_channel_has_global(channel))
2834 channel->global_users = FALSE;
2837 server->stat.my_chanclients--;
2839 /* If there is not at least one local user on the channel then we don't
2840 need the channel entry anymore, we can remove it safely. */
2841 if (server->server_type != SILC_ROUTER &&
2842 !silc_server_channel_has_local(channel)) {
2843 /* Notify about leaving client if this channel has global users. */
2844 if (notify && channel->global_users)
2845 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2846 SILC_NOTIFY_TYPE_LEAVE, 1,
2847 clidp->data, clidp->len);
2849 silc_buffer_free(clidp);
2852 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2854 if (channel->founder_key) {
2855 /* The founder auth data exists, do not remove the channel entry */
2856 SilcChannelClientEntry chl2;
2857 SilcHashTableList htl2;
2859 channel->disabled = TRUE;
2861 silc_hash_table_list(channel->user_list, &htl2);
2862 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2863 silc_hash_table_del(chl2->client->channels, channel);
2864 silc_hash_table_del(channel->user_list, chl2->client);
2865 channel->user_count--;
2868 silc_hash_table_list_reset(&htl2);
2872 /* Remove the channel entry */
2873 if (silc_idlist_del_channel(server->local_list, channel))
2874 server->stat.my_channels--;
2876 silc_idlist_del_channel(server->global_list, channel);
2880 /* Send notify to channel about client leaving the channel */
2882 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2883 SILC_NOTIFY_TYPE_LEAVE, 1,
2884 clidp->data, clidp->len);
2886 silc_buffer_free(clidp);
2890 /* Timeout callback. This is called if connection is idle or for some
2891 other reason is not responding within some period of time. This
2892 disconnects the remote end. */
2894 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2896 SilcServer server = (SilcServer)context;
2897 SilcSocketConnection sock = server->sockets[fd];
2899 SILC_LOG_DEBUG(("Start"));
2904 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2905 sock->hostname, sock->ip));
2907 /* If we have protocol active we must assure that we call the protocol's
2908 final callback so that all the memory is freed. */
2909 if (sock->protocol) {
2910 silc_protocol_cancel(sock->protocol, server->schedule);
2911 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2912 silc_protocol_execute_final(sock->protocol, server->schedule);
2913 sock->protocol = NULL;
2917 if (sock->user_data)
2918 silc_server_free_sock_user_data(server, sock, NULL);
2920 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2921 "Connection timeout");
2924 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2925 function may be used only by router. In real SILC network all channels
2926 are created by routers thus this function is never used by normal
2929 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2930 SilcServerID *router_id,
2936 SilcChannelID *channel_id;
2937 SilcChannelEntry entry;
2941 SILC_LOG_DEBUG(("Creating new channel"));
2944 cipher = SILC_DEFAULT_CIPHER;
2946 hmac = SILC_DEFAULT_HMAC;
2948 /* Allocate cipher */
2949 if (!silc_cipher_alloc(cipher, &key))
2953 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2954 silc_cipher_free(key);
2958 channel_name = strdup(channel_name);
2960 /* Create the channel ID */
2961 if (!silc_id_create_channel_id(server, router_id, server->rng,
2963 silc_free(channel_name);
2964 silc_cipher_free(key);
2965 silc_hmac_free(newhmac);
2969 /* Create the channel */
2970 entry = silc_idlist_add_channel(server->local_list, channel_name,
2971 SILC_CHANNEL_MODE_NONE, channel_id,
2972 NULL, key, newhmac, 0);
2974 silc_free(channel_name);
2975 silc_cipher_free(key);
2976 silc_hmac_free(newhmac);
2977 silc_free(channel_id);
2981 entry->cipher = strdup(cipher);
2982 entry->hmac_name = strdup(hmac);
2984 /* Now create the actual key material */
2985 if (!silc_server_create_channel_key(server, entry,
2986 silc_cipher_get_key_len(key) / 8)) {
2987 silc_idlist_del_channel(server->local_list, entry);
2991 /* Notify other routers about the new channel. We send the packet
2992 to our primary route. */
2993 if (broadcast && server->standalone == FALSE)
2994 silc_server_send_new_channel(server, server->router->connection, TRUE,
2995 channel_name, entry->id,
2996 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2999 server->stat.my_channels++;
3004 /* Same as above but creates the channel with Channel ID `channel_id. */
3007 silc_server_create_new_channel_with_id(SilcServer server,
3011 SilcChannelID *channel_id,
3014 SilcChannelEntry entry;
3018 SILC_LOG_DEBUG(("Creating new channel"));
3021 cipher = SILC_DEFAULT_CIPHER;
3023 hmac = SILC_DEFAULT_HMAC;
3025 /* Allocate cipher */
3026 if (!silc_cipher_alloc(cipher, &key))
3030 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3031 silc_cipher_free(key);
3035 channel_name = strdup(channel_name);
3037 /* Create the channel */
3038 entry = silc_idlist_add_channel(server->local_list, channel_name,
3039 SILC_CHANNEL_MODE_NONE, channel_id,
3040 NULL, key, newhmac, 0);
3042 silc_cipher_free(key);
3043 silc_hmac_free(newhmac);
3044 silc_free(channel_name);
3048 /* Now create the actual key material */
3049 if (!silc_server_create_channel_key(server, entry,
3050 silc_cipher_get_key_len(key) / 8)) {
3051 silc_idlist_del_channel(server->local_list, entry);
3055 /* Notify other routers about the new channel. We send the packet
3056 to our primary route. */
3057 if (broadcast && server->standalone == FALSE)
3058 silc_server_send_new_channel(server, server->router->connection, TRUE,
3059 channel_name, entry->id,
3060 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3063 server->stat.my_channels++;
3068 /* Channel's key re-key timeout callback. */
3070 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3072 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3073 SilcServer server = (SilcServer)rekey->context;
3077 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3080 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3083 /* Generates new channel key. This is used to create the initial channel key
3084 but also to re-generate new key for channel. If `key_len' is provided
3085 it is the bytes of the key length. */
3087 bool silc_server_create_channel_key(SilcServer server,
3088 SilcChannelEntry channel,
3092 unsigned char channel_key[32], hash[32];
3095 SILC_LOG_DEBUG(("Generating channel key"));
3097 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3098 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3102 if (!channel->channel_key)
3103 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3104 channel->channel_key = NULL;
3110 else if (channel->key_len)
3111 len = channel->key_len / 8;
3113 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3115 /* Create channel key */
3116 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3119 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3121 /* Remove old key if exists */
3123 memset(channel->key, 0, channel->key_len / 8);
3124 silc_free(channel->key);
3128 channel->key_len = len * 8;
3129 channel->key = silc_memdup(channel_key, len);
3130 memset(channel_key, 0, sizeof(channel_key));
3132 /* Generate HMAC key from the channel key data and set it */
3134 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3135 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3136 silc_hmac_set_key(channel->hmac, hash,
3137 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3138 memset(hash, 0, sizeof(hash));
3140 if (server->server_type == SILC_ROUTER) {
3141 if (!channel->rekey)
3142 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3143 channel->rekey->context = (void *)server;
3144 channel->rekey->channel = channel;
3145 channel->rekey->key_len = key_len;
3146 if (channel->rekey->task)
3147 silc_schedule_task_del(server->schedule, channel->rekey->task);
3149 channel->rekey->task =
3150 silc_schedule_task_add(server->schedule, 0,
3151 silc_server_channel_key_rekey,
3152 (void *)channel->rekey,
3153 server->config->channel_rekey_secs, 0,
3155 SILC_TASK_PRI_NORMAL);
3161 /* Saves the channel key found in the encoded `key_payload' buffer. This
3162 function is used when we receive Channel Key Payload and also when we're
3163 processing JOIN command reply. Returns entry to the channel. */
3165 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3166 SilcBuffer key_payload,
3167 SilcChannelEntry channel)
3169 SilcChannelKeyPayload payload = NULL;
3170 SilcChannelID *id = NULL;
3171 unsigned char *tmp, hash[32];
3175 SILC_LOG_DEBUG(("Start"));
3177 /* Decode channel key payload */
3178 payload = silc_channel_key_payload_parse(key_payload->data,
3181 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3186 /* Get the channel entry */
3189 /* Get channel ID */
3190 tmp = silc_channel_key_get_id(payload, &tmp_len);
3191 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3197 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3199 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3201 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3202 silc_id_render(id, SILC_ID_CHANNEL)));
3208 tmp = silc_channel_key_get_key(payload, &tmp_len);
3214 cipher = silc_channel_key_get_cipher(payload, NULL);
3220 /* Remove old key if exists */
3222 memset(channel->key, 0, channel->key_len / 8);
3223 silc_free(channel->key);
3224 silc_cipher_free(channel->channel_key);
3227 /* Create new cipher */
3228 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3229 channel->channel_key = NULL;
3234 if (channel->cipher)
3235 silc_free(channel->cipher);
3236 channel->cipher = strdup(cipher);
3239 channel->key_len = tmp_len * 8;
3240 channel->key = silc_memdup(tmp, tmp_len);
3241 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3243 /* Generate HMAC key from the channel key data and set it */
3245 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3246 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3247 silc_hmac_set_key(channel->hmac, hash,
3248 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3250 memset(hash, 0, sizeof(hash));
3251 memset(tmp, 0, tmp_len);
3253 if (server->server_type == SILC_ROUTER) {
3254 if (!channel->rekey)
3255 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3256 channel->rekey->context = (void *)server;
3257 channel->rekey->channel = channel;
3258 if (channel->rekey->task)
3259 silc_schedule_task_del(server->schedule, channel->rekey->task);
3261 channel->rekey->task =
3262 silc_schedule_task_add(server->schedule, 0,
3263 silc_server_channel_key_rekey,
3264 (void *)channel->rekey,
3265 server->config->channel_rekey_secs, 0,
3267 SILC_TASK_PRI_NORMAL);
3273 silc_channel_key_payload_free(payload);
3278 /* Heartbeat callback. This function is set as argument for the
3279 silc_socket_set_heartbeat function. The library will call this function
3280 at the set time interval. */
3282 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3285 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3287 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3289 /* Send the heartbeat */
3290 silc_server_send_heartbeat(hb->server, sock);
3293 /* Returns assembled of all servers in the given ID list. The packet's
3294 form is dictated by the New ID payload. */
3296 static void silc_server_announce_get_servers(SilcServer server,
3297 SilcServerEntry remote,
3299 SilcBuffer *servers,
3300 unsigned long creation_time)
3302 SilcIDCacheList list;
3303 SilcIDCacheEntry id_cache;
3304 SilcServerEntry entry;
3307 /* Go through all clients in the list */
3308 if (silc_idcache_get_all(id_list->servers, &list)) {
3309 if (silc_idcache_list_first(list, &id_cache)) {
3311 entry = (SilcServerEntry)id_cache->context;
3313 /* Do not announce the one we've sending our announcements and
3314 do not announce ourself. Also check the creation time if it's
3316 if ((entry == remote) || (entry == server->id_entry) ||
3317 (creation_time && entry->data.created < creation_time)) {
3318 if (!silc_idcache_list_next(list, &id_cache))
3323 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3325 *servers = silc_buffer_realloc(*servers,
3327 (*servers)->truelen + idp->len :
3329 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3330 silc_buffer_put(*servers, idp->data, idp->len);
3331 silc_buffer_pull(*servers, idp->len);
3332 silc_buffer_free(idp);
3334 if (!silc_idcache_list_next(list, &id_cache))
3339 silc_idcache_list_free(list);
3344 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3350 p = silc_notify_payload_encode(notify, argc, ap);
3356 /* This function is used by router to announce existing servers to our
3357 primary router when we've connected to it. If `creation_time' is non-zero
3358 then only the servers that has been created after the `creation_time'
3359 will be announced. */
3361 void silc_server_announce_servers(SilcServer server, bool global,
3362 unsigned long creation_time,
3363 SilcSocketConnection remote)
3365 SilcBuffer servers = NULL;
3367 SILC_LOG_DEBUG(("Announcing servers"));
3369 /* Get servers in local list */
3370 silc_server_announce_get_servers(server, remote->user_data,
3371 server->local_list, &servers,
3375 /* Get servers in global list */
3376 silc_server_announce_get_servers(server, remote->user_data,
3377 server->global_list, &servers,
3381 silc_buffer_push(servers, servers->data - servers->head);
3382 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3384 /* Send the packet */
3385 silc_server_packet_send(server, remote,
3386 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3387 servers->data, servers->len, TRUE);
3389 silc_buffer_free(servers);
3393 /* Returns assembled packet of all clients in the given ID list. The
3394 packet's form is dictated by the New ID Payload. */
3396 static void silc_server_announce_get_clients(SilcServer server,
3398 SilcBuffer *clients,
3400 unsigned long creation_time)
3402 SilcIDCacheList list;
3403 SilcIDCacheEntry id_cache;
3404 SilcClientEntry client;
3407 unsigned char mode[4];
3409 /* Go through all clients in the list */
3410 if (silc_idcache_get_all(id_list->clients, &list)) {
3411 if (silc_idcache_list_first(list, &id_cache)) {
3413 client = (SilcClientEntry)id_cache->context;
3415 if (creation_time && client->data.created < creation_time) {
3416 if (!silc_idcache_list_next(list, &id_cache))
3421 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3423 *clients = silc_buffer_realloc(*clients,
3425 (*clients)->truelen + idp->len :
3427 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3428 silc_buffer_put(*clients, idp->data, idp->len);
3429 silc_buffer_pull(*clients, idp->len);
3431 SILC_PUT32_MSB(client->mode, mode);
3432 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3433 2, idp->data, idp->len,
3435 *umodes = silc_buffer_realloc(*umodes,
3437 (*umodes)->truelen + tmp->len :
3439 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3440 silc_buffer_put(*umodes, tmp->data, tmp->len);
3441 silc_buffer_pull(*umodes, tmp->len);
3442 silc_buffer_free(tmp);
3444 silc_buffer_free(idp);
3446 if (!silc_idcache_list_next(list, &id_cache))
3451 silc_idcache_list_free(list);
3455 /* This function is used to announce our existing clients to our router
3456 when we've connected to it. If `creation_time' is non-zero then only
3457 the clients that has been created after the `creation_time' will be
3460 void silc_server_announce_clients(SilcServer server,
3461 unsigned long creation_time,
3462 SilcSocketConnection remote)
3464 SilcBuffer clients = NULL;
3465 SilcBuffer umodes = NULL;
3467 SILC_LOG_DEBUG(("Announcing clients"));
3469 /* Get clients in local list */
3470 silc_server_announce_get_clients(server, server->local_list,
3471 &clients, &umodes, creation_time);
3473 /* As router we announce our global list as well */
3474 if (server->server_type == SILC_ROUTER)
3475 silc_server_announce_get_clients(server, server->global_list,
3476 &clients, &umodes, creation_time);
3479 silc_buffer_push(clients, clients->data - clients->head);
3480 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3482 /* Send the packet */
3483 silc_server_packet_send(server, remote,
3484 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3485 clients->data, clients->len, TRUE);
3487 silc_buffer_free(clients);
3491 silc_buffer_push(umodes, umodes->data - umodes->head);
3492 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3494 /* Send the packet */
3495 silc_server_packet_send(server, remote,
3496 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3497 umodes->data, umodes->len, TRUE);
3499 silc_buffer_free(umodes);
3503 /* Returns channel's topic for announcing it */
3505 void silc_server_announce_get_channel_topic(SilcServer server,
3506 SilcChannelEntry channel,
3511 if (channel->topic) {
3512 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3513 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3514 chidp->data, chidp->len,
3516 strlen(channel->topic));
3517 silc_buffer_free(chidp);
3521 /* Returns assembled packets for channel users of the `channel'. */
3523 void silc_server_announce_get_channel_users(SilcServer server,
3524 SilcChannelEntry channel,
3525 SilcBuffer *channel_users,
3526 SilcBuffer *channel_users_modes)
3528 SilcChannelClientEntry chl;
3529 SilcHashTableList htl;
3530 SilcBuffer chidp, clidp;
3533 unsigned char mode[4];
3535 SILC_LOG_DEBUG(("Start"));
3537 /* Now find all users on the channel */
3538 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3539 silc_hash_table_list(channel->user_list, &htl);
3540 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3541 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3544 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3545 clidp->data, clidp->len,
3546 chidp->data, chidp->len);
3549 silc_buffer_realloc(*channel_users,
3551 (*channel_users)->truelen + len : len));
3552 silc_buffer_pull_tail(*channel_users,
3553 ((*channel_users)->end -
3554 (*channel_users)->data));
3556 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3557 silc_buffer_pull(*channel_users, len);
3558 silc_buffer_free(tmp);
3560 /* CUMODE notify for mode change on the channel */
3561 SILC_PUT32_MSB(chl->mode, mode);
3562 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3563 3, clidp->data, clidp->len,
3565 clidp->data, clidp->len);
3567 *channel_users_modes =
3568 silc_buffer_realloc(*channel_users_modes,
3569 (*channel_users_modes ?
3570 (*channel_users_modes)->truelen + len : len));
3571 silc_buffer_pull_tail(*channel_users_modes,
3572 ((*channel_users_modes)->end -
3573 (*channel_users_modes)->data));
3575 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3576 silc_buffer_pull(*channel_users_modes, len);
3577 silc_buffer_free(tmp);
3579 silc_buffer_free(clidp);
3581 silc_hash_table_list_reset(&htl);
3582 silc_buffer_free(chidp);
3585 /* Returns assembled packets for all channels and users on those channels
3586 from the given ID List. The packets are in the form dictated by the
3587 New Channel and New Channel User payloads. */
3589 void silc_server_announce_get_channels(SilcServer server,
3591 SilcBuffer *channels,
3592 SilcBuffer *channel_users,
3593 SilcBuffer **channel_users_modes,
3594 SilcUInt32 *channel_users_modes_c,
3595 SilcBuffer **channel_topics,
3596 SilcChannelID ***channel_ids,
3597 unsigned long creation_time)
3599 SilcIDCacheList list;
3600 SilcIDCacheEntry id_cache;
3601 SilcChannelEntry channel;
3604 SilcUInt16 name_len;
3606 int i = *channel_users_modes_c;
3609 SILC_LOG_DEBUG(("Start"));
3611 /* Go through all channels in the list */
3612 if (silc_idcache_get_all(id_list->channels, &list)) {
3613 if (silc_idcache_list_first(list, &id_cache)) {
3615 channel = (SilcChannelEntry)id_cache->context;
3617 if (creation_time && channel->created < creation_time)
3622 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3623 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3624 name_len = strlen(channel->channel_name);
3627 len = 4 + name_len + id_len + 4;
3629 silc_buffer_realloc(*channels,
3630 (*channels ? (*channels)->truelen +
3632 silc_buffer_pull_tail(*channels,
3633 ((*channels)->end - (*channels)->data));
3634 silc_buffer_format(*channels,
3635 SILC_STR_UI_SHORT(name_len),
3636 SILC_STR_UI_XNSTRING(channel->channel_name,
3638 SILC_STR_UI_SHORT(id_len),
3639 SILC_STR_UI_XNSTRING(cid, id_len),
3640 SILC_STR_UI_INT(channel->mode),
3642 silc_buffer_pull(*channels, len);
3645 /* Channel user modes */
3646 *channel_users_modes = silc_realloc(*channel_users_modes,
3647 sizeof(**channel_users_modes) *
3649 (*channel_users_modes)[i] = NULL;
3650 *channel_ids = silc_realloc(*channel_ids,
3651 sizeof(**channel_ids) * (i + 1));
3652 (*channel_ids)[i] = NULL;
3653 silc_server_announce_get_channel_users(server, channel,
3655 &(*channel_users_modes)[i]);
3656 (*channel_ids)[i] = channel->id;
3658 /* Channel's topic */
3659 *channel_topics = silc_realloc(*channel_topics,
3660 sizeof(**channel_topics) * (i + 1));
3661 (*channel_topics)[i] = NULL;
3662 silc_server_announce_get_channel_topic(server, channel,
3663 &(*channel_topics)[i]);
3666 if (!silc_idcache_list_next(list, &id_cache))
3670 *channel_users_modes_c += i;
3673 silc_idcache_list_free(list);
3677 /* This function is used to announce our existing channels to our router
3678 when we've connected to it. This also announces the users on the
3679 channels to the router. If the `creation_time' is non-zero only the
3680 channels that was created after the `creation_time' are announced.
3681 Note that the channel users are still announced even if the `creation_time'
3684 void silc_server_announce_channels(SilcServer server,
3685 unsigned long creation_time,
3686 SilcSocketConnection remote)
3688 SilcBuffer channels = NULL, channel_users = NULL;
3689 SilcBuffer *channel_users_modes = NULL;
3690 SilcBuffer *channel_topics = NULL;
3691 SilcUInt32 channel_users_modes_c = 0;
3692 SilcChannelID **channel_ids = NULL;
3694 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3696 /* Get channels and channel users in local list */
3697 silc_server_announce_get_channels(server, server->local_list,
3698 &channels, &channel_users,
3699 &channel_users_modes,
3700 &channel_users_modes_c,
3702 &channel_ids, creation_time);
3704 /* Get channels and channel users in global list */
3705 if (server->server_type != SILC_SERVER)
3706 silc_server_announce_get_channels(server, server->global_list,
3707 &channels, &channel_users,
3708 &channel_users_modes,
3709 &channel_users_modes_c,
3711 &channel_ids, creation_time);
3714 silc_buffer_push(channels, channels->data - channels->head);
3715 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3717 /* Send the packet */
3718 silc_server_packet_send(server, remote,
3719 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3720 channels->data, channels->len,
3723 silc_buffer_free(channels);
3726 if (channel_users) {
3727 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3728 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3729 channel_users->len);
3731 /* Send the packet */
3732 silc_server_packet_send(server, remote,
3733 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3734 channel_users->data, channel_users->len,
3737 silc_buffer_free(channel_users);
3740 if (channel_users_modes) {
3743 for (i = 0; i < channel_users_modes_c; i++) {
3744 if (!channel_users_modes[i])
3746 silc_buffer_push(channel_users_modes[i],
3747 channel_users_modes[i]->data -
3748 channel_users_modes[i]->head);
3749 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3750 channel_users_modes[i]->len);
3751 silc_server_packet_send_dest(server, remote,
3752 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3753 channel_ids[i], SILC_ID_CHANNEL,
3754 channel_users_modes[i]->data,
3755 channel_users_modes[i]->len,
3757 silc_buffer_free(channel_users_modes[i]);
3759 silc_free(channel_users_modes);
3762 if (channel_topics) {
3765 for (i = 0; i < channel_users_modes_c; i++) {
3766 if (!channel_topics[i])
3769 silc_buffer_push(channel_topics[i],
3770 channel_topics[i]->data -
3771 channel_topics[i]->head);
3772 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3773 channel_topics[i]->len);
3774 silc_server_packet_send_dest(server, remote,
3775 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3776 channel_ids[i], SILC_ID_CHANNEL,
3777 channel_topics[i]->data,
3778 channel_topics[i]->len,
3780 silc_buffer_free(channel_topics[i]);
3782 silc_free(channel_topics);
3785 silc_free(channel_ids);
3788 /* Failure timeout callback. If this is called then we will immediately
3789 process the received failure. We always process the failure with timeout
3790 since we do not want to blindly trust to received failure packets.
3791 This won't be called (the timeout is cancelled) if the failure was
3792 bogus (it is bogus if remote does not close the connection after sending
3795 SILC_TASK_CALLBACK(silc_server_failure_callback)
3797 SilcServerFailureContext f = (SilcServerFailureContext)context;
3799 if (f->sock->protocol) {
3800 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3801 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3807 /* Assembles user list and users mode list from the `channel'. */
3809 void silc_server_get_users_on_channel(SilcServer server,
3810 SilcChannelEntry channel,
3811 SilcBuffer *user_list,
3812 SilcBuffer *mode_list,
3813 SilcUInt32 *user_count)
3815 SilcChannelClientEntry chl;
3816 SilcHashTableList htl;
3817 SilcBuffer client_id_list;
3818 SilcBuffer client_mode_list;
3820 SilcUInt32 list_count = 0, len = 0;
3822 silc_hash_table_list(channel->user_list, &htl);
3823 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3824 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3825 silc_hash_table_list_reset(&htl);
3827 client_id_list = silc_buffer_alloc(len);
3829 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3830 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3831 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3833 silc_hash_table_list(channel->user_list, &htl);
3834 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3836 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3837 silc_buffer_put(client_id_list, idp->data, idp->len);
3838 silc_buffer_pull(client_id_list, idp->len);
3839 silc_buffer_free(idp);
3841 /* Client's mode on channel */
3842 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3843 silc_buffer_pull(client_mode_list, 4);
3847 silc_hash_table_list_reset(&htl);
3848 silc_buffer_push(client_id_list,
3849 client_id_list->data - client_id_list->head);
3850 silc_buffer_push(client_mode_list,
3851 client_mode_list->data - client_mode_list->head);
3853 *user_list = client_id_list;
3854 *mode_list = client_mode_list;
3855 *user_count = list_count;
3858 /* Saves users and their modes to the `channel'. */
3860 void silc_server_save_users_on_channel(SilcServer server,
3861 SilcSocketConnection sock,
3862 SilcChannelEntry channel,
3863 SilcClientID *noadd,
3864 SilcBuffer user_list,
3865 SilcBuffer mode_list,
3866 SilcUInt32 user_count)
3871 SilcClientID *client_id;
3872 SilcClientEntry client;
3873 SilcIDCacheEntry cache;
3876 SILC_LOG_DEBUG(("Start"));
3878 for (i = 0; i < user_count; i++) {
3880 SILC_GET16_MSB(idp_len, user_list->data + 2);
3882 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3883 silc_buffer_pull(user_list, idp_len);
3888 SILC_GET32_MSB(mode, mode_list->data);
3889 silc_buffer_pull(mode_list, 4);
3891 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3892 silc_free(client_id);
3898 /* Check if we have this client cached already. */
3899 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3900 server->server_type, &cache);
3902 client = silc_idlist_find_client_by_id(server->global_list,
3903 client_id, server->server_type,
3908 /* If router did not find such Client ID in its lists then this must
3909 be bogus client or some router in the net is buggy. */
3910 if (server->server_type == SILC_ROUTER) {
3911 silc_free(client_id);
3915 /* We don't have that client anywhere, add it. The client is added
3916 to global list since server didn't have it in the lists so it must be
3918 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3919 silc_id_dup(client_id, SILC_ID_CLIENT),
3920 sock->user_data, NULL, 0);
3922 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3923 silc_free(client_id);
3927 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3929 /* Found, if it is from global list we'll assure that we won't
3930 expire it now that the entry is on channel. */
3935 silc_free(client_id);
3937 if (!silc_server_client_on_channel(client, channel, NULL)) {
3938 /* Client was not on the channel, add it. */
3939 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3940 chl->client = client;
3942 chl->channel = channel;
3943 silc_hash_table_add(channel->user_list, chl->client, chl);
3944 silc_hash_table_add(client->channels, chl->channel, chl);
3945 channel->user_count++;
3950 /* Lookups route to the client indicated by the `id_data'. The connection
3951 object and internal data object is returned. Returns NULL if route
3952 could not be found to the client. If the `client_id' is specified then
3953 it is used and the `id_data' is ignored. */
3955 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3956 unsigned char *id_data,
3958 SilcClientID *client_id,
3959 SilcIDListData *idata)
3962 SilcClientEntry client;
3964 SILC_LOG_DEBUG(("Start"));
3966 /* Decode destination Client ID */
3968 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3970 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3974 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3977 /* If the destination belongs to our server we don't have to route
3978 the packet anywhere but to send it to the local destination. */
3979 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3983 /* If we are router and the client has router then the client is in
3984 our cell but not directly connected to us. */
3985 if (server->server_type == SILC_ROUTER && client->router) {
3986 /* We are of course in this case the client's router thus the route
3987 to the client is the server who owns the client. So, we will send
3988 the packet to that server. */
3990 *idata = (SilcIDListData)client->router;
3991 return client->router->connection;
3994 /* Seems that client really is directly connected to us */
3996 *idata = (SilcIDListData)client;
3997 return client->connection;
4000 /* Destination belongs to someone not in this server. If we are normal
4001 server our action is to send the packet to our router. */
4002 if (server->server_type != SILC_ROUTER && !server->standalone) {
4005 *idata = (SilcIDListData)server->router;
4006 return server->router->connection;
4009 /* We are router and we will perform route lookup for the destination
4010 and send the packet to fastest route. */
4011 if (server->server_type == SILC_ROUTER && !server->standalone) {
4012 /* Check first that the ID is valid */
4013 client = silc_idlist_find_client_by_id(server->global_list, id,
4016 SilcSocketConnection dst_sock;
4018 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4022 *idata = (SilcIDListData)dst_sock->user_data;
4031 /* Encodes and returns channel list of channels the `client' has joined.
4032 Secret channels are not put to the list. */
4034 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4035 SilcClientEntry client)
4037 SilcBuffer buffer = NULL;
4038 SilcChannelEntry channel;
4039 SilcChannelClientEntry chl;
4040 SilcHashTableList htl;
4043 SilcUInt16 name_len;
4046 silc_hash_table_list(client->channels, &htl);
4047 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4048 channel = chl->channel;
4050 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4051 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4054 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4055 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4056 name_len = strlen(channel->channel_name);
4058 len = 4 + name_len + id_len + 4;
4059 buffer = silc_buffer_realloc(buffer,
4060 (buffer ? (buffer)->truelen + len : len));
4061 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4062 silc_buffer_format(buffer,
4063 SILC_STR_UI_SHORT(name_len),
4064 SILC_STR_UI_XNSTRING(channel->channel_name,
4066 SILC_STR_UI_SHORT(id_len),
4067 SILC_STR_UI_XNSTRING(cid, id_len),
4068 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4070 silc_buffer_pull(buffer, len);
4073 silc_hash_table_list_reset(&htl);
4076 silc_buffer_push(buffer, buffer->data - buffer->head);
4081 /* Finds client entry by Client ID and if it is not found then resolves
4082 it using WHOIS command. */
4084 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4085 SilcClientID *client_id,
4088 SilcClientEntry client;
4093 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4096 client = silc_idlist_find_client_by_id(server->global_list,
4097 client_id, TRUE, NULL);
4098 if (!client && server->server_type == SILC_ROUTER)
4102 if (!client && server->standalone)
4105 if (!client || !client->nickname || !client->username) {
4106 SilcBuffer buffer, idp;
4108 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4109 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4110 client->resolve_cmd_ident = ++server->cmd_ident;
4112 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4113 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4114 server->cmd_ident, 1,
4115 3, idp->data, idp->len);
4116 silc_server_packet_send(server, client ? client->router->connection :
4117 server->router->connection,
4118 SILC_PACKET_COMMAND, 0,
4119 buffer->data, buffer->len, FALSE);
4120 silc_buffer_free(idp);
4121 silc_buffer_free(buffer);
4132 /* A timeout callback for the re-key. We will be the initiator of the
4135 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4137 SilcSocketConnection sock = (SilcSocketConnection)context;
4138 SilcIDListData idata = (SilcIDListData)sock->user_data;
4139 SilcServer server = (SilcServer)idata->rekey->context;
4140 SilcProtocol protocol;
4141 SilcServerRekeyInternalContext *proto_ctx;
4143 SILC_LOG_DEBUG(("Start"));
4145 /* Allocate internal protocol context. This is sent as context
4147 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4148 proto_ctx->server = (void *)server;
4149 proto_ctx->sock = sock;
4150 proto_ctx->responder = FALSE;
4151 proto_ctx->pfs = idata->rekey->pfs;
4153 /* Perform rekey protocol. Will call the final callback after the
4154 protocol is over. */
4155 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4156 &protocol, proto_ctx, silc_server_rekey_final);
4157 sock->protocol = protocol;
4159 /* Run the protocol */
4160 silc_protocol_execute(protocol, server->schedule, 0, 0);
4162 /* Re-register re-key timeout */
4163 silc_schedule_task_add(server->schedule, sock->sock,
4164 silc_server_rekey_callback,
4165 context, idata->rekey->timeout, 0,
4166 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4169 /* The final callback for the REKEY protocol. This will actually take the
4170 new key material into use. */
4172 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4174 SilcProtocol protocol = (SilcProtocol)context;
4175 SilcServerRekeyInternalContext *ctx =
4176 (SilcServerRekeyInternalContext *)protocol->context;
4177 SilcServer server = (SilcServer)ctx->server;
4178 SilcSocketConnection sock = ctx->sock;
4180 SILC_LOG_DEBUG(("Start"));
4182 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4183 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4184 /* Error occured during protocol */
4185 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4186 silc_protocol_cancel(protocol, server->schedule);
4187 silc_protocol_free(protocol);
4188 sock->protocol = NULL;
4190 silc_packet_context_free(ctx->packet);
4192 silc_ske_free(ctx->ske);
4197 /* Purge the outgoing data queue to assure that all rekey packets really
4198 go to the network before we quit the protocol. */
4199 silc_server_packet_queue_purge(server, sock);
4202 silc_protocol_free(protocol);
4203 sock->protocol = NULL;
4205 silc_packet_context_free(ctx->packet);
4207 silc_ske_free(ctx->ske);