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_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
44 /* Allocates a new SILC server object. This has to be done before the server
45 can be used. After allocation one must call silc_server_init to initialize
46 the server. The new allocated server object is returned to the new_server
49 int silc_server_alloc(SilcServer *new_server)
53 SILC_LOG_DEBUG(("Allocating new server object"));
55 server = silc_calloc(1, sizeof(*server));
56 server->server_type = SILC_SERVER;
57 server->standalone = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
80 silc_free(server->local_list);
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 silc_pkcs_free(server->pkcs);
89 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
90 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
96 if (server->pending_commands)
97 silc_dlist_uninit(server->pending_commands);
103 /* Initializes the entire SILC server. This is called always before running
104 the server. This is called only once at the initialization of the program.
105 This binds the server to its listenning port. After this function returns
106 one should call silc_server_run to start the server. This returns TRUE
107 when everything is ok to run the server. Configuration file must be
108 read and parsed before calling this. */
110 int silc_server_init(SilcServer server)
114 SilcServerEntry id_entry;
115 SilcIDListPurge purge;
117 SILC_LOG_DEBUG(("Initializing server"));
119 assert(server->config);
121 /* Set public and private keys */
122 if (!server->config->server_info ||
123 !server->config->server_info->public_key ||
124 !server->config->server_info->private_key) {
125 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
128 server->public_key = server->config->server_info->public_key;
129 server->private_key = server->config->server_info->private_key;
131 /* Set default to configuration parameters */
132 silc_server_config_set_defaults(server);
134 /* Register all configured ciphers, PKCS and hash functions. */
135 if (!silc_server_config_register_ciphers(server))
136 silc_cipher_register_default();
137 if (!silc_server_config_register_pkcs(server))
138 silc_pkcs_register_default();
139 if (!silc_server_config_register_hashfuncs(server))
140 silc_hash_register_default();
141 if (!silc_server_config_register_hmacs(server))
142 silc_hmac_register_default();
144 /* Initialize random number generator for the server. */
145 server->rng = silc_rng_alloc();
146 silc_rng_init(server->rng);
147 silc_rng_global_init(server->rng);
149 /* Initialize hash functions for server to use */
150 silc_hash_alloc("md5", &server->md5hash);
151 silc_hash_alloc("sha1", &server->sha1hash);
153 /* Allocate PKCS context for local public and private keys */
154 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
155 silc_pkcs_public_key_set(server->pkcs, server->public_key);
156 silc_pkcs_private_key_set(server->pkcs, server->private_key);
158 /* Create a listening server */
159 sock = silc_net_create_server(server->config->server_info->port,
160 server->config->server_info->server_ip);
162 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
163 server->config->server_info->server_ip,
164 server->config->server_info->port));
168 /* Initialize ID caches */
169 server->local_list->clients =
170 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
171 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
172 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
174 /* These are allocated for normal server as well as these hold some
175 global information that the server has fetched from its router. For
176 router these are used as they are supposed to be used on router. */
177 server->global_list->clients =
178 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
179 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
180 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
182 /* Allocate the entire socket list that is used in server. Eventually
183 all connections will have entry in this table (it is a table of
184 pointers to the actual object that is allocated individually
186 server->sockets = silc_calloc(server->config->param.connections_max,
187 sizeof(*server->sockets));
190 SilcSocketConnection newsocket = NULL;
192 /* Set socket to non-blocking mode */
193 silc_net_set_socket_nonblock(sock);
196 /* Add ourselves also to the socket table. The entry allocated above
197 is sent as argument for fast referencing in the future. */
198 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
199 server->sockets[sock] = newsocket;
201 /* Perform name and address lookups to resolve the listenning address
203 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
205 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
207 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
208 newsocket->hostname ? newsocket->hostname :
209 newsocket->ip ? newsocket->ip : ""));
210 server->stat.conn_failures++;
213 if (!newsocket->hostname)
214 newsocket->hostname = strdup(newsocket->ip);
216 newsocket->port = silc_net_get_local_port(sock);
218 /* Create a Server ID for the server. */
219 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
224 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
225 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
226 server->id_type = SILC_ID_SERVER;
227 server->server_name = server->config->server_info->server_name;
229 /* Add ourselves to the server list. We don't have a router yet
230 beacuse we haven't established a route yet. It will be done later.
231 For now, NULL is sent as router. This allocates new entry to
234 silc_idlist_add_server(server->local_list,
235 server->config->server_info->server_name,
236 server->server_type, server->id, NULL, NULL);
238 SILC_LOG_ERROR(("Could not add ourselves to cache"));
241 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
243 /* Put the allocated socket pointer also to the entry allocated above
244 for fast back-referencing to the socket list. */
245 newsocket->user_data = (void *)id_entry;
246 id_entry->connection = (void *)newsocket;
247 server->id_entry = id_entry;
250 /* Register protocols */
251 silc_server_protocols_register();
253 /* Initialize the scheduler. */
254 server->schedule = silc_schedule_init(server->config->param.connections_max);
255 if (!server->schedule)
258 /* Add the first task to the scheduler. This is task that is executed by
259 timeout. It expires as soon as the caller calls silc_server_run. This
260 task performs authentication protocol and key exchange with our
262 silc_schedule_task_add(server->schedule, sock,
263 silc_server_connect_to_router,
264 (void *)server, 0, 1,
266 SILC_TASK_PRI_NORMAL);
268 /* Add listener task to the scheduler. This task receives new connections
269 to the server. This task remains on the queue until the end of the
271 silc_schedule_task_add(server->schedule, sock,
272 silc_server_accept_new_connection,
273 (void *)server, 0, 0,
275 SILC_TASK_PRI_NORMAL);
276 server->listenning = TRUE;
278 /* Send log file configuration */
279 silc_server_config_setlogfiles(server);
281 /* If server connections has been configured then we must be router as
282 normal server cannot have server connections, only router connections. */
283 if (server->config->servers) {
284 SilcServerConfigServer *ptr = server->config->servers;
286 server->server_type = SILC_ROUTER;
288 if (ptr->backup_router) {
289 server->server_type = SILC_BACKUP_ROUTER;
290 server->backup_router = TRUE;
291 server->id_entry->server_type = SILC_BACKUP_ROUTER;
298 /* Register the ID Cache purge task. This periodically purges the ID cache
299 and removes the expired cache entries. */
301 /* Clients local list */
302 purge = silc_calloc(1, sizeof(*purge));
303 purge->cache = server->local_list->clients;
304 purge->schedule = server->schedule;
305 purge->timeout = 600;
306 silc_schedule_task_add(purge->schedule, 0,
308 (void *)purge, purge->timeout, 0,
309 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
311 /* Clients global list */
312 purge = silc_calloc(1, sizeof(*purge));
313 purge->cache = server->global_list->clients;
314 purge->schedule = server->schedule;
315 purge->timeout = 300;
316 silc_schedule_task_add(purge->schedule, 0,
318 (void *)purge, purge->timeout, 0,
319 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
321 SILC_LOG_DEBUG(("Server initialized"));
323 /* We are done here, return succesfully */
327 silc_net_close_server(sock);
331 /* Fork server to background */
333 void silc_server_daemonise(SilcServer server)
337 SILC_LOG_DEBUG(("Forking SILC server to background"));
342 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
347 SILC_LOG_DEBUG(("Server started as user"));
349 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
355 /* Drop root privligies. If this cannot be done, die. */
357 void silc_server_drop(SilcServer server)
359 /* Are we executing silcd as root or a regular user? */
365 /* Get the values given for user and group in configuration file */
366 user = server->config->server_info->user;
367 group = server->config->server_info->group;
369 if (!user || !group) {
370 fprintf(stderr, "Error:" /* XXX update this error message */
371 "\tSILC server must not be run as root. For the security of your\n"
372 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
373 "\tuser account. Modify the [Identity] configuration section to run\n"
374 "\tthe server as non-root user.\n");
378 /* Check whether the user/group does not begin with a number */
379 if (isdigit(user[0]) || isdigit(group[0])) {
380 SILC_LOG_DEBUG(("User and/or group starts with a number"));
381 fprintf(stderr, "Invalid user and/or group information\n");
382 fprintf(stderr, "Please assign them as names, not numbers\n");
386 if (!(pw = getpwnam(user))) {
387 fprintf(stderr, "Error: No such user %s found.\n", user);
390 if (!(gr = getgrnam(group))) {
391 fprintf(stderr, "Error: No such group %s found.\n", group);
395 /* Check whether user and/or group is set to root. If yes, exit
396 immediately. Otherwise, setgid and setuid server to user.group */
397 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
398 fprintf(stderr, "Error:"
399 "\tSILC server must not be run as root. For the security of your\n"
400 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
401 "\tuser account. Modify the [Identity] configuration section to run\n"
402 "\tthe server as non-root user.\n");
406 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
407 if (setgid(gr->gr_gid) != 0) {
408 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
412 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
413 SILC_LOG_DEBUG(("Removing supplementary groups"));
414 if (setgroups(0, NULL) != 0) {
415 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
418 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
419 if (initgroups(user, gr->gr_gid) != 0) {
420 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
421 "Exiting.\n", user, gr->gr_gid);
425 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
426 if (setuid(pw->pw_uid) != 0) {
427 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
434 /* The heart of the server. This runs the scheduler thus runs the server.
435 When this returns the server has been stopped and the program will
438 void silc_server_run(SilcServer server)
440 SILC_LOG_DEBUG(("Running server"));
442 SILC_LOG_INFO(("SILC Server started"));
444 /* Start the scheduler, the heart of the SILC server. When this returns
445 the program will be terminated. */
446 silc_schedule(server->schedule);
449 /* Stops the SILC server. This function is used to shutdown the server.
450 This is usually called after the scheduler has returned. After stopping
451 the server one should call silc_server_free. */
453 void silc_server_stop(SilcServer server)
455 SILC_LOG_DEBUG(("Stopping server"));
457 if (server->schedule) {
458 silc_schedule_stop(server->schedule);
459 silc_schedule_uninit(server->schedule);
460 server->schedule = NULL;
463 silc_server_protocols_unregister();
465 SILC_LOG_DEBUG(("Server stopped"));
468 /* Function that is called when the network connection to a router has
469 been established. This will continue with the key exchange protocol
470 with the remote router. */
472 void silc_server_start_key_exchange(SilcServer server,
473 SilcServerConnection sconn,
476 SilcSocketConnection newsocket;
477 SilcProtocol protocol;
478 SilcServerKEInternalContext *proto_ctx;
479 SilcServerConfigRouter *conn = sconn->conn;
482 /* Cancel any possible retry timeouts */
483 silc_schedule_task_del_by_callback(server->schedule,
484 silc_server_connect_router);
486 /* Set socket options */
487 silc_net_set_socket_nonblock(sock);
488 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
490 /* Create socket connection for the connection. Even though we
491 know that we are connecting to a router we will mark the socket
492 to be unknown connection until we have executed authentication
494 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
495 server->sockets[sock] = newsocket;
496 newsocket->hostname = strdup(sconn->remote_host);
497 newsocket->ip = strdup(sconn->remote_host);
498 newsocket->port = sconn->remote_port;
499 sconn->sock = newsocket;
501 /* Allocate internal protocol context. This is sent as context
503 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
504 proto_ctx->server = (void *)server;
505 proto_ctx->context = (void *)sconn;
506 proto_ctx->sock = newsocket;
507 proto_ctx->rng = server->rng;
508 proto_ctx->responder = FALSE;
510 /* Set Key Exchange flags from configuration, but fall back to global
512 SILC_GET_SKE_FLAGS(conn, proto_ctx);
513 if (server->config->param.key_exchange_pfs)
514 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
516 /* Perform key exchange protocol. silc_server_connect_to_router_second
517 will be called after the protocol is finished. */
518 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
519 &protocol, proto_ctx,
520 silc_server_connect_to_router_second);
521 newsocket->protocol = protocol;
523 /* Register a timeout task that will be executed if the protocol
524 is not executed within set limit. */
525 proto_ctx->timeout_task =
526 silc_schedule_task_add(server->schedule, sock,
527 silc_server_timeout_remote,
528 server, server->config->key_exchange_timeout, 0,
532 /* Register the connection for network input and output. This sets
533 that scheduler will listen for incoming packets for this connection
534 and sets that outgoing packets may be sent to this connection as
535 well. However, this doesn't set the scheduler for outgoing traffic,
536 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
537 later when outgoing data is available. */
538 context = (void *)server;
539 SILC_REGISTER_CONNECTION_FOR_IO(sock);
541 /* Run the protocol */
542 silc_protocol_execute(protocol, server->schedule, 0, 0);
545 /* Timeout callback that will be called to retry connecting to remote
546 router. This is used by both normal and router server. This will wait
547 before retrying the connecting. The timeout is generated by exponential
548 backoff algorithm. */
550 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
552 SilcServerConnection sconn = (SilcServerConnection)context;
553 SilcServer server = sconn->server;
554 SilcServerConfigConnParams *param =
555 (sconn->param ? sconn->param : &server->config->param);
557 SILC_LOG_INFO(("Retrying connecting to a router"));
559 /* Calculate next timeout */
560 if (sconn->retry_count >= 1) {
561 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
562 if (sconn->retry_timeout > param->reconnect_interval_max)
563 sconn->retry_timeout = param->reconnect_interval_max;
565 sconn->retry_timeout = param->reconnect_interval;
567 sconn->retry_count++;
568 sconn->retry_timeout = sconn->retry_timeout +
569 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
571 /* If we've reached max retry count, give up. */
572 if (sconn->retry_count > param->reconnect_count &&
573 param->reconnect_keep_trying == FALSE) {
574 SILC_LOG_ERROR(("Could not connect to router, giving up"));
575 silc_free(sconn->remote_host);
580 /* Wait one before retrying */
581 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
582 context, sconn->retry_timeout, 0,
583 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
586 /* Generic routine to use connect to a router. */
588 SILC_TASK_CALLBACK(silc_server_connect_router)
590 SilcServerConnection sconn = (SilcServerConnection)context;
591 SilcServer server = sconn->server;
594 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
595 (sconn->backup ? "backup router" : "router"),
596 sconn->remote_host, sconn->remote_port));
598 server->router_connect = time(NULL);
600 /* Connect to remote host */
601 sock = silc_net_create_connection(server->config->server_info->server_ip,
605 SILC_LOG_ERROR(("Could not connect to router %s:%d",
606 sconn->remote_host, sconn->remote_port));
607 if (!sconn->no_reconnect)
608 silc_schedule_task_add(server->schedule, fd,
609 silc_server_connect_to_router_retry,
610 context, 0, 1, SILC_TASK_TIMEOUT,
611 SILC_TASK_PRI_NORMAL);
615 /* Continue with key exchange protocol */
616 silc_server_start_key_exchange(server, sconn, sock);
619 /* This function connects to our primary router or if we are a router this
620 establishes all our primary routes. This is called at the start of the
621 server to do authentication and key exchange with our router - called
624 SILC_TASK_CALLBACK(silc_server_connect_to_router)
626 SilcServer server = (SilcServer)context;
627 SilcServerConnection sconn;
628 SilcServerConfigRouter *ptr;
630 SILC_LOG_DEBUG(("Connecting to router(s)"));
632 if (server->server_type == SILC_SERVER) {
633 SILC_LOG_DEBUG(("We are normal server"));
634 } else if (server->server_type == SILC_ROUTER) {
635 SILC_LOG_DEBUG(("We are router"));
637 SILC_LOG_DEBUG(("We are backup router/normal server"));
640 /* Create the connections to all our routes */
641 ptr = server->config->routers;
644 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
645 ptr->backup_router ? "Backup router" : "Router",
646 ptr->initiator ? "Initiator" : "Responder",
647 ptr->host, ptr->port));
649 if (ptr->initiator) {
650 /* Allocate connection object for hold connection specific stuff. */
651 sconn = silc_calloc(1, sizeof(*sconn));
652 sconn->server = server;
653 sconn->remote_host = strdup(ptr->host);
654 sconn->remote_port = ptr->port;
655 sconn->backup = ptr->backup_router;
657 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
658 sconn->backup_replace_port = ptr->backup_replace_port;
661 if (!server->router_conn && !sconn->backup)
662 server->router_conn = sconn;
665 sconn->param = ptr->param;
667 silc_schedule_task_add(server->schedule, fd,
668 silc_server_connect_router,
669 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
670 SILC_TASK_PRI_NORMAL);
679 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
681 /* There wasn't a configured router, we will continue but we don't
682 have a connection to outside world. We will be standalone server. */
683 server->standalone = TRUE;
686 /* Second part of connecting to router(s). Key exchange protocol has been
687 executed and now we will execute authentication protocol. */
689 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
691 SilcProtocol protocol = (SilcProtocol)context;
692 SilcServerKEInternalContext *ctx =
693 (SilcServerKEInternalContext *)protocol->context;
694 SilcServer server = (SilcServer)ctx->server;
695 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
696 SilcSocketConnection sock = ctx->sock;
697 SilcServerConnAuthInternalContext *proto_ctx;
698 SilcServerConfigRouter *conn = NULL;
700 SILC_LOG_DEBUG(("Start"));
702 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
703 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
704 /* Error occured during protocol */
705 silc_protocol_free(protocol);
706 sock->protocol = NULL;
707 silc_ske_free_key_material(ctx->keymat);
709 silc_packet_context_free(ctx->packet);
711 silc_ske_free(ctx->ske);
712 silc_free(ctx->dest_id);
714 silc_schedule_task_del_by_callback(server->schedule,
715 silc_server_failure_callback);
716 silc_server_disconnect_remote(server, sock, "Server closed connection: "
717 "Key exchange failed");
721 /* We now have the key material as the result of the key exchange
722 protocol. Take the key material into use. Free the raw key material
723 as soon as we've set them into use. */
724 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
725 ctx->sock, ctx->keymat,
726 ctx->ske->prop->cipher,
727 ctx->ske->prop->pkcs,
728 ctx->ske->prop->hash,
729 ctx->ske->prop->hmac,
730 ctx->ske->prop->group,
732 silc_protocol_free(protocol);
733 sock->protocol = NULL;
734 silc_ske_free_key_material(ctx->keymat);
736 silc_packet_context_free(ctx->packet);
738 silc_ske_free(ctx->ske);
739 silc_free(ctx->dest_id);
741 silc_schedule_task_del_by_callback(server->schedule,
742 silc_server_failure_callback);
743 silc_server_disconnect_remote(server, sock, "Server closed connection: "
744 "Key exchange failed");
747 silc_ske_free_key_material(ctx->keymat);
749 /* Allocate internal context for the authentication protocol. This
750 is sent as context for the protocol. */
751 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
752 proto_ctx->server = (void *)server;
753 proto_ctx->context = (void *)sconn;
754 proto_ctx->sock = sock;
755 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
756 proto_ctx->dest_id_type = ctx->dest_id_type;
757 proto_ctx->dest_id = ctx->dest_id;
759 /* Resolve the authentication method used in this connection. Check if
760 we find a match from user configured connections */
762 conn = silc_server_config_find_router_conn(server, sock->hostname,
768 /* Match found. Use the configured authentication method */
769 if (conn->passphrase) {
770 if (conn->publickey && !server->config->prefer_passphrase_auth) {
771 proto_ctx->auth_data = conn->publickey;
772 proto_ctx->auth_data_len = 0;
773 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
775 proto_ctx->auth_data = strdup(conn->passphrase);
776 proto_ctx->auth_data_len = strlen(conn->passphrase);
777 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
779 } else if (conn->publickey) {
780 proto_ctx->auth_data = conn->publickey;
781 proto_ctx->auth_data_len = 0;
782 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
784 proto_ctx->auth_meth = SILC_AUTH_NONE;
787 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
788 sock->hostname, sock->ip, sock->port));
789 silc_protocol_free(protocol);
790 sock->protocol = NULL;
792 silc_packet_context_free(ctx->packet);
794 silc_ske_free(ctx->ske);
795 silc_free(ctx->dest_id);
797 silc_schedule_task_del_by_callback(server->schedule,
798 silc_server_failure_callback);
799 silc_server_disconnect_remote(server, sock, "Server closed connection: "
800 "Key exchange failed");
804 /* Free old protocol as it is finished now */
805 silc_protocol_free(protocol);
807 silc_packet_context_free(ctx->packet);
809 sock->protocol = NULL;
811 /* Allocate the authentication protocol. This is allocated here
812 but we won't start it yet. We will be receiving party of this
813 protocol thus we will wait that connecting party will make
815 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
816 &sock->protocol, proto_ctx,
817 silc_server_connect_to_router_final);
819 /* Register timeout task. If the protocol is not executed inside
820 this timelimit the connection will be terminated. */
821 proto_ctx->timeout_task =
822 silc_schedule_task_add(server->schedule, sock->sock,
823 silc_server_timeout_remote,
825 server->config->conn_auth_timeout, 0,
829 /* Run the protocol */
830 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
833 /* Finalizes the connection to router. Registers a server task to the
834 queue so that we can accept new connections. */
836 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
838 SilcProtocol protocol = (SilcProtocol)context;
839 SilcServerConnAuthInternalContext *ctx =
840 (SilcServerConnAuthInternalContext *)protocol->context;
841 SilcServer server = (SilcServer)ctx->server;
842 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
843 SilcSocketConnection sock = ctx->sock;
844 SilcServerEntry id_entry;
846 SilcServerHBContext hb_context;
847 unsigned char *id_string;
849 SilcIDListData idata;
850 SilcServerConfigConnParams *param;
852 SILC_LOG_DEBUG(("Start"));
854 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
855 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
856 /* Error occured during protocol */
857 silc_free(ctx->dest_id);
858 silc_server_disconnect_remote(server, sock, "Server closed connection: "
859 "Authentication failed");
863 /* Add a task to the queue. This task receives new connections to the
864 server. This task remains on the queue until the end of the program. */
865 if (!server->listenning && !sconn->backup) {
866 silc_schedule_task_add(server->schedule, server->sock,
867 silc_server_accept_new_connection,
868 (void *)server, 0, 0,
870 SILC_TASK_PRI_NORMAL);
871 server->listenning = TRUE;
874 /* Send NEW_SERVER packet to the router. We will become registered
875 to the SILC network after sending this packet. */
876 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
877 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
878 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
879 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
880 silc_buffer_format(packet,
881 SILC_STR_UI_SHORT(id_len),
882 SILC_STR_UI_XNSTRING(id_string, id_len),
883 SILC_STR_UI_SHORT(strlen(server->server_name)),
884 SILC_STR_UI_XNSTRING(server->server_name,
885 strlen(server->server_name)),
888 /* Send the packet */
889 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
890 packet->data, packet->len, TRUE);
891 silc_buffer_free(packet);
892 silc_free(id_string);
894 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
896 /* Check that we do not have this ID already */
897 id_entry = silc_idlist_find_server_by_id(server->local_list,
898 ctx->dest_id, TRUE, NULL);
900 silc_idcache_del_by_context(server->local_list->servers, id_entry);
902 id_entry = silc_idlist_find_server_by_id(server->global_list,
903 ctx->dest_id, TRUE, NULL);
905 silc_idcache_del_by_context(server->global_list->servers, id_entry);
908 SILC_LOG_DEBUG(("New server id(%s)",
909 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
911 /* Add the connected router to global server list */
912 id_entry = silc_idlist_add_server(server->global_list,
913 strdup(sock->hostname),
914 SILC_ROUTER, ctx->dest_id, NULL, sock);
916 silc_free(ctx->dest_id);
917 silc_server_disconnect_remote(server, sock, "Server closed connection: "
918 "Authentication failed");
922 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
923 silc_free(sock->user_data);
924 sock->user_data = (void *)id_entry;
925 sock->type = SILC_SOCKET_TYPE_ROUTER;
926 idata = (SilcIDListData)sock->user_data;
927 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
929 param = (sconn->param ? sconn->param : &server->config->param);
931 /* Perform keepalive. The `hb_context' will be freed automatically
932 when finally calling the silc_socket_free function. */
933 hb_context = silc_calloc(1, sizeof(*hb_context));
934 hb_context->server = server;
935 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
936 silc_server_perform_heartbeat,
939 /* Register re-key timeout */
940 idata->rekey->timeout = param->key_exchange_rekey;
941 idata->rekey->context = (void *)server;
942 silc_schedule_task_add(server->schedule, sock->sock,
943 silc_server_rekey_callback,
944 (void *)sock, idata->rekey->timeout, 0,
945 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
947 if (!sconn->backup) {
948 /* Mark this router our primary router if we're still standalone */
949 if (server->standalone) {
950 server->id_entry->router = id_entry;
951 server->router = id_entry;
952 server->standalone = FALSE;
954 /* If we are router then announce our possible servers. */
955 if (server->server_type == SILC_ROUTER)
956 silc_server_announce_servers(server, FALSE, 0,
957 server->router->connection);
959 /* Announce our clients and channels to the router */
960 silc_server_announce_clients(server, 0, server->router->connection);
961 silc_server_announce_channels(server, 0, server->router->connection);
964 /* Add this server to be our backup router */
965 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
966 sconn->backup_replace_port, FALSE);
969 sock->protocol = NULL;
971 /* Call the completion callback to indicate that we've connected to
974 (*sconn->callback)(server, id_entry, sconn->callback_context);
977 /* Free the temporary connection data context */
979 silc_free(sconn->remote_host);
980 silc_free(sconn->backup_replace_ip);
983 if (sconn == server->router_conn)
984 server->router_conn = NULL;
986 /* Free the protocol object */
987 if (sock->protocol == protocol)
988 sock->protocol = NULL;
989 silc_protocol_free(protocol);
991 silc_packet_context_free(ctx->packet);
993 silc_ske_free(ctx->ske);
994 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
995 silc_free(ctx->auth_data);
999 /* Host lookup callbcak that is called after the incoming connection's
1000 IP and FQDN lookup is performed. This will actually check the acceptance
1001 of the incoming connection and will register the key exchange protocol
1002 for this connection. */
1005 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1008 SilcServer server = (SilcServer)context;
1009 SilcServerKEInternalContext *proto_ctx;
1010 SilcServerConfigClient *cconfig = NULL;
1011 SilcServerConfigServer *sconfig = NULL;
1012 SilcServerConfigRouter *rconfig = NULL;
1013 SilcServerConfigDeny *deny;
1016 SILC_LOG_DEBUG(("Start"));
1018 /* Check whether we could resolve both IP and FQDN. */
1019 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1020 server->config->require_reverse_lookup)) {
1021 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1022 sock->hostname ? sock->hostname :
1023 sock->ip ? sock->ip : ""));
1024 server->stat.conn_failures++;
1025 silc_server_disconnect_remote(server, sock,
1026 "Server closed connection: Unknown host");
1030 /* Register the connection for network input and output. This sets
1031 that scheduler will listen for incoming packets for this connection
1032 and sets that outgoing packets may be sent to this connection as well.
1033 However, this doesn't set the scheduler for outgoing traffic, it
1034 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1035 later when outgoing data is available. */
1036 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1038 SILC_LOG_INFO(("Incoming connection from %s (%s)", sock->hostname,
1041 port = server->sockets[server->sock]->port; /* Listenning port */
1043 /* Check whether this connection is denied to connect to us. */
1044 deny = silc_server_config_find_denied(server, sock->ip);
1046 deny = silc_server_config_find_denied(server, sock->hostname);
1048 /* The connection is denied */
1049 SILC_LOG_INFO(("Connection %s (%s) is denied",
1050 sock->hostname, sock->ip));
1051 silc_server_disconnect_remote(server, sock, deny->reason ?
1053 "Server closed connection: "
1054 "Connection refused");
1055 server->stat.conn_failures++;
1059 /* Check whether we have configred this sort of connection at all. We
1060 have to check all configurations since we don't know what type of
1061 connection this is. */
1062 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1063 cconfig = silc_server_config_find_client(server, sock->hostname);
1064 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1065 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1066 if (server->server_type == SILC_ROUTER) {
1067 if (!(rconfig = silc_server_config_find_router_conn(server,
1069 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1072 if (!cconfig && !sconfig && !rconfig) {
1073 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1075 silc_server_disconnect_remote(server, sock,
1076 "Server closed connection: "
1077 "Connection refused");
1078 server->stat.conn_failures++;
1082 /* The connection is allowed */
1084 /* Allocate internal context for key exchange protocol. This is
1085 sent as context for the protocol. */
1086 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1087 proto_ctx->server = context;
1088 proto_ctx->sock = sock;
1089 proto_ctx->rng = server->rng;
1090 proto_ctx->responder = TRUE;
1091 proto_ctx->cconfig = cconfig;
1092 proto_ctx->sconfig = sconfig;
1093 proto_ctx->rconfig = rconfig;
1095 /* Take flags for key exchange. Since we do not know what type of connection
1096 this is, we go through all found configuratios and use the global ones
1097 as well. This will result always into strictest key exchange flags. */
1098 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1099 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1100 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1101 if (server->config->param.key_exchange_pfs)
1102 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1104 /* Prepare the connection for key exchange protocol. We allocate the
1105 protocol but will not start it yet. The connector will be the
1106 initiator of the protocol thus we will wait for initiation from
1107 there before we start the protocol. */
1108 server->stat.auth_attempts++;
1109 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1110 &sock->protocol, proto_ctx,
1111 silc_server_accept_new_connection_second);
1113 /* Register a timeout task that will be executed if the connector
1114 will not start the key exchange protocol within specified timeout
1115 and the connection will be closed. */
1116 proto_ctx->timeout_task =
1117 silc_schedule_task_add(server->schedule, sock->sock,
1118 silc_server_timeout_remote,
1119 context, server->config->key_exchange_timeout, 0,
1124 /* Accepts new connections to the server. Accepting new connections are
1125 done in three parts to make it async. */
1127 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1129 SilcServer server = (SilcServer)context;
1130 SilcSocketConnection newsocket;
1133 SILC_LOG_DEBUG(("Accepting new connection"));
1135 server->stat.conn_attempts++;
1137 sock = silc_net_accept_connection(server->sock);
1139 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1140 server->stat.conn_failures++;
1144 /* Check for maximum allowed connections */
1145 if (sock > server->config->param.connections_max) {
1146 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1147 server->stat.conn_failures++;
1151 /* Set socket options */
1152 silc_net_set_socket_nonblock(sock);
1153 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1155 /* We don't create a ID yet, since we don't know what type of connection
1156 this is yet. But, we do add the connection to the socket table. */
1157 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1158 server->sockets[sock] = newsocket;
1160 /* Perform asynchronous host lookup. This will lookup the IP and the
1161 FQDN of the remote connection. After the lookup is done the connection
1162 is accepted further. */
1163 silc_socket_host_lookup(newsocket, TRUE,
1164 silc_server_accept_new_connection_lookup, context,
1168 /* Second part of accepting new connection. Key exchange protocol has been
1169 performed and now it is time to do little connection authentication
1170 protocol to figure out whether this connection is client or server
1171 and whether it has right to access this server (especially server
1172 connections needs to be authenticated). */
1174 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1176 SilcProtocol protocol = (SilcProtocol)context;
1177 SilcServerKEInternalContext *ctx =
1178 (SilcServerKEInternalContext *)protocol->context;
1179 SilcServer server = (SilcServer)ctx->server;
1180 SilcSocketConnection sock = ctx->sock;
1181 SilcServerConnAuthInternalContext *proto_ctx;
1183 SILC_LOG_DEBUG(("Start"));
1185 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1186 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1187 /* Error occured during protocol */
1188 silc_protocol_free(protocol);
1189 sock->protocol = NULL;
1190 silc_ske_free_key_material(ctx->keymat);
1192 silc_packet_context_free(ctx->packet);
1194 silc_ske_free(ctx->ske);
1195 silc_free(ctx->dest_id);
1197 silc_schedule_task_del_by_callback(server->schedule,
1198 silc_server_failure_callback);
1199 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1200 "Key exchange failed");
1201 server->stat.auth_failures++;
1205 /* We now have the key material as the result of the key exchange
1206 protocol. Take the key material into use. Free the raw key material
1207 as soon as we've set them into use. */
1208 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1209 ctx->sock, ctx->keymat,
1210 ctx->ske->prop->cipher,
1211 ctx->ske->prop->pkcs,
1212 ctx->ske->prop->hash,
1213 ctx->ske->prop->hmac,
1214 ctx->ske->prop->group,
1216 silc_protocol_free(protocol);
1217 sock->protocol = NULL;
1218 silc_ske_free_key_material(ctx->keymat);
1220 silc_packet_context_free(ctx->packet);
1222 silc_ske_free(ctx->ske);
1223 silc_free(ctx->dest_id);
1225 silc_schedule_task_del_by_callback(server->schedule,
1226 silc_server_failure_callback);
1227 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1228 "Key exchange failed");
1229 server->stat.auth_failures++;
1232 silc_ske_free_key_material(ctx->keymat);
1234 /* Allocate internal context for the authentication protocol. This
1235 is sent as context for the protocol. */
1236 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1237 proto_ctx->server = (void *)server;
1238 proto_ctx->sock = sock;
1239 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1240 proto_ctx->responder = TRUE;
1241 proto_ctx->dest_id_type = ctx->dest_id_type;
1242 proto_ctx->dest_id = ctx->dest_id;
1243 proto_ctx->cconfig = ctx->cconfig;
1244 proto_ctx->sconfig = ctx->sconfig;
1245 proto_ctx->rconfig = ctx->rconfig;
1247 /* Free old protocol as it is finished now */
1248 silc_protocol_free(protocol);
1250 silc_packet_context_free(ctx->packet);
1252 sock->protocol = NULL;
1254 /* Allocate the authentication protocol. This is allocated here
1255 but we won't start it yet. We will be receiving party of this
1256 protocol thus we will wait that connecting party will make
1257 their first move. */
1258 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1259 &sock->protocol, proto_ctx,
1260 silc_server_accept_new_connection_final);
1262 /* Register timeout task. If the protocol is not executed inside
1263 this timelimit the connection will be terminated. */
1264 proto_ctx->timeout_task =
1265 silc_schedule_task_add(server->schedule, sock->sock,
1266 silc_server_timeout_remote,
1268 server->config->conn_auth_timeout, 0,
1273 /* Final part of accepting new connection. The connection has now
1274 been authenticated and keys has been exchanged. We also know whether
1275 this is client or server connection. */
1277 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1279 SilcProtocol protocol = (SilcProtocol)context;
1280 SilcServerConnAuthInternalContext *ctx =
1281 (SilcServerConnAuthInternalContext *)protocol->context;
1282 SilcServer server = (SilcServer)ctx->server;
1283 SilcSocketConnection sock = ctx->sock;
1284 SilcServerHBContext hb_context;
1285 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1287 uint32 hearbeat_timeout = server->config->param.keepalive_secs;
1290 SILC_LOG_DEBUG(("Start"));
1292 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1293 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1294 /* Error occured during protocol */
1295 silc_protocol_free(protocol);
1296 sock->protocol = NULL;
1298 silc_packet_context_free(ctx->packet);
1300 silc_ske_free(ctx->ske);
1301 silc_free(ctx->dest_id);
1303 silc_schedule_task_del_by_callback(server->schedule,
1304 silc_server_failure_callback);
1305 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1306 "Authentication failed");
1307 server->stat.auth_failures++;
1311 entry->data.last_receive = time(NULL);
1313 num_sockets = silc_server_num_sockets_by_ip(server, sock->ip);
1315 switch (ctx->conn_type) {
1316 case SILC_SOCKET_TYPE_CLIENT:
1318 SilcClientEntry client;
1319 SilcServerConfigClient *conn = ctx->cconfig;
1320 uint32 max_per_host = server->config->param.connections_max_per_host;
1322 /* Check for maximum connections limit */
1324 if (conn->param->connections_max &&
1325 server->stat.my_clients >= conn->param->connections_max) {
1326 silc_server_disconnect_remote(server, sock,
1327 "Server closed connection: "
1328 "Server is full, try again later");
1329 server->stat.auth_failures++;
1333 max_per_host = conn->param->connections_max_per_host;
1336 if (num_sockets > max_per_host) {
1337 silc_server_disconnect_remote(server, sock,
1338 "Server closed connection: "
1339 "Too many connections from your host");
1340 server->stat.auth_failures++;
1344 SILC_LOG_DEBUG(("Remote host is client"));
1345 SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1348 /* Add the client to the client ID cache. The nickname and Client ID
1349 and other information is created after we have received NEW_CLIENT
1350 packet from client. */
1351 client = silc_idlist_add_client(server->local_list,
1352 NULL, NULL, NULL, NULL, NULL, sock, 0);
1354 SILC_LOG_ERROR(("Could not add new client to cache"));
1355 silc_free(sock->user_data);
1356 silc_server_disconnect_remote(server, sock,
1357 "Server closed connection: "
1358 "Authentication failed");
1359 server->stat.auth_failures++;
1364 server->stat.my_clients++;
1365 server->stat.clients++;
1366 if (server->server_type == SILC_ROUTER)
1367 server->stat.cell_clients++;
1369 /* Get connection parameters */
1371 if (conn->param->keepalive_secs)
1372 hearbeat_timeout = conn->param->keepalive_secs;
1375 id_entry = (void *)client;
1378 case SILC_SOCKET_TYPE_SERVER:
1379 case SILC_SOCKET_TYPE_ROUTER:
1381 SilcServerEntry new_server;
1382 bool initiator = FALSE;
1383 bool backup_local = FALSE;
1384 bool backup_router = FALSE;
1385 char *backup_replace_ip = NULL;
1386 uint16 backup_replace_port = 0;
1387 SilcServerConfigServer *sconn = ctx->sconfig;
1388 SilcServerConfigRouter *rconn = ctx->rconfig;
1389 uint32 max_per_host = server->config->param.connections_max_per_host;
1391 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && rconn) {
1393 /* Check for maximum connections limit */
1394 if (rconn->param->connections_max &&
1395 server->stat.my_routers >= rconn->param->connections_max) {
1396 silc_server_disconnect_remote(server, sock,
1397 "Server closed connection: "
1398 "Server is full, try again later");
1399 server->stat.auth_failures++;
1402 max_per_host = rconn->param->connections_max_per_host;
1404 if (rconn->param->keepalive_secs)
1405 hearbeat_timeout = rconn->param->keepalive_secs;
1408 initiator = rconn->initiator;
1409 backup_local = rconn->backup_local;
1410 backup_router = rconn->backup_router;
1411 backup_replace_ip = rconn->backup_replace_ip;
1412 backup_replace_port = rconn->backup_replace_port;
1415 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER && sconn) {
1417 /* Check for maximum connections limit */
1418 if (sconn->param->connections_max &&
1419 server->stat.my_servers >= sconn->param->connections_max) {
1420 silc_server_disconnect_remote(server, sock,
1421 "Server closed connection: "
1422 "Server is full, try again later");
1423 server->stat.auth_failures++;
1426 max_per_host = sconn->param->connections_max_per_host;
1428 if (sconn->param->keepalive_secs)
1429 hearbeat_timeout = sconn->param->keepalive_secs;
1432 backup_router = sconn->backup_router;
1435 if (num_sockets > max_per_host) {
1436 silc_server_disconnect_remote(server, sock,
1437 "Server closed connection: "
1438 "Too many connections from your host");
1439 server->stat.auth_failures++;
1443 SILC_LOG_DEBUG(("Remote host is %s",
1444 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1445 "server" : (backup_router ?
1446 "backup router" : "router")));
1447 SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1448 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1449 "server" : (backup_router ?
1450 "backup router" : "router")));
1452 /* Add the server into server cache. The server name and Server ID
1453 is updated after we have received NEW_SERVER packet from the
1454 server. We mark ourselves as router for this server if we really
1457 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1458 server->local_list : (backup_router ?
1459 server->local_list :
1460 server->global_list)),
1462 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1463 SILC_SERVER : SILC_ROUTER),
1465 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1466 server->id_entry : (backup_router ?
1467 server->id_entry : NULL)),
1470 SILC_LOG_ERROR(("Could not add new server to cache"));
1471 silc_free(sock->user_data);
1472 silc_server_disconnect_remote(server, sock,
1473 "Server closed connection: "
1474 "Authentication failed");
1475 server->stat.auth_failures++;
1480 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1481 server->stat.my_servers++;
1483 server->stat.my_routers++;
1484 server->stat.servers++;
1486 id_entry = (void *)new_server;
1488 /* If the incoming connection is router and marked as backup router
1489 then add it to be one of our backups */
1490 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1491 silc_server_backup_add(server, new_server, backup_replace_ip,
1492 backup_replace_port, backup_local);
1494 /* Change it back to SERVER type since that's what it really is. */
1496 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1498 new_server->server_type = SILC_BACKUP_ROUTER;
1501 /* Check whether this connection is to be our primary router connection
1502 if we do not already have the primary route. */
1503 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1504 if (silc_server_config_is_primary_route(server) && !initiator)
1507 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1508 server->standalone = FALSE;
1509 if (!server->id_entry->router) {
1510 server->id_entry->router = id_entry;
1511 server->router = id_entry;
1522 sock->type = ctx->conn_type;
1524 /* Add the common data structure to the ID entry. */
1525 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1527 /* Add to sockets internal pointer for fast referencing */
1528 silc_free(sock->user_data);
1529 sock->user_data = id_entry;
1531 /* Connection has been fully established now. Everything is ok. */
1532 SILC_LOG_DEBUG(("New connection authenticated"));
1534 /* Perform keepalive. The `hb_context' will be freed automatically
1535 when finally calling the silc_socket_free function. */
1536 hb_context = silc_calloc(1, sizeof(*hb_context));
1537 hb_context->server = server;
1538 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1539 silc_server_perform_heartbeat,
1543 silc_schedule_task_del_by_callback(server->schedule,
1544 silc_server_failure_callback);
1545 silc_protocol_free(protocol);
1547 silc_packet_context_free(ctx->packet);
1549 silc_ske_free(ctx->ske);
1550 silc_free(ctx->dest_id);
1552 sock->protocol = NULL;
1555 /* This function is used to read packets from network and send packets to
1556 network. This is usually a generic task. */
1558 SILC_TASK_CALLBACK(silc_server_packet_process)
1560 SilcServer server = (SilcServer)context;
1561 SilcSocketConnection sock = server->sockets[fd];
1562 SilcIDListData idata;
1563 SilcCipher cipher = NULL;
1564 SilcHmac hmac = NULL;
1565 uint32 sequence = 0;
1571 SILC_LOG_DEBUG(("Processing packet"));
1573 /* Packet sending */
1575 if (type == SILC_TASK_WRITE) {
1576 /* Do not send data to disconnected connection */
1577 if (SILC_IS_DISCONNECTED(sock))
1580 server->stat.packets_sent++;
1582 if (sock->outbuf->data - sock->outbuf->head)
1583 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1585 /* Send the packet */
1586 ret = silc_packet_send(sock, TRUE);
1588 /* If returned -2 could not write to connection now, will do
1594 SILC_LOG_ERROR(("Error sending packet to connection "
1595 "%s:%d [%s]", sock->hostname, sock->port,
1596 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1597 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1598 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1603 /* The packet has been sent and now it is time to set the connection
1604 back to only for input. When there is again some outgoing data
1605 available for this connection it will be set for output as well.
1606 This call clears the output setting and sets it only for input. */
1607 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1608 SILC_UNSET_OUTBUF_PENDING(sock);
1610 silc_buffer_clear(sock->outbuf);
1614 /* Packet receiving */
1616 /* Read some data from connection */
1617 ret = silc_packet_receive(sock);
1621 SILC_LOG_ERROR(("Error receiving packet from connection "
1622 "%s:%d [%s] %s", sock->hostname, sock->port,
1623 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1624 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1625 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1626 "Router"), strerror(errno)));
1632 SILC_LOG_DEBUG(("Read EOF"));
1634 /* If connection is disconnecting already we will finally
1635 close the connection */
1636 if (SILC_IS_DISCONNECTING(sock)) {
1637 if (sock->user_data)
1638 silc_server_free_sock_user_data(server, sock, NULL);
1639 silc_server_close_connection(server, sock);
1643 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1644 SILC_SET_DISCONNECTING(sock);
1646 if (sock->user_data) {
1648 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1649 silc_server_free_sock_user_data(server, sock, tmp);
1651 silc_server_free_sock_user_data(server, sock, NULL);
1652 } else if (server->router_conn && server->router_conn->sock == sock &&
1653 !server->router && server->standalone)
1654 silc_schedule_task_add(server->schedule, 0,
1655 silc_server_connect_to_router,
1658 SILC_TASK_PRI_NORMAL);
1660 silc_server_close_connection(server, sock);
1664 /* If connection is disconnecting or disconnected we will ignore
1666 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1667 SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1671 server->stat.packets_received++;
1673 /* Get keys and stuff from ID entry */
1674 idata = (SilcIDListData)sock->user_data;
1676 cipher = idata->receive_key;
1677 hmac = idata->hmac_receive;
1678 sequence = idata->psn_receive;
1681 /* Process the packet. This will call the parser that will then
1682 decrypt and parse the packet. */
1683 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1684 TRUE : FALSE, cipher, hmac, sequence,
1685 silc_server_packet_parse, server);
1687 /* If this socket connection is not authenticated yet and the packet
1688 processing failed we will drop the connection since it can be
1689 a malicious flooder. */
1690 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1691 (!sock->protocol || sock->protocol->protocol->type ==
1692 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1693 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1694 SILC_SET_DISCONNECTING(sock);
1696 if (sock->user_data)
1697 silc_server_free_sock_user_data(server, sock, NULL);
1698 silc_server_close_connection(server, sock);
1702 /* Parses whole packet, received earlier. */
1704 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1706 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1707 SilcServer server = (SilcServer)parse_ctx->context;
1708 SilcSocketConnection sock = parse_ctx->sock;
1709 SilcPacketContext *packet = parse_ctx->packet;
1710 SilcIDListData idata = (SilcIDListData)sock->user_data;
1713 SILC_LOG_DEBUG(("Start"));
1715 /* Parse the packet */
1716 if (parse_ctx->normal)
1717 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1719 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1721 /* If entry is disabled ignore what we got. */
1722 if (ret != SILC_PACKET_RESUME_ROUTER &&
1723 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1724 SILC_LOG_DEBUG(("Connection is disabled"));
1728 if (ret == SILC_PACKET_NONE)
1731 /* Check that the the current client ID is same as in the client's packet. */
1732 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1733 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1734 if (client && client->id) {
1735 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1736 packet->src_id_type);
1737 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1745 if (server->server_type == SILC_ROUTER) {
1746 /* Route the packet if it is not destined to us. Other ID types but
1747 server are handled separately after processing them. */
1748 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1749 packet->dst_id_type == SILC_ID_SERVER &&
1750 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1751 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1753 /* Route the packet to fastest route for the destination ID */
1754 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1755 packet->dst_id_type);
1758 silc_server_packet_route(server,
1759 silc_server_route_get(server, id,
1760 packet->dst_id_type),
1767 /* Parse the incoming packet type */
1768 silc_server_packet_parse_type(server, sock, packet);
1770 if (server->server_type == SILC_ROUTER) {
1771 /* Broadcast packet if it is marked as broadcast packet and it is
1772 originated from router and we are router. */
1773 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1774 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1775 !server->standalone) {
1776 /* Broadcast to our primary route */
1777 silc_server_packet_broadcast(server, server->router->connection, packet);
1779 /* If we have backup routers then we need to feed all broadcast
1780 data to those servers. */
1781 silc_server_backup_broadcast(server, sock, packet);
1786 silc_packet_context_free(packet);
1787 silc_free(parse_ctx);
1790 /* Parser callback called by silc_packet_receive_process. This merely
1791 registers timeout that will handle the actual parsing when appropriate. */
1793 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1796 SilcServer server = (SilcServer)context;
1797 SilcSocketConnection sock = parser_context->sock;
1798 SilcIDListData idata = (SilcIDListData)sock->user_data;
1801 idata->psn_receive = parser_context->packet->sequence + 1;
1803 /* If protocol for this connection is key exchange or rekey then we'll
1804 process all packets synchronously, since there might be packets in
1805 queue that we are not able to decrypt without first processing the
1806 packets before them. */
1807 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1808 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1809 (sock->protocol && sock->protocol->protocol &&
1810 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1811 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1812 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1815 /* Reprocess data since we'll return FALSE here. This is because
1816 the idata->receive_key might have become valid in the last packet
1817 and we want to call this processor with valid cipher. */
1819 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1820 TRUE : FALSE, idata->receive_key,
1821 idata->hmac_receive, idata->psn_receive,
1822 silc_server_packet_parse, server);
1824 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1825 TRUE : FALSE, NULL, NULL, 0,
1826 silc_server_packet_parse, server);
1830 switch (sock->type) {
1831 case SILC_SOCKET_TYPE_UNKNOWN:
1832 case SILC_SOCKET_TYPE_CLIENT:
1833 /* Parse the packet with timeout */
1834 silc_schedule_task_add(server->schedule, sock->sock,
1835 silc_server_packet_parse_real,
1836 (void *)parser_context, 0, 100000,
1838 SILC_TASK_PRI_NORMAL);
1840 case SILC_SOCKET_TYPE_SERVER:
1841 case SILC_SOCKET_TYPE_ROUTER:
1842 /* Packets from servers are parsed immediately */
1843 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1853 /* Parses the packet type and calls what ever routines the packet type
1854 requires. This is done for all incoming packets. */
1856 void silc_server_packet_parse_type(SilcServer server,
1857 SilcSocketConnection sock,
1858 SilcPacketContext *packet)
1860 SilcPacketType type = packet->type;
1861 SilcIDListData idata = (SilcIDListData)sock->user_data;
1863 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1865 /* Parse the packet type */
1867 case SILC_PACKET_DISCONNECT:
1868 SILC_LOG_DEBUG(("Disconnect packet"));
1869 if (packet->flags & SILC_PACKET_FLAG_LIST)
1873 case SILC_PACKET_SUCCESS:
1875 * Success received for something. For now we can have only
1876 * one protocol for connection executing at once hence this
1877 * success message is for whatever protocol is executing currently.
1879 SILC_LOG_DEBUG(("Success packet"));
1880 if (packet->flags & SILC_PACKET_FLAG_LIST)
1883 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1886 case SILC_PACKET_FAILURE:
1888 * Failure received for something. For now we can have only
1889 * one protocol for connection executing at once hence this
1890 * failure message is for whatever protocol is executing currently.
1892 SILC_LOG_DEBUG(("Failure packet"));
1893 if (packet->flags & SILC_PACKET_FLAG_LIST)
1895 if (sock->protocol) {
1896 SilcServerFailureContext f;
1897 f = silc_calloc(1, sizeof(*f));
1901 /* We will wait 5 seconds to process this failure packet */
1902 silc_schedule_task_add(server->schedule, sock->sock,
1903 silc_server_failure_callback, (void *)f, 5, 0,
1904 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1908 case SILC_PACKET_REJECT:
1909 SILC_LOG_DEBUG(("Reject packet"));
1910 if (packet->flags & SILC_PACKET_FLAG_LIST)
1915 case SILC_PACKET_NOTIFY:
1917 * Received notify packet. Server can receive notify packets from
1918 * router. Server then relays the notify messages to clients if needed.
1920 SILC_LOG_DEBUG(("Notify packet"));
1921 if (packet->flags & SILC_PACKET_FLAG_LIST)
1922 silc_server_notify_list(server, sock, packet);
1924 silc_server_notify(server, sock, packet);
1930 case SILC_PACKET_CHANNEL_MESSAGE:
1932 * Received channel message. Channel messages are special packets
1933 * (although probably most common ones) thus they are handled
1936 SILC_LOG_DEBUG(("Channel Message packet"));
1937 if (packet->flags & SILC_PACKET_FLAG_LIST)
1939 idata->last_receive = time(NULL);
1940 silc_server_channel_message(server, sock, packet);
1943 case SILC_PACKET_CHANNEL_KEY:
1945 * Received key for channel. As channels are created by the router
1946 * the keys are as well. We will distribute the key to all of our
1947 * locally connected clients on the particular channel. Router
1948 * never receives this channel and thus is ignored.
1950 SILC_LOG_DEBUG(("Channel Key packet"));
1951 if (packet->flags & SILC_PACKET_FLAG_LIST)
1953 silc_server_channel_key(server, sock, packet);
1959 case SILC_PACKET_COMMAND:
1961 * Recived command. Processes the command request and allocates the
1962 * command context and calls the command.
1964 SILC_LOG_DEBUG(("Command packet"));
1965 if (packet->flags & SILC_PACKET_FLAG_LIST)
1967 silc_server_command_process(server, sock, packet);
1970 case SILC_PACKET_COMMAND_REPLY:
1972 * Received command reply packet. Received command reply to command. It
1973 * may be reply to command sent by us or reply to command sent by client
1974 * that we've routed further.
1976 SILC_LOG_DEBUG(("Command Reply packet"));
1977 if (packet->flags & SILC_PACKET_FLAG_LIST)
1979 silc_server_command_reply(server, sock, packet);
1983 * Private Message packets
1985 case SILC_PACKET_PRIVATE_MESSAGE:
1987 * Received private message packet. The packet is coming from either
1990 SILC_LOG_DEBUG(("Private Message packet"));
1991 if (packet->flags & SILC_PACKET_FLAG_LIST)
1993 idata->last_receive = time(NULL);
1994 silc_server_private_message(server, sock, packet);
1997 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1999 * Private message key packet.
2001 if (packet->flags & SILC_PACKET_FLAG_LIST)
2003 silc_server_private_message_key(server, sock, packet);
2007 * Key Exchange protocol packets
2009 case SILC_PACKET_KEY_EXCHANGE:
2010 SILC_LOG_DEBUG(("KE packet"));
2011 if (packet->flags & SILC_PACKET_FLAG_LIST)
2014 if (sock->protocol && sock->protocol->protocol &&
2015 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2017 SilcServerKEInternalContext *proto_ctx =
2018 (SilcServerKEInternalContext *)sock->protocol->context;
2020 proto_ctx->packet = silc_packet_context_dup(packet);
2022 /* Let the protocol handle the packet */
2023 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2025 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2026 "protocol active, packet dropped."));
2030 case SILC_PACKET_KEY_EXCHANGE_1:
2031 SILC_LOG_DEBUG(("KE 1 packet"));
2032 if (packet->flags & SILC_PACKET_FLAG_LIST)
2035 if (sock->protocol && sock->protocol->protocol &&
2036 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2037 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2039 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2040 SilcServerRekeyInternalContext *proto_ctx =
2041 (SilcServerRekeyInternalContext *)sock->protocol->context;
2043 if (proto_ctx->packet)
2044 silc_packet_context_free(proto_ctx->packet);
2046 proto_ctx->packet = silc_packet_context_dup(packet);
2048 /* Let the protocol handle the packet */
2049 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2051 SilcServerKEInternalContext *proto_ctx =
2052 (SilcServerKEInternalContext *)sock->protocol->context;
2054 if (proto_ctx->packet)
2055 silc_packet_context_free(proto_ctx->packet);
2057 proto_ctx->packet = silc_packet_context_dup(packet);
2058 proto_ctx->dest_id_type = packet->src_id_type;
2059 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2060 packet->src_id_type);
2061 if (!proto_ctx->dest_id)
2064 /* Let the protocol handle the packet */
2065 silc_protocol_execute(sock->protocol, server->schedule,
2069 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2070 "protocol active, packet dropped."));
2074 case SILC_PACKET_KEY_EXCHANGE_2:
2075 SILC_LOG_DEBUG(("KE 2 packet"));
2076 if (packet->flags & SILC_PACKET_FLAG_LIST)
2079 if (sock->protocol && sock->protocol->protocol &&
2080 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2081 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2083 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2084 SilcServerRekeyInternalContext *proto_ctx =
2085 (SilcServerRekeyInternalContext *)sock->protocol->context;
2087 if (proto_ctx->packet)
2088 silc_packet_context_free(proto_ctx->packet);
2090 proto_ctx->packet = silc_packet_context_dup(packet);
2092 /* Let the protocol handle the packet */
2093 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2095 SilcServerKEInternalContext *proto_ctx =
2096 (SilcServerKEInternalContext *)sock->protocol->context;
2098 if (proto_ctx->packet)
2099 silc_packet_context_free(proto_ctx->packet);
2101 proto_ctx->packet = silc_packet_context_dup(packet);
2102 proto_ctx->dest_id_type = packet->src_id_type;
2103 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2104 packet->src_id_type);
2105 if (!proto_ctx->dest_id)
2108 /* Let the protocol handle the packet */
2109 silc_protocol_execute(sock->protocol, server->schedule,
2113 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2114 "protocol active, packet dropped."));
2118 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2120 * Connection authentication request packet. When we receive this packet
2121 * we will send to the other end information about our mandatory
2122 * authentication method for the connection. This packet maybe received
2125 SILC_LOG_DEBUG(("Connection authentication request packet"));
2126 if (packet->flags & SILC_PACKET_FLAG_LIST)
2128 silc_server_connection_auth_request(server, sock, packet);
2132 * Connection Authentication protocol packets
2134 case SILC_PACKET_CONNECTION_AUTH:
2135 /* Start of the authentication protocol. We receive here the
2136 authentication data and will verify it. */
2137 SILC_LOG_DEBUG(("Connection auth packet"));
2138 if (packet->flags & SILC_PACKET_FLAG_LIST)
2141 if (sock->protocol && sock->protocol->protocol->type
2142 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2144 SilcServerConnAuthInternalContext *proto_ctx =
2145 (SilcServerConnAuthInternalContext *)sock->protocol->context;
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 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2153 "protocol active, packet dropped."));
2157 case SILC_PACKET_NEW_ID:
2159 * Received New ID packet. This includes some new ID that has been
2160 * created. It may be for client, server or channel. This is the way
2161 * to distribute information about new registered entities in the
2164 SILC_LOG_DEBUG(("New ID packet"));
2165 if (packet->flags & SILC_PACKET_FLAG_LIST)
2166 silc_server_new_id_list(server, sock, packet);
2168 silc_server_new_id(server, sock, packet);
2171 case SILC_PACKET_NEW_CLIENT:
2173 * Received new client packet. This includes client information that
2174 * we will use to create initial client ID. After creating new
2175 * ID we will send it to the client.
2177 SILC_LOG_DEBUG(("New Client packet"));
2178 if (packet->flags & SILC_PACKET_FLAG_LIST)
2180 silc_server_new_client(server, sock, packet);
2183 case SILC_PACKET_NEW_SERVER:
2185 * Received new server packet. This includes Server ID and some other
2186 * information that we may save. This is received after server has
2189 SILC_LOG_DEBUG(("New Server packet"));
2190 if (packet->flags & SILC_PACKET_FLAG_LIST)
2192 silc_server_new_server(server, sock, packet);
2195 case SILC_PACKET_NEW_CHANNEL:
2197 * Received new channel packet. Information about new channel in the
2198 * network are distributed using this packet.
2200 SILC_LOG_DEBUG(("New Channel packet"));
2201 if (packet->flags & SILC_PACKET_FLAG_LIST)
2202 silc_server_new_channel_list(server, sock, packet);
2204 silc_server_new_channel(server, sock, packet);
2207 case SILC_PACKET_HEARTBEAT:
2209 * Received heartbeat.
2211 SILC_LOG_DEBUG(("Heartbeat packet"));
2212 if (packet->flags & SILC_PACKET_FLAG_LIST)
2216 case SILC_PACKET_KEY_AGREEMENT:
2218 * Received heartbeat.
2220 SILC_LOG_DEBUG(("Key agreement packet"));
2221 if (packet->flags & SILC_PACKET_FLAG_LIST)
2223 silc_server_key_agreement(server, sock, packet);
2226 case SILC_PACKET_REKEY:
2228 * Received re-key packet. The sender wants to regenerate the session
2231 SILC_LOG_DEBUG(("Re-key packet"));
2232 if (packet->flags & SILC_PACKET_FLAG_LIST)
2234 silc_server_rekey(server, sock, packet);
2237 case SILC_PACKET_REKEY_DONE:
2239 * The re-key is done.
2241 SILC_LOG_DEBUG(("Re-key done packet"));
2242 if (packet->flags & SILC_PACKET_FLAG_LIST)
2245 if (sock->protocol && sock->protocol->protocol &&
2246 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2248 SilcServerRekeyInternalContext *proto_ctx =
2249 (SilcServerRekeyInternalContext *)sock->protocol->context;
2251 if (proto_ctx->packet)
2252 silc_packet_context_free(proto_ctx->packet);
2254 proto_ctx->packet = silc_packet_context_dup(packet);
2256 /* Let the protocol handle the packet */
2257 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2259 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2260 "protocol active, packet dropped."));
2264 case SILC_PACKET_FTP:
2266 SILC_LOG_DEBUG(("FTP packet"));
2267 if (packet->flags & SILC_PACKET_FLAG_LIST)
2269 silc_server_ftp(server, sock, packet);
2272 case SILC_PACKET_RESUME_ROUTER:
2273 /* Resume router packet received. This packet is received for backup
2274 router resuming protocol. */
2275 SILC_LOG_DEBUG(("Resume router packet"));
2276 if (packet->flags & SILC_PACKET_FLAG_LIST)
2278 silc_server_backup_resume_router(server, sock, packet);
2282 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2288 /* Creates connection to a remote router. */
2290 void silc_server_create_connection(SilcServer server,
2291 const char *remote_host, uint32 port)
2293 SilcServerConnection sconn;
2295 /* Allocate connection object for hold connection specific stuff. */
2296 sconn = silc_calloc(1, sizeof(*sconn));
2297 sconn->server = server;
2298 sconn->remote_host = strdup(remote_host);
2299 sconn->remote_port = port;
2300 sconn->no_reconnect = TRUE;
2301 sconn->param = &server->config->param;
2303 silc_schedule_task_add(server->schedule, 0,
2304 silc_server_connect_router,
2305 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2306 SILC_TASK_PRI_NORMAL);
2309 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2311 silc_socket_free((SilcSocketConnection)context);
2314 /* Closes connection to socket connection */
2316 void silc_server_close_connection(SilcServer server,
2317 SilcSocketConnection sock)
2319 if (!server->sockets[sock->sock])
2322 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2324 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2325 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2326 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2329 /* We won't listen for this connection anymore */
2330 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2332 /* Unregister all tasks */
2333 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2335 /* Close the actual connection */
2336 silc_net_close_connection(sock->sock);
2337 server->sockets[sock->sock] = NULL;
2339 /* If sock->user_data is NULL then we'll check for active protocols
2340 here since the silc_server_free_sock_user_data has not been called
2341 for this connection. */
2342 if (!sock->user_data) {
2343 /* If any protocol is active cancel its execution. It will call
2344 the final callback which will finalize the disconnection. */
2345 if (sock->protocol) {
2346 silc_protocol_cancel(sock->protocol, server->schedule);
2347 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2348 silc_protocol_execute_final(sock->protocol, server->schedule);
2349 sock->protocol = NULL;
2354 silc_schedule_task_add(server->schedule, 0,
2355 silc_server_close_connection_final,
2356 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2357 SILC_TASK_PRI_NORMAL);
2360 /* Sends disconnect message to remote connection and disconnects the
2363 void silc_server_disconnect_remote(SilcServer server,
2364 SilcSocketConnection sock,
2365 const char *fmt, ...)
2368 unsigned char buf[4096];
2373 memset(buf, 0, sizeof(buf));
2375 vsprintf(buf, fmt, ap);
2378 SILC_LOG_DEBUG(("Disconnecting remote host"));
2380 /* Notify remote end that the conversation is over. The notify message
2381 is tried to be sent immediately. */
2382 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2383 buf, strlen(buf), TRUE);
2385 /* Mark the connection to be disconnected */
2386 SILC_SET_DISCONNECTED(sock);
2387 silc_server_close_connection(server, sock);
2392 SilcClientEntry client;
2393 } *FreeClientInternal;
2395 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2397 FreeClientInternal i = (FreeClientInternal)context;
2399 silc_idlist_del_data(i->client);
2400 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2404 /* Frees client data and notifies about client's signoff. */
2406 void silc_server_free_client_data(SilcServer server,
2407 SilcSocketConnection sock,
2408 SilcClientEntry client,
2410 const char *signoff)
2412 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2414 /* If there is pending outgoing data for the client then purge it
2415 to the network before removing the client entry. */
2416 silc_server_packet_queue_purge(server, sock);
2421 /* Send SIGNOFF notify to routers. */
2422 if (notify && !server->standalone && server->router)
2423 silc_server_send_notify_signoff(server, server->router->connection,
2424 server->server_type == SILC_SERVER ?
2425 FALSE : TRUE, client->id, signoff);
2427 /* Remove client from all channels */
2429 silc_server_remove_from_channels(server, NULL, client,
2430 TRUE, (char *)signoff, TRUE);
2432 silc_server_remove_from_channels(server, NULL, client,
2433 FALSE, NULL, FALSE);
2435 /* Update statistics */
2436 server->stat.my_clients--;
2437 server->stat.clients--;
2438 if (server->server_type == SILC_ROUTER)
2439 server->stat.cell_clients--;
2440 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2441 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2443 /* We will not delete the client entry right away. We will take it
2444 into history (for WHOWAS command) for 5 minutes */
2447 silc_schedule_task_add(server->schedule, 0,
2448 silc_server_free_client_data_timeout,
2450 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2451 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2452 client->router = NULL;
2453 client->connection = NULL;
2457 /* Frees user_data pointer from socket connection object. This also sends
2458 appropriate notify packets to the network to inform about leaving
2461 void silc_server_free_sock_user_data(SilcServer server,
2462 SilcSocketConnection sock,
2463 const char *signoff_message)
2465 SILC_LOG_DEBUG(("Start"));
2467 switch (sock->type) {
2468 case SILC_SOCKET_TYPE_CLIENT:
2470 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2471 silc_server_free_client_data(server, sock, user_data, TRUE,
2475 case SILC_SOCKET_TYPE_SERVER:
2476 case SILC_SOCKET_TYPE_ROUTER:
2478 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2479 SilcServerEntry backup_router = NULL;
2482 backup_router = silc_server_backup_get(server, user_data->id);
2484 /* If this was our primary router connection then we're lost to
2485 the outside world. */
2486 if (server->router == user_data) {
2487 /* Check whether we have a backup router connection */
2488 if (!backup_router || backup_router == user_data) {
2489 silc_schedule_task_add(server->schedule, 0,
2490 silc_server_connect_to_router,
2493 SILC_TASK_PRI_NORMAL);
2495 server->id_entry->router = NULL;
2496 server->router = NULL;
2497 server->standalone = TRUE;
2498 backup_router = NULL;
2500 SILC_LOG_INFO(("New primary router is backup router %s",
2501 backup_router->server_name));
2502 SILC_LOG_DEBUG(("New primary router is backup router %s",
2503 backup_router->server_name));
2504 server->id_entry->router = backup_router;
2505 server->router = backup_router;
2506 server->router_connect = time(0);
2507 server->backup_primary = TRUE;
2508 if (server->server_type == SILC_BACKUP_ROUTER) {
2509 server->server_type = SILC_ROUTER;
2511 /* We'll need to constantly try to reconnect to the primary
2512 router so that we'll see when it comes back online. */
2513 silc_server_backup_reconnect(server, sock->ip, sock->port,
2514 silc_server_backup_connected,
2518 /* Mark this connection as replaced */
2519 silc_server_backup_replaced_add(server, user_data->id,
2522 } else if (backup_router) {
2523 SILC_LOG_INFO(("Enabling the use of backup router %s",
2524 backup_router->server_name));
2525 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2526 backup_router->server_name));
2528 /* Mark this connection as replaced */
2529 silc_server_backup_replaced_add(server, user_data->id,
2533 if (!backup_router) {
2534 /* Free all client entries that this server owns as they will
2535 become invalid now as well. */
2537 silc_server_remove_clients_by_server(server, user_data, TRUE);
2538 if (server->server_type == SILC_SERVER)
2539 silc_server_remove_channels_by_server(server, user_data);
2541 /* Update the client entries of this server to the new backup
2542 router. This also removes the clients that *really* was owned
2543 by the primary router and went down with the router. */
2544 silc_server_update_clients_by_server(server, user_data, backup_router,
2546 silc_server_update_servers_by_server(server, user_data, backup_router);
2547 if (server->server_type == SILC_SERVER)
2548 silc_server_update_channels_by_server(server, user_data,
2552 /* Free the server entry */
2553 silc_server_backup_del(server, user_data);
2554 silc_server_backup_replaced_del(server, user_data);
2555 silc_idlist_del_data(user_data);
2556 if (!silc_idlist_del_server(server->local_list, user_data))
2557 silc_idlist_del_server(server->global_list, user_data);
2558 server->stat.my_servers--;
2559 server->stat.servers--;
2560 if (server->server_type == SILC_ROUTER)
2561 server->stat.cell_servers--;
2563 if (backup_router) {
2564 /* Announce all of our stuff that was created about 5 minutes ago.
2565 The backup router knows all the other stuff already. */
2566 if (server->server_type == SILC_ROUTER)
2567 silc_server_announce_servers(server, FALSE, time(0) - 300,
2568 backup_router->connection);
2570 /* Announce our clients and channels to the router */
2571 silc_server_announce_clients(server, time(0) - 300,
2572 backup_router->connection);
2573 silc_server_announce_channels(server, time(0) - 300,
2574 backup_router->connection);
2580 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2582 silc_idlist_del_data(user_data);
2583 silc_free(user_data);
2588 /* If any protocol is active cancel its execution */
2589 if (sock->protocol) {
2590 silc_protocol_cancel(sock->protocol, server->schedule);
2591 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2592 silc_protocol_execute_final(sock->protocol, server->schedule);
2593 sock->protocol = NULL;
2596 sock->user_data = NULL;
2599 /* Removes client from all channels it has joined. This is used when client
2600 connection is disconnected. If the client on a channel is last, the
2601 channel is removed as well. This sends the SIGNOFF notify types. */
2603 void silc_server_remove_from_channels(SilcServer server,
2604 SilcSocketConnection sock,
2605 SilcClientEntry client,
2607 char *signoff_message,
2610 SilcChannelEntry channel;
2611 SilcChannelClientEntry chl;
2612 SilcHashTableList htl;
2615 SILC_LOG_DEBUG(("Start"));
2617 if (!client || !client->id)
2620 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2622 /* Remove the client from all channels. The client is removed from
2623 the channels' user list. */
2624 silc_hash_table_list(client->channels, &htl);
2625 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2626 channel = chl->channel;
2628 /* Remove channel from client's channel list */
2629 silc_hash_table_del(client->channels, channel);
2631 /* Remove channel if there is no users anymore */
2632 if (server->server_type == SILC_ROUTER &&
2633 silc_hash_table_count(channel->user_list) < 2) {
2635 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2636 if (silc_idlist_del_channel(server->local_list, channel))
2637 server->stat.my_channels--;
2639 silc_idlist_del_channel(server->global_list, channel);
2643 /* Remove client from channel's client list */
2644 silc_hash_table_del(channel->user_list, chl->client);
2645 channel->user_count--;
2647 /* If there is no global users on the channel anymore mark the channel
2648 as local channel. Do not check if the removed client is local client. */
2649 if (server->server_type != SILC_ROUTER && channel->global_users &&
2650 chl->client->router && !silc_server_channel_has_global(channel))
2651 channel->global_users = FALSE;
2654 server->stat.my_chanclients--;
2656 /* If there is not at least one local user on the channel then we don't
2657 need the channel entry anymore, we can remove it safely. */
2658 if (server->server_type != SILC_ROUTER &&
2659 !silc_server_channel_has_local(channel)) {
2660 /* Notify about leaving client if this channel has global users. */
2661 if (notify && channel->global_users)
2662 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2663 SILC_NOTIFY_TYPE_SIGNOFF,
2664 signoff_message ? 2 : 1,
2665 clidp->data, clidp->len,
2666 signoff_message, signoff_message ?
2667 strlen(signoff_message) : 0);
2670 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2672 if (channel->founder_key) {
2673 /* The founder auth data exists, do not remove the channel entry */
2674 SilcChannelClientEntry chl2;
2675 SilcHashTableList htl2;
2677 channel->disabled = TRUE;
2679 silc_hash_table_list(channel->user_list, &htl2);
2680 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2681 silc_hash_table_del(chl2->client->channels, channel);
2682 silc_hash_table_del(channel->user_list, chl2->client);
2683 channel->user_count--;
2686 silc_hash_table_list_reset(&htl2);
2690 /* Remove the channel entry */
2691 if (silc_idlist_del_channel(server->local_list, channel))
2692 server->stat.my_channels--;
2694 silc_idlist_del_channel(server->global_list, channel);
2698 /* Send notify to channel about client leaving SILC and thus
2699 the entire channel. */
2701 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2702 SILC_NOTIFY_TYPE_SIGNOFF,
2703 signoff_message ? 2 : 1,
2704 clidp->data, clidp->len,
2705 signoff_message, signoff_message ?
2706 strlen(signoff_message) : 0);
2708 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2709 /* Re-generate channel key */
2710 if (!silc_server_create_channel_key(server, channel, 0))
2713 /* Send the channel key to the channel. The key of course is not sent
2714 to the client who was removed from the channel. */
2715 silc_server_send_channel_key(server, client->connection, channel,
2716 server->server_type == SILC_ROUTER ?
2717 FALSE : !server->standalone);
2722 silc_hash_table_list_reset(&htl);
2723 silc_buffer_free(clidp);
2726 /* Removes client from one channel. This is used for example when client
2727 calls LEAVE command to remove itself from the channel. Returns TRUE
2728 if channel still exists and FALSE if the channel is removed when
2729 last client leaves the channel. If `notify' is FALSE notify messages
2732 int silc_server_remove_from_one_channel(SilcServer server,
2733 SilcSocketConnection sock,
2734 SilcChannelEntry channel,
2735 SilcClientEntry client,
2738 SilcChannelClientEntry chl;
2741 SILC_LOG_DEBUG(("Start"));
2743 /* Get the entry to the channel, if this client is not on the channel
2745 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2748 /* Remove the client from the channel. The client is removed from
2749 the channel's user list. */
2751 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2753 /* Remove channel from client's channel list */
2754 silc_hash_table_del(client->channels, chl->channel);
2756 /* Remove channel if there is no users anymore */
2757 if (server->server_type == SILC_ROUTER &&
2758 silc_hash_table_count(channel->user_list) < 2) {
2760 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2761 if (silc_idlist_del_channel(server->local_list, channel))
2762 server->stat.my_channels--;
2764 silc_idlist_del_channel(server->global_list, channel);
2765 silc_buffer_free(clidp);
2769 /* Remove client from channel's client list */
2770 silc_hash_table_del(channel->user_list, chl->client);
2771 channel->user_count--;
2773 /* If there is no global users on the channel anymore mark the channel
2774 as local channel. Do not check if the client is local client. */
2775 if (server->server_type != SILC_ROUTER && channel->global_users &&
2776 chl->client->router && !silc_server_channel_has_global(channel))
2777 channel->global_users = FALSE;
2780 server->stat.my_chanclients--;
2782 /* If there is not at least one local user on the channel then we don't
2783 need the channel entry anymore, we can remove it safely. */
2784 if (server->server_type != SILC_ROUTER &&
2785 !silc_server_channel_has_local(channel)) {
2786 /* Notify about leaving client if this channel has global users. */
2787 if (notify && channel->global_users)
2788 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2789 SILC_NOTIFY_TYPE_LEAVE, 1,
2790 clidp->data, clidp->len);
2792 silc_buffer_free(clidp);
2795 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2797 if (channel->founder_key) {
2798 /* The founder auth data exists, do not remove the channel entry */
2799 SilcChannelClientEntry chl2;
2800 SilcHashTableList htl2;
2802 channel->disabled = TRUE;
2804 silc_hash_table_list(channel->user_list, &htl2);
2805 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2806 silc_hash_table_del(chl2->client->channels, channel);
2807 silc_hash_table_del(channel->user_list, chl2->client);
2808 channel->user_count--;
2811 silc_hash_table_list_reset(&htl2);
2815 /* Remove the channel entry */
2816 if (silc_idlist_del_channel(server->local_list, channel))
2817 server->stat.my_channels--;
2819 silc_idlist_del_channel(server->global_list, channel);
2823 /* Send notify to channel about client leaving the channel */
2825 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2826 SILC_NOTIFY_TYPE_LEAVE, 1,
2827 clidp->data, clidp->len);
2829 silc_buffer_free(clidp);
2833 /* Timeout callback. This is called if connection is idle or for some
2834 other reason is not responding within some period of time. This
2835 disconnects the remote end. */
2837 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2839 SilcServer server = (SilcServer)context;
2840 SilcSocketConnection sock = server->sockets[fd];
2842 SILC_LOG_DEBUG(("Start"));
2847 /* If we have protocol active we must assure that we call the protocol's
2848 final callback so that all the memory is freed. */
2849 if (sock->protocol) {
2850 silc_protocol_cancel(sock->protocol, server->schedule);
2851 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2852 silc_protocol_execute_final(sock->protocol, server->schedule);
2853 sock->protocol = NULL;
2857 if (sock->user_data)
2858 silc_server_free_sock_user_data(server, sock, NULL);
2860 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2861 "Connection timeout");
2864 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2865 function may be used only by router. In real SILC network all channels
2866 are created by routers thus this function is never used by normal
2869 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2870 SilcServerID *router_id,
2876 SilcChannelID *channel_id;
2877 SilcChannelEntry entry;
2881 SILC_LOG_DEBUG(("Creating new channel"));
2884 cipher = SILC_DEFAULT_CIPHER;
2886 hmac = SILC_DEFAULT_HMAC;
2888 /* Allocate cipher */
2889 if (!silc_cipher_alloc(cipher, &key))
2893 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2894 silc_cipher_free(key);
2898 channel_name = strdup(channel_name);
2900 /* Create the channel ID */
2901 if (!silc_id_create_channel_id(server, router_id, server->rng,
2903 silc_free(channel_name);
2904 silc_cipher_free(key);
2905 silc_hmac_free(newhmac);
2909 /* Create the channel */
2910 entry = silc_idlist_add_channel(server->local_list, channel_name,
2911 SILC_CHANNEL_MODE_NONE, channel_id,
2912 NULL, key, newhmac, 0);
2914 silc_free(channel_name);
2915 silc_cipher_free(key);
2916 silc_hmac_free(newhmac);
2917 silc_free(channel_id);
2921 entry->cipher = strdup(cipher);
2922 entry->hmac_name = strdup(hmac);
2924 /* Now create the actual key material */
2925 if (!silc_server_create_channel_key(server, entry,
2926 silc_cipher_get_key_len(key) / 8)) {
2927 silc_idlist_del_channel(server->local_list, entry);
2931 /* Notify other routers about the new channel. We send the packet
2932 to our primary route. */
2933 if (broadcast && server->standalone == FALSE)
2934 silc_server_send_new_channel(server, server->router->connection, TRUE,
2935 channel_name, entry->id,
2936 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2939 server->stat.my_channels++;
2944 /* Same as above but creates the channel with Channel ID `channel_id. */
2947 silc_server_create_new_channel_with_id(SilcServer server,
2951 SilcChannelID *channel_id,
2954 SilcChannelEntry entry;
2958 SILC_LOG_DEBUG(("Creating new channel"));
2961 cipher = SILC_DEFAULT_CIPHER;
2963 hmac = SILC_DEFAULT_HMAC;
2965 /* Allocate cipher */
2966 if (!silc_cipher_alloc(cipher, &key))
2970 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2971 silc_cipher_free(key);
2975 channel_name = strdup(channel_name);
2977 /* Create the channel */
2978 entry = silc_idlist_add_channel(server->local_list, channel_name,
2979 SILC_CHANNEL_MODE_NONE, channel_id,
2980 NULL, key, newhmac, 0);
2982 silc_cipher_free(key);
2983 silc_hmac_free(newhmac);
2984 silc_free(channel_name);
2988 /* Now create the actual key material */
2989 if (!silc_server_create_channel_key(server, entry,
2990 silc_cipher_get_key_len(key) / 8)) {
2991 silc_idlist_del_channel(server->local_list, entry);
2995 /* Notify other routers about the new channel. We send the packet
2996 to our primary route. */
2997 if (broadcast && server->standalone == FALSE)
2998 silc_server_send_new_channel(server, server->router->connection, TRUE,
2999 channel_name, entry->id,
3000 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3003 server->stat.my_channels++;
3008 /* Channel's key re-key timeout callback. */
3010 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3012 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3013 SilcServer server = (SilcServer)rekey->context;
3017 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3020 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3023 /* Generates new channel key. This is used to create the initial channel key
3024 but also to re-generate new key for channel. If `key_len' is provided
3025 it is the bytes of the key length. */
3027 bool silc_server_create_channel_key(SilcServer server,
3028 SilcChannelEntry channel,
3032 unsigned char channel_key[32], hash[32];
3035 SILC_LOG_DEBUG(("Generating channel key"));
3037 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3038 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3042 if (!channel->channel_key)
3043 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3044 channel->channel_key = NULL;
3050 else if (channel->key_len)
3051 len = channel->key_len / 8;
3053 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3055 /* Create channel key */
3056 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3059 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3061 /* Remove old key if exists */
3063 memset(channel->key, 0, channel->key_len / 8);
3064 silc_free(channel->key);
3068 channel->key_len = len * 8;
3069 channel->key = silc_calloc(len, sizeof(*channel->key));
3070 memcpy(channel->key, channel_key, len);
3071 memset(channel_key, 0, sizeof(channel_key));
3073 /* Generate HMAC key from the channel key data and set it */
3075 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3076 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3077 silc_hmac_set_key(channel->hmac, hash,
3078 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3079 memset(hash, 0, sizeof(hash));
3081 if (server->server_type == SILC_ROUTER) {
3082 if (!channel->rekey)
3083 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3084 channel->rekey->context = (void *)server;
3085 channel->rekey->channel = channel;
3086 channel->rekey->key_len = key_len;
3087 if (channel->rekey->task)
3088 silc_schedule_task_del(server->schedule, channel->rekey->task);
3090 channel->rekey->task =
3091 silc_schedule_task_add(server->schedule, 0,
3092 silc_server_channel_key_rekey,
3093 (void *)channel->rekey,
3094 server->config->channel_rekey_secs, 0,
3096 SILC_TASK_PRI_NORMAL);
3102 /* Saves the channel key found in the encoded `key_payload' buffer. This
3103 function is used when we receive Channel Key Payload and also when we're
3104 processing JOIN command reply. Returns entry to the channel. */
3106 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3107 SilcBuffer key_payload,
3108 SilcChannelEntry channel)
3110 SilcChannelKeyPayload payload = NULL;
3111 SilcChannelID *id = NULL;
3112 unsigned char *tmp, hash[32];
3116 SILC_LOG_DEBUG(("Start"));
3118 /* Decode channel key payload */
3119 payload = silc_channel_key_payload_parse(key_payload->data,
3122 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3127 /* Get the channel entry */
3130 /* Get channel ID */
3131 tmp = silc_channel_key_get_id(payload, &tmp_len);
3132 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3138 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3140 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3142 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3143 silc_id_render(id, SILC_ID_CHANNEL)));
3149 tmp = silc_channel_key_get_key(payload, &tmp_len);
3155 cipher = silc_channel_key_get_cipher(payload, NULL);
3161 /* Remove old key if exists */
3163 memset(channel->key, 0, channel->key_len / 8);
3164 silc_free(channel->key);
3165 silc_cipher_free(channel->channel_key);
3168 /* Create new cipher */
3169 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3170 channel->channel_key = NULL;
3175 if (channel->cipher)
3176 silc_free(channel->cipher);
3177 channel->cipher = strdup(cipher);
3180 channel->key_len = tmp_len * 8;
3181 channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3182 memcpy(channel->key, tmp, tmp_len);
3183 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3185 /* Generate HMAC key from the channel key data and set it */
3187 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3188 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3189 silc_hmac_set_key(channel->hmac, hash,
3190 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3192 memset(hash, 0, sizeof(hash));
3193 memset(tmp, 0, tmp_len);
3195 if (server->server_type == SILC_ROUTER) {
3196 if (!channel->rekey)
3197 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3198 channel->rekey->context = (void *)server;
3199 channel->rekey->channel = channel;
3200 if (channel->rekey->task)
3201 silc_schedule_task_del(server->schedule, channel->rekey->task);
3203 channel->rekey->task =
3204 silc_schedule_task_add(server->schedule, 0,
3205 silc_server_channel_key_rekey,
3206 (void *)channel->rekey,
3207 server->config->channel_rekey_secs, 0,
3209 SILC_TASK_PRI_NORMAL);
3215 silc_channel_key_payload_free(payload);
3220 /* Heartbeat callback. This function is set as argument for the
3221 silc_socket_set_heartbeat function. The library will call this function
3222 at the set time interval. */
3224 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3227 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3229 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3231 /* Send the heartbeat */
3232 silc_server_send_heartbeat(hb->server, sock);
3235 /* Returns assembled of all servers in the given ID list. The packet's
3236 form is dictated by the New ID payload. */
3238 static void silc_server_announce_get_servers(SilcServer server,
3239 SilcServerEntry remote,
3241 SilcBuffer *servers,
3242 unsigned long creation_time)
3244 SilcIDCacheList list;
3245 SilcIDCacheEntry id_cache;
3246 SilcServerEntry entry;
3249 /* Go through all clients in the list */
3250 if (silc_idcache_get_all(id_list->servers, &list)) {
3251 if (silc_idcache_list_first(list, &id_cache)) {
3253 entry = (SilcServerEntry)id_cache->context;
3255 /* Do not announce the one we've sending our announcements and
3256 do not announce ourself. Also check the creation time if it's
3258 if ((entry == remote) || (entry == server->id_entry) ||
3259 (creation_time && entry->data.created < creation_time)) {
3260 if (!silc_idcache_list_next(list, &id_cache))
3265 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3267 *servers = silc_buffer_realloc(*servers,
3269 (*servers)->truelen + idp->len :
3271 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3272 silc_buffer_put(*servers, idp->data, idp->len);
3273 silc_buffer_pull(*servers, idp->len);
3274 silc_buffer_free(idp);
3276 if (!silc_idcache_list_next(list, &id_cache))
3281 silc_idcache_list_free(list);
3286 silc_server_announce_encode_notify(SilcNotifyType notify, uint32 argc, ...)
3292 p = silc_notify_payload_encode(notify, argc, ap);
3298 /* This function is used by router to announce existing servers to our
3299 primary router when we've connected to it. If `creation_time' is non-zero
3300 then only the servers that has been created after the `creation_time'
3301 will be announced. */
3303 void silc_server_announce_servers(SilcServer server, bool global,
3304 unsigned long creation_time,
3305 SilcSocketConnection remote)
3307 SilcBuffer servers = NULL;
3309 SILC_LOG_DEBUG(("Announcing servers"));
3311 /* Get servers in local list */
3312 silc_server_announce_get_servers(server, remote->user_data,
3313 server->local_list, &servers,
3317 /* Get servers in global list */
3318 silc_server_announce_get_servers(server, remote->user_data,
3319 server->global_list, &servers,
3323 silc_buffer_push(servers, servers->data - servers->head);
3324 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3326 /* Send the packet */
3327 silc_server_packet_send(server, remote,
3328 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3329 servers->data, servers->len, TRUE);
3331 silc_buffer_free(servers);
3335 /* Returns assembled packet of all clients in the given ID list. The
3336 packet's form is dictated by the New ID Payload. */
3338 static void silc_server_announce_get_clients(SilcServer server,
3340 SilcBuffer *clients,
3342 unsigned long creation_time)
3344 SilcIDCacheList list;
3345 SilcIDCacheEntry id_cache;
3346 SilcClientEntry client;
3349 unsigned char mode[4];
3351 /* Go through all clients in the list */
3352 if (silc_idcache_get_all(id_list->clients, &list)) {
3353 if (silc_idcache_list_first(list, &id_cache)) {
3355 client = (SilcClientEntry)id_cache->context;
3357 if (creation_time && client->data.created < creation_time) {
3358 if (!silc_idcache_list_next(list, &id_cache))
3363 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3365 *clients = silc_buffer_realloc(*clients,
3367 (*clients)->truelen + idp->len :
3369 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3370 silc_buffer_put(*clients, idp->data, idp->len);
3371 silc_buffer_pull(*clients, idp->len);
3373 SILC_PUT32_MSB(client->mode, mode);
3374 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3375 2, idp->data, idp->len,
3377 *umodes = silc_buffer_realloc(*umodes,
3379 (*umodes)->truelen + tmp->len :
3381 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3382 silc_buffer_put(*umodes, tmp->data, tmp->len);
3383 silc_buffer_pull(*umodes, tmp->len);
3384 silc_buffer_free(tmp);
3386 silc_buffer_free(idp);
3388 if (!silc_idcache_list_next(list, &id_cache))
3393 silc_idcache_list_free(list);
3397 /* This function is used to announce our existing clients to our router
3398 when we've connected to it. If `creation_time' is non-zero then only
3399 the clients that has been created after the `creation_time' will be
3402 void silc_server_announce_clients(SilcServer server,
3403 unsigned long creation_time,
3404 SilcSocketConnection remote)
3406 SilcBuffer clients = NULL;
3407 SilcBuffer umodes = NULL;
3409 SILC_LOG_DEBUG(("Announcing clients"));
3411 /* Get clients in local list */
3412 silc_server_announce_get_clients(server, server->local_list,
3413 &clients, &umodes, creation_time);
3415 /* As router we announce our global list as well */
3416 if (server->server_type == SILC_ROUTER)
3417 silc_server_announce_get_clients(server, server->global_list,
3418 &clients, &umodes, creation_time);
3421 silc_buffer_push(clients, clients->data - clients->head);
3422 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3424 /* Send the packet */
3425 silc_server_packet_send(server, remote,
3426 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3427 clients->data, clients->len, TRUE);
3429 silc_buffer_free(clients);
3433 silc_buffer_push(umodes, umodes->data - umodes->head);
3434 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3436 /* Send the packet */
3437 silc_server_packet_send(server, remote,
3438 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3439 umodes->data, umodes->len, TRUE);
3441 silc_buffer_free(umodes);
3445 /* Returns channel's topic for announcing it */
3447 void silc_server_announce_get_channel_topic(SilcServer server,
3448 SilcChannelEntry channel,
3453 if (channel->topic) {
3454 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3455 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3456 chidp->data, chidp->len,
3458 strlen(channel->topic));
3459 silc_buffer_free(chidp);
3463 /* Returns assembled packets for channel users of the `channel'. */
3465 void silc_server_announce_get_channel_users(SilcServer server,
3466 SilcChannelEntry channel,
3467 SilcBuffer *channel_users,
3468 SilcBuffer *channel_users_modes)
3470 SilcChannelClientEntry chl;
3471 SilcHashTableList htl;
3472 SilcBuffer chidp, clidp;
3475 unsigned char mode[4];
3477 SILC_LOG_DEBUG(("Start"));
3479 /* Now find all users on the channel */
3480 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3481 silc_hash_table_list(channel->user_list, &htl);
3482 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3483 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3486 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3487 clidp->data, clidp->len,
3488 chidp->data, chidp->len);
3491 silc_buffer_realloc(*channel_users,
3493 (*channel_users)->truelen + len : len));
3494 silc_buffer_pull_tail(*channel_users,
3495 ((*channel_users)->end -
3496 (*channel_users)->data));
3498 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3499 silc_buffer_pull(*channel_users, len);
3500 silc_buffer_free(tmp);
3502 /* CUMODE notify for mode change on the channel */
3503 SILC_PUT32_MSB(chl->mode, mode);
3504 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3505 3, clidp->data, clidp->len,
3507 clidp->data, clidp->len);
3509 *channel_users_modes =
3510 silc_buffer_realloc(*channel_users_modes,
3511 (*channel_users_modes ?
3512 (*channel_users_modes)->truelen + len : len));
3513 silc_buffer_pull_tail(*channel_users_modes,
3514 ((*channel_users_modes)->end -
3515 (*channel_users_modes)->data));
3517 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3518 silc_buffer_pull(*channel_users_modes, len);
3519 silc_buffer_free(tmp);
3521 silc_buffer_free(clidp);
3523 silc_hash_table_list_reset(&htl);
3524 silc_buffer_free(chidp);
3527 /* Returns assembled packets for all channels and users on those channels
3528 from the given ID List. The packets are in the form dictated by the
3529 New Channel and New Channel User payloads. */
3531 void silc_server_announce_get_channels(SilcServer server,
3533 SilcBuffer *channels,
3534 SilcBuffer *channel_users,
3535 SilcBuffer **channel_users_modes,
3536 uint32 *channel_users_modes_c,
3537 SilcBuffer **channel_topics,
3538 SilcChannelID ***channel_ids,
3539 unsigned long creation_time)
3541 SilcIDCacheList list;
3542 SilcIDCacheEntry id_cache;
3543 SilcChannelEntry channel;
3548 int i = *channel_users_modes_c;
3551 SILC_LOG_DEBUG(("Start"));
3553 /* Go through all channels in the list */
3554 if (silc_idcache_get_all(id_list->channels, &list)) {
3555 if (silc_idcache_list_first(list, &id_cache)) {
3557 channel = (SilcChannelEntry)id_cache->context;
3559 if (creation_time && channel->created < creation_time)
3564 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3565 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3566 name_len = strlen(channel->channel_name);
3569 len = 4 + name_len + id_len + 4;
3571 silc_buffer_realloc(*channels,
3572 (*channels ? (*channels)->truelen +
3574 silc_buffer_pull_tail(*channels,
3575 ((*channels)->end - (*channels)->data));
3576 silc_buffer_format(*channels,
3577 SILC_STR_UI_SHORT(name_len),
3578 SILC_STR_UI_XNSTRING(channel->channel_name,
3580 SILC_STR_UI_SHORT(id_len),
3581 SILC_STR_UI_XNSTRING(cid, id_len),
3582 SILC_STR_UI_INT(channel->mode),
3584 silc_buffer_pull(*channels, len);
3587 /* Channel user modes */
3588 *channel_users_modes = silc_realloc(*channel_users_modes,
3589 sizeof(**channel_users_modes) *
3591 (*channel_users_modes)[i] = NULL;
3592 *channel_ids = silc_realloc(*channel_ids,
3593 sizeof(**channel_ids) * (i + 1));
3594 (*channel_ids)[i] = NULL;
3595 silc_server_announce_get_channel_users(server, channel,
3597 &(*channel_users_modes)[i]);
3598 (*channel_ids)[i] = channel->id;
3600 /* Channel's topic */
3601 *channel_topics = silc_realloc(*channel_topics,
3602 sizeof(**channel_topics) * (i + 1));
3603 (*channel_topics)[i] = NULL;
3604 silc_server_announce_get_channel_topic(server, channel,
3605 &(*channel_topics)[i]);
3608 if (!silc_idcache_list_next(list, &id_cache))
3612 *channel_users_modes_c += i;
3615 silc_idcache_list_free(list);
3619 /* This function is used to announce our existing channels to our router
3620 when we've connected to it. This also announces the users on the
3621 channels to the router. If the `creation_time' is non-zero only the
3622 channels that was created after the `creation_time' are announced.
3623 Note that the channel users are still announced even if the `creation_time'
3626 void silc_server_announce_channels(SilcServer server,
3627 unsigned long creation_time,
3628 SilcSocketConnection remote)
3630 SilcBuffer channels = NULL, channel_users = NULL;
3631 SilcBuffer *channel_users_modes = NULL;
3632 SilcBuffer *channel_topics = NULL;
3633 uint32 channel_users_modes_c = 0;
3634 SilcChannelID **channel_ids = NULL;
3636 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3638 /* Get channels and channel users in local list */
3639 silc_server_announce_get_channels(server, server->local_list,
3640 &channels, &channel_users,
3641 &channel_users_modes,
3642 &channel_users_modes_c,
3644 &channel_ids, creation_time);
3646 /* Get channels and channel users in global list */
3647 if (server->server_type != SILC_SERVER)
3648 silc_server_announce_get_channels(server, server->global_list,
3649 &channels, &channel_users,
3650 &channel_users_modes,
3651 &channel_users_modes_c,
3653 &channel_ids, creation_time);
3656 silc_buffer_push(channels, channels->data - channels->head);
3657 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3659 /* Send the packet */
3660 silc_server_packet_send(server, remote,
3661 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3662 channels->data, channels->len,
3665 silc_buffer_free(channels);
3668 if (channel_users) {
3669 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3670 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3671 channel_users->len);
3673 /* Send the packet */
3674 silc_server_packet_send(server, remote,
3675 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3676 channel_users->data, channel_users->len,
3679 silc_buffer_free(channel_users);
3682 if (channel_users_modes) {
3685 for (i = 0; i < channel_users_modes_c; i++) {
3686 if (!channel_users_modes[i])
3688 silc_buffer_push(channel_users_modes[i],
3689 channel_users_modes[i]->data -
3690 channel_users_modes[i]->head);
3691 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3692 channel_users_modes[i]->len);
3693 silc_server_packet_send_dest(server, remote,
3694 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3695 channel_ids[i], SILC_ID_CHANNEL,
3696 channel_users_modes[i]->data,
3697 channel_users_modes[i]->len,
3699 silc_buffer_free(channel_users_modes[i]);
3701 silc_free(channel_users_modes);
3704 if (channel_topics) {
3707 for (i = 0; i < channel_users_modes_c; i++) {
3708 if (!channel_topics[i])
3711 silc_buffer_push(channel_topics[i],
3712 channel_topics[i]->data -
3713 channel_topics[i]->head);
3714 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3715 channel_topics[i]->len);
3716 silc_server_packet_send_dest(server, remote,
3717 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3718 channel_ids[i], SILC_ID_CHANNEL,
3719 channel_topics[i]->data,
3720 channel_topics[i]->len,
3722 silc_buffer_free(channel_topics[i]);
3724 silc_free(channel_topics);
3727 silc_free(channel_ids);
3730 /* Failure timeout callback. If this is called then we will immediately
3731 process the received failure. We always process the failure with timeout
3732 since we do not want to blindly trust to received failure packets.
3733 This won't be called (the timeout is cancelled) if the failure was
3734 bogus (it is bogus if remote does not close the connection after sending
3737 SILC_TASK_CALLBACK(silc_server_failure_callback)
3739 SilcServerFailureContext f = (SilcServerFailureContext)context;
3741 if (f->sock->protocol) {
3742 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3743 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3749 /* Assembles user list and users mode list from the `channel'. */
3751 void silc_server_get_users_on_channel(SilcServer server,
3752 SilcChannelEntry channel,
3753 SilcBuffer *user_list,
3754 SilcBuffer *mode_list,
3757 SilcChannelClientEntry chl;
3758 SilcHashTableList htl;
3759 SilcBuffer client_id_list;
3760 SilcBuffer client_mode_list;
3762 uint32 list_count = 0, len = 0;
3764 silc_hash_table_list(channel->user_list, &htl);
3765 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3766 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3767 silc_hash_table_list_reset(&htl);
3769 client_id_list = silc_buffer_alloc(len);
3771 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3772 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3773 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3775 silc_hash_table_list(channel->user_list, &htl);
3776 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3778 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3779 silc_buffer_put(client_id_list, idp->data, idp->len);
3780 silc_buffer_pull(client_id_list, idp->len);
3781 silc_buffer_free(idp);
3783 /* Client's mode on channel */
3784 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3785 silc_buffer_pull(client_mode_list, 4);
3789 silc_hash_table_list_reset(&htl);
3790 silc_buffer_push(client_id_list,
3791 client_id_list->data - client_id_list->head);
3792 silc_buffer_push(client_mode_list,
3793 client_mode_list->data - client_mode_list->head);
3795 *user_list = client_id_list;
3796 *mode_list = client_mode_list;
3797 *user_count = list_count;
3800 /* Saves users and their modes to the `channel'. */
3802 void silc_server_save_users_on_channel(SilcServer server,
3803 SilcSocketConnection sock,
3804 SilcChannelEntry channel,
3805 SilcClientID *noadd,
3806 SilcBuffer user_list,
3807 SilcBuffer mode_list,
3813 SilcClientID *client_id;
3814 SilcClientEntry client;
3815 SilcIDCacheEntry cache;
3818 SILC_LOG_DEBUG(("Start"));
3820 for (i = 0; i < user_count; i++) {
3822 SILC_GET16_MSB(idp_len, user_list->data + 2);
3824 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3825 silc_buffer_pull(user_list, idp_len);
3830 SILC_GET32_MSB(mode, mode_list->data);
3831 silc_buffer_pull(mode_list, 4);
3833 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3834 silc_free(client_id);
3840 /* Check if we have this client cached already. */
3841 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3842 server->server_type, &cache);
3844 client = silc_idlist_find_client_by_id(server->global_list,
3845 client_id, server->server_type,
3850 /* If router did not find such Client ID in its lists then this must
3851 be bogus client or some router in the net is buggy. */
3852 if (server->server_type == SILC_ROUTER) {
3853 silc_free(client_id);
3857 /* We don't have that client anywhere, add it. The client is added
3858 to global list since server didn't have it in the lists so it must be
3860 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3861 silc_id_dup(client_id, SILC_ID_CLIENT),
3862 sock->user_data, NULL, 0);
3864 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3865 silc_free(client_id);
3869 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3871 /* Found, if it is from global list we'll assure that we won't
3872 expire it now that the entry is on channel. */
3877 silc_free(client_id);
3879 if (!silc_server_client_on_channel(client, channel)) {
3880 /* Client was not on the channel, add it. */
3881 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3882 chl->client = client;
3884 chl->channel = channel;
3885 silc_hash_table_add(channel->user_list, chl->client, chl);
3886 silc_hash_table_add(client->channels, chl->channel, chl);
3887 channel->user_count++;
3892 /* Lookups route to the client indicated by the `id_data'. The connection
3893 object and internal data object is returned. Returns NULL if route
3894 could not be found to the client. If the `client_id' is specified then
3895 it is used and the `id_data' is ignored. */
3897 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3898 unsigned char *id_data,
3900 SilcClientID *client_id,
3901 SilcIDListData *idata)
3904 SilcClientEntry client;
3906 SILC_LOG_DEBUG(("Start"));
3908 /* Decode destination Client ID */
3910 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3912 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3916 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3919 /* If the destination belongs to our server we don't have to route
3920 the packet anywhere but to send it to the local destination. */
3921 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3925 /* If we are router and the client has router then the client is in
3926 our cell but not directly connected to us. */
3927 if (server->server_type == SILC_ROUTER && client->router) {
3928 /* We are of course in this case the client's router thus the route
3929 to the client is the server who owns the client. So, we will send
3930 the packet to that server. */
3932 *idata = (SilcIDListData)client->router;
3933 return client->router->connection;
3936 /* Seems that client really is directly connected to us */
3938 *idata = (SilcIDListData)client;
3939 return client->connection;
3942 /* Destination belongs to someone not in this server. If we are normal
3943 server our action is to send the packet to our router. */
3944 if (server->server_type != SILC_ROUTER && !server->standalone) {
3947 *idata = (SilcIDListData)server->router;
3948 return server->router->connection;
3951 /* We are router and we will perform route lookup for the destination
3952 and send the packet to fastest route. */
3953 if (server->server_type == SILC_ROUTER && !server->standalone) {
3954 /* Check first that the ID is valid */
3955 client = silc_idlist_find_client_by_id(server->global_list, id,
3958 SilcSocketConnection dst_sock;
3960 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3964 *idata = (SilcIDListData)dst_sock->user_data;
3973 /* Encodes and returns channel list of channels the `client' has joined.
3974 Secret channels are not put to the list. */
3976 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3977 SilcClientEntry client)
3979 SilcBuffer buffer = NULL;
3980 SilcChannelEntry channel;
3981 SilcChannelClientEntry chl;
3982 SilcHashTableList htl;
3988 silc_hash_table_list(client->channels, &htl);
3989 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3990 channel = chl->channel;
3992 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3993 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3996 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3997 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3998 name_len = strlen(channel->channel_name);
4000 len = 4 + name_len + id_len + 4;
4001 buffer = silc_buffer_realloc(buffer,
4002 (buffer ? (buffer)->truelen + len : len));
4003 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4004 silc_buffer_format(buffer,
4005 SILC_STR_UI_SHORT(name_len),
4006 SILC_STR_UI_XNSTRING(channel->channel_name,
4008 SILC_STR_UI_SHORT(id_len),
4009 SILC_STR_UI_XNSTRING(cid, id_len),
4010 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4012 silc_buffer_pull(buffer, len);
4015 silc_hash_table_list_reset(&htl);
4018 silc_buffer_push(buffer, buffer->data - buffer->head);
4023 /* Finds client entry by Client ID and if it is not found then resolves
4024 it using WHOIS command. */
4026 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4027 SilcClientID *client_id,
4030 SilcClientEntry client;
4035 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4038 client = silc_idlist_find_client_by_id(server->global_list,
4039 client_id, TRUE, NULL);
4040 if (!client && server->server_type == SILC_ROUTER)
4044 if (!client && server->standalone)
4047 if (!client || !client->nickname || !client->username) {
4048 SilcBuffer buffer, idp;
4050 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4051 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4052 client->resolve_cmd_ident = ++server->cmd_ident;
4054 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4055 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4056 server->cmd_ident, 1,
4057 3, idp->data, idp->len);
4058 silc_server_packet_send(server, client ? client->router->connection :
4059 server->router->connection,
4060 SILC_PACKET_COMMAND, 0,
4061 buffer->data, buffer->len, FALSE);
4062 silc_buffer_free(idp);
4063 silc_buffer_free(buffer);
4074 /* A timeout callback for the re-key. We will be the initiator of the
4077 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4079 SilcSocketConnection sock = (SilcSocketConnection)context;
4080 SilcIDListData idata = (SilcIDListData)sock->user_data;
4081 SilcServer server = (SilcServer)idata->rekey->context;
4082 SilcProtocol protocol;
4083 SilcServerRekeyInternalContext *proto_ctx;
4085 SILC_LOG_DEBUG(("Start"));
4087 /* Allocate internal protocol context. This is sent as context
4089 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4090 proto_ctx->server = (void *)server;
4091 proto_ctx->sock = sock;
4092 proto_ctx->responder = FALSE;
4093 proto_ctx->pfs = idata->rekey->pfs;
4095 /* Perform rekey protocol. Will call the final callback after the
4096 protocol is over. */
4097 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4098 &protocol, proto_ctx, silc_server_rekey_final);
4099 sock->protocol = protocol;
4101 /* Run the protocol */
4102 silc_protocol_execute(protocol, server->schedule, 0, 0);
4104 /* Re-register re-key timeout */
4105 silc_schedule_task_add(server->schedule, sock->sock,
4106 silc_server_rekey_callback,
4107 context, idata->rekey->timeout, 0,
4108 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4111 /* The final callback for the REKEY protocol. This will actually take the
4112 new key material into use. */
4114 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4116 SilcProtocol protocol = (SilcProtocol)context;
4117 SilcServerRekeyInternalContext *ctx =
4118 (SilcServerRekeyInternalContext *)protocol->context;
4119 SilcServer server = (SilcServer)ctx->server;
4120 SilcSocketConnection sock = ctx->sock;
4122 SILC_LOG_DEBUG(("Start"));
4124 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4125 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4126 /* Error occured during protocol */
4127 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4128 silc_protocol_cancel(protocol, server->schedule);
4129 silc_protocol_free(protocol);
4130 sock->protocol = NULL;
4132 silc_packet_context_free(ctx->packet);
4134 silc_ske_free(ctx->ske);
4139 /* Purge the outgoing data queue to assure that all rekey packets really
4140 go to the network before we quit the protocol. */
4141 silc_server_packet_queue_purge(server, sock);
4144 silc_protocol_free(protocol);
4145 sock->protocol = NULL;
4147 silc_packet_context_free(ctx->packet);
4149 silc_ske_free(ctx->ske);