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_LOG_ERROR(("Cannot add new server entry to cache"));
918 silc_server_disconnect_remote(server, sock, "Server closed connection: "
919 "Authentication failed");
923 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
924 silc_free(sock->user_data);
925 sock->user_data = (void *)id_entry;
926 sock->type = SILC_SOCKET_TYPE_ROUTER;
927 idata = (SilcIDListData)sock->user_data;
928 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
930 param = (sconn->param ? sconn->param : &server->config->param);
932 /* Perform keepalive. The `hb_context' will be freed automatically
933 when finally calling the silc_socket_free function. */
934 hb_context = silc_calloc(1, sizeof(*hb_context));
935 hb_context->server = server;
936 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
937 silc_server_perform_heartbeat,
940 /* Register re-key timeout */
941 idata->rekey->timeout = param->key_exchange_rekey;
942 idata->rekey->context = (void *)server;
943 silc_schedule_task_add(server->schedule, sock->sock,
944 silc_server_rekey_callback,
945 (void *)sock, idata->rekey->timeout, 0,
946 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
948 if (!sconn->backup) {
949 /* Mark this router our primary router if we're still standalone */
950 if (server->standalone) {
951 server->id_entry->router = id_entry;
952 server->router = id_entry;
953 server->standalone = FALSE;
955 /* If we are router then announce our possible servers. */
956 if (server->server_type == SILC_ROUTER)
957 silc_server_announce_servers(server, FALSE, 0,
958 server->router->connection);
960 /* Announce our clients and channels to the router */
961 silc_server_announce_clients(server, 0, server->router->connection);
962 silc_server_announce_channels(server, 0, server->router->connection);
965 /* Add this server to be our backup router */
966 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
967 sconn->backup_replace_port, FALSE);
970 sock->protocol = NULL;
972 /* Call the completion callback to indicate that we've connected to
975 (*sconn->callback)(server, id_entry, sconn->callback_context);
978 /* Free the temporary connection data context */
980 silc_free(sconn->remote_host);
981 silc_free(sconn->backup_replace_ip);
984 if (sconn == server->router_conn)
985 server->router_conn = NULL;
987 /* Free the protocol object */
988 if (sock->protocol == protocol)
989 sock->protocol = NULL;
990 silc_protocol_free(protocol);
992 silc_packet_context_free(ctx->packet);
994 silc_ske_free(ctx->ske);
995 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
996 silc_free(ctx->auth_data);
1000 /* Host lookup callbcak that is called after the incoming connection's
1001 IP and FQDN lookup is performed. This will actually check the acceptance
1002 of the incoming connection and will register the key exchange protocol
1003 for this connection. */
1006 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1009 SilcServer server = (SilcServer)context;
1010 SilcServerKEInternalContext *proto_ctx;
1011 SilcServerConfigClient *cconfig = NULL;
1012 SilcServerConfigServer *sconfig = NULL;
1013 SilcServerConfigRouter *rconfig = NULL;
1014 SilcServerConfigDeny *deny;
1017 SILC_LOG_DEBUG(("Start"));
1019 /* Check whether we could resolve both IP and FQDN. */
1020 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1021 server->config->require_reverse_lookup)) {
1022 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1023 sock->hostname ? sock->hostname :
1024 sock->ip ? sock->ip : ""));
1025 server->stat.conn_failures++;
1026 silc_server_disconnect_remote(server, sock,
1027 "Server closed connection: Unknown host");
1031 /* Register the connection for network input and output. This sets
1032 that scheduler will listen for incoming packets for this connection
1033 and sets that outgoing packets may be sent to this connection as well.
1034 However, this doesn't set the scheduler for outgoing traffic, it
1035 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1036 later when outgoing data is available. */
1037 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1039 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1042 port = server->sockets[server->sock]->port; /* Listenning port */
1044 /* Check whether this connection is denied to connect to us. */
1045 deny = silc_server_config_find_denied(server, sock->ip);
1047 deny = silc_server_config_find_denied(server, sock->hostname);
1049 /* The connection is denied */
1050 SILC_LOG_INFO(("Connection %s (%s) is denied",
1051 sock->hostname, sock->ip));
1052 silc_server_disconnect_remote(server, sock, deny->reason ?
1054 "Server closed connection: "
1055 "Connection refused");
1056 server->stat.conn_failures++;
1060 /* Check whether we have configred this sort of connection at all. We
1061 have to check all configurations since we don't know what type of
1062 connection this is. */
1063 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1064 cconfig = silc_server_config_find_client(server, sock->hostname);
1065 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1066 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1067 if (server->server_type == SILC_ROUTER) {
1068 if (!(rconfig = silc_server_config_find_router_conn(server,
1070 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1073 if (!cconfig && !sconfig && !rconfig) {
1074 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1076 silc_server_disconnect_remote(server, sock,
1077 "Server closed connection: "
1078 "Connection refused");
1079 server->stat.conn_failures++;
1083 /* The connection is allowed */
1085 /* Allocate internal context for key exchange protocol. This is
1086 sent as context for the protocol. */
1087 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1088 proto_ctx->server = context;
1089 proto_ctx->sock = sock;
1090 proto_ctx->rng = server->rng;
1091 proto_ctx->responder = TRUE;
1092 proto_ctx->cconfig = cconfig;
1093 proto_ctx->sconfig = sconfig;
1094 proto_ctx->rconfig = rconfig;
1096 /* Take flags for key exchange. Since we do not know what type of connection
1097 this is, we go through all found configuratios and use the global ones
1098 as well. This will result always into strictest key exchange flags. */
1099 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1100 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1101 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1102 if (server->config->param.key_exchange_pfs)
1103 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1105 /* Prepare the connection for key exchange protocol. We allocate the
1106 protocol but will not start it yet. The connector will be the
1107 initiator of the protocol thus we will wait for initiation from
1108 there before we start the protocol. */
1109 server->stat.auth_attempts++;
1110 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1111 &sock->protocol, proto_ctx,
1112 silc_server_accept_new_connection_second);
1114 /* Register a timeout task that will be executed if the connector
1115 will not start the key exchange protocol within specified timeout
1116 and the connection will be closed. */
1117 proto_ctx->timeout_task =
1118 silc_schedule_task_add(server->schedule, sock->sock,
1119 silc_server_timeout_remote,
1120 context, server->config->key_exchange_timeout, 0,
1125 /* Accepts new connections to the server. Accepting new connections are
1126 done in three parts to make it async. */
1128 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1130 SilcServer server = (SilcServer)context;
1131 SilcSocketConnection newsocket;
1134 SILC_LOG_DEBUG(("Accepting new connection"));
1136 server->stat.conn_attempts++;
1138 sock = silc_net_accept_connection(server->sock);
1140 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1141 server->stat.conn_failures++;
1145 /* Check for maximum allowed connections */
1146 if (sock > server->config->param.connections_max) {
1147 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1148 server->stat.conn_failures++;
1152 /* Set socket options */
1153 silc_net_set_socket_nonblock(sock);
1154 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1156 /* We don't create a ID yet, since we don't know what type of connection
1157 this is yet. But, we do add the connection to the socket table. */
1158 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1159 server->sockets[sock] = newsocket;
1161 /* Perform asynchronous host lookup. This will lookup the IP and the
1162 FQDN of the remote connection. After the lookup is done the connection
1163 is accepted further. */
1164 silc_socket_host_lookup(newsocket, TRUE,
1165 silc_server_accept_new_connection_lookup, context,
1169 /* Second part of accepting new connection. Key exchange protocol has been
1170 performed and now it is time to do little connection authentication
1171 protocol to figure out whether this connection is client or server
1172 and whether it has right to access this server (especially server
1173 connections needs to be authenticated). */
1175 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1177 SilcProtocol protocol = (SilcProtocol)context;
1178 SilcServerKEInternalContext *ctx =
1179 (SilcServerKEInternalContext *)protocol->context;
1180 SilcServer server = (SilcServer)ctx->server;
1181 SilcSocketConnection sock = ctx->sock;
1182 SilcServerConnAuthInternalContext *proto_ctx;
1184 SILC_LOG_DEBUG(("Start"));
1186 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1187 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1188 /* Error occured during protocol */
1189 silc_protocol_free(protocol);
1190 sock->protocol = NULL;
1191 silc_ske_free_key_material(ctx->keymat);
1193 silc_packet_context_free(ctx->packet);
1195 silc_ske_free(ctx->ske);
1196 silc_free(ctx->dest_id);
1198 silc_schedule_task_del_by_callback(server->schedule,
1199 silc_server_failure_callback);
1200 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1201 "Key exchange failed");
1202 server->stat.auth_failures++;
1206 /* We now have the key material as the result of the key exchange
1207 protocol. Take the key material into use. Free the raw key material
1208 as soon as we've set them into use. */
1209 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1210 ctx->sock, ctx->keymat,
1211 ctx->ske->prop->cipher,
1212 ctx->ske->prop->pkcs,
1213 ctx->ske->prop->hash,
1214 ctx->ske->prop->hmac,
1215 ctx->ske->prop->group,
1217 silc_protocol_free(protocol);
1218 sock->protocol = NULL;
1219 silc_ske_free_key_material(ctx->keymat);
1221 silc_packet_context_free(ctx->packet);
1223 silc_ske_free(ctx->ske);
1224 silc_free(ctx->dest_id);
1226 silc_schedule_task_del_by_callback(server->schedule,
1227 silc_server_failure_callback);
1228 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1229 "Key exchange failed");
1230 server->stat.auth_failures++;
1233 silc_ske_free_key_material(ctx->keymat);
1235 /* Allocate internal context for the authentication protocol. This
1236 is sent as context for the protocol. */
1237 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1238 proto_ctx->server = (void *)server;
1239 proto_ctx->sock = sock;
1240 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1241 proto_ctx->responder = TRUE;
1242 proto_ctx->dest_id_type = ctx->dest_id_type;
1243 proto_ctx->dest_id = ctx->dest_id;
1244 proto_ctx->cconfig = ctx->cconfig;
1245 proto_ctx->sconfig = ctx->sconfig;
1246 proto_ctx->rconfig = ctx->rconfig;
1248 /* Free old protocol as it is finished now */
1249 silc_protocol_free(protocol);
1251 silc_packet_context_free(ctx->packet);
1253 sock->protocol = NULL;
1255 /* Allocate the authentication protocol. This is allocated here
1256 but we won't start it yet. We will be receiving party of this
1257 protocol thus we will wait that connecting party will make
1258 their first move. */
1259 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1260 &sock->protocol, proto_ctx,
1261 silc_server_accept_new_connection_final);
1263 /* Register timeout task. If the protocol is not executed inside
1264 this timelimit the connection will be terminated. */
1265 proto_ctx->timeout_task =
1266 silc_schedule_task_add(server->schedule, sock->sock,
1267 silc_server_timeout_remote,
1269 server->config->conn_auth_timeout, 0,
1274 /* Final part of accepting new connection. The connection has now
1275 been authenticated and keys has been exchanged. We also know whether
1276 this is client or server connection. */
1278 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1280 SilcProtocol protocol = (SilcProtocol)context;
1281 SilcServerConnAuthInternalContext *ctx =
1282 (SilcServerConnAuthInternalContext *)protocol->context;
1283 SilcServer server = (SilcServer)ctx->server;
1284 SilcSocketConnection sock = ctx->sock;
1285 SilcServerHBContext hb_context;
1286 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1288 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1289 SilcUInt32 num_sockets;
1291 SILC_LOG_DEBUG(("Start"));
1293 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1294 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1295 /* Error occured during protocol */
1296 silc_protocol_free(protocol);
1297 sock->protocol = NULL;
1299 silc_packet_context_free(ctx->packet);
1301 silc_ske_free(ctx->ske);
1302 silc_free(ctx->dest_id);
1304 silc_schedule_task_del_by_callback(server->schedule,
1305 silc_server_failure_callback);
1306 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1307 "Authentication failed");
1308 server->stat.auth_failures++;
1312 entry->data.last_receive = time(NULL);
1314 num_sockets = silc_server_num_sockets_by_ip(server, sock->ip,
1317 switch (ctx->conn_type) {
1318 case SILC_SOCKET_TYPE_CLIENT:
1320 SilcClientEntry client;
1321 SilcServerConfigClient *conn = ctx->cconfig;
1322 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1324 /* Check for maximum connections limit */
1326 if (conn->param->connections_max &&
1327 server->stat.my_clients >= conn->param->connections_max) {
1328 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1329 sock->hostname, sock->ip));
1330 silc_server_disconnect_remote(server, sock,
1331 "Server closed connection: "
1332 "Server is full, try again later");
1333 server->stat.auth_failures++;
1337 max_per_host = conn->param->connections_max_per_host;
1340 if (num_sockets >= max_per_host) {
1341 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1342 sock->hostname, sock->ip));
1343 silc_server_disconnect_remote(server, sock,
1344 "Server closed connection: "
1345 "Too many connections from your host");
1346 server->stat.auth_failures++;
1350 SILC_LOG_DEBUG(("Remote host is client"));
1351 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1354 /* Add the client to the client ID cache. The nickname and Client ID
1355 and other information is created after we have received NEW_CLIENT
1356 packet from client. */
1357 client = silc_idlist_add_client(server->local_list,
1358 NULL, NULL, NULL, NULL, NULL, sock, 0);
1360 SILC_LOG_ERROR(("Could not add new client to cache"));
1361 silc_free(sock->user_data);
1362 silc_server_disconnect_remote(server, sock,
1363 "Server closed connection: "
1364 "Authentication failed");
1365 server->stat.auth_failures++;
1370 server->stat.my_clients++;
1371 server->stat.clients++;
1372 if (server->server_type == SILC_ROUTER)
1373 server->stat.cell_clients++;
1375 /* Get connection parameters */
1377 if (conn->param->keepalive_secs)
1378 hearbeat_timeout = conn->param->keepalive_secs;
1381 id_entry = (void *)client;
1384 case SILC_SOCKET_TYPE_SERVER:
1385 case SILC_SOCKET_TYPE_ROUTER:
1387 SilcServerEntry new_server;
1388 bool initiator = FALSE;
1389 bool backup_local = FALSE;
1390 bool backup_router = FALSE;
1391 char *backup_replace_ip = NULL;
1392 SilcUInt16 backup_replace_port = 0;
1393 SilcServerConfigServer *sconn = ctx->sconfig;
1394 SilcServerConfigRouter *rconn = ctx->rconfig;
1395 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1397 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && rconn) {
1399 /* Check for maximum connections limit */
1400 if (rconn->param->connections_max &&
1401 server->stat.my_routers >= rconn->param->connections_max) {
1402 silc_server_disconnect_remote(server, sock,
1403 "Server closed connection: "
1404 "Server is full, try again later");
1405 server->stat.auth_failures++;
1408 max_per_host = rconn->param->connections_max_per_host;
1410 if (rconn->param->keepalive_secs)
1411 hearbeat_timeout = rconn->param->keepalive_secs;
1414 initiator = rconn->initiator;
1415 backup_local = rconn->backup_local;
1416 backup_router = rconn->backup_router;
1417 backup_replace_ip = rconn->backup_replace_ip;
1418 backup_replace_port = rconn->backup_replace_port;
1421 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER && sconn) {
1423 /* Check for maximum connections limit */
1424 if (sconn->param->connections_max &&
1425 server->stat.my_servers >= sconn->param->connections_max) {
1426 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1427 sock->hostname, sock->ip));
1428 silc_server_disconnect_remote(server, sock,
1429 "Server closed connection: "
1430 "Server is full, try again later");
1431 server->stat.auth_failures++;
1434 max_per_host = sconn->param->connections_max_per_host;
1436 if (sconn->param->keepalive_secs)
1437 hearbeat_timeout = sconn->param->keepalive_secs;
1440 backup_router = sconn->backup_router;
1443 if (num_sockets >= max_per_host) {
1444 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1445 sock->hostname, sock->ip));
1446 silc_server_disconnect_remote(server, sock,
1447 "Server closed connection: "
1448 "Too many connections from your host");
1449 server->stat.auth_failures++;
1453 SILC_LOG_DEBUG(("Remote host is %s",
1454 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1455 "server" : (backup_router ?
1456 "backup router" : "router")));
1457 SILC_LOG_INFO(("Connection s (%s) is %s", sock->hostname,
1458 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1459 "server" : (backup_router ?
1460 "backup router" : "router")));
1462 /* Add the server into server cache. The server name and Server ID
1463 is updated after we have received NEW_SERVER packet from the
1464 server. We mark ourselves as router for this server if we really
1467 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1468 server->local_list : (backup_router ?
1469 server->local_list :
1470 server->global_list)),
1472 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1473 SILC_SERVER : SILC_ROUTER),
1475 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1476 server->id_entry : (backup_router ?
1477 server->id_entry : NULL)),
1480 SILC_LOG_ERROR(("Could not add new server to cache"));
1481 silc_free(sock->user_data);
1482 silc_server_disconnect_remote(server, sock,
1483 "Server closed connection: "
1484 "Authentication failed");
1485 server->stat.auth_failures++;
1490 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1491 server->stat.my_servers++;
1493 server->stat.my_routers++;
1494 server->stat.servers++;
1496 id_entry = (void *)new_server;
1498 /* If the incoming connection is router and marked as backup router
1499 then add it to be one of our backups */
1500 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1501 silc_server_backup_add(server, new_server, backup_replace_ip,
1502 backup_replace_port, backup_local);
1504 /* Change it back to SERVER type since that's what it really is. */
1506 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1508 new_server->server_type = SILC_BACKUP_ROUTER;
1511 /* Check whether this connection is to be our primary router connection
1512 if we do not already have the primary route. */
1513 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1514 if (silc_server_config_is_primary_route(server) && !initiator)
1517 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1518 server->standalone = FALSE;
1519 if (!server->id_entry->router) {
1520 server->id_entry->router = id_entry;
1521 server->router = id_entry;
1532 sock->type = ctx->conn_type;
1534 /* Add the common data structure to the ID entry. */
1535 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1537 /* Add to sockets internal pointer for fast referencing */
1538 silc_free(sock->user_data);
1539 sock->user_data = id_entry;
1541 /* Connection has been fully established now. Everything is ok. */
1542 SILC_LOG_DEBUG(("New connection authenticated"));
1544 /* Perform keepalive. The `hb_context' will be freed automatically
1545 when finally calling the silc_socket_free function. */
1546 hb_context = silc_calloc(1, sizeof(*hb_context));
1547 hb_context->server = server;
1548 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1549 silc_server_perform_heartbeat,
1553 silc_schedule_task_del_by_callback(server->schedule,
1554 silc_server_failure_callback);
1555 silc_protocol_free(protocol);
1557 silc_packet_context_free(ctx->packet);
1559 silc_ske_free(ctx->ske);
1560 silc_free(ctx->dest_id);
1562 sock->protocol = NULL;
1565 /* This function is used to read packets from network and send packets to
1566 network. This is usually a generic task. */
1568 SILC_TASK_CALLBACK(silc_server_packet_process)
1570 SilcServer server = (SilcServer)context;
1571 SilcSocketConnection sock = server->sockets[fd];
1572 SilcIDListData idata;
1573 SilcCipher cipher = NULL;
1574 SilcHmac hmac = NULL;
1575 SilcUInt32 sequence = 0;
1581 SILC_LOG_DEBUG(("Processing packet"));
1583 /* Packet sending */
1585 if (type == SILC_TASK_WRITE) {
1586 /* Do not send data to disconnected connection */
1587 if (SILC_IS_DISCONNECTED(sock))
1590 server->stat.packets_sent++;
1592 if (sock->outbuf->data - sock->outbuf->head)
1593 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1595 /* Send the packet */
1596 ret = silc_packet_send(sock, TRUE);
1598 /* If returned -2 could not write to connection now, will do
1604 SILC_LOG_ERROR(("Error sending packet to connection "
1605 "%s:%d [%s]", sock->hostname, sock->port,
1606 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1607 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1608 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1613 /* The packet has been sent and now it is time to set the connection
1614 back to only for input. When there is again some outgoing data
1615 available for this connection it will be set for output as well.
1616 This call clears the output setting and sets it only for input. */
1617 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1618 SILC_UNSET_OUTBUF_PENDING(sock);
1620 silc_buffer_clear(sock->outbuf);
1624 /* Packet receiving */
1626 /* Read some data from connection */
1627 ret = silc_packet_receive(sock);
1631 SILC_LOG_ERROR(("Error receiving packet from connection "
1632 "%s:%d [%s] %s", sock->hostname, sock->port,
1633 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1634 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1635 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1636 "Router"), strerror(errno)));
1642 SILC_LOG_DEBUG(("Read EOF"));
1644 /* If connection is disconnecting already we will finally
1645 close the connection */
1646 if (SILC_IS_DISCONNECTING(sock)) {
1647 if (sock->user_data)
1648 silc_server_free_sock_user_data(server, sock, NULL);
1649 silc_server_close_connection(server, sock);
1653 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1654 SILC_SET_DISCONNECTING(sock);
1656 if (sock->user_data) {
1658 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1659 silc_server_free_sock_user_data(server, sock, tmp);
1661 silc_server_free_sock_user_data(server, sock, NULL);
1662 } else if (server->router_conn && server->router_conn->sock == sock &&
1663 !server->router && server->standalone)
1664 silc_schedule_task_add(server->schedule, 0,
1665 silc_server_connect_to_router,
1668 SILC_TASK_PRI_NORMAL);
1670 silc_server_close_connection(server, sock);
1674 /* If connection is disconnecting or disconnected we will ignore
1676 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1677 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1681 server->stat.packets_received++;
1683 /* Get keys and stuff from ID entry */
1684 idata = (SilcIDListData)sock->user_data;
1686 cipher = idata->receive_key;
1687 hmac = idata->hmac_receive;
1688 sequence = idata->psn_receive;
1691 /* Process the packet. This will call the parser that will then
1692 decrypt and parse the packet. */
1693 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1694 TRUE : FALSE, cipher, hmac, sequence,
1695 silc_server_packet_parse, server);
1697 /* If this socket connection is not authenticated yet and the packet
1698 processing failed we will drop the connection since it can be
1699 a malicious flooder. */
1700 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1701 (!sock->protocol || sock->protocol->protocol->type ==
1702 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1703 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1704 SILC_SET_DISCONNECTING(sock);
1706 if (sock->user_data)
1707 silc_server_free_sock_user_data(server, sock, NULL);
1708 silc_server_close_connection(server, sock);
1712 /* Parses whole packet, received earlier. */
1714 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1716 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1717 SilcServer server = (SilcServer)parse_ctx->context;
1718 SilcSocketConnection sock = parse_ctx->sock;
1719 SilcPacketContext *packet = parse_ctx->packet;
1720 SilcIDListData idata = (SilcIDListData)sock->user_data;
1723 SILC_LOG_DEBUG(("Start"));
1725 /* Parse the packet */
1726 if (parse_ctx->normal)
1727 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1729 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1731 /* If entry is disabled ignore what we got. */
1732 if (ret != SILC_PACKET_RESUME_ROUTER &&
1733 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1734 SILC_LOG_DEBUG(("Connection is disabled"));
1738 if (ret == SILC_PACKET_NONE)
1741 /* Check that the the current client ID is same as in the client's packet. */
1742 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1743 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1744 if (client && client->id) {
1745 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1746 packet->src_id_type);
1747 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1755 if (server->server_type == SILC_ROUTER) {
1756 /* Route the packet if it is not destined to us. Other ID types but
1757 server are handled separately after processing them. */
1758 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1759 packet->dst_id_type == SILC_ID_SERVER &&
1760 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1761 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1763 /* Route the packet to fastest route for the destination ID */
1764 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1765 packet->dst_id_type);
1768 silc_server_packet_route(server,
1769 silc_server_route_get(server, id,
1770 packet->dst_id_type),
1777 /* Parse the incoming packet type */
1778 silc_server_packet_parse_type(server, sock, packet);
1780 if (server->server_type == SILC_ROUTER) {
1781 /* Broadcast packet if it is marked as broadcast packet and it is
1782 originated from router and we are router. */
1783 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1784 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1785 !server->standalone) {
1786 /* Broadcast to our primary route */
1787 silc_server_packet_broadcast(server, server->router->connection, packet);
1789 /* If we have backup routers then we need to feed all broadcast
1790 data to those servers. */
1791 silc_server_backup_broadcast(server, sock, packet);
1796 silc_packet_context_free(packet);
1797 silc_free(parse_ctx);
1800 /* Parser callback called by silc_packet_receive_process. This merely
1801 registers timeout that will handle the actual parsing when appropriate. */
1803 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1806 SilcServer server = (SilcServer)context;
1807 SilcSocketConnection sock = parser_context->sock;
1808 SilcIDListData idata = (SilcIDListData)sock->user_data;
1811 idata->psn_receive = parser_context->packet->sequence + 1;
1813 /* If protocol for this connection is key exchange or rekey then we'll
1814 process all packets synchronously, since there might be packets in
1815 queue that we are not able to decrypt without first processing the
1816 packets before them. */
1817 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1818 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1819 (sock->protocol && sock->protocol->protocol &&
1820 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1821 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1822 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1825 /* Reprocess data since we'll return FALSE here. This is because
1826 the idata->receive_key might have become valid in the last packet
1827 and we want to call this processor with valid cipher. */
1829 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1830 TRUE : FALSE, idata->receive_key,
1831 idata->hmac_receive, idata->psn_receive,
1832 silc_server_packet_parse, server);
1834 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1835 TRUE : FALSE, NULL, NULL, 0,
1836 silc_server_packet_parse, server);
1840 switch (sock->type) {
1841 case SILC_SOCKET_TYPE_UNKNOWN:
1842 case SILC_SOCKET_TYPE_CLIENT:
1843 /* Parse the packet with timeout */
1844 silc_schedule_task_add(server->schedule, sock->sock,
1845 silc_server_packet_parse_real,
1846 (void *)parser_context, 0, 100000,
1848 SILC_TASK_PRI_NORMAL);
1850 case SILC_SOCKET_TYPE_SERVER:
1851 case SILC_SOCKET_TYPE_ROUTER:
1852 /* Packets from servers are parsed immediately */
1853 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1863 /* Parses the packet type and calls what ever routines the packet type
1864 requires. This is done for all incoming packets. */
1866 void silc_server_packet_parse_type(SilcServer server,
1867 SilcSocketConnection sock,
1868 SilcPacketContext *packet)
1870 SilcPacketType type = packet->type;
1871 SilcIDListData idata = (SilcIDListData)sock->user_data;
1873 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1875 /* Parse the packet type */
1877 case SILC_PACKET_DISCONNECT:
1878 SILC_LOG_DEBUG(("Disconnect packet"));
1879 if (packet->flags & SILC_PACKET_FLAG_LIST)
1883 case SILC_PACKET_SUCCESS:
1885 * Success received for something. For now we can have only
1886 * one protocol for connection executing at once hence this
1887 * success message is for whatever protocol is executing currently.
1889 SILC_LOG_DEBUG(("Success packet"));
1890 if (packet->flags & SILC_PACKET_FLAG_LIST)
1893 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1896 case SILC_PACKET_FAILURE:
1898 * Failure received for something. For now we can have only
1899 * one protocol for connection executing at once hence this
1900 * failure message is for whatever protocol is executing currently.
1902 SILC_LOG_DEBUG(("Failure packet"));
1903 if (packet->flags & SILC_PACKET_FLAG_LIST)
1905 if (sock->protocol) {
1906 SilcServerFailureContext f;
1907 f = silc_calloc(1, sizeof(*f));
1911 /* We will wait 5 seconds to process this failure packet */
1912 silc_schedule_task_add(server->schedule, sock->sock,
1913 silc_server_failure_callback, (void *)f, 5, 0,
1914 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1918 case SILC_PACKET_REJECT:
1919 SILC_LOG_DEBUG(("Reject packet"));
1920 if (packet->flags & SILC_PACKET_FLAG_LIST)
1925 case SILC_PACKET_NOTIFY:
1927 * Received notify packet. Server can receive notify packets from
1928 * router. Server then relays the notify messages to clients if needed.
1930 SILC_LOG_DEBUG(("Notify packet"));
1931 if (packet->flags & SILC_PACKET_FLAG_LIST)
1932 silc_server_notify_list(server, sock, packet);
1934 silc_server_notify(server, sock, packet);
1940 case SILC_PACKET_CHANNEL_MESSAGE:
1942 * Received channel message. Channel messages are special packets
1943 * (although probably most common ones) thus they are handled
1946 SILC_LOG_DEBUG(("Channel Message packet"));
1947 if (packet->flags & SILC_PACKET_FLAG_LIST)
1949 idata->last_receive = time(NULL);
1950 silc_server_channel_message(server, sock, packet);
1953 case SILC_PACKET_CHANNEL_KEY:
1955 * Received key for channel. As channels are created by the router
1956 * the keys are as well. We will distribute the key to all of our
1957 * locally connected clients on the particular channel. Router
1958 * never receives this channel and thus is ignored.
1960 SILC_LOG_DEBUG(("Channel Key packet"));
1961 if (packet->flags & SILC_PACKET_FLAG_LIST)
1963 silc_server_channel_key(server, sock, packet);
1969 case SILC_PACKET_COMMAND:
1971 * Recived command. Processes the command request and allocates the
1972 * command context and calls the command.
1974 SILC_LOG_DEBUG(("Command packet"));
1975 if (packet->flags & SILC_PACKET_FLAG_LIST)
1977 silc_server_command_process(server, sock, packet);
1980 case SILC_PACKET_COMMAND_REPLY:
1982 * Received command reply packet. Received command reply to command. It
1983 * may be reply to command sent by us or reply to command sent by client
1984 * that we've routed further.
1986 SILC_LOG_DEBUG(("Command Reply packet"));
1987 if (packet->flags & SILC_PACKET_FLAG_LIST)
1989 silc_server_command_reply(server, sock, packet);
1993 * Private Message packets
1995 case SILC_PACKET_PRIVATE_MESSAGE:
1997 * Received private message packet. The packet is coming from either
2000 SILC_LOG_DEBUG(("Private Message packet"));
2001 if (packet->flags & SILC_PACKET_FLAG_LIST)
2003 idata->last_receive = time(NULL);
2004 silc_server_private_message(server, sock, packet);
2007 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2009 * Private message key packet.
2011 if (packet->flags & SILC_PACKET_FLAG_LIST)
2013 silc_server_private_message_key(server, sock, packet);
2017 * Key Exchange protocol packets
2019 case SILC_PACKET_KEY_EXCHANGE:
2020 SILC_LOG_DEBUG(("KE packet"));
2021 if (packet->flags & SILC_PACKET_FLAG_LIST)
2024 if (sock->protocol && sock->protocol->protocol &&
2025 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2027 SilcServerKEInternalContext *proto_ctx =
2028 (SilcServerKEInternalContext *)sock->protocol->context;
2030 proto_ctx->packet = silc_packet_context_dup(packet);
2032 /* Let the protocol handle the packet */
2033 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2035 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2036 "protocol active, packet dropped."));
2040 case SILC_PACKET_KEY_EXCHANGE_1:
2041 SILC_LOG_DEBUG(("KE 1 packet"));
2042 if (packet->flags & SILC_PACKET_FLAG_LIST)
2045 if (sock->protocol && sock->protocol->protocol &&
2046 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2047 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2049 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2050 SilcServerRekeyInternalContext *proto_ctx =
2051 (SilcServerRekeyInternalContext *)sock->protocol->context;
2053 if (proto_ctx->packet)
2054 silc_packet_context_free(proto_ctx->packet);
2056 proto_ctx->packet = silc_packet_context_dup(packet);
2058 /* Let the protocol handle the packet */
2059 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2061 SilcServerKEInternalContext *proto_ctx =
2062 (SilcServerKEInternalContext *)sock->protocol->context;
2064 if (proto_ctx->packet)
2065 silc_packet_context_free(proto_ctx->packet);
2067 proto_ctx->packet = silc_packet_context_dup(packet);
2068 proto_ctx->dest_id_type = packet->src_id_type;
2069 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2070 packet->src_id_type);
2071 if (!proto_ctx->dest_id)
2074 /* Let the protocol handle the packet */
2075 silc_protocol_execute(sock->protocol, server->schedule,
2079 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2080 "protocol active, packet dropped."));
2084 case SILC_PACKET_KEY_EXCHANGE_2:
2085 SILC_LOG_DEBUG(("KE 2 packet"));
2086 if (packet->flags & SILC_PACKET_FLAG_LIST)
2089 if (sock->protocol && sock->protocol->protocol &&
2090 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2091 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2093 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2094 SilcServerRekeyInternalContext *proto_ctx =
2095 (SilcServerRekeyInternalContext *)sock->protocol->context;
2097 if (proto_ctx->packet)
2098 silc_packet_context_free(proto_ctx->packet);
2100 proto_ctx->packet = silc_packet_context_dup(packet);
2102 /* Let the protocol handle the packet */
2103 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2105 SilcServerKEInternalContext *proto_ctx =
2106 (SilcServerKEInternalContext *)sock->protocol->context;
2108 if (proto_ctx->packet)
2109 silc_packet_context_free(proto_ctx->packet);
2111 proto_ctx->packet = silc_packet_context_dup(packet);
2112 proto_ctx->dest_id_type = packet->src_id_type;
2113 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2114 packet->src_id_type);
2115 if (!proto_ctx->dest_id)
2118 /* Let the protocol handle the packet */
2119 silc_protocol_execute(sock->protocol, server->schedule,
2123 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2124 "protocol active, packet dropped."));
2128 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2130 * Connection authentication request packet. When we receive this packet
2131 * we will send to the other end information about our mandatory
2132 * authentication method for the connection. This packet maybe received
2135 SILC_LOG_DEBUG(("Connection authentication request packet"));
2136 if (packet->flags & SILC_PACKET_FLAG_LIST)
2138 silc_server_connection_auth_request(server, sock, packet);
2142 * Connection Authentication protocol packets
2144 case SILC_PACKET_CONNECTION_AUTH:
2145 /* Start of the authentication protocol. We receive here the
2146 authentication data and will verify it. */
2147 SILC_LOG_DEBUG(("Connection auth packet"));
2148 if (packet->flags & SILC_PACKET_FLAG_LIST)
2151 if (sock->protocol && sock->protocol->protocol->type
2152 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2154 SilcServerConnAuthInternalContext *proto_ctx =
2155 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2157 proto_ctx->packet = silc_packet_context_dup(packet);
2159 /* Let the protocol handle the packet */
2160 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2162 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2163 "protocol active, packet dropped."));
2167 case SILC_PACKET_NEW_ID:
2169 * Received New ID packet. This includes some new ID that has been
2170 * created. It may be for client, server or channel. This is the way
2171 * to distribute information about new registered entities in the
2174 SILC_LOG_DEBUG(("New ID packet"));
2175 if (packet->flags & SILC_PACKET_FLAG_LIST)
2176 silc_server_new_id_list(server, sock, packet);
2178 silc_server_new_id(server, sock, packet);
2181 case SILC_PACKET_NEW_CLIENT:
2183 * Received new client packet. This includes client information that
2184 * we will use to create initial client ID. After creating new
2185 * ID we will send it to the client.
2187 SILC_LOG_DEBUG(("New Client packet"));
2188 if (packet->flags & SILC_PACKET_FLAG_LIST)
2190 silc_server_new_client(server, sock, packet);
2193 case SILC_PACKET_NEW_SERVER:
2195 * Received new server packet. This includes Server ID and some other
2196 * information that we may save. This is received after server has
2199 SILC_LOG_DEBUG(("New Server packet"));
2200 if (packet->flags & SILC_PACKET_FLAG_LIST)
2202 silc_server_new_server(server, sock, packet);
2205 case SILC_PACKET_NEW_CHANNEL:
2207 * Received new channel packet. Information about new channel in the
2208 * network are distributed using this packet.
2210 SILC_LOG_DEBUG(("New Channel packet"));
2211 if (packet->flags & SILC_PACKET_FLAG_LIST)
2212 silc_server_new_channel_list(server, sock, packet);
2214 silc_server_new_channel(server, sock, packet);
2217 case SILC_PACKET_HEARTBEAT:
2219 * Received heartbeat.
2221 SILC_LOG_DEBUG(("Heartbeat packet"));
2222 if (packet->flags & SILC_PACKET_FLAG_LIST)
2226 case SILC_PACKET_KEY_AGREEMENT:
2228 * Received heartbeat.
2230 SILC_LOG_DEBUG(("Key agreement packet"));
2231 if (packet->flags & SILC_PACKET_FLAG_LIST)
2233 silc_server_key_agreement(server, sock, packet);
2236 case SILC_PACKET_REKEY:
2238 * Received re-key packet. The sender wants to regenerate the session
2241 SILC_LOG_DEBUG(("Re-key packet"));
2242 if (packet->flags & SILC_PACKET_FLAG_LIST)
2244 silc_server_rekey(server, sock, packet);
2247 case SILC_PACKET_REKEY_DONE:
2249 * The re-key is done.
2251 SILC_LOG_DEBUG(("Re-key done packet"));
2252 if (packet->flags & SILC_PACKET_FLAG_LIST)
2255 if (sock->protocol && sock->protocol->protocol &&
2256 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2258 SilcServerRekeyInternalContext *proto_ctx =
2259 (SilcServerRekeyInternalContext *)sock->protocol->context;
2261 if (proto_ctx->packet)
2262 silc_packet_context_free(proto_ctx->packet);
2264 proto_ctx->packet = silc_packet_context_dup(packet);
2266 /* Let the protocol handle the packet */
2267 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2269 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2270 "protocol active, packet dropped."));
2274 case SILC_PACKET_FTP:
2276 SILC_LOG_DEBUG(("FTP packet"));
2277 if (packet->flags & SILC_PACKET_FLAG_LIST)
2279 silc_server_ftp(server, sock, packet);
2282 case SILC_PACKET_RESUME_ROUTER:
2283 /* Resume router packet received. This packet is received for backup
2284 router resuming protocol. */
2285 SILC_LOG_DEBUG(("Resume router packet"));
2286 if (packet->flags & SILC_PACKET_FLAG_LIST)
2288 silc_server_backup_resume_router(server, sock, packet);
2292 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2298 /* Creates connection to a remote router. */
2300 void silc_server_create_connection(SilcServer server,
2301 const char *remote_host, SilcUInt32 port)
2303 SilcServerConnection sconn;
2305 /* Allocate connection object for hold connection specific stuff. */
2306 sconn = silc_calloc(1, sizeof(*sconn));
2307 sconn->server = server;
2308 sconn->remote_host = strdup(remote_host);
2309 sconn->remote_port = port;
2310 sconn->no_reconnect = TRUE;
2311 sconn->param = &server->config->param;
2313 silc_schedule_task_add(server->schedule, 0,
2314 silc_server_connect_router,
2315 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2316 SILC_TASK_PRI_NORMAL);
2319 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2321 silc_socket_free((SilcSocketConnection)context);
2324 /* Closes connection to socket connection */
2326 void silc_server_close_connection(SilcServer server,
2327 SilcSocketConnection sock)
2329 if (!server->sockets[sock->sock])
2332 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2334 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2335 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2336 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2339 /* We won't listen for this connection anymore */
2340 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2342 /* Unregister all tasks */
2343 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2345 /* Close the actual connection */
2346 silc_net_close_connection(sock->sock);
2347 server->sockets[sock->sock] = NULL;
2349 /* If sock->user_data is NULL then we'll check for active protocols
2350 here since the silc_server_free_sock_user_data has not been called
2351 for this connection. */
2352 if (!sock->user_data) {
2353 /* If any protocol is active cancel its execution. It will call
2354 the final callback which will finalize the disconnection. */
2355 if (sock->protocol) {
2356 silc_protocol_cancel(sock->protocol, server->schedule);
2357 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2358 silc_protocol_execute_final(sock->protocol, server->schedule);
2359 sock->protocol = NULL;
2364 silc_schedule_task_add(server->schedule, 0,
2365 silc_server_close_connection_final,
2366 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2367 SILC_TASK_PRI_NORMAL);
2370 /* Sends disconnect message to remote connection and disconnects the
2373 void silc_server_disconnect_remote(SilcServer server,
2374 SilcSocketConnection sock,
2375 const char *fmt, ...)
2378 unsigned char buf[4096];
2383 memset(buf, 0, sizeof(buf));
2385 vsprintf(buf, fmt, ap);
2388 SILC_LOG_DEBUG(("Disconnecting remote host"));
2390 /* Notify remote end that the conversation is over. The notify message
2391 is tried to be sent immediately. */
2392 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2393 buf, strlen(buf), TRUE);
2395 /* Mark the connection to be disconnected */
2396 SILC_SET_DISCONNECTED(sock);
2397 silc_server_close_connection(server, sock);
2402 SilcClientEntry client;
2403 } *FreeClientInternal;
2405 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2407 FreeClientInternal i = (FreeClientInternal)context;
2409 silc_idlist_del_data(i->client);
2410 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2414 /* Frees client data and notifies about client's signoff. */
2416 void silc_server_free_client_data(SilcServer server,
2417 SilcSocketConnection sock,
2418 SilcClientEntry client,
2420 const char *signoff)
2422 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2424 /* If there is pending outgoing data for the client then purge it
2425 to the network before removing the client entry. */
2426 silc_server_packet_queue_purge(server, sock);
2431 /* Send SIGNOFF notify to routers. */
2432 if (notify && !server->standalone && server->router)
2433 silc_server_send_notify_signoff(server, server->router->connection,
2434 server->server_type == SILC_SERVER ?
2435 FALSE : TRUE, client->id, signoff);
2437 /* Remove client from all channels */
2439 silc_server_remove_from_channels(server, NULL, client,
2440 TRUE, (char *)signoff, TRUE);
2442 silc_server_remove_from_channels(server, NULL, client,
2443 FALSE, NULL, FALSE);
2445 /* Update statistics */
2446 server->stat.my_clients--;
2447 server->stat.clients--;
2448 if (server->server_type == SILC_ROUTER)
2449 server->stat.cell_clients--;
2450 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2451 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2453 /* We will not delete the client entry right away. We will take it
2454 into history (for WHOWAS command) for 5 minutes */
2457 silc_schedule_task_add(server->schedule, 0,
2458 silc_server_free_client_data_timeout,
2460 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2461 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2462 client->router = NULL;
2463 client->connection = NULL;
2467 /* Frees user_data pointer from socket connection object. This also sends
2468 appropriate notify packets to the network to inform about leaving
2471 void silc_server_free_sock_user_data(SilcServer server,
2472 SilcSocketConnection sock,
2473 const char *signoff_message)
2475 SILC_LOG_DEBUG(("Start"));
2477 switch (sock->type) {
2478 case SILC_SOCKET_TYPE_CLIENT:
2480 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2481 silc_server_free_client_data(server, sock, user_data, TRUE,
2485 case SILC_SOCKET_TYPE_SERVER:
2486 case SILC_SOCKET_TYPE_ROUTER:
2488 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2489 SilcServerEntry backup_router = NULL;
2492 backup_router = silc_server_backup_get(server, user_data->id);
2494 /* If this was our primary router connection then we're lost to
2495 the outside world. */
2496 if (server->router == user_data) {
2497 /* Check whether we have a backup router connection */
2498 if (!backup_router || backup_router == user_data) {
2499 silc_schedule_task_add(server->schedule, 0,
2500 silc_server_connect_to_router,
2503 SILC_TASK_PRI_NORMAL);
2505 server->id_entry->router = NULL;
2506 server->router = NULL;
2507 server->standalone = TRUE;
2508 backup_router = NULL;
2510 SILC_LOG_INFO(("New primary router is backup router %s",
2511 backup_router->server_name));
2512 SILC_LOG_DEBUG(("New primary router is backup router %s",
2513 backup_router->server_name));
2514 server->id_entry->router = backup_router;
2515 server->router = backup_router;
2516 server->router_connect = time(0);
2517 server->backup_primary = TRUE;
2518 if (server->server_type == SILC_BACKUP_ROUTER) {
2519 server->server_type = SILC_ROUTER;
2521 /* We'll need to constantly try to reconnect to the primary
2522 router so that we'll see when it comes back online. */
2523 silc_server_backup_reconnect(server, sock->ip, sock->port,
2524 silc_server_backup_connected,
2528 /* Mark this connection as replaced */
2529 silc_server_backup_replaced_add(server, user_data->id,
2532 } else if (backup_router) {
2533 SILC_LOG_INFO(("Enabling the use of backup router %s",
2534 backup_router->server_name));
2535 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2536 backup_router->server_name));
2538 /* Mark this connection as replaced */
2539 silc_server_backup_replaced_add(server, user_data->id,
2543 if (!backup_router) {
2544 /* Free all client entries that this server owns as they will
2545 become invalid now as well. */
2547 silc_server_remove_clients_by_server(server, user_data, TRUE);
2548 if (server->server_type == SILC_SERVER)
2549 silc_server_remove_channels_by_server(server, user_data);
2551 /* Update the client entries of this server to the new backup
2552 router. This also removes the clients that *really* was owned
2553 by the primary router and went down with the router. */
2554 silc_server_update_clients_by_server(server, user_data, backup_router,
2556 silc_server_update_servers_by_server(server, user_data, backup_router);
2557 if (server->server_type == SILC_SERVER)
2558 silc_server_update_channels_by_server(server, user_data,
2562 /* Free the server entry */
2563 silc_server_backup_del(server, user_data);
2564 silc_server_backup_replaced_del(server, user_data);
2565 silc_idlist_del_data(user_data);
2566 if (!silc_idlist_del_server(server->local_list, user_data))
2567 silc_idlist_del_server(server->global_list, user_data);
2568 server->stat.my_servers--;
2569 server->stat.servers--;
2570 if (server->server_type == SILC_ROUTER)
2571 server->stat.cell_servers--;
2573 if (backup_router) {
2574 /* Announce all of our stuff that was created about 5 minutes ago.
2575 The backup router knows all the other stuff already. */
2576 if (server->server_type == SILC_ROUTER)
2577 silc_server_announce_servers(server, FALSE, time(0) - 300,
2578 backup_router->connection);
2580 /* Announce our clients and channels to the router */
2581 silc_server_announce_clients(server, time(0) - 300,
2582 backup_router->connection);
2583 silc_server_announce_channels(server, time(0) - 300,
2584 backup_router->connection);
2590 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2592 silc_idlist_del_data(user_data);
2593 silc_free(user_data);
2598 /* If any protocol is active cancel its execution */
2599 if (sock->protocol) {
2600 silc_protocol_cancel(sock->protocol, server->schedule);
2601 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2602 silc_protocol_execute_final(sock->protocol, server->schedule);
2603 sock->protocol = NULL;
2606 sock->user_data = NULL;
2609 /* Removes client from all channels it has joined. This is used when client
2610 connection is disconnected. If the client on a channel is last, the
2611 channel is removed as well. This sends the SIGNOFF notify types. */
2613 void silc_server_remove_from_channels(SilcServer server,
2614 SilcSocketConnection sock,
2615 SilcClientEntry client,
2617 char *signoff_message,
2620 SilcChannelEntry channel;
2621 SilcChannelClientEntry chl;
2622 SilcHashTableList htl;
2625 SILC_LOG_DEBUG(("Start"));
2627 if (!client || !client->id)
2630 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2632 /* Remove the client from all channels. The client is removed from
2633 the channels' user list. */
2634 silc_hash_table_list(client->channels, &htl);
2635 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2636 channel = chl->channel;
2638 /* Remove channel from client's channel list */
2639 silc_hash_table_del(client->channels, channel);
2641 /* Remove channel if there is no users anymore */
2642 if (server->server_type == SILC_ROUTER &&
2643 silc_hash_table_count(channel->user_list) < 2) {
2645 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2646 if (silc_idlist_del_channel(server->local_list, channel))
2647 server->stat.my_channels--;
2649 silc_idlist_del_channel(server->global_list, channel);
2653 /* Remove client from channel's client list */
2654 silc_hash_table_del(channel->user_list, chl->client);
2655 channel->user_count--;
2657 /* If there is no global users on the channel anymore mark the channel
2658 as local channel. Do not check if the removed client is local client. */
2659 if (server->server_type != SILC_ROUTER && channel->global_users &&
2660 chl->client->router && !silc_server_channel_has_global(channel))
2661 channel->global_users = FALSE;
2664 server->stat.my_chanclients--;
2666 /* If there is not at least one local user on the channel then we don't
2667 need the channel entry anymore, we can remove it safely. */
2668 if (server->server_type != SILC_ROUTER &&
2669 !silc_server_channel_has_local(channel)) {
2670 /* Notify about leaving client if this channel has global users. */
2671 if (notify && channel->global_users)
2672 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2673 SILC_NOTIFY_TYPE_SIGNOFF,
2674 signoff_message ? 2 : 1,
2675 clidp->data, clidp->len,
2676 signoff_message, signoff_message ?
2677 strlen(signoff_message) : 0);
2680 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2682 if (channel->founder_key) {
2683 /* The founder auth data exists, do not remove the channel entry */
2684 SilcChannelClientEntry chl2;
2685 SilcHashTableList htl2;
2687 channel->disabled = TRUE;
2689 silc_hash_table_list(channel->user_list, &htl2);
2690 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2691 silc_hash_table_del(chl2->client->channels, channel);
2692 silc_hash_table_del(channel->user_list, chl2->client);
2693 channel->user_count--;
2696 silc_hash_table_list_reset(&htl2);
2700 /* Remove the channel entry */
2701 if (silc_idlist_del_channel(server->local_list, channel))
2702 server->stat.my_channels--;
2704 silc_idlist_del_channel(server->global_list, channel);
2708 /* Send notify to channel about client leaving SILC and thus
2709 the entire channel. */
2711 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2712 SILC_NOTIFY_TYPE_SIGNOFF,
2713 signoff_message ? 2 : 1,
2714 clidp->data, clidp->len,
2715 signoff_message, signoff_message ?
2716 strlen(signoff_message) : 0);
2718 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2719 /* Re-generate channel key */
2720 if (!silc_server_create_channel_key(server, channel, 0))
2723 /* Send the channel key to the channel. The key of course is not sent
2724 to the client who was removed from the channel. */
2725 silc_server_send_channel_key(server, client->connection, channel,
2726 server->server_type == SILC_ROUTER ?
2727 FALSE : !server->standalone);
2732 silc_hash_table_list_reset(&htl);
2733 silc_buffer_free(clidp);
2736 /* Removes client from one channel. This is used for example when client
2737 calls LEAVE command to remove itself from the channel. Returns TRUE
2738 if channel still exists and FALSE if the channel is removed when
2739 last client leaves the channel. If `notify' is FALSE notify messages
2742 int silc_server_remove_from_one_channel(SilcServer server,
2743 SilcSocketConnection sock,
2744 SilcChannelEntry channel,
2745 SilcClientEntry client,
2748 SilcChannelClientEntry chl;
2751 SILC_LOG_DEBUG(("Start"));
2753 /* Get the entry to the channel, if this client is not on the channel
2755 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2758 /* Remove the client from the channel. The client is removed from
2759 the channel's user list. */
2761 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2763 /* Remove channel from client's channel list */
2764 silc_hash_table_del(client->channels, chl->channel);
2766 /* Remove channel if there is no users anymore */
2767 if (server->server_type == SILC_ROUTER &&
2768 silc_hash_table_count(channel->user_list) < 2) {
2770 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2771 if (silc_idlist_del_channel(server->local_list, channel))
2772 server->stat.my_channels--;
2774 silc_idlist_del_channel(server->global_list, channel);
2775 silc_buffer_free(clidp);
2779 /* Remove client from channel's client list */
2780 silc_hash_table_del(channel->user_list, chl->client);
2781 channel->user_count--;
2783 /* If there is no global users on the channel anymore mark the channel
2784 as local channel. Do not check if the client is local client. */
2785 if (server->server_type != SILC_ROUTER && channel->global_users &&
2786 chl->client->router && !silc_server_channel_has_global(channel))
2787 channel->global_users = FALSE;
2790 server->stat.my_chanclients--;
2792 /* If there is not at least one local user on the channel then we don't
2793 need the channel entry anymore, we can remove it safely. */
2794 if (server->server_type != SILC_ROUTER &&
2795 !silc_server_channel_has_local(channel)) {
2796 /* Notify about leaving client if this channel has global users. */
2797 if (notify && channel->global_users)
2798 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2799 SILC_NOTIFY_TYPE_LEAVE, 1,
2800 clidp->data, clidp->len);
2802 silc_buffer_free(clidp);
2805 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2807 if (channel->founder_key) {
2808 /* The founder auth data exists, do not remove the channel entry */
2809 SilcChannelClientEntry chl2;
2810 SilcHashTableList htl2;
2812 channel->disabled = TRUE;
2814 silc_hash_table_list(channel->user_list, &htl2);
2815 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2816 silc_hash_table_del(chl2->client->channels, channel);
2817 silc_hash_table_del(channel->user_list, chl2->client);
2818 channel->user_count--;
2821 silc_hash_table_list_reset(&htl2);
2825 /* Remove the channel entry */
2826 if (silc_idlist_del_channel(server->local_list, channel))
2827 server->stat.my_channels--;
2829 silc_idlist_del_channel(server->global_list, channel);
2833 /* Send notify to channel about client leaving the channel */
2835 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2836 SILC_NOTIFY_TYPE_LEAVE, 1,
2837 clidp->data, clidp->len);
2839 silc_buffer_free(clidp);
2843 /* Timeout callback. This is called if connection is idle or for some
2844 other reason is not responding within some period of time. This
2845 disconnects the remote end. */
2847 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2849 SilcServer server = (SilcServer)context;
2850 SilcSocketConnection sock = server->sockets[fd];
2852 SILC_LOG_DEBUG(("Start"));
2857 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2858 sock->hostname, sock->ip));
2860 /* If we have protocol active we must assure that we call the protocol's
2861 final callback so that all the memory is freed. */
2862 if (sock->protocol) {
2863 silc_protocol_cancel(sock->protocol, server->schedule);
2864 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2865 silc_protocol_execute_final(sock->protocol, server->schedule);
2866 sock->protocol = NULL;
2870 if (sock->user_data)
2871 silc_server_free_sock_user_data(server, sock, NULL);
2873 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2874 "Connection timeout");
2877 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2878 function may be used only by router. In real SILC network all channels
2879 are created by routers thus this function is never used by normal
2882 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2883 SilcServerID *router_id,
2889 SilcChannelID *channel_id;
2890 SilcChannelEntry entry;
2894 SILC_LOG_DEBUG(("Creating new channel"));
2897 cipher = SILC_DEFAULT_CIPHER;
2899 hmac = SILC_DEFAULT_HMAC;
2901 /* Allocate cipher */
2902 if (!silc_cipher_alloc(cipher, &key))
2906 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2907 silc_cipher_free(key);
2911 channel_name = strdup(channel_name);
2913 /* Create the channel ID */
2914 if (!silc_id_create_channel_id(server, router_id, server->rng,
2916 silc_free(channel_name);
2917 silc_cipher_free(key);
2918 silc_hmac_free(newhmac);
2922 /* Create the channel */
2923 entry = silc_idlist_add_channel(server->local_list, channel_name,
2924 SILC_CHANNEL_MODE_NONE, channel_id,
2925 NULL, key, newhmac, 0);
2927 silc_free(channel_name);
2928 silc_cipher_free(key);
2929 silc_hmac_free(newhmac);
2930 silc_free(channel_id);
2934 entry->cipher = strdup(cipher);
2935 entry->hmac_name = strdup(hmac);
2937 /* Now create the actual key material */
2938 if (!silc_server_create_channel_key(server, entry,
2939 silc_cipher_get_key_len(key) / 8)) {
2940 silc_idlist_del_channel(server->local_list, entry);
2944 /* Notify other routers about the new channel. We send the packet
2945 to our primary route. */
2946 if (broadcast && server->standalone == FALSE)
2947 silc_server_send_new_channel(server, server->router->connection, TRUE,
2948 channel_name, entry->id,
2949 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2952 server->stat.my_channels++;
2957 /* Same as above but creates the channel with Channel ID `channel_id. */
2960 silc_server_create_new_channel_with_id(SilcServer server,
2964 SilcChannelID *channel_id,
2967 SilcChannelEntry entry;
2971 SILC_LOG_DEBUG(("Creating new channel"));
2974 cipher = SILC_DEFAULT_CIPHER;
2976 hmac = SILC_DEFAULT_HMAC;
2978 /* Allocate cipher */
2979 if (!silc_cipher_alloc(cipher, &key))
2983 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2984 silc_cipher_free(key);
2988 channel_name = strdup(channel_name);
2990 /* Create the channel */
2991 entry = silc_idlist_add_channel(server->local_list, channel_name,
2992 SILC_CHANNEL_MODE_NONE, channel_id,
2993 NULL, key, newhmac, 0);
2995 silc_cipher_free(key);
2996 silc_hmac_free(newhmac);
2997 silc_free(channel_name);
3001 /* Now create the actual key material */
3002 if (!silc_server_create_channel_key(server, entry,
3003 silc_cipher_get_key_len(key) / 8)) {
3004 silc_idlist_del_channel(server->local_list, entry);
3008 /* Notify other routers about the new channel. We send the packet
3009 to our primary route. */
3010 if (broadcast && server->standalone == FALSE)
3011 silc_server_send_new_channel(server, server->router->connection, TRUE,
3012 channel_name, entry->id,
3013 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3016 server->stat.my_channels++;
3021 /* Channel's key re-key timeout callback. */
3023 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3025 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3026 SilcServer server = (SilcServer)rekey->context;
3030 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3033 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3036 /* Generates new channel key. This is used to create the initial channel key
3037 but also to re-generate new key for channel. If `key_len' is provided
3038 it is the bytes of the key length. */
3040 bool silc_server_create_channel_key(SilcServer server,
3041 SilcChannelEntry channel,
3045 unsigned char channel_key[32], hash[32];
3048 SILC_LOG_DEBUG(("Generating channel key"));
3050 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3051 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3055 if (!channel->channel_key)
3056 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3057 channel->channel_key = NULL;
3063 else if (channel->key_len)
3064 len = channel->key_len / 8;
3066 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3068 /* Create channel key */
3069 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3072 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3074 /* Remove old key if exists */
3076 memset(channel->key, 0, channel->key_len / 8);
3077 silc_free(channel->key);
3081 channel->key_len = len * 8;
3082 channel->key = silc_memdup(channel_key, len);
3083 memset(channel_key, 0, sizeof(channel_key));
3085 /* Generate HMAC key from the channel key data and set it */
3087 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3088 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3089 silc_hmac_set_key(channel->hmac, hash,
3090 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3091 memset(hash, 0, sizeof(hash));
3093 if (server->server_type == SILC_ROUTER) {
3094 if (!channel->rekey)
3095 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3096 channel->rekey->context = (void *)server;
3097 channel->rekey->channel = channel;
3098 channel->rekey->key_len = key_len;
3099 if (channel->rekey->task)
3100 silc_schedule_task_del(server->schedule, channel->rekey->task);
3102 channel->rekey->task =
3103 silc_schedule_task_add(server->schedule, 0,
3104 silc_server_channel_key_rekey,
3105 (void *)channel->rekey,
3106 server->config->channel_rekey_secs, 0,
3108 SILC_TASK_PRI_NORMAL);
3114 /* Saves the channel key found in the encoded `key_payload' buffer. This
3115 function is used when we receive Channel Key Payload and also when we're
3116 processing JOIN command reply. Returns entry to the channel. */
3118 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3119 SilcBuffer key_payload,
3120 SilcChannelEntry channel)
3122 SilcChannelKeyPayload payload = NULL;
3123 SilcChannelID *id = NULL;
3124 unsigned char *tmp, hash[32];
3128 SILC_LOG_DEBUG(("Start"));
3130 /* Decode channel key payload */
3131 payload = silc_channel_key_payload_parse(key_payload->data,
3134 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3139 /* Get the channel entry */
3142 /* Get channel ID */
3143 tmp = silc_channel_key_get_id(payload, &tmp_len);
3144 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3150 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3152 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3154 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3155 silc_id_render(id, SILC_ID_CHANNEL)));
3161 tmp = silc_channel_key_get_key(payload, &tmp_len);
3167 cipher = silc_channel_key_get_cipher(payload, NULL);
3173 /* Remove old key if exists */
3175 memset(channel->key, 0, channel->key_len / 8);
3176 silc_free(channel->key);
3177 silc_cipher_free(channel->channel_key);
3180 /* Create new cipher */
3181 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3182 channel->channel_key = NULL;
3187 if (channel->cipher)
3188 silc_free(channel->cipher);
3189 channel->cipher = strdup(cipher);
3192 channel->key_len = tmp_len * 8;
3193 channel->key = silc_memdup(tmp, tmp_len);
3194 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3196 /* Generate HMAC key from the channel key data and set it */
3198 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3199 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3200 silc_hmac_set_key(channel->hmac, hash,
3201 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3203 memset(hash, 0, sizeof(hash));
3204 memset(tmp, 0, tmp_len);
3206 if (server->server_type == SILC_ROUTER) {
3207 if (!channel->rekey)
3208 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3209 channel->rekey->context = (void *)server;
3210 channel->rekey->channel = channel;
3211 if (channel->rekey->task)
3212 silc_schedule_task_del(server->schedule, channel->rekey->task);
3214 channel->rekey->task =
3215 silc_schedule_task_add(server->schedule, 0,
3216 silc_server_channel_key_rekey,
3217 (void *)channel->rekey,
3218 server->config->channel_rekey_secs, 0,
3220 SILC_TASK_PRI_NORMAL);
3226 silc_channel_key_payload_free(payload);
3231 /* Heartbeat callback. This function is set as argument for the
3232 silc_socket_set_heartbeat function. The library will call this function
3233 at the set time interval. */
3235 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3238 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3240 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3242 /* Send the heartbeat */
3243 silc_server_send_heartbeat(hb->server, sock);
3246 /* Returns assembled of all servers in the given ID list. The packet's
3247 form is dictated by the New ID payload. */
3249 static void silc_server_announce_get_servers(SilcServer server,
3250 SilcServerEntry remote,
3252 SilcBuffer *servers,
3253 unsigned long creation_time)
3255 SilcIDCacheList list;
3256 SilcIDCacheEntry id_cache;
3257 SilcServerEntry entry;
3260 /* Go through all clients in the list */
3261 if (silc_idcache_get_all(id_list->servers, &list)) {
3262 if (silc_idcache_list_first(list, &id_cache)) {
3264 entry = (SilcServerEntry)id_cache->context;
3266 /* Do not announce the one we've sending our announcements and
3267 do not announce ourself. Also check the creation time if it's
3269 if ((entry == remote) || (entry == server->id_entry) ||
3270 (creation_time && entry->data.created < creation_time)) {
3271 if (!silc_idcache_list_next(list, &id_cache))
3276 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3278 *servers = silc_buffer_realloc(*servers,
3280 (*servers)->truelen + idp->len :
3282 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3283 silc_buffer_put(*servers, idp->data, idp->len);
3284 silc_buffer_pull(*servers, idp->len);
3285 silc_buffer_free(idp);
3287 if (!silc_idcache_list_next(list, &id_cache))
3292 silc_idcache_list_free(list);
3297 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3303 p = silc_notify_payload_encode(notify, argc, ap);
3309 /* This function is used by router to announce existing servers to our
3310 primary router when we've connected to it. If `creation_time' is non-zero
3311 then only the servers that has been created after the `creation_time'
3312 will be announced. */
3314 void silc_server_announce_servers(SilcServer server, bool global,
3315 unsigned long creation_time,
3316 SilcSocketConnection remote)
3318 SilcBuffer servers = NULL;
3320 SILC_LOG_DEBUG(("Announcing servers"));
3322 /* Get servers in local list */
3323 silc_server_announce_get_servers(server, remote->user_data,
3324 server->local_list, &servers,
3328 /* Get servers in global list */
3329 silc_server_announce_get_servers(server, remote->user_data,
3330 server->global_list, &servers,
3334 silc_buffer_push(servers, servers->data - servers->head);
3335 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3337 /* Send the packet */
3338 silc_server_packet_send(server, remote,
3339 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3340 servers->data, servers->len, TRUE);
3342 silc_buffer_free(servers);
3346 /* Returns assembled packet of all clients in the given ID list. The
3347 packet's form is dictated by the New ID Payload. */
3349 static void silc_server_announce_get_clients(SilcServer server,
3351 SilcBuffer *clients,
3353 unsigned long creation_time)
3355 SilcIDCacheList list;
3356 SilcIDCacheEntry id_cache;
3357 SilcClientEntry client;
3360 unsigned char mode[4];
3362 /* Go through all clients in the list */
3363 if (silc_idcache_get_all(id_list->clients, &list)) {
3364 if (silc_idcache_list_first(list, &id_cache)) {
3366 client = (SilcClientEntry)id_cache->context;
3368 if (creation_time && client->data.created < creation_time) {
3369 if (!silc_idcache_list_next(list, &id_cache))
3374 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3376 *clients = silc_buffer_realloc(*clients,
3378 (*clients)->truelen + idp->len :
3380 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3381 silc_buffer_put(*clients, idp->data, idp->len);
3382 silc_buffer_pull(*clients, idp->len);
3384 SILC_PUT32_MSB(client->mode, mode);
3385 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3386 2, idp->data, idp->len,
3388 *umodes = silc_buffer_realloc(*umodes,
3390 (*umodes)->truelen + tmp->len :
3392 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3393 silc_buffer_put(*umodes, tmp->data, tmp->len);
3394 silc_buffer_pull(*umodes, tmp->len);
3395 silc_buffer_free(tmp);
3397 silc_buffer_free(idp);
3399 if (!silc_idcache_list_next(list, &id_cache))
3404 silc_idcache_list_free(list);
3408 /* This function is used to announce our existing clients to our router
3409 when we've connected to it. If `creation_time' is non-zero then only
3410 the clients that has been created after the `creation_time' will be
3413 void silc_server_announce_clients(SilcServer server,
3414 unsigned long creation_time,
3415 SilcSocketConnection remote)
3417 SilcBuffer clients = NULL;
3418 SilcBuffer umodes = NULL;
3420 SILC_LOG_DEBUG(("Announcing clients"));
3422 /* Get clients in local list */
3423 silc_server_announce_get_clients(server, server->local_list,
3424 &clients, &umodes, creation_time);
3426 /* As router we announce our global list as well */
3427 if (server->server_type == SILC_ROUTER)
3428 silc_server_announce_get_clients(server, server->global_list,
3429 &clients, &umodes, creation_time);
3432 silc_buffer_push(clients, clients->data - clients->head);
3433 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3435 /* Send the packet */
3436 silc_server_packet_send(server, remote,
3437 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3438 clients->data, clients->len, TRUE);
3440 silc_buffer_free(clients);
3444 silc_buffer_push(umodes, umodes->data - umodes->head);
3445 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3447 /* Send the packet */
3448 silc_server_packet_send(server, remote,
3449 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3450 umodes->data, umodes->len, TRUE);
3452 silc_buffer_free(umodes);
3456 /* Returns channel's topic for announcing it */
3458 void silc_server_announce_get_channel_topic(SilcServer server,
3459 SilcChannelEntry channel,
3464 if (channel->topic) {
3465 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3466 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3467 chidp->data, chidp->len,
3469 strlen(channel->topic));
3470 silc_buffer_free(chidp);
3474 /* Returns assembled packets for channel users of the `channel'. */
3476 void silc_server_announce_get_channel_users(SilcServer server,
3477 SilcChannelEntry channel,
3478 SilcBuffer *channel_users,
3479 SilcBuffer *channel_users_modes)
3481 SilcChannelClientEntry chl;
3482 SilcHashTableList htl;
3483 SilcBuffer chidp, clidp;
3486 unsigned char mode[4];
3488 SILC_LOG_DEBUG(("Start"));
3490 /* Now find all users on the channel */
3491 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3492 silc_hash_table_list(channel->user_list, &htl);
3493 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3494 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3497 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3498 clidp->data, clidp->len,
3499 chidp->data, chidp->len);
3502 silc_buffer_realloc(*channel_users,
3504 (*channel_users)->truelen + len : len));
3505 silc_buffer_pull_tail(*channel_users,
3506 ((*channel_users)->end -
3507 (*channel_users)->data));
3509 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3510 silc_buffer_pull(*channel_users, len);
3511 silc_buffer_free(tmp);
3513 /* CUMODE notify for mode change on the channel */
3514 SILC_PUT32_MSB(chl->mode, mode);
3515 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3516 3, clidp->data, clidp->len,
3518 clidp->data, clidp->len);
3520 *channel_users_modes =
3521 silc_buffer_realloc(*channel_users_modes,
3522 (*channel_users_modes ?
3523 (*channel_users_modes)->truelen + len : len));
3524 silc_buffer_pull_tail(*channel_users_modes,
3525 ((*channel_users_modes)->end -
3526 (*channel_users_modes)->data));
3528 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3529 silc_buffer_pull(*channel_users_modes, len);
3530 silc_buffer_free(tmp);
3532 silc_buffer_free(clidp);
3534 silc_hash_table_list_reset(&htl);
3535 silc_buffer_free(chidp);
3538 /* Returns assembled packets for all channels and users on those channels
3539 from the given ID List. The packets are in the form dictated by the
3540 New Channel and New Channel User payloads. */
3542 void silc_server_announce_get_channels(SilcServer server,
3544 SilcBuffer *channels,
3545 SilcBuffer *channel_users,
3546 SilcBuffer **channel_users_modes,
3547 SilcUInt32 *channel_users_modes_c,
3548 SilcBuffer **channel_topics,
3549 SilcChannelID ***channel_ids,
3550 unsigned long creation_time)
3552 SilcIDCacheList list;
3553 SilcIDCacheEntry id_cache;
3554 SilcChannelEntry channel;
3557 SilcUInt16 name_len;
3559 int i = *channel_users_modes_c;
3562 SILC_LOG_DEBUG(("Start"));
3564 /* Go through all channels in the list */
3565 if (silc_idcache_get_all(id_list->channels, &list)) {
3566 if (silc_idcache_list_first(list, &id_cache)) {
3568 channel = (SilcChannelEntry)id_cache->context;
3570 if (creation_time && channel->created < creation_time)
3575 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3576 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3577 name_len = strlen(channel->channel_name);
3580 len = 4 + name_len + id_len + 4;
3582 silc_buffer_realloc(*channels,
3583 (*channels ? (*channels)->truelen +
3585 silc_buffer_pull_tail(*channels,
3586 ((*channels)->end - (*channels)->data));
3587 silc_buffer_format(*channels,
3588 SILC_STR_UI_SHORT(name_len),
3589 SILC_STR_UI_XNSTRING(channel->channel_name,
3591 SILC_STR_UI_SHORT(id_len),
3592 SILC_STR_UI_XNSTRING(cid, id_len),
3593 SILC_STR_UI_INT(channel->mode),
3595 silc_buffer_pull(*channels, len);
3598 /* Channel user modes */
3599 *channel_users_modes = silc_realloc(*channel_users_modes,
3600 sizeof(**channel_users_modes) *
3602 (*channel_users_modes)[i] = NULL;
3603 *channel_ids = silc_realloc(*channel_ids,
3604 sizeof(**channel_ids) * (i + 1));
3605 (*channel_ids)[i] = NULL;
3606 silc_server_announce_get_channel_users(server, channel,
3608 &(*channel_users_modes)[i]);
3609 (*channel_ids)[i] = channel->id;
3611 /* Channel's topic */
3612 *channel_topics = silc_realloc(*channel_topics,
3613 sizeof(**channel_topics) * (i + 1));
3614 (*channel_topics)[i] = NULL;
3615 silc_server_announce_get_channel_topic(server, channel,
3616 &(*channel_topics)[i]);
3619 if (!silc_idcache_list_next(list, &id_cache))
3623 *channel_users_modes_c += i;
3626 silc_idcache_list_free(list);
3630 /* This function is used to announce our existing channels to our router
3631 when we've connected to it. This also announces the users on the
3632 channels to the router. If the `creation_time' is non-zero only the
3633 channels that was created after the `creation_time' are announced.
3634 Note that the channel users are still announced even if the `creation_time'
3637 void silc_server_announce_channels(SilcServer server,
3638 unsigned long creation_time,
3639 SilcSocketConnection remote)
3641 SilcBuffer channels = NULL, channel_users = NULL;
3642 SilcBuffer *channel_users_modes = NULL;
3643 SilcBuffer *channel_topics = NULL;
3644 SilcUInt32 channel_users_modes_c = 0;
3645 SilcChannelID **channel_ids = NULL;
3647 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3649 /* Get channels and channel users in local list */
3650 silc_server_announce_get_channels(server, server->local_list,
3651 &channels, &channel_users,
3652 &channel_users_modes,
3653 &channel_users_modes_c,
3655 &channel_ids, creation_time);
3657 /* Get channels and channel users in global list */
3658 if (server->server_type != SILC_SERVER)
3659 silc_server_announce_get_channels(server, server->global_list,
3660 &channels, &channel_users,
3661 &channel_users_modes,
3662 &channel_users_modes_c,
3664 &channel_ids, creation_time);
3667 silc_buffer_push(channels, channels->data - channels->head);
3668 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3670 /* Send the packet */
3671 silc_server_packet_send(server, remote,
3672 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3673 channels->data, channels->len,
3676 silc_buffer_free(channels);
3679 if (channel_users) {
3680 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3681 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3682 channel_users->len);
3684 /* Send the packet */
3685 silc_server_packet_send(server, remote,
3686 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3687 channel_users->data, channel_users->len,
3690 silc_buffer_free(channel_users);
3693 if (channel_users_modes) {
3696 for (i = 0; i < channel_users_modes_c; i++) {
3697 if (!channel_users_modes[i])
3699 silc_buffer_push(channel_users_modes[i],
3700 channel_users_modes[i]->data -
3701 channel_users_modes[i]->head);
3702 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3703 channel_users_modes[i]->len);
3704 silc_server_packet_send_dest(server, remote,
3705 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3706 channel_ids[i], SILC_ID_CHANNEL,
3707 channel_users_modes[i]->data,
3708 channel_users_modes[i]->len,
3710 silc_buffer_free(channel_users_modes[i]);
3712 silc_free(channel_users_modes);
3715 if (channel_topics) {
3718 for (i = 0; i < channel_users_modes_c; i++) {
3719 if (!channel_topics[i])
3722 silc_buffer_push(channel_topics[i],
3723 channel_topics[i]->data -
3724 channel_topics[i]->head);
3725 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3726 channel_topics[i]->len);
3727 silc_server_packet_send_dest(server, remote,
3728 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3729 channel_ids[i], SILC_ID_CHANNEL,
3730 channel_topics[i]->data,
3731 channel_topics[i]->len,
3733 silc_buffer_free(channel_topics[i]);
3735 silc_free(channel_topics);
3738 silc_free(channel_ids);
3741 /* Failure timeout callback. If this is called then we will immediately
3742 process the received failure. We always process the failure with timeout
3743 since we do not want to blindly trust to received failure packets.
3744 This won't be called (the timeout is cancelled) if the failure was
3745 bogus (it is bogus if remote does not close the connection after sending
3748 SILC_TASK_CALLBACK(silc_server_failure_callback)
3750 SilcServerFailureContext f = (SilcServerFailureContext)context;
3752 if (f->sock->protocol) {
3753 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3754 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3760 /* Assembles user list and users mode list from the `channel'. */
3762 void silc_server_get_users_on_channel(SilcServer server,
3763 SilcChannelEntry channel,
3764 SilcBuffer *user_list,
3765 SilcBuffer *mode_list,
3766 SilcUInt32 *user_count)
3768 SilcChannelClientEntry chl;
3769 SilcHashTableList htl;
3770 SilcBuffer client_id_list;
3771 SilcBuffer client_mode_list;
3773 SilcUInt32 list_count = 0, len = 0;
3775 silc_hash_table_list(channel->user_list, &htl);
3776 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3777 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3778 silc_hash_table_list_reset(&htl);
3780 client_id_list = silc_buffer_alloc(len);
3782 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3783 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3784 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3786 silc_hash_table_list(channel->user_list, &htl);
3787 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3789 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3790 silc_buffer_put(client_id_list, idp->data, idp->len);
3791 silc_buffer_pull(client_id_list, idp->len);
3792 silc_buffer_free(idp);
3794 /* Client's mode on channel */
3795 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3796 silc_buffer_pull(client_mode_list, 4);
3800 silc_hash_table_list_reset(&htl);
3801 silc_buffer_push(client_id_list,
3802 client_id_list->data - client_id_list->head);
3803 silc_buffer_push(client_mode_list,
3804 client_mode_list->data - client_mode_list->head);
3806 *user_list = client_id_list;
3807 *mode_list = client_mode_list;
3808 *user_count = list_count;
3811 /* Saves users and their modes to the `channel'. */
3813 void silc_server_save_users_on_channel(SilcServer server,
3814 SilcSocketConnection sock,
3815 SilcChannelEntry channel,
3816 SilcClientID *noadd,
3817 SilcBuffer user_list,
3818 SilcBuffer mode_list,
3819 SilcUInt32 user_count)
3824 SilcClientID *client_id;
3825 SilcClientEntry client;
3826 SilcIDCacheEntry cache;
3829 SILC_LOG_DEBUG(("Start"));
3831 for (i = 0; i < user_count; i++) {
3833 SILC_GET16_MSB(idp_len, user_list->data + 2);
3835 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3836 silc_buffer_pull(user_list, idp_len);
3841 SILC_GET32_MSB(mode, mode_list->data);
3842 silc_buffer_pull(mode_list, 4);
3844 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3845 silc_free(client_id);
3851 /* Check if we have this client cached already. */
3852 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3853 server->server_type, &cache);
3855 client = silc_idlist_find_client_by_id(server->global_list,
3856 client_id, server->server_type,
3861 /* If router did not find such Client ID in its lists then this must
3862 be bogus client or some router in the net is buggy. */
3863 if (server->server_type == SILC_ROUTER) {
3864 silc_free(client_id);
3868 /* We don't have that client anywhere, add it. The client is added
3869 to global list since server didn't have it in the lists so it must be
3871 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3872 silc_id_dup(client_id, SILC_ID_CLIENT),
3873 sock->user_data, NULL, 0);
3875 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3876 silc_free(client_id);
3880 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3882 /* Found, if it is from global list we'll assure that we won't
3883 expire it now that the entry is on channel. */
3888 silc_free(client_id);
3890 if (!silc_server_client_on_channel(client, channel)) {
3891 /* Client was not on the channel, add it. */
3892 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3893 chl->client = client;
3895 chl->channel = channel;
3896 silc_hash_table_add(channel->user_list, chl->client, chl);
3897 silc_hash_table_add(client->channels, chl->channel, chl);
3898 channel->user_count++;
3903 /* Lookups route to the client indicated by the `id_data'. The connection
3904 object and internal data object is returned. Returns NULL if route
3905 could not be found to the client. If the `client_id' is specified then
3906 it is used and the `id_data' is ignored. */
3908 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3909 unsigned char *id_data,
3911 SilcClientID *client_id,
3912 SilcIDListData *idata)
3915 SilcClientEntry client;
3917 SILC_LOG_DEBUG(("Start"));
3919 /* Decode destination Client ID */
3921 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3923 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3927 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3930 /* If the destination belongs to our server we don't have to route
3931 the packet anywhere but to send it to the local destination. */
3932 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3936 /* If we are router and the client has router then the client is in
3937 our cell but not directly connected to us. */
3938 if (server->server_type == SILC_ROUTER && client->router) {
3939 /* We are of course in this case the client's router thus the route
3940 to the client is the server who owns the client. So, we will send
3941 the packet to that server. */
3943 *idata = (SilcIDListData)client->router;
3944 return client->router->connection;
3947 /* Seems that client really is directly connected to us */
3949 *idata = (SilcIDListData)client;
3950 return client->connection;
3953 /* Destination belongs to someone not in this server. If we are normal
3954 server our action is to send the packet to our router. */
3955 if (server->server_type != SILC_ROUTER && !server->standalone) {
3958 *idata = (SilcIDListData)server->router;
3959 return server->router->connection;
3962 /* We are router and we will perform route lookup for the destination
3963 and send the packet to fastest route. */
3964 if (server->server_type == SILC_ROUTER && !server->standalone) {
3965 /* Check first that the ID is valid */
3966 client = silc_idlist_find_client_by_id(server->global_list, id,
3969 SilcSocketConnection dst_sock;
3971 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3975 *idata = (SilcIDListData)dst_sock->user_data;
3984 /* Encodes and returns channel list of channels the `client' has joined.
3985 Secret channels are not put to the list. */
3987 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3988 SilcClientEntry client)
3990 SilcBuffer buffer = NULL;
3991 SilcChannelEntry channel;
3992 SilcChannelClientEntry chl;
3993 SilcHashTableList htl;
3996 SilcUInt16 name_len;
3999 silc_hash_table_list(client->channels, &htl);
4000 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4001 channel = chl->channel;
4003 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4004 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4007 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4008 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4009 name_len = strlen(channel->channel_name);
4011 len = 4 + name_len + id_len + 4;
4012 buffer = silc_buffer_realloc(buffer,
4013 (buffer ? (buffer)->truelen + len : len));
4014 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4015 silc_buffer_format(buffer,
4016 SILC_STR_UI_SHORT(name_len),
4017 SILC_STR_UI_XNSTRING(channel->channel_name,
4019 SILC_STR_UI_SHORT(id_len),
4020 SILC_STR_UI_XNSTRING(cid, id_len),
4021 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4023 silc_buffer_pull(buffer, len);
4026 silc_hash_table_list_reset(&htl);
4029 silc_buffer_push(buffer, buffer->data - buffer->head);
4034 /* Finds client entry by Client ID and if it is not found then resolves
4035 it using WHOIS command. */
4037 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4038 SilcClientID *client_id,
4041 SilcClientEntry client;
4046 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4049 client = silc_idlist_find_client_by_id(server->global_list,
4050 client_id, TRUE, NULL);
4051 if (!client && server->server_type == SILC_ROUTER)
4055 if (!client && server->standalone)
4058 if (!client || !client->nickname || !client->username) {
4059 SilcBuffer buffer, idp;
4061 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4062 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4063 client->resolve_cmd_ident = ++server->cmd_ident;
4065 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4066 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4067 server->cmd_ident, 1,
4068 3, idp->data, idp->len);
4069 silc_server_packet_send(server, client ? client->router->connection :
4070 server->router->connection,
4071 SILC_PACKET_COMMAND, 0,
4072 buffer->data, buffer->len, FALSE);
4073 silc_buffer_free(idp);
4074 silc_buffer_free(buffer);
4085 /* A timeout callback for the re-key. We will be the initiator of the
4088 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4090 SilcSocketConnection sock = (SilcSocketConnection)context;
4091 SilcIDListData idata = (SilcIDListData)sock->user_data;
4092 SilcServer server = (SilcServer)idata->rekey->context;
4093 SilcProtocol protocol;
4094 SilcServerRekeyInternalContext *proto_ctx;
4096 SILC_LOG_DEBUG(("Start"));
4098 /* Allocate internal protocol context. This is sent as context
4100 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4101 proto_ctx->server = (void *)server;
4102 proto_ctx->sock = sock;
4103 proto_ctx->responder = FALSE;
4104 proto_ctx->pfs = idata->rekey->pfs;
4106 /* Perform rekey protocol. Will call the final callback after the
4107 protocol is over. */
4108 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4109 &protocol, proto_ctx, silc_server_rekey_final);
4110 sock->protocol = protocol;
4112 /* Run the protocol */
4113 silc_protocol_execute(protocol, server->schedule, 0, 0);
4115 /* Re-register re-key timeout */
4116 silc_schedule_task_add(server->schedule, sock->sock,
4117 silc_server_rekey_callback,
4118 context, idata->rekey->timeout, 0,
4119 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4122 /* The final callback for the REKEY protocol. This will actually take the
4123 new key material into use. */
4125 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4127 SilcProtocol protocol = (SilcProtocol)context;
4128 SilcServerRekeyInternalContext *ctx =
4129 (SilcServerRekeyInternalContext *)protocol->context;
4130 SilcServer server = (SilcServer)ctx->server;
4131 SilcSocketConnection sock = ctx->sock;
4133 SILC_LOG_DEBUG(("Start"));
4135 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4136 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4137 /* Error occured during protocol */
4138 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4139 silc_protocol_cancel(protocol, server->schedule);
4140 silc_protocol_free(protocol);
4141 sock->protocol = NULL;
4143 silc_packet_context_free(ctx->packet);
4145 silc_ske_free(ctx->ske);
4150 /* Purge the outgoing data queue to assure that all rekey packets really
4151 go to the network before we quit the protocol. */
4152 silc_server_packet_queue_purge(server, sock);
4155 silc_protocol_free(protocol);
4156 sock->protocol = NULL;
4158 silc_packet_context_free(ctx->packet);
4160 silc_ske_free(ctx->ske);