5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
44 /* Allocates a new SILC server object. This has to be done before the server
45 can be used. After allocation one must call silc_server_init to initialize
46 the server. The new allocated server object is returned to the new_server
49 int silc_server_alloc(SilcServer *new_server)
53 SILC_LOG_DEBUG(("Allocating new server object"));
55 server = silc_calloc(1, sizeof(*server));
56 server->server_type = SILC_SERVER;
57 server->standalone = TRUE;
58 server->local_list = silc_calloc(1, sizeof(*server->local_list));
59 server->global_list = silc_calloc(1, sizeof(*server->global_list));
60 server->pending_commands = silc_dlist_init();
62 server->sim = silc_dlist_init();
70 /* Free's the SILC server object. This is called at the very end before
73 void silc_server_free(SilcServer server)
80 silc_free(server->local_list);
81 silc_free(server->global_list);
83 silc_rng_free(server->rng);
86 silc_pkcs_free(server->pkcs);
89 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
90 silc_dlist_del(server->sim, sim);
93 silc_dlist_uninit(server->sim);
96 if (server->pending_commands)
97 silc_dlist_uninit(server->pending_commands);
103 /* Initializes the entire SILC server. This is called always before running
104 the server. This is called only once at the initialization of the program.
105 This binds the server to its listenning port. After this function returns
106 one should call silc_server_run to start the server. This returns TRUE
107 when everything is ok to run the server. Configuration file must be
108 read and parsed before calling this. */
110 int silc_server_init(SilcServer server)
114 SilcServerEntry id_entry;
115 SilcIDListPurge purge;
117 SILC_LOG_DEBUG(("Initializing server"));
119 assert(server->config);
121 /* Set public and private keys */
122 if (!server->config->server_info ||
123 !server->config->server_info->public_key ||
124 !server->config->server_info->private_key) {
125 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
128 server->public_key = server->config->server_info->public_key;
129 server->private_key = server->config->server_info->private_key;
131 /* Set default to configuration parameters */
132 silc_server_config_set_defaults(server);
134 /* Register all configured ciphers, PKCS and hash functions. */
135 if (!silc_server_config_register_ciphers(server))
136 silc_cipher_register_default();
137 if (!silc_server_config_register_pkcs(server))
138 silc_pkcs_register_default();
139 if (!silc_server_config_register_hashfuncs(server))
140 silc_hash_register_default();
141 if (!silc_server_config_register_hmacs(server))
142 silc_hmac_register_default();
144 /* Initialize random number generator for the server. */
145 server->rng = silc_rng_alloc();
146 silc_rng_init(server->rng);
147 silc_rng_global_init(server->rng);
149 /* Initialize hash functions for server to use */
150 silc_hash_alloc("md5", &server->md5hash);
151 silc_hash_alloc("sha1", &server->sha1hash);
153 /* Allocate PKCS context for local public and private keys */
154 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
155 silc_pkcs_public_key_set(server->pkcs, server->public_key);
156 silc_pkcs_private_key_set(server->pkcs, server->private_key);
158 /* Create a listening server */
159 sock = silc_net_create_server(server->config->server_info->port,
160 server->config->server_info->server_ip);
162 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
163 server->config->server_info->server_ip,
164 server->config->server_info->port));
168 /* Initialize ID caches */
169 server->local_list->clients =
170 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
171 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
172 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
174 /* These are allocated for normal server as well as these hold some
175 global information that the server has fetched from its router. For
176 router these are used as they are supposed to be used on router. */
177 server->global_list->clients =
178 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
179 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
180 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
182 /* Allocate the entire socket list that is used in server. Eventually
183 all connections will have entry in this table (it is a table of
184 pointers to the actual object that is allocated individually
186 server->sockets = silc_calloc(server->config->param.connections_max,
187 sizeof(*server->sockets));
190 SilcSocketConnection newsocket = NULL;
192 /* Set socket to non-blocking mode */
193 silc_net_set_socket_nonblock(sock);
196 /* Add ourselves also to the socket table. The entry allocated above
197 is sent as argument for fast referencing in the future. */
198 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
199 server->sockets[sock] = newsocket;
201 /* Perform name and address lookups to resolve the listenning address
203 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
205 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
207 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
208 newsocket->hostname ? newsocket->hostname :
209 newsocket->ip ? newsocket->ip : ""));
210 server->stat.conn_failures++;
213 if (!newsocket->hostname)
214 newsocket->hostname = strdup(newsocket->ip);
216 newsocket->port = silc_net_get_local_port(sock);
218 /* Create a Server ID for the server. */
219 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
224 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
225 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
226 server->id_type = SILC_ID_SERVER;
227 server->server_name = server->config->server_info->server_name;
229 /* Add ourselves to the server list. We don't have a router yet
230 beacuse we haven't established a route yet. It will be done later.
231 For now, NULL is sent as router. This allocates new entry to
234 silc_idlist_add_server(server->local_list,
235 server->config->server_info->server_name,
236 server->server_type, server->id, NULL, NULL);
238 SILC_LOG_ERROR(("Could not add ourselves to cache"));
241 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
243 /* Put the allocated socket pointer also to the entry allocated above
244 for fast back-referencing to the socket list. */
245 newsocket->user_data = (void *)id_entry;
246 id_entry->connection = (void *)newsocket;
247 server->id_entry = id_entry;
250 /* Register protocols */
251 silc_server_protocols_register();
253 /* Initialize the scheduler. */
254 server->schedule = silc_schedule_init(server->config->param.connections_max);
255 if (!server->schedule)
258 /* Add the first task to the scheduler. This is task that is executed by
259 timeout. It expires as soon as the caller calls silc_server_run. This
260 task performs authentication protocol and key exchange with our
262 silc_schedule_task_add(server->schedule, sock,
263 silc_server_connect_to_router,
264 (void *)server, 0, 1,
266 SILC_TASK_PRI_NORMAL);
268 /* Add listener task to the scheduler. This task receives new connections
269 to the server. This task remains on the queue until the end of the
271 silc_schedule_task_add(server->schedule, sock,
272 silc_server_accept_new_connection,
273 (void *)server, 0, 0,
275 SILC_TASK_PRI_NORMAL);
276 server->listenning = TRUE;
278 /* Send log file configuration */
279 silc_server_config_setlogfiles(server);
281 /* If server connections has been configured then we must be router as
282 normal server cannot have server connections, only router connections. */
283 if (server->config->servers) {
284 SilcServerConfigServer *ptr = server->config->servers;
286 server->server_type = SILC_ROUTER;
288 if (ptr->backup_router) {
289 server->server_type = SILC_BACKUP_ROUTER;
290 server->backup_router = TRUE;
291 server->id_entry->server_type = SILC_BACKUP_ROUTER;
298 /* Register the ID Cache purge task. This periodically purges the ID cache
299 and removes the expired cache entries. */
301 /* Clients local list */
302 purge = silc_calloc(1, sizeof(*purge));
303 purge->cache = server->local_list->clients;
304 purge->schedule = server->schedule;
305 purge->timeout = 600;
306 silc_schedule_task_add(purge->schedule, 0,
308 (void *)purge, purge->timeout, 0,
309 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
311 /* Clients global list */
312 purge = silc_calloc(1, sizeof(*purge));
313 purge->cache = server->global_list->clients;
314 purge->schedule = server->schedule;
315 purge->timeout = 300;
316 silc_schedule_task_add(purge->schedule, 0,
318 (void *)purge, purge->timeout, 0,
319 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
321 SILC_LOG_DEBUG(("Server initialized"));
323 /* We are done here, return succesfully */
327 silc_net_close_server(sock);
331 /* Fork server to background */
333 void silc_server_daemonise(SilcServer server)
337 SILC_LOG_DEBUG(("Forking SILC server to background"));
342 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
347 SILC_LOG_DEBUG(("Server started as user"));
349 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
355 /* Drop root privligies. If this cannot be done, die. */
357 void silc_server_drop(SilcServer server)
359 /* Are we executing silcd as root or a regular user? */
365 /* Get the values given for user and group in configuration file */
366 user = server->config->server_info->user;
367 group = server->config->server_info->group;
369 if (!user || !group) {
370 fprintf(stderr, "Error:" /* XXX update this error message */
371 "\tSILC server must not be run as root. For the security of your\n"
372 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
373 "\tuser account. Modify the [Identity] configuration section to run\n"
374 "\tthe server as non-root user.\n");
378 /* Check whether the user/group does not begin with a number */
379 if (isdigit(user[0]) || isdigit(group[0])) {
380 SILC_LOG_DEBUG(("User and/or group starts with a number"));
381 fprintf(stderr, "Invalid user and/or group information\n");
382 fprintf(stderr, "Please assign them as names, not numbers\n");
386 if (!(pw = getpwnam(user))) {
387 fprintf(stderr, "Error: No such user %s found.\n", user);
390 if (!(gr = getgrnam(group))) {
391 fprintf(stderr, "Error: No such group %s found.\n", group);
395 /* Check whether user and/or group is set to root. If yes, exit
396 immediately. Otherwise, setgid and setuid server to user.group */
397 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
398 fprintf(stderr, "Error:"
399 "\tSILC server must not be run as root. For the security of your\n"
400 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
401 "\tuser account. Modify the [Identity] configuration section to run\n"
402 "\tthe server as non-root user.\n");
406 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
407 if (setgid(gr->gr_gid) != 0) {
408 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
412 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
413 SILC_LOG_DEBUG(("Removing supplementary groups"));
414 if (setgroups(0, NULL) != 0) {
415 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
418 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
419 if (initgroups(user, gr->gr_gid) != 0) {
420 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
421 "Exiting.\n", user, gr->gr_gid);
425 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
426 if (setuid(pw->pw_uid) != 0) {
427 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
434 /* The heart of the server. This runs the scheduler thus runs the server.
435 When this returns the server has been stopped and the program will
438 void silc_server_run(SilcServer server)
440 SILC_LOG_DEBUG(("Running server"));
442 SILC_LOG_INFO(("SILC Server started"));
444 /* Start the scheduler, the heart of the SILC server. When this returns
445 the program will be terminated. */
446 silc_schedule(server->schedule);
449 /* Stops the SILC server. This function is used to shutdown the server.
450 This is usually called after the scheduler has returned. After stopping
451 the server one should call silc_server_free. */
453 void silc_server_stop(SilcServer server)
455 SILC_LOG_DEBUG(("Stopping server"));
457 if (server->schedule) {
458 silc_schedule_stop(server->schedule);
459 silc_schedule_uninit(server->schedule);
460 server->schedule = NULL;
463 silc_server_protocols_unregister();
465 SILC_LOG_DEBUG(("Server stopped"));
468 /* Function that is called when the network connection to a router has
469 been established. This will continue with the key exchange protocol
470 with the remote router. */
472 void silc_server_start_key_exchange(SilcServer server,
473 SilcServerConnection sconn,
476 SilcSocketConnection newsocket;
477 SilcProtocol protocol;
478 SilcServerKEInternalContext *proto_ctx;
479 SilcServerConfigRouter *conn = sconn->conn;
482 /* Cancel any possible retry timeouts */
483 silc_schedule_task_del_by_callback(server->schedule,
484 silc_server_connect_router);
486 /* Set socket options */
487 silc_net_set_socket_nonblock(sock);
488 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
490 /* Create socket connection for the connection. Even though we
491 know that we are connecting to a router we will mark the socket
492 to be unknown connection until we have executed authentication
494 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
495 server->sockets[sock] = newsocket;
496 newsocket->hostname = strdup(sconn->remote_host);
497 newsocket->ip = strdup(sconn->remote_host);
498 newsocket->port = sconn->remote_port;
499 sconn->sock = newsocket;
501 /* Allocate internal protocol context. This is sent as context
503 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
504 proto_ctx->server = (void *)server;
505 proto_ctx->context = (void *)sconn;
506 proto_ctx->sock = newsocket;
507 proto_ctx->rng = server->rng;
508 proto_ctx->responder = FALSE;
510 /* Set Key Exchange flags from configuration, but fall back to global
512 SILC_GET_SKE_FLAGS(conn, proto_ctx);
513 if (server->config->param.key_exchange_pfs)
514 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
516 /* Perform key exchange protocol. silc_server_connect_to_router_second
517 will be called after the protocol is finished. */
518 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
519 &protocol, proto_ctx,
520 silc_server_connect_to_router_second);
521 newsocket->protocol = protocol;
523 /* Register a timeout task that will be executed if the protocol
524 is not executed within set limit. */
525 proto_ctx->timeout_task =
526 silc_schedule_task_add(server->schedule, sock,
527 silc_server_timeout_remote,
528 server, server->config->key_exchange_timeout, 0,
532 /* Register the connection for network input and output. This sets
533 that scheduler will listen for incoming packets for this connection
534 and sets that outgoing packets may be sent to this connection as
535 well. However, this doesn't set the scheduler for outgoing traffic,
536 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
537 later when outgoing data is available. */
538 context = (void *)server;
539 SILC_REGISTER_CONNECTION_FOR_IO(sock);
541 /* Run the protocol */
542 silc_protocol_execute(protocol, server->schedule, 0, 0);
545 /* Timeout callback that will be called to retry connecting to remote
546 router. This is used by both normal and router server. This will wait
547 before retrying the connecting. The timeout is generated by exponential
548 backoff algorithm. */
550 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
552 SilcServerConnection sconn = (SilcServerConnection)context;
553 SilcServer server = sconn->server;
554 SilcServerConfigConnParams *param =
555 (sconn->param ? sconn->param : &server->config->param);
557 SILC_LOG_INFO(("Retrying connecting to a router"));
559 /* Calculate next timeout */
560 if (sconn->retry_count >= 1) {
561 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
562 if (sconn->retry_timeout > param->reconnect_interval_max)
563 sconn->retry_timeout = param->reconnect_interval_max;
565 sconn->retry_timeout = param->reconnect_interval;
567 sconn->retry_count++;
568 sconn->retry_timeout = sconn->retry_timeout +
569 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
571 /* If we've reached max retry count, give up. */
572 if (sconn->retry_count > param->reconnect_count &&
573 param->reconnect_keep_trying == FALSE) {
574 SILC_LOG_ERROR(("Could not connect to router, giving up"));
575 silc_free(sconn->remote_host);
580 /* Wait one before retrying */
581 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
582 context, sconn->retry_timeout, 0,
583 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
586 /* Generic routine to use connect to a router. */
588 SILC_TASK_CALLBACK(silc_server_connect_router)
590 SilcServerConnection sconn = (SilcServerConnection)context;
591 SilcServer server = sconn->server;
594 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
595 (sconn->backup ? "backup router" : "router"),
596 sconn->remote_host, sconn->remote_port));
598 server->router_connect = time(NULL);
600 /* Connect to remote host */
601 sock = silc_net_create_connection(server->config->server_info->server_ip,
605 SILC_LOG_ERROR(("Could not connect to router %s:%d",
606 sconn->remote_host, sconn->remote_port));
607 if (!sconn->no_reconnect)
608 silc_schedule_task_add(server->schedule, fd,
609 silc_server_connect_to_router_retry,
610 context, 0, 1, SILC_TASK_TIMEOUT,
611 SILC_TASK_PRI_NORMAL);
615 /* Continue with key exchange protocol */
616 silc_server_start_key_exchange(server, sconn, sock);
619 /* This function connects to our primary router or if we are a router this
620 establishes all our primary routes. This is called at the start of the
621 server to do authentication and key exchange with our router - called
624 SILC_TASK_CALLBACK(silc_server_connect_to_router)
626 SilcServer server = (SilcServer)context;
627 SilcServerConnection sconn;
628 SilcServerConfigRouter *ptr;
630 SILC_LOG_DEBUG(("Connecting to router(s)"));
632 if (server->server_type == SILC_SERVER) {
633 SILC_LOG_DEBUG(("We are normal server"));
634 } else if (server->server_type == SILC_ROUTER) {
635 SILC_LOG_DEBUG(("We are router"));
637 SILC_LOG_DEBUG(("We are backup router/normal server"));
640 /* Create the connections to all our routes */
641 ptr = server->config->routers;
644 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
645 ptr->backup_router ? "Backup router" : "Router",
646 ptr->initiator ? "Initiator" : "Responder",
647 ptr->host, ptr->port));
649 if (ptr->initiator) {
650 /* Allocate connection object for hold connection specific stuff. */
651 sconn = silc_calloc(1, sizeof(*sconn));
652 sconn->server = server;
653 sconn->remote_host = strdup(ptr->host);
654 sconn->remote_port = ptr->port;
655 sconn->backup = ptr->backup_router;
657 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
658 sconn->backup_replace_port = ptr->backup_replace_port;
661 if (!server->router_conn && !sconn->backup)
662 server->router_conn = sconn;
665 sconn->param = ptr->param;
667 silc_schedule_task_add(server->schedule, fd,
668 silc_server_connect_router,
669 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
670 SILC_TASK_PRI_NORMAL);
679 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
681 /* There wasn't a configured router, we will continue but we don't
682 have a connection to outside world. We will be standalone server. */
683 server->standalone = TRUE;
686 /* Second part of connecting to router(s). Key exchange protocol has been
687 executed and now we will execute authentication protocol. */
689 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
691 SilcProtocol protocol = (SilcProtocol)context;
692 SilcServerKEInternalContext *ctx =
693 (SilcServerKEInternalContext *)protocol->context;
694 SilcServer server = (SilcServer)ctx->server;
695 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
696 SilcSocketConnection sock = ctx->sock;
697 SilcServerConnAuthInternalContext *proto_ctx;
698 SilcServerConfigRouter *conn = NULL;
700 SILC_LOG_DEBUG(("Start"));
702 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
703 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
704 /* Error occured during protocol */
705 silc_protocol_free(protocol);
706 sock->protocol = NULL;
707 silc_ske_free_key_material(ctx->keymat);
709 silc_packet_context_free(ctx->packet);
711 silc_ske_free(ctx->ske);
712 silc_free(ctx->dest_id);
714 silc_schedule_task_del_by_callback(server->schedule,
715 silc_server_failure_callback);
716 silc_server_disconnect_remote(server, sock, "Server closed connection: "
717 "Key exchange failed");
721 /* We now have the key material as the result of the key exchange
722 protocol. Take the key material into use. Free the raw key material
723 as soon as we've set them into use. */
724 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
725 ctx->sock, ctx->keymat,
726 ctx->ske->prop->cipher,
727 ctx->ske->prop->pkcs,
728 ctx->ske->prop->hash,
729 ctx->ske->prop->hmac,
730 ctx->ske->prop->group,
732 silc_protocol_free(protocol);
733 sock->protocol = NULL;
734 silc_ske_free_key_material(ctx->keymat);
736 silc_packet_context_free(ctx->packet);
738 silc_ske_free(ctx->ske);
739 silc_free(ctx->dest_id);
741 silc_schedule_task_del_by_callback(server->schedule,
742 silc_server_failure_callback);
743 silc_server_disconnect_remote(server, sock, "Server closed connection: "
744 "Key exchange failed");
747 silc_ske_free_key_material(ctx->keymat);
749 /* Allocate internal context for the authentication protocol. This
750 is sent as context for the protocol. */
751 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
752 proto_ctx->server = (void *)server;
753 proto_ctx->context = (void *)sconn;
754 proto_ctx->sock = sock;
755 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
756 proto_ctx->dest_id_type = ctx->dest_id_type;
757 proto_ctx->dest_id = ctx->dest_id;
759 /* Resolve the authentication method used in this connection. Check if
760 we find a match from user configured connections */
762 conn = silc_server_config_find_router_conn(server, sock->hostname,
768 /* Match found. Use the configured authentication method */
769 if (conn->passphrase) {
770 if (conn->publickey && !server->config->prefer_passphrase_auth) {
771 proto_ctx->auth_data = conn->publickey;
772 proto_ctx->auth_data_len = 0;
773 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
775 proto_ctx->auth_data = strdup(conn->passphrase);
776 proto_ctx->auth_data_len = strlen(conn->passphrase);
777 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
779 } else if (conn->publickey) {
780 proto_ctx->auth_data = conn->publickey;
781 proto_ctx->auth_data_len = 0;
782 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
784 proto_ctx->auth_meth = SILC_AUTH_NONE;
787 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
788 sock->hostname, sock->ip, sock->port));
789 silc_protocol_free(protocol);
790 sock->protocol = NULL;
792 silc_packet_context_free(ctx->packet);
794 silc_ske_free(ctx->ske);
795 silc_free(ctx->dest_id);
797 silc_schedule_task_del_by_callback(server->schedule,
798 silc_server_failure_callback);
799 silc_server_disconnect_remote(server, sock, "Server closed connection: "
800 "Key exchange failed");
804 /* Free old protocol as it is finished now */
805 silc_protocol_free(protocol);
807 silc_packet_context_free(ctx->packet);
809 sock->protocol = NULL;
811 /* Allocate the authentication protocol. This is allocated here
812 but we won't start it yet. We will be receiving party of this
813 protocol thus we will wait that connecting party will make
815 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
816 &sock->protocol, proto_ctx,
817 silc_server_connect_to_router_final);
819 /* Register timeout task. If the protocol is not executed inside
820 this timelimit the connection will be terminated. */
821 proto_ctx->timeout_task =
822 silc_schedule_task_add(server->schedule, sock->sock,
823 silc_server_timeout_remote,
825 server->config->conn_auth_timeout, 0,
829 /* Run the protocol */
830 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
833 /* Finalizes the connection to router. Registers a server task to the
834 queue so that we can accept new connections. */
836 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
838 SilcProtocol protocol = (SilcProtocol)context;
839 SilcServerConnAuthInternalContext *ctx =
840 (SilcServerConnAuthInternalContext *)protocol->context;
841 SilcServer server = (SilcServer)ctx->server;
842 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
843 SilcSocketConnection sock = ctx->sock;
844 SilcServerEntry id_entry;
846 SilcServerHBContext hb_context;
847 unsigned char *id_string;
849 SilcIDListData idata;
850 SilcServerConfigConnParams *param;
852 SILC_LOG_DEBUG(("Start"));
854 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
855 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
856 /* Error occured during protocol */
857 silc_free(ctx->dest_id);
858 silc_server_disconnect_remote(server, sock, "Server closed connection: "
859 "Authentication failed");
863 /* Add a task to the queue. This task receives new connections to the
864 server. This task remains on the queue until the end of the program. */
865 if (!server->listenning && !sconn->backup) {
866 silc_schedule_task_add(server->schedule, server->sock,
867 silc_server_accept_new_connection,
868 (void *)server, 0, 0,
870 SILC_TASK_PRI_NORMAL);
871 server->listenning = TRUE;
874 /* Send NEW_SERVER packet to the router. We will become registered
875 to the SILC network after sending this packet. */
876 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
877 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
878 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
879 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
880 silc_buffer_format(packet,
881 SILC_STR_UI_SHORT(id_len),
882 SILC_STR_UI_XNSTRING(id_string, id_len),
883 SILC_STR_UI_SHORT(strlen(server->server_name)),
884 SILC_STR_UI_XNSTRING(server->server_name,
885 strlen(server->server_name)),
888 /* Send the packet */
889 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
890 packet->data, packet->len, TRUE);
891 silc_buffer_free(packet);
892 silc_free(id_string);
894 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
896 /* Check that we do not have this ID already */
897 id_entry = silc_idlist_find_server_by_id(server->local_list,
898 ctx->dest_id, TRUE, NULL);
900 silc_idcache_del_by_context(server->local_list->servers, id_entry);
902 id_entry = silc_idlist_find_server_by_id(server->global_list,
903 ctx->dest_id, TRUE, NULL);
905 silc_idcache_del_by_context(server->global_list->servers, id_entry);
908 SILC_LOG_DEBUG(("New server id(%s)",
909 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
911 /* Add the connected router to global server list */
912 id_entry = silc_idlist_add_server(server->global_list,
913 strdup(sock->hostname),
914 SILC_ROUTER, ctx->dest_id, NULL, sock);
916 silc_free(ctx->dest_id);
917 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
918 silc_server_disconnect_remote(server, sock, "Server closed connection: "
919 "Authentication failed");
923 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
924 silc_free(sock->user_data);
925 sock->user_data = (void *)id_entry;
926 sock->type = SILC_SOCKET_TYPE_ROUTER;
927 idata = (SilcIDListData)sock->user_data;
928 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
930 param = (sconn->param ? sconn->param : &server->config->param);
932 /* Perform keepalive. The `hb_context' will be freed automatically
933 when finally calling the silc_socket_free function. */
934 hb_context = silc_calloc(1, sizeof(*hb_context));
935 hb_context->server = server;
936 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
937 silc_server_perform_heartbeat,
940 /* Register re-key timeout */
941 idata->rekey->timeout = param->key_exchange_rekey;
942 idata->rekey->context = (void *)server;
943 silc_schedule_task_add(server->schedule, sock->sock,
944 silc_server_rekey_callback,
945 (void *)sock, idata->rekey->timeout, 0,
946 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
948 if (!sconn->backup) {
949 /* Mark this router our primary router if we're still standalone */
950 if (server->standalone) {
951 server->id_entry->router = id_entry;
952 server->router = id_entry;
953 server->standalone = FALSE;
955 /* If we are router then announce our possible servers. */
956 if (server->server_type == SILC_ROUTER)
957 silc_server_announce_servers(server, FALSE, 0,
958 server->router->connection);
960 /* Announce our clients and channels to the router */
961 silc_server_announce_clients(server, 0, server->router->connection);
962 silc_server_announce_channels(server, 0, server->router->connection);
965 /* Add this server to be our backup router */
966 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
967 sconn->backup_replace_port, FALSE);
970 sock->protocol = NULL;
972 /* Call the completion callback to indicate that we've connected to
975 (*sconn->callback)(server, id_entry, sconn->callback_context);
978 /* Free the temporary connection data context */
980 silc_free(sconn->remote_host);
981 silc_free(sconn->backup_replace_ip);
984 if (sconn == server->router_conn)
985 server->router_conn = NULL;
987 /* Free the protocol object */
988 if (sock->protocol == protocol)
989 sock->protocol = NULL;
990 silc_protocol_free(protocol);
992 silc_packet_context_free(ctx->packet);
994 silc_ske_free(ctx->ske);
995 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
996 silc_free(ctx->auth_data);
1000 /* Host lookup callbcak that is called after the incoming connection's
1001 IP and FQDN lookup is performed. This will actually check the acceptance
1002 of the incoming connection and will register the key exchange protocol
1003 for this connection. */
1006 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1009 SilcServer server = (SilcServer)context;
1010 SilcServerKEInternalContext *proto_ctx;
1011 SilcServerConfigClient *cconfig = NULL;
1012 SilcServerConfigServer *sconfig = NULL;
1013 SilcServerConfigRouter *rconfig = NULL;
1014 SilcServerConfigDeny *deny;
1017 SILC_LOG_DEBUG(("Start"));
1019 /* Check whether we could resolve both IP and FQDN. */
1020 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1021 server->config->require_reverse_lookup)) {
1022 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1023 sock->hostname ? sock->hostname :
1024 sock->ip ? sock->ip : ""));
1025 server->stat.conn_failures++;
1026 silc_server_disconnect_remote(server, sock,
1027 "Server closed connection: Unknown host");
1031 /* Register the connection for network input and output. This sets
1032 that scheduler will listen for incoming packets for this connection
1033 and sets that outgoing packets may be sent to this connection as well.
1034 However, this doesn't set the scheduler for outgoing traffic, it
1035 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1036 later when outgoing data is available. */
1037 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1039 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1042 port = server->sockets[server->sock]->port; /* Listenning port */
1044 /* Check whether this connection is denied to connect to us. */
1045 deny = silc_server_config_find_denied(server, sock->ip);
1047 deny = silc_server_config_find_denied(server, sock->hostname);
1049 /* The connection is denied */
1050 SILC_LOG_INFO(("Connection %s (%s) is denied",
1051 sock->hostname, sock->ip));
1052 silc_server_disconnect_remote(server, sock, deny->reason ?
1054 "Server closed connection: "
1055 "Connection refused");
1056 server->stat.conn_failures++;
1060 /* Check whether we have configred this sort of connection at all. We
1061 have to check all configurations since we don't know what type of
1062 connection this is. */
1063 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1064 cconfig = silc_server_config_find_client(server, sock->hostname);
1065 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1066 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1067 if (server->server_type == SILC_ROUTER) {
1068 if (!(rconfig = silc_server_config_find_router_conn(server,
1070 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1073 if (!cconfig && !sconfig && !rconfig) {
1074 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1076 silc_server_disconnect_remote(server, sock,
1077 "Server closed connection: "
1078 "Connection refused");
1079 server->stat.conn_failures++;
1083 /* The connection is allowed */
1085 /* Allocate internal context for key exchange protocol. This is
1086 sent as context for the protocol. */
1087 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1088 proto_ctx->server = context;
1089 proto_ctx->sock = sock;
1090 proto_ctx->rng = server->rng;
1091 proto_ctx->responder = TRUE;
1092 proto_ctx->cconfig = cconfig;
1093 proto_ctx->sconfig = sconfig;
1094 proto_ctx->rconfig = rconfig;
1096 /* Take flags for key exchange. Since we do not know what type of connection
1097 this is, we go through all found configuratios and use the global ones
1098 as well. This will result always into strictest key exchange flags. */
1099 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1100 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1101 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1102 if (server->config->param.key_exchange_pfs)
1103 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1105 /* Prepare the connection for key exchange protocol. We allocate the
1106 protocol but will not start it yet. The connector will be the
1107 initiator of the protocol thus we will wait for initiation from
1108 there before we start the protocol. */
1109 server->stat.auth_attempts++;
1110 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1111 &sock->protocol, proto_ctx,
1112 silc_server_accept_new_connection_second);
1114 /* Register a timeout task that will be executed if the connector
1115 will not start the key exchange protocol within specified timeout
1116 and the connection will be closed. */
1117 proto_ctx->timeout_task =
1118 silc_schedule_task_add(server->schedule, sock->sock,
1119 silc_server_timeout_remote,
1120 context, server->config->key_exchange_timeout, 0,
1125 /* Accepts new connections to the server. Accepting new connections are
1126 done in three parts to make it async. */
1128 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1130 SilcServer server = (SilcServer)context;
1131 SilcSocketConnection newsocket;
1134 SILC_LOG_DEBUG(("Accepting new connection"));
1136 server->stat.conn_attempts++;
1138 sock = silc_net_accept_connection(server->sock);
1140 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1141 server->stat.conn_failures++;
1145 /* Check for maximum allowed connections */
1146 if (sock > server->config->param.connections_max) {
1147 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1148 server->stat.conn_failures++;
1152 /* Set socket options */
1153 silc_net_set_socket_nonblock(sock);
1154 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1156 /* We don't create a ID yet, since we don't know what type of connection
1157 this is yet. But, we do add the connection to the socket table. */
1158 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1159 server->sockets[sock] = newsocket;
1161 /* Perform asynchronous host lookup. This will lookup the IP and the
1162 FQDN of the remote connection. After the lookup is done the connection
1163 is accepted further. */
1164 silc_socket_host_lookup(newsocket, TRUE,
1165 silc_server_accept_new_connection_lookup, context,
1169 /* Second part of accepting new connection. Key exchange protocol has been
1170 performed and now it is time to do little connection authentication
1171 protocol to figure out whether this connection is client or server
1172 and whether it has right to access this server (especially server
1173 connections needs to be authenticated). */
1175 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1177 SilcProtocol protocol = (SilcProtocol)context;
1178 SilcServerKEInternalContext *ctx =
1179 (SilcServerKEInternalContext *)protocol->context;
1180 SilcServer server = (SilcServer)ctx->server;
1181 SilcSocketConnection sock = ctx->sock;
1182 SilcServerConnAuthInternalContext *proto_ctx;
1184 SILC_LOG_DEBUG(("Start"));
1186 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1187 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1188 /* Error occured during protocol */
1189 silc_protocol_free(protocol);
1190 sock->protocol = NULL;
1191 silc_ske_free_key_material(ctx->keymat);
1193 silc_packet_context_free(ctx->packet);
1195 silc_ske_free(ctx->ske);
1196 silc_free(ctx->dest_id);
1198 silc_schedule_task_del_by_callback(server->schedule,
1199 silc_server_failure_callback);
1200 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1201 "Key exchange failed");
1202 server->stat.auth_failures++;
1206 /* We now have the key material as the result of the key exchange
1207 protocol. Take the key material into use. Free the raw key material
1208 as soon as we've set them into use. */
1209 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1210 ctx->sock, ctx->keymat,
1211 ctx->ske->prop->cipher,
1212 ctx->ske->prop->pkcs,
1213 ctx->ske->prop->hash,
1214 ctx->ske->prop->hmac,
1215 ctx->ske->prop->group,
1217 silc_protocol_free(protocol);
1218 sock->protocol = NULL;
1219 silc_ske_free_key_material(ctx->keymat);
1221 silc_packet_context_free(ctx->packet);
1223 silc_ske_free(ctx->ske);
1224 silc_free(ctx->dest_id);
1226 silc_schedule_task_del_by_callback(server->schedule,
1227 silc_server_failure_callback);
1228 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1229 "Key exchange failed");
1230 server->stat.auth_failures++;
1233 silc_ske_free_key_material(ctx->keymat);
1235 /* Allocate internal context for the authentication protocol. This
1236 is sent as context for the protocol. */
1237 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1238 proto_ctx->server = (void *)server;
1239 proto_ctx->sock = sock;
1240 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1241 proto_ctx->responder = TRUE;
1242 proto_ctx->dest_id_type = ctx->dest_id_type;
1243 proto_ctx->dest_id = ctx->dest_id;
1244 proto_ctx->cconfig = ctx->cconfig;
1245 proto_ctx->sconfig = ctx->sconfig;
1246 proto_ctx->rconfig = ctx->rconfig;
1248 /* Free old protocol as it is finished now */
1249 silc_protocol_free(protocol);
1251 silc_packet_context_free(ctx->packet);
1253 sock->protocol = NULL;
1255 /* Allocate the authentication protocol. This is allocated here
1256 but we won't start it yet. We will be receiving party of this
1257 protocol thus we will wait that connecting party will make
1258 their first move. */
1259 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1260 &sock->protocol, proto_ctx,
1261 silc_server_accept_new_connection_final);
1263 /* Register timeout task. If the protocol is not executed inside
1264 this timelimit the connection will be terminated. */
1265 proto_ctx->timeout_task =
1266 silc_schedule_task_add(server->schedule, sock->sock,
1267 silc_server_timeout_remote,
1269 server->config->conn_auth_timeout, 0,
1274 /* Final part of accepting new connection. The connection has now
1275 been authenticated and keys has been exchanged. We also know whether
1276 this is client or server connection. */
1278 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1280 SilcProtocol protocol = (SilcProtocol)context;
1281 SilcServerConnAuthInternalContext *ctx =
1282 (SilcServerConnAuthInternalContext *)protocol->context;
1283 SilcServer server = (SilcServer)ctx->server;
1284 SilcSocketConnection sock = ctx->sock;
1285 SilcServerHBContext hb_context;
1286 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1288 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1289 SilcUInt32 num_sockets;
1291 SILC_LOG_DEBUG(("Start"));
1293 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1294 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1295 /* Error occured during protocol */
1296 silc_protocol_free(protocol);
1297 sock->protocol = NULL;
1299 silc_packet_context_free(ctx->packet);
1301 silc_ske_free(ctx->ske);
1302 silc_free(ctx->dest_id);
1304 silc_schedule_task_del_by_callback(server->schedule,
1305 silc_server_failure_callback);
1306 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1307 "Authentication failed");
1308 server->stat.auth_failures++;
1312 entry->data.last_receive = time(NULL);
1314 num_sockets = silc_server_num_sockets_by_ip(server, sock->ip);
1316 switch (ctx->conn_type) {
1317 case SILC_SOCKET_TYPE_CLIENT:
1319 SilcClientEntry client;
1320 SilcServerConfigClient *conn = ctx->cconfig;
1321 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1323 /* Check for maximum connections limit */
1325 if (conn->param->connections_max &&
1326 server->stat.my_clients >= conn->param->connections_max) {
1327 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1328 sock->hostname, sock->ip));
1329 silc_server_disconnect_remote(server, sock,
1330 "Server closed connection: "
1331 "Server is full, try again later");
1332 server->stat.auth_failures++;
1336 max_per_host = conn->param->connections_max_per_host;
1339 if (num_sockets > max_per_host) {
1340 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1341 sock->hostname, sock->ip));
1342 silc_server_disconnect_remote(server, sock,
1343 "Server closed connection: "
1344 "Too many connections from your host");
1345 server->stat.auth_failures++;
1349 SILC_LOG_DEBUG(("Remote host is client"));
1350 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1353 /* Add the client to the client ID cache. The nickname and Client ID
1354 and other information is created after we have received NEW_CLIENT
1355 packet from client. */
1356 client = silc_idlist_add_client(server->local_list,
1357 NULL, NULL, NULL, NULL, NULL, sock, 0);
1359 SILC_LOG_ERROR(("Could not add new client to cache"));
1360 silc_free(sock->user_data);
1361 silc_server_disconnect_remote(server, sock,
1362 "Server closed connection: "
1363 "Authentication failed");
1364 server->stat.auth_failures++;
1369 server->stat.my_clients++;
1370 server->stat.clients++;
1371 if (server->server_type == SILC_ROUTER)
1372 server->stat.cell_clients++;
1374 /* Get connection parameters */
1376 if (conn->param->keepalive_secs)
1377 hearbeat_timeout = conn->param->keepalive_secs;
1380 id_entry = (void *)client;
1383 case SILC_SOCKET_TYPE_SERVER:
1384 case SILC_SOCKET_TYPE_ROUTER:
1386 SilcServerEntry new_server;
1387 bool initiator = FALSE;
1388 bool backup_local = FALSE;
1389 bool backup_router = FALSE;
1390 char *backup_replace_ip = NULL;
1391 SilcUInt16 backup_replace_port = 0;
1392 SilcServerConfigServer *sconn = ctx->sconfig;
1393 SilcServerConfigRouter *rconn = ctx->rconfig;
1394 SilcUInt32 max_per_host = server->config->param.connections_max_per_host;
1396 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && rconn) {
1398 /* Check for maximum connections limit */
1399 if (rconn->param->connections_max &&
1400 server->stat.my_routers >= rconn->param->connections_max) {
1401 silc_server_disconnect_remote(server, sock,
1402 "Server closed connection: "
1403 "Server is full, try again later");
1404 server->stat.auth_failures++;
1407 max_per_host = rconn->param->connections_max_per_host;
1409 if (rconn->param->keepalive_secs)
1410 hearbeat_timeout = rconn->param->keepalive_secs;
1413 initiator = rconn->initiator;
1414 backup_local = rconn->backup_local;
1415 backup_router = rconn->backup_router;
1416 backup_replace_ip = rconn->backup_replace_ip;
1417 backup_replace_port = rconn->backup_replace_port;
1420 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER && sconn) {
1422 /* Check for maximum connections limit */
1423 if (sconn->param->connections_max &&
1424 server->stat.my_servers >= sconn->param->connections_max) {
1425 SILC_LOG_INFO(("Server is full, closing %s (%s) connection",
1426 sock->hostname, sock->ip));
1427 silc_server_disconnect_remote(server, sock,
1428 "Server closed connection: "
1429 "Server is full, try again later");
1430 server->stat.auth_failures++;
1433 max_per_host = sconn->param->connections_max_per_host;
1435 if (sconn->param->keepalive_secs)
1436 hearbeat_timeout = sconn->param->keepalive_secs;
1439 backup_router = sconn->backup_router;
1442 if (num_sockets > max_per_host) {
1443 SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
1444 sock->hostname, sock->ip));
1445 silc_server_disconnect_remote(server, sock,
1446 "Server closed connection: "
1447 "Too many connections from your host");
1448 server->stat.auth_failures++;
1452 SILC_LOG_DEBUG(("Remote host is %s",
1453 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1454 "server" : (backup_router ?
1455 "backup router" : "router")));
1456 SILC_LOG_INFO(("Connection s (%s) is %s", sock->hostname,
1457 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1458 "server" : (backup_router ?
1459 "backup router" : "router")));
1461 /* Add the server into server cache. The server name and Server ID
1462 is updated after we have received NEW_SERVER packet from the
1463 server. We mark ourselves as router for this server if we really
1466 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1467 server->local_list : (backup_router ?
1468 server->local_list :
1469 server->global_list)),
1471 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1472 SILC_SERVER : SILC_ROUTER),
1474 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1475 server->id_entry : (backup_router ?
1476 server->id_entry : NULL)),
1479 SILC_LOG_ERROR(("Could not add new server to cache"));
1480 silc_free(sock->user_data);
1481 silc_server_disconnect_remote(server, sock,
1482 "Server closed connection: "
1483 "Authentication failed");
1484 server->stat.auth_failures++;
1489 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1490 server->stat.my_servers++;
1492 server->stat.my_routers++;
1493 server->stat.servers++;
1495 id_entry = (void *)new_server;
1497 /* If the incoming connection is router and marked as backup router
1498 then add it to be one of our backups */
1499 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1500 silc_server_backup_add(server, new_server, backup_replace_ip,
1501 backup_replace_port, backup_local);
1503 /* Change it back to SERVER type since that's what it really is. */
1505 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1507 new_server->server_type = SILC_BACKUP_ROUTER;
1510 /* Check whether this connection is to be our primary router connection
1511 if we do not already have the primary route. */
1512 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1513 if (silc_server_config_is_primary_route(server) && !initiator)
1516 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1517 server->standalone = FALSE;
1518 if (!server->id_entry->router) {
1519 server->id_entry->router = id_entry;
1520 server->router = id_entry;
1531 sock->type = ctx->conn_type;
1533 /* Add the common data structure to the ID entry. */
1534 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1536 /* Add to sockets internal pointer for fast referencing */
1537 silc_free(sock->user_data);
1538 sock->user_data = id_entry;
1540 /* Connection has been fully established now. Everything is ok. */
1541 SILC_LOG_DEBUG(("New connection authenticated"));
1543 /* Perform keepalive. The `hb_context' will be freed automatically
1544 when finally calling the silc_socket_free function. */
1545 hb_context = silc_calloc(1, sizeof(*hb_context));
1546 hb_context->server = server;
1547 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1548 silc_server_perform_heartbeat,
1552 silc_schedule_task_del_by_callback(server->schedule,
1553 silc_server_failure_callback);
1554 silc_protocol_free(protocol);
1556 silc_packet_context_free(ctx->packet);
1558 silc_ske_free(ctx->ske);
1559 silc_free(ctx->dest_id);
1561 sock->protocol = NULL;
1564 /* This function is used to read packets from network and send packets to
1565 network. This is usually a generic task. */
1567 SILC_TASK_CALLBACK(silc_server_packet_process)
1569 SilcServer server = (SilcServer)context;
1570 SilcSocketConnection sock = server->sockets[fd];
1571 SilcIDListData idata;
1572 SilcCipher cipher = NULL;
1573 SilcHmac hmac = NULL;
1574 SilcUInt32 sequence = 0;
1580 SILC_LOG_DEBUG(("Processing packet"));
1582 /* Packet sending */
1584 if (type == SILC_TASK_WRITE) {
1585 /* Do not send data to disconnected connection */
1586 if (SILC_IS_DISCONNECTED(sock))
1589 server->stat.packets_sent++;
1591 if (sock->outbuf->data - sock->outbuf->head)
1592 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1594 /* Send the packet */
1595 ret = silc_packet_send(sock, TRUE);
1597 /* If returned -2 could not write to connection now, will do
1603 SILC_LOG_ERROR(("Error sending packet to connection "
1604 "%s:%d [%s]", sock->hostname, sock->port,
1605 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1606 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1607 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1612 /* The packet has been sent and now it is time to set the connection
1613 back to only for input. When there is again some outgoing data
1614 available for this connection it will be set for output as well.
1615 This call clears the output setting and sets it only for input. */
1616 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1617 SILC_UNSET_OUTBUF_PENDING(sock);
1619 silc_buffer_clear(sock->outbuf);
1623 /* Packet receiving */
1625 /* Read some data from connection */
1626 ret = silc_packet_receive(sock);
1630 SILC_LOG_ERROR(("Error receiving packet from connection "
1631 "%s:%d [%s] %s", sock->hostname, sock->port,
1632 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1633 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1634 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1635 "Router"), strerror(errno)));
1641 SILC_LOG_DEBUG(("Read EOF"));
1643 /* If connection is disconnecting already we will finally
1644 close the connection */
1645 if (SILC_IS_DISCONNECTING(sock)) {
1646 if (sock->user_data)
1647 silc_server_free_sock_user_data(server, sock, NULL);
1648 silc_server_close_connection(server, sock);
1652 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1653 SILC_SET_DISCONNECTING(sock);
1655 if (sock->user_data) {
1657 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1658 silc_server_free_sock_user_data(server, sock, tmp);
1660 silc_server_free_sock_user_data(server, sock, NULL);
1661 } else if (server->router_conn && server->router_conn->sock == sock &&
1662 !server->router && server->standalone)
1663 silc_schedule_task_add(server->schedule, 0,
1664 silc_server_connect_to_router,
1667 SILC_TASK_PRI_NORMAL);
1669 silc_server_close_connection(server, sock);
1673 /* If connection is disconnecting or disconnected we will ignore
1675 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1676 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1680 server->stat.packets_received++;
1682 /* Get keys and stuff from ID entry */
1683 idata = (SilcIDListData)sock->user_data;
1685 cipher = idata->receive_key;
1686 hmac = idata->hmac_receive;
1687 sequence = idata->psn_receive;
1690 /* Process the packet. This will call the parser that will then
1691 decrypt and parse the packet. */
1692 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1693 TRUE : FALSE, cipher, hmac, sequence,
1694 silc_server_packet_parse, server);
1696 /* If this socket connection is not authenticated yet and the packet
1697 processing failed we will drop the connection since it can be
1698 a malicious flooder. */
1699 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1700 (!sock->protocol || sock->protocol->protocol->type ==
1701 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1702 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1703 SILC_SET_DISCONNECTING(sock);
1705 if (sock->user_data)
1706 silc_server_free_sock_user_data(server, sock, NULL);
1707 silc_server_close_connection(server, sock);
1711 /* Parses whole packet, received earlier. */
1713 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1715 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1716 SilcServer server = (SilcServer)parse_ctx->context;
1717 SilcSocketConnection sock = parse_ctx->sock;
1718 SilcPacketContext *packet = parse_ctx->packet;
1719 SilcIDListData idata = (SilcIDListData)sock->user_data;
1722 SILC_LOG_DEBUG(("Start"));
1724 /* Parse the packet */
1725 if (parse_ctx->normal)
1726 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1728 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1730 /* If entry is disabled ignore what we got. */
1731 if (ret != SILC_PACKET_RESUME_ROUTER &&
1732 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1733 SILC_LOG_DEBUG(("Connection is disabled"));
1737 if (ret == SILC_PACKET_NONE)
1740 /* Check that the the current client ID is same as in the client's packet. */
1741 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1742 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1743 if (client && client->id) {
1744 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1745 packet->src_id_type);
1746 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1754 if (server->server_type == SILC_ROUTER) {
1755 /* Route the packet if it is not destined to us. Other ID types but
1756 server are handled separately after processing them. */
1757 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1758 packet->dst_id_type == SILC_ID_SERVER &&
1759 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1760 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1762 /* Route the packet to fastest route for the destination ID */
1763 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1764 packet->dst_id_type);
1767 silc_server_packet_route(server,
1768 silc_server_route_get(server, id,
1769 packet->dst_id_type),
1776 /* Parse the incoming packet type */
1777 silc_server_packet_parse_type(server, sock, packet);
1779 if (server->server_type == SILC_ROUTER) {
1780 /* Broadcast packet if it is marked as broadcast packet and it is
1781 originated from router and we are router. */
1782 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1783 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1784 !server->standalone) {
1785 /* Broadcast to our primary route */
1786 silc_server_packet_broadcast(server, server->router->connection, packet);
1788 /* If we have backup routers then we need to feed all broadcast
1789 data to those servers. */
1790 silc_server_backup_broadcast(server, sock, packet);
1795 silc_packet_context_free(packet);
1796 silc_free(parse_ctx);
1799 /* Parser callback called by silc_packet_receive_process. This merely
1800 registers timeout that will handle the actual parsing when appropriate. */
1802 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1805 SilcServer server = (SilcServer)context;
1806 SilcSocketConnection sock = parser_context->sock;
1807 SilcIDListData idata = (SilcIDListData)sock->user_data;
1810 idata->psn_receive = parser_context->packet->sequence + 1;
1812 /* If protocol for this connection is key exchange or rekey then we'll
1813 process all packets synchronously, since there might be packets in
1814 queue that we are not able to decrypt without first processing the
1815 packets before them. */
1816 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1817 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1818 (sock->protocol && sock->protocol->protocol &&
1819 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1820 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1821 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1824 /* Reprocess data since we'll return FALSE here. This is because
1825 the idata->receive_key might have become valid in the last packet
1826 and we want to call this processor with valid cipher. */
1828 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1829 TRUE : FALSE, idata->receive_key,
1830 idata->hmac_receive, idata->psn_receive,
1831 silc_server_packet_parse, server);
1833 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1834 TRUE : FALSE, NULL, NULL, 0,
1835 silc_server_packet_parse, server);
1839 switch (sock->type) {
1840 case SILC_SOCKET_TYPE_UNKNOWN:
1841 case SILC_SOCKET_TYPE_CLIENT:
1842 /* Parse the packet with timeout */
1843 silc_schedule_task_add(server->schedule, sock->sock,
1844 silc_server_packet_parse_real,
1845 (void *)parser_context, 0, 100000,
1847 SILC_TASK_PRI_NORMAL);
1849 case SILC_SOCKET_TYPE_SERVER:
1850 case SILC_SOCKET_TYPE_ROUTER:
1851 /* Packets from servers are parsed immediately */
1852 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1862 /* Parses the packet type and calls what ever routines the packet type
1863 requires. This is done for all incoming packets. */
1865 void silc_server_packet_parse_type(SilcServer server,
1866 SilcSocketConnection sock,
1867 SilcPacketContext *packet)
1869 SilcPacketType type = packet->type;
1870 SilcIDListData idata = (SilcIDListData)sock->user_data;
1872 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1874 /* Parse the packet type */
1876 case SILC_PACKET_DISCONNECT:
1877 SILC_LOG_DEBUG(("Disconnect packet"));
1878 if (packet->flags & SILC_PACKET_FLAG_LIST)
1882 case SILC_PACKET_SUCCESS:
1884 * Success received for something. For now we can have only
1885 * one protocol for connection executing at once hence this
1886 * success message is for whatever protocol is executing currently.
1888 SILC_LOG_DEBUG(("Success packet"));
1889 if (packet->flags & SILC_PACKET_FLAG_LIST)
1892 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1895 case SILC_PACKET_FAILURE:
1897 * Failure received for something. For now we can have only
1898 * one protocol for connection executing at once hence this
1899 * failure message is for whatever protocol is executing currently.
1901 SILC_LOG_DEBUG(("Failure packet"));
1902 if (packet->flags & SILC_PACKET_FLAG_LIST)
1904 if (sock->protocol) {
1905 SilcServerFailureContext f;
1906 f = silc_calloc(1, sizeof(*f));
1910 /* We will wait 5 seconds to process this failure packet */
1911 silc_schedule_task_add(server->schedule, sock->sock,
1912 silc_server_failure_callback, (void *)f, 5, 0,
1913 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1917 case SILC_PACKET_REJECT:
1918 SILC_LOG_DEBUG(("Reject packet"));
1919 if (packet->flags & SILC_PACKET_FLAG_LIST)
1924 case SILC_PACKET_NOTIFY:
1926 * Received notify packet. Server can receive notify packets from
1927 * router. Server then relays the notify messages to clients if needed.
1929 SILC_LOG_DEBUG(("Notify packet"));
1930 if (packet->flags & SILC_PACKET_FLAG_LIST)
1931 silc_server_notify_list(server, sock, packet);
1933 silc_server_notify(server, sock, packet);
1939 case SILC_PACKET_CHANNEL_MESSAGE:
1941 * Received channel message. Channel messages are special packets
1942 * (although probably most common ones) thus they are handled
1945 SILC_LOG_DEBUG(("Channel Message packet"));
1946 if (packet->flags & SILC_PACKET_FLAG_LIST)
1948 idata->last_receive = time(NULL);
1949 silc_server_channel_message(server, sock, packet);
1952 case SILC_PACKET_CHANNEL_KEY:
1954 * Received key for channel. As channels are created by the router
1955 * the keys are as well. We will distribute the key to all of our
1956 * locally connected clients on the particular channel. Router
1957 * never receives this channel and thus is ignored.
1959 SILC_LOG_DEBUG(("Channel Key packet"));
1960 if (packet->flags & SILC_PACKET_FLAG_LIST)
1962 silc_server_channel_key(server, sock, packet);
1968 case SILC_PACKET_COMMAND:
1970 * Recived command. Processes the command request and allocates the
1971 * command context and calls the command.
1973 SILC_LOG_DEBUG(("Command packet"));
1974 if (packet->flags & SILC_PACKET_FLAG_LIST)
1976 silc_server_command_process(server, sock, packet);
1979 case SILC_PACKET_COMMAND_REPLY:
1981 * Received command reply packet. Received command reply to command. It
1982 * may be reply to command sent by us or reply to command sent by client
1983 * that we've routed further.
1985 SILC_LOG_DEBUG(("Command Reply packet"));
1986 if (packet->flags & SILC_PACKET_FLAG_LIST)
1988 silc_server_command_reply(server, sock, packet);
1992 * Private Message packets
1994 case SILC_PACKET_PRIVATE_MESSAGE:
1996 * Received private message packet. The packet is coming from either
1999 SILC_LOG_DEBUG(("Private Message packet"));
2000 if (packet->flags & SILC_PACKET_FLAG_LIST)
2002 idata->last_receive = time(NULL);
2003 silc_server_private_message(server, sock, packet);
2006 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2008 * Private message key packet.
2010 if (packet->flags & SILC_PACKET_FLAG_LIST)
2012 silc_server_private_message_key(server, sock, packet);
2016 * Key Exchange protocol packets
2018 case SILC_PACKET_KEY_EXCHANGE:
2019 SILC_LOG_DEBUG(("KE packet"));
2020 if (packet->flags & SILC_PACKET_FLAG_LIST)
2023 if (sock->protocol && sock->protocol->protocol &&
2024 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2026 SilcServerKEInternalContext *proto_ctx =
2027 (SilcServerKEInternalContext *)sock->protocol->context;
2029 proto_ctx->packet = silc_packet_context_dup(packet);
2031 /* Let the protocol handle the packet */
2032 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2034 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2035 "protocol active, packet dropped."));
2039 case SILC_PACKET_KEY_EXCHANGE_1:
2040 SILC_LOG_DEBUG(("KE 1 packet"));
2041 if (packet->flags & SILC_PACKET_FLAG_LIST)
2044 if (sock->protocol && sock->protocol->protocol &&
2045 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2046 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2048 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2049 SilcServerRekeyInternalContext *proto_ctx =
2050 (SilcServerRekeyInternalContext *)sock->protocol->context;
2052 if (proto_ctx->packet)
2053 silc_packet_context_free(proto_ctx->packet);
2055 proto_ctx->packet = silc_packet_context_dup(packet);
2057 /* Let the protocol handle the packet */
2058 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2060 SilcServerKEInternalContext *proto_ctx =
2061 (SilcServerKEInternalContext *)sock->protocol->context;
2063 if (proto_ctx->packet)
2064 silc_packet_context_free(proto_ctx->packet);
2066 proto_ctx->packet = silc_packet_context_dup(packet);
2067 proto_ctx->dest_id_type = packet->src_id_type;
2068 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2069 packet->src_id_type);
2070 if (!proto_ctx->dest_id)
2073 /* Let the protocol handle the packet */
2074 silc_protocol_execute(sock->protocol, server->schedule,
2078 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2079 "protocol active, packet dropped."));
2083 case SILC_PACKET_KEY_EXCHANGE_2:
2084 SILC_LOG_DEBUG(("KE 2 packet"));
2085 if (packet->flags & SILC_PACKET_FLAG_LIST)
2088 if (sock->protocol && sock->protocol->protocol &&
2089 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2090 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2092 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2093 SilcServerRekeyInternalContext *proto_ctx =
2094 (SilcServerRekeyInternalContext *)sock->protocol->context;
2096 if (proto_ctx->packet)
2097 silc_packet_context_free(proto_ctx->packet);
2099 proto_ctx->packet = silc_packet_context_dup(packet);
2101 /* Let the protocol handle the packet */
2102 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2104 SilcServerKEInternalContext *proto_ctx =
2105 (SilcServerKEInternalContext *)sock->protocol->context;
2107 if (proto_ctx->packet)
2108 silc_packet_context_free(proto_ctx->packet);
2110 proto_ctx->packet = silc_packet_context_dup(packet);
2111 proto_ctx->dest_id_type = packet->src_id_type;
2112 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2113 packet->src_id_type);
2114 if (!proto_ctx->dest_id)
2117 /* Let the protocol handle the packet */
2118 silc_protocol_execute(sock->protocol, server->schedule,
2122 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2123 "protocol active, packet dropped."));
2127 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2129 * Connection authentication request packet. When we receive this packet
2130 * we will send to the other end information about our mandatory
2131 * authentication method for the connection. This packet maybe received
2134 SILC_LOG_DEBUG(("Connection authentication request packet"));
2135 if (packet->flags & SILC_PACKET_FLAG_LIST)
2137 silc_server_connection_auth_request(server, sock, packet);
2141 * Connection Authentication protocol packets
2143 case SILC_PACKET_CONNECTION_AUTH:
2144 /* Start of the authentication protocol. We receive here the
2145 authentication data and will verify it. */
2146 SILC_LOG_DEBUG(("Connection auth packet"));
2147 if (packet->flags & SILC_PACKET_FLAG_LIST)
2150 if (sock->protocol && sock->protocol->protocol->type
2151 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2153 SilcServerConnAuthInternalContext *proto_ctx =
2154 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2156 proto_ctx->packet = silc_packet_context_dup(packet);
2158 /* Let the protocol handle the packet */
2159 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2161 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2162 "protocol active, packet dropped."));
2166 case SILC_PACKET_NEW_ID:
2168 * Received New ID packet. This includes some new ID that has been
2169 * created. It may be for client, server or channel. This is the way
2170 * to distribute information about new registered entities in the
2173 SILC_LOG_DEBUG(("New ID packet"));
2174 if (packet->flags & SILC_PACKET_FLAG_LIST)
2175 silc_server_new_id_list(server, sock, packet);
2177 silc_server_new_id(server, sock, packet);
2180 case SILC_PACKET_NEW_CLIENT:
2182 * Received new client packet. This includes client information that
2183 * we will use to create initial client ID. After creating new
2184 * ID we will send it to the client.
2186 SILC_LOG_DEBUG(("New Client packet"));
2187 if (packet->flags & SILC_PACKET_FLAG_LIST)
2189 silc_server_new_client(server, sock, packet);
2192 case SILC_PACKET_NEW_SERVER:
2194 * Received new server packet. This includes Server ID and some other
2195 * information that we may save. This is received after server has
2198 SILC_LOG_DEBUG(("New Server packet"));
2199 if (packet->flags & SILC_PACKET_FLAG_LIST)
2201 silc_server_new_server(server, sock, packet);
2204 case SILC_PACKET_NEW_CHANNEL:
2206 * Received new channel packet. Information about new channel in the
2207 * network are distributed using this packet.
2209 SILC_LOG_DEBUG(("New Channel packet"));
2210 if (packet->flags & SILC_PACKET_FLAG_LIST)
2211 silc_server_new_channel_list(server, sock, packet);
2213 silc_server_new_channel(server, sock, packet);
2216 case SILC_PACKET_HEARTBEAT:
2218 * Received heartbeat.
2220 SILC_LOG_DEBUG(("Heartbeat packet"));
2221 if (packet->flags & SILC_PACKET_FLAG_LIST)
2225 case SILC_PACKET_KEY_AGREEMENT:
2227 * Received heartbeat.
2229 SILC_LOG_DEBUG(("Key agreement packet"));
2230 if (packet->flags & SILC_PACKET_FLAG_LIST)
2232 silc_server_key_agreement(server, sock, packet);
2235 case SILC_PACKET_REKEY:
2237 * Received re-key packet. The sender wants to regenerate the session
2240 SILC_LOG_DEBUG(("Re-key packet"));
2241 if (packet->flags & SILC_PACKET_FLAG_LIST)
2243 silc_server_rekey(server, sock, packet);
2246 case SILC_PACKET_REKEY_DONE:
2248 * The re-key is done.
2250 SILC_LOG_DEBUG(("Re-key done packet"));
2251 if (packet->flags & SILC_PACKET_FLAG_LIST)
2254 if (sock->protocol && sock->protocol->protocol &&
2255 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2257 SilcServerRekeyInternalContext *proto_ctx =
2258 (SilcServerRekeyInternalContext *)sock->protocol->context;
2260 if (proto_ctx->packet)
2261 silc_packet_context_free(proto_ctx->packet);
2263 proto_ctx->packet = silc_packet_context_dup(packet);
2265 /* Let the protocol handle the packet */
2266 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2268 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2269 "protocol active, packet dropped."));
2273 case SILC_PACKET_FTP:
2275 SILC_LOG_DEBUG(("FTP packet"));
2276 if (packet->flags & SILC_PACKET_FLAG_LIST)
2278 silc_server_ftp(server, sock, packet);
2281 case SILC_PACKET_RESUME_ROUTER:
2282 /* Resume router packet received. This packet is received for backup
2283 router resuming protocol. */
2284 SILC_LOG_DEBUG(("Resume router packet"));
2285 if (packet->flags & SILC_PACKET_FLAG_LIST)
2287 silc_server_backup_resume_router(server, sock, packet);
2291 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2297 /* Creates connection to a remote router. */
2299 void silc_server_create_connection(SilcServer server,
2300 const char *remote_host, SilcUInt32 port)
2302 SilcServerConnection sconn;
2304 /* Allocate connection object for hold connection specific stuff. */
2305 sconn = silc_calloc(1, sizeof(*sconn));
2306 sconn->server = server;
2307 sconn->remote_host = strdup(remote_host);
2308 sconn->remote_port = port;
2309 sconn->no_reconnect = TRUE;
2310 sconn->param = &server->config->param;
2312 silc_schedule_task_add(server->schedule, 0,
2313 silc_server_connect_router,
2314 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2315 SILC_TASK_PRI_NORMAL);
2318 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2320 silc_socket_free((SilcSocketConnection)context);
2323 /* Closes connection to socket connection */
2325 void silc_server_close_connection(SilcServer server,
2326 SilcSocketConnection sock)
2328 if (!server->sockets[sock->sock])
2331 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2333 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2334 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2335 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2338 /* We won't listen for this connection anymore */
2339 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2341 /* Unregister all tasks */
2342 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2344 /* Close the actual connection */
2345 silc_net_close_connection(sock->sock);
2346 server->sockets[sock->sock] = NULL;
2348 /* If sock->user_data is NULL then we'll check for active protocols
2349 here since the silc_server_free_sock_user_data has not been called
2350 for this connection. */
2351 if (!sock->user_data) {
2352 /* If any protocol is active cancel its execution. It will call
2353 the final callback which will finalize the disconnection. */
2354 if (sock->protocol) {
2355 silc_protocol_cancel(sock->protocol, server->schedule);
2356 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2357 silc_protocol_execute_final(sock->protocol, server->schedule);
2358 sock->protocol = NULL;
2363 silc_schedule_task_add(server->schedule, 0,
2364 silc_server_close_connection_final,
2365 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2366 SILC_TASK_PRI_NORMAL);
2369 /* Sends disconnect message to remote connection and disconnects the
2372 void silc_server_disconnect_remote(SilcServer server,
2373 SilcSocketConnection sock,
2374 const char *fmt, ...)
2377 unsigned char buf[4096];
2382 memset(buf, 0, sizeof(buf));
2384 vsprintf(buf, fmt, ap);
2387 SILC_LOG_DEBUG(("Disconnecting remote host"));
2389 /* Notify remote end that the conversation is over. The notify message
2390 is tried to be sent immediately. */
2391 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2392 buf, strlen(buf), TRUE);
2394 /* Mark the connection to be disconnected */
2395 SILC_SET_DISCONNECTED(sock);
2396 silc_server_close_connection(server, sock);
2401 SilcClientEntry client;
2402 } *FreeClientInternal;
2404 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2406 FreeClientInternal i = (FreeClientInternal)context;
2408 silc_idlist_del_data(i->client);
2409 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2413 /* Frees client data and notifies about client's signoff. */
2415 void silc_server_free_client_data(SilcServer server,
2416 SilcSocketConnection sock,
2417 SilcClientEntry client,
2419 const char *signoff)
2421 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2423 /* If there is pending outgoing data for the client then purge it
2424 to the network before removing the client entry. */
2425 silc_server_packet_queue_purge(server, sock);
2430 /* Send SIGNOFF notify to routers. */
2431 if (notify && !server->standalone && server->router)
2432 silc_server_send_notify_signoff(server, server->router->connection,
2433 server->server_type == SILC_SERVER ?
2434 FALSE : TRUE, client->id, signoff);
2436 /* Remove client from all channels */
2438 silc_server_remove_from_channels(server, NULL, client,
2439 TRUE, (char *)signoff, TRUE);
2441 silc_server_remove_from_channels(server, NULL, client,
2442 FALSE, NULL, FALSE);
2444 /* Update statistics */
2445 server->stat.my_clients--;
2446 server->stat.clients--;
2447 if (server->server_type == SILC_ROUTER)
2448 server->stat.cell_clients--;
2449 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2450 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2452 /* We will not delete the client entry right away. We will take it
2453 into history (for WHOWAS command) for 5 minutes */
2456 silc_schedule_task_add(server->schedule, 0,
2457 silc_server_free_client_data_timeout,
2459 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2460 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2461 client->router = NULL;
2462 client->connection = NULL;
2466 /* Frees user_data pointer from socket connection object. This also sends
2467 appropriate notify packets to the network to inform about leaving
2470 void silc_server_free_sock_user_data(SilcServer server,
2471 SilcSocketConnection sock,
2472 const char *signoff_message)
2474 SILC_LOG_DEBUG(("Start"));
2476 switch (sock->type) {
2477 case SILC_SOCKET_TYPE_CLIENT:
2479 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2480 silc_server_free_client_data(server, sock, user_data, TRUE,
2484 case SILC_SOCKET_TYPE_SERVER:
2485 case SILC_SOCKET_TYPE_ROUTER:
2487 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2488 SilcServerEntry backup_router = NULL;
2491 backup_router = silc_server_backup_get(server, user_data->id);
2493 /* If this was our primary router connection then we're lost to
2494 the outside world. */
2495 if (server->router == user_data) {
2496 /* Check whether we have a backup router connection */
2497 if (!backup_router || backup_router == user_data) {
2498 silc_schedule_task_add(server->schedule, 0,
2499 silc_server_connect_to_router,
2502 SILC_TASK_PRI_NORMAL);
2504 server->id_entry->router = NULL;
2505 server->router = NULL;
2506 server->standalone = TRUE;
2507 backup_router = NULL;
2509 SILC_LOG_INFO(("New primary router is backup router %s",
2510 backup_router->server_name));
2511 SILC_LOG_DEBUG(("New primary router is backup router %s",
2512 backup_router->server_name));
2513 server->id_entry->router = backup_router;
2514 server->router = backup_router;
2515 server->router_connect = time(0);
2516 server->backup_primary = TRUE;
2517 if (server->server_type == SILC_BACKUP_ROUTER) {
2518 server->server_type = SILC_ROUTER;
2520 /* We'll need to constantly try to reconnect to the primary
2521 router so that we'll see when it comes back online. */
2522 silc_server_backup_reconnect(server, sock->ip, sock->port,
2523 silc_server_backup_connected,
2527 /* Mark this connection as replaced */
2528 silc_server_backup_replaced_add(server, user_data->id,
2531 } else if (backup_router) {
2532 SILC_LOG_INFO(("Enabling the use of backup router %s",
2533 backup_router->server_name));
2534 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2535 backup_router->server_name));
2537 /* Mark this connection as replaced */
2538 silc_server_backup_replaced_add(server, user_data->id,
2542 if (!backup_router) {
2543 /* Free all client entries that this server owns as they will
2544 become invalid now as well. */
2546 silc_server_remove_clients_by_server(server, user_data, TRUE);
2547 if (server->server_type == SILC_SERVER)
2548 silc_server_remove_channels_by_server(server, user_data);
2550 /* Update the client entries of this server to the new backup
2551 router. This also removes the clients that *really* was owned
2552 by the primary router and went down with the router. */
2553 silc_server_update_clients_by_server(server, user_data, backup_router,
2555 silc_server_update_servers_by_server(server, user_data, backup_router);
2556 if (server->server_type == SILC_SERVER)
2557 silc_server_update_channels_by_server(server, user_data,
2561 /* Free the server entry */
2562 silc_server_backup_del(server, user_data);
2563 silc_server_backup_replaced_del(server, user_data);
2564 silc_idlist_del_data(user_data);
2565 if (!silc_idlist_del_server(server->local_list, user_data))
2566 silc_idlist_del_server(server->global_list, user_data);
2567 server->stat.my_servers--;
2568 server->stat.servers--;
2569 if (server->server_type == SILC_ROUTER)
2570 server->stat.cell_servers--;
2572 if (backup_router) {
2573 /* Announce all of our stuff that was created about 5 minutes ago.
2574 The backup router knows all the other stuff already. */
2575 if (server->server_type == SILC_ROUTER)
2576 silc_server_announce_servers(server, FALSE, time(0) - 300,
2577 backup_router->connection);
2579 /* Announce our clients and channels to the router */
2580 silc_server_announce_clients(server, time(0) - 300,
2581 backup_router->connection);
2582 silc_server_announce_channels(server, time(0) - 300,
2583 backup_router->connection);
2589 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2591 silc_idlist_del_data(user_data);
2592 silc_free(user_data);
2597 /* If any protocol is active cancel its execution */
2598 if (sock->protocol) {
2599 silc_protocol_cancel(sock->protocol, server->schedule);
2600 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2601 silc_protocol_execute_final(sock->protocol, server->schedule);
2602 sock->protocol = NULL;
2605 sock->user_data = NULL;
2608 /* Removes client from all channels it has joined. This is used when client
2609 connection is disconnected. If the client on a channel is last, the
2610 channel is removed as well. This sends the SIGNOFF notify types. */
2612 void silc_server_remove_from_channels(SilcServer server,
2613 SilcSocketConnection sock,
2614 SilcClientEntry client,
2616 char *signoff_message,
2619 SilcChannelEntry channel;
2620 SilcChannelClientEntry chl;
2621 SilcHashTableList htl;
2624 SILC_LOG_DEBUG(("Start"));
2626 if (!client || !client->id)
2629 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2631 /* Remove the client from all channels. The client is removed from
2632 the channels' user list. */
2633 silc_hash_table_list(client->channels, &htl);
2634 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2635 channel = chl->channel;
2637 /* Remove channel from client's channel list */
2638 silc_hash_table_del(client->channels, channel);
2640 /* Remove channel if there is no users anymore */
2641 if (server->server_type == SILC_ROUTER &&
2642 silc_hash_table_count(channel->user_list) < 2) {
2644 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2645 if (silc_idlist_del_channel(server->local_list, channel))
2646 server->stat.my_channels--;
2648 silc_idlist_del_channel(server->global_list, channel);
2652 /* Remove client from channel's client list */
2653 silc_hash_table_del(channel->user_list, chl->client);
2654 channel->user_count--;
2656 /* If there is no global users on the channel anymore mark the channel
2657 as local channel. Do not check if the removed client is local client. */
2658 if (server->server_type != SILC_ROUTER && channel->global_users &&
2659 chl->client->router && !silc_server_channel_has_global(channel))
2660 channel->global_users = FALSE;
2663 server->stat.my_chanclients--;
2665 /* If there is not at least one local user on the channel then we don't
2666 need the channel entry anymore, we can remove it safely. */
2667 if (server->server_type != SILC_ROUTER &&
2668 !silc_server_channel_has_local(channel)) {
2669 /* Notify about leaving client if this channel has global users. */
2670 if (notify && channel->global_users)
2671 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2672 SILC_NOTIFY_TYPE_SIGNOFF,
2673 signoff_message ? 2 : 1,
2674 clidp->data, clidp->len,
2675 signoff_message, signoff_message ?
2676 strlen(signoff_message) : 0);
2679 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2681 if (channel->founder_key) {
2682 /* The founder auth data exists, do not remove the channel entry */
2683 SilcChannelClientEntry chl2;
2684 SilcHashTableList htl2;
2686 channel->disabled = TRUE;
2688 silc_hash_table_list(channel->user_list, &htl2);
2689 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2690 silc_hash_table_del(chl2->client->channels, channel);
2691 silc_hash_table_del(channel->user_list, chl2->client);
2692 channel->user_count--;
2695 silc_hash_table_list_reset(&htl2);
2699 /* Remove the channel entry */
2700 if (silc_idlist_del_channel(server->local_list, channel))
2701 server->stat.my_channels--;
2703 silc_idlist_del_channel(server->global_list, channel);
2707 /* Send notify to channel about client leaving SILC and thus
2708 the entire channel. */
2710 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2711 SILC_NOTIFY_TYPE_SIGNOFF,
2712 signoff_message ? 2 : 1,
2713 clidp->data, clidp->len,
2714 signoff_message, signoff_message ?
2715 strlen(signoff_message) : 0);
2717 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2718 /* Re-generate channel key */
2719 if (!silc_server_create_channel_key(server, channel, 0))
2722 /* Send the channel key to the channel. The key of course is not sent
2723 to the client who was removed from the channel. */
2724 silc_server_send_channel_key(server, client->connection, channel,
2725 server->server_type == SILC_ROUTER ?
2726 FALSE : !server->standalone);
2731 silc_hash_table_list_reset(&htl);
2732 silc_buffer_free(clidp);
2735 /* Removes client from one channel. This is used for example when client
2736 calls LEAVE command to remove itself from the channel. Returns TRUE
2737 if channel still exists and FALSE if the channel is removed when
2738 last client leaves the channel. If `notify' is FALSE notify messages
2741 int silc_server_remove_from_one_channel(SilcServer server,
2742 SilcSocketConnection sock,
2743 SilcChannelEntry channel,
2744 SilcClientEntry client,
2747 SilcChannelClientEntry chl;
2750 SILC_LOG_DEBUG(("Start"));
2752 /* Get the entry to the channel, if this client is not on the channel
2754 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2757 /* Remove the client from the channel. The client is removed from
2758 the channel's user list. */
2760 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2762 /* Remove channel from client's channel list */
2763 silc_hash_table_del(client->channels, chl->channel);
2765 /* Remove channel if there is no users anymore */
2766 if (server->server_type == SILC_ROUTER &&
2767 silc_hash_table_count(channel->user_list) < 2) {
2769 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2770 if (silc_idlist_del_channel(server->local_list, channel))
2771 server->stat.my_channels--;
2773 silc_idlist_del_channel(server->global_list, channel);
2774 silc_buffer_free(clidp);
2778 /* Remove client from channel's client list */
2779 silc_hash_table_del(channel->user_list, chl->client);
2780 channel->user_count--;
2782 /* If there is no global users on the channel anymore mark the channel
2783 as local channel. Do not check if the client is local client. */
2784 if (server->server_type != SILC_ROUTER && channel->global_users &&
2785 chl->client->router && !silc_server_channel_has_global(channel))
2786 channel->global_users = FALSE;
2789 server->stat.my_chanclients--;
2791 /* If there is not at least one local user on the channel then we don't
2792 need the channel entry anymore, we can remove it safely. */
2793 if (server->server_type != SILC_ROUTER &&
2794 !silc_server_channel_has_local(channel)) {
2795 /* Notify about leaving client if this channel has global users. */
2796 if (notify && channel->global_users)
2797 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2798 SILC_NOTIFY_TYPE_LEAVE, 1,
2799 clidp->data, clidp->len);
2801 silc_buffer_free(clidp);
2804 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2806 if (channel->founder_key) {
2807 /* The founder auth data exists, do not remove the channel entry */
2808 SilcChannelClientEntry chl2;
2809 SilcHashTableList htl2;
2811 channel->disabled = TRUE;
2813 silc_hash_table_list(channel->user_list, &htl2);
2814 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2815 silc_hash_table_del(chl2->client->channels, channel);
2816 silc_hash_table_del(channel->user_list, chl2->client);
2817 channel->user_count--;
2820 silc_hash_table_list_reset(&htl2);
2824 /* Remove the channel entry */
2825 if (silc_idlist_del_channel(server->local_list, channel))
2826 server->stat.my_channels--;
2828 silc_idlist_del_channel(server->global_list, channel);
2832 /* Send notify to channel about client leaving the channel */
2834 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2835 SILC_NOTIFY_TYPE_LEAVE, 1,
2836 clidp->data, clidp->len);
2838 silc_buffer_free(clidp);
2842 /* Timeout callback. This is called if connection is idle or for some
2843 other reason is not responding within some period of time. This
2844 disconnects the remote end. */
2846 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2848 SilcServer server = (SilcServer)context;
2849 SilcSocketConnection sock = server->sockets[fd];
2851 SILC_LOG_DEBUG(("Start"));
2856 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2857 sock->hostname, sock->ip));
2859 /* If we have protocol active we must assure that we call the protocol's
2860 final callback so that all the memory is freed. */
2861 if (sock->protocol) {
2862 silc_protocol_cancel(sock->protocol, server->schedule);
2863 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2864 silc_protocol_execute_final(sock->protocol, server->schedule);
2865 sock->protocol = NULL;
2869 if (sock->user_data)
2870 silc_server_free_sock_user_data(server, sock, NULL);
2872 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2873 "Connection timeout");
2876 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2877 function may be used only by router. In real SILC network all channels
2878 are created by routers thus this function is never used by normal
2881 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2882 SilcServerID *router_id,
2888 SilcChannelID *channel_id;
2889 SilcChannelEntry entry;
2893 SILC_LOG_DEBUG(("Creating new channel"));
2896 cipher = SILC_DEFAULT_CIPHER;
2898 hmac = SILC_DEFAULT_HMAC;
2900 /* Allocate cipher */
2901 if (!silc_cipher_alloc(cipher, &key))
2905 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2906 silc_cipher_free(key);
2910 channel_name = strdup(channel_name);
2912 /* Create the channel ID */
2913 if (!silc_id_create_channel_id(server, router_id, server->rng,
2915 silc_free(channel_name);
2916 silc_cipher_free(key);
2917 silc_hmac_free(newhmac);
2921 /* Create the channel */
2922 entry = silc_idlist_add_channel(server->local_list, channel_name,
2923 SILC_CHANNEL_MODE_NONE, channel_id,
2924 NULL, key, newhmac, 0);
2926 silc_free(channel_name);
2927 silc_cipher_free(key);
2928 silc_hmac_free(newhmac);
2929 silc_free(channel_id);
2933 entry->cipher = strdup(cipher);
2934 entry->hmac_name = strdup(hmac);
2936 /* Now create the actual key material */
2937 if (!silc_server_create_channel_key(server, entry,
2938 silc_cipher_get_key_len(key) / 8)) {
2939 silc_idlist_del_channel(server->local_list, entry);
2943 /* Notify other routers about the new channel. We send the packet
2944 to our primary route. */
2945 if (broadcast && server->standalone == FALSE)
2946 silc_server_send_new_channel(server, server->router->connection, TRUE,
2947 channel_name, entry->id,
2948 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2951 server->stat.my_channels++;
2956 /* Same as above but creates the channel with Channel ID `channel_id. */
2959 silc_server_create_new_channel_with_id(SilcServer server,
2963 SilcChannelID *channel_id,
2966 SilcChannelEntry entry;
2970 SILC_LOG_DEBUG(("Creating new channel"));
2973 cipher = SILC_DEFAULT_CIPHER;
2975 hmac = SILC_DEFAULT_HMAC;
2977 /* Allocate cipher */
2978 if (!silc_cipher_alloc(cipher, &key))
2982 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2983 silc_cipher_free(key);
2987 channel_name = strdup(channel_name);
2989 /* Create the channel */
2990 entry = silc_idlist_add_channel(server->local_list, channel_name,
2991 SILC_CHANNEL_MODE_NONE, channel_id,
2992 NULL, key, newhmac, 0);
2994 silc_cipher_free(key);
2995 silc_hmac_free(newhmac);
2996 silc_free(channel_name);
3000 /* Now create the actual key material */
3001 if (!silc_server_create_channel_key(server, entry,
3002 silc_cipher_get_key_len(key) / 8)) {
3003 silc_idlist_del_channel(server->local_list, entry);
3007 /* Notify other routers about the new channel. We send the packet
3008 to our primary route. */
3009 if (broadcast && server->standalone == FALSE)
3010 silc_server_send_new_channel(server, server->router->connection, TRUE,
3011 channel_name, entry->id,
3012 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3015 server->stat.my_channels++;
3020 /* Channel's key re-key timeout callback. */
3022 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3024 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3025 SilcServer server = (SilcServer)rekey->context;
3029 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3032 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3035 /* Generates new channel key. This is used to create the initial channel key
3036 but also to re-generate new key for channel. If `key_len' is provided
3037 it is the bytes of the key length. */
3039 bool silc_server_create_channel_key(SilcServer server,
3040 SilcChannelEntry channel,
3044 unsigned char channel_key[32], hash[32];
3047 SILC_LOG_DEBUG(("Generating channel key"));
3049 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3050 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3054 if (!channel->channel_key)
3055 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3056 channel->channel_key = NULL;
3062 else if (channel->key_len)
3063 len = channel->key_len / 8;
3065 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3067 /* Create channel key */
3068 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3071 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3073 /* Remove old key if exists */
3075 memset(channel->key, 0, channel->key_len / 8);
3076 silc_free(channel->key);
3080 channel->key_len = len * 8;
3081 channel->key = silc_memdup(channel_key, len);
3082 memset(channel_key, 0, sizeof(channel_key));
3084 /* Generate HMAC key from the channel key data and set it */
3086 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3087 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3088 silc_hmac_set_key(channel->hmac, hash,
3089 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3090 memset(hash, 0, sizeof(hash));
3092 if (server->server_type == SILC_ROUTER) {
3093 if (!channel->rekey)
3094 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3095 channel->rekey->context = (void *)server;
3096 channel->rekey->channel = channel;
3097 channel->rekey->key_len = key_len;
3098 if (channel->rekey->task)
3099 silc_schedule_task_del(server->schedule, channel->rekey->task);
3101 channel->rekey->task =
3102 silc_schedule_task_add(server->schedule, 0,
3103 silc_server_channel_key_rekey,
3104 (void *)channel->rekey,
3105 server->config->channel_rekey_secs, 0,
3107 SILC_TASK_PRI_NORMAL);
3113 /* Saves the channel key found in the encoded `key_payload' buffer. This
3114 function is used when we receive Channel Key Payload and also when we're
3115 processing JOIN command reply. Returns entry to the channel. */
3117 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3118 SilcBuffer key_payload,
3119 SilcChannelEntry channel)
3121 SilcChannelKeyPayload payload = NULL;
3122 SilcChannelID *id = NULL;
3123 unsigned char *tmp, hash[32];
3127 SILC_LOG_DEBUG(("Start"));
3129 /* Decode channel key payload */
3130 payload = silc_channel_key_payload_parse(key_payload->data,
3133 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3138 /* Get the channel entry */
3141 /* Get channel ID */
3142 tmp = silc_channel_key_get_id(payload, &tmp_len);
3143 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3149 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3151 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3153 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3154 silc_id_render(id, SILC_ID_CHANNEL)));
3160 tmp = silc_channel_key_get_key(payload, &tmp_len);
3166 cipher = silc_channel_key_get_cipher(payload, NULL);
3172 /* Remove old key if exists */
3174 memset(channel->key, 0, channel->key_len / 8);
3175 silc_free(channel->key);
3176 silc_cipher_free(channel->channel_key);
3179 /* Create new cipher */
3180 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3181 channel->channel_key = NULL;
3186 if (channel->cipher)
3187 silc_free(channel->cipher);
3188 channel->cipher = strdup(cipher);
3191 channel->key_len = tmp_len * 8;
3192 channel->key = silc_memdup(tmp, tmp_len);
3193 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3195 /* Generate HMAC key from the channel key data and set it */
3197 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3198 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3199 silc_hmac_set_key(channel->hmac, hash,
3200 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3202 memset(hash, 0, sizeof(hash));
3203 memset(tmp, 0, tmp_len);
3205 if (server->server_type == SILC_ROUTER) {
3206 if (!channel->rekey)
3207 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3208 channel->rekey->context = (void *)server;
3209 channel->rekey->channel = channel;
3210 if (channel->rekey->task)
3211 silc_schedule_task_del(server->schedule, channel->rekey->task);
3213 channel->rekey->task =
3214 silc_schedule_task_add(server->schedule, 0,
3215 silc_server_channel_key_rekey,
3216 (void *)channel->rekey,
3217 server->config->channel_rekey_secs, 0,
3219 SILC_TASK_PRI_NORMAL);
3225 silc_channel_key_payload_free(payload);
3230 /* Heartbeat callback. This function is set as argument for the
3231 silc_socket_set_heartbeat function. The library will call this function
3232 at the set time interval. */
3234 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3237 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3239 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3241 /* Send the heartbeat */
3242 silc_server_send_heartbeat(hb->server, sock);
3245 /* Returns assembled of all servers in the given ID list. The packet's
3246 form is dictated by the New ID payload. */
3248 static void silc_server_announce_get_servers(SilcServer server,
3249 SilcServerEntry remote,
3251 SilcBuffer *servers,
3252 unsigned long creation_time)
3254 SilcIDCacheList list;
3255 SilcIDCacheEntry id_cache;
3256 SilcServerEntry entry;
3259 /* Go through all clients in the list */
3260 if (silc_idcache_get_all(id_list->servers, &list)) {
3261 if (silc_idcache_list_first(list, &id_cache)) {
3263 entry = (SilcServerEntry)id_cache->context;
3265 /* Do not announce the one we've sending our announcements and
3266 do not announce ourself. Also check the creation time if it's
3268 if ((entry == remote) || (entry == server->id_entry) ||
3269 (creation_time && entry->data.created < creation_time)) {
3270 if (!silc_idcache_list_next(list, &id_cache))
3275 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3277 *servers = silc_buffer_realloc(*servers,
3279 (*servers)->truelen + idp->len :
3281 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3282 silc_buffer_put(*servers, idp->data, idp->len);
3283 silc_buffer_pull(*servers, idp->len);
3284 silc_buffer_free(idp);
3286 if (!silc_idcache_list_next(list, &id_cache))
3291 silc_idcache_list_free(list);
3296 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3302 p = silc_notify_payload_encode(notify, argc, ap);
3308 /* This function is used by router to announce existing servers to our
3309 primary router when we've connected to it. If `creation_time' is non-zero
3310 then only the servers that has been created after the `creation_time'
3311 will be announced. */
3313 void silc_server_announce_servers(SilcServer server, bool global,
3314 unsigned long creation_time,
3315 SilcSocketConnection remote)
3317 SilcBuffer servers = NULL;
3319 SILC_LOG_DEBUG(("Announcing servers"));
3321 /* Get servers in local list */
3322 silc_server_announce_get_servers(server, remote->user_data,
3323 server->local_list, &servers,
3327 /* Get servers in global list */
3328 silc_server_announce_get_servers(server, remote->user_data,
3329 server->global_list, &servers,
3333 silc_buffer_push(servers, servers->data - servers->head);
3334 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3336 /* Send the packet */
3337 silc_server_packet_send(server, remote,
3338 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3339 servers->data, servers->len, TRUE);
3341 silc_buffer_free(servers);
3345 /* Returns assembled packet of all clients in the given ID list. The
3346 packet's form is dictated by the New ID Payload. */
3348 static void silc_server_announce_get_clients(SilcServer server,
3350 SilcBuffer *clients,
3352 unsigned long creation_time)
3354 SilcIDCacheList list;
3355 SilcIDCacheEntry id_cache;
3356 SilcClientEntry client;
3359 unsigned char mode[4];
3361 /* Go through all clients in the list */
3362 if (silc_idcache_get_all(id_list->clients, &list)) {
3363 if (silc_idcache_list_first(list, &id_cache)) {
3365 client = (SilcClientEntry)id_cache->context;
3367 if (creation_time && client->data.created < creation_time) {
3368 if (!silc_idcache_list_next(list, &id_cache))
3373 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3375 *clients = silc_buffer_realloc(*clients,
3377 (*clients)->truelen + idp->len :
3379 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3380 silc_buffer_put(*clients, idp->data, idp->len);
3381 silc_buffer_pull(*clients, idp->len);
3383 SILC_PUT32_MSB(client->mode, mode);
3384 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3385 2, idp->data, idp->len,
3387 *umodes = silc_buffer_realloc(*umodes,
3389 (*umodes)->truelen + tmp->len :
3391 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3392 silc_buffer_put(*umodes, tmp->data, tmp->len);
3393 silc_buffer_pull(*umodes, tmp->len);
3394 silc_buffer_free(tmp);
3396 silc_buffer_free(idp);
3398 if (!silc_idcache_list_next(list, &id_cache))
3403 silc_idcache_list_free(list);
3407 /* This function is used to announce our existing clients to our router
3408 when we've connected to it. If `creation_time' is non-zero then only
3409 the clients that has been created after the `creation_time' will be
3412 void silc_server_announce_clients(SilcServer server,
3413 unsigned long creation_time,
3414 SilcSocketConnection remote)
3416 SilcBuffer clients = NULL;
3417 SilcBuffer umodes = NULL;
3419 SILC_LOG_DEBUG(("Announcing clients"));
3421 /* Get clients in local list */
3422 silc_server_announce_get_clients(server, server->local_list,
3423 &clients, &umodes, creation_time);
3425 /* As router we announce our global list as well */
3426 if (server->server_type == SILC_ROUTER)
3427 silc_server_announce_get_clients(server, server->global_list,
3428 &clients, &umodes, creation_time);
3431 silc_buffer_push(clients, clients->data - clients->head);
3432 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3434 /* Send the packet */
3435 silc_server_packet_send(server, remote,
3436 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3437 clients->data, clients->len, TRUE);
3439 silc_buffer_free(clients);
3443 silc_buffer_push(umodes, umodes->data - umodes->head);
3444 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3446 /* Send the packet */
3447 silc_server_packet_send(server, remote,
3448 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3449 umodes->data, umodes->len, TRUE);
3451 silc_buffer_free(umodes);
3455 /* Returns channel's topic for announcing it */
3457 void silc_server_announce_get_channel_topic(SilcServer server,
3458 SilcChannelEntry channel,
3463 if (channel->topic) {
3464 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3465 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3466 chidp->data, chidp->len,
3468 strlen(channel->topic));
3469 silc_buffer_free(chidp);
3473 /* Returns assembled packets for channel users of the `channel'. */
3475 void silc_server_announce_get_channel_users(SilcServer server,
3476 SilcChannelEntry channel,
3477 SilcBuffer *channel_users,
3478 SilcBuffer *channel_users_modes)
3480 SilcChannelClientEntry chl;
3481 SilcHashTableList htl;
3482 SilcBuffer chidp, clidp;
3485 unsigned char mode[4];
3487 SILC_LOG_DEBUG(("Start"));
3489 /* Now find all users on the channel */
3490 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3491 silc_hash_table_list(channel->user_list, &htl);
3492 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3493 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3496 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3497 clidp->data, clidp->len,
3498 chidp->data, chidp->len);
3501 silc_buffer_realloc(*channel_users,
3503 (*channel_users)->truelen + len : len));
3504 silc_buffer_pull_tail(*channel_users,
3505 ((*channel_users)->end -
3506 (*channel_users)->data));
3508 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3509 silc_buffer_pull(*channel_users, len);
3510 silc_buffer_free(tmp);
3512 /* CUMODE notify for mode change on the channel */
3513 SILC_PUT32_MSB(chl->mode, mode);
3514 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3515 3, clidp->data, clidp->len,
3517 clidp->data, clidp->len);
3519 *channel_users_modes =
3520 silc_buffer_realloc(*channel_users_modes,
3521 (*channel_users_modes ?
3522 (*channel_users_modes)->truelen + len : len));
3523 silc_buffer_pull_tail(*channel_users_modes,
3524 ((*channel_users_modes)->end -
3525 (*channel_users_modes)->data));
3527 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3528 silc_buffer_pull(*channel_users_modes, len);
3529 silc_buffer_free(tmp);
3531 silc_buffer_free(clidp);
3533 silc_hash_table_list_reset(&htl);
3534 silc_buffer_free(chidp);
3537 /* Returns assembled packets for all channels and users on those channels
3538 from the given ID List. The packets are in the form dictated by the
3539 New Channel and New Channel User payloads. */
3541 void silc_server_announce_get_channels(SilcServer server,
3543 SilcBuffer *channels,
3544 SilcBuffer *channel_users,
3545 SilcBuffer **channel_users_modes,
3546 SilcUInt32 *channel_users_modes_c,
3547 SilcBuffer **channel_topics,
3548 SilcChannelID ***channel_ids,
3549 unsigned long creation_time)
3551 SilcIDCacheList list;
3552 SilcIDCacheEntry id_cache;
3553 SilcChannelEntry channel;
3556 SilcUInt16 name_len;
3558 int i = *channel_users_modes_c;
3561 SILC_LOG_DEBUG(("Start"));
3563 /* Go through all channels in the list */
3564 if (silc_idcache_get_all(id_list->channels, &list)) {
3565 if (silc_idcache_list_first(list, &id_cache)) {
3567 channel = (SilcChannelEntry)id_cache->context;
3569 if (creation_time && channel->created < creation_time)
3574 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3575 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3576 name_len = strlen(channel->channel_name);
3579 len = 4 + name_len + id_len + 4;
3581 silc_buffer_realloc(*channels,
3582 (*channels ? (*channels)->truelen +
3584 silc_buffer_pull_tail(*channels,
3585 ((*channels)->end - (*channels)->data));
3586 silc_buffer_format(*channels,
3587 SILC_STR_UI_SHORT(name_len),
3588 SILC_STR_UI_XNSTRING(channel->channel_name,
3590 SILC_STR_UI_SHORT(id_len),
3591 SILC_STR_UI_XNSTRING(cid, id_len),
3592 SILC_STR_UI_INT(channel->mode),
3594 silc_buffer_pull(*channels, len);
3597 /* Channel user modes */
3598 *channel_users_modes = silc_realloc(*channel_users_modes,
3599 sizeof(**channel_users_modes) *
3601 (*channel_users_modes)[i] = NULL;
3602 *channel_ids = silc_realloc(*channel_ids,
3603 sizeof(**channel_ids) * (i + 1));
3604 (*channel_ids)[i] = NULL;
3605 silc_server_announce_get_channel_users(server, channel,
3607 &(*channel_users_modes)[i]);
3608 (*channel_ids)[i] = channel->id;
3610 /* Channel's topic */
3611 *channel_topics = silc_realloc(*channel_topics,
3612 sizeof(**channel_topics) * (i + 1));
3613 (*channel_topics)[i] = NULL;
3614 silc_server_announce_get_channel_topic(server, channel,
3615 &(*channel_topics)[i]);
3618 if (!silc_idcache_list_next(list, &id_cache))
3622 *channel_users_modes_c += i;
3625 silc_idcache_list_free(list);
3629 /* This function is used to announce our existing channels to our router
3630 when we've connected to it. This also announces the users on the
3631 channels to the router. If the `creation_time' is non-zero only the
3632 channels that was created after the `creation_time' are announced.
3633 Note that the channel users are still announced even if the `creation_time'
3636 void silc_server_announce_channels(SilcServer server,
3637 unsigned long creation_time,
3638 SilcSocketConnection remote)
3640 SilcBuffer channels = NULL, channel_users = NULL;
3641 SilcBuffer *channel_users_modes = NULL;
3642 SilcBuffer *channel_topics = NULL;
3643 SilcUInt32 channel_users_modes_c = 0;
3644 SilcChannelID **channel_ids = NULL;
3646 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3648 /* Get channels and channel users in local list */
3649 silc_server_announce_get_channels(server, server->local_list,
3650 &channels, &channel_users,
3651 &channel_users_modes,
3652 &channel_users_modes_c,
3654 &channel_ids, creation_time);
3656 /* Get channels and channel users in global list */
3657 if (server->server_type != SILC_SERVER)
3658 silc_server_announce_get_channels(server, server->global_list,
3659 &channels, &channel_users,
3660 &channel_users_modes,
3661 &channel_users_modes_c,
3663 &channel_ids, creation_time);
3666 silc_buffer_push(channels, channels->data - channels->head);
3667 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3669 /* Send the packet */
3670 silc_server_packet_send(server, remote,
3671 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3672 channels->data, channels->len,
3675 silc_buffer_free(channels);
3678 if (channel_users) {
3679 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3680 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3681 channel_users->len);
3683 /* Send the packet */
3684 silc_server_packet_send(server, remote,
3685 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3686 channel_users->data, channel_users->len,
3689 silc_buffer_free(channel_users);
3692 if (channel_users_modes) {
3695 for (i = 0; i < channel_users_modes_c; i++) {
3696 if (!channel_users_modes[i])
3698 silc_buffer_push(channel_users_modes[i],
3699 channel_users_modes[i]->data -
3700 channel_users_modes[i]->head);
3701 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3702 channel_users_modes[i]->len);
3703 silc_server_packet_send_dest(server, remote,
3704 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3705 channel_ids[i], SILC_ID_CHANNEL,
3706 channel_users_modes[i]->data,
3707 channel_users_modes[i]->len,
3709 silc_buffer_free(channel_users_modes[i]);
3711 silc_free(channel_users_modes);
3714 if (channel_topics) {
3717 for (i = 0; i < channel_users_modes_c; i++) {
3718 if (!channel_topics[i])
3721 silc_buffer_push(channel_topics[i],
3722 channel_topics[i]->data -
3723 channel_topics[i]->head);
3724 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3725 channel_topics[i]->len);
3726 silc_server_packet_send_dest(server, remote,
3727 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3728 channel_ids[i], SILC_ID_CHANNEL,
3729 channel_topics[i]->data,
3730 channel_topics[i]->len,
3732 silc_buffer_free(channel_topics[i]);
3734 silc_free(channel_topics);
3737 silc_free(channel_ids);
3740 /* Failure timeout callback. If this is called then we will immediately
3741 process the received failure. We always process the failure with timeout
3742 since we do not want to blindly trust to received failure packets.
3743 This won't be called (the timeout is cancelled) if the failure was
3744 bogus (it is bogus if remote does not close the connection after sending
3747 SILC_TASK_CALLBACK(silc_server_failure_callback)
3749 SilcServerFailureContext f = (SilcServerFailureContext)context;
3751 if (f->sock->protocol) {
3752 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3753 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3759 /* Assembles user list and users mode list from the `channel'. */
3761 void silc_server_get_users_on_channel(SilcServer server,
3762 SilcChannelEntry channel,
3763 SilcBuffer *user_list,
3764 SilcBuffer *mode_list,
3765 SilcUInt32 *user_count)
3767 SilcChannelClientEntry chl;
3768 SilcHashTableList htl;
3769 SilcBuffer client_id_list;
3770 SilcBuffer client_mode_list;
3772 SilcUInt32 list_count = 0, len = 0;
3774 silc_hash_table_list(channel->user_list, &htl);
3775 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3776 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3777 silc_hash_table_list_reset(&htl);
3779 client_id_list = silc_buffer_alloc(len);
3781 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3782 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3783 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3785 silc_hash_table_list(channel->user_list, &htl);
3786 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3788 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3789 silc_buffer_put(client_id_list, idp->data, idp->len);
3790 silc_buffer_pull(client_id_list, idp->len);
3791 silc_buffer_free(idp);
3793 /* Client's mode on channel */
3794 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3795 silc_buffer_pull(client_mode_list, 4);
3799 silc_hash_table_list_reset(&htl);
3800 silc_buffer_push(client_id_list,
3801 client_id_list->data - client_id_list->head);
3802 silc_buffer_push(client_mode_list,
3803 client_mode_list->data - client_mode_list->head);
3805 *user_list = client_id_list;
3806 *mode_list = client_mode_list;
3807 *user_count = list_count;
3810 /* Saves users and their modes to the `channel'. */
3812 void silc_server_save_users_on_channel(SilcServer server,
3813 SilcSocketConnection sock,
3814 SilcChannelEntry channel,
3815 SilcClientID *noadd,
3816 SilcBuffer user_list,
3817 SilcBuffer mode_list,
3818 SilcUInt32 user_count)
3823 SilcClientID *client_id;
3824 SilcClientEntry client;
3825 SilcIDCacheEntry cache;
3828 SILC_LOG_DEBUG(("Start"));
3830 for (i = 0; i < user_count; i++) {
3832 SILC_GET16_MSB(idp_len, user_list->data + 2);
3834 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3835 silc_buffer_pull(user_list, idp_len);
3840 SILC_GET32_MSB(mode, mode_list->data);
3841 silc_buffer_pull(mode_list, 4);
3843 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3844 silc_free(client_id);
3850 /* Check if we have this client cached already. */
3851 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3852 server->server_type, &cache);
3854 client = silc_idlist_find_client_by_id(server->global_list,
3855 client_id, server->server_type,
3860 /* If router did not find such Client ID in its lists then this must
3861 be bogus client or some router in the net is buggy. */
3862 if (server->server_type == SILC_ROUTER) {
3863 silc_free(client_id);
3867 /* We don't have that client anywhere, add it. The client is added
3868 to global list since server didn't have it in the lists so it must be
3870 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3871 silc_id_dup(client_id, SILC_ID_CLIENT),
3872 sock->user_data, NULL, 0);
3874 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3875 silc_free(client_id);
3879 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3881 /* Found, if it is from global list we'll assure that we won't
3882 expire it now that the entry is on channel. */
3887 silc_free(client_id);
3889 if (!silc_server_client_on_channel(client, channel)) {
3890 /* Client was not on the channel, add it. */
3891 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3892 chl->client = client;
3894 chl->channel = channel;
3895 silc_hash_table_add(channel->user_list, chl->client, chl);
3896 silc_hash_table_add(client->channels, chl->channel, chl);
3897 channel->user_count++;
3902 /* Lookups route to the client indicated by the `id_data'. The connection
3903 object and internal data object is returned. Returns NULL if route
3904 could not be found to the client. If the `client_id' is specified then
3905 it is used and the `id_data' is ignored. */
3907 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3908 unsigned char *id_data,
3910 SilcClientID *client_id,
3911 SilcIDListData *idata)
3914 SilcClientEntry client;
3916 SILC_LOG_DEBUG(("Start"));
3918 /* Decode destination Client ID */
3920 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3922 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3926 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3929 /* If the destination belongs to our server we don't have to route
3930 the packet anywhere but to send it to the local destination. */
3931 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3935 /* If we are router and the client has router then the client is in
3936 our cell but not directly connected to us. */
3937 if (server->server_type == SILC_ROUTER && client->router) {
3938 /* We are of course in this case the client's router thus the route
3939 to the client is the server who owns the client. So, we will send
3940 the packet to that server. */
3942 *idata = (SilcIDListData)client->router;
3943 return client->router->connection;
3946 /* Seems that client really is directly connected to us */
3948 *idata = (SilcIDListData)client;
3949 return client->connection;
3952 /* Destination belongs to someone not in this server. If we are normal
3953 server our action is to send the packet to our router. */
3954 if (server->server_type != SILC_ROUTER && !server->standalone) {
3957 *idata = (SilcIDListData)server->router;
3958 return server->router->connection;
3961 /* We are router and we will perform route lookup for the destination
3962 and send the packet to fastest route. */
3963 if (server->server_type == SILC_ROUTER && !server->standalone) {
3964 /* Check first that the ID is valid */
3965 client = silc_idlist_find_client_by_id(server->global_list, id,
3968 SilcSocketConnection dst_sock;
3970 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3974 *idata = (SilcIDListData)dst_sock->user_data;
3983 /* Encodes and returns channel list of channels the `client' has joined.
3984 Secret channels are not put to the list. */
3986 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3987 SilcClientEntry client)
3989 SilcBuffer buffer = NULL;
3990 SilcChannelEntry channel;
3991 SilcChannelClientEntry chl;
3992 SilcHashTableList htl;
3995 SilcUInt16 name_len;
3998 silc_hash_table_list(client->channels, &htl);
3999 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4000 channel = chl->channel;
4002 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4003 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4006 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4007 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4008 name_len = strlen(channel->channel_name);
4010 len = 4 + name_len + id_len + 4;
4011 buffer = silc_buffer_realloc(buffer,
4012 (buffer ? (buffer)->truelen + len : len));
4013 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4014 silc_buffer_format(buffer,
4015 SILC_STR_UI_SHORT(name_len),
4016 SILC_STR_UI_XNSTRING(channel->channel_name,
4018 SILC_STR_UI_SHORT(id_len),
4019 SILC_STR_UI_XNSTRING(cid, id_len),
4020 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4022 silc_buffer_pull(buffer, len);
4025 silc_hash_table_list_reset(&htl);
4028 silc_buffer_push(buffer, buffer->data - buffer->head);
4033 /* Finds client entry by Client ID and if it is not found then resolves
4034 it using WHOIS command. */
4036 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4037 SilcClientID *client_id,
4040 SilcClientEntry client;
4045 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4048 client = silc_idlist_find_client_by_id(server->global_list,
4049 client_id, TRUE, NULL);
4050 if (!client && server->server_type == SILC_ROUTER)
4054 if (!client && server->standalone)
4057 if (!client || !client->nickname || !client->username) {
4058 SilcBuffer buffer, idp;
4060 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4061 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4062 client->resolve_cmd_ident = ++server->cmd_ident;
4064 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4065 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4066 server->cmd_ident, 1,
4067 3, idp->data, idp->len);
4068 silc_server_packet_send(server, client ? client->router->connection :
4069 server->router->connection,
4070 SILC_PACKET_COMMAND, 0,
4071 buffer->data, buffer->len, FALSE);
4072 silc_buffer_free(idp);
4073 silc_buffer_free(buffer);
4084 /* A timeout callback for the re-key. We will be the initiator of the
4087 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4089 SilcSocketConnection sock = (SilcSocketConnection)context;
4090 SilcIDListData idata = (SilcIDListData)sock->user_data;
4091 SilcServer server = (SilcServer)idata->rekey->context;
4092 SilcProtocol protocol;
4093 SilcServerRekeyInternalContext *proto_ctx;
4095 SILC_LOG_DEBUG(("Start"));
4097 /* Allocate internal protocol context. This is sent as context
4099 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4100 proto_ctx->server = (void *)server;
4101 proto_ctx->sock = sock;
4102 proto_ctx->responder = FALSE;
4103 proto_ctx->pfs = idata->rekey->pfs;
4105 /* Perform rekey protocol. Will call the final callback after the
4106 protocol is over. */
4107 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4108 &protocol, proto_ctx, silc_server_rekey_final);
4109 sock->protocol = protocol;
4111 /* Run the protocol */
4112 silc_protocol_execute(protocol, server->schedule, 0, 0);
4114 /* Re-register re-key timeout */
4115 silc_schedule_task_add(server->schedule, sock->sock,
4116 silc_server_rekey_callback,
4117 context, idata->rekey->timeout, 0,
4118 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4121 /* The final callback for the REKEY protocol. This will actually take the
4122 new key material into use. */
4124 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4126 SilcProtocol protocol = (SilcProtocol)context;
4127 SilcServerRekeyInternalContext *ctx =
4128 (SilcServerRekeyInternalContext *)protocol->context;
4129 SilcServer server = (SilcServer)ctx->server;
4130 SilcSocketConnection sock = ctx->sock;
4132 SILC_LOG_DEBUG(("Start"));
4134 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4135 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4136 /* Error occured during protocol */
4137 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4138 silc_protocol_cancel(protocol, server->schedule);
4139 silc_protocol_free(protocol);
4140 sock->protocol = NULL;
4142 silc_packet_context_free(ctx->packet);
4144 silc_ske_free(ctx->ske);
4149 /* Purge the outgoing data queue to assure that all rekey packets really
4150 go to the network before we quit the protocol. */
4151 silc_server_packet_queue_purge(server, sock);
4154 silc_protocol_free(protocol);
4155 sock->protocol = NULL;
4157 silc_packet_context_free(ctx->packet);
4159 silc_ske_free(ctx->ske);