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. Take only
769 the passphrase, since for public key auth we automatically use
770 our local key pair. */
771 if (conn->passphrase) {
772 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
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->publickeys) {
780 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
782 proto_ctx->auth_meth = SILC_AUTH_NONE;
785 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
786 sock->hostname, sock->ip, sock->port));
787 silc_protocol_free(protocol);
788 sock->protocol = NULL;
790 silc_packet_context_free(ctx->packet);
792 silc_ske_free(ctx->ske);
793 silc_free(ctx->dest_id);
795 silc_schedule_task_del_by_callback(server->schedule,
796 silc_server_failure_callback);
797 silc_server_disconnect_remote(server, sock, "Server closed connection: "
798 "Key exchange failed");
802 /* Free old protocol as it is finished now */
803 silc_protocol_free(protocol);
805 silc_packet_context_free(ctx->packet);
807 sock->protocol = NULL;
809 /* Allocate the authentication protocol. This is allocated here
810 but we won't start it yet. We will be receiving party of this
811 protocol thus we will wait that connecting party will make
813 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
814 &sock->protocol, proto_ctx,
815 silc_server_connect_to_router_final);
817 /* Register timeout task. If the protocol is not executed inside
818 this timelimit the connection will be terminated. */
819 proto_ctx->timeout_task =
820 silc_schedule_task_add(server->schedule, sock->sock,
821 silc_server_timeout_remote,
823 server->config->conn_auth_timeout, 0,
827 /* Run the protocol */
828 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
831 /* Finalizes the connection to router. Registers a server task to the
832 queue so that we can accept new connections. */
834 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
836 SilcProtocol protocol = (SilcProtocol)context;
837 SilcServerConnAuthInternalContext *ctx =
838 (SilcServerConnAuthInternalContext *)protocol->context;
839 SilcServer server = (SilcServer)ctx->server;
840 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
841 SilcSocketConnection sock = ctx->sock;
842 SilcServerEntry id_entry;
844 SilcServerHBContext hb_context;
845 unsigned char *id_string;
847 SilcIDListData idata;
848 SilcServerConfigConnParams *param;
850 SILC_LOG_DEBUG(("Start"));
852 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
853 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
854 /* Error occured during protocol */
855 silc_free(ctx->dest_id);
856 silc_server_disconnect_remote(server, sock, "Server closed connection: "
857 "Authentication failed");
861 /* Add a task to the queue. This task receives new connections to the
862 server. This task remains on the queue until the end of the program. */
863 if (!server->listenning && !sconn->backup) {
864 silc_schedule_task_add(server->schedule, server->sock,
865 silc_server_accept_new_connection,
866 (void *)server, 0, 0,
868 SILC_TASK_PRI_NORMAL);
869 server->listenning = TRUE;
872 /* Send NEW_SERVER packet to the router. We will become registered
873 to the SILC network after sending this packet. */
874 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
875 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
876 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
877 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
878 silc_buffer_format(packet,
879 SILC_STR_UI_SHORT(id_len),
880 SILC_STR_UI_XNSTRING(id_string, id_len),
881 SILC_STR_UI_SHORT(strlen(server->server_name)),
882 SILC_STR_UI_XNSTRING(server->server_name,
883 strlen(server->server_name)),
886 /* Send the packet */
887 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
888 packet->data, packet->len, TRUE);
889 silc_buffer_free(packet);
890 silc_free(id_string);
892 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
894 /* Check that we do not have this ID already */
895 id_entry = silc_idlist_find_server_by_id(server->local_list,
896 ctx->dest_id, TRUE, NULL);
898 silc_idcache_del_by_context(server->local_list->servers, id_entry);
900 id_entry = silc_idlist_find_server_by_id(server->global_list,
901 ctx->dest_id, TRUE, NULL);
903 silc_idcache_del_by_context(server->global_list->servers, id_entry);
906 SILC_LOG_DEBUG(("New server id(%s)",
907 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
909 /* Add the connected router to global server list */
910 id_entry = silc_idlist_add_server(server->global_list,
911 strdup(sock->hostname),
912 SILC_ROUTER, ctx->dest_id, NULL, sock);
914 silc_free(ctx->dest_id);
915 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
916 silc_server_disconnect_remote(server, sock, "Server closed connection: "
917 "Authentication failed");
921 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
922 silc_free(sock->user_data);
923 sock->user_data = (void *)id_entry;
924 sock->type = SILC_SOCKET_TYPE_ROUTER;
925 idata = (SilcIDListData)sock->user_data;
926 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
928 param = (sconn->param ? sconn->param : &server->config->param);
930 /* Perform keepalive. The `hb_context' will be freed automatically
931 when finally calling the silc_socket_free function. */
932 hb_context = silc_calloc(1, sizeof(*hb_context));
933 hb_context->server = server;
934 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
935 silc_server_perform_heartbeat,
938 /* Register re-key timeout */
939 idata->rekey->timeout = param->key_exchange_rekey;
940 idata->rekey->context = (void *)server;
941 silc_schedule_task_add(server->schedule, sock->sock,
942 silc_server_rekey_callback,
943 (void *)sock, idata->rekey->timeout, 0,
944 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
946 if (!sconn->backup) {
947 /* Mark this router our primary router if we're still standalone */
948 if (server->standalone) {
949 server->id_entry->router = id_entry;
950 server->router = id_entry;
951 server->standalone = FALSE;
953 /* If we are router then announce our possible servers. */
954 if (server->server_type == SILC_ROUTER)
955 silc_server_announce_servers(server, FALSE, 0,
956 server->router->connection);
958 /* Announce our clients and channels to the router */
959 silc_server_announce_clients(server, 0, server->router->connection);
960 silc_server_announce_channels(server, 0, server->router->connection);
963 /* Add this server to be our backup router */
964 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
965 sconn->backup_replace_port, FALSE);
968 sock->protocol = NULL;
970 /* Call the completion callback to indicate that we've connected to
973 (*sconn->callback)(server, id_entry, sconn->callback_context);
976 /* Free the temporary connection data context */
978 silc_free(sconn->remote_host);
979 silc_free(sconn->backup_replace_ip);
982 if (sconn == server->router_conn)
983 server->router_conn = NULL;
985 /* Free the protocol object */
986 if (sock->protocol == protocol)
987 sock->protocol = NULL;
988 silc_protocol_free(protocol);
990 silc_packet_context_free(ctx->packet);
992 silc_ske_free(ctx->ske);
993 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
994 silc_free(ctx->auth_data);
998 /* Host lookup callbcak that is called after the incoming connection's
999 IP and FQDN lookup is performed. This will actually check the acceptance
1000 of the incoming connection and will register the key exchange protocol
1001 for this connection. */
1004 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1007 SilcServer server = (SilcServer)context;
1008 SilcServerKEInternalContext *proto_ctx;
1009 SilcServerConfigClient *cconfig = NULL;
1010 SilcServerConfigServer *sconfig = NULL;
1011 SilcServerConfigRouter *rconfig = NULL;
1012 SilcServerConfigDeny *deny;
1015 SILC_LOG_DEBUG(("Start"));
1017 /* Check whether we could resolve both IP and FQDN. */
1018 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1019 server->config->require_reverse_lookup)) {
1020 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1021 sock->hostname ? sock->hostname :
1022 sock->ip ? sock->ip : ""));
1023 server->stat.conn_failures++;
1024 silc_server_disconnect_remote(server, sock,
1025 "Server closed connection: Unknown host");
1029 /* Register the connection for network input and output. This sets
1030 that scheduler will listen for incoming packets for this connection
1031 and sets that outgoing packets may be sent to this connection as well.
1032 However, this doesn't set the scheduler for outgoing traffic, it
1033 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1034 later when outgoing data is available. */
1035 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1037 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1040 port = server->sockets[server->sock]->port; /* Listenning port */
1042 /* Check whether this connection is denied to connect to us. */
1043 deny = silc_server_config_find_denied(server, sock->ip);
1045 deny = silc_server_config_find_denied(server, sock->hostname);
1047 /* The connection is denied */
1048 SILC_LOG_INFO(("Connection %s (%s) is denied",
1049 sock->hostname, sock->ip));
1050 silc_server_disconnect_remote(server, sock, deny->reason ?
1052 "Server closed connection: "
1053 "Connection refused");
1054 server->stat.conn_failures++;
1058 /* Check whether we have configred this sort of connection at all. We
1059 have to check all configurations since we don't know what type of
1060 connection this is. */
1061 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1062 cconfig = silc_server_config_find_client(server, sock->hostname);
1063 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1064 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1065 if (server->server_type == SILC_ROUTER) {
1066 if (!(rconfig = silc_server_config_find_router_conn(server,
1068 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1071 if (!cconfig && !sconfig && !rconfig) {
1072 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1074 silc_server_disconnect_remote(server, sock,
1075 "Server closed connection: "
1076 "Connection refused");
1077 server->stat.conn_failures++;
1081 /* The connection is allowed */
1083 /* Allocate internal context for key exchange protocol. This is
1084 sent as context for the protocol. */
1085 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1086 proto_ctx->server = context;
1087 proto_ctx->sock = sock;
1088 proto_ctx->rng = server->rng;
1089 proto_ctx->responder = TRUE;
1090 proto_ctx->cconfig = cconfig;
1091 proto_ctx->sconfig = sconfig;
1092 proto_ctx->rconfig = rconfig;
1094 /* Take flags for key exchange. Since we do not know what type of connection
1095 this is, we go through all found configuratios and use the global ones
1096 as well. This will result always into strictest key exchange flags. */
1097 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1098 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1099 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1100 if (server->config->param.key_exchange_pfs)
1101 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1103 /* Prepare the connection for key exchange protocol. We allocate the
1104 protocol but will not start it yet. The connector will be the
1105 initiator of the protocol thus we will wait for initiation from
1106 there before we start the protocol. */
1107 server->stat.auth_attempts++;
1108 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1109 &sock->protocol, proto_ctx,
1110 silc_server_accept_new_connection_second);
1112 /* Register a timeout task that will be executed if the connector
1113 will not start the key exchange protocol within specified timeout
1114 and the connection will be closed. */
1115 proto_ctx->timeout_task =
1116 silc_schedule_task_add(server->schedule, sock->sock,
1117 silc_server_timeout_remote,
1118 context, server->config->key_exchange_timeout, 0,
1123 /* Accepts new connections to the server. Accepting new connections are
1124 done in three parts to make it async. */
1126 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1128 SilcServer server = (SilcServer)context;
1129 SilcSocketConnection newsocket;
1132 SILC_LOG_DEBUG(("Accepting new connection"));
1134 server->stat.conn_attempts++;
1136 sock = silc_net_accept_connection(server->sock);
1138 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1139 server->stat.conn_failures++;
1143 /* Check for maximum allowed connections */
1144 if (sock > server->config->param.connections_max) {
1145 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1146 server->stat.conn_failures++;
1150 /* Set socket options */
1151 silc_net_set_socket_nonblock(sock);
1152 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1154 /* We don't create a ID yet, since we don't know what type of connection
1155 this is yet. But, we do add the connection to the socket table. */
1156 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1157 server->sockets[sock] = newsocket;
1159 /* Perform asynchronous host lookup. This will lookup the IP and the
1160 FQDN of the remote connection. After the lookup is done the connection
1161 is accepted further. */
1162 silc_socket_host_lookup(newsocket, TRUE,
1163 silc_server_accept_new_connection_lookup, context,
1167 /* Second part of accepting new connection. Key exchange protocol has been
1168 performed and now it is time to do little connection authentication
1169 protocol to figure out whether this connection is client or server
1170 and whether it has right to access this server (especially server
1171 connections needs to be authenticated). */
1173 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1175 SilcProtocol protocol = (SilcProtocol)context;
1176 SilcServerKEInternalContext *ctx =
1177 (SilcServerKEInternalContext *)protocol->context;
1178 SilcServer server = (SilcServer)ctx->server;
1179 SilcSocketConnection sock = ctx->sock;
1180 SilcServerConnAuthInternalContext *proto_ctx;
1182 SILC_LOG_DEBUG(("Start"));
1184 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1185 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1186 /* Error occured during protocol */
1187 silc_protocol_free(protocol);
1188 sock->protocol = NULL;
1189 silc_ske_free_key_material(ctx->keymat);
1191 silc_packet_context_free(ctx->packet);
1193 silc_ske_free(ctx->ske);
1194 silc_free(ctx->dest_id);
1196 silc_schedule_task_del_by_callback(server->schedule,
1197 silc_server_failure_callback);
1198 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1199 "Key exchange failed");
1200 server->stat.auth_failures++;
1204 /* We now have the key material as the result of the key exchange
1205 protocol. Take the key material into use. Free the raw key material
1206 as soon as we've set them into use. */
1207 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1208 ctx->sock, ctx->keymat,
1209 ctx->ske->prop->cipher,
1210 ctx->ske->prop->pkcs,
1211 ctx->ske->prop->hash,
1212 ctx->ske->prop->hmac,
1213 ctx->ske->prop->group,
1215 silc_protocol_free(protocol);
1216 sock->protocol = NULL;
1217 silc_ske_free_key_material(ctx->keymat);
1219 silc_packet_context_free(ctx->packet);
1221 silc_ske_free(ctx->ske);
1222 silc_free(ctx->dest_id);
1224 silc_schedule_task_del_by_callback(server->schedule,
1225 silc_server_failure_callback);
1226 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1227 "Key exchange failed");
1228 server->stat.auth_failures++;
1231 silc_ske_free_key_material(ctx->keymat);
1233 /* Allocate internal context for the authentication protocol. This
1234 is sent as context for the protocol. */
1235 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1236 proto_ctx->server = (void *)server;
1237 proto_ctx->sock = sock;
1238 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1239 proto_ctx->responder = TRUE;
1240 proto_ctx->dest_id_type = ctx->dest_id_type;
1241 proto_ctx->dest_id = ctx->dest_id;
1242 proto_ctx->cconfig = ctx->cconfig;
1243 proto_ctx->sconfig = ctx->sconfig;
1244 proto_ctx->rconfig = ctx->rconfig;
1246 /* Free old protocol as it is finished now */
1247 silc_protocol_free(protocol);
1249 silc_packet_context_free(ctx->packet);
1251 sock->protocol = NULL;
1253 /* Allocate the authentication protocol. This is allocated here
1254 but we won't start it yet. We will be receiving party of this
1255 protocol thus we will wait that connecting party will make
1256 their first move. */
1257 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1258 &sock->protocol, proto_ctx,
1259 silc_server_accept_new_connection_final);
1261 /* Register timeout task. If the protocol is not executed inside
1262 this timelimit the connection will be terminated. */
1263 proto_ctx->timeout_task =
1264 silc_schedule_task_add(server->schedule, sock->sock,
1265 silc_server_timeout_remote,
1267 server->config->conn_auth_timeout, 0,
1272 /* Final part of accepting new connection. The connection has now
1273 been authenticated and keys has been exchanged. We also know whether
1274 this is client or server connection. */
1276 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1278 SilcProtocol protocol = (SilcProtocol)context;
1279 SilcServerConnAuthInternalContext *ctx =
1280 (SilcServerConnAuthInternalContext *)protocol->context;
1281 SilcServer server = (SilcServer)ctx->server;
1282 SilcSocketConnection sock = ctx->sock;
1283 SilcServerHBContext hb_context;
1284 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1286 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1287 SilcUInt32 num_sockets;
1289 SILC_LOG_DEBUG(("Start"));
1291 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1292 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1293 /* Error occured during protocol */
1294 silc_protocol_free(protocol);
1295 sock->protocol = NULL;
1297 silc_packet_context_free(ctx->packet);
1299 silc_ske_free(ctx->ske);
1300 silc_free(ctx->dest_id);
1302 silc_schedule_task_del_by_callback(server->schedule,
1303 silc_server_failure_callback);
1304 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1305 "Authentication failed");
1306 server->stat.auth_failures++;
1310 entry->data.last_receive = time(NULL);
1312 num_sockets = silc_server_num_sockets_by_ip(server, sock->ip,
1315 switch (ctx->conn_type) {
1316 case SILC_SOCKET_TYPE_CLIENT:
1318 SilcClientEntry client;
1319 SilcServerConfigClient *conn = ctx->cconfig;
1320 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1322 /* Check for maximum connections limit */
1324 if (conn->param->connections_max &&
1325 server->stat.my_clients >= conn->param->connections_max) {
1326 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1327 sock->hostname, sock->ip));
1328 silc_server_disconnect_remote(server, sock,
1329 "Server closed connection: "
1330 "Server is full, try again later");
1331 server->stat.auth_failures++;
1335 max_per_host = conn->param->connections_max_per_host;
1338 if (num_sockets >= max_per_host) {
1339 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1340 sock->hostname, sock->ip));
1341 silc_server_disconnect_remote(server, sock,
1342 "Server closed connection: "
1343 "Too many connections from your host");
1344 server->stat.auth_failures++;
1348 SILC_LOG_DEBUG(("Remote host is client"));
1349 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1352 /* Add the client to the client ID cache. The nickname and Client ID
1353 and other information is created after we have received NEW_CLIENT
1354 packet from client. */
1355 client = silc_idlist_add_client(server->local_list,
1356 NULL, NULL, NULL, NULL, NULL, sock, 0);
1358 SILC_LOG_ERROR(("Could not add new client to cache"));
1359 silc_free(sock->user_data);
1360 silc_server_disconnect_remote(server, sock,
1361 "Server closed connection: "
1362 "Authentication failed");
1363 server->stat.auth_failures++;
1368 server->stat.my_clients++;
1369 server->stat.clients++;
1370 if (server->server_type == SILC_ROUTER)
1371 server->stat.cell_clients++;
1373 /* Get connection parameters */
1375 if (conn->param->keepalive_secs)
1376 hearbeat_timeout = conn->param->keepalive_secs;
1379 id_entry = (void *)client;
1382 case SILC_SOCKET_TYPE_SERVER:
1383 case SILC_SOCKET_TYPE_ROUTER:
1385 SilcServerEntry new_server;
1386 bool initiator = FALSE;
1387 bool backup_local = FALSE;
1388 bool backup_router = FALSE;
1389 char *backup_replace_ip = NULL;
1390 SilcUInt16 backup_replace_port = 0;
1391 SilcServerConfigServer *sconn = ctx->sconfig;
1392 SilcServerConfigRouter *rconn = ctx->rconfig;
1393 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1395 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && rconn) {
1397 /* Check for maximum connections limit */
1398 if (rconn->param->connections_max &&
1399 server->stat.my_routers >= rconn->param->connections_max) {
1400 silc_server_disconnect_remote(server, sock,
1401 "Server closed connection: "
1402 "Server is full, try again later");
1403 server->stat.auth_failures++;
1406 max_per_host = rconn->param->connections_max_per_host;
1408 if (rconn->param->keepalive_secs)
1409 hearbeat_timeout = rconn->param->keepalive_secs;
1412 initiator = rconn->initiator;
1413 backup_local = rconn->backup_local;
1414 backup_router = rconn->backup_router;
1415 backup_replace_ip = rconn->backup_replace_ip;
1416 backup_replace_port = rconn->backup_replace_port;
1419 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER && sconn) {
1421 /* Check for maximum connections limit */
1422 if (sconn->param->connections_max &&
1423 server->stat.my_servers >= sconn->param->connections_max) {
1424 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1425 sock->hostname, sock->ip));
1426 silc_server_disconnect_remote(server, sock,
1427 "Server closed connection: "
1428 "Server is full, try again later");
1429 server->stat.auth_failures++;
1432 max_per_host = sconn->param->connections_max_per_host;
1434 if (sconn->param->keepalive_secs)
1435 hearbeat_timeout = sconn->param->keepalive_secs;
1438 backup_router = sconn->backup_router;
1441 if (num_sockets >= max_per_host) {
1442 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1443 sock->hostname, sock->ip));
1444 silc_server_disconnect_remote(server, sock,
1445 "Server closed connection: "
1446 "Too many connections from your host");
1447 server->stat.auth_failures++;
1451 SILC_LOG_DEBUG(("Remote host is %s",
1452 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1453 "server" : (backup_router ?
1454 "backup router" : "router")));
1455 SILC_LOG_INFO(("Connection s (%s) is %s", sock->hostname,
1456 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1457 "server" : (backup_router ?
1458 "backup router" : "router")));
1460 /* Add the server into server cache. The server name and Server ID
1461 is updated after we have received NEW_SERVER packet from the
1462 server. We mark ourselves as router for this server if we really
1465 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1466 server->local_list : (backup_router ?
1467 server->local_list :
1468 server->global_list)),
1470 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1471 SILC_SERVER : SILC_ROUTER),
1473 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1474 server->id_entry : (backup_router ?
1475 server->id_entry : NULL)),
1478 SILC_LOG_ERROR(("Could not add new server to cache"));
1479 silc_free(sock->user_data);
1480 silc_server_disconnect_remote(server, sock,
1481 "Server closed connection: "
1482 "Authentication failed");
1483 server->stat.auth_failures++;
1488 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1489 server->stat.my_servers++;
1491 server->stat.my_routers++;
1492 server->stat.servers++;
1494 id_entry = (void *)new_server;
1496 /* If the incoming connection is router and marked as backup router
1497 then add it to be one of our backups */
1498 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1499 silc_server_backup_add(server, new_server, backup_replace_ip,
1500 backup_replace_port, backup_local);
1502 /* Change it back to SERVER type since that's what it really is. */
1504 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1506 new_server->server_type = SILC_BACKUP_ROUTER;
1509 /* Check whether this connection is to be our primary router connection
1510 if we do not already have the primary route. */
1511 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1512 if (silc_server_config_is_primary_route(server) && !initiator)
1515 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1516 server->standalone = FALSE;
1517 if (!server->id_entry->router) {
1518 server->id_entry->router = id_entry;
1519 server->router = id_entry;
1530 sock->type = ctx->conn_type;
1532 /* Add the common data structure to the ID entry. */
1533 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1535 /* Add to sockets internal pointer for fast referencing */
1536 silc_free(sock->user_data);
1537 sock->user_data = id_entry;
1539 /* Connection has been fully established now. Everything is ok. */
1540 SILC_LOG_DEBUG(("New connection authenticated"));
1542 /* Perform keepalive. The `hb_context' will be freed automatically
1543 when finally calling the silc_socket_free function. */
1544 hb_context = silc_calloc(1, sizeof(*hb_context));
1545 hb_context->server = server;
1546 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1547 silc_server_perform_heartbeat,
1551 silc_schedule_task_del_by_callback(server->schedule,
1552 silc_server_failure_callback);
1553 silc_protocol_free(protocol);
1555 silc_packet_context_free(ctx->packet);
1557 silc_ske_free(ctx->ske);
1558 silc_free(ctx->dest_id);
1560 sock->protocol = NULL;
1563 /* This function is used to read packets from network and send packets to
1564 network. This is usually a generic task. */
1566 SILC_TASK_CALLBACK(silc_server_packet_process)
1568 SilcServer server = (SilcServer)context;
1569 SilcSocketConnection sock = server->sockets[fd];
1570 SilcIDListData idata;
1571 SilcCipher cipher = NULL;
1572 SilcHmac hmac = NULL;
1573 SilcUInt32 sequence = 0;
1579 SILC_LOG_DEBUG(("Processing packet"));
1581 /* Packet sending */
1583 if (type == SILC_TASK_WRITE) {
1584 /* Do not send data to disconnected connection */
1585 if (SILC_IS_DISCONNECTED(sock))
1588 server->stat.packets_sent++;
1590 if (sock->outbuf->data - sock->outbuf->head)
1591 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1593 /* Send the packet */
1594 ret = silc_packet_send(sock, TRUE);
1596 /* If returned -2 could not write to connection now, will do
1602 SILC_LOG_ERROR(("Error sending packet to connection "
1603 "%s:%d [%s]", sock->hostname, sock->port,
1604 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1605 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1606 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1611 /* The packet has been sent and now it is time to set the connection
1612 back to only for input. When there is again some outgoing data
1613 available for this connection it will be set for output as well.
1614 This call clears the output setting and sets it only for input. */
1615 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1616 SILC_UNSET_OUTBUF_PENDING(sock);
1618 silc_buffer_clear(sock->outbuf);
1622 /* Packet receiving */
1624 /* Read some data from connection */
1625 ret = silc_packet_receive(sock);
1629 SILC_LOG_ERROR(("Error receiving packet from connection "
1630 "%s:%d [%s] %s", sock->hostname, sock->port,
1631 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1632 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1633 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1634 "Router"), strerror(errno)));
1640 SILC_LOG_DEBUG(("Read EOF"));
1642 /* If connection is disconnecting already we will finally
1643 close the connection */
1644 if (SILC_IS_DISCONNECTING(sock)) {
1645 if (sock->user_data)
1646 silc_server_free_sock_user_data(server, sock, NULL);
1647 silc_server_close_connection(server, sock);
1651 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1652 SILC_SET_DISCONNECTING(sock);
1654 if (sock->user_data) {
1656 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1657 silc_server_free_sock_user_data(server, sock, tmp);
1659 silc_server_free_sock_user_data(server, sock, NULL);
1660 } else if (server->router_conn && server->router_conn->sock == sock &&
1661 !server->router && server->standalone)
1662 silc_schedule_task_add(server->schedule, 0,
1663 silc_server_connect_to_router,
1666 SILC_TASK_PRI_NORMAL);
1668 silc_server_close_connection(server, sock);
1672 /* If connection is disconnecting or disconnected we will ignore
1674 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1675 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1679 server->stat.packets_received++;
1681 /* Get keys and stuff from ID entry */
1682 idata = (SilcIDListData)sock->user_data;
1684 cipher = idata->receive_key;
1685 hmac = idata->hmac_receive;
1686 sequence = idata->psn_receive;
1689 /* Process the packet. This will call the parser that will then
1690 decrypt and parse the packet. */
1691 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1692 TRUE : FALSE, cipher, hmac, sequence,
1693 silc_server_packet_parse, server);
1695 /* If this socket connection is not authenticated yet and the packet
1696 processing failed we will drop the connection since it can be
1697 a malicious flooder. */
1698 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1699 (!sock->protocol || sock->protocol->protocol->type ==
1700 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1701 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1702 SILC_SET_DISCONNECTING(sock);
1704 if (sock->user_data)
1705 silc_server_free_sock_user_data(server, sock, NULL);
1706 silc_server_close_connection(server, sock);
1710 /* Parses whole packet, received earlier. */
1712 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1714 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1715 SilcServer server = (SilcServer)parse_ctx->context;
1716 SilcSocketConnection sock = parse_ctx->sock;
1717 SilcPacketContext *packet = parse_ctx->packet;
1718 SilcIDListData idata = (SilcIDListData)sock->user_data;
1721 SILC_LOG_DEBUG(("Start"));
1723 /* Parse the packet */
1724 if (parse_ctx->normal)
1725 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1727 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1729 /* If entry is disabled ignore what we got. */
1730 if (ret != SILC_PACKET_RESUME_ROUTER &&
1731 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1732 SILC_LOG_DEBUG(("Connection is disabled"));
1736 if (ret == SILC_PACKET_NONE)
1739 /* Check that the the current client ID is same as in the client's packet. */
1740 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1741 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1742 if (client && client->id) {
1743 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1744 packet->src_id_type);
1745 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1753 if (server->server_type == SILC_ROUTER) {
1754 /* Route the packet if it is not destined to us. Other ID types but
1755 server are handled separately after processing them. */
1756 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1757 packet->dst_id_type == SILC_ID_SERVER &&
1758 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1759 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1761 /* Route the packet to fastest route for the destination ID */
1762 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1763 packet->dst_id_type);
1766 silc_server_packet_route(server,
1767 silc_server_route_get(server, id,
1768 packet->dst_id_type),
1775 /* Parse the incoming packet type */
1776 silc_server_packet_parse_type(server, sock, packet);
1778 if (server->server_type == SILC_ROUTER) {
1779 /* Broadcast packet if it is marked as broadcast packet and it is
1780 originated from router and we are router. */
1781 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1782 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1783 !server->standalone) {
1784 /* Broadcast to our primary route */
1785 silc_server_packet_broadcast(server, server->router->connection, packet);
1787 /* If we have backup routers then we need to feed all broadcast
1788 data to those servers. */
1789 silc_server_backup_broadcast(server, sock, packet);
1794 silc_packet_context_free(packet);
1795 silc_free(parse_ctx);
1798 /* Parser callback called by silc_packet_receive_process. This merely
1799 registers timeout that will handle the actual parsing when appropriate. */
1801 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1804 SilcServer server = (SilcServer)context;
1805 SilcSocketConnection sock = parser_context->sock;
1806 SilcIDListData idata = (SilcIDListData)sock->user_data;
1809 idata->psn_receive = parser_context->packet->sequence + 1;
1811 /* If protocol for this connection is key exchange or rekey then we'll
1812 process all packets synchronously, since there might be packets in
1813 queue that we are not able to decrypt without first processing the
1814 packets before them. */
1815 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1816 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1817 (sock->protocol && sock->protocol->protocol &&
1818 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1819 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1820 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1823 /* Reprocess data since we'll return FALSE here. This is because
1824 the idata->receive_key might have become valid in the last packet
1825 and we want to call this processor with valid cipher. */
1827 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1828 TRUE : FALSE, idata->receive_key,
1829 idata->hmac_receive, idata->psn_receive,
1830 silc_server_packet_parse, server);
1832 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1833 TRUE : FALSE, NULL, NULL, 0,
1834 silc_server_packet_parse, server);
1838 switch (sock->type) {
1839 case SILC_SOCKET_TYPE_UNKNOWN:
1840 case SILC_SOCKET_TYPE_CLIENT:
1841 /* Parse the packet with timeout */
1842 silc_schedule_task_add(server->schedule, sock->sock,
1843 silc_server_packet_parse_real,
1844 (void *)parser_context, 0, 100000,
1846 SILC_TASK_PRI_NORMAL);
1848 case SILC_SOCKET_TYPE_SERVER:
1849 case SILC_SOCKET_TYPE_ROUTER:
1850 /* Packets from servers are parsed immediately */
1851 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1861 /* Parses the packet type and calls what ever routines the packet type
1862 requires. This is done for all incoming packets. */
1864 void silc_server_packet_parse_type(SilcServer server,
1865 SilcSocketConnection sock,
1866 SilcPacketContext *packet)
1868 SilcPacketType type = packet->type;
1869 SilcIDListData idata = (SilcIDListData)sock->user_data;
1871 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1873 /* Parse the packet type */
1875 case SILC_PACKET_DISCONNECT:
1876 SILC_LOG_DEBUG(("Disconnect packet"));
1877 if (packet->flags & SILC_PACKET_FLAG_LIST)
1879 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1880 /* Duplicate to null terminate the string. */
1881 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1882 SILC_LOG_ERROR(("%s", message));
1887 case SILC_PACKET_SUCCESS:
1889 * Success received for something. For now we can have only
1890 * one protocol for connection executing at once hence this
1891 * success message is for whatever protocol is executing currently.
1893 SILC_LOG_DEBUG(("Success packet"));
1894 if (packet->flags & SILC_PACKET_FLAG_LIST)
1897 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1900 case SILC_PACKET_FAILURE:
1902 * Failure received for something. For now we can have only
1903 * one protocol for connection executing at once hence this
1904 * failure message is for whatever protocol is executing currently.
1906 SILC_LOG_DEBUG(("Failure packet"));
1907 if (packet->flags & SILC_PACKET_FLAG_LIST)
1909 if (sock->protocol) {
1910 SilcServerFailureContext f;
1911 f = silc_calloc(1, sizeof(*f));
1915 /* We will wait 5 seconds to process this failure packet */
1916 silc_schedule_task_add(server->schedule, sock->sock,
1917 silc_server_failure_callback, (void *)f, 5, 0,
1918 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1922 case SILC_PACKET_REJECT:
1923 SILC_LOG_DEBUG(("Reject packet"));
1924 if (packet->flags & SILC_PACKET_FLAG_LIST)
1929 case SILC_PACKET_NOTIFY:
1931 * Received notify packet. Server can receive notify packets from
1932 * router. Server then relays the notify messages to clients if needed.
1934 SILC_LOG_DEBUG(("Notify packet"));
1935 if (packet->flags & SILC_PACKET_FLAG_LIST)
1936 silc_server_notify_list(server, sock, packet);
1938 silc_server_notify(server, sock, packet);
1944 case SILC_PACKET_CHANNEL_MESSAGE:
1946 * Received channel message. Channel messages are special packets
1947 * (although probably most common ones) thus they are handled
1950 SILC_LOG_DEBUG(("Channel Message packet"));
1951 if (packet->flags & SILC_PACKET_FLAG_LIST)
1953 idata->last_receive = time(NULL);
1954 silc_server_channel_message(server, sock, packet);
1957 case SILC_PACKET_CHANNEL_KEY:
1959 * Received key for channel. As channels are created by the router
1960 * the keys are as well. We will distribute the key to all of our
1961 * locally connected clients on the particular channel. Router
1962 * never receives this channel and thus is ignored.
1964 SILC_LOG_DEBUG(("Channel Key packet"));
1965 if (packet->flags & SILC_PACKET_FLAG_LIST)
1967 silc_server_channel_key(server, sock, packet);
1973 case SILC_PACKET_COMMAND:
1975 * Recived command. Processes the command request and allocates the
1976 * command context and calls the command.
1978 SILC_LOG_DEBUG(("Command packet"));
1979 if (packet->flags & SILC_PACKET_FLAG_LIST)
1981 silc_server_command_process(server, sock, packet);
1984 case SILC_PACKET_COMMAND_REPLY:
1986 * Received command reply packet. Received command reply to command. It
1987 * may be reply to command sent by us or reply to command sent by client
1988 * that we've routed further.
1990 SILC_LOG_DEBUG(("Command Reply packet"));
1991 if (packet->flags & SILC_PACKET_FLAG_LIST)
1993 silc_server_command_reply(server, sock, packet);
1997 * Private Message packets
1999 case SILC_PACKET_PRIVATE_MESSAGE:
2001 * Received private message packet. The packet is coming from either
2004 SILC_LOG_DEBUG(("Private Message packet"));
2005 if (packet->flags & SILC_PACKET_FLAG_LIST)
2007 idata->last_receive = time(NULL);
2008 silc_server_private_message(server, sock, packet);
2011 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2013 * Private message key packet.
2015 if (packet->flags & SILC_PACKET_FLAG_LIST)
2017 silc_server_private_message_key(server, sock, packet);
2021 * Key Exchange protocol packets
2023 case SILC_PACKET_KEY_EXCHANGE:
2024 SILC_LOG_DEBUG(("KE packet"));
2025 if (packet->flags & SILC_PACKET_FLAG_LIST)
2028 if (sock->protocol && sock->protocol->protocol &&
2029 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2031 SilcServerKEInternalContext *proto_ctx =
2032 (SilcServerKEInternalContext *)sock->protocol->context;
2034 proto_ctx->packet = silc_packet_context_dup(packet);
2036 /* Let the protocol handle the packet */
2037 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2039 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2040 "protocol active, packet dropped."));
2044 case SILC_PACKET_KEY_EXCHANGE_1:
2045 SILC_LOG_DEBUG(("KE 1 packet"));
2046 if (packet->flags & SILC_PACKET_FLAG_LIST)
2049 if (sock->protocol && sock->protocol->protocol &&
2050 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2051 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2053 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2054 SilcServerRekeyInternalContext *proto_ctx =
2055 (SilcServerRekeyInternalContext *)sock->protocol->context;
2057 if (proto_ctx->packet)
2058 silc_packet_context_free(proto_ctx->packet);
2060 proto_ctx->packet = silc_packet_context_dup(packet);
2062 /* Let the protocol handle the packet */
2063 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2065 SilcServerKEInternalContext *proto_ctx =
2066 (SilcServerKEInternalContext *)sock->protocol->context;
2068 if (proto_ctx->packet)
2069 silc_packet_context_free(proto_ctx->packet);
2071 proto_ctx->packet = silc_packet_context_dup(packet);
2072 proto_ctx->dest_id_type = packet->src_id_type;
2073 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2074 packet->src_id_type);
2075 if (!proto_ctx->dest_id)
2078 /* Let the protocol handle the packet */
2079 silc_protocol_execute(sock->protocol, server->schedule,
2083 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2084 "protocol active, packet dropped."));
2088 case SILC_PACKET_KEY_EXCHANGE_2:
2089 SILC_LOG_DEBUG(("KE 2 packet"));
2090 if (packet->flags & SILC_PACKET_FLAG_LIST)
2093 if (sock->protocol && sock->protocol->protocol &&
2094 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2095 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2097 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2098 SilcServerRekeyInternalContext *proto_ctx =
2099 (SilcServerRekeyInternalContext *)sock->protocol->context;
2101 if (proto_ctx->packet)
2102 silc_packet_context_free(proto_ctx->packet);
2104 proto_ctx->packet = silc_packet_context_dup(packet);
2106 /* Let the protocol handle the packet */
2107 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2109 SilcServerKEInternalContext *proto_ctx =
2110 (SilcServerKEInternalContext *)sock->protocol->context;
2112 if (proto_ctx->packet)
2113 silc_packet_context_free(proto_ctx->packet);
2115 proto_ctx->packet = silc_packet_context_dup(packet);
2116 proto_ctx->dest_id_type = packet->src_id_type;
2117 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2118 packet->src_id_type);
2119 if (!proto_ctx->dest_id)
2122 /* Let the protocol handle the packet */
2123 silc_protocol_execute(sock->protocol, server->schedule,
2127 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2128 "protocol active, packet dropped."));
2132 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2134 * Connection authentication request packet. When we receive this packet
2135 * we will send to the other end information about our mandatory
2136 * authentication method for the connection. This packet maybe received
2139 SILC_LOG_DEBUG(("Connection authentication request packet"));
2140 if (packet->flags & SILC_PACKET_FLAG_LIST)
2142 silc_server_connection_auth_request(server, sock, packet);
2146 * Connection Authentication protocol packets
2148 case SILC_PACKET_CONNECTION_AUTH:
2149 /* Start of the authentication protocol. We receive here the
2150 authentication data and will verify it. */
2151 SILC_LOG_DEBUG(("Connection auth packet"));
2152 if (packet->flags & SILC_PACKET_FLAG_LIST)
2155 if (sock->protocol && sock->protocol->protocol->type
2156 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2158 SilcServerConnAuthInternalContext *proto_ctx =
2159 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2161 proto_ctx->packet = silc_packet_context_dup(packet);
2163 /* Let the protocol handle the packet */
2164 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2166 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2167 "protocol active, packet dropped."));
2171 case SILC_PACKET_NEW_ID:
2173 * Received New ID packet. This includes some new ID that has been
2174 * created. It may be for client, server or channel. This is the way
2175 * to distribute information about new registered entities in the
2178 SILC_LOG_DEBUG(("New ID packet"));
2179 if (packet->flags & SILC_PACKET_FLAG_LIST)
2180 silc_server_new_id_list(server, sock, packet);
2182 silc_server_new_id(server, sock, packet);
2185 case SILC_PACKET_NEW_CLIENT:
2187 * Received new client packet. This includes client information that
2188 * we will use to create initial client ID. After creating new
2189 * ID we will send it to the client.
2191 SILC_LOG_DEBUG(("New Client packet"));
2192 if (packet->flags & SILC_PACKET_FLAG_LIST)
2194 silc_server_new_client(server, sock, packet);
2197 case SILC_PACKET_NEW_SERVER:
2199 * Received new server packet. This includes Server ID and some other
2200 * information that we may save. This is received after server has
2203 SILC_LOG_DEBUG(("New Server packet"));
2204 if (packet->flags & SILC_PACKET_FLAG_LIST)
2206 silc_server_new_server(server, sock, packet);
2209 case SILC_PACKET_NEW_CHANNEL:
2211 * Received new channel packet. Information about new channel in the
2212 * network are distributed using this packet.
2214 SILC_LOG_DEBUG(("New Channel packet"));
2215 if (packet->flags & SILC_PACKET_FLAG_LIST)
2216 silc_server_new_channel_list(server, sock, packet);
2218 silc_server_new_channel(server, sock, packet);
2221 case SILC_PACKET_HEARTBEAT:
2223 * Received heartbeat.
2225 SILC_LOG_DEBUG(("Heartbeat packet"));
2226 if (packet->flags & SILC_PACKET_FLAG_LIST)
2230 case SILC_PACKET_KEY_AGREEMENT:
2232 * Received heartbeat.
2234 SILC_LOG_DEBUG(("Key agreement packet"));
2235 if (packet->flags & SILC_PACKET_FLAG_LIST)
2237 silc_server_key_agreement(server, sock, packet);
2240 case SILC_PACKET_REKEY:
2242 * Received re-key packet. The sender wants to regenerate the session
2245 SILC_LOG_DEBUG(("Re-key packet"));
2246 if (packet->flags & SILC_PACKET_FLAG_LIST)
2248 silc_server_rekey(server, sock, packet);
2251 case SILC_PACKET_REKEY_DONE:
2253 * The re-key is done.
2255 SILC_LOG_DEBUG(("Re-key done packet"));
2256 if (packet->flags & SILC_PACKET_FLAG_LIST)
2259 if (sock->protocol && sock->protocol->protocol &&
2260 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2262 SilcServerRekeyInternalContext *proto_ctx =
2263 (SilcServerRekeyInternalContext *)sock->protocol->context;
2265 if (proto_ctx->packet)
2266 silc_packet_context_free(proto_ctx->packet);
2268 proto_ctx->packet = silc_packet_context_dup(packet);
2270 /* Let the protocol handle the packet */
2271 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2273 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2274 "protocol active, packet dropped."));
2278 case SILC_PACKET_FTP:
2280 SILC_LOG_DEBUG(("FTP packet"));
2281 if (packet->flags & SILC_PACKET_FLAG_LIST)
2283 silc_server_ftp(server, sock, packet);
2286 case SILC_PACKET_RESUME_ROUTER:
2287 /* Resume router packet received. This packet is received for backup
2288 router resuming protocol. */
2289 SILC_LOG_DEBUG(("Resume router packet"));
2290 if (packet->flags & SILC_PACKET_FLAG_LIST)
2292 silc_server_backup_resume_router(server, sock, packet);
2296 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2302 /* Creates connection to a remote router. */
2304 void silc_server_create_connection(SilcServer server,
2305 const char *remote_host, SilcUInt32 port)
2307 SilcServerConnection sconn;
2309 /* Allocate connection object for hold connection specific stuff. */
2310 sconn = silc_calloc(1, sizeof(*sconn));
2311 sconn->server = server;
2312 sconn->remote_host = strdup(remote_host);
2313 sconn->remote_port = port;
2314 sconn->no_reconnect = TRUE;
2315 sconn->param = &server->config->param;
2317 silc_schedule_task_add(server->schedule, 0,
2318 silc_server_connect_router,
2319 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2320 SILC_TASK_PRI_NORMAL);
2323 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2325 silc_socket_free((SilcSocketConnection)context);
2328 /* Closes connection to socket connection */
2330 void silc_server_close_connection(SilcServer server,
2331 SilcSocketConnection sock)
2333 if (!server->sockets[sock->sock])
2336 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2338 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2339 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2340 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2343 /* We won't listen for this connection anymore */
2344 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2346 /* Unregister all tasks */
2347 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2349 /* Close the actual connection */
2350 silc_net_close_connection(sock->sock);
2351 server->sockets[sock->sock] = NULL;
2353 /* If sock->user_data is NULL then we'll check for active protocols
2354 here since the silc_server_free_sock_user_data has not been called
2355 for this connection. */
2356 if (!sock->user_data) {
2357 /* If any protocol is active cancel its execution. It will call
2358 the final callback which will finalize the disconnection. */
2359 if (sock->protocol) {
2360 silc_protocol_cancel(sock->protocol, server->schedule);
2361 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2362 silc_protocol_execute_final(sock->protocol, server->schedule);
2363 sock->protocol = NULL;
2368 silc_schedule_task_add(server->schedule, 0,
2369 silc_server_close_connection_final,
2370 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2371 SILC_TASK_PRI_NORMAL);
2374 /* Sends disconnect message to remote connection and disconnects the
2377 void silc_server_disconnect_remote(SilcServer server,
2378 SilcSocketConnection sock,
2379 const char *fmt, ...)
2382 unsigned char buf[4096];
2387 memset(buf, 0, sizeof(buf));
2389 vsprintf(buf, fmt, ap);
2392 SILC_LOG_DEBUG(("Disconnecting remote host"));
2394 /* Notify remote end that the conversation is over. The notify message
2395 is tried to be sent immediately. */
2396 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2397 buf, strlen(buf), TRUE);
2399 /* Mark the connection to be disconnected */
2400 SILC_SET_DISCONNECTED(sock);
2401 silc_server_close_connection(server, sock);
2406 SilcClientEntry client;
2407 } *FreeClientInternal;
2409 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2411 FreeClientInternal i = (FreeClientInternal)context;
2413 silc_idlist_del_data(i->client);
2414 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2418 /* Frees client data and notifies about client's signoff. */
2420 void silc_server_free_client_data(SilcServer server,
2421 SilcSocketConnection sock,
2422 SilcClientEntry client,
2424 const char *signoff)
2426 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2428 /* If there is pending outgoing data for the client then purge it
2429 to the network before removing the client entry. */
2430 silc_server_packet_queue_purge(server, sock);
2435 /* Send SIGNOFF notify to routers. */
2436 if (notify && !server->standalone && server->router)
2437 silc_server_send_notify_signoff(server, server->router->connection,
2438 server->server_type == SILC_SERVER ?
2439 FALSE : TRUE, client->id, signoff);
2441 /* Remove client from all channels */
2443 silc_server_remove_from_channels(server, NULL, client,
2444 TRUE, (char *)signoff, TRUE);
2446 silc_server_remove_from_channels(server, NULL, client,
2447 FALSE, NULL, FALSE);
2449 /* Update statistics */
2450 server->stat.my_clients--;
2451 server->stat.clients--;
2452 if (server->server_type == SILC_ROUTER)
2453 server->stat.cell_clients--;
2454 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2455 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2457 /* We will not delete the client entry right away. We will take it
2458 into history (for WHOWAS command) for 5 minutes */
2461 silc_schedule_task_add(server->schedule, 0,
2462 silc_server_free_client_data_timeout,
2464 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2465 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2466 client->router = NULL;
2467 client->connection = NULL;
2471 /* Frees user_data pointer from socket connection object. This also sends
2472 appropriate notify packets to the network to inform about leaving
2475 void silc_server_free_sock_user_data(SilcServer server,
2476 SilcSocketConnection sock,
2477 const char *signoff_message)
2479 SILC_LOG_DEBUG(("Start"));
2481 switch (sock->type) {
2482 case SILC_SOCKET_TYPE_CLIENT:
2484 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2485 silc_server_free_client_data(server, sock, user_data, TRUE,
2489 case SILC_SOCKET_TYPE_SERVER:
2490 case SILC_SOCKET_TYPE_ROUTER:
2492 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2493 SilcServerEntry backup_router = NULL;
2496 backup_router = silc_server_backup_get(server, user_data->id);
2498 /* If this was our primary router connection then we're lost to
2499 the outside world. */
2500 if (server->router == user_data) {
2501 /* Check whether we have a backup router connection */
2502 if (!backup_router || backup_router == user_data) {
2503 silc_schedule_task_add(server->schedule, 0,
2504 silc_server_connect_to_router,
2507 SILC_TASK_PRI_NORMAL);
2509 server->id_entry->router = NULL;
2510 server->router = NULL;
2511 server->standalone = TRUE;
2512 backup_router = NULL;
2514 SILC_LOG_INFO(("New primary router is backup router %s",
2515 backup_router->server_name));
2516 SILC_LOG_DEBUG(("New primary router is backup router %s",
2517 backup_router->server_name));
2518 server->id_entry->router = backup_router;
2519 server->router = backup_router;
2520 server->router_connect = time(0);
2521 server->backup_primary = TRUE;
2522 if (server->server_type == SILC_BACKUP_ROUTER) {
2523 server->server_type = SILC_ROUTER;
2525 /* We'll need to constantly try to reconnect to the primary
2526 router so that we'll see when it comes back online. */
2527 silc_server_backup_reconnect(server, sock->ip, sock->port,
2528 silc_server_backup_connected,
2532 /* Mark this connection as replaced */
2533 silc_server_backup_replaced_add(server, user_data->id,
2536 } else if (backup_router) {
2537 SILC_LOG_INFO(("Enabling the use of backup router %s",
2538 backup_router->server_name));
2539 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2540 backup_router->server_name));
2542 /* Mark this connection as replaced */
2543 silc_server_backup_replaced_add(server, user_data->id,
2547 if (!backup_router) {
2548 /* Free all client entries that this server owns as they will
2549 become invalid now as well. */
2551 silc_server_remove_clients_by_server(server, user_data, TRUE);
2552 if (server->server_type == SILC_SERVER)
2553 silc_server_remove_channels_by_server(server, user_data);
2555 /* Update the client entries of this server to the new backup
2556 router. This also removes the clients that *really* was owned
2557 by the primary router and went down with the router. */
2558 silc_server_update_clients_by_server(server, user_data, backup_router,
2560 silc_server_update_servers_by_server(server, user_data, backup_router);
2561 if (server->server_type == SILC_SERVER)
2562 silc_server_update_channels_by_server(server, user_data,
2566 /* Free the server entry */
2567 silc_server_backup_del(server, user_data);
2568 silc_server_backup_replaced_del(server, user_data);
2569 silc_idlist_del_data(user_data);
2570 if (!silc_idlist_del_server(server->local_list, user_data))
2571 silc_idlist_del_server(server->global_list, user_data);
2572 server->stat.my_servers--;
2573 server->stat.servers--;
2574 if (server->server_type == SILC_ROUTER)
2575 server->stat.cell_servers--;
2577 if (backup_router) {
2578 /* Announce all of our stuff that was created about 5 minutes ago.
2579 The backup router knows all the other stuff already. */
2580 if (server->server_type == SILC_ROUTER)
2581 silc_server_announce_servers(server, FALSE, time(0) - 300,
2582 backup_router->connection);
2584 /* Announce our clients and channels to the router */
2585 silc_server_announce_clients(server, time(0) - 300,
2586 backup_router->connection);
2587 silc_server_announce_channels(server, time(0) - 300,
2588 backup_router->connection);
2594 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2596 silc_idlist_del_data(user_data);
2597 silc_free(user_data);
2602 /* If any protocol is active cancel its execution */
2603 if (sock->protocol) {
2604 silc_protocol_cancel(sock->protocol, server->schedule);
2605 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2606 silc_protocol_execute_final(sock->protocol, server->schedule);
2607 sock->protocol = NULL;
2610 sock->user_data = NULL;
2613 /* Removes client from all channels it has joined. This is used when client
2614 connection is disconnected. If the client on a channel is last, the
2615 channel is removed as well. This sends the SIGNOFF notify types. */
2617 void silc_server_remove_from_channels(SilcServer server,
2618 SilcSocketConnection sock,
2619 SilcClientEntry client,
2621 char *signoff_message,
2624 SilcChannelEntry channel;
2625 SilcChannelClientEntry chl;
2626 SilcHashTableList htl;
2629 SILC_LOG_DEBUG(("Start"));
2631 if (!client || !client->id)
2634 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2636 /* Remove the client from all channels. The client is removed from
2637 the channels' user list. */
2638 silc_hash_table_list(client->channels, &htl);
2639 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2640 channel = chl->channel;
2642 /* Remove channel from client's channel list */
2643 silc_hash_table_del(client->channels, channel);
2645 /* Remove channel if there is no users anymore */
2646 if (server->server_type == SILC_ROUTER &&
2647 silc_hash_table_count(channel->user_list) < 2) {
2649 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2650 if (silc_idlist_del_channel(server->local_list, channel))
2651 server->stat.my_channels--;
2653 silc_idlist_del_channel(server->global_list, channel);
2657 /* Remove client from channel's client list */
2658 silc_hash_table_del(channel->user_list, chl->client);
2659 channel->user_count--;
2661 /* If there is no global users on the channel anymore mark the channel
2662 as local channel. Do not check if the removed client is local client. */
2663 if (server->server_type != SILC_ROUTER && channel->global_users &&
2664 chl->client->router && !silc_server_channel_has_global(channel))
2665 channel->global_users = FALSE;
2668 server->stat.my_chanclients--;
2670 /* If there is not at least one local user on the channel then we don't
2671 need the channel entry anymore, we can remove it safely. */
2672 if (server->server_type != SILC_ROUTER &&
2673 !silc_server_channel_has_local(channel)) {
2674 /* Notify about leaving client if this channel has global users. */
2675 if (notify && channel->global_users)
2676 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2677 SILC_NOTIFY_TYPE_SIGNOFF,
2678 signoff_message ? 2 : 1,
2679 clidp->data, clidp->len,
2680 signoff_message, signoff_message ?
2681 strlen(signoff_message) : 0);
2684 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2686 if (channel->founder_key) {
2687 /* The founder auth data exists, do not remove the channel entry */
2688 SilcChannelClientEntry chl2;
2689 SilcHashTableList htl2;
2691 channel->disabled = TRUE;
2693 silc_hash_table_list(channel->user_list, &htl2);
2694 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2695 silc_hash_table_del(chl2->client->channels, channel);
2696 silc_hash_table_del(channel->user_list, chl2->client);
2697 channel->user_count--;
2700 silc_hash_table_list_reset(&htl2);
2704 /* Remove the channel entry */
2705 if (silc_idlist_del_channel(server->local_list, channel))
2706 server->stat.my_channels--;
2708 silc_idlist_del_channel(server->global_list, channel);
2712 /* Send notify to channel about client leaving SILC and thus
2713 the entire channel. */
2715 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2716 SILC_NOTIFY_TYPE_SIGNOFF,
2717 signoff_message ? 2 : 1,
2718 clidp->data, clidp->len,
2719 signoff_message, signoff_message ?
2720 strlen(signoff_message) : 0);
2722 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2723 /* Re-generate channel key */
2724 if (!silc_server_create_channel_key(server, channel, 0))
2727 /* Send the channel key to the channel. The key of course is not sent
2728 to the client who was removed from the channel. */
2729 silc_server_send_channel_key(server, client->connection, channel,
2730 server->server_type == SILC_ROUTER ?
2731 FALSE : !server->standalone);
2736 silc_hash_table_list_reset(&htl);
2737 silc_buffer_free(clidp);
2740 /* Removes client from one channel. This is used for example when client
2741 calls LEAVE command to remove itself from the channel. Returns TRUE
2742 if channel still exists and FALSE if the channel is removed when
2743 last client leaves the channel. If `notify' is FALSE notify messages
2746 int silc_server_remove_from_one_channel(SilcServer server,
2747 SilcSocketConnection sock,
2748 SilcChannelEntry channel,
2749 SilcClientEntry client,
2752 SilcChannelClientEntry chl;
2755 SILC_LOG_DEBUG(("Start"));
2757 /* Get the entry to the channel, if this client is not on the channel
2759 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2762 /* Remove the client from the channel. The client is removed from
2763 the channel's user list. */
2765 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2767 /* Remove channel from client's channel list */
2768 silc_hash_table_del(client->channels, chl->channel);
2770 /* Remove channel if there is no users anymore */
2771 if (server->server_type == SILC_ROUTER &&
2772 silc_hash_table_count(channel->user_list) < 2) {
2774 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2775 if (silc_idlist_del_channel(server->local_list, channel))
2776 server->stat.my_channels--;
2778 silc_idlist_del_channel(server->global_list, channel);
2779 silc_buffer_free(clidp);
2783 /* Remove client from channel's client list */
2784 silc_hash_table_del(channel->user_list, chl->client);
2785 channel->user_count--;
2787 /* If there is no global users on the channel anymore mark the channel
2788 as local channel. Do not check if the client is local client. */
2789 if (server->server_type != SILC_ROUTER && channel->global_users &&
2790 chl->client->router && !silc_server_channel_has_global(channel))
2791 channel->global_users = FALSE;
2794 server->stat.my_chanclients--;
2796 /* If there is not at least one local user on the channel then we don't
2797 need the channel entry anymore, we can remove it safely. */
2798 if (server->server_type != SILC_ROUTER &&
2799 !silc_server_channel_has_local(channel)) {
2800 /* Notify about leaving client if this channel has global users. */
2801 if (notify && channel->global_users)
2802 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2803 SILC_NOTIFY_TYPE_LEAVE, 1,
2804 clidp->data, clidp->len);
2806 silc_buffer_free(clidp);
2809 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2811 if (channel->founder_key) {
2812 /* The founder auth data exists, do not remove the channel entry */
2813 SilcChannelClientEntry chl2;
2814 SilcHashTableList htl2;
2816 channel->disabled = TRUE;
2818 silc_hash_table_list(channel->user_list, &htl2);
2819 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2820 silc_hash_table_del(chl2->client->channels, channel);
2821 silc_hash_table_del(channel->user_list, chl2->client);
2822 channel->user_count--;
2825 silc_hash_table_list_reset(&htl2);
2829 /* Remove the channel entry */
2830 if (silc_idlist_del_channel(server->local_list, channel))
2831 server->stat.my_channels--;
2833 silc_idlist_del_channel(server->global_list, channel);
2837 /* Send notify to channel about client leaving the channel */
2839 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2840 SILC_NOTIFY_TYPE_LEAVE, 1,
2841 clidp->data, clidp->len);
2843 silc_buffer_free(clidp);
2847 /* Timeout callback. This is called if connection is idle or for some
2848 other reason is not responding within some period of time. This
2849 disconnects the remote end. */
2851 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2853 SilcServer server = (SilcServer)context;
2854 SilcSocketConnection sock = server->sockets[fd];
2856 SILC_LOG_DEBUG(("Start"));
2861 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2862 sock->hostname, sock->ip));
2864 /* If we have protocol active we must assure that we call the protocol's
2865 final callback so that all the memory is freed. */
2866 if (sock->protocol) {
2867 silc_protocol_cancel(sock->protocol, server->schedule);
2868 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2869 silc_protocol_execute_final(sock->protocol, server->schedule);
2870 sock->protocol = NULL;
2874 if (sock->user_data)
2875 silc_server_free_sock_user_data(server, sock, NULL);
2877 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2878 "Connection timeout");
2881 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2882 function may be used only by router. In real SILC network all channels
2883 are created by routers thus this function is never used by normal
2886 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2887 SilcServerID *router_id,
2893 SilcChannelID *channel_id;
2894 SilcChannelEntry entry;
2898 SILC_LOG_DEBUG(("Creating new channel"));
2901 cipher = SILC_DEFAULT_CIPHER;
2903 hmac = SILC_DEFAULT_HMAC;
2905 /* Allocate cipher */
2906 if (!silc_cipher_alloc(cipher, &key))
2910 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2911 silc_cipher_free(key);
2915 channel_name = strdup(channel_name);
2917 /* Create the channel ID */
2918 if (!silc_id_create_channel_id(server, router_id, server->rng,
2920 silc_free(channel_name);
2921 silc_cipher_free(key);
2922 silc_hmac_free(newhmac);
2926 /* Create the channel */
2927 entry = silc_idlist_add_channel(server->local_list, channel_name,
2928 SILC_CHANNEL_MODE_NONE, channel_id,
2929 NULL, key, newhmac, 0);
2931 silc_free(channel_name);
2932 silc_cipher_free(key);
2933 silc_hmac_free(newhmac);
2934 silc_free(channel_id);
2938 entry->cipher = strdup(cipher);
2939 entry->hmac_name = strdup(hmac);
2941 /* Now create the actual key material */
2942 if (!silc_server_create_channel_key(server, entry,
2943 silc_cipher_get_key_len(key) / 8)) {
2944 silc_idlist_del_channel(server->local_list, entry);
2948 /* Notify other routers about the new channel. We send the packet
2949 to our primary route. */
2950 if (broadcast && server->standalone == FALSE)
2951 silc_server_send_new_channel(server, server->router->connection, TRUE,
2952 channel_name, entry->id,
2953 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2956 server->stat.my_channels++;
2961 /* Same as above but creates the channel with Channel ID `channel_id. */
2964 silc_server_create_new_channel_with_id(SilcServer server,
2968 SilcChannelID *channel_id,
2971 SilcChannelEntry entry;
2975 SILC_LOG_DEBUG(("Creating new channel"));
2978 cipher = SILC_DEFAULT_CIPHER;
2980 hmac = SILC_DEFAULT_HMAC;
2982 /* Allocate cipher */
2983 if (!silc_cipher_alloc(cipher, &key))
2987 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2988 silc_cipher_free(key);
2992 channel_name = strdup(channel_name);
2994 /* Create the channel */
2995 entry = silc_idlist_add_channel(server->local_list, channel_name,
2996 SILC_CHANNEL_MODE_NONE, channel_id,
2997 NULL, key, newhmac, 0);
2999 silc_cipher_free(key);
3000 silc_hmac_free(newhmac);
3001 silc_free(channel_name);
3005 /* Now create the actual key material */
3006 if (!silc_server_create_channel_key(server, entry,
3007 silc_cipher_get_key_len(key) / 8)) {
3008 silc_idlist_del_channel(server->local_list, entry);
3012 /* Notify other routers about the new channel. We send the packet
3013 to our primary route. */
3014 if (broadcast && server->standalone == FALSE)
3015 silc_server_send_new_channel(server, server->router->connection, TRUE,
3016 channel_name, entry->id,
3017 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3020 server->stat.my_channels++;
3025 /* Channel's key re-key timeout callback. */
3027 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3029 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3030 SilcServer server = (SilcServer)rekey->context;
3034 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3037 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3040 /* Generates new channel key. This is used to create the initial channel key
3041 but also to re-generate new key for channel. If `key_len' is provided
3042 it is the bytes of the key length. */
3044 bool silc_server_create_channel_key(SilcServer server,
3045 SilcChannelEntry channel,
3049 unsigned char channel_key[32], hash[32];
3052 SILC_LOG_DEBUG(("Generating channel key"));
3054 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3055 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3059 if (!channel->channel_key)
3060 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3061 channel->channel_key = NULL;
3067 else if (channel->key_len)
3068 len = channel->key_len / 8;
3070 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3072 /* Create channel key */
3073 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3076 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3078 /* Remove old key if exists */
3080 memset(channel->key, 0, channel->key_len / 8);
3081 silc_free(channel->key);
3085 channel->key_len = len * 8;
3086 channel->key = silc_memdup(channel_key, len);
3087 memset(channel_key, 0, sizeof(channel_key));
3089 /* Generate HMAC key from the channel key data and set it */
3091 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3092 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3093 silc_hmac_set_key(channel->hmac, hash,
3094 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3095 memset(hash, 0, sizeof(hash));
3097 if (server->server_type == SILC_ROUTER) {
3098 if (!channel->rekey)
3099 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3100 channel->rekey->context = (void *)server;
3101 channel->rekey->channel = channel;
3102 channel->rekey->key_len = key_len;
3103 if (channel->rekey->task)
3104 silc_schedule_task_del(server->schedule, channel->rekey->task);
3106 channel->rekey->task =
3107 silc_schedule_task_add(server->schedule, 0,
3108 silc_server_channel_key_rekey,
3109 (void *)channel->rekey,
3110 server->config->channel_rekey_secs, 0,
3112 SILC_TASK_PRI_NORMAL);
3118 /* Saves the channel key found in the encoded `key_payload' buffer. This
3119 function is used when we receive Channel Key Payload and also when we're
3120 processing JOIN command reply. Returns entry to the channel. */
3122 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3123 SilcBuffer key_payload,
3124 SilcChannelEntry channel)
3126 SilcChannelKeyPayload payload = NULL;
3127 SilcChannelID *id = NULL;
3128 unsigned char *tmp, hash[32];
3132 SILC_LOG_DEBUG(("Start"));
3134 /* Decode channel key payload */
3135 payload = silc_channel_key_payload_parse(key_payload->data,
3138 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3143 /* Get the channel entry */
3146 /* Get channel ID */
3147 tmp = silc_channel_key_get_id(payload, &tmp_len);
3148 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3154 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3156 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3158 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3159 silc_id_render(id, SILC_ID_CHANNEL)));
3165 tmp = silc_channel_key_get_key(payload, &tmp_len);
3171 cipher = silc_channel_key_get_cipher(payload, NULL);
3177 /* Remove old key if exists */
3179 memset(channel->key, 0, channel->key_len / 8);
3180 silc_free(channel->key);
3181 silc_cipher_free(channel->channel_key);
3184 /* Create new cipher */
3185 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3186 channel->channel_key = NULL;
3191 if (channel->cipher)
3192 silc_free(channel->cipher);
3193 channel->cipher = strdup(cipher);
3196 channel->key_len = tmp_len * 8;
3197 channel->key = silc_memdup(tmp, tmp_len);
3198 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3200 /* Generate HMAC key from the channel key data and set it */
3202 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3203 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3204 silc_hmac_set_key(channel->hmac, hash,
3205 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3207 memset(hash, 0, sizeof(hash));
3208 memset(tmp, 0, tmp_len);
3210 if (server->server_type == SILC_ROUTER) {
3211 if (!channel->rekey)
3212 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3213 channel->rekey->context = (void *)server;
3214 channel->rekey->channel = channel;
3215 if (channel->rekey->task)
3216 silc_schedule_task_del(server->schedule, channel->rekey->task);
3218 channel->rekey->task =
3219 silc_schedule_task_add(server->schedule, 0,
3220 silc_server_channel_key_rekey,
3221 (void *)channel->rekey,
3222 server->config->channel_rekey_secs, 0,
3224 SILC_TASK_PRI_NORMAL);
3230 silc_channel_key_payload_free(payload);
3235 /* Heartbeat callback. This function is set as argument for the
3236 silc_socket_set_heartbeat function. The library will call this function
3237 at the set time interval. */
3239 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3242 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3244 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3246 /* Send the heartbeat */
3247 silc_server_send_heartbeat(hb->server, sock);
3250 /* Returns assembled of all servers in the given ID list. The packet's
3251 form is dictated by the New ID payload. */
3253 static void silc_server_announce_get_servers(SilcServer server,
3254 SilcServerEntry remote,
3256 SilcBuffer *servers,
3257 unsigned long creation_time)
3259 SilcIDCacheList list;
3260 SilcIDCacheEntry id_cache;
3261 SilcServerEntry entry;
3264 /* Go through all clients in the list */
3265 if (silc_idcache_get_all(id_list->servers, &list)) {
3266 if (silc_idcache_list_first(list, &id_cache)) {
3268 entry = (SilcServerEntry)id_cache->context;
3270 /* Do not announce the one we've sending our announcements and
3271 do not announce ourself. Also check the creation time if it's
3273 if ((entry == remote) || (entry == server->id_entry) ||
3274 (creation_time && entry->data.created < creation_time)) {
3275 if (!silc_idcache_list_next(list, &id_cache))
3280 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3282 *servers = silc_buffer_realloc(*servers,
3284 (*servers)->truelen + idp->len :
3286 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3287 silc_buffer_put(*servers, idp->data, idp->len);
3288 silc_buffer_pull(*servers, idp->len);
3289 silc_buffer_free(idp);
3291 if (!silc_idcache_list_next(list, &id_cache))
3296 silc_idcache_list_free(list);
3301 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3307 p = silc_notify_payload_encode(notify, argc, ap);
3313 /* This function is used by router to announce existing servers to our
3314 primary router when we've connected to it. If `creation_time' is non-zero
3315 then only the servers that has been created after the `creation_time'
3316 will be announced. */
3318 void silc_server_announce_servers(SilcServer server, bool global,
3319 unsigned long creation_time,
3320 SilcSocketConnection remote)
3322 SilcBuffer servers = NULL;
3324 SILC_LOG_DEBUG(("Announcing servers"));
3326 /* Get servers in local list */
3327 silc_server_announce_get_servers(server, remote->user_data,
3328 server->local_list, &servers,
3332 /* Get servers in global list */
3333 silc_server_announce_get_servers(server, remote->user_data,
3334 server->global_list, &servers,
3338 silc_buffer_push(servers, servers->data - servers->head);
3339 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3341 /* Send the packet */
3342 silc_server_packet_send(server, remote,
3343 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3344 servers->data, servers->len, TRUE);
3346 silc_buffer_free(servers);
3350 /* Returns assembled packet of all clients in the given ID list. The
3351 packet's form is dictated by the New ID Payload. */
3353 static void silc_server_announce_get_clients(SilcServer server,
3355 SilcBuffer *clients,
3357 unsigned long creation_time)
3359 SilcIDCacheList list;
3360 SilcIDCacheEntry id_cache;
3361 SilcClientEntry client;
3364 unsigned char mode[4];
3366 /* Go through all clients in the list */
3367 if (silc_idcache_get_all(id_list->clients, &list)) {
3368 if (silc_idcache_list_first(list, &id_cache)) {
3370 client = (SilcClientEntry)id_cache->context;
3372 if (creation_time && client->data.created < creation_time) {
3373 if (!silc_idcache_list_next(list, &id_cache))
3378 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3380 *clients = silc_buffer_realloc(*clients,
3382 (*clients)->truelen + idp->len :
3384 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3385 silc_buffer_put(*clients, idp->data, idp->len);
3386 silc_buffer_pull(*clients, idp->len);
3388 SILC_PUT32_MSB(client->mode, mode);
3389 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3390 2, idp->data, idp->len,
3392 *umodes = silc_buffer_realloc(*umodes,
3394 (*umodes)->truelen + tmp->len :
3396 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3397 silc_buffer_put(*umodes, tmp->data, tmp->len);
3398 silc_buffer_pull(*umodes, tmp->len);
3399 silc_buffer_free(tmp);
3401 silc_buffer_free(idp);
3403 if (!silc_idcache_list_next(list, &id_cache))
3408 silc_idcache_list_free(list);
3412 /* This function is used to announce our existing clients to our router
3413 when we've connected to it. If `creation_time' is non-zero then only
3414 the clients that has been created after the `creation_time' will be
3417 void silc_server_announce_clients(SilcServer server,
3418 unsigned long creation_time,
3419 SilcSocketConnection remote)
3421 SilcBuffer clients = NULL;
3422 SilcBuffer umodes = NULL;
3424 SILC_LOG_DEBUG(("Announcing clients"));
3426 /* Get clients in local list */
3427 silc_server_announce_get_clients(server, server->local_list,
3428 &clients, &umodes, creation_time);
3430 /* As router we announce our global list as well */
3431 if (server->server_type == SILC_ROUTER)
3432 silc_server_announce_get_clients(server, server->global_list,
3433 &clients, &umodes, creation_time);
3436 silc_buffer_push(clients, clients->data - clients->head);
3437 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3439 /* Send the packet */
3440 silc_server_packet_send(server, remote,
3441 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3442 clients->data, clients->len, TRUE);
3444 silc_buffer_free(clients);
3448 silc_buffer_push(umodes, umodes->data - umodes->head);
3449 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3451 /* Send the packet */
3452 silc_server_packet_send(server, remote,
3453 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3454 umodes->data, umodes->len, TRUE);
3456 silc_buffer_free(umodes);
3460 /* Returns channel's topic for announcing it */
3462 void silc_server_announce_get_channel_topic(SilcServer server,
3463 SilcChannelEntry channel,
3468 if (channel->topic) {
3469 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3470 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3471 chidp->data, chidp->len,
3473 strlen(channel->topic));
3474 silc_buffer_free(chidp);
3478 /* Returns assembled packets for channel users of the `channel'. */
3480 void silc_server_announce_get_channel_users(SilcServer server,
3481 SilcChannelEntry channel,
3482 SilcBuffer *channel_users,
3483 SilcBuffer *channel_users_modes)
3485 SilcChannelClientEntry chl;
3486 SilcHashTableList htl;
3487 SilcBuffer chidp, clidp;
3490 unsigned char mode[4];
3492 SILC_LOG_DEBUG(("Start"));
3494 /* Now find all users on the channel */
3495 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3496 silc_hash_table_list(channel->user_list, &htl);
3497 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3498 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3501 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3502 clidp->data, clidp->len,
3503 chidp->data, chidp->len);
3506 silc_buffer_realloc(*channel_users,
3508 (*channel_users)->truelen + len : len));
3509 silc_buffer_pull_tail(*channel_users,
3510 ((*channel_users)->end -
3511 (*channel_users)->data));
3513 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3514 silc_buffer_pull(*channel_users, len);
3515 silc_buffer_free(tmp);
3517 /* CUMODE notify for mode change on the channel */
3518 SILC_PUT32_MSB(chl->mode, mode);
3519 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3520 3, clidp->data, clidp->len,
3522 clidp->data, clidp->len);
3524 *channel_users_modes =
3525 silc_buffer_realloc(*channel_users_modes,
3526 (*channel_users_modes ?
3527 (*channel_users_modes)->truelen + len : len));
3528 silc_buffer_pull_tail(*channel_users_modes,
3529 ((*channel_users_modes)->end -
3530 (*channel_users_modes)->data));
3532 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3533 silc_buffer_pull(*channel_users_modes, len);
3534 silc_buffer_free(tmp);
3536 silc_buffer_free(clidp);
3538 silc_hash_table_list_reset(&htl);
3539 silc_buffer_free(chidp);
3542 /* Returns assembled packets for all channels and users on those channels
3543 from the given ID List. The packets are in the form dictated by the
3544 New Channel and New Channel User payloads. */
3546 void silc_server_announce_get_channels(SilcServer server,
3548 SilcBuffer *channels,
3549 SilcBuffer *channel_users,
3550 SilcBuffer **channel_users_modes,
3551 SilcUInt32 *channel_users_modes_c,
3552 SilcBuffer **channel_topics,
3553 SilcChannelID ***channel_ids,
3554 unsigned long creation_time)
3556 SilcIDCacheList list;
3557 SilcIDCacheEntry id_cache;
3558 SilcChannelEntry channel;
3561 SilcUInt16 name_len;
3563 int i = *channel_users_modes_c;
3566 SILC_LOG_DEBUG(("Start"));
3568 /* Go through all channels in the list */
3569 if (silc_idcache_get_all(id_list->channels, &list)) {
3570 if (silc_idcache_list_first(list, &id_cache)) {
3572 channel = (SilcChannelEntry)id_cache->context;
3574 if (creation_time && channel->created < creation_time)
3579 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3580 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3581 name_len = strlen(channel->channel_name);
3584 len = 4 + name_len + id_len + 4;
3586 silc_buffer_realloc(*channels,
3587 (*channels ? (*channels)->truelen +
3589 silc_buffer_pull_tail(*channels,
3590 ((*channels)->end - (*channels)->data));
3591 silc_buffer_format(*channels,
3592 SILC_STR_UI_SHORT(name_len),
3593 SILC_STR_UI_XNSTRING(channel->channel_name,
3595 SILC_STR_UI_SHORT(id_len),
3596 SILC_STR_UI_XNSTRING(cid, id_len),
3597 SILC_STR_UI_INT(channel->mode),
3599 silc_buffer_pull(*channels, len);
3602 /* Channel user modes */
3603 *channel_users_modes = silc_realloc(*channel_users_modes,
3604 sizeof(**channel_users_modes) *
3606 (*channel_users_modes)[i] = NULL;
3607 *channel_ids = silc_realloc(*channel_ids,
3608 sizeof(**channel_ids) * (i + 1));
3609 (*channel_ids)[i] = NULL;
3610 silc_server_announce_get_channel_users(server, channel,
3612 &(*channel_users_modes)[i]);
3613 (*channel_ids)[i] = channel->id;
3615 /* Channel's topic */
3616 *channel_topics = silc_realloc(*channel_topics,
3617 sizeof(**channel_topics) * (i + 1));
3618 (*channel_topics)[i] = NULL;
3619 silc_server_announce_get_channel_topic(server, channel,
3620 &(*channel_topics)[i]);
3623 if (!silc_idcache_list_next(list, &id_cache))
3627 *channel_users_modes_c += i;
3630 silc_idcache_list_free(list);
3634 /* This function is used to announce our existing channels to our router
3635 when we've connected to it. This also announces the users on the
3636 channels to the router. If the `creation_time' is non-zero only the
3637 channels that was created after the `creation_time' are announced.
3638 Note that the channel users are still announced even if the `creation_time'
3641 void silc_server_announce_channels(SilcServer server,
3642 unsigned long creation_time,
3643 SilcSocketConnection remote)
3645 SilcBuffer channels = NULL, channel_users = NULL;
3646 SilcBuffer *channel_users_modes = NULL;
3647 SilcBuffer *channel_topics = NULL;
3648 SilcUInt32 channel_users_modes_c = 0;
3649 SilcChannelID **channel_ids = NULL;
3651 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3653 /* Get channels and channel users in local list */
3654 silc_server_announce_get_channels(server, server->local_list,
3655 &channels, &channel_users,
3656 &channel_users_modes,
3657 &channel_users_modes_c,
3659 &channel_ids, creation_time);
3661 /* Get channels and channel users in global list */
3662 if (server->server_type != SILC_SERVER)
3663 silc_server_announce_get_channels(server, server->global_list,
3664 &channels, &channel_users,
3665 &channel_users_modes,
3666 &channel_users_modes_c,
3668 &channel_ids, creation_time);
3671 silc_buffer_push(channels, channels->data - channels->head);
3672 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3674 /* Send the packet */
3675 silc_server_packet_send(server, remote,
3676 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3677 channels->data, channels->len,
3680 silc_buffer_free(channels);
3683 if (channel_users) {
3684 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3685 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3686 channel_users->len);
3688 /* Send the packet */
3689 silc_server_packet_send(server, remote,
3690 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3691 channel_users->data, channel_users->len,
3694 silc_buffer_free(channel_users);
3697 if (channel_users_modes) {
3700 for (i = 0; i < channel_users_modes_c; i++) {
3701 if (!channel_users_modes[i])
3703 silc_buffer_push(channel_users_modes[i],
3704 channel_users_modes[i]->data -
3705 channel_users_modes[i]->head);
3706 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3707 channel_users_modes[i]->len);
3708 silc_server_packet_send_dest(server, remote,
3709 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3710 channel_ids[i], SILC_ID_CHANNEL,
3711 channel_users_modes[i]->data,
3712 channel_users_modes[i]->len,
3714 silc_buffer_free(channel_users_modes[i]);
3716 silc_free(channel_users_modes);
3719 if (channel_topics) {
3722 for (i = 0; i < channel_users_modes_c; i++) {
3723 if (!channel_topics[i])
3726 silc_buffer_push(channel_topics[i],
3727 channel_topics[i]->data -
3728 channel_topics[i]->head);
3729 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3730 channel_topics[i]->len);
3731 silc_server_packet_send_dest(server, remote,
3732 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3733 channel_ids[i], SILC_ID_CHANNEL,
3734 channel_topics[i]->data,
3735 channel_topics[i]->len,
3737 silc_buffer_free(channel_topics[i]);
3739 silc_free(channel_topics);
3742 silc_free(channel_ids);
3745 /* Failure timeout callback. If this is called then we will immediately
3746 process the received failure. We always process the failure with timeout
3747 since we do not want to blindly trust to received failure packets.
3748 This won't be called (the timeout is cancelled) if the failure was
3749 bogus (it is bogus if remote does not close the connection after sending
3752 SILC_TASK_CALLBACK(silc_server_failure_callback)
3754 SilcServerFailureContext f = (SilcServerFailureContext)context;
3756 if (f->sock->protocol) {
3757 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3758 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3764 /* Assembles user list and users mode list from the `channel'. */
3766 void silc_server_get_users_on_channel(SilcServer server,
3767 SilcChannelEntry channel,
3768 SilcBuffer *user_list,
3769 SilcBuffer *mode_list,
3770 SilcUInt32 *user_count)
3772 SilcChannelClientEntry chl;
3773 SilcHashTableList htl;
3774 SilcBuffer client_id_list;
3775 SilcBuffer client_mode_list;
3777 SilcUInt32 list_count = 0, len = 0;
3779 silc_hash_table_list(channel->user_list, &htl);
3780 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3781 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3782 silc_hash_table_list_reset(&htl);
3784 client_id_list = silc_buffer_alloc(len);
3786 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3787 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3788 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3790 silc_hash_table_list(channel->user_list, &htl);
3791 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3793 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3794 silc_buffer_put(client_id_list, idp->data, idp->len);
3795 silc_buffer_pull(client_id_list, idp->len);
3796 silc_buffer_free(idp);
3798 /* Client's mode on channel */
3799 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3800 silc_buffer_pull(client_mode_list, 4);
3804 silc_hash_table_list_reset(&htl);
3805 silc_buffer_push(client_id_list,
3806 client_id_list->data - client_id_list->head);
3807 silc_buffer_push(client_mode_list,
3808 client_mode_list->data - client_mode_list->head);
3810 *user_list = client_id_list;
3811 *mode_list = client_mode_list;
3812 *user_count = list_count;
3815 /* Saves users and their modes to the `channel'. */
3817 void silc_server_save_users_on_channel(SilcServer server,
3818 SilcSocketConnection sock,
3819 SilcChannelEntry channel,
3820 SilcClientID *noadd,
3821 SilcBuffer user_list,
3822 SilcBuffer mode_list,
3823 SilcUInt32 user_count)
3828 SilcClientID *client_id;
3829 SilcClientEntry client;
3830 SilcIDCacheEntry cache;
3833 SILC_LOG_DEBUG(("Start"));
3835 for (i = 0; i < user_count; i++) {
3837 SILC_GET16_MSB(idp_len, user_list->data + 2);
3839 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3840 silc_buffer_pull(user_list, idp_len);
3845 SILC_GET32_MSB(mode, mode_list->data);
3846 silc_buffer_pull(mode_list, 4);
3848 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3849 silc_free(client_id);
3855 /* Check if we have this client cached already. */
3856 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3857 server->server_type, &cache);
3859 client = silc_idlist_find_client_by_id(server->global_list,
3860 client_id, server->server_type,
3865 /* If router did not find such Client ID in its lists then this must
3866 be bogus client or some router in the net is buggy. */
3867 if (server->server_type == SILC_ROUTER) {
3868 silc_free(client_id);
3872 /* We don't have that client anywhere, add it. The client is added
3873 to global list since server didn't have it in the lists so it must be
3875 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3876 silc_id_dup(client_id, SILC_ID_CLIENT),
3877 sock->user_data, NULL, 0);
3879 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3880 silc_free(client_id);
3884 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3886 /* Found, if it is from global list we'll assure that we won't
3887 expire it now that the entry is on channel. */
3892 silc_free(client_id);
3894 if (!silc_server_client_on_channel(client, channel)) {
3895 /* Client was not on the channel, add it. */
3896 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3897 chl->client = client;
3899 chl->channel = channel;
3900 silc_hash_table_add(channel->user_list, chl->client, chl);
3901 silc_hash_table_add(client->channels, chl->channel, chl);
3902 channel->user_count++;
3907 /* Lookups route to the client indicated by the `id_data'. The connection
3908 object and internal data object is returned. Returns NULL if route
3909 could not be found to the client. If the `client_id' is specified then
3910 it is used and the `id_data' is ignored. */
3912 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3913 unsigned char *id_data,
3915 SilcClientID *client_id,
3916 SilcIDListData *idata)
3919 SilcClientEntry client;
3921 SILC_LOG_DEBUG(("Start"));
3923 /* Decode destination Client ID */
3925 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3927 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3931 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3934 /* If the destination belongs to our server we don't have to route
3935 the packet anywhere but to send it to the local destination. */
3936 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3940 /* If we are router and the client has router then the client is in
3941 our cell but not directly connected to us. */
3942 if (server->server_type == SILC_ROUTER && client->router) {
3943 /* We are of course in this case the client's router thus the route
3944 to the client is the server who owns the client. So, we will send
3945 the packet to that server. */
3947 *idata = (SilcIDListData)client->router;
3948 return client->router->connection;
3951 /* Seems that client really is directly connected to us */
3953 *idata = (SilcIDListData)client;
3954 return client->connection;
3957 /* Destination belongs to someone not in this server. If we are normal
3958 server our action is to send the packet to our router. */
3959 if (server->server_type != SILC_ROUTER && !server->standalone) {
3962 *idata = (SilcIDListData)server->router;
3963 return server->router->connection;
3966 /* We are router and we will perform route lookup for the destination
3967 and send the packet to fastest route. */
3968 if (server->server_type == SILC_ROUTER && !server->standalone) {
3969 /* Check first that the ID is valid */
3970 client = silc_idlist_find_client_by_id(server->global_list, id,
3973 SilcSocketConnection dst_sock;
3975 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3979 *idata = (SilcIDListData)dst_sock->user_data;
3988 /* Encodes and returns channel list of channels the `client' has joined.
3989 Secret channels are not put to the list. */
3991 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3992 SilcClientEntry client)
3994 SilcBuffer buffer = NULL;
3995 SilcChannelEntry channel;
3996 SilcChannelClientEntry chl;
3997 SilcHashTableList htl;
4000 SilcUInt16 name_len;
4003 silc_hash_table_list(client->channels, &htl);
4004 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4005 channel = chl->channel;
4007 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4008 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4011 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4012 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4013 name_len = strlen(channel->channel_name);
4015 len = 4 + name_len + id_len + 4;
4016 buffer = silc_buffer_realloc(buffer,
4017 (buffer ? (buffer)->truelen + len : len));
4018 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4019 silc_buffer_format(buffer,
4020 SILC_STR_UI_SHORT(name_len),
4021 SILC_STR_UI_XNSTRING(channel->channel_name,
4023 SILC_STR_UI_SHORT(id_len),
4024 SILC_STR_UI_XNSTRING(cid, id_len),
4025 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4027 silc_buffer_pull(buffer, len);
4030 silc_hash_table_list_reset(&htl);
4033 silc_buffer_push(buffer, buffer->data - buffer->head);
4038 /* Finds client entry by Client ID and if it is not found then resolves
4039 it using WHOIS command. */
4041 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4042 SilcClientID *client_id,
4045 SilcClientEntry client;
4050 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4053 client = silc_idlist_find_client_by_id(server->global_list,
4054 client_id, TRUE, NULL);
4055 if (!client && server->server_type == SILC_ROUTER)
4059 if (!client && server->standalone)
4062 if (!client || !client->nickname || !client->username) {
4063 SilcBuffer buffer, idp;
4065 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4066 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4067 client->resolve_cmd_ident = ++server->cmd_ident;
4069 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4070 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4071 server->cmd_ident, 1,
4072 3, idp->data, idp->len);
4073 silc_server_packet_send(server, client ? client->router->connection :
4074 server->router->connection,
4075 SILC_PACKET_COMMAND, 0,
4076 buffer->data, buffer->len, FALSE);
4077 silc_buffer_free(idp);
4078 silc_buffer_free(buffer);
4089 /* A timeout callback for the re-key. We will be the initiator of the
4092 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4094 SilcSocketConnection sock = (SilcSocketConnection)context;
4095 SilcIDListData idata = (SilcIDListData)sock->user_data;
4096 SilcServer server = (SilcServer)idata->rekey->context;
4097 SilcProtocol protocol;
4098 SilcServerRekeyInternalContext *proto_ctx;
4100 SILC_LOG_DEBUG(("Start"));
4102 /* Allocate internal protocol context. This is sent as context
4104 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4105 proto_ctx->server = (void *)server;
4106 proto_ctx->sock = sock;
4107 proto_ctx->responder = FALSE;
4108 proto_ctx->pfs = idata->rekey->pfs;
4110 /* Perform rekey protocol. Will call the final callback after the
4111 protocol is over. */
4112 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4113 &protocol, proto_ctx, silc_server_rekey_final);
4114 sock->protocol = protocol;
4116 /* Run the protocol */
4117 silc_protocol_execute(protocol, server->schedule, 0, 0);
4119 /* Re-register re-key timeout */
4120 silc_schedule_task_add(server->schedule, sock->sock,
4121 silc_server_rekey_callback,
4122 context, idata->rekey->timeout, 0,
4123 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4126 /* The final callback for the REKEY protocol. This will actually take the
4127 new key material into use. */
4129 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4131 SilcProtocol protocol = (SilcProtocol)context;
4132 SilcServerRekeyInternalContext *ctx =
4133 (SilcServerRekeyInternalContext *)protocol->context;
4134 SilcServer server = (SilcServer)ctx->server;
4135 SilcSocketConnection sock = ctx->sock;
4137 SILC_LOG_DEBUG(("Start"));
4139 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4140 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4141 /* Error occured during protocol */
4142 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4143 silc_protocol_cancel(protocol, server->schedule);
4144 silc_protocol_free(protocol);
4145 sock->protocol = NULL;
4147 silc_packet_context_free(ctx->packet);
4149 silc_ske_free(ctx->ske);
4154 /* Purge the outgoing data queue to assure that all rekey packets really
4155 go to the network before we quit the protocol. */
4156 silc_server_packet_queue_purge(server, sock);
4159 silc_protocol_free(protocol);
4160 sock->protocol = NULL;
4162 silc_packet_context_free(ctx->packet);
4164 silc_ske_free(ctx->ske);