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)
79 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
80 silc_dlist_del(server->sim, sim);
83 silc_dlist_uninit(server->sim);
87 silc_rng_free(server->rng);
89 silc_pkcs_free(server->pkcs);
90 if (server->pending_commands)
91 silc_dlist_uninit(server->pending_commands);
93 silc_idlist_del_server(server->local_list, server->id_entry);
95 silc_idcache_free(server->local_list->clients);
96 silc_idcache_free(server->local_list->servers);
97 silc_idcache_free(server->local_list->channels);
98 silc_idcache_free(server->global_list->clients);
99 silc_idcache_free(server->global_list->servers);
100 silc_idcache_free(server->global_list->channels);
102 silc_free(server->sockets);
107 /* Initializes the entire SILC server. This is called always before running
108 the server. This is called only once at the initialization of the program.
109 This binds the server to its listenning port. After this function returns
110 one should call silc_server_run to start the server. This returns TRUE
111 when everything is ok to run the server. Configuration file must be
112 read and parsed before calling this. */
114 int silc_server_init(SilcServer server)
118 SilcServerEntry id_entry;
119 SilcIDListPurge purge;
121 SILC_LOG_DEBUG(("Initializing server"));
123 assert(server->config);
125 /* Set public and private keys */
126 if (!server->config->server_info ||
127 !server->config->server_info->public_key ||
128 !server->config->server_info->private_key) {
129 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
132 server->public_key = server->config->server_info->public_key;
133 server->private_key = server->config->server_info->private_key;
135 /* Set default to configuration parameters */
136 silc_server_config_set_defaults(server);
138 /* Register all configured ciphers, PKCS and hash functions. */
139 if (!silc_server_config_register_ciphers(server))
140 silc_cipher_register_default();
141 if (!silc_server_config_register_pkcs(server))
142 silc_pkcs_register_default();
143 if (!silc_server_config_register_hashfuncs(server))
144 silc_hash_register_default();
145 if (!silc_server_config_register_hmacs(server))
146 silc_hmac_register_default();
148 /* Initialize random number generator for the server. */
149 server->rng = silc_rng_alloc();
150 silc_rng_init(server->rng);
151 silc_rng_global_init(server->rng);
153 /* Initialize hash functions for server to use */
154 silc_hash_alloc("md5", &server->md5hash);
155 silc_hash_alloc("sha1", &server->sha1hash);
157 /* Allocate PKCS context for local public and private keys */
158 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
159 silc_pkcs_public_key_set(server->pkcs, server->public_key);
160 silc_pkcs_private_key_set(server->pkcs, server->private_key);
162 /* Create a listening server */
163 sock = silc_net_create_server(server->config->server_info->port,
164 server->config->server_info->server_ip);
166 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
167 server->config->server_info->server_ip,
168 server->config->server_info->port));
172 /* Initialize ID caches */
173 server->local_list->clients =
174 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
175 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
176 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
178 /* These are allocated for normal server as well as these hold some
179 global information that the server has fetched from its router. For
180 router these are used as they are supposed to be used on router. */
181 server->global_list->clients =
182 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
183 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
184 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
186 /* Allocate the entire socket list that is used in server. Eventually
187 all connections will have entry in this table (it is a table of
188 pointers to the actual object that is allocated individually
190 server->sockets = silc_calloc(server->config->param.connections_max,
191 sizeof(*server->sockets));
194 SilcSocketConnection newsocket = NULL;
196 /* Set socket to non-blocking mode */
197 silc_net_set_socket_nonblock(sock);
200 /* Add ourselves also to the socket table. The entry allocated above
201 is sent as argument for fast referencing in the future. */
202 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
203 server->sockets[sock] = newsocket;
205 /* Perform name and address lookups to resolve the listenning address
207 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
209 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
211 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
212 newsocket->hostname ? newsocket->hostname :
213 newsocket->ip ? newsocket->ip : ""));
214 server->stat.conn_failures++;
217 if (!newsocket->hostname)
218 newsocket->hostname = strdup(newsocket->ip);
220 newsocket->port = silc_net_get_local_port(sock);
222 /* Create a Server ID for the server. */
223 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
228 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
229 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
230 server->id_type = SILC_ID_SERVER;
231 server->server_name = server->config->server_info->server_name;
233 /* Add ourselves to the server list. We don't have a router yet
234 beacuse we haven't established a route yet. It will be done later.
235 For now, NULL is sent as router. This allocates new entry to
238 silc_idlist_add_server(server->local_list, strdup(server->server_name),
239 server->server_type, server->id, NULL, NULL);
241 SILC_LOG_ERROR(("Could not add ourselves to cache"));
244 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
246 /* Put the allocated socket pointer also to the entry allocated above
247 for fast back-referencing to the socket list. */
248 newsocket->user_data = (void *)id_entry;
249 id_entry->connection = (void *)newsocket;
250 server->id_entry = id_entry;
253 /* Register protocols */
254 silc_server_protocols_register();
256 /* Initialize the scheduler. */
257 server->schedule = silc_schedule_init(server->config->param.connections_max);
258 if (!server->schedule)
261 /* Add the first task to the scheduler. This is task that is executed by
262 timeout. It expires as soon as the caller calls silc_server_run. This
263 task performs authentication protocol and key exchange with our
265 silc_schedule_task_add(server->schedule, sock,
266 silc_server_connect_to_router,
267 (void *)server, 0, 1,
269 SILC_TASK_PRI_NORMAL);
271 /* Add listener task to the scheduler. This task receives new connections
272 to the server. This task remains on the queue until the end of the
274 silc_schedule_task_add(server->schedule, sock,
275 silc_server_accept_new_connection,
276 (void *)server, 0, 0,
278 SILC_TASK_PRI_NORMAL);
279 server->listenning = TRUE;
281 /* Send log file configuration */
282 silc_server_config_setlogfiles(server);
284 /* If server connections has been configured then we must be router as
285 normal server cannot have server connections, only router connections. */
286 if (server->config->servers) {
287 SilcServerConfigServer *ptr = server->config->servers;
289 server->server_type = SILC_ROUTER;
291 if (ptr->backup_router) {
292 server->server_type = SILC_BACKUP_ROUTER;
293 server->backup_router = TRUE;
294 server->id_entry->server_type = SILC_BACKUP_ROUTER;
301 /* Register the ID Cache purge task. This periodically purges the ID cache
302 and removes the expired cache entries. */
304 /* Clients local list */
305 purge = silc_calloc(1, sizeof(*purge));
306 purge->cache = server->local_list->clients;
307 purge->schedule = server->schedule;
308 purge->timeout = 600;
309 silc_schedule_task_add(purge->schedule, 0,
311 (void *)purge, purge->timeout, 0,
312 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
314 /* Clients global list */
315 purge = silc_calloc(1, sizeof(*purge));
316 purge->cache = server->global_list->clients;
317 purge->schedule = server->schedule;
318 purge->timeout = 300;
319 silc_schedule_task_add(purge->schedule, 0,
321 (void *)purge, purge->timeout, 0,
322 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
324 SILC_LOG_DEBUG(("Server initialized"));
326 /* We are done here, return succesfully */
330 silc_net_close_server(sock);
334 /* Fork server to background */
336 void silc_server_daemonise(SilcServer server)
340 SILC_LOG_DEBUG(("Forking SILC server to background"));
345 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
350 SILC_LOG_DEBUG(("Server started as user"));
352 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
358 /* Drop root privligies. If this cannot be done, die. */
360 void silc_server_drop(SilcServer server)
362 /* Are we executing silcd as root or a regular user? */
368 /* Get the values given for user and group in configuration file */
369 user = server->config->server_info->user;
370 group = server->config->server_info->group;
372 if (!user || !group) {
373 fprintf(stderr, "Error:" /* XXX update this error message */
374 "\tSILC server must not be run as root. For the security of your\n"
375 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
376 "\tuser account. Modify the [Identity] configuration section to run\n"
377 "\tthe server as non-root user.\n");
381 /* Check whether the user/group does not begin with a number */
382 if (isdigit(user[0]) || isdigit(group[0])) {
383 SILC_LOG_DEBUG(("User and/or group starts with a number"));
384 fprintf(stderr, "Invalid user and/or group information\n");
385 fprintf(stderr, "Please assign them as names, not numbers\n");
389 if (!(pw = getpwnam(user))) {
390 fprintf(stderr, "Error: No such user %s found.\n", user);
393 if (!(gr = getgrnam(group))) {
394 fprintf(stderr, "Error: No such group %s found.\n", group);
398 /* Check whether user and/or group is set to root. If yes, exit
399 immediately. Otherwise, setgid and setuid server to user.group */
400 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
401 fprintf(stderr, "Error:"
402 "\tSILC server must not be run as root. For the security of your\n"
403 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
404 "\tuser account. Modify the [Identity] configuration section to run\n"
405 "\tthe server as non-root user.\n");
409 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
410 if (setgid(gr->gr_gid) != 0) {
411 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
415 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
416 SILC_LOG_DEBUG(("Removing supplementary groups"));
417 if (setgroups(0, NULL) != 0) {
418 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
421 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
422 if (initgroups(user, gr->gr_gid) != 0) {
423 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
424 "Exiting.\n", user, gr->gr_gid);
428 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
429 if (setuid(pw->pw_uid) != 0) {
430 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
437 /* The heart of the server. This runs the scheduler thus runs the server.
438 When this returns the server has been stopped and the program will
441 void silc_server_run(SilcServer server)
443 SILC_LOG_DEBUG(("Running server"));
445 SILC_LOG_INFO(("SILC Server started"));
447 /* Start the scheduler, the heart of the SILC server. When this returns
448 the program will be terminated. */
449 silc_schedule(server->schedule);
452 /* Stops the SILC server. This function is used to shutdown the server.
453 This is usually called after the scheduler has returned. After stopping
454 the server one should call silc_server_free. */
456 void silc_server_stop(SilcServer server)
458 SILC_LOG_DEBUG(("Stopping server"));
460 if (server->schedule) {
461 silc_schedule_stop(server->schedule);
462 silc_schedule_uninit(server->schedule);
463 server->schedule = NULL;
466 silc_server_protocols_unregister();
468 SILC_LOG_DEBUG(("Server stopped"));
471 /* Function that is called when the network connection to a router has
472 been established. This will continue with the key exchange protocol
473 with the remote router. */
475 void silc_server_start_key_exchange(SilcServer server,
476 SilcServerConnection sconn,
479 SilcSocketConnection newsocket;
480 SilcProtocol protocol;
481 SilcServerKEInternalContext *proto_ctx;
482 SilcServerConfigRouter *conn = sconn->conn;
485 /* Cancel any possible retry timeouts */
486 silc_schedule_task_del_by_callback(server->schedule,
487 silc_server_connect_router);
489 /* Set socket options */
490 silc_net_set_socket_nonblock(sock);
491 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
493 /* Create socket connection for the connection. Even though we
494 know that we are connecting to a router we will mark the socket
495 to be unknown connection until we have executed authentication
497 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
498 server->sockets[sock] = newsocket;
499 newsocket->hostname = strdup(sconn->remote_host);
500 newsocket->ip = strdup(sconn->remote_host);
501 newsocket->port = sconn->remote_port;
502 sconn->sock = newsocket;
504 /* Allocate internal protocol context. This is sent as context
506 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
507 proto_ctx->server = (void *)server;
508 proto_ctx->context = (void *)sconn;
509 proto_ctx->sock = newsocket;
510 proto_ctx->rng = server->rng;
511 proto_ctx->responder = FALSE;
513 /* Set Key Exchange flags from configuration, but fall back to global
515 SILC_GET_SKE_FLAGS(conn, proto_ctx);
516 if (server->config->param.key_exchange_pfs)
517 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
519 /* Perform key exchange protocol. silc_server_connect_to_router_second
520 will be called after the protocol is finished. */
521 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
522 &protocol, proto_ctx,
523 silc_server_connect_to_router_second);
524 newsocket->protocol = protocol;
526 /* Register a timeout task that will be executed if the protocol
527 is not executed within set limit. */
528 proto_ctx->timeout_task =
529 silc_schedule_task_add(server->schedule, sock,
530 silc_server_timeout_remote,
531 server, server->config->key_exchange_timeout, 0,
535 /* Register the connection for network input and output. This sets
536 that scheduler will listen for incoming packets for this connection
537 and sets that outgoing packets may be sent to this connection as
538 well. However, this doesn't set the scheduler for outgoing traffic,
539 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
540 later when outgoing data is available. */
541 context = (void *)server;
542 SILC_REGISTER_CONNECTION_FOR_IO(sock);
544 /* Run the protocol */
545 silc_protocol_execute(protocol, server->schedule, 0, 0);
548 /* Timeout callback that will be called to retry connecting to remote
549 router. This is used by both normal and router server. This will wait
550 before retrying the connecting. The timeout is generated by exponential
551 backoff algorithm. */
553 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
555 SilcServerConnection sconn = (SilcServerConnection)context;
556 SilcServer server = sconn->server;
557 SilcServerConfigConnParams *param =
558 (sconn->param ? sconn->param : &server->config->param);
560 SILC_LOG_INFO(("Retrying connecting to a router"));
562 /* Calculate next timeout */
563 if (sconn->retry_count >= 1) {
564 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
565 if (sconn->retry_timeout > param->reconnect_interval_max)
566 sconn->retry_timeout = param->reconnect_interval_max;
568 sconn->retry_timeout = param->reconnect_interval;
570 sconn->retry_count++;
571 sconn->retry_timeout = sconn->retry_timeout +
572 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
574 /* If we've reached max retry count, give up. */
575 if (sconn->retry_count > param->reconnect_count &&
576 param->reconnect_keep_trying == FALSE) {
577 SILC_LOG_ERROR(("Could not connect to router, giving up"));
578 silc_free(sconn->remote_host);
583 /* Wait one before retrying */
584 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
585 context, sconn->retry_timeout, 0,
586 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
589 /* Generic routine to use connect to a router. */
591 SILC_TASK_CALLBACK(silc_server_connect_router)
593 SilcServerConnection sconn = (SilcServerConnection)context;
594 SilcServer server = sconn->server;
597 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
598 (sconn->backup ? "backup router" : "router"),
599 sconn->remote_host, sconn->remote_port));
601 server->router_connect = time(NULL);
603 /* Connect to remote host */
604 sock = silc_net_create_connection(server->config->server_info->server_ip,
608 SILC_LOG_ERROR(("Could not connect to router %s:%d",
609 sconn->remote_host, sconn->remote_port));
610 if (!sconn->no_reconnect)
611 silc_schedule_task_add(server->schedule, fd,
612 silc_server_connect_to_router_retry,
613 context, 0, 1, SILC_TASK_TIMEOUT,
614 SILC_TASK_PRI_NORMAL);
618 /* Continue with key exchange protocol */
619 silc_server_start_key_exchange(server, sconn, sock);
622 /* This function connects to our primary router or if we are a router this
623 establishes all our primary routes. This is called at the start of the
624 server to do authentication and key exchange with our router - called
627 SILC_TASK_CALLBACK(silc_server_connect_to_router)
629 SilcServer server = (SilcServer)context;
630 SilcServerConnection sconn;
631 SilcServerConfigRouter *ptr;
633 SILC_LOG_DEBUG(("Connecting to router(s)"));
635 if (server->server_type == SILC_SERVER) {
636 SILC_LOG_DEBUG(("We are normal server"));
637 } else if (server->server_type == SILC_ROUTER) {
638 SILC_LOG_DEBUG(("We are router"));
640 SILC_LOG_DEBUG(("We are backup router/normal server"));
643 /* Create the connections to all our routes */
644 ptr = server->config->routers;
647 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
648 ptr->backup_router ? "Backup router" : "Router",
649 ptr->initiator ? "Initiator" : "Responder",
650 ptr->host, ptr->port));
652 if (ptr->initiator) {
653 /* Allocate connection object for hold connection specific stuff. */
654 sconn = silc_calloc(1, sizeof(*sconn));
655 sconn->server = server;
656 sconn->remote_host = strdup(ptr->host);
657 sconn->remote_port = ptr->port;
658 sconn->backup = ptr->backup_router;
660 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
661 sconn->backup_replace_port = ptr->backup_replace_port;
664 if (!server->router_conn && !sconn->backup)
665 server->router_conn = sconn;
668 sconn->param = ptr->param;
670 silc_schedule_task_add(server->schedule, fd,
671 silc_server_connect_router,
672 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
673 SILC_TASK_PRI_NORMAL);
682 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
684 /* There wasn't a configured router, we will continue but we don't
685 have a connection to outside world. We will be standalone server. */
686 server->standalone = TRUE;
689 /* Second part of connecting to router(s). Key exchange protocol has been
690 executed and now we will execute authentication protocol. */
692 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
694 SilcProtocol protocol = (SilcProtocol)context;
695 SilcServerKEInternalContext *ctx =
696 (SilcServerKEInternalContext *)protocol->context;
697 SilcServer server = (SilcServer)ctx->server;
698 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
699 SilcSocketConnection sock = ctx->sock;
700 SilcServerConnAuthInternalContext *proto_ctx;
701 SilcServerConfigRouter *conn = NULL;
703 SILC_LOG_DEBUG(("Start"));
705 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
706 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
707 /* Error occured during protocol */
708 silc_protocol_free(protocol);
709 sock->protocol = NULL;
710 silc_ske_free_key_material(ctx->keymat);
712 silc_packet_context_free(ctx->packet);
714 silc_ske_free(ctx->ske);
715 silc_free(ctx->dest_id);
717 silc_schedule_task_del_by_callback(server->schedule,
718 silc_server_failure_callback);
719 silc_server_disconnect_remote(server, sock, "Server closed connection: "
720 "Key exchange failed");
724 /* We now have the key material as the result of the key exchange
725 protocol. Take the key material into use. Free the raw key material
726 as soon as we've set them into use. */
727 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
728 ctx->sock, ctx->keymat,
729 ctx->ske->prop->cipher,
730 ctx->ske->prop->pkcs,
731 ctx->ske->prop->hash,
732 ctx->ske->prop->hmac,
733 ctx->ske->prop->group,
735 silc_protocol_free(protocol);
736 sock->protocol = NULL;
737 silc_ske_free_key_material(ctx->keymat);
739 silc_packet_context_free(ctx->packet);
741 silc_ske_free(ctx->ske);
742 silc_free(ctx->dest_id);
744 silc_schedule_task_del_by_callback(server->schedule,
745 silc_server_failure_callback);
746 silc_server_disconnect_remote(server, sock, "Server closed connection: "
747 "Key exchange failed");
750 silc_ske_free_key_material(ctx->keymat);
752 /* Allocate internal context for the authentication protocol. This
753 is sent as context for the protocol. */
754 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
755 proto_ctx->server = (void *)server;
756 proto_ctx->context = (void *)sconn;
757 proto_ctx->sock = sock;
758 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
759 proto_ctx->dest_id_type = ctx->dest_id_type;
760 proto_ctx->dest_id = ctx->dest_id;
762 /* Resolve the authentication method used in this connection. Check if
763 we find a match from user configured connections */
765 conn = silc_server_config_find_router_conn(server, sock->hostname,
771 /* Match found. Use the configured authentication method. Take only
772 the passphrase, since for public key auth we automatically use
773 our local key pair. */
774 if (conn->passphrase) {
775 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
776 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
778 proto_ctx->auth_data = strdup(conn->passphrase);
779 proto_ctx->auth_data_len = strlen(conn->passphrase);
780 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
782 } else if (conn->publickeys) {
783 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
785 proto_ctx->auth_meth = SILC_AUTH_NONE;
788 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
789 sock->hostname, sock->ip, sock->port));
790 silc_protocol_free(protocol);
791 sock->protocol = NULL;
793 silc_packet_context_free(ctx->packet);
795 silc_ske_free(ctx->ske);
796 silc_free(ctx->dest_id);
798 silc_schedule_task_del_by_callback(server->schedule,
799 silc_server_failure_callback);
800 silc_server_disconnect_remote(server, sock, "Server closed connection: "
801 "Key exchange failed");
805 /* Free old protocol as it is finished now */
806 silc_protocol_free(protocol);
808 silc_packet_context_free(ctx->packet);
810 sock->protocol = NULL;
812 /* Allocate the authentication protocol. This is allocated here
813 but we won't start it yet. We will be receiving party of this
814 protocol thus we will wait that connecting party will make
816 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
817 &sock->protocol, proto_ctx,
818 silc_server_connect_to_router_final);
820 /* Register timeout task. If the protocol is not executed inside
821 this timelimit the connection will be terminated. */
822 proto_ctx->timeout_task =
823 silc_schedule_task_add(server->schedule, sock->sock,
824 silc_server_timeout_remote,
826 server->config->conn_auth_timeout, 0,
830 /* Run the protocol */
831 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
834 /* Finalizes the connection to router. Registers a server task to the
835 queue so that we can accept new connections. */
837 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
839 SilcProtocol protocol = (SilcProtocol)context;
840 SilcServerConnAuthInternalContext *ctx =
841 (SilcServerConnAuthInternalContext *)protocol->context;
842 SilcServer server = (SilcServer)ctx->server;
843 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
844 SilcSocketConnection sock = ctx->sock;
845 SilcServerEntry id_entry;
847 SilcServerHBContext hb_context;
848 unsigned char *id_string;
850 SilcIDListData idata;
851 SilcServerConfigConnParams *param;
853 SILC_LOG_DEBUG(("Start"));
855 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
856 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
857 /* Error occured during protocol */
858 silc_free(ctx->dest_id);
859 silc_server_disconnect_remote(server, sock, "Server closed connection: "
860 "Authentication failed");
864 /* Add a task to the queue. This task receives new connections to the
865 server. This task remains on the queue until the end of the program. */
866 if (!server->listenning && !sconn->backup) {
867 silc_schedule_task_add(server->schedule, server->sock,
868 silc_server_accept_new_connection,
869 (void *)server, 0, 0,
871 SILC_TASK_PRI_NORMAL);
872 server->listenning = TRUE;
875 /* Send NEW_SERVER packet to the router. We will become registered
876 to the SILC network after sending this packet. */
877 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
878 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
879 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
880 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
881 silc_buffer_format(packet,
882 SILC_STR_UI_SHORT(id_len),
883 SILC_STR_UI_XNSTRING(id_string, id_len),
884 SILC_STR_UI_SHORT(strlen(server->server_name)),
885 SILC_STR_UI_XNSTRING(server->server_name,
886 strlen(server->server_name)),
889 /* Send the packet */
890 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
891 packet->data, packet->len, TRUE);
892 silc_buffer_free(packet);
893 silc_free(id_string);
895 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
897 /* Check that we do not have this ID already */
898 id_entry = silc_idlist_find_server_by_id(server->local_list,
899 ctx->dest_id, TRUE, NULL);
901 silc_idcache_del_by_context(server->local_list->servers, id_entry);
903 id_entry = silc_idlist_find_server_by_id(server->global_list,
904 ctx->dest_id, TRUE, NULL);
906 silc_idcache_del_by_context(server->global_list->servers, id_entry);
909 SILC_LOG_DEBUG(("New server id(%s)",
910 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
912 /* Add the connected router to global server list */
913 id_entry = silc_idlist_add_server(server->global_list,
914 strdup(sock->hostname),
915 SILC_ROUTER, ctx->dest_id, NULL, sock);
917 silc_free(ctx->dest_id);
918 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
919 silc_server_disconnect_remote(server, sock, "Server closed connection: "
920 "Authentication failed");
924 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
925 silc_free(sock->user_data);
926 sock->user_data = (void *)id_entry;
927 sock->type = SILC_SOCKET_TYPE_ROUTER;
928 idata = (SilcIDListData)sock->user_data;
929 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
931 param = (sconn->param ? sconn->param : &server->config->param);
933 /* Perform keepalive. The `hb_context' will be freed automatically
934 when finally calling the silc_socket_free function. */
935 hb_context = silc_calloc(1, sizeof(*hb_context));
936 hb_context->server = server;
937 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
938 silc_server_perform_heartbeat,
941 /* Register re-key timeout */
942 idata->rekey->timeout = param->key_exchange_rekey;
943 idata->rekey->context = (void *)server;
944 silc_schedule_task_add(server->schedule, sock->sock,
945 silc_server_rekey_callback,
946 (void *)sock, idata->rekey->timeout, 0,
947 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
949 if (!sconn->backup) {
950 /* Mark this router our primary router if we're still standalone */
951 if (server->standalone) {
952 server->id_entry->router = id_entry;
953 server->router = id_entry;
954 server->standalone = FALSE;
956 /* If we are router then announce our possible servers. */
957 if (server->server_type == SILC_ROUTER)
958 silc_server_announce_servers(server, FALSE, 0,
959 server->router->connection);
961 /* Announce our clients and channels to the router */
962 silc_server_announce_clients(server, 0, server->router->connection);
963 silc_server_announce_channels(server, 0, server->router->connection);
966 /* Add this server to be our backup router */
967 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
968 sconn->backup_replace_port, FALSE);
971 sock->protocol = NULL;
973 /* Call the completion callback to indicate that we've connected to
976 (*sconn->callback)(server, id_entry, sconn->callback_context);
979 /* Free the temporary connection data context */
981 silc_free(sconn->remote_host);
982 silc_free(sconn->backup_replace_ip);
985 if (sconn == server->router_conn)
986 server->router_conn = NULL;
988 /* Free the protocol object */
989 if (sock->protocol == protocol)
990 sock->protocol = NULL;
991 silc_protocol_free(protocol);
993 silc_packet_context_free(ctx->packet);
995 silc_ske_free(ctx->ske);
996 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
997 silc_free(ctx->auth_data);
1001 /* Host lookup callbcak that is called after the incoming connection's
1002 IP and FQDN lookup is performed. This will actually check the acceptance
1003 of the incoming connection and will register the key exchange protocol
1004 for this connection. */
1007 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1010 SilcServer server = (SilcServer)context;
1011 SilcServerKEInternalContext *proto_ctx;
1012 SilcServerConfigClient *cconfig = NULL;
1013 SilcServerConfigServer *sconfig = NULL;
1014 SilcServerConfigRouter *rconfig = NULL;
1015 SilcServerConfigDeny *deny;
1018 SILC_LOG_DEBUG(("Start"));
1020 /* Check whether we could resolve both IP and FQDN. */
1021 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1022 server->config->require_reverse_lookup)) {
1023 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1024 sock->hostname ? sock->hostname :
1025 sock->ip ? sock->ip : ""));
1026 server->stat.conn_failures++;
1027 silc_server_disconnect_remote(server, sock,
1028 "Server closed connection: Unknown host");
1032 /* Register the connection for network input and output. This sets
1033 that scheduler will listen for incoming packets for this connection
1034 and sets that outgoing packets may be sent to this connection as well.
1035 However, this doesn't set the scheduler for outgoing traffic, it
1036 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1037 later when outgoing data is available. */
1038 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1040 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1043 port = server->sockets[server->sock]->port; /* Listenning port */
1045 /* Check whether this connection is denied to connect to us. */
1046 deny = silc_server_config_find_denied(server, sock->ip);
1048 deny = silc_server_config_find_denied(server, sock->hostname);
1050 /* The connection is denied */
1051 SILC_LOG_INFO(("Connection %s (%s) is denied",
1052 sock->hostname, sock->ip));
1053 silc_server_disconnect_remote(server, sock, deny->reason ?
1055 "Server closed connection: "
1056 "Connection refused");
1057 server->stat.conn_failures++;
1061 /* Check whether we have configred this sort of connection at all. We
1062 have to check all configurations since we don't know what type of
1063 connection this is. */
1064 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1065 cconfig = silc_server_config_find_client(server, sock->hostname);
1066 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1067 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1068 if (server->server_type == SILC_ROUTER) {
1069 if (!(rconfig = silc_server_config_find_router_conn(server,
1071 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1074 if (!cconfig && !sconfig && !rconfig) {
1075 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1077 silc_server_disconnect_remote(server, sock,
1078 "Server closed connection: "
1079 "Connection refused");
1080 server->stat.conn_failures++;
1084 /* The connection is allowed */
1086 /* Allocate internal context for key exchange protocol. This is
1087 sent as context for the protocol. */
1088 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1089 proto_ctx->server = context;
1090 proto_ctx->sock = sock;
1091 proto_ctx->rng = server->rng;
1092 proto_ctx->responder = TRUE;
1093 proto_ctx->cconfig = cconfig;
1094 proto_ctx->sconfig = sconfig;
1095 proto_ctx->rconfig = rconfig;
1097 /* Take flags for key exchange. Since we do not know what type of connection
1098 this is, we go through all found configuratios and use the global ones
1099 as well. This will result always into strictest key exchange flags. */
1100 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1101 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1102 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1103 if (server->config->param.key_exchange_pfs)
1104 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1106 /* Prepare the connection for key exchange protocol. We allocate the
1107 protocol but will not start it yet. The connector will be the
1108 initiator of the protocol thus we will wait for initiation from
1109 there before we start the protocol. */
1110 server->stat.auth_attempts++;
1111 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1112 &sock->protocol, proto_ctx,
1113 silc_server_accept_new_connection_second);
1115 /* Register a timeout task that will be executed if the connector
1116 will not start the key exchange protocol within specified timeout
1117 and the connection will be closed. */
1118 proto_ctx->timeout_task =
1119 silc_schedule_task_add(server->schedule, sock->sock,
1120 silc_server_timeout_remote,
1121 context, server->config->key_exchange_timeout, 0,
1126 /* Accepts new connections to the server. Accepting new connections are
1127 done in three parts to make it async. */
1129 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1131 SilcServer server = (SilcServer)context;
1132 SilcSocketConnection newsocket;
1135 SILC_LOG_DEBUG(("Accepting new connection"));
1137 server->stat.conn_attempts++;
1139 sock = silc_net_accept_connection(server->sock);
1141 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1142 server->stat.conn_failures++;
1146 /* Check for maximum allowed connections */
1147 if (sock > server->config->param.connections_max) {
1148 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1149 server->stat.conn_failures++;
1153 /* Set socket options */
1154 silc_net_set_socket_nonblock(sock);
1155 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1157 /* We don't create a ID yet, since we don't know what type of connection
1158 this is yet. But, we do add the connection to the socket table. */
1159 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1160 server->sockets[sock] = newsocket;
1162 /* Perform asynchronous host lookup. This will lookup the IP and the
1163 FQDN of the remote connection. After the lookup is done the connection
1164 is accepted further. */
1165 silc_socket_host_lookup(newsocket, TRUE,
1166 silc_server_accept_new_connection_lookup, context,
1170 /* Second part of accepting new connection. Key exchange protocol has been
1171 performed and now it is time to do little connection authentication
1172 protocol to figure out whether this connection is client or server
1173 and whether it has right to access this server (especially server
1174 connections needs to be authenticated). */
1176 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1178 SilcProtocol protocol = (SilcProtocol)context;
1179 SilcServerKEInternalContext *ctx =
1180 (SilcServerKEInternalContext *)protocol->context;
1181 SilcServer server = (SilcServer)ctx->server;
1182 SilcSocketConnection sock = ctx->sock;
1183 SilcServerConnAuthInternalContext *proto_ctx;
1185 SILC_LOG_DEBUG(("Start"));
1187 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1188 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1189 /* Error occured during protocol */
1190 silc_protocol_free(protocol);
1191 sock->protocol = NULL;
1192 silc_ske_free_key_material(ctx->keymat);
1194 silc_packet_context_free(ctx->packet);
1196 silc_ske_free(ctx->ske);
1197 silc_free(ctx->dest_id);
1199 silc_schedule_task_del_by_callback(server->schedule,
1200 silc_server_failure_callback);
1201 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1202 "Key exchange failed");
1203 server->stat.auth_failures++;
1207 /* We now have the key material as the result of the key exchange
1208 protocol. Take the key material into use. Free the raw key material
1209 as soon as we've set them into use. */
1210 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1211 ctx->sock, ctx->keymat,
1212 ctx->ske->prop->cipher,
1213 ctx->ske->prop->pkcs,
1214 ctx->ske->prop->hash,
1215 ctx->ske->prop->hmac,
1216 ctx->ske->prop->group,
1218 silc_protocol_free(protocol);
1219 sock->protocol = NULL;
1220 silc_ske_free_key_material(ctx->keymat);
1222 silc_packet_context_free(ctx->packet);
1224 silc_ske_free(ctx->ske);
1225 silc_free(ctx->dest_id);
1227 silc_schedule_task_del_by_callback(server->schedule,
1228 silc_server_failure_callback);
1229 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1230 "Key exchange failed");
1231 server->stat.auth_failures++;
1234 silc_ske_free_key_material(ctx->keymat);
1236 /* Allocate internal context for the authentication protocol. This
1237 is sent as context for the protocol. */
1238 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1239 proto_ctx->server = (void *)server;
1240 proto_ctx->sock = sock;
1241 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1242 proto_ctx->responder = TRUE;
1243 proto_ctx->dest_id_type = ctx->dest_id_type;
1244 proto_ctx->dest_id = ctx->dest_id;
1245 proto_ctx->cconfig = ctx->cconfig;
1246 proto_ctx->sconfig = ctx->sconfig;
1247 proto_ctx->rconfig = ctx->rconfig;
1249 /* Free old protocol as it is finished now */
1250 silc_protocol_free(protocol);
1252 silc_packet_context_free(ctx->packet);
1254 sock->protocol = NULL;
1256 /* Allocate the authentication protocol. This is allocated here
1257 but we won't start it yet. We will be receiving party of this
1258 protocol thus we will wait that connecting party will make
1259 their first move. */
1260 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1261 &sock->protocol, proto_ctx,
1262 silc_server_accept_new_connection_final);
1264 /* Register timeout task. If the protocol is not executed inside
1265 this timelimit the connection will be terminated. */
1266 proto_ctx->timeout_task =
1267 silc_schedule_task_add(server->schedule, sock->sock,
1268 silc_server_timeout_remote,
1270 server->config->conn_auth_timeout, 0,
1275 /* Final part of accepting new connection. The connection has now
1276 been authenticated and keys has been exchanged. We also know whether
1277 this is client or server connection. */
1279 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1281 SilcProtocol protocol = (SilcProtocol)context;
1282 SilcServerConnAuthInternalContext *ctx =
1283 (SilcServerConnAuthInternalContext *)protocol->context;
1284 SilcServer server = (SilcServer)ctx->server;
1285 SilcSocketConnection sock = ctx->sock;
1286 SilcServerHBContext hb_context;
1287 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1289 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
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 switch (ctx->conn_type) {
1315 case SILC_SOCKET_TYPE_CLIENT:
1317 SilcClientEntry client;
1318 SilcServerConfigClient *conn = ctx->cconfig;
1320 /* Verify whether this connection is after all allowed to connect */
1321 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1322 &server->config->param,
1323 conn->param, ctx->ske)) {
1324 server->stat.auth_failures++;
1328 SILC_LOG_DEBUG(("Remote host is client"));
1329 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1332 /* Add the client to the client ID cache. The nickname and Client ID
1333 and other information is created after we have received NEW_CLIENT
1334 packet from client. */
1335 client = silc_idlist_add_client(server->local_list,
1336 NULL, NULL, NULL, NULL, NULL, sock, 0);
1338 SILC_LOG_ERROR(("Could not add new client to cache"));
1339 silc_free(sock->user_data);
1340 silc_server_disconnect_remote(server, sock,
1341 "Server closed connection: "
1342 "Authentication failed");
1343 server->stat.auth_failures++;
1348 server->stat.my_clients++;
1349 server->stat.clients++;
1350 if (server->server_type == SILC_ROUTER)
1351 server->stat.cell_clients++;
1353 /* Get connection parameters */
1355 if (conn->param->keepalive_secs)
1356 hearbeat_timeout = conn->param->keepalive_secs;
1359 id_entry = (void *)client;
1362 case SILC_SOCKET_TYPE_SERVER:
1363 case SILC_SOCKET_TYPE_ROUTER:
1365 SilcServerEntry new_server;
1366 bool initiator = FALSE;
1367 bool backup_local = FALSE;
1368 bool backup_router = FALSE;
1369 char *backup_replace_ip = NULL;
1370 SilcUInt16 backup_replace_port = 0;
1371 SilcServerConfigServer *sconn = ctx->sconfig;
1372 SilcServerConfigRouter *rconn = ctx->rconfig;
1374 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1375 /* Verify whether this connection is after all allowed to connect */
1376 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1377 &server->config->param,
1378 rconn ? rconn->param : NULL,
1380 server->stat.auth_failures++;
1386 if (rconn->param->keepalive_secs)
1387 hearbeat_timeout = rconn->param->keepalive_secs;
1390 initiator = rconn->initiator;
1391 backup_local = rconn->backup_local;
1392 backup_router = rconn->backup_router;
1393 backup_replace_ip = rconn->backup_replace_ip;
1394 backup_replace_port = rconn->backup_replace_port;
1398 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1399 /* Verify whether this connection is after all allowed to connect */
1400 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1401 &server->config->param,
1402 sconn ? sconn->param : NULL,
1404 server->stat.auth_failures++;
1409 if (sconn->param->keepalive_secs)
1410 hearbeat_timeout = sconn->param->keepalive_secs;
1413 backup_router = sconn->backup_router;
1417 SILC_LOG_DEBUG(("Remote host is %s",
1418 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1419 "server" : (backup_router ?
1420 "backup router" : "router")));
1421 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1422 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1423 "server" : (backup_router ?
1424 "backup router" : "router")));
1426 /* Add the server into server cache. The server name and Server ID
1427 is updated after we have received NEW_SERVER packet from the
1428 server. We mark ourselves as router for this server if we really
1431 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1432 server->local_list : (backup_router ?
1433 server->local_list :
1434 server->global_list)),
1436 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1437 SILC_SERVER : SILC_ROUTER),
1439 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1440 server->id_entry : (backup_router ?
1441 server->id_entry : NULL)),
1444 SILC_LOG_ERROR(("Could not add new server to cache"));
1445 silc_free(sock->user_data);
1446 silc_server_disconnect_remote(server, sock,
1447 "Server closed connection: "
1448 "Authentication failed");
1449 server->stat.auth_failures++;
1454 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1455 server->stat.my_servers++;
1457 server->stat.my_routers++;
1458 server->stat.servers++;
1460 id_entry = (void *)new_server;
1462 /* If the incoming connection is router and marked as backup router
1463 then add it to be one of our backups */
1464 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1465 silc_server_backup_add(server, new_server, backup_replace_ip,
1466 backup_replace_port, backup_local);
1468 /* Change it back to SERVER type since that's what it really is. */
1470 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1472 new_server->server_type = SILC_BACKUP_ROUTER;
1475 /* Check whether this connection is to be our primary router connection
1476 if we do not already have the primary route. */
1477 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1478 if (silc_server_config_is_primary_route(server) && !initiator)
1481 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1482 server->standalone = FALSE;
1483 if (!server->id_entry->router) {
1484 server->id_entry->router = id_entry;
1485 server->router = id_entry;
1496 sock->type = ctx->conn_type;
1498 /* Add the common data structure to the ID entry. */
1499 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1501 /* Add to sockets internal pointer for fast referencing */
1502 silc_free(sock->user_data);
1503 sock->user_data = id_entry;
1505 /* Connection has been fully established now. Everything is ok. */
1506 SILC_LOG_DEBUG(("New connection authenticated"));
1508 /* Perform keepalive. The `hb_context' will be freed automatically
1509 when finally calling the silc_socket_free function. */
1510 hb_context = silc_calloc(1, sizeof(*hb_context));
1511 hb_context->server = server;
1512 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1513 silc_server_perform_heartbeat,
1517 silc_schedule_task_del_by_callback(server->schedule,
1518 silc_server_failure_callback);
1519 silc_protocol_free(protocol);
1521 silc_packet_context_free(ctx->packet);
1523 silc_ske_free(ctx->ske);
1524 silc_free(ctx->dest_id);
1526 sock->protocol = NULL;
1529 /* This function is used to read packets from network and send packets to
1530 network. This is usually a generic task. */
1532 SILC_TASK_CALLBACK(silc_server_packet_process)
1534 SilcServer server = (SilcServer)context;
1535 SilcSocketConnection sock = server->sockets[fd];
1536 SilcIDListData idata;
1537 SilcCipher cipher = NULL;
1538 SilcHmac hmac = NULL;
1539 SilcUInt32 sequence = 0;
1545 SILC_LOG_DEBUG(("Processing packet"));
1547 /* Packet sending */
1549 if (type == SILC_TASK_WRITE) {
1550 /* Do not send data to disconnected connection */
1551 if (SILC_IS_DISCONNECTED(sock))
1554 server->stat.packets_sent++;
1556 if (sock->outbuf->data - sock->outbuf->head)
1557 silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1559 /* Send the packet */
1560 ret = silc_packet_send(sock, TRUE);
1562 /* If returned -2 could not write to connection now, will do
1568 SILC_LOG_ERROR(("Error sending packet to connection "
1569 "%s:%d [%s]", sock->hostname, sock->port,
1570 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1571 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1572 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1577 /* The packet has been sent and now it is time to set the connection
1578 back to only for input. When there is again some outgoing data
1579 available for this connection it will be set for output as well.
1580 This call clears the output setting and sets it only for input. */
1581 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1582 SILC_UNSET_OUTBUF_PENDING(sock);
1584 silc_buffer_clear(sock->outbuf);
1588 /* Packet receiving */
1590 /* Read some data from connection */
1591 ret = silc_packet_receive(sock);
1595 SILC_LOG_ERROR(("Error receiving packet from connection "
1596 "%s:%d [%s] %s", sock->hostname, sock->port,
1597 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1598 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1599 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1600 "Router"), strerror(errno)));
1606 SILC_LOG_DEBUG(("Read EOF"));
1608 /* If connection is disconnecting already we will finally
1609 close the connection */
1610 if (SILC_IS_DISCONNECTING(sock)) {
1611 if (sock->user_data)
1612 silc_server_free_sock_user_data(server, sock, NULL);
1613 silc_server_close_connection(server, sock);
1617 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1618 SILC_SET_DISCONNECTING(sock);
1620 if (sock->user_data) {
1622 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1623 silc_server_free_sock_user_data(server, sock, tmp);
1625 silc_server_free_sock_user_data(server, sock, NULL);
1626 } else if (server->router_conn && server->router_conn->sock == sock &&
1627 !server->router && server->standalone)
1628 silc_schedule_task_add(server->schedule, 0,
1629 silc_server_connect_to_router,
1632 SILC_TASK_PRI_NORMAL);
1634 silc_server_close_connection(server, sock);
1638 /* If connection is disconnecting or disconnected we will ignore
1640 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1641 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1645 server->stat.packets_received++;
1647 /* Get keys and stuff from ID entry */
1648 idata = (SilcIDListData)sock->user_data;
1650 cipher = idata->receive_key;
1651 hmac = idata->hmac_receive;
1652 sequence = idata->psn_receive;
1655 /* Process the packet. This will call the parser that will then
1656 decrypt and parse the packet. */
1657 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1658 TRUE : FALSE, cipher, hmac, sequence,
1659 silc_server_packet_parse, server);
1661 /* If this socket connection is not authenticated yet and the packet
1662 processing failed we will drop the connection since it can be
1663 a malicious flooder. */
1664 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1665 (!sock->protocol || sock->protocol->protocol->type ==
1666 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1667 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1668 SILC_SET_DISCONNECTING(sock);
1670 if (sock->user_data)
1671 silc_server_free_sock_user_data(server, sock, NULL);
1672 silc_server_close_connection(server, sock);
1676 /* Parses whole packet, received earlier. */
1678 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1680 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1681 SilcServer server = (SilcServer)parse_ctx->context;
1682 SilcSocketConnection sock = parse_ctx->sock;
1683 SilcPacketContext *packet = parse_ctx->packet;
1684 SilcIDListData idata = (SilcIDListData)sock->user_data;
1687 SILC_LOG_DEBUG(("Start"));
1689 /* Parse the packet */
1690 if (parse_ctx->normal)
1691 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1693 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1695 /* If entry is disabled ignore what we got. */
1696 if (ret != SILC_PACKET_RESUME_ROUTER &&
1697 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1698 SILC_LOG_DEBUG(("Connection is disabled"));
1702 if (ret == SILC_PACKET_NONE)
1705 /* Check that the the current client ID is same as in the client's packet. */
1706 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1707 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1708 if (client && client->id) {
1709 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1710 packet->src_id_type);
1711 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1719 if (server->server_type == SILC_ROUTER) {
1720 /* Route the packet if it is not destined to us. Other ID types but
1721 server are handled separately after processing them. */
1722 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1723 packet->dst_id_type == SILC_ID_SERVER &&
1724 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1725 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1727 /* Route the packet to fastest route for the destination ID */
1728 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1729 packet->dst_id_type);
1732 silc_server_packet_route(server,
1733 silc_server_route_get(server, id,
1734 packet->dst_id_type),
1741 /* Parse the incoming packet type */
1742 silc_server_packet_parse_type(server, sock, packet);
1744 if (server->server_type == SILC_ROUTER) {
1745 /* Broadcast packet if it is marked as broadcast packet and it is
1746 originated from router and we are router. */
1747 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1748 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1749 !server->standalone) {
1750 /* Broadcast to our primary route */
1751 silc_server_packet_broadcast(server, server->router->connection, packet);
1753 /* If we have backup routers then we need to feed all broadcast
1754 data to those servers. */
1755 silc_server_backup_broadcast(server, sock, packet);
1760 silc_packet_context_free(packet);
1761 silc_free(parse_ctx);
1764 /* Parser callback called by silc_packet_receive_process. This merely
1765 registers timeout that will handle the actual parsing when appropriate. */
1767 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1770 SilcServer server = (SilcServer)context;
1771 SilcSocketConnection sock = parser_context->sock;
1772 SilcIDListData idata = (SilcIDListData)sock->user_data;
1775 idata->psn_receive = parser_context->packet->sequence + 1;
1777 /* If protocol for this connection is key exchange or rekey then we'll
1778 process all packets synchronously, since there might be packets in
1779 queue that we are not able to decrypt without first processing the
1780 packets before them. */
1781 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1782 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1783 (sock->protocol && sock->protocol->protocol &&
1784 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1785 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1786 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1789 /* Reprocess data since we'll return FALSE here. This is because
1790 the idata->receive_key might have become valid in the last packet
1791 and we want to call this processor with valid cipher. */
1793 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1794 TRUE : FALSE, idata->receive_key,
1795 idata->hmac_receive, idata->psn_receive,
1796 silc_server_packet_parse, server);
1798 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1799 TRUE : FALSE, NULL, NULL, 0,
1800 silc_server_packet_parse, server);
1804 switch (sock->type) {
1805 case SILC_SOCKET_TYPE_UNKNOWN:
1806 case SILC_SOCKET_TYPE_CLIENT:
1807 /* Parse the packet with timeout */
1808 silc_schedule_task_add(server->schedule, sock->sock,
1809 silc_server_packet_parse_real,
1810 (void *)parser_context, 0, 100000,
1812 SILC_TASK_PRI_NORMAL);
1814 case SILC_SOCKET_TYPE_SERVER:
1815 case SILC_SOCKET_TYPE_ROUTER:
1816 /* Packets from servers are parsed immediately */
1817 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1827 /* Parses the packet type and calls what ever routines the packet type
1828 requires. This is done for all incoming packets. */
1830 void silc_server_packet_parse_type(SilcServer server,
1831 SilcSocketConnection sock,
1832 SilcPacketContext *packet)
1834 SilcPacketType type = packet->type;
1835 SilcIDListData idata = (SilcIDListData)sock->user_data;
1837 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1839 /* Parse the packet type */
1841 case SILC_PACKET_DISCONNECT:
1842 SILC_LOG_DEBUG(("Disconnect packet"));
1843 if (packet->flags & SILC_PACKET_FLAG_LIST)
1845 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1846 /* Duplicate to null terminate the string. */
1847 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1848 SILC_LOG_ERROR(("%s", message));
1853 case SILC_PACKET_SUCCESS:
1855 * Success received for something. For now we can have only
1856 * one protocol for connection executing at once hence this
1857 * success message is for whatever protocol is executing currently.
1859 SILC_LOG_DEBUG(("Success packet"));
1860 if (packet->flags & SILC_PACKET_FLAG_LIST)
1863 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1866 case SILC_PACKET_FAILURE:
1868 * Failure received for something. For now we can have only
1869 * one protocol for connection executing at once hence this
1870 * failure message is for whatever protocol is executing currently.
1872 SILC_LOG_DEBUG(("Failure packet"));
1873 if (packet->flags & SILC_PACKET_FLAG_LIST)
1875 if (sock->protocol) {
1876 SilcServerFailureContext f;
1877 f = silc_calloc(1, sizeof(*f));
1881 /* We will wait 5 seconds to process this failure packet */
1882 silc_schedule_task_add(server->schedule, sock->sock,
1883 silc_server_failure_callback, (void *)f, 5, 0,
1884 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1888 case SILC_PACKET_REJECT:
1889 SILC_LOG_DEBUG(("Reject packet"));
1890 if (packet->flags & SILC_PACKET_FLAG_LIST)
1895 case SILC_PACKET_NOTIFY:
1897 * Received notify packet. Server can receive notify packets from
1898 * router. Server then relays the notify messages to clients if needed.
1900 SILC_LOG_DEBUG(("Notify packet"));
1901 if (packet->flags & SILC_PACKET_FLAG_LIST)
1902 silc_server_notify_list(server, sock, packet);
1904 silc_server_notify(server, sock, packet);
1910 case SILC_PACKET_CHANNEL_MESSAGE:
1912 * Received channel message. Channel messages are special packets
1913 * (although probably most common ones) thus they are handled
1916 SILC_LOG_DEBUG(("Channel Message packet"));
1917 if (packet->flags & SILC_PACKET_FLAG_LIST)
1919 idata->last_receive = time(NULL);
1920 silc_server_channel_message(server, sock, packet);
1923 case SILC_PACKET_CHANNEL_KEY:
1925 * Received key for channel. As channels are created by the router
1926 * the keys are as well. We will distribute the key to all of our
1927 * locally connected clients on the particular channel. Router
1928 * never receives this channel and thus is ignored.
1930 SILC_LOG_DEBUG(("Channel Key packet"));
1931 if (packet->flags & SILC_PACKET_FLAG_LIST)
1933 silc_server_channel_key(server, sock, packet);
1939 case SILC_PACKET_COMMAND:
1941 * Recived command. Processes the command request and allocates the
1942 * command context and calls the command.
1944 SILC_LOG_DEBUG(("Command packet"));
1945 if (packet->flags & SILC_PACKET_FLAG_LIST)
1947 silc_server_command_process(server, sock, packet);
1950 case SILC_PACKET_COMMAND_REPLY:
1952 * Received command reply packet. Received command reply to command. It
1953 * may be reply to command sent by us or reply to command sent by client
1954 * that we've routed further.
1956 SILC_LOG_DEBUG(("Command Reply packet"));
1957 if (packet->flags & SILC_PACKET_FLAG_LIST)
1959 silc_server_command_reply(server, sock, packet);
1963 * Private Message packets
1965 case SILC_PACKET_PRIVATE_MESSAGE:
1967 * Received private message packet. The packet is coming from either
1970 SILC_LOG_DEBUG(("Private Message packet"));
1971 if (packet->flags & SILC_PACKET_FLAG_LIST)
1973 idata->last_receive = time(NULL);
1974 silc_server_private_message(server, sock, packet);
1977 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1979 * Private message key packet.
1981 if (packet->flags & SILC_PACKET_FLAG_LIST)
1983 silc_server_private_message_key(server, sock, packet);
1987 * Key Exchange protocol packets
1989 case SILC_PACKET_KEY_EXCHANGE:
1990 SILC_LOG_DEBUG(("KE packet"));
1991 if (packet->flags & SILC_PACKET_FLAG_LIST)
1994 if (sock->protocol && sock->protocol->protocol &&
1995 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1997 SilcServerKEInternalContext *proto_ctx =
1998 (SilcServerKEInternalContext *)sock->protocol->context;
2000 proto_ctx->packet = silc_packet_context_dup(packet);
2002 /* Let the protocol handle the packet */
2003 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2005 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2006 "protocol active, packet dropped."));
2010 case SILC_PACKET_KEY_EXCHANGE_1:
2011 SILC_LOG_DEBUG(("KE 1 packet"));
2012 if (packet->flags & SILC_PACKET_FLAG_LIST)
2015 if (sock->protocol && sock->protocol->protocol &&
2016 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2017 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2019 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2020 SilcServerRekeyInternalContext *proto_ctx =
2021 (SilcServerRekeyInternalContext *)sock->protocol->context;
2023 if (proto_ctx->packet)
2024 silc_packet_context_free(proto_ctx->packet);
2026 proto_ctx->packet = silc_packet_context_dup(packet);
2028 /* Let the protocol handle the packet */
2029 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2031 SilcServerKEInternalContext *proto_ctx =
2032 (SilcServerKEInternalContext *)sock->protocol->context;
2034 if (proto_ctx->packet)
2035 silc_packet_context_free(proto_ctx->packet);
2037 proto_ctx->packet = silc_packet_context_dup(packet);
2038 proto_ctx->dest_id_type = packet->src_id_type;
2039 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2040 packet->src_id_type);
2041 if (!proto_ctx->dest_id)
2044 /* Let the protocol handle the packet */
2045 silc_protocol_execute(sock->protocol, server->schedule,
2049 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2050 "protocol active, packet dropped."));
2054 case SILC_PACKET_KEY_EXCHANGE_2:
2055 SILC_LOG_DEBUG(("KE 2 packet"));
2056 if (packet->flags & SILC_PACKET_FLAG_LIST)
2059 if (sock->protocol && sock->protocol->protocol &&
2060 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2061 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2063 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2064 SilcServerRekeyInternalContext *proto_ctx =
2065 (SilcServerRekeyInternalContext *)sock->protocol->context;
2067 if (proto_ctx->packet)
2068 silc_packet_context_free(proto_ctx->packet);
2070 proto_ctx->packet = silc_packet_context_dup(packet);
2072 /* Let the protocol handle the packet */
2073 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2075 SilcServerKEInternalContext *proto_ctx =
2076 (SilcServerKEInternalContext *)sock->protocol->context;
2078 if (proto_ctx->packet)
2079 silc_packet_context_free(proto_ctx->packet);
2081 proto_ctx->packet = silc_packet_context_dup(packet);
2082 proto_ctx->dest_id_type = packet->src_id_type;
2083 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2084 packet->src_id_type);
2085 if (!proto_ctx->dest_id)
2088 /* Let the protocol handle the packet */
2089 silc_protocol_execute(sock->protocol, server->schedule,
2093 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2094 "protocol active, packet dropped."));
2098 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2100 * Connection authentication request packet. When we receive this packet
2101 * we will send to the other end information about our mandatory
2102 * authentication method for the connection. This packet maybe received
2105 SILC_LOG_DEBUG(("Connection authentication request packet"));
2106 if (packet->flags & SILC_PACKET_FLAG_LIST)
2108 silc_server_connection_auth_request(server, sock, packet);
2112 * Connection Authentication protocol packets
2114 case SILC_PACKET_CONNECTION_AUTH:
2115 /* Start of the authentication protocol. We receive here the
2116 authentication data and will verify it. */
2117 SILC_LOG_DEBUG(("Connection auth packet"));
2118 if (packet->flags & SILC_PACKET_FLAG_LIST)
2121 if (sock->protocol && sock->protocol->protocol->type
2122 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2124 SilcServerConnAuthInternalContext *proto_ctx =
2125 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2127 proto_ctx->packet = silc_packet_context_dup(packet);
2129 /* Let the protocol handle the packet */
2130 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2132 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2133 "protocol active, packet dropped."));
2137 case SILC_PACKET_NEW_ID:
2139 * Received New ID packet. This includes some new ID that has been
2140 * created. It may be for client, server or channel. This is the way
2141 * to distribute information about new registered entities in the
2144 SILC_LOG_DEBUG(("New ID packet"));
2145 if (packet->flags & SILC_PACKET_FLAG_LIST)
2146 silc_server_new_id_list(server, sock, packet);
2148 silc_server_new_id(server, sock, packet);
2151 case SILC_PACKET_NEW_CLIENT:
2153 * Received new client packet. This includes client information that
2154 * we will use to create initial client ID. After creating new
2155 * ID we will send it to the client.
2157 SILC_LOG_DEBUG(("New Client packet"));
2158 if (packet->flags & SILC_PACKET_FLAG_LIST)
2160 silc_server_new_client(server, sock, packet);
2163 case SILC_PACKET_NEW_SERVER:
2165 * Received new server packet. This includes Server ID and some other
2166 * information that we may save. This is received after server has
2169 SILC_LOG_DEBUG(("New Server packet"));
2170 if (packet->flags & SILC_PACKET_FLAG_LIST)
2172 silc_server_new_server(server, sock, packet);
2175 case SILC_PACKET_NEW_CHANNEL:
2177 * Received new channel packet. Information about new channel in the
2178 * network are distributed using this packet.
2180 SILC_LOG_DEBUG(("New Channel packet"));
2181 if (packet->flags & SILC_PACKET_FLAG_LIST)
2182 silc_server_new_channel_list(server, sock, packet);
2184 silc_server_new_channel(server, sock, packet);
2187 case SILC_PACKET_HEARTBEAT:
2189 * Received heartbeat.
2191 SILC_LOG_DEBUG(("Heartbeat packet"));
2192 if (packet->flags & SILC_PACKET_FLAG_LIST)
2196 case SILC_PACKET_KEY_AGREEMENT:
2198 * Received heartbeat.
2200 SILC_LOG_DEBUG(("Key agreement packet"));
2201 if (packet->flags & SILC_PACKET_FLAG_LIST)
2203 silc_server_key_agreement(server, sock, packet);
2206 case SILC_PACKET_REKEY:
2208 * Received re-key packet. The sender wants to regenerate the session
2211 SILC_LOG_DEBUG(("Re-key packet"));
2212 if (packet->flags & SILC_PACKET_FLAG_LIST)
2214 silc_server_rekey(server, sock, packet);
2217 case SILC_PACKET_REKEY_DONE:
2219 * The re-key is done.
2221 SILC_LOG_DEBUG(("Re-key done packet"));
2222 if (packet->flags & SILC_PACKET_FLAG_LIST)
2225 if (sock->protocol && sock->protocol->protocol &&
2226 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2228 SilcServerRekeyInternalContext *proto_ctx =
2229 (SilcServerRekeyInternalContext *)sock->protocol->context;
2231 if (proto_ctx->packet)
2232 silc_packet_context_free(proto_ctx->packet);
2234 proto_ctx->packet = silc_packet_context_dup(packet);
2236 /* Let the protocol handle the packet */
2237 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2239 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2240 "protocol active, packet dropped."));
2244 case SILC_PACKET_FTP:
2246 SILC_LOG_DEBUG(("FTP packet"));
2247 if (packet->flags & SILC_PACKET_FLAG_LIST)
2249 silc_server_ftp(server, sock, packet);
2252 case SILC_PACKET_RESUME_ROUTER:
2253 /* Resume router packet received. This packet is received for backup
2254 router resuming protocol. */
2255 SILC_LOG_DEBUG(("Resume router packet"));
2256 if (packet->flags & SILC_PACKET_FLAG_LIST)
2258 silc_server_backup_resume_router(server, sock, packet);
2262 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2268 /* Creates connection to a remote router. */
2270 void silc_server_create_connection(SilcServer server,
2271 const char *remote_host, SilcUInt32 port)
2273 SilcServerConnection sconn;
2275 /* Allocate connection object for hold connection specific stuff. */
2276 sconn = silc_calloc(1, sizeof(*sconn));
2277 sconn->server = server;
2278 sconn->remote_host = strdup(remote_host);
2279 sconn->remote_port = port;
2280 sconn->no_reconnect = TRUE;
2281 sconn->param = &server->config->param;
2283 silc_schedule_task_add(server->schedule, 0,
2284 silc_server_connect_router,
2285 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2286 SILC_TASK_PRI_NORMAL);
2289 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2291 silc_socket_free((SilcSocketConnection)context);
2294 /* Closes connection to socket connection */
2296 void silc_server_close_connection(SilcServer server,
2297 SilcSocketConnection sock)
2299 if (!server->sockets[sock->sock])
2302 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2304 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2305 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2306 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2309 /* We won't listen for this connection anymore */
2310 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2312 /* Unregister all tasks */
2313 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2315 /* Close the actual connection */
2316 silc_net_close_connection(sock->sock);
2317 server->sockets[sock->sock] = NULL;
2319 /* If sock->user_data is NULL then we'll check for active protocols
2320 here since the silc_server_free_sock_user_data has not been called
2321 for this connection. */
2322 if (!sock->user_data) {
2323 /* If any protocol is active cancel its execution. It will call
2324 the final callback which will finalize the disconnection. */
2325 if (sock->protocol) {
2326 silc_protocol_cancel(sock->protocol, server->schedule);
2327 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2328 silc_protocol_execute_final(sock->protocol, server->schedule);
2329 sock->protocol = NULL;
2334 silc_schedule_task_add(server->schedule, 0,
2335 silc_server_close_connection_final,
2336 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2337 SILC_TASK_PRI_NORMAL);
2340 /* Sends disconnect message to remote connection and disconnects the
2343 void silc_server_disconnect_remote(SilcServer server,
2344 SilcSocketConnection sock,
2345 const char *fmt, ...)
2348 unsigned char buf[4096];
2353 memset(buf, 0, sizeof(buf));
2355 vsprintf(buf, fmt, ap);
2358 SILC_LOG_DEBUG(("Disconnecting remote host"));
2360 /* Notify remote end that the conversation is over. The notify message
2361 is tried to be sent immediately. */
2362 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2363 buf, strlen(buf), TRUE);
2364 silc_server_packet_queue_purge(server, sock);
2366 /* Mark the connection to be disconnected */
2367 SILC_SET_DISCONNECTED(sock);
2368 silc_server_close_connection(server, sock);
2373 SilcClientEntry client;
2374 } *FreeClientInternal;
2376 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2378 FreeClientInternal i = (FreeClientInternal)context;
2380 silc_idlist_del_data(i->client);
2381 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2385 /* Frees client data and notifies about client's signoff. */
2387 void silc_server_free_client_data(SilcServer server,
2388 SilcSocketConnection sock,
2389 SilcClientEntry client,
2391 const char *signoff)
2393 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2395 /* If there is pending outgoing data for the client then purge it
2396 to the network before removing the client entry. */
2397 silc_server_packet_queue_purge(server, sock);
2402 /* Send SIGNOFF notify to routers. */
2403 if (notify && !server->standalone && server->router)
2404 silc_server_send_notify_signoff(server, server->router->connection,
2405 server->server_type == SILC_SERVER ?
2406 FALSE : TRUE, client->id, signoff);
2408 /* Remove client from all channels */
2410 silc_server_remove_from_channels(server, NULL, client,
2411 TRUE, (char *)signoff, TRUE);
2413 silc_server_remove_from_channels(server, NULL, client,
2414 FALSE, NULL, FALSE);
2416 /* Update statistics */
2417 server->stat.my_clients--;
2418 server->stat.clients--;
2419 if (server->server_type == SILC_ROUTER)
2420 server->stat.cell_clients--;
2421 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2422 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2424 /* We will not delete the client entry right away. We will take it
2425 into history (for WHOWAS command) for 5 minutes */
2428 silc_schedule_task_add(server->schedule, 0,
2429 silc_server_free_client_data_timeout,
2431 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2432 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2433 client->router = NULL;
2434 client->connection = NULL;
2438 /* Frees user_data pointer from socket connection object. This also sends
2439 appropriate notify packets to the network to inform about leaving
2442 void silc_server_free_sock_user_data(SilcServer server,
2443 SilcSocketConnection sock,
2444 const char *signoff_message)
2446 SILC_LOG_DEBUG(("Start"));
2448 switch (sock->type) {
2449 case SILC_SOCKET_TYPE_CLIENT:
2451 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2452 silc_server_free_client_data(server, sock, user_data, TRUE,
2456 case SILC_SOCKET_TYPE_SERVER:
2457 case SILC_SOCKET_TYPE_ROUTER:
2459 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2460 SilcServerEntry backup_router = NULL;
2463 backup_router = silc_server_backup_get(server, user_data->id);
2465 /* If this was our primary router connection then we're lost to
2466 the outside world. */
2467 if (server->router == user_data) {
2468 /* Check whether we have a backup router connection */
2469 if (!backup_router || backup_router == user_data) {
2470 silc_schedule_task_add(server->schedule, 0,
2471 silc_server_connect_to_router,
2474 SILC_TASK_PRI_NORMAL);
2476 server->id_entry->router = NULL;
2477 server->router = NULL;
2478 server->standalone = TRUE;
2479 backup_router = NULL;
2481 SILC_LOG_INFO(("New primary router is backup router %s",
2482 backup_router->server_name));
2483 SILC_LOG_DEBUG(("New primary router is backup router %s",
2484 backup_router->server_name));
2485 server->id_entry->router = backup_router;
2486 server->router = backup_router;
2487 server->router_connect = time(0);
2488 server->backup_primary = TRUE;
2489 if (server->server_type == SILC_BACKUP_ROUTER) {
2490 server->server_type = SILC_ROUTER;
2492 /* We'll need to constantly try to reconnect to the primary
2493 router so that we'll see when it comes back online. */
2494 silc_server_backup_reconnect(server, sock->ip, sock->port,
2495 silc_server_backup_connected,
2499 /* Mark this connection as replaced */
2500 silc_server_backup_replaced_add(server, user_data->id,
2503 } else if (backup_router) {
2504 SILC_LOG_INFO(("Enabling the use of backup router %s",
2505 backup_router->server_name));
2506 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2507 backup_router->server_name));
2509 /* Mark this connection as replaced */
2510 silc_server_backup_replaced_add(server, user_data->id,
2514 if (!backup_router) {
2515 /* Free all client entries that this server owns as they will
2516 become invalid now as well. */
2518 silc_server_remove_clients_by_server(server, user_data, TRUE);
2519 if (server->server_type == SILC_SERVER)
2520 silc_server_remove_channels_by_server(server, user_data);
2522 /* Update the client entries of this server to the new backup
2523 router. This also removes the clients that *really* was owned
2524 by the primary router and went down with the router. */
2525 silc_server_update_clients_by_server(server, user_data, backup_router,
2527 silc_server_update_servers_by_server(server, user_data, backup_router);
2528 if (server->server_type == SILC_SERVER)
2529 silc_server_update_channels_by_server(server, user_data,
2533 /* Free the server entry */
2534 silc_server_backup_del(server, user_data);
2535 silc_server_backup_replaced_del(server, user_data);
2536 silc_idlist_del_data(user_data);
2537 if (!silc_idlist_del_server(server->local_list, user_data))
2538 silc_idlist_del_server(server->global_list, user_data);
2539 server->stat.my_servers--;
2540 server->stat.servers--;
2541 if (server->server_type == SILC_ROUTER)
2542 server->stat.cell_servers--;
2544 if (backup_router) {
2545 /* Announce all of our stuff that was created about 5 minutes ago.
2546 The backup router knows all the other stuff already. */
2547 if (server->server_type == SILC_ROUTER)
2548 silc_server_announce_servers(server, FALSE, time(0) - 300,
2549 backup_router->connection);
2551 /* Announce our clients and channels to the router */
2552 silc_server_announce_clients(server, time(0) - 300,
2553 backup_router->connection);
2554 silc_server_announce_channels(server, time(0) - 300,
2555 backup_router->connection);
2561 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2563 silc_idlist_del_data(user_data);
2564 silc_free(user_data);
2569 /* If any protocol is active cancel its execution */
2570 if (sock->protocol) {
2571 silc_protocol_cancel(sock->protocol, server->schedule);
2572 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2573 silc_protocol_execute_final(sock->protocol, server->schedule);
2574 sock->protocol = NULL;
2577 sock->user_data = NULL;
2580 /* Removes client from all channels it has joined. This is used when client
2581 connection is disconnected. If the client on a channel is last, the
2582 channel is removed as well. This sends the SIGNOFF notify types. */
2584 void silc_server_remove_from_channels(SilcServer server,
2585 SilcSocketConnection sock,
2586 SilcClientEntry client,
2588 char *signoff_message,
2591 SilcChannelEntry channel;
2592 SilcChannelClientEntry chl;
2593 SilcHashTableList htl;
2596 SILC_LOG_DEBUG(("Start"));
2598 if (!client || !client->id)
2601 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2603 /* Remove the client from all channels. The client is removed from
2604 the channels' user list. */
2605 silc_hash_table_list(client->channels, &htl);
2606 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2607 channel = chl->channel;
2609 /* Remove channel from client's channel list */
2610 silc_hash_table_del(client->channels, channel);
2612 /* Remove channel if there is no users anymore */
2613 if (server->server_type == SILC_ROUTER &&
2614 silc_hash_table_count(channel->user_list) < 2) {
2616 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2617 if (silc_idlist_del_channel(server->local_list, channel))
2618 server->stat.my_channels--;
2620 silc_idlist_del_channel(server->global_list, channel);
2624 /* Remove client from channel's client list */
2625 silc_hash_table_del(channel->user_list, chl->client);
2626 channel->user_count--;
2628 /* If there is no global users on the channel anymore mark the channel
2629 as local channel. Do not check if the removed client is local client. */
2630 if (server->server_type != SILC_ROUTER && channel->global_users &&
2631 chl->client->router && !silc_server_channel_has_global(channel))
2632 channel->global_users = FALSE;
2635 server->stat.my_chanclients--;
2637 /* If there is not at least one local user on the channel then we don't
2638 need the channel entry anymore, we can remove it safely. */
2639 if (server->server_type != SILC_ROUTER &&
2640 !silc_server_channel_has_local(channel)) {
2641 /* Notify about leaving client if this channel has global users. */
2642 if (notify && channel->global_users)
2643 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2644 SILC_NOTIFY_TYPE_SIGNOFF,
2645 signoff_message ? 2 : 1,
2646 clidp->data, clidp->len,
2647 signoff_message, signoff_message ?
2648 strlen(signoff_message) : 0);
2651 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2653 if (channel->founder_key) {
2654 /* The founder auth data exists, do not remove the channel entry */
2655 SilcChannelClientEntry chl2;
2656 SilcHashTableList htl2;
2658 channel->disabled = TRUE;
2660 silc_hash_table_list(channel->user_list, &htl2);
2661 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2662 silc_hash_table_del(chl2->client->channels, channel);
2663 silc_hash_table_del(channel->user_list, chl2->client);
2664 channel->user_count--;
2667 silc_hash_table_list_reset(&htl2);
2671 /* Remove the channel entry */
2672 if (silc_idlist_del_channel(server->local_list, channel))
2673 server->stat.my_channels--;
2675 silc_idlist_del_channel(server->global_list, channel);
2679 /* Send notify to channel about client leaving SILC and thus
2680 the entire channel. */
2682 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2683 SILC_NOTIFY_TYPE_SIGNOFF,
2684 signoff_message ? 2 : 1,
2685 clidp->data, clidp->len,
2686 signoff_message, signoff_message ?
2687 strlen(signoff_message) : 0);
2689 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2690 /* Re-generate channel key */
2691 if (!silc_server_create_channel_key(server, channel, 0))
2694 /* Send the channel key to the channel. The key of course is not sent
2695 to the client who was removed from the channel. */
2696 silc_server_send_channel_key(server, client->connection, channel,
2697 server->server_type == SILC_ROUTER ?
2698 FALSE : !server->standalone);
2703 silc_hash_table_list_reset(&htl);
2704 silc_buffer_free(clidp);
2707 /* Removes client from one channel. This is used for example when client
2708 calls LEAVE command to remove itself from the channel. Returns TRUE
2709 if channel still exists and FALSE if the channel is removed when
2710 last client leaves the channel. If `notify' is FALSE notify messages
2713 int silc_server_remove_from_one_channel(SilcServer server,
2714 SilcSocketConnection sock,
2715 SilcChannelEntry channel,
2716 SilcClientEntry client,
2719 SilcChannelClientEntry chl;
2722 SILC_LOG_DEBUG(("Start"));
2724 /* Get the entry to the channel, if this client is not on the channel
2726 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2729 /* Remove the client from the channel. The client is removed from
2730 the channel's user list. */
2732 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2734 /* Remove channel from client's channel list */
2735 silc_hash_table_del(client->channels, chl->channel);
2737 /* Remove channel if there is no users anymore */
2738 if (server->server_type == SILC_ROUTER &&
2739 silc_hash_table_count(channel->user_list) < 2) {
2741 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2742 if (silc_idlist_del_channel(server->local_list, channel))
2743 server->stat.my_channels--;
2745 silc_idlist_del_channel(server->global_list, channel);
2746 silc_buffer_free(clidp);
2750 /* Remove client from channel's client list */
2751 silc_hash_table_del(channel->user_list, chl->client);
2752 channel->user_count--;
2754 /* If there is no global users on the channel anymore mark the channel
2755 as local channel. Do not check if the client is local client. */
2756 if (server->server_type != SILC_ROUTER && channel->global_users &&
2757 chl->client->router && !silc_server_channel_has_global(channel))
2758 channel->global_users = FALSE;
2761 server->stat.my_chanclients--;
2763 /* If there is not at least one local user on the channel then we don't
2764 need the channel entry anymore, we can remove it safely. */
2765 if (server->server_type != SILC_ROUTER &&
2766 !silc_server_channel_has_local(channel)) {
2767 /* Notify about leaving client if this channel has global users. */
2768 if (notify && channel->global_users)
2769 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2770 SILC_NOTIFY_TYPE_LEAVE, 1,
2771 clidp->data, clidp->len);
2773 silc_buffer_free(clidp);
2776 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2778 if (channel->founder_key) {
2779 /* The founder auth data exists, do not remove the channel entry */
2780 SilcChannelClientEntry chl2;
2781 SilcHashTableList htl2;
2783 channel->disabled = TRUE;
2785 silc_hash_table_list(channel->user_list, &htl2);
2786 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2787 silc_hash_table_del(chl2->client->channels, channel);
2788 silc_hash_table_del(channel->user_list, chl2->client);
2789 channel->user_count--;
2792 silc_hash_table_list_reset(&htl2);
2796 /* Remove the channel entry */
2797 if (silc_idlist_del_channel(server->local_list, channel))
2798 server->stat.my_channels--;
2800 silc_idlist_del_channel(server->global_list, channel);
2804 /* Send notify to channel about client leaving the channel */
2806 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2807 SILC_NOTIFY_TYPE_LEAVE, 1,
2808 clidp->data, clidp->len);
2810 silc_buffer_free(clidp);
2814 /* Timeout callback. This is called if connection is idle or for some
2815 other reason is not responding within some period of time. This
2816 disconnects the remote end. */
2818 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2820 SilcServer server = (SilcServer)context;
2821 SilcSocketConnection sock = server->sockets[fd];
2823 SILC_LOG_DEBUG(("Start"));
2828 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2829 sock->hostname, sock->ip));
2831 /* If we have protocol active we must assure that we call the protocol's
2832 final callback so that all the memory is freed. */
2833 if (sock->protocol) {
2834 silc_protocol_cancel(sock->protocol, server->schedule);
2835 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2836 silc_protocol_execute_final(sock->protocol, server->schedule);
2837 sock->protocol = NULL;
2841 if (sock->user_data)
2842 silc_server_free_sock_user_data(server, sock, NULL);
2844 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2845 "Connection timeout");
2848 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2849 function may be used only by router. In real SILC network all channels
2850 are created by routers thus this function is never used by normal
2853 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2854 SilcServerID *router_id,
2860 SilcChannelID *channel_id;
2861 SilcChannelEntry entry;
2865 SILC_LOG_DEBUG(("Creating new channel"));
2868 cipher = SILC_DEFAULT_CIPHER;
2870 hmac = SILC_DEFAULT_HMAC;
2872 /* Allocate cipher */
2873 if (!silc_cipher_alloc(cipher, &key))
2877 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2878 silc_cipher_free(key);
2882 channel_name = strdup(channel_name);
2884 /* Create the channel ID */
2885 if (!silc_id_create_channel_id(server, router_id, server->rng,
2887 silc_free(channel_name);
2888 silc_cipher_free(key);
2889 silc_hmac_free(newhmac);
2893 /* Create the channel */
2894 entry = silc_idlist_add_channel(server->local_list, channel_name,
2895 SILC_CHANNEL_MODE_NONE, channel_id,
2896 NULL, key, newhmac, 0);
2898 silc_free(channel_name);
2899 silc_cipher_free(key);
2900 silc_hmac_free(newhmac);
2901 silc_free(channel_id);
2905 entry->cipher = strdup(cipher);
2906 entry->hmac_name = strdup(hmac);
2908 /* Now create the actual key material */
2909 if (!silc_server_create_channel_key(server, entry,
2910 silc_cipher_get_key_len(key) / 8)) {
2911 silc_idlist_del_channel(server->local_list, entry);
2915 /* Notify other routers about the new channel. We send the packet
2916 to our primary route. */
2917 if (broadcast && server->standalone == FALSE)
2918 silc_server_send_new_channel(server, server->router->connection, TRUE,
2919 channel_name, entry->id,
2920 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2923 server->stat.my_channels++;
2928 /* Same as above but creates the channel with Channel ID `channel_id. */
2931 silc_server_create_new_channel_with_id(SilcServer server,
2935 SilcChannelID *channel_id,
2938 SilcChannelEntry entry;
2942 SILC_LOG_DEBUG(("Creating new channel"));
2945 cipher = SILC_DEFAULT_CIPHER;
2947 hmac = SILC_DEFAULT_HMAC;
2949 /* Allocate cipher */
2950 if (!silc_cipher_alloc(cipher, &key))
2954 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2955 silc_cipher_free(key);
2959 channel_name = strdup(channel_name);
2961 /* Create the channel */
2962 entry = silc_idlist_add_channel(server->local_list, channel_name,
2963 SILC_CHANNEL_MODE_NONE, channel_id,
2964 NULL, key, newhmac, 0);
2966 silc_cipher_free(key);
2967 silc_hmac_free(newhmac);
2968 silc_free(channel_name);
2972 /* Now create the actual key material */
2973 if (!silc_server_create_channel_key(server, entry,
2974 silc_cipher_get_key_len(key) / 8)) {
2975 silc_idlist_del_channel(server->local_list, entry);
2979 /* Notify other routers about the new channel. We send the packet
2980 to our primary route. */
2981 if (broadcast && server->standalone == FALSE)
2982 silc_server_send_new_channel(server, server->router->connection, TRUE,
2983 channel_name, entry->id,
2984 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2987 server->stat.my_channels++;
2992 /* Channel's key re-key timeout callback. */
2994 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2996 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2997 SilcServer server = (SilcServer)rekey->context;
3001 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3004 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3007 /* Generates new channel key. This is used to create the initial channel key
3008 but also to re-generate new key for channel. If `key_len' is provided
3009 it is the bytes of the key length. */
3011 bool silc_server_create_channel_key(SilcServer server,
3012 SilcChannelEntry channel,
3016 unsigned char channel_key[32], hash[32];
3019 SILC_LOG_DEBUG(("Generating channel key"));
3021 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3022 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3026 if (!channel->channel_key)
3027 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3028 channel->channel_key = NULL;
3034 else if (channel->key_len)
3035 len = channel->key_len / 8;
3037 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3039 /* Create channel key */
3040 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3043 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3045 /* Remove old key if exists */
3047 memset(channel->key, 0, channel->key_len / 8);
3048 silc_free(channel->key);
3052 channel->key_len = len * 8;
3053 channel->key = silc_memdup(channel_key, len);
3054 memset(channel_key, 0, sizeof(channel_key));
3056 /* Generate HMAC key from the channel key data and set it */
3058 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3059 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3060 silc_hmac_set_key(channel->hmac, hash,
3061 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3062 memset(hash, 0, sizeof(hash));
3064 if (server->server_type == SILC_ROUTER) {
3065 if (!channel->rekey)
3066 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3067 channel->rekey->context = (void *)server;
3068 channel->rekey->channel = channel;
3069 channel->rekey->key_len = key_len;
3070 if (channel->rekey->task)
3071 silc_schedule_task_del(server->schedule, channel->rekey->task);
3073 channel->rekey->task =
3074 silc_schedule_task_add(server->schedule, 0,
3075 silc_server_channel_key_rekey,
3076 (void *)channel->rekey,
3077 server->config->channel_rekey_secs, 0,
3079 SILC_TASK_PRI_NORMAL);
3085 /* Saves the channel key found in the encoded `key_payload' buffer. This
3086 function is used when we receive Channel Key Payload and also when we're
3087 processing JOIN command reply. Returns entry to the channel. */
3089 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3090 SilcBuffer key_payload,
3091 SilcChannelEntry channel)
3093 SilcChannelKeyPayload payload = NULL;
3094 SilcChannelID *id = NULL;
3095 unsigned char *tmp, hash[32];
3099 SILC_LOG_DEBUG(("Start"));
3101 /* Decode channel key payload */
3102 payload = silc_channel_key_payload_parse(key_payload->data,
3105 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3110 /* Get the channel entry */
3113 /* Get channel ID */
3114 tmp = silc_channel_key_get_id(payload, &tmp_len);
3115 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3121 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3123 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3125 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3126 silc_id_render(id, SILC_ID_CHANNEL)));
3132 tmp = silc_channel_key_get_key(payload, &tmp_len);
3138 cipher = silc_channel_key_get_cipher(payload, NULL);
3144 /* Remove old key if exists */
3146 memset(channel->key, 0, channel->key_len / 8);
3147 silc_free(channel->key);
3148 silc_cipher_free(channel->channel_key);
3151 /* Create new cipher */
3152 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3153 channel->channel_key = NULL;
3158 if (channel->cipher)
3159 silc_free(channel->cipher);
3160 channel->cipher = strdup(cipher);
3163 channel->key_len = tmp_len * 8;
3164 channel->key = silc_memdup(tmp, tmp_len);
3165 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3167 /* Generate HMAC key from the channel key data and set it */
3169 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3170 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3171 silc_hmac_set_key(channel->hmac, hash,
3172 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3174 memset(hash, 0, sizeof(hash));
3175 memset(tmp, 0, tmp_len);
3177 if (server->server_type == SILC_ROUTER) {
3178 if (!channel->rekey)
3179 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3180 channel->rekey->context = (void *)server;
3181 channel->rekey->channel = channel;
3182 if (channel->rekey->task)
3183 silc_schedule_task_del(server->schedule, channel->rekey->task);
3185 channel->rekey->task =
3186 silc_schedule_task_add(server->schedule, 0,
3187 silc_server_channel_key_rekey,
3188 (void *)channel->rekey,
3189 server->config->channel_rekey_secs, 0,
3191 SILC_TASK_PRI_NORMAL);
3197 silc_channel_key_payload_free(payload);
3202 /* Heartbeat callback. This function is set as argument for the
3203 silc_socket_set_heartbeat function. The library will call this function
3204 at the set time interval. */
3206 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3209 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3211 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3213 /* Send the heartbeat */
3214 silc_server_send_heartbeat(hb->server, sock);
3217 /* Returns assembled of all servers in the given ID list. The packet's
3218 form is dictated by the New ID payload. */
3220 static void silc_server_announce_get_servers(SilcServer server,
3221 SilcServerEntry remote,
3223 SilcBuffer *servers,
3224 unsigned long creation_time)
3226 SilcIDCacheList list;
3227 SilcIDCacheEntry id_cache;
3228 SilcServerEntry entry;
3231 /* Go through all clients in the list */
3232 if (silc_idcache_get_all(id_list->servers, &list)) {
3233 if (silc_idcache_list_first(list, &id_cache)) {
3235 entry = (SilcServerEntry)id_cache->context;
3237 /* Do not announce the one we've sending our announcements and
3238 do not announce ourself. Also check the creation time if it's
3240 if ((entry == remote) || (entry == server->id_entry) ||
3241 (creation_time && entry->data.created < creation_time)) {
3242 if (!silc_idcache_list_next(list, &id_cache))
3247 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3249 *servers = silc_buffer_realloc(*servers,
3251 (*servers)->truelen + idp->len :
3253 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3254 silc_buffer_put(*servers, idp->data, idp->len);
3255 silc_buffer_pull(*servers, idp->len);
3256 silc_buffer_free(idp);
3258 if (!silc_idcache_list_next(list, &id_cache))
3263 silc_idcache_list_free(list);
3268 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3274 p = silc_notify_payload_encode(notify, argc, ap);
3280 /* This function is used by router to announce existing servers to our
3281 primary router when we've connected to it. If `creation_time' is non-zero
3282 then only the servers that has been created after the `creation_time'
3283 will be announced. */
3285 void silc_server_announce_servers(SilcServer server, bool global,
3286 unsigned long creation_time,
3287 SilcSocketConnection remote)
3289 SilcBuffer servers = NULL;
3291 SILC_LOG_DEBUG(("Announcing servers"));
3293 /* Get servers in local list */
3294 silc_server_announce_get_servers(server, remote->user_data,
3295 server->local_list, &servers,
3299 /* Get servers in global list */
3300 silc_server_announce_get_servers(server, remote->user_data,
3301 server->global_list, &servers,
3305 silc_buffer_push(servers, servers->data - servers->head);
3306 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3308 /* Send the packet */
3309 silc_server_packet_send(server, remote,
3310 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3311 servers->data, servers->len, TRUE);
3313 silc_buffer_free(servers);
3317 /* Returns assembled packet of all clients in the given ID list. The
3318 packet's form is dictated by the New ID Payload. */
3320 static void silc_server_announce_get_clients(SilcServer server,
3322 SilcBuffer *clients,
3324 unsigned long creation_time)
3326 SilcIDCacheList list;
3327 SilcIDCacheEntry id_cache;
3328 SilcClientEntry client;
3331 unsigned char mode[4];
3333 /* Go through all clients in the list */
3334 if (silc_idcache_get_all(id_list->clients, &list)) {
3335 if (silc_idcache_list_first(list, &id_cache)) {
3337 client = (SilcClientEntry)id_cache->context;
3339 if (creation_time && client->data.created < creation_time) {
3340 if (!silc_idcache_list_next(list, &id_cache))
3345 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3347 *clients = silc_buffer_realloc(*clients,
3349 (*clients)->truelen + idp->len :
3351 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3352 silc_buffer_put(*clients, idp->data, idp->len);
3353 silc_buffer_pull(*clients, idp->len);
3355 SILC_PUT32_MSB(client->mode, mode);
3356 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3357 2, idp->data, idp->len,
3359 *umodes = silc_buffer_realloc(*umodes,
3361 (*umodes)->truelen + tmp->len :
3363 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3364 silc_buffer_put(*umodes, tmp->data, tmp->len);
3365 silc_buffer_pull(*umodes, tmp->len);
3366 silc_buffer_free(tmp);
3368 silc_buffer_free(idp);
3370 if (!silc_idcache_list_next(list, &id_cache))
3375 silc_idcache_list_free(list);
3379 /* This function is used to announce our existing clients to our router
3380 when we've connected to it. If `creation_time' is non-zero then only
3381 the clients that has been created after the `creation_time' will be
3384 void silc_server_announce_clients(SilcServer server,
3385 unsigned long creation_time,
3386 SilcSocketConnection remote)
3388 SilcBuffer clients = NULL;
3389 SilcBuffer umodes = NULL;
3391 SILC_LOG_DEBUG(("Announcing clients"));
3393 /* Get clients in local list */
3394 silc_server_announce_get_clients(server, server->local_list,
3395 &clients, &umodes, creation_time);
3397 /* As router we announce our global list as well */
3398 if (server->server_type == SILC_ROUTER)
3399 silc_server_announce_get_clients(server, server->global_list,
3400 &clients, &umodes, creation_time);
3403 silc_buffer_push(clients, clients->data - clients->head);
3404 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3406 /* Send the packet */
3407 silc_server_packet_send(server, remote,
3408 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3409 clients->data, clients->len, TRUE);
3411 silc_buffer_free(clients);
3415 silc_buffer_push(umodes, umodes->data - umodes->head);
3416 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3418 /* Send the packet */
3419 silc_server_packet_send(server, remote,
3420 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3421 umodes->data, umodes->len, TRUE);
3423 silc_buffer_free(umodes);
3427 /* Returns channel's topic for announcing it */
3429 void silc_server_announce_get_channel_topic(SilcServer server,
3430 SilcChannelEntry channel,
3435 if (channel->topic) {
3436 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3437 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3438 chidp->data, chidp->len,
3440 strlen(channel->topic));
3441 silc_buffer_free(chidp);
3445 /* Returns assembled packets for channel users of the `channel'. */
3447 void silc_server_announce_get_channel_users(SilcServer server,
3448 SilcChannelEntry channel,
3449 SilcBuffer *channel_users,
3450 SilcBuffer *channel_users_modes)
3452 SilcChannelClientEntry chl;
3453 SilcHashTableList htl;
3454 SilcBuffer chidp, clidp;
3457 unsigned char mode[4];
3459 SILC_LOG_DEBUG(("Start"));
3461 /* Now find all users on the channel */
3462 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3463 silc_hash_table_list(channel->user_list, &htl);
3464 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3465 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3468 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3469 clidp->data, clidp->len,
3470 chidp->data, chidp->len);
3473 silc_buffer_realloc(*channel_users,
3475 (*channel_users)->truelen + len : len));
3476 silc_buffer_pull_tail(*channel_users,
3477 ((*channel_users)->end -
3478 (*channel_users)->data));
3480 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3481 silc_buffer_pull(*channel_users, len);
3482 silc_buffer_free(tmp);
3484 /* CUMODE notify for mode change on the channel */
3485 SILC_PUT32_MSB(chl->mode, mode);
3486 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3487 3, clidp->data, clidp->len,
3489 clidp->data, clidp->len);
3491 *channel_users_modes =
3492 silc_buffer_realloc(*channel_users_modes,
3493 (*channel_users_modes ?
3494 (*channel_users_modes)->truelen + len : len));
3495 silc_buffer_pull_tail(*channel_users_modes,
3496 ((*channel_users_modes)->end -
3497 (*channel_users_modes)->data));
3499 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3500 silc_buffer_pull(*channel_users_modes, len);
3501 silc_buffer_free(tmp);
3503 silc_buffer_free(clidp);
3505 silc_hash_table_list_reset(&htl);
3506 silc_buffer_free(chidp);
3509 /* Returns assembled packets for all channels and users on those channels
3510 from the given ID List. The packets are in the form dictated by the
3511 New Channel and New Channel User payloads. */
3513 void silc_server_announce_get_channels(SilcServer server,
3515 SilcBuffer *channels,
3516 SilcBuffer *channel_users,
3517 SilcBuffer **channel_users_modes,
3518 SilcUInt32 *channel_users_modes_c,
3519 SilcBuffer **channel_topics,
3520 SilcChannelID ***channel_ids,
3521 unsigned long creation_time)
3523 SilcIDCacheList list;
3524 SilcIDCacheEntry id_cache;
3525 SilcChannelEntry channel;
3528 SilcUInt16 name_len;
3530 int i = *channel_users_modes_c;
3533 SILC_LOG_DEBUG(("Start"));
3535 /* Go through all channels in the list */
3536 if (silc_idcache_get_all(id_list->channels, &list)) {
3537 if (silc_idcache_list_first(list, &id_cache)) {
3539 channel = (SilcChannelEntry)id_cache->context;
3541 if (creation_time && channel->created < creation_time)
3546 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3547 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3548 name_len = strlen(channel->channel_name);
3551 len = 4 + name_len + id_len + 4;
3553 silc_buffer_realloc(*channels,
3554 (*channels ? (*channels)->truelen +
3556 silc_buffer_pull_tail(*channels,
3557 ((*channels)->end - (*channels)->data));
3558 silc_buffer_format(*channels,
3559 SILC_STR_UI_SHORT(name_len),
3560 SILC_STR_UI_XNSTRING(channel->channel_name,
3562 SILC_STR_UI_SHORT(id_len),
3563 SILC_STR_UI_XNSTRING(cid, id_len),
3564 SILC_STR_UI_INT(channel->mode),
3566 silc_buffer_pull(*channels, len);
3569 /* Channel user modes */
3570 *channel_users_modes = silc_realloc(*channel_users_modes,
3571 sizeof(**channel_users_modes) *
3573 (*channel_users_modes)[i] = NULL;
3574 *channel_ids = silc_realloc(*channel_ids,
3575 sizeof(**channel_ids) * (i + 1));
3576 (*channel_ids)[i] = NULL;
3577 silc_server_announce_get_channel_users(server, channel,
3579 &(*channel_users_modes)[i]);
3580 (*channel_ids)[i] = channel->id;
3582 /* Channel's topic */
3583 *channel_topics = silc_realloc(*channel_topics,
3584 sizeof(**channel_topics) * (i + 1));
3585 (*channel_topics)[i] = NULL;
3586 silc_server_announce_get_channel_topic(server, channel,
3587 &(*channel_topics)[i]);
3590 if (!silc_idcache_list_next(list, &id_cache))
3594 *channel_users_modes_c += i;
3597 silc_idcache_list_free(list);
3601 /* This function is used to announce our existing channels to our router
3602 when we've connected to it. This also announces the users on the
3603 channels to the router. If the `creation_time' is non-zero only the
3604 channels that was created after the `creation_time' are announced.
3605 Note that the channel users are still announced even if the `creation_time'
3608 void silc_server_announce_channels(SilcServer server,
3609 unsigned long creation_time,
3610 SilcSocketConnection remote)
3612 SilcBuffer channels = NULL, channel_users = NULL;
3613 SilcBuffer *channel_users_modes = NULL;
3614 SilcBuffer *channel_topics = NULL;
3615 SilcUInt32 channel_users_modes_c = 0;
3616 SilcChannelID **channel_ids = NULL;
3618 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3620 /* Get channels and channel users in local list */
3621 silc_server_announce_get_channels(server, server->local_list,
3622 &channels, &channel_users,
3623 &channel_users_modes,
3624 &channel_users_modes_c,
3626 &channel_ids, creation_time);
3628 /* Get channels and channel users in global list */
3629 if (server->server_type != SILC_SERVER)
3630 silc_server_announce_get_channels(server, server->global_list,
3631 &channels, &channel_users,
3632 &channel_users_modes,
3633 &channel_users_modes_c,
3635 &channel_ids, creation_time);
3638 silc_buffer_push(channels, channels->data - channels->head);
3639 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3641 /* Send the packet */
3642 silc_server_packet_send(server, remote,
3643 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3644 channels->data, channels->len,
3647 silc_buffer_free(channels);
3650 if (channel_users) {
3651 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3652 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3653 channel_users->len);
3655 /* Send the packet */
3656 silc_server_packet_send(server, remote,
3657 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3658 channel_users->data, channel_users->len,
3661 silc_buffer_free(channel_users);
3664 if (channel_users_modes) {
3667 for (i = 0; i < channel_users_modes_c; i++) {
3668 if (!channel_users_modes[i])
3670 silc_buffer_push(channel_users_modes[i],
3671 channel_users_modes[i]->data -
3672 channel_users_modes[i]->head);
3673 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3674 channel_users_modes[i]->len);
3675 silc_server_packet_send_dest(server, remote,
3676 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3677 channel_ids[i], SILC_ID_CHANNEL,
3678 channel_users_modes[i]->data,
3679 channel_users_modes[i]->len,
3681 silc_buffer_free(channel_users_modes[i]);
3683 silc_free(channel_users_modes);
3686 if (channel_topics) {
3689 for (i = 0; i < channel_users_modes_c; i++) {
3690 if (!channel_topics[i])
3693 silc_buffer_push(channel_topics[i],
3694 channel_topics[i]->data -
3695 channel_topics[i]->head);
3696 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3697 channel_topics[i]->len);
3698 silc_server_packet_send_dest(server, remote,
3699 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3700 channel_ids[i], SILC_ID_CHANNEL,
3701 channel_topics[i]->data,
3702 channel_topics[i]->len,
3704 silc_buffer_free(channel_topics[i]);
3706 silc_free(channel_topics);
3709 silc_free(channel_ids);
3712 /* Failure timeout callback. If this is called then we will immediately
3713 process the received failure. We always process the failure with timeout
3714 since we do not want to blindly trust to received failure packets.
3715 This won't be called (the timeout is cancelled) if the failure was
3716 bogus (it is bogus if remote does not close the connection after sending
3719 SILC_TASK_CALLBACK(silc_server_failure_callback)
3721 SilcServerFailureContext f = (SilcServerFailureContext)context;
3723 if (f->sock->protocol) {
3724 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3725 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3731 /* Assembles user list and users mode list from the `channel'. */
3733 void silc_server_get_users_on_channel(SilcServer server,
3734 SilcChannelEntry channel,
3735 SilcBuffer *user_list,
3736 SilcBuffer *mode_list,
3737 SilcUInt32 *user_count)
3739 SilcChannelClientEntry chl;
3740 SilcHashTableList htl;
3741 SilcBuffer client_id_list;
3742 SilcBuffer client_mode_list;
3744 SilcUInt32 list_count = 0, len = 0;
3746 silc_hash_table_list(channel->user_list, &htl);
3747 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3748 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3749 silc_hash_table_list_reset(&htl);
3751 client_id_list = silc_buffer_alloc(len);
3753 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3754 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3755 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3757 silc_hash_table_list(channel->user_list, &htl);
3758 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3760 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3761 silc_buffer_put(client_id_list, idp->data, idp->len);
3762 silc_buffer_pull(client_id_list, idp->len);
3763 silc_buffer_free(idp);
3765 /* Client's mode on channel */
3766 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3767 silc_buffer_pull(client_mode_list, 4);
3771 silc_hash_table_list_reset(&htl);
3772 silc_buffer_push(client_id_list,
3773 client_id_list->data - client_id_list->head);
3774 silc_buffer_push(client_mode_list,
3775 client_mode_list->data - client_mode_list->head);
3777 *user_list = client_id_list;
3778 *mode_list = client_mode_list;
3779 *user_count = list_count;
3782 /* Saves users and their modes to the `channel'. */
3784 void silc_server_save_users_on_channel(SilcServer server,
3785 SilcSocketConnection sock,
3786 SilcChannelEntry channel,
3787 SilcClientID *noadd,
3788 SilcBuffer user_list,
3789 SilcBuffer mode_list,
3790 SilcUInt32 user_count)
3795 SilcClientID *client_id;
3796 SilcClientEntry client;
3797 SilcIDCacheEntry cache;
3800 SILC_LOG_DEBUG(("Start"));
3802 for (i = 0; i < user_count; i++) {
3804 SILC_GET16_MSB(idp_len, user_list->data + 2);
3806 client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3807 silc_buffer_pull(user_list, idp_len);
3812 SILC_GET32_MSB(mode, mode_list->data);
3813 silc_buffer_pull(mode_list, 4);
3815 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3816 silc_free(client_id);
3822 /* Check if we have this client cached already. */
3823 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3824 server->server_type, &cache);
3826 client = silc_idlist_find_client_by_id(server->global_list,
3827 client_id, server->server_type,
3832 /* If router did not find such Client ID in its lists then this must
3833 be bogus client or some router in the net is buggy. */
3834 if (server->server_type == SILC_ROUTER) {
3835 silc_free(client_id);
3839 /* We don't have that client anywhere, add it. The client is added
3840 to global list since server didn't have it in the lists so it must be
3842 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3843 silc_id_dup(client_id, SILC_ID_CLIENT),
3844 sock->user_data, NULL, 0);
3846 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3847 silc_free(client_id);
3851 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3853 /* Found, if it is from global list we'll assure that we won't
3854 expire it now that the entry is on channel. */
3859 silc_free(client_id);
3861 if (!silc_server_client_on_channel(client, channel)) {
3862 /* Client was not on the channel, add it. */
3863 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3864 chl->client = client;
3866 chl->channel = channel;
3867 silc_hash_table_add(channel->user_list, chl->client, chl);
3868 silc_hash_table_add(client->channels, chl->channel, chl);
3869 channel->user_count++;
3874 /* Lookups route to the client indicated by the `id_data'. The connection
3875 object and internal data object is returned. Returns NULL if route
3876 could not be found to the client. If the `client_id' is specified then
3877 it is used and the `id_data' is ignored. */
3879 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3880 unsigned char *id_data,
3882 SilcClientID *client_id,
3883 SilcIDListData *idata)
3886 SilcClientEntry client;
3888 SILC_LOG_DEBUG(("Start"));
3890 /* Decode destination Client ID */
3892 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3894 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3898 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3901 /* If the destination belongs to our server we don't have to route
3902 the packet anywhere but to send it to the local destination. */
3903 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3907 /* If we are router and the client has router then the client is in
3908 our cell but not directly connected to us. */
3909 if (server->server_type == SILC_ROUTER && client->router) {
3910 /* We are of course in this case the client's router thus the route
3911 to the client is the server who owns the client. So, we will send
3912 the packet to that server. */
3914 *idata = (SilcIDListData)client->router;
3915 return client->router->connection;
3918 /* Seems that client really is directly connected to us */
3920 *idata = (SilcIDListData)client;
3921 return client->connection;
3924 /* Destination belongs to someone not in this server. If we are normal
3925 server our action is to send the packet to our router. */
3926 if (server->server_type != SILC_ROUTER && !server->standalone) {
3929 *idata = (SilcIDListData)server->router;
3930 return server->router->connection;
3933 /* We are router and we will perform route lookup for the destination
3934 and send the packet to fastest route. */
3935 if (server->server_type == SILC_ROUTER && !server->standalone) {
3936 /* Check first that the ID is valid */
3937 client = silc_idlist_find_client_by_id(server->global_list, id,
3940 SilcSocketConnection dst_sock;
3942 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3946 *idata = (SilcIDListData)dst_sock->user_data;
3955 /* Encodes and returns channel list of channels the `client' has joined.
3956 Secret channels are not put to the list. */
3958 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3959 SilcClientEntry client)
3961 SilcBuffer buffer = NULL;
3962 SilcChannelEntry channel;
3963 SilcChannelClientEntry chl;
3964 SilcHashTableList htl;
3967 SilcUInt16 name_len;
3970 silc_hash_table_list(client->channels, &htl);
3971 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3972 channel = chl->channel;
3974 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3975 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3978 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3979 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3980 name_len = strlen(channel->channel_name);
3982 len = 4 + name_len + id_len + 4;
3983 buffer = silc_buffer_realloc(buffer,
3984 (buffer ? (buffer)->truelen + len : len));
3985 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3986 silc_buffer_format(buffer,
3987 SILC_STR_UI_SHORT(name_len),
3988 SILC_STR_UI_XNSTRING(channel->channel_name,
3990 SILC_STR_UI_SHORT(id_len),
3991 SILC_STR_UI_XNSTRING(cid, id_len),
3992 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3994 silc_buffer_pull(buffer, len);
3997 silc_hash_table_list_reset(&htl);
4000 silc_buffer_push(buffer, buffer->data - buffer->head);
4005 /* Finds client entry by Client ID and if it is not found then resolves
4006 it using WHOIS command. */
4008 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4009 SilcClientID *client_id,
4012 SilcClientEntry client;
4017 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4020 client = silc_idlist_find_client_by_id(server->global_list,
4021 client_id, TRUE, NULL);
4022 if (!client && server->server_type == SILC_ROUTER)
4026 if (!client && server->standalone)
4029 if (!client || !client->nickname || !client->username) {
4030 SilcBuffer buffer, idp;
4032 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4033 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4034 client->resolve_cmd_ident = ++server->cmd_ident;
4036 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4037 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4038 server->cmd_ident, 1,
4039 3, idp->data, idp->len);
4040 silc_server_packet_send(server, client ? client->router->connection :
4041 server->router->connection,
4042 SILC_PACKET_COMMAND, 0,
4043 buffer->data, buffer->len, FALSE);
4044 silc_buffer_free(idp);
4045 silc_buffer_free(buffer);
4056 /* A timeout callback for the re-key. We will be the initiator of the
4059 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4061 SilcSocketConnection sock = (SilcSocketConnection)context;
4062 SilcIDListData idata = (SilcIDListData)sock->user_data;
4063 SilcServer server = (SilcServer)idata->rekey->context;
4064 SilcProtocol protocol;
4065 SilcServerRekeyInternalContext *proto_ctx;
4067 SILC_LOG_DEBUG(("Start"));
4069 /* Allocate internal protocol context. This is sent as context
4071 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4072 proto_ctx->server = (void *)server;
4073 proto_ctx->sock = sock;
4074 proto_ctx->responder = FALSE;
4075 proto_ctx->pfs = idata->rekey->pfs;
4077 /* Perform rekey protocol. Will call the final callback after the
4078 protocol is over. */
4079 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4080 &protocol, proto_ctx, silc_server_rekey_final);
4081 sock->protocol = protocol;
4083 /* Run the protocol */
4084 silc_protocol_execute(protocol, server->schedule, 0, 0);
4086 /* Re-register re-key timeout */
4087 silc_schedule_task_add(server->schedule, sock->sock,
4088 silc_server_rekey_callback,
4089 context, idata->rekey->timeout, 0,
4090 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4093 /* The final callback for the REKEY protocol. This will actually take the
4094 new key material into use. */
4096 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4098 SilcProtocol protocol = (SilcProtocol)context;
4099 SilcServerRekeyInternalContext *ctx =
4100 (SilcServerRekeyInternalContext *)protocol->context;
4101 SilcServer server = (SilcServer)ctx->server;
4102 SilcSocketConnection sock = ctx->sock;
4104 SILC_LOG_DEBUG(("Start"));
4106 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4107 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4108 /* Error occured during protocol */
4109 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4110 silc_protocol_cancel(protocol, server->schedule);
4111 silc_protocol_free(protocol);
4112 sock->protocol = NULL;
4114 silc_packet_context_free(ctx->packet);
4116 silc_ske_free(ctx->ske);
4121 /* Purge the outgoing data queue to assure that all rekey packets really
4122 go to the network before we quit the protocol. */
4123 silc_server_packet_queue_purge(server, sock);
4126 silc_protocol_free(protocol);
4127 sock->protocol = NULL;
4129 silc_packet_context_free(ctx->packet);
4131 silc_ske_free(ctx->ske);