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_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
91 silc_rng_free(server->rng);
93 silc_pkcs_free(server->pkcs);
94 if (server->pending_commands)
95 silc_dlist_uninit(server->pending_commands);
97 silc_idlist_del_server(server->local_list, server->id_entry);
99 silc_idcache_free(server->local_list->clients);
100 silc_idcache_free(server->local_list->servers);
101 silc_idcache_free(server->local_list->channels);
102 silc_idcache_free(server->global_list->clients);
103 silc_idcache_free(server->global_list->servers);
104 silc_idcache_free(server->global_list->channels);
106 silc_free(server->sockets);
111 /* Initializes the entire SILC server. This is called always before running
112 the server. This is called only once at the initialization of the program.
113 This binds the server to its listenning port. After this function returns
114 one should call silc_server_run to start the server. This returns TRUE
115 when everything is ok to run the server. Configuration file must be
116 read and parsed before calling this. */
118 int silc_server_init(SilcServer server)
122 SilcServerEntry id_entry;
123 SilcIDListPurge purge;
125 SILC_LOG_DEBUG(("Initializing server"));
127 assert(server->config);
129 /* Set public and private keys */
130 if (!server->config->server_info ||
131 !server->config->server_info->public_key ||
132 !server->config->server_info->private_key) {
133 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
136 server->public_key = server->config->server_info->public_key;
137 server->private_key = server->config->server_info->private_key;
139 /* Set default to configuration parameters */
140 silc_server_config_set_defaults(server);
142 /* Register all configured ciphers, PKCS and hash functions. */
143 if (!silc_server_config_register_ciphers(server))
144 silc_cipher_register_default();
145 if (!silc_server_config_register_pkcs(server))
146 silc_pkcs_register_default();
147 if (!silc_server_config_register_hashfuncs(server))
148 silc_hash_register_default();
149 if (!silc_server_config_register_hmacs(server))
150 silc_hmac_register_default();
152 /* Initialize random number generator for the server. */
153 server->rng = silc_rng_alloc();
154 silc_rng_init(server->rng);
155 silc_rng_global_init(server->rng);
157 /* Initialize hash functions for server to use */
158 silc_hash_alloc("md5", &server->md5hash);
159 silc_hash_alloc("sha1", &server->sha1hash);
161 /* Allocate PKCS context for local public and private keys */
162 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
163 silc_pkcs_public_key_set(server->pkcs, server->public_key);
164 silc_pkcs_private_key_set(server->pkcs, server->private_key);
166 /* Create a listening server */
167 sock = silc_net_create_server(server->config->server_info->port,
168 server->config->server_info->server_ip);
170 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
171 server->config->server_info->server_ip,
172 server->config->server_info->port));
176 /* Initialize ID caches */
177 server->local_list->clients =
178 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
179 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
180 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
182 /* These are allocated for normal server as well as these hold some
183 global information that the server has fetched from its router. For
184 router these are used as they are supposed to be used on router. */
185 server->global_list->clients =
186 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
187 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
188 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
190 /* Allocate the entire socket list that is used in server. Eventually
191 all connections will have entry in this table (it is a table of
192 pointers to the actual object that is allocated individually
194 server->sockets = silc_calloc(server->config->param.connections_max,
195 sizeof(*server->sockets));
198 SilcSocketConnection newsocket = NULL;
200 /* Set socket to non-blocking mode */
201 silc_net_set_socket_nonblock(sock);
204 /* Add ourselves also to the socket table. The entry allocated above
205 is sent as argument for fast referencing in the future. */
206 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
207 server->sockets[sock] = newsocket;
209 /* Perform name and address lookups to resolve the listenning address
211 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
213 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
215 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
216 newsocket->hostname ? newsocket->hostname :
217 newsocket->ip ? newsocket->ip : ""));
218 server->stat.conn_failures++;
221 if (!newsocket->hostname)
222 newsocket->hostname = strdup(newsocket->ip);
224 newsocket->port = silc_net_get_local_port(sock);
226 /* Create a Server ID for the server. */
227 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
232 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
233 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
234 server->id_type = SILC_ID_SERVER;
235 server->server_name = server->config->server_info->server_name;
237 /* Add ourselves to the server list. We don't have a router yet
238 beacuse we haven't established a route yet. It will be done later.
239 For now, NULL is sent as router. This allocates new entry to
242 silc_idlist_add_server(server->local_list, strdup(server->server_name),
243 server->server_type, server->id, NULL, NULL);
245 SILC_LOG_ERROR(("Could not add ourselves to cache"));
248 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
250 /* Put the allocated socket pointer also to the entry allocated above
251 for fast back-referencing to the socket list. */
252 newsocket->user_data = (void *)id_entry;
253 id_entry->connection = (void *)newsocket;
254 server->id_entry = id_entry;
257 /* Register protocols */
258 silc_server_protocols_register();
260 /* Initialize the scheduler. */
261 server->schedule = silc_schedule_init(server->config->param.connections_max);
262 if (!server->schedule)
265 /* Add the first task to the scheduler. This is task that is executed by
266 timeout. It expires as soon as the caller calls silc_server_run. This
267 task performs authentication protocol and key exchange with our
269 silc_schedule_task_add(server->schedule, sock,
270 silc_server_connect_to_router,
271 (void *)server, 0, 1,
273 SILC_TASK_PRI_NORMAL);
275 /* Add listener task to the scheduler. This task receives new connections
276 to the server. This task remains on the queue until the end of the
278 silc_schedule_task_add(server->schedule, sock,
279 silc_server_accept_new_connection,
280 (void *)server, 0, 0,
282 SILC_TASK_PRI_NORMAL);
283 server->listenning = TRUE;
285 /* Send log file configuration */
286 silc_server_config_setlogfiles(server);
288 /* If server connections has been configured then we must be router as
289 normal server cannot have server connections, only router connections. */
290 if (server->config->servers) {
291 SilcServerConfigServer *ptr = server->config->servers;
293 server->server_type = SILC_ROUTER;
295 if (ptr->backup_router) {
296 server->server_type = SILC_BACKUP_ROUTER;
297 server->backup_router = TRUE;
298 server->id_entry->server_type = SILC_BACKUP_ROUTER;
305 /* Register the ID Cache purge task. This periodically purges the ID cache
306 and removes the expired cache entries. */
308 /* Clients local list */
309 purge = silc_calloc(1, sizeof(*purge));
310 purge->cache = server->local_list->clients;
311 purge->schedule = server->schedule;
312 purge->timeout = 600;
313 silc_schedule_task_add(purge->schedule, 0,
315 (void *)purge, purge->timeout, 0,
316 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
318 /* Clients global list */
319 purge = silc_calloc(1, sizeof(*purge));
320 purge->cache = server->global_list->clients;
321 purge->schedule = server->schedule;
322 purge->timeout = 300;
323 silc_schedule_task_add(purge->schedule, 0,
325 (void *)purge, purge->timeout, 0,
326 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
328 SILC_LOG_DEBUG(("Server initialized"));
330 /* We are done here, return succesfully */
334 silc_net_close_server(sock);
338 /* Fork server to background */
340 void silc_server_daemonise(SilcServer server)
344 SILC_LOG_DEBUG(("Forking SILC server to background"));
349 SILC_LOG_DEBUG(("fork() failed, cannot proceed"));
354 SILC_LOG_DEBUG(("Server started as user"));
356 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
362 /* Drop root privligies. If this cannot be done, die. */
364 void silc_server_drop(SilcServer server)
366 /* Are we executing silcd as root or a regular user? */
372 /* Get the values given for user and group in configuration file */
373 user = server->config->server_info->user;
374 group = server->config->server_info->group;
376 if (!user || !group) {
377 fprintf(stderr, "Error:" /* XXX update this error message */
378 "\tSILC server must not be run as root. For the security of your\n"
379 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
380 "\tuser account. Modify the [Identity] configuration section to run\n"
381 "\tthe server as non-root user.\n");
385 /* Check whether the user/group does not begin with a number */
386 if (isdigit(user[0]) || isdigit(group[0])) {
387 SILC_LOG_DEBUG(("User and/or group starts with a number"));
388 fprintf(stderr, "Invalid user and/or group information\n");
389 fprintf(stderr, "Please assign them as names, not numbers\n");
393 if (!(pw = getpwnam(user))) {
394 fprintf(stderr, "Error: No such user %s found.\n", user);
397 if (!(gr = getgrnam(group))) {
398 fprintf(stderr, "Error: No such group %s found.\n", group);
402 /* Check whether user and/or group is set to root. If yes, exit
403 immediately. Otherwise, setgid and setuid server to user.group */
404 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
405 fprintf(stderr, "Error:"
406 "\tSILC server must not be run as root. For the security of your\n"
407 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
408 "\tuser account. Modify the [Identity] configuration section to run\n"
409 "\tthe server as non-root user.\n");
413 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
414 if (setgid(gr->gr_gid) != 0) {
415 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
419 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
420 SILC_LOG_DEBUG(("Removing supplementary groups"));
421 if (setgroups(0, NULL) != 0) {
422 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
425 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
426 if (initgroups(user, gr->gr_gid) != 0) {
427 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
428 "Exiting.\n", user, gr->gr_gid);
432 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
433 if (setuid(pw->pw_uid) != 0) {
434 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
441 /* The heart of the server. This runs the scheduler thus runs the server.
442 When this returns the server has been stopped and the program will
445 void silc_server_run(SilcServer server)
447 SILC_LOG_DEBUG(("Running server"));
449 SILC_LOG_INFO(("SILC Server started"));
451 /* Start the scheduler, the heart of the SILC server. When this returns
452 the program will be terminated. */
453 silc_schedule(server->schedule);
456 /* Stops the SILC server. This function is used to shutdown the server.
457 This is usually called after the scheduler has returned. After stopping
458 the server one should call silc_server_free. */
460 void silc_server_stop(SilcServer server)
462 SILC_LOG_DEBUG(("Stopping server"));
464 if (server->schedule) {
465 silc_schedule_stop(server->schedule);
466 silc_schedule_uninit(server->schedule);
467 server->schedule = NULL;
470 silc_server_protocols_unregister();
472 SILC_LOG_DEBUG(("Server stopped"));
475 /* Function that is called when the network connection to a router has
476 been established. This will continue with the key exchange protocol
477 with the remote router. */
479 void silc_server_start_key_exchange(SilcServer server,
480 SilcServerConnection sconn,
483 SilcSocketConnection newsocket;
484 SilcProtocol protocol;
485 SilcServerKEInternalContext *proto_ctx;
486 SilcServerConfigRouter *conn = sconn->conn;
489 /* Cancel any possible retry timeouts */
490 silc_schedule_task_del_by_callback(server->schedule,
491 silc_server_connect_router);
493 /* Set socket options */
494 silc_net_set_socket_nonblock(sock);
495 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
497 /* Create socket connection for the connection. Even though we
498 know that we are connecting to a router we will mark the socket
499 to be unknown connection until we have executed authentication
501 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
502 server->sockets[sock] = newsocket;
503 newsocket->hostname = strdup(sconn->remote_host);
504 newsocket->ip = strdup(sconn->remote_host);
505 newsocket->port = sconn->remote_port;
506 sconn->sock = newsocket;
508 /* Allocate internal protocol context. This is sent as context
510 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
511 proto_ctx->server = (void *)server;
512 proto_ctx->context = (void *)sconn;
513 proto_ctx->sock = newsocket;
514 proto_ctx->rng = server->rng;
515 proto_ctx->responder = FALSE;
517 /* Set Key Exchange flags from configuration, but fall back to global
519 SILC_GET_SKE_FLAGS(conn, proto_ctx);
520 if (server->config->param.key_exchange_pfs)
521 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
523 /* Perform key exchange protocol. silc_server_connect_to_router_second
524 will be called after the protocol is finished. */
525 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
526 &protocol, proto_ctx,
527 silc_server_connect_to_router_second);
528 newsocket->protocol = protocol;
530 /* Register a timeout task that will be executed if the protocol
531 is not executed within set limit. */
532 proto_ctx->timeout_task =
533 silc_schedule_task_add(server->schedule, sock,
534 silc_server_timeout_remote,
535 server, server->config->key_exchange_timeout, 0,
539 /* Register the connection for network input and output. This sets
540 that scheduler will listen for incoming packets for this connection
541 and sets that outgoing packets may be sent to this connection as
542 well. However, this doesn't set the scheduler for outgoing traffic,
543 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
544 later when outgoing data is available. */
545 context = (void *)server;
546 SILC_REGISTER_CONNECTION_FOR_IO(sock);
548 /* Run the protocol */
549 silc_protocol_execute(protocol, server->schedule, 0, 0);
552 /* Timeout callback that will be called to retry connecting to remote
553 router. This is used by both normal and router server. This will wait
554 before retrying the connecting. The timeout is generated by exponential
555 backoff algorithm. */
557 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
559 SilcServerConnection sconn = (SilcServerConnection)context;
560 SilcServer server = sconn->server;
561 SilcServerConfigConnParams *param =
562 (sconn->param ? sconn->param : &server->config->param);
564 SILC_LOG_INFO(("Retrying connecting to a router"));
566 /* Calculate next timeout */
567 if (sconn->retry_count >= 1) {
568 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
569 if (sconn->retry_timeout > param->reconnect_interval_max)
570 sconn->retry_timeout = param->reconnect_interval_max;
572 sconn->retry_timeout = param->reconnect_interval;
574 sconn->retry_count++;
575 sconn->retry_timeout = sconn->retry_timeout +
576 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
578 /* If we've reached max retry count, give up. */
579 if (sconn->retry_count > param->reconnect_count &&
580 param->reconnect_keep_trying == FALSE) {
581 SILC_LOG_ERROR(("Could not connect to router, giving up"));
582 silc_free(sconn->remote_host);
587 /* Wait one before retrying */
588 silc_schedule_task_add(server->schedule, fd, silc_server_connect_router,
589 context, sconn->retry_timeout, 0,
590 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
593 /* Generic routine to use connect to a router. */
595 SILC_TASK_CALLBACK(silc_server_connect_router)
597 SilcServerConnection sconn = (SilcServerConnection)context;
598 SilcServer server = sconn->server;
601 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
602 (sconn->backup ? "backup router" : "router"),
603 sconn->remote_host, sconn->remote_port));
605 server->router_connect = time(NULL);
607 /* Connect to remote host */
608 sock = silc_net_create_connection(server->config->server_info->server_ip,
612 SILC_LOG_ERROR(("Could not connect to router %s:%d",
613 sconn->remote_host, sconn->remote_port));
614 if (!sconn->no_reconnect)
615 silc_schedule_task_add(server->schedule, fd,
616 silc_server_connect_to_router_retry,
617 context, 0, 1, SILC_TASK_TIMEOUT,
618 SILC_TASK_PRI_NORMAL);
622 /* Continue with key exchange protocol */
623 silc_server_start_key_exchange(server, sconn, sock);
626 /* This function connects to our primary router or if we are a router this
627 establishes all our primary routes. This is called at the start of the
628 server to do authentication and key exchange with our router - called
631 SILC_TASK_CALLBACK(silc_server_connect_to_router)
633 SilcServer server = (SilcServer)context;
634 SilcServerConnection sconn;
635 SilcServerConfigRouter *ptr;
637 SILC_LOG_DEBUG(("Connecting to router(s)"));
639 if (server->server_type == SILC_SERVER) {
640 SILC_LOG_DEBUG(("We are normal server"));
641 } else if (server->server_type == SILC_ROUTER) {
642 SILC_LOG_DEBUG(("We are router"));
644 SILC_LOG_DEBUG(("We are backup router/normal server"));
647 /* Create the connections to all our routes */
648 ptr = server->config->routers;
651 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
652 ptr->backup_router ? "Backup router" : "Router",
653 ptr->initiator ? "Initiator" : "Responder",
654 ptr->host, ptr->port));
656 if (ptr->initiator) {
657 /* Allocate connection object for hold connection specific stuff. */
658 sconn = silc_calloc(1, sizeof(*sconn));
659 sconn->server = server;
660 sconn->remote_host = strdup(ptr->host);
661 sconn->remote_port = ptr->port;
662 sconn->backup = ptr->backup_router;
664 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
665 sconn->backup_replace_port = ptr->backup_replace_port;
668 if (!server->router_conn && !sconn->backup)
669 server->router_conn = sconn;
672 sconn->param = ptr->param;
674 silc_schedule_task_add(server->schedule, fd,
675 silc_server_connect_router,
676 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
677 SILC_TASK_PRI_NORMAL);
686 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
688 /* There wasn't a configured router, we will continue but we don't
689 have a connection to outside world. We will be standalone server. */
690 server->standalone = TRUE;
693 /* Second part of connecting to router(s). Key exchange protocol has been
694 executed and now we will execute authentication protocol. */
696 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
698 SilcProtocol protocol = (SilcProtocol)context;
699 SilcServerKEInternalContext *ctx =
700 (SilcServerKEInternalContext *)protocol->context;
701 SilcServer server = (SilcServer)ctx->server;
702 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
703 SilcSocketConnection sock = ctx->sock;
704 SilcServerConnAuthInternalContext *proto_ctx;
705 SilcServerConfigRouter *conn = NULL;
707 SILC_LOG_DEBUG(("Start"));
709 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
710 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
711 /* Error occured during protocol */
712 silc_protocol_free(protocol);
713 sock->protocol = NULL;
714 silc_ske_free_key_material(ctx->keymat);
716 silc_packet_context_free(ctx->packet);
718 silc_ske_free(ctx->ske);
719 silc_free(ctx->dest_id);
721 silc_schedule_task_del_by_callback(server->schedule,
722 silc_server_failure_callback);
723 silc_server_disconnect_remote(server, sock, "Server closed connection: "
724 "Key exchange failed");
728 /* We now have the key material as the result of the key exchange
729 protocol. Take the key material into use. Free the raw key material
730 as soon as we've set them into use. */
731 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
732 ctx->sock, ctx->keymat,
733 ctx->ske->prop->cipher,
734 ctx->ske->prop->pkcs,
735 ctx->ske->prop->hash,
736 ctx->ske->prop->hmac,
737 ctx->ske->prop->group,
739 silc_protocol_free(protocol);
740 sock->protocol = NULL;
741 silc_ske_free_key_material(ctx->keymat);
743 silc_packet_context_free(ctx->packet);
745 silc_ske_free(ctx->ske);
746 silc_free(ctx->dest_id);
748 silc_schedule_task_del_by_callback(server->schedule,
749 silc_server_failure_callback);
750 silc_server_disconnect_remote(server, sock, "Server closed connection: "
751 "Key exchange failed");
754 silc_ske_free_key_material(ctx->keymat);
756 /* Allocate internal context for the authentication protocol. This
757 is sent as context for the protocol. */
758 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
759 proto_ctx->server = (void *)server;
760 proto_ctx->context = (void *)sconn;
761 proto_ctx->sock = sock;
762 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
763 proto_ctx->dest_id_type = ctx->dest_id_type;
764 proto_ctx->dest_id = ctx->dest_id;
766 /* Resolve the authentication method used in this connection. Check if
767 we find a match from user configured connections */
769 conn = silc_server_config_find_router_conn(server, sock->hostname,
775 /* Match found. Use the configured authentication method. Take only
776 the passphrase, since for public key auth we automatically use
777 our local key pair. */
778 if (conn->passphrase) {
779 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
780 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
782 proto_ctx->auth_data = strdup(conn->passphrase);
783 proto_ctx->auth_data_len = strlen(conn->passphrase);
784 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
786 } else if (conn->publickeys) {
787 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
789 proto_ctx->auth_meth = SILC_AUTH_NONE;
792 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
793 sock->hostname, sock->ip, sock->port));
794 silc_protocol_free(protocol);
795 sock->protocol = NULL;
797 silc_packet_context_free(ctx->packet);
799 silc_ske_free(ctx->ske);
800 silc_free(ctx->dest_id);
802 silc_schedule_task_del_by_callback(server->schedule,
803 silc_server_failure_callback);
804 silc_server_disconnect_remote(server, sock, "Server closed connection: "
805 "Key exchange failed");
809 /* Free old protocol as it is finished now */
810 silc_protocol_free(protocol);
812 silc_packet_context_free(ctx->packet);
814 sock->protocol = NULL;
816 /* Allocate the authentication protocol. This is allocated here
817 but we won't start it yet. We will be receiving party of this
818 protocol thus we will wait that connecting party will make
820 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
821 &sock->protocol, proto_ctx,
822 silc_server_connect_to_router_final);
824 /* Register timeout task. If the protocol is not executed inside
825 this timelimit the connection will be terminated. */
826 proto_ctx->timeout_task =
827 silc_schedule_task_add(server->schedule, sock->sock,
828 silc_server_timeout_remote,
830 server->config->conn_auth_timeout, 0,
834 /* Run the protocol */
835 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
838 /* Finalizes the connection to router. Registers a server task to the
839 queue so that we can accept new connections. */
841 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
843 SilcProtocol protocol = (SilcProtocol)context;
844 SilcServerConnAuthInternalContext *ctx =
845 (SilcServerConnAuthInternalContext *)protocol->context;
846 SilcServer server = (SilcServer)ctx->server;
847 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
848 SilcSocketConnection sock = ctx->sock;
849 SilcServerEntry id_entry;
851 SilcServerHBContext hb_context;
852 unsigned char *id_string;
854 SilcIDListData idata;
855 SilcServerConfigConnParams *param;
857 SILC_LOG_DEBUG(("Start"));
859 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
860 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
861 /* Error occured during protocol */
862 silc_free(ctx->dest_id);
863 silc_server_disconnect_remote(server, sock, "Server closed connection: "
864 "Authentication failed");
868 /* Add a task to the queue. This task receives new connections to the
869 server. This task remains on the queue until the end of the program. */
870 if (!server->listenning && !sconn->backup) {
871 silc_schedule_task_add(server->schedule, server->sock,
872 silc_server_accept_new_connection,
873 (void *)server, 0, 0,
875 SILC_TASK_PRI_NORMAL);
876 server->listenning = TRUE;
879 /* Send NEW_SERVER packet to the router. We will become registered
880 to the SILC network after sending this packet. */
881 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
882 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
883 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
884 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
885 silc_buffer_format(packet,
886 SILC_STR_UI_SHORT(id_len),
887 SILC_STR_UI_XNSTRING(id_string, id_len),
888 SILC_STR_UI_SHORT(strlen(server->server_name)),
889 SILC_STR_UI_XNSTRING(server->server_name,
890 strlen(server->server_name)),
893 /* Send the packet */
894 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
895 packet->data, packet->len, TRUE);
896 silc_buffer_free(packet);
897 silc_free(id_string);
899 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
901 /* Check that we do not have this ID already */
902 id_entry = silc_idlist_find_server_by_id(server->local_list,
903 ctx->dest_id, TRUE, NULL);
905 silc_idcache_del_by_context(server->local_list->servers, id_entry);
907 id_entry = silc_idlist_find_server_by_id(server->global_list,
908 ctx->dest_id, TRUE, NULL);
910 silc_idcache_del_by_context(server->global_list->servers, id_entry);
913 SILC_LOG_DEBUG(("New server id(%s)",
914 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
916 /* Add the connected router to global server list */
917 id_entry = silc_idlist_add_server(server->global_list,
918 strdup(sock->hostname),
919 SILC_ROUTER, ctx->dest_id, NULL, sock);
921 silc_free(ctx->dest_id);
922 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
923 silc_server_disconnect_remote(server, sock, "Server closed connection: "
924 "Authentication failed");
928 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
929 silc_free(sock->user_data);
930 sock->user_data = (void *)id_entry;
931 sock->type = SILC_SOCKET_TYPE_ROUTER;
932 idata = (SilcIDListData)sock->user_data;
933 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
935 param = (sconn->param ? sconn->param : &server->config->param);
937 /* Perform keepalive. The `hb_context' will be freed automatically
938 when finally calling the silc_socket_free function. */
939 hb_context = silc_calloc(1, sizeof(*hb_context));
940 hb_context->server = server;
941 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
942 silc_server_perform_heartbeat,
945 /* Register re-key timeout */
946 idata->rekey->timeout = param->key_exchange_rekey;
947 idata->rekey->context = (void *)server;
948 silc_schedule_task_add(server->schedule, sock->sock,
949 silc_server_rekey_callback,
950 (void *)sock, idata->rekey->timeout, 0,
951 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
953 if (!sconn->backup) {
954 /* Mark this router our primary router if we're still standalone */
955 if (server->standalone) {
956 server->id_entry->router = id_entry;
957 server->router = id_entry;
958 server->standalone = FALSE;
960 /* If we are router then announce our possible servers. */
961 if (server->server_type == SILC_ROUTER)
962 silc_server_announce_servers(server, FALSE, 0,
963 server->router->connection);
965 /* Announce our clients and channels to the router */
966 silc_server_announce_clients(server, 0, server->router->connection);
967 silc_server_announce_channels(server, 0, server->router->connection);
970 /* Add this server to be our backup router */
971 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
972 sconn->backup_replace_port, FALSE);
975 sock->protocol = NULL;
977 /* Call the completion callback to indicate that we've connected to
980 (*sconn->callback)(server, id_entry, sconn->callback_context);
983 /* Free the temporary connection data context */
985 silc_free(sconn->remote_host);
986 silc_free(sconn->backup_replace_ip);
989 if (sconn == server->router_conn)
990 server->router_conn = NULL;
992 /* Free the protocol object */
993 if (sock->protocol == protocol)
994 sock->protocol = NULL;
995 silc_protocol_free(protocol);
997 silc_packet_context_free(ctx->packet);
999 silc_ske_free(ctx->ske);
1000 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1001 silc_free(ctx->auth_data);
1005 /* Host lookup callbcak that is called after the incoming connection's
1006 IP and FQDN lookup is performed. This will actually check the acceptance
1007 of the incoming connection and will register the key exchange protocol
1008 for this connection. */
1011 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1014 SilcServer server = (SilcServer)context;
1015 SilcServerKEInternalContext *proto_ctx;
1016 SilcServerConfigClient *cconfig = NULL;
1017 SilcServerConfigServer *sconfig = NULL;
1018 SilcServerConfigRouter *rconfig = NULL;
1019 SilcServerConfigDeny *deny;
1022 SILC_LOG_DEBUG(("Start"));
1024 /* Check whether we could resolve both IP and FQDN. */
1025 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1026 server->config->require_reverse_lookup)) {
1027 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1028 sock->hostname ? sock->hostname :
1029 sock->ip ? sock->ip : ""));
1030 server->stat.conn_failures++;
1031 silc_server_disconnect_remote(server, sock,
1032 "Server closed connection: Unknown host");
1036 /* Register the connection for network input and output. This sets
1037 that scheduler will listen for incoming packets for this connection
1038 and sets that outgoing packets may be sent to this connection as well.
1039 However, this doesn't set the scheduler for outgoing traffic, it
1040 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1041 later when outgoing data is available. */
1042 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1044 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1047 port = server->sockets[server->sock]->port; /* Listenning port */
1049 /* Check whether this connection is denied to connect to us. */
1050 deny = silc_server_config_find_denied(server, sock->ip);
1052 deny = silc_server_config_find_denied(server, sock->hostname);
1054 /* The connection is denied */
1055 SILC_LOG_INFO(("Connection %s (%s) is denied",
1056 sock->hostname, sock->ip));
1057 silc_server_disconnect_remote(server, sock, deny->reason ?
1059 "Server closed connection: "
1060 "Connection refused");
1061 server->stat.conn_failures++;
1065 /* Check whether we have configred this sort of connection at all. We
1066 have to check all configurations since we don't know what type of
1067 connection this is. */
1068 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1069 cconfig = silc_server_config_find_client(server, sock->hostname);
1070 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1071 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1072 if (server->server_type == SILC_ROUTER) {
1073 if (!(rconfig = silc_server_config_find_router_conn(server,
1075 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1078 if (!cconfig && !sconfig && !rconfig) {
1079 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1081 silc_server_disconnect_remote(server, sock,
1082 "Server closed connection: "
1083 "Connection refused");
1084 server->stat.conn_failures++;
1088 /* The connection is allowed */
1090 /* Allocate internal context for key exchange protocol. This is
1091 sent as context for the protocol. */
1092 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1093 proto_ctx->server = context;
1094 proto_ctx->sock = sock;
1095 proto_ctx->rng = server->rng;
1096 proto_ctx->responder = TRUE;
1097 proto_ctx->cconfig = cconfig;
1098 proto_ctx->sconfig = sconfig;
1099 proto_ctx->rconfig = rconfig;
1101 /* Take flags for key exchange. Since we do not know what type of connection
1102 this is, we go through all found configuratios and use the global ones
1103 as well. This will result always into strictest key exchange flags. */
1104 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1105 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1106 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1107 if (server->config->param.key_exchange_pfs)
1108 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1110 /* Prepare the connection for key exchange protocol. We allocate the
1111 protocol but will not start it yet. The connector will be the
1112 initiator of the protocol thus we will wait for initiation from
1113 there before we start the protocol. */
1114 server->stat.auth_attempts++;
1115 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1116 &sock->protocol, proto_ctx,
1117 silc_server_accept_new_connection_second);
1119 /* Register a timeout task that will be executed if the connector
1120 will not start the key exchange protocol within specified timeout
1121 and the connection will be closed. */
1122 proto_ctx->timeout_task =
1123 silc_schedule_task_add(server->schedule, sock->sock,
1124 silc_server_timeout_remote,
1125 context, server->config->key_exchange_timeout, 0,
1130 /* Accepts new connections to the server. Accepting new connections are
1131 done in three parts to make it async. */
1133 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1135 SilcServer server = (SilcServer)context;
1136 SilcSocketConnection newsocket;
1139 SILC_LOG_DEBUG(("Accepting new connection"));
1141 server->stat.conn_attempts++;
1143 sock = silc_net_accept_connection(server->sock);
1145 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1146 server->stat.conn_failures++;
1150 /* Check for maximum allowed connections */
1151 if (sock > server->config->param.connections_max) {
1152 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1153 server->stat.conn_failures++;
1157 /* Set socket options */
1158 silc_net_set_socket_nonblock(sock);
1159 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1161 /* We don't create a ID yet, since we don't know what type of connection
1162 this is yet. But, we do add the connection to the socket table. */
1163 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1164 server->sockets[sock] = newsocket;
1166 /* Perform asynchronous host lookup. This will lookup the IP and the
1167 FQDN of the remote connection. After the lookup is done the connection
1168 is accepted further. */
1169 silc_socket_host_lookup(newsocket, TRUE,
1170 silc_server_accept_new_connection_lookup, context,
1174 /* Second part of accepting new connection. Key exchange protocol has been
1175 performed and now it is time to do little connection authentication
1176 protocol to figure out whether this connection is client or server
1177 and whether it has right to access this server (especially server
1178 connections needs to be authenticated). */
1180 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1182 SilcProtocol protocol = (SilcProtocol)context;
1183 SilcServerKEInternalContext *ctx =
1184 (SilcServerKEInternalContext *)protocol->context;
1185 SilcServer server = (SilcServer)ctx->server;
1186 SilcSocketConnection sock = ctx->sock;
1187 SilcServerConnAuthInternalContext *proto_ctx;
1189 SILC_LOG_DEBUG(("Start"));
1191 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1192 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1193 /* Error occured during protocol */
1194 silc_protocol_free(protocol);
1195 sock->protocol = NULL;
1196 silc_ske_free_key_material(ctx->keymat);
1198 silc_packet_context_free(ctx->packet);
1200 silc_ske_free(ctx->ske);
1201 silc_free(ctx->dest_id);
1203 silc_schedule_task_del_by_callback(server->schedule,
1204 silc_server_failure_callback);
1205 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1206 "Key exchange failed");
1207 server->stat.auth_failures++;
1211 /* We now have the key material as the result of the key exchange
1212 protocol. Take the key material into use. Free the raw key material
1213 as soon as we've set them into use. */
1214 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1215 ctx->sock, ctx->keymat,
1216 ctx->ske->prop->cipher,
1217 ctx->ske->prop->pkcs,
1218 ctx->ske->prop->hash,
1219 ctx->ske->prop->hmac,
1220 ctx->ske->prop->group,
1222 silc_protocol_free(protocol);
1223 sock->protocol = NULL;
1224 silc_ske_free_key_material(ctx->keymat);
1226 silc_packet_context_free(ctx->packet);
1228 silc_ske_free(ctx->ske);
1229 silc_free(ctx->dest_id);
1231 silc_schedule_task_del_by_callback(server->schedule,
1232 silc_server_failure_callback);
1233 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1234 "Key exchange failed");
1235 server->stat.auth_failures++;
1238 silc_ske_free_key_material(ctx->keymat);
1240 /* Allocate internal context for the authentication protocol. This
1241 is sent as context for the protocol. */
1242 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1243 proto_ctx->server = (void *)server;
1244 proto_ctx->sock = sock;
1245 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1246 proto_ctx->responder = TRUE;
1247 proto_ctx->dest_id_type = ctx->dest_id_type;
1248 proto_ctx->dest_id = ctx->dest_id;
1249 proto_ctx->cconfig = ctx->cconfig;
1250 proto_ctx->sconfig = ctx->sconfig;
1251 proto_ctx->rconfig = ctx->rconfig;
1253 /* Free old protocol as it is finished now */
1254 silc_protocol_free(protocol);
1256 silc_packet_context_free(ctx->packet);
1258 sock->protocol = NULL;
1260 /* Allocate the authentication protocol. This is allocated here
1261 but we won't start it yet. We will be receiving party of this
1262 protocol thus we will wait that connecting party will make
1263 their first move. */
1264 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1265 &sock->protocol, proto_ctx,
1266 silc_server_accept_new_connection_final);
1268 /* Register timeout task. If the protocol is not executed inside
1269 this timelimit the connection will be terminated. */
1270 proto_ctx->timeout_task =
1271 silc_schedule_task_add(server->schedule, sock->sock,
1272 silc_server_timeout_remote,
1274 server->config->conn_auth_timeout, 0,
1279 /* Final part of accepting new connection. The connection has now
1280 been authenticated and keys has been exchanged. We also know whether
1281 this is client or server connection. */
1283 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1285 SilcProtocol protocol = (SilcProtocol)context;
1286 SilcServerConnAuthInternalContext *ctx =
1287 (SilcServerConnAuthInternalContext *)protocol->context;
1288 SilcServer server = (SilcServer)ctx->server;
1289 SilcSocketConnection sock = ctx->sock;
1290 SilcServerHBContext hb_context;
1291 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1293 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1295 SILC_LOG_DEBUG(("Start"));
1297 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1298 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1299 /* Error occured during protocol */
1300 silc_protocol_free(protocol);
1301 sock->protocol = NULL;
1303 silc_packet_context_free(ctx->packet);
1305 silc_ske_free(ctx->ske);
1306 silc_free(ctx->dest_id);
1308 silc_schedule_task_del_by_callback(server->schedule,
1309 silc_server_failure_callback);
1310 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1311 "Authentication failed");
1312 server->stat.auth_failures++;
1316 entry->data.last_receive = time(NULL);
1318 switch (ctx->conn_type) {
1319 case SILC_SOCKET_TYPE_CLIENT:
1321 SilcClientEntry client;
1322 SilcServerConfigClient *conn = ctx->cconfig;
1324 /* Verify whether this connection is after all allowed to connect */
1325 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1326 &server->config->param,
1327 conn->param, ctx->ske)) {
1328 server->stat.auth_failures++;
1332 SILC_LOG_DEBUG(("Remote host is client"));
1333 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1336 /* Add the client to the client ID cache. The nickname and Client ID
1337 and other information is created after we have received NEW_CLIENT
1338 packet from client. */
1339 client = silc_idlist_add_client(server->local_list,
1340 NULL, NULL, NULL, NULL, NULL, sock, 0);
1342 SILC_LOG_ERROR(("Could not add new client to cache"));
1343 silc_free(sock->user_data);
1344 silc_server_disconnect_remote(server, sock,
1345 "Server closed connection: "
1346 "Authentication failed");
1347 server->stat.auth_failures++;
1352 server->stat.my_clients++;
1353 server->stat.clients++;
1354 if (server->server_type == SILC_ROUTER)
1355 server->stat.cell_clients++;
1357 /* Get connection parameters */
1359 if (conn->param->keepalive_secs)
1360 hearbeat_timeout = conn->param->keepalive_secs;
1363 id_entry = (void *)client;
1366 case SILC_SOCKET_TYPE_SERVER:
1367 case SILC_SOCKET_TYPE_ROUTER:
1369 SilcServerEntry new_server;
1370 bool initiator = FALSE;
1371 bool backup_local = FALSE;
1372 bool backup_router = FALSE;
1373 char *backup_replace_ip = NULL;
1374 SilcUInt16 backup_replace_port = 0;
1375 SilcServerConfigServer *sconn = ctx->sconfig;
1376 SilcServerConfigRouter *rconn = ctx->rconfig;
1378 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1379 /* Verify whether this connection is after all allowed to connect */
1380 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1381 &server->config->param,
1382 rconn ? rconn->param : NULL,
1384 server->stat.auth_failures++;
1390 if (rconn->param->keepalive_secs)
1391 hearbeat_timeout = rconn->param->keepalive_secs;
1394 initiator = rconn->initiator;
1395 backup_local = rconn->backup_local;
1396 backup_router = rconn->backup_router;
1397 backup_replace_ip = rconn->backup_replace_ip;
1398 backup_replace_port = rconn->backup_replace_port;
1402 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1403 /* Verify whether this connection is after all allowed to connect */
1404 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1405 &server->config->param,
1406 sconn ? sconn->param : NULL,
1408 server->stat.auth_failures++;
1413 if (sconn->param->keepalive_secs)
1414 hearbeat_timeout = sconn->param->keepalive_secs;
1417 backup_router = sconn->backup_router;
1421 SILC_LOG_DEBUG(("Remote host is %s",
1422 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1423 "server" : (backup_router ?
1424 "backup router" : "router")));
1425 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1426 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1427 "server" : (backup_router ?
1428 "backup router" : "router")));
1430 /* Add the server into server cache. The server name and Server ID
1431 is updated after we have received NEW_SERVER packet from the
1432 server. We mark ourselves as router for this server if we really
1435 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1436 server->local_list : (backup_router ?
1437 server->local_list :
1438 server->global_list)),
1440 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1441 SILC_SERVER : SILC_ROUTER),
1443 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1444 server->id_entry : (backup_router ?
1445 server->id_entry : NULL)),
1448 SILC_LOG_ERROR(("Could not add new server to cache"));
1449 silc_free(sock->user_data);
1450 silc_server_disconnect_remote(server, sock,
1451 "Server closed connection: "
1452 "Authentication failed");
1453 server->stat.auth_failures++;
1458 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1459 server->stat.my_servers++;
1461 server->stat.my_routers++;
1462 server->stat.servers++;
1464 id_entry = (void *)new_server;
1466 /* If the incoming connection is router and marked as backup router
1467 then add it to be one of our backups */
1468 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1469 silc_server_backup_add(server, new_server, backup_replace_ip,
1470 backup_replace_port, backup_local);
1472 /* Change it back to SERVER type since that's what it really is. */
1474 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1476 new_server->server_type = SILC_BACKUP_ROUTER;
1479 /* Check whether this connection is to be our primary router connection
1480 if we do not already have the primary route. */
1481 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1482 if (silc_server_config_is_primary_route(server) && !initiator)
1485 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1486 server->standalone = FALSE;
1487 if (!server->id_entry->router) {
1488 server->id_entry->router = id_entry;
1489 server->router = id_entry;
1500 sock->type = ctx->conn_type;
1502 /* Add the common data structure to the ID entry. */
1503 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1505 /* Add to sockets internal pointer for fast referencing */
1506 silc_free(sock->user_data);
1507 sock->user_data = id_entry;
1509 /* Connection has been fully established now. Everything is ok. */
1510 SILC_LOG_DEBUG(("New connection authenticated"));
1512 /* Perform keepalive. The `hb_context' will be freed automatically
1513 when finally calling the silc_socket_free function. */
1514 hb_context = silc_calloc(1, sizeof(*hb_context));
1515 hb_context->server = server;
1516 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1517 silc_server_perform_heartbeat,
1521 silc_schedule_task_del_by_callback(server->schedule,
1522 silc_server_failure_callback);
1523 silc_protocol_free(protocol);
1525 silc_packet_context_free(ctx->packet);
1527 silc_ske_free(ctx->ske);
1528 silc_free(ctx->dest_id);
1530 sock->protocol = NULL;
1533 /* This function is used to read packets from network and send packets to
1534 network. This is usually a generic task. */
1536 SILC_TASK_CALLBACK(silc_server_packet_process)
1538 SilcServer server = (SilcServer)context;
1539 SilcSocketConnection sock = server->sockets[fd];
1540 SilcIDListData idata;
1541 SilcCipher cipher = NULL;
1542 SilcHmac hmac = NULL;
1543 SilcUInt32 sequence = 0;
1549 SILC_LOG_DEBUG(("Processing packet"));
1551 /* Packet sending */
1553 if (type == SILC_TASK_WRITE) {
1554 /* Do not send data to disconnected connection */
1555 if (SILC_IS_DISCONNECTED(sock))
1558 server->stat.packets_sent++;
1560 /* Send the packet */
1561 ret = silc_packet_send(sock, TRUE);
1563 /* If returned -2 could not write to connection now, will do
1569 SILC_LOG_ERROR(("Error sending packet to connection "
1570 "%s:%d [%s]", sock->hostname, sock->port,
1571 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1572 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1573 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1578 /* The packet has been sent and now it is time to set the connection
1579 back to only for input. When there is again some outgoing data
1580 available for this connection it will be set for output as well.
1581 This call clears the output setting and sets it only for input. */
1582 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1583 SILC_UNSET_OUTBUF_PENDING(sock);
1585 silc_buffer_clear(sock->outbuf);
1589 /* Packet receiving */
1591 /* Read some data from connection */
1592 ret = silc_packet_receive(sock);
1596 SILC_LOG_ERROR(("Error receiving packet from connection "
1597 "%s:%d [%s] %s", sock->hostname, sock->port,
1598 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1599 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1600 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1601 "Router"), strerror(errno)));
1607 SILC_LOG_DEBUG(("Read EOF"));
1609 /* If connection is disconnecting already we will finally
1610 close the connection */
1611 if (SILC_IS_DISCONNECTING(sock)) {
1612 if (sock->user_data)
1613 silc_server_free_sock_user_data(server, sock, NULL);
1614 silc_server_close_connection(server, sock);
1618 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1619 SILC_SET_DISCONNECTING(sock);
1621 if (sock->user_data) {
1623 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1624 silc_server_free_sock_user_data(server, sock, tmp);
1626 silc_server_free_sock_user_data(server, sock, NULL);
1627 } else if (server->router_conn && server->router_conn->sock == sock &&
1628 !server->router && server->standalone)
1629 silc_schedule_task_add(server->schedule, 0,
1630 silc_server_connect_to_router,
1633 SILC_TASK_PRI_NORMAL);
1635 silc_server_close_connection(server, sock);
1639 /* If connection is disconnecting or disconnected we will ignore
1641 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1642 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1646 server->stat.packets_received++;
1648 /* Get keys and stuff from ID entry */
1649 idata = (SilcIDListData)sock->user_data;
1651 cipher = idata->receive_key;
1652 hmac = idata->hmac_receive;
1653 sequence = idata->psn_receive;
1656 /* Process the packet. This will call the parser that will then
1657 decrypt and parse the packet. */
1658 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1659 TRUE : FALSE, cipher, hmac, sequence,
1660 silc_server_packet_parse, server);
1662 /* If this socket connection is not authenticated yet and the packet
1663 processing failed we will drop the connection since it can be
1664 a malicious flooder. */
1665 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1666 (!sock->protocol || sock->protocol->protocol->type ==
1667 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1668 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1669 SILC_SET_DISCONNECTING(sock);
1671 if (sock->user_data)
1672 silc_server_free_sock_user_data(server, sock, NULL);
1673 silc_server_close_connection(server, sock);
1677 /* Parses whole packet, received earlier. */
1679 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1681 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1682 SilcServer server = (SilcServer)parse_ctx->context;
1683 SilcSocketConnection sock = parse_ctx->sock;
1684 SilcPacketContext *packet = parse_ctx->packet;
1685 SilcIDListData idata = (SilcIDListData)sock->user_data;
1688 SILC_LOG_DEBUG(("Start"));
1690 /* Parse the packet */
1691 if (parse_ctx->normal)
1692 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1694 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1696 /* If entry is disabled ignore what we got. */
1697 if (ret != SILC_PACKET_RESUME_ROUTER &&
1698 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1699 SILC_LOG_DEBUG(("Connection is disabled"));
1703 if (ret == SILC_PACKET_NONE)
1706 /* Check that the the current client ID is same as in the client's packet. */
1707 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1708 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1709 if (client && client->id) {
1710 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1711 packet->src_id_type);
1712 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1720 if (server->server_type == SILC_ROUTER) {
1721 /* Route the packet if it is not destined to us. Other ID types but
1722 server are handled separately after processing them. */
1723 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1724 packet->dst_id_type == SILC_ID_SERVER &&
1725 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1726 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1728 /* Route the packet to fastest route for the destination ID */
1729 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1730 packet->dst_id_type);
1733 silc_server_packet_route(server,
1734 silc_server_route_get(server, id,
1735 packet->dst_id_type),
1742 /* Parse the incoming packet type */
1743 silc_server_packet_parse_type(server, sock, packet);
1745 if (server->server_type == SILC_ROUTER) {
1746 /* Broadcast packet if it is marked as broadcast packet and it is
1747 originated from router and we are router. */
1748 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1749 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1750 !server->standalone) {
1751 /* Broadcast to our primary route */
1752 silc_server_packet_broadcast(server, server->router->connection, packet);
1754 /* If we have backup routers then we need to feed all broadcast
1755 data to those servers. */
1756 silc_server_backup_broadcast(server, sock, packet);
1761 silc_packet_context_free(packet);
1762 silc_free(parse_ctx);
1765 /* Parser callback called by silc_packet_receive_process. This merely
1766 registers timeout that will handle the actual parsing when appropriate. */
1768 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1771 SilcServer server = (SilcServer)context;
1772 SilcSocketConnection sock = parser_context->sock;
1773 SilcIDListData idata = (SilcIDListData)sock->user_data;
1776 idata->psn_receive = parser_context->packet->sequence + 1;
1778 /* If protocol for this connection is key exchange or rekey then we'll
1779 process all packets synchronously, since there might be packets in
1780 queue that we are not able to decrypt without first processing the
1781 packets before them. */
1782 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1783 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1784 (sock->protocol && sock->protocol->protocol &&
1785 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1786 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1787 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1790 /* Reprocess data since we'll return FALSE here. This is because
1791 the idata->receive_key might have become valid in the last packet
1792 and we want to call this processor with valid cipher. */
1794 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1795 TRUE : FALSE, idata->receive_key,
1796 idata->hmac_receive, idata->psn_receive,
1797 silc_server_packet_parse, server);
1799 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1800 TRUE : FALSE, NULL, NULL, 0,
1801 silc_server_packet_parse, server);
1805 switch (sock->type) {
1806 case SILC_SOCKET_TYPE_UNKNOWN:
1807 case SILC_SOCKET_TYPE_CLIENT:
1808 /* Parse the packet with timeout */
1809 silc_schedule_task_add(server->schedule, sock->sock,
1810 silc_server_packet_parse_real,
1811 (void *)parser_context, 0, 100000,
1813 SILC_TASK_PRI_NORMAL);
1815 case SILC_SOCKET_TYPE_SERVER:
1816 case SILC_SOCKET_TYPE_ROUTER:
1817 /* Packets from servers are parsed immediately */
1818 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1828 /* Parses the packet type and calls what ever routines the packet type
1829 requires. This is done for all incoming packets. */
1831 void silc_server_packet_parse_type(SilcServer server,
1832 SilcSocketConnection sock,
1833 SilcPacketContext *packet)
1835 SilcPacketType type = packet->type;
1836 SilcIDListData idata = (SilcIDListData)sock->user_data;
1838 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1840 /* Parse the packet type */
1842 case SILC_PACKET_DISCONNECT:
1843 SILC_LOG_DEBUG(("Disconnect packet"));
1844 if (packet->flags & SILC_PACKET_FLAG_LIST)
1846 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1847 /* Duplicate to null terminate the string. */
1848 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1849 SILC_LOG_ERROR(("%s", message));
1854 case SILC_PACKET_SUCCESS:
1856 * Success received for something. For now we can have only
1857 * one protocol for connection executing at once hence this
1858 * success message is for whatever protocol is executing currently.
1860 SILC_LOG_DEBUG(("Success packet"));
1861 if (packet->flags & SILC_PACKET_FLAG_LIST)
1864 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1867 case SILC_PACKET_FAILURE:
1869 * Failure received for something. For now we can have only
1870 * one protocol for connection executing at once hence this
1871 * failure message is for whatever protocol is executing currently.
1873 SILC_LOG_DEBUG(("Failure packet"));
1874 if (packet->flags & SILC_PACKET_FLAG_LIST)
1876 if (sock->protocol) {
1877 SilcServerFailureContext f;
1878 f = silc_calloc(1, sizeof(*f));
1882 /* We will wait 5 seconds to process this failure packet */
1883 silc_schedule_task_add(server->schedule, sock->sock,
1884 silc_server_failure_callback, (void *)f, 5, 0,
1885 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1889 case SILC_PACKET_REJECT:
1890 SILC_LOG_DEBUG(("Reject packet"));
1891 if (packet->flags & SILC_PACKET_FLAG_LIST)
1896 case SILC_PACKET_NOTIFY:
1898 * Received notify packet. Server can receive notify packets from
1899 * router. Server then relays the notify messages to clients if needed.
1901 SILC_LOG_DEBUG(("Notify packet"));
1902 if (packet->flags & SILC_PACKET_FLAG_LIST)
1903 silc_server_notify_list(server, sock, packet);
1905 silc_server_notify(server, sock, packet);
1911 case SILC_PACKET_CHANNEL_MESSAGE:
1913 * Received channel message. Channel messages are special packets
1914 * (although probably most common ones) thus they are handled
1917 SILC_LOG_DEBUG(("Channel Message packet"));
1918 if (packet->flags & SILC_PACKET_FLAG_LIST)
1920 idata->last_receive = time(NULL);
1921 silc_server_channel_message(server, sock, packet);
1924 case SILC_PACKET_CHANNEL_KEY:
1926 * Received key for channel. As channels are created by the router
1927 * the keys are as well. We will distribute the key to all of our
1928 * locally connected clients on the particular channel. Router
1929 * never receives this channel and thus is ignored.
1931 SILC_LOG_DEBUG(("Channel Key packet"));
1932 if (packet->flags & SILC_PACKET_FLAG_LIST)
1934 silc_server_channel_key(server, sock, packet);
1940 case SILC_PACKET_COMMAND:
1942 * Recived command. Processes the command request and allocates the
1943 * command context and calls the command.
1945 SILC_LOG_DEBUG(("Command packet"));
1946 if (packet->flags & SILC_PACKET_FLAG_LIST)
1948 silc_server_command_process(server, sock, packet);
1951 case SILC_PACKET_COMMAND_REPLY:
1953 * Received command reply packet. Received command reply to command. It
1954 * may be reply to command sent by us or reply to command sent by client
1955 * that we've routed further.
1957 SILC_LOG_DEBUG(("Command Reply packet"));
1958 if (packet->flags & SILC_PACKET_FLAG_LIST)
1960 silc_server_command_reply(server, sock, packet);
1964 * Private Message packets
1966 case SILC_PACKET_PRIVATE_MESSAGE:
1968 * Received private message packet. The packet is coming from either
1971 SILC_LOG_DEBUG(("Private Message packet"));
1972 if (packet->flags & SILC_PACKET_FLAG_LIST)
1974 idata->last_receive = time(NULL);
1975 silc_server_private_message(server, sock, packet);
1978 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1980 * Private message key packet.
1982 if (packet->flags & SILC_PACKET_FLAG_LIST)
1984 silc_server_private_message_key(server, sock, packet);
1988 * Key Exchange protocol packets
1990 case SILC_PACKET_KEY_EXCHANGE:
1991 SILC_LOG_DEBUG(("KE packet"));
1992 if (packet->flags & SILC_PACKET_FLAG_LIST)
1995 if (sock->protocol && sock->protocol->protocol &&
1996 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1998 SilcServerKEInternalContext *proto_ctx =
1999 (SilcServerKEInternalContext *)sock->protocol->context;
2001 proto_ctx->packet = silc_packet_context_dup(packet);
2003 /* Let the protocol handle the packet */
2004 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2006 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2007 "protocol active, packet dropped."));
2011 case SILC_PACKET_KEY_EXCHANGE_1:
2012 SILC_LOG_DEBUG(("KE 1 packet"));
2013 if (packet->flags & SILC_PACKET_FLAG_LIST)
2016 if (sock->protocol && sock->protocol->protocol &&
2017 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2018 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2020 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2021 SilcServerRekeyInternalContext *proto_ctx =
2022 (SilcServerRekeyInternalContext *)sock->protocol->context;
2024 if (proto_ctx->packet)
2025 silc_packet_context_free(proto_ctx->packet);
2027 proto_ctx->packet = silc_packet_context_dup(packet);
2029 /* Let the protocol handle the packet */
2030 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2032 SilcServerKEInternalContext *proto_ctx =
2033 (SilcServerKEInternalContext *)sock->protocol->context;
2035 if (proto_ctx->packet)
2036 silc_packet_context_free(proto_ctx->packet);
2038 proto_ctx->packet = silc_packet_context_dup(packet);
2039 proto_ctx->dest_id_type = packet->src_id_type;
2040 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2041 packet->src_id_type);
2042 if (!proto_ctx->dest_id)
2045 /* Let the protocol handle the packet */
2046 silc_protocol_execute(sock->protocol, server->schedule,
2050 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2051 "protocol active, packet dropped."));
2055 case SILC_PACKET_KEY_EXCHANGE_2:
2056 SILC_LOG_DEBUG(("KE 2 packet"));
2057 if (packet->flags & SILC_PACKET_FLAG_LIST)
2060 if (sock->protocol && sock->protocol->protocol &&
2061 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2062 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2064 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2065 SilcServerRekeyInternalContext *proto_ctx =
2066 (SilcServerRekeyInternalContext *)sock->protocol->context;
2068 if (proto_ctx->packet)
2069 silc_packet_context_free(proto_ctx->packet);
2071 proto_ctx->packet = silc_packet_context_dup(packet);
2073 /* Let the protocol handle the packet */
2074 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2076 SilcServerKEInternalContext *proto_ctx =
2077 (SilcServerKEInternalContext *)sock->protocol->context;
2079 if (proto_ctx->packet)
2080 silc_packet_context_free(proto_ctx->packet);
2082 proto_ctx->packet = silc_packet_context_dup(packet);
2083 proto_ctx->dest_id_type = packet->src_id_type;
2084 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2085 packet->src_id_type);
2086 if (!proto_ctx->dest_id)
2089 /* Let the protocol handle the packet */
2090 silc_protocol_execute(sock->protocol, server->schedule,
2094 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2095 "protocol active, packet dropped."));
2099 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2101 * Connection authentication request packet. When we receive this packet
2102 * we will send to the other end information about our mandatory
2103 * authentication method for the connection. This packet maybe received
2106 SILC_LOG_DEBUG(("Connection authentication request packet"));
2107 if (packet->flags & SILC_PACKET_FLAG_LIST)
2109 silc_server_connection_auth_request(server, sock, packet);
2113 * Connection Authentication protocol packets
2115 case SILC_PACKET_CONNECTION_AUTH:
2116 /* Start of the authentication protocol. We receive here the
2117 authentication data and will verify it. */
2118 SILC_LOG_DEBUG(("Connection auth packet"));
2119 if (packet->flags & SILC_PACKET_FLAG_LIST)
2122 if (sock->protocol && sock->protocol->protocol->type
2123 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2125 SilcServerConnAuthInternalContext *proto_ctx =
2126 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2128 proto_ctx->packet = silc_packet_context_dup(packet);
2130 /* Let the protocol handle the packet */
2131 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2133 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2134 "protocol active, packet dropped."));
2138 case SILC_PACKET_NEW_ID:
2140 * Received New ID packet. This includes some new ID that has been
2141 * created. It may be for client, server or channel. This is the way
2142 * to distribute information about new registered entities in the
2145 SILC_LOG_DEBUG(("New ID packet"));
2146 if (packet->flags & SILC_PACKET_FLAG_LIST)
2147 silc_server_new_id_list(server, sock, packet);
2149 silc_server_new_id(server, sock, packet);
2152 case SILC_PACKET_NEW_CLIENT:
2154 * Received new client packet. This includes client information that
2155 * we will use to create initial client ID. After creating new
2156 * ID we will send it to the client.
2158 SILC_LOG_DEBUG(("New Client packet"));
2159 if (packet->flags & SILC_PACKET_FLAG_LIST)
2161 silc_server_new_client(server, sock, packet);
2164 case SILC_PACKET_NEW_SERVER:
2166 * Received new server packet. This includes Server ID and some other
2167 * information that we may save. This is received after server has
2170 SILC_LOG_DEBUG(("New Server packet"));
2171 if (packet->flags & SILC_PACKET_FLAG_LIST)
2173 silc_server_new_server(server, sock, packet);
2176 case SILC_PACKET_NEW_CHANNEL:
2178 * Received new channel packet. Information about new channel in the
2179 * network are distributed using this packet.
2181 SILC_LOG_DEBUG(("New Channel packet"));
2182 if (packet->flags & SILC_PACKET_FLAG_LIST)
2183 silc_server_new_channel_list(server, sock, packet);
2185 silc_server_new_channel(server, sock, packet);
2188 case SILC_PACKET_HEARTBEAT:
2190 * Received heartbeat.
2192 SILC_LOG_DEBUG(("Heartbeat packet"));
2193 if (packet->flags & SILC_PACKET_FLAG_LIST)
2197 case SILC_PACKET_KEY_AGREEMENT:
2199 * Received heartbeat.
2201 SILC_LOG_DEBUG(("Key agreement packet"));
2202 if (packet->flags & SILC_PACKET_FLAG_LIST)
2204 silc_server_key_agreement(server, sock, packet);
2207 case SILC_PACKET_REKEY:
2209 * Received re-key packet. The sender wants to regenerate the session
2212 SILC_LOG_DEBUG(("Re-key packet"));
2213 if (packet->flags & SILC_PACKET_FLAG_LIST)
2215 silc_server_rekey(server, sock, packet);
2218 case SILC_PACKET_REKEY_DONE:
2220 * The re-key is done.
2222 SILC_LOG_DEBUG(("Re-key done packet"));
2223 if (packet->flags & SILC_PACKET_FLAG_LIST)
2226 if (sock->protocol && sock->protocol->protocol &&
2227 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2229 SilcServerRekeyInternalContext *proto_ctx =
2230 (SilcServerRekeyInternalContext *)sock->protocol->context;
2232 if (proto_ctx->packet)
2233 silc_packet_context_free(proto_ctx->packet);
2235 proto_ctx->packet = silc_packet_context_dup(packet);
2237 /* Let the protocol handle the packet */
2238 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2240 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2241 "protocol active, packet dropped."));
2245 case SILC_PACKET_FTP:
2247 SILC_LOG_DEBUG(("FTP packet"));
2248 if (packet->flags & SILC_PACKET_FLAG_LIST)
2250 silc_server_ftp(server, sock, packet);
2253 case SILC_PACKET_RESUME_ROUTER:
2254 /* Resume router packet received. This packet is received for backup
2255 router resuming protocol. */
2256 SILC_LOG_DEBUG(("Resume router packet"));
2257 if (packet->flags & SILC_PACKET_FLAG_LIST)
2259 silc_server_backup_resume_router(server, sock, packet);
2263 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2269 /* Creates connection to a remote router. */
2271 void silc_server_create_connection(SilcServer server,
2272 const char *remote_host, SilcUInt32 port)
2274 SilcServerConnection sconn;
2276 /* Allocate connection object for hold connection specific stuff. */
2277 sconn = silc_calloc(1, sizeof(*sconn));
2278 sconn->server = server;
2279 sconn->remote_host = strdup(remote_host);
2280 sconn->remote_port = port;
2281 sconn->no_reconnect = TRUE;
2282 sconn->param = &server->config->param;
2284 silc_schedule_task_add(server->schedule, 0,
2285 silc_server_connect_router,
2286 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2287 SILC_TASK_PRI_NORMAL);
2290 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2292 silc_socket_free((SilcSocketConnection)context);
2295 /* Closes connection to socket connection */
2297 void silc_server_close_connection(SilcServer server,
2298 SilcSocketConnection sock)
2300 if (!server->sockets[sock->sock])
2303 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2305 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2306 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2307 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2310 /* We won't listen for this connection anymore */
2311 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2313 /* Unregister all tasks */
2314 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2316 /* Close the actual connection */
2317 silc_net_close_connection(sock->sock);
2318 server->sockets[sock->sock] = NULL;
2320 /* If sock->user_data is NULL then we'll check for active protocols
2321 here since the silc_server_free_sock_user_data has not been called
2322 for this connection. */
2323 if (!sock->user_data) {
2324 /* If any protocol is active cancel its execution. It will call
2325 the final callback which will finalize the disconnection. */
2326 if (sock->protocol) {
2327 silc_protocol_cancel(sock->protocol, server->schedule);
2328 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2329 silc_protocol_execute_final(sock->protocol, server->schedule);
2330 sock->protocol = NULL;
2335 silc_schedule_task_add(server->schedule, 0,
2336 silc_server_close_connection_final,
2337 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2338 SILC_TASK_PRI_NORMAL);
2341 /* Sends disconnect message to remote connection and disconnects the
2344 void silc_server_disconnect_remote(SilcServer server,
2345 SilcSocketConnection sock,
2346 const char *fmt, ...)
2349 unsigned char buf[4096];
2354 memset(buf, 0, sizeof(buf));
2356 vsprintf(buf, fmt, ap);
2359 SILC_LOG_DEBUG(("Disconnecting remote host"));
2361 /* Notify remote end that the conversation is over. The notify message
2362 is tried to be sent immediately. */
2363 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2364 buf, strlen(buf), TRUE);
2365 silc_server_packet_queue_purge(server, sock);
2367 /* Mark the connection to be disconnected */
2368 SILC_SET_DISCONNECTED(sock);
2369 silc_server_close_connection(server, sock);
2374 SilcClientEntry client;
2375 } *FreeClientInternal;
2377 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2379 FreeClientInternal i = (FreeClientInternal)context;
2381 silc_idlist_del_data(i->client);
2382 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2386 /* Frees client data and notifies about client's signoff. */
2388 void silc_server_free_client_data(SilcServer server,
2389 SilcSocketConnection sock,
2390 SilcClientEntry client,
2392 const char *signoff)
2394 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2396 /* If there is pending outgoing data for the client then purge it
2397 to the network before removing the client entry. */
2398 silc_server_packet_queue_purge(server, sock);
2403 /* Send SIGNOFF notify to routers. */
2404 if (notify && !server->standalone && server->router)
2405 silc_server_send_notify_signoff(server, server->router->connection,
2406 server->server_type == SILC_SERVER ?
2407 FALSE : TRUE, client->id, signoff);
2409 /* Remove client from all channels */
2411 silc_server_remove_from_channels(server, NULL, client,
2412 TRUE, (char *)signoff, TRUE);
2414 silc_server_remove_from_channels(server, NULL, client,
2415 FALSE, NULL, FALSE);
2417 /* Update statistics */
2418 server->stat.my_clients--;
2419 server->stat.clients--;
2420 if (server->server_type == SILC_ROUTER)
2421 server->stat.cell_clients--;
2422 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2423 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2425 /* We will not delete the client entry right away. We will take it
2426 into history (for WHOWAS command) for 5 minutes */
2429 silc_schedule_task_add(server->schedule, 0,
2430 silc_server_free_client_data_timeout,
2432 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2433 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2434 client->router = NULL;
2435 client->connection = NULL;
2439 /* Frees user_data pointer from socket connection object. This also sends
2440 appropriate notify packets to the network to inform about leaving
2443 void silc_server_free_sock_user_data(SilcServer server,
2444 SilcSocketConnection sock,
2445 const char *signoff_message)
2447 SILC_LOG_DEBUG(("Start"));
2449 switch (sock->type) {
2450 case SILC_SOCKET_TYPE_CLIENT:
2452 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2453 silc_server_free_client_data(server, sock, user_data, TRUE,
2457 case SILC_SOCKET_TYPE_SERVER:
2458 case SILC_SOCKET_TYPE_ROUTER:
2460 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2461 SilcServerEntry backup_router = NULL;
2464 backup_router = silc_server_backup_get(server, user_data->id);
2466 /* If this was our primary router connection then we're lost to
2467 the outside world. */
2468 if (server->router == user_data) {
2469 /* Check whether we have a backup router connection */
2470 if (!backup_router || backup_router == user_data) {
2471 silc_schedule_task_add(server->schedule, 0,
2472 silc_server_connect_to_router,
2475 SILC_TASK_PRI_NORMAL);
2477 server->id_entry->router = NULL;
2478 server->router = NULL;
2479 server->standalone = TRUE;
2480 backup_router = NULL;
2482 SILC_LOG_INFO(("New primary router is backup router %s",
2483 backup_router->server_name));
2484 SILC_LOG_DEBUG(("New primary router is backup router %s",
2485 backup_router->server_name));
2486 server->id_entry->router = backup_router;
2487 server->router = backup_router;
2488 server->router_connect = time(0);
2489 server->backup_primary = TRUE;
2490 if (server->server_type == SILC_BACKUP_ROUTER) {
2491 server->server_type = SILC_ROUTER;
2493 /* We'll need to constantly try to reconnect to the primary
2494 router so that we'll see when it comes back online. */
2495 silc_server_backup_reconnect(server, sock->ip, sock->port,
2496 silc_server_backup_connected,
2500 /* Mark this connection as replaced */
2501 silc_server_backup_replaced_add(server, user_data->id,
2504 } else if (backup_router) {
2505 SILC_LOG_INFO(("Enabling the use of backup router %s",
2506 backup_router->server_name));
2507 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2508 backup_router->server_name));
2510 /* Mark this connection as replaced */
2511 silc_server_backup_replaced_add(server, user_data->id,
2515 if (!backup_router) {
2516 /* Free all client entries that this server owns as they will
2517 become invalid now as well. */
2519 silc_server_remove_clients_by_server(server, user_data, TRUE);
2520 if (server->server_type == SILC_SERVER)
2521 silc_server_remove_channels_by_server(server, user_data);
2523 /* Update the client entries of this server to the new backup
2524 router. This also removes the clients that *really* was owned
2525 by the primary router and went down with the router. */
2526 silc_server_update_clients_by_server(server, user_data, backup_router,
2528 silc_server_update_servers_by_server(server, user_data, backup_router);
2529 if (server->server_type == SILC_SERVER)
2530 silc_server_update_channels_by_server(server, user_data,
2534 /* Free the server entry */
2535 silc_server_backup_del(server, user_data);
2536 silc_server_backup_replaced_del(server, user_data);
2537 silc_idlist_del_data(user_data);
2538 if (!silc_idlist_del_server(server->local_list, user_data))
2539 silc_idlist_del_server(server->global_list, user_data);
2540 server->stat.my_servers--;
2541 server->stat.servers--;
2542 if (server->server_type == SILC_ROUTER)
2543 server->stat.cell_servers--;
2545 if (backup_router) {
2546 /* Announce all of our stuff that was created about 5 minutes ago.
2547 The backup router knows all the other stuff already. */
2548 if (server->server_type == SILC_ROUTER)
2549 silc_server_announce_servers(server, FALSE, time(0) - 300,
2550 backup_router->connection);
2552 /* Announce our clients and channels to the router */
2553 silc_server_announce_clients(server, time(0) - 300,
2554 backup_router->connection);
2555 silc_server_announce_channels(server, time(0) - 300,
2556 backup_router->connection);
2562 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2564 silc_idlist_del_data(user_data);
2565 silc_free(user_data);
2570 /* If any protocol is active cancel its execution */
2571 if (sock->protocol) {
2572 silc_protocol_cancel(sock->protocol, server->schedule);
2573 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2574 silc_protocol_execute_final(sock->protocol, server->schedule);
2575 sock->protocol = NULL;
2578 sock->user_data = NULL;
2581 /* Removes client from all channels it has joined. This is used when client
2582 connection is disconnected. If the client on a channel is last, the
2583 channel is removed as well. This sends the SIGNOFF notify types. */
2585 void silc_server_remove_from_channels(SilcServer server,
2586 SilcSocketConnection sock,
2587 SilcClientEntry client,
2589 char *signoff_message,
2592 SilcChannelEntry channel;
2593 SilcChannelClientEntry chl;
2594 SilcHashTableList htl;
2597 SILC_LOG_DEBUG(("Start"));
2599 if (!client || !client->id)
2602 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2604 /* Remove the client from all channels. The client is removed from
2605 the channels' user list. */
2606 silc_hash_table_list(client->channels, &htl);
2607 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2608 channel = chl->channel;
2610 /* Remove channel from client's channel list */
2611 silc_hash_table_del(client->channels, channel);
2613 /* Remove channel if there is no users anymore */
2614 if (server->server_type == SILC_ROUTER &&
2615 silc_hash_table_count(channel->user_list) < 2) {
2617 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2618 if (silc_idlist_del_channel(server->local_list, channel))
2619 server->stat.my_channels--;
2621 silc_idlist_del_channel(server->global_list, channel);
2625 /* Remove client from channel's client list */
2626 silc_hash_table_del(channel->user_list, chl->client);
2627 channel->user_count--;
2629 /* If there is no global users on the channel anymore mark the channel
2630 as local channel. Do not check if the removed client is local client. */
2631 if (server->server_type != SILC_ROUTER && channel->global_users &&
2632 chl->client->router && !silc_server_channel_has_global(channel))
2633 channel->global_users = FALSE;
2636 server->stat.my_chanclients--;
2638 /* If there is not at least one local user on the channel then we don't
2639 need the channel entry anymore, we can remove it safely. */
2640 if (server->server_type != SILC_ROUTER &&
2641 !silc_server_channel_has_local(channel)) {
2642 /* Notify about leaving client if this channel has global users. */
2643 if (notify && channel->global_users)
2644 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2645 SILC_NOTIFY_TYPE_SIGNOFF,
2646 signoff_message ? 2 : 1,
2647 clidp->data, clidp->len,
2648 signoff_message, signoff_message ?
2649 strlen(signoff_message) : 0);
2652 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2654 if (channel->founder_key) {
2655 /* The founder auth data exists, do not remove the channel entry */
2656 SilcChannelClientEntry chl2;
2657 SilcHashTableList htl2;
2659 channel->disabled = TRUE;
2661 silc_hash_table_list(channel->user_list, &htl2);
2662 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2663 silc_hash_table_del(chl2->client->channels, channel);
2664 silc_hash_table_del(channel->user_list, chl2->client);
2665 channel->user_count--;
2668 silc_hash_table_list_reset(&htl2);
2672 /* Remove the channel entry */
2673 if (silc_idlist_del_channel(server->local_list, channel))
2674 server->stat.my_channels--;
2676 silc_idlist_del_channel(server->global_list, channel);
2680 /* Send notify to channel about client leaving SILC and thus
2681 the entire channel. */
2683 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2684 SILC_NOTIFY_TYPE_SIGNOFF,
2685 signoff_message ? 2 : 1,
2686 clidp->data, clidp->len,
2687 signoff_message, signoff_message ?
2688 strlen(signoff_message) : 0);
2690 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2691 /* Re-generate channel key */
2692 if (!silc_server_create_channel_key(server, channel, 0))
2695 /* Send the channel key to the channel. The key of course is not sent
2696 to the client who was removed from the channel. */
2697 silc_server_send_channel_key(server, client->connection, channel,
2698 server->server_type == SILC_ROUTER ?
2699 FALSE : !server->standalone);
2704 silc_hash_table_list_reset(&htl);
2705 silc_buffer_free(clidp);
2708 /* Removes client from one channel. This is used for example when client
2709 calls LEAVE command to remove itself from the channel. Returns TRUE
2710 if channel still exists and FALSE if the channel is removed when
2711 last client leaves the channel. If `notify' is FALSE notify messages
2714 int silc_server_remove_from_one_channel(SilcServer server,
2715 SilcSocketConnection sock,
2716 SilcChannelEntry channel,
2717 SilcClientEntry client,
2720 SilcChannelClientEntry chl;
2723 SILC_LOG_DEBUG(("Start"));
2725 /* Get the entry to the channel, if this client is not on the channel
2727 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2730 /* Remove the client from the channel. The client is removed from
2731 the channel's user list. */
2733 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2735 /* Remove channel from client's channel list */
2736 silc_hash_table_del(client->channels, chl->channel);
2738 /* Remove channel if there is no users anymore */
2739 if (server->server_type == SILC_ROUTER &&
2740 silc_hash_table_count(channel->user_list) < 2) {
2742 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2743 if (silc_idlist_del_channel(server->local_list, channel))
2744 server->stat.my_channels--;
2746 silc_idlist_del_channel(server->global_list, channel);
2747 silc_buffer_free(clidp);
2751 /* Remove client from channel's client list */
2752 silc_hash_table_del(channel->user_list, chl->client);
2753 channel->user_count--;
2755 /* If there is no global users on the channel anymore mark the channel
2756 as local channel. Do not check if the client is local client. */
2757 if (server->server_type != SILC_ROUTER && channel->global_users &&
2758 chl->client->router && !silc_server_channel_has_global(channel))
2759 channel->global_users = FALSE;
2762 server->stat.my_chanclients--;
2764 /* If there is not at least one local user on the channel then we don't
2765 need the channel entry anymore, we can remove it safely. */
2766 if (server->server_type != SILC_ROUTER &&
2767 !silc_server_channel_has_local(channel)) {
2768 /* Notify about leaving client if this channel has global users. */
2769 if (notify && channel->global_users)
2770 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2771 SILC_NOTIFY_TYPE_LEAVE, 1,
2772 clidp->data, clidp->len);
2774 silc_buffer_free(clidp);
2777 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2779 if (channel->founder_key) {
2780 /* The founder auth data exists, do not remove the channel entry */
2781 SilcChannelClientEntry chl2;
2782 SilcHashTableList htl2;
2784 channel->disabled = TRUE;
2786 silc_hash_table_list(channel->user_list, &htl2);
2787 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2788 silc_hash_table_del(chl2->client->channels, channel);
2789 silc_hash_table_del(channel->user_list, chl2->client);
2790 channel->user_count--;
2793 silc_hash_table_list_reset(&htl2);
2797 /* Remove the channel entry */
2798 if (silc_idlist_del_channel(server->local_list, channel))
2799 server->stat.my_channels--;
2801 silc_idlist_del_channel(server->global_list, channel);
2805 /* Send notify to channel about client leaving the channel */
2807 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2808 SILC_NOTIFY_TYPE_LEAVE, 1,
2809 clidp->data, clidp->len);
2811 silc_buffer_free(clidp);
2815 /* Timeout callback. This is called if connection is idle or for some
2816 other reason is not responding within some period of time. This
2817 disconnects the remote end. */
2819 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2821 SilcServer server = (SilcServer)context;
2822 SilcSocketConnection sock = server->sockets[fd];
2824 SILC_LOG_DEBUG(("Start"));
2829 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2830 sock->hostname, sock->ip));
2832 /* If we have protocol active we must assure that we call the protocol's
2833 final callback so that all the memory is freed. */
2834 if (sock->protocol) {
2835 silc_protocol_cancel(sock->protocol, server->schedule);
2836 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2837 silc_protocol_execute_final(sock->protocol, server->schedule);
2838 sock->protocol = NULL;
2842 if (sock->user_data)
2843 silc_server_free_sock_user_data(server, sock, NULL);
2845 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2846 "Connection timeout");
2849 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2850 function may be used only by router. In real SILC network all channels
2851 are created by routers thus this function is never used by normal
2854 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2855 SilcServerID *router_id,
2861 SilcChannelID *channel_id;
2862 SilcChannelEntry entry;
2866 SILC_LOG_DEBUG(("Creating new channel"));
2869 cipher = SILC_DEFAULT_CIPHER;
2871 hmac = SILC_DEFAULT_HMAC;
2873 /* Allocate cipher */
2874 if (!silc_cipher_alloc(cipher, &key))
2878 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2879 silc_cipher_free(key);
2883 channel_name = strdup(channel_name);
2885 /* Create the channel ID */
2886 if (!silc_id_create_channel_id(server, router_id, server->rng,
2888 silc_free(channel_name);
2889 silc_cipher_free(key);
2890 silc_hmac_free(newhmac);
2894 /* Create the channel */
2895 entry = silc_idlist_add_channel(server->local_list, channel_name,
2896 SILC_CHANNEL_MODE_NONE, channel_id,
2897 NULL, key, newhmac, 0);
2899 silc_free(channel_name);
2900 silc_cipher_free(key);
2901 silc_hmac_free(newhmac);
2902 silc_free(channel_id);
2906 entry->cipher = strdup(cipher);
2907 entry->hmac_name = strdup(hmac);
2909 /* Now create the actual key material */
2910 if (!silc_server_create_channel_key(server, entry,
2911 silc_cipher_get_key_len(key) / 8)) {
2912 silc_idlist_del_channel(server->local_list, entry);
2916 /* Notify other routers about the new channel. We send the packet
2917 to our primary route. */
2918 if (broadcast && server->standalone == FALSE)
2919 silc_server_send_new_channel(server, server->router->connection, TRUE,
2920 channel_name, entry->id,
2921 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2924 server->stat.my_channels++;
2929 /* Same as above but creates the channel with Channel ID `channel_id. */
2932 silc_server_create_new_channel_with_id(SilcServer server,
2936 SilcChannelID *channel_id,
2939 SilcChannelEntry entry;
2943 SILC_LOG_DEBUG(("Creating new channel"));
2946 cipher = SILC_DEFAULT_CIPHER;
2948 hmac = SILC_DEFAULT_HMAC;
2950 /* Allocate cipher */
2951 if (!silc_cipher_alloc(cipher, &key))
2955 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2956 silc_cipher_free(key);
2960 channel_name = strdup(channel_name);
2962 /* Create the channel */
2963 entry = silc_idlist_add_channel(server->local_list, channel_name,
2964 SILC_CHANNEL_MODE_NONE, channel_id,
2965 NULL, key, newhmac, 0);
2967 silc_cipher_free(key);
2968 silc_hmac_free(newhmac);
2969 silc_free(channel_name);
2973 /* Now create the actual key material */
2974 if (!silc_server_create_channel_key(server, entry,
2975 silc_cipher_get_key_len(key) / 8)) {
2976 silc_idlist_del_channel(server->local_list, entry);
2980 /* Notify other routers about the new channel. We send the packet
2981 to our primary route. */
2982 if (broadcast && server->standalone == FALSE)
2983 silc_server_send_new_channel(server, server->router->connection, TRUE,
2984 channel_name, entry->id,
2985 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2988 server->stat.my_channels++;
2993 /* Channel's key re-key timeout callback. */
2995 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2997 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2998 SilcServer server = (SilcServer)rekey->context;
3002 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3005 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3008 /* Generates new channel key. This is used to create the initial channel key
3009 but also to re-generate new key for channel. If `key_len' is provided
3010 it is the bytes of the key length. */
3012 bool silc_server_create_channel_key(SilcServer server,
3013 SilcChannelEntry channel,
3017 unsigned char channel_key[32], hash[32];
3020 SILC_LOG_DEBUG(("Generating channel key"));
3022 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3023 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3027 if (!channel->channel_key)
3028 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3029 channel->channel_key = NULL;
3035 else if (channel->key_len)
3036 len = channel->key_len / 8;
3038 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3040 /* Create channel key */
3041 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3044 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3046 /* Remove old key if exists */
3048 memset(channel->key, 0, channel->key_len / 8);
3049 silc_free(channel->key);
3053 channel->key_len = len * 8;
3054 channel->key = silc_memdup(channel_key, len);
3055 memset(channel_key, 0, sizeof(channel_key));
3057 /* Generate HMAC key from the channel key data and set it */
3059 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3060 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3061 silc_hmac_set_key(channel->hmac, hash,
3062 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3063 memset(hash, 0, sizeof(hash));
3065 if (server->server_type == SILC_ROUTER) {
3066 if (!channel->rekey)
3067 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3068 channel->rekey->context = (void *)server;
3069 channel->rekey->channel = channel;
3070 channel->rekey->key_len = key_len;
3071 if (channel->rekey->task)
3072 silc_schedule_task_del(server->schedule, channel->rekey->task);
3074 channel->rekey->task =
3075 silc_schedule_task_add(server->schedule, 0,
3076 silc_server_channel_key_rekey,
3077 (void *)channel->rekey,
3078 server->config->channel_rekey_secs, 0,
3080 SILC_TASK_PRI_NORMAL);
3086 /* Saves the channel key found in the encoded `key_payload' buffer. This
3087 function is used when we receive Channel Key Payload and also when we're
3088 processing JOIN command reply. Returns entry to the channel. */
3090 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3091 SilcBuffer key_payload,
3092 SilcChannelEntry channel)
3094 SilcChannelKeyPayload payload = NULL;
3095 SilcChannelID *id = NULL;
3096 unsigned char *tmp, hash[32];
3100 SILC_LOG_DEBUG(("Start"));
3102 /* Decode channel key payload */
3103 payload = silc_channel_key_payload_parse(key_payload->data,
3106 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3111 /* Get the channel entry */
3114 /* Get channel ID */
3115 tmp = silc_channel_key_get_id(payload, &tmp_len);
3116 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3122 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3124 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3126 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3127 silc_id_render(id, SILC_ID_CHANNEL)));
3133 tmp = silc_channel_key_get_key(payload, &tmp_len);
3139 cipher = silc_channel_key_get_cipher(payload, NULL);
3145 /* Remove old key if exists */
3147 memset(channel->key, 0, channel->key_len / 8);
3148 silc_free(channel->key);
3149 silc_cipher_free(channel->channel_key);
3152 /* Create new cipher */
3153 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3154 channel->channel_key = NULL;
3159 if (channel->cipher)
3160 silc_free(channel->cipher);
3161 channel->cipher = strdup(cipher);
3164 channel->key_len = tmp_len * 8;
3165 channel->key = silc_memdup(tmp, tmp_len);
3166 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3168 /* Generate HMAC key from the channel key data and set it */
3170 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3171 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3172 silc_hmac_set_key(channel->hmac, hash,
3173 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3175 memset(hash, 0, sizeof(hash));
3176 memset(tmp, 0, tmp_len);
3178 if (server->server_type == SILC_ROUTER) {
3179 if (!channel->rekey)
3180 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3181 channel->rekey->context = (void *)server;
3182 channel->rekey->channel = channel;
3183 if (channel->rekey->task)
3184 silc_schedule_task_del(server->schedule, channel->rekey->task);
3186 channel->rekey->task =
3187 silc_schedule_task_add(server->schedule, 0,
3188 silc_server_channel_key_rekey,
3189 (void *)channel->rekey,
3190 server->config->channel_rekey_secs, 0,
3192 SILC_TASK_PRI_NORMAL);
3198 silc_channel_key_payload_free(payload);
3203 /* Heartbeat callback. This function is set as argument for the
3204 silc_socket_set_heartbeat function. The library will call this function
3205 at the set time interval. */
3207 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3210 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3212 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3214 /* Send the heartbeat */
3215 silc_server_send_heartbeat(hb->server, sock);
3218 /* Returns assembled of all servers in the given ID list. The packet's
3219 form is dictated by the New ID payload. */
3221 static void silc_server_announce_get_servers(SilcServer server,
3222 SilcServerEntry remote,
3224 SilcBuffer *servers,
3225 unsigned long creation_time)
3227 SilcIDCacheList list;
3228 SilcIDCacheEntry id_cache;
3229 SilcServerEntry entry;
3232 /* Go through all clients in the list */
3233 if (silc_idcache_get_all(id_list->servers, &list)) {
3234 if (silc_idcache_list_first(list, &id_cache)) {
3236 entry = (SilcServerEntry)id_cache->context;
3238 /* Do not announce the one we've sending our announcements and
3239 do not announce ourself. Also check the creation time if it's
3241 if ((entry == remote) || (entry == server->id_entry) ||
3242 (creation_time && entry->data.created < creation_time)) {
3243 if (!silc_idcache_list_next(list, &id_cache))
3248 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3250 *servers = silc_buffer_realloc(*servers,
3252 (*servers)->truelen + idp->len :
3254 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3255 silc_buffer_put(*servers, idp->data, idp->len);
3256 silc_buffer_pull(*servers, idp->len);
3257 silc_buffer_free(idp);
3259 if (!silc_idcache_list_next(list, &id_cache))
3264 silc_idcache_list_free(list);
3269 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3275 p = silc_notify_payload_encode(notify, argc, ap);
3281 /* This function is used by router to announce existing servers to our
3282 primary router when we've connected to it. If `creation_time' is non-zero
3283 then only the servers that has been created after the `creation_time'
3284 will be announced. */
3286 void silc_server_announce_servers(SilcServer server, bool global,
3287 unsigned long creation_time,
3288 SilcSocketConnection remote)
3290 SilcBuffer servers = NULL;
3292 SILC_LOG_DEBUG(("Announcing servers"));
3294 /* Get servers in local list */
3295 silc_server_announce_get_servers(server, remote->user_data,
3296 server->local_list, &servers,
3300 /* Get servers in global list */
3301 silc_server_announce_get_servers(server, remote->user_data,
3302 server->global_list, &servers,
3306 silc_buffer_push(servers, servers->data - servers->head);
3307 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3309 /* Send the packet */
3310 silc_server_packet_send(server, remote,
3311 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3312 servers->data, servers->len, TRUE);
3314 silc_buffer_free(servers);
3318 /* Returns assembled packet of all clients in the given ID list. The
3319 packet's form is dictated by the New ID Payload. */
3321 static void silc_server_announce_get_clients(SilcServer server,
3323 SilcBuffer *clients,
3325 unsigned long creation_time)
3327 SilcIDCacheList list;
3328 SilcIDCacheEntry id_cache;
3329 SilcClientEntry client;
3332 unsigned char mode[4];
3334 /* Go through all clients in the list */
3335 if (silc_idcache_get_all(id_list->clients, &list)) {
3336 if (silc_idcache_list_first(list, &id_cache)) {
3338 client = (SilcClientEntry)id_cache->context;
3340 if (creation_time && client->data.created < creation_time) {
3341 if (!silc_idcache_list_next(list, &id_cache))
3346 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3348 *clients = silc_buffer_realloc(*clients,
3350 (*clients)->truelen + idp->len :
3352 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3353 silc_buffer_put(*clients, idp->data, idp->len);
3354 silc_buffer_pull(*clients, idp->len);
3356 SILC_PUT32_MSB(client->mode, mode);
3357 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3358 2, idp->data, idp->len,
3360 *umodes = silc_buffer_realloc(*umodes,
3362 (*umodes)->truelen + tmp->len :
3364 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3365 silc_buffer_put(*umodes, tmp->data, tmp->len);
3366 silc_buffer_pull(*umodes, tmp->len);
3367 silc_buffer_free(tmp);
3369 silc_buffer_free(idp);
3371 if (!silc_idcache_list_next(list, &id_cache))
3376 silc_idcache_list_free(list);
3380 /* This function is used to announce our existing clients to our router
3381 when we've connected to it. If `creation_time' is non-zero then only
3382 the clients that has been created after the `creation_time' will be
3385 void silc_server_announce_clients(SilcServer server,
3386 unsigned long creation_time,
3387 SilcSocketConnection remote)
3389 SilcBuffer clients = NULL;
3390 SilcBuffer umodes = NULL;
3392 SILC_LOG_DEBUG(("Announcing clients"));
3394 /* Get clients in local list */
3395 silc_server_announce_get_clients(server, server->local_list,
3396 &clients, &umodes, creation_time);
3398 /* As router we announce our global list as well */
3399 if (server->server_type == SILC_ROUTER)
3400 silc_server_announce_get_clients(server, server->global_list,
3401 &clients, &umodes, creation_time);
3404 silc_buffer_push(clients, clients->data - clients->head);
3405 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3407 /* Send the packet */
3408 silc_server_packet_send(server, remote,
3409 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3410 clients->data, clients->len, TRUE);
3412 silc_buffer_free(clients);
3416 silc_buffer_push(umodes, umodes->data - umodes->head);
3417 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3419 /* Send the packet */
3420 silc_server_packet_send(server, remote,
3421 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3422 umodes->data, umodes->len, TRUE);
3424 silc_buffer_free(umodes);
3428 /* Returns channel's topic for announcing it */
3430 void silc_server_announce_get_channel_topic(SilcServer server,
3431 SilcChannelEntry channel,
3436 if (channel->topic) {
3437 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3438 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3439 chidp->data, chidp->len,
3441 strlen(channel->topic));
3442 silc_buffer_free(chidp);
3446 /* Returns assembled packets for channel users of the `channel'. */
3448 void silc_server_announce_get_channel_users(SilcServer server,
3449 SilcChannelEntry channel,
3450 SilcBuffer *channel_users,
3451 SilcBuffer *channel_users_modes)
3453 SilcChannelClientEntry chl;
3454 SilcHashTableList htl;
3455 SilcBuffer chidp, clidp;
3458 unsigned char mode[4];
3460 SILC_LOG_DEBUG(("Start"));
3462 /* Now find all users on the channel */
3463 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3464 silc_hash_table_list(channel->user_list, &htl);
3465 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3466 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3469 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3470 clidp->data, clidp->len,
3471 chidp->data, chidp->len);
3474 silc_buffer_realloc(*channel_users,
3476 (*channel_users)->truelen + len : len));
3477 silc_buffer_pull_tail(*channel_users,
3478 ((*channel_users)->end -
3479 (*channel_users)->data));
3481 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3482 silc_buffer_pull(*channel_users, len);
3483 silc_buffer_free(tmp);
3485 /* CUMODE notify for mode change on the channel */
3486 SILC_PUT32_MSB(chl->mode, mode);
3487 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3488 3, clidp->data, clidp->len,
3490 clidp->data, clidp->len);
3492 *channel_users_modes =
3493 silc_buffer_realloc(*channel_users_modes,
3494 (*channel_users_modes ?
3495 (*channel_users_modes)->truelen + len : len));
3496 silc_buffer_pull_tail(*channel_users_modes,
3497 ((*channel_users_modes)->end -
3498 (*channel_users_modes)->data));
3500 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3501 silc_buffer_pull(*channel_users_modes, len);
3502 silc_buffer_free(tmp);
3504 silc_buffer_free(clidp);
3506 silc_hash_table_list_reset(&htl);
3507 silc_buffer_free(chidp);
3510 /* Returns assembled packets for all channels and users on those channels
3511 from the given ID List. The packets are in the form dictated by the
3512 New Channel and New Channel User payloads. */
3514 void silc_server_announce_get_channels(SilcServer server,
3516 SilcBuffer *channels,
3517 SilcBuffer *channel_users,
3518 SilcBuffer **channel_users_modes,
3519 SilcUInt32 *channel_users_modes_c,
3520 SilcBuffer **channel_topics,
3521 SilcChannelID ***channel_ids,
3522 unsigned long creation_time)
3524 SilcIDCacheList list;
3525 SilcIDCacheEntry id_cache;
3526 SilcChannelEntry channel;
3529 SilcUInt16 name_len;
3531 int i = *channel_users_modes_c;
3534 SILC_LOG_DEBUG(("Start"));
3536 /* Go through all channels in the list */
3537 if (silc_idcache_get_all(id_list->channels, &list)) {
3538 if (silc_idcache_list_first(list, &id_cache)) {
3540 channel = (SilcChannelEntry)id_cache->context;
3542 if (creation_time && channel->created < creation_time)
3547 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3548 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3549 name_len = strlen(channel->channel_name);
3552 len = 4 + name_len + id_len + 4;
3554 silc_buffer_realloc(*channels,
3555 (*channels ? (*channels)->truelen +
3557 silc_buffer_pull_tail(*channels,
3558 ((*channels)->end - (*channels)->data));
3559 silc_buffer_format(*channels,
3560 SILC_STR_UI_SHORT(name_len),
3561 SILC_STR_UI_XNSTRING(channel->channel_name,
3563 SILC_STR_UI_SHORT(id_len),
3564 SILC_STR_UI_XNSTRING(cid, id_len),
3565 SILC_STR_UI_INT(channel->mode),
3567 silc_buffer_pull(*channels, len);
3570 /* Channel user modes */
3571 *channel_users_modes = silc_realloc(*channel_users_modes,
3572 sizeof(**channel_users_modes) *
3574 (*channel_users_modes)[i] = NULL;
3575 *channel_ids = silc_realloc(*channel_ids,
3576 sizeof(**channel_ids) * (i + 1));
3577 (*channel_ids)[i] = NULL;
3578 silc_server_announce_get_channel_users(server, channel,
3580 &(*channel_users_modes)[i]);
3581 (*channel_ids)[i] = channel->id;
3583 /* Channel's topic */
3584 *channel_topics = silc_realloc(*channel_topics,
3585 sizeof(**channel_topics) * (i + 1));
3586 (*channel_topics)[i] = NULL;
3587 silc_server_announce_get_channel_topic(server, channel,
3588 &(*channel_topics)[i]);
3591 if (!silc_idcache_list_next(list, &id_cache))
3595 *channel_users_modes_c += i;
3598 silc_idcache_list_free(list);
3602 /* This function is used to announce our existing channels to our router
3603 when we've connected to it. This also announces the users on the
3604 channels to the router. If the `creation_time' is non-zero only the
3605 channels that was created after the `creation_time' are announced.
3606 Note that the channel users are still announced even if the `creation_time'
3609 void silc_server_announce_channels(SilcServer server,
3610 unsigned long creation_time,
3611 SilcSocketConnection remote)
3613 SilcBuffer channels = NULL, channel_users = NULL;
3614 SilcBuffer *channel_users_modes = NULL;
3615 SilcBuffer *channel_topics = NULL;
3616 SilcUInt32 channel_users_modes_c = 0;
3617 SilcChannelID **channel_ids = NULL;
3619 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3621 /* Get channels and channel users in local list */
3622 silc_server_announce_get_channels(server, server->local_list,
3623 &channels, &channel_users,
3624 &channel_users_modes,
3625 &channel_users_modes_c,
3627 &channel_ids, creation_time);
3629 /* Get channels and channel users in global list */
3630 if (server->server_type != SILC_SERVER)
3631 silc_server_announce_get_channels(server, server->global_list,
3632 &channels, &channel_users,
3633 &channel_users_modes,
3634 &channel_users_modes_c,
3636 &channel_ids, creation_time);
3639 silc_buffer_push(channels, channels->data - channels->head);
3640 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3642 /* Send the packet */
3643 silc_server_packet_send(server, remote,
3644 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3645 channels->data, channels->len,
3648 silc_buffer_free(channels);
3651 if (channel_users) {
3652 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3653 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3654 channel_users->len);
3656 /* Send the packet */
3657 silc_server_packet_send(server, remote,
3658 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3659 channel_users->data, channel_users->len,
3662 silc_buffer_free(channel_users);
3665 if (channel_users_modes) {
3668 for (i = 0; i < channel_users_modes_c; i++) {
3669 if (!channel_users_modes[i])
3671 silc_buffer_push(channel_users_modes[i],
3672 channel_users_modes[i]->data -
3673 channel_users_modes[i]->head);
3674 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3675 channel_users_modes[i]->len);
3676 silc_server_packet_send_dest(server, remote,
3677 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3678 channel_ids[i], SILC_ID_CHANNEL,
3679 channel_users_modes[i]->data,
3680 channel_users_modes[i]->len,
3682 silc_buffer_free(channel_users_modes[i]);
3684 silc_free(channel_users_modes);
3687 if (channel_topics) {
3690 for (i = 0; i < channel_users_modes_c; i++) {
3691 if (!channel_topics[i])
3694 silc_buffer_push(channel_topics[i],
3695 channel_topics[i]->data -
3696 channel_topics[i]->head);
3697 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3698 channel_topics[i]->len);
3699 silc_server_packet_send_dest(server, remote,
3700 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3701 channel_ids[i], SILC_ID_CHANNEL,
3702 channel_topics[i]->data,
3703 channel_topics[i]->len,
3705 silc_buffer_free(channel_topics[i]);
3707 silc_free(channel_topics);
3710 silc_free(channel_ids);
3713 /* Failure timeout callback. If this is called then we will immediately
3714 process the received failure. We always process the failure with timeout
3715 since we do not want to blindly trust to received failure packets.
3716 This won't be called (the timeout is cancelled) if the failure was
3717 bogus (it is bogus if remote does not close the connection after sending
3720 SILC_TASK_CALLBACK(silc_server_failure_callback)
3722 SilcServerFailureContext f = (SilcServerFailureContext)context;
3724 if (f->sock->protocol) {
3725 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3726 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3732 /* Assembles user list and users mode list from the `channel'. */
3734 void silc_server_get_users_on_channel(SilcServer server,
3735 SilcChannelEntry channel,
3736 SilcBuffer *user_list,
3737 SilcBuffer *mode_list,
3738 SilcUInt32 *user_count)
3740 SilcChannelClientEntry chl;
3741 SilcHashTableList htl;
3742 SilcBuffer client_id_list;
3743 SilcBuffer client_mode_list;
3745 SilcUInt32 list_count = 0, len = 0;
3747 silc_hash_table_list(channel->user_list, &htl);
3748 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3749 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3750 silc_hash_table_list_reset(&htl);
3752 client_id_list = silc_buffer_alloc(len);
3754 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3755 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3756 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3758 silc_hash_table_list(channel->user_list, &htl);
3759 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3761 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3762 silc_buffer_put(client_id_list, idp->data, idp->len);
3763 silc_buffer_pull(client_id_list, idp->len);
3764 silc_buffer_free(idp);
3766 /* Client's mode on channel */
3767 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3768 silc_buffer_pull(client_mode_list, 4);
3772 silc_hash_table_list_reset(&htl);
3773 silc_buffer_push(client_id_list,
3774 client_id_list->data - client_id_list->head);
3775 silc_buffer_push(client_mode_list,
3776 client_mode_list->data - client_mode_list->head);
3778 *user_list = client_id_list;
3779 *mode_list = client_mode_list;
3780 *user_count = list_count;
3783 /* Saves users and their modes to the `channel'. */
3785 void silc_server_save_users_on_channel(SilcServer server,
3786 SilcSocketConnection sock,
3787 SilcChannelEntry channel,
3788 SilcClientID *noadd,
3789 SilcBuffer user_list,
3790 SilcBuffer mode_list,
3791 SilcUInt32 user_count)
3796 SilcClientID *client_id;
3797 SilcClientEntry client;
3798 SilcIDCacheEntry cache;
3801 SILC_LOG_DEBUG(("Start"));
3803 for (i = 0; i < user_count; i++) {
3805 SILC_GET16_MSB(idp_len, user_list->data + 2);
3807 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3808 silc_buffer_pull(user_list, idp_len);
3813 SILC_GET32_MSB(mode, mode_list->data);
3814 silc_buffer_pull(mode_list, 4);
3816 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3817 silc_free(client_id);
3823 /* Check if we have this client cached already. */
3824 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3825 server->server_type, &cache);
3827 client = silc_idlist_find_client_by_id(server->global_list,
3828 client_id, server->server_type,
3833 /* If router did not find such Client ID in its lists then this must
3834 be bogus client or some router in the net is buggy. */
3835 if (server->server_type == SILC_ROUTER) {
3836 silc_free(client_id);
3840 /* We don't have that client anywhere, add it. The client is added
3841 to global list since server didn't have it in the lists so it must be
3843 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3844 silc_id_dup(client_id, SILC_ID_CLIENT),
3845 sock->user_data, NULL, 0);
3847 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3848 silc_free(client_id);
3852 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3854 /* Found, if it is from global list we'll assure that we won't
3855 expire it now that the entry is on channel. */
3860 silc_free(client_id);
3862 if (!silc_server_client_on_channel(client, channel, NULL)) {
3863 /* Client was not on the channel, add it. */
3864 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3865 chl->client = client;
3867 chl->channel = channel;
3868 silc_hash_table_add(channel->user_list, chl->client, chl);
3869 silc_hash_table_add(client->channels, chl->channel, chl);
3870 channel->user_count++;
3875 /* Lookups route to the client indicated by the `id_data'. The connection
3876 object and internal data object is returned. Returns NULL if route
3877 could not be found to the client. If the `client_id' is specified then
3878 it is used and the `id_data' is ignored. */
3880 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3881 unsigned char *id_data,
3883 SilcClientID *client_id,
3884 SilcIDListData *idata)
3887 SilcClientEntry client;
3889 SILC_LOG_DEBUG(("Start"));
3891 /* Decode destination Client ID */
3893 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3895 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3899 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3902 /* If the destination belongs to our server we don't have to route
3903 the packet anywhere but to send it to the local destination. */
3904 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3908 /* If we are router and the client has router then the client is in
3909 our cell but not directly connected to us. */
3910 if (server->server_type == SILC_ROUTER && client->router) {
3911 /* We are of course in this case the client's router thus the route
3912 to the client is the server who owns the client. So, we will send
3913 the packet to that server. */
3915 *idata = (SilcIDListData)client->router;
3916 return client->router->connection;
3919 /* Seems that client really is directly connected to us */
3921 *idata = (SilcIDListData)client;
3922 return client->connection;
3925 /* Destination belongs to someone not in this server. If we are normal
3926 server our action is to send the packet to our router. */
3927 if (server->server_type != SILC_ROUTER && !server->standalone) {
3930 *idata = (SilcIDListData)server->router;
3931 return server->router->connection;
3934 /* We are router and we will perform route lookup for the destination
3935 and send the packet to fastest route. */
3936 if (server->server_type == SILC_ROUTER && !server->standalone) {
3937 /* Check first that the ID is valid */
3938 client = silc_idlist_find_client_by_id(server->global_list, id,
3941 SilcSocketConnection dst_sock;
3943 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3947 *idata = (SilcIDListData)dst_sock->user_data;
3956 /* Encodes and returns channel list of channels the `client' has joined.
3957 Secret channels are not put to the list. */
3959 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3960 SilcClientEntry client)
3962 SilcBuffer buffer = NULL;
3963 SilcChannelEntry channel;
3964 SilcChannelClientEntry chl;
3965 SilcHashTableList htl;
3968 SilcUInt16 name_len;
3971 silc_hash_table_list(client->channels, &htl);
3972 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3973 channel = chl->channel;
3975 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3976 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3979 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3980 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3981 name_len = strlen(channel->channel_name);
3983 len = 4 + name_len + id_len + 4;
3984 buffer = silc_buffer_realloc(buffer,
3985 (buffer ? (buffer)->truelen + len : len));
3986 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3987 silc_buffer_format(buffer,
3988 SILC_STR_UI_SHORT(name_len),
3989 SILC_STR_UI_XNSTRING(channel->channel_name,
3991 SILC_STR_UI_SHORT(id_len),
3992 SILC_STR_UI_XNSTRING(cid, id_len),
3993 SILC_STR_UI_INT(chl->mode), /* Client's mode */
3995 silc_buffer_pull(buffer, len);
3998 silc_hash_table_list_reset(&htl);
4001 silc_buffer_push(buffer, buffer->data - buffer->head);
4006 /* Finds client entry by Client ID and if it is not found then resolves
4007 it using WHOIS command. */
4009 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4010 SilcClientID *client_id,
4013 SilcClientEntry client;
4018 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4021 client = silc_idlist_find_client_by_id(server->global_list,
4022 client_id, TRUE, NULL);
4023 if (!client && server->server_type == SILC_ROUTER)
4027 if (!client && server->standalone)
4030 if (!client || !client->nickname || !client->username) {
4031 SilcBuffer buffer, idp;
4033 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4034 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4035 client->resolve_cmd_ident = ++server->cmd_ident;
4037 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4038 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4039 server->cmd_ident, 1,
4040 3, idp->data, idp->len);
4041 silc_server_packet_send(server, client ? client->router->connection :
4042 server->router->connection,
4043 SILC_PACKET_COMMAND, 0,
4044 buffer->data, buffer->len, FALSE);
4045 silc_buffer_free(idp);
4046 silc_buffer_free(buffer);
4057 /* A timeout callback for the re-key. We will be the initiator of the
4060 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4062 SilcSocketConnection sock = (SilcSocketConnection)context;
4063 SilcIDListData idata = (SilcIDListData)sock->user_data;
4064 SilcServer server = (SilcServer)idata->rekey->context;
4065 SilcProtocol protocol;
4066 SilcServerRekeyInternalContext *proto_ctx;
4068 SILC_LOG_DEBUG(("Start"));
4070 /* Allocate internal protocol context. This is sent as context
4072 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4073 proto_ctx->server = (void *)server;
4074 proto_ctx->sock = sock;
4075 proto_ctx->responder = FALSE;
4076 proto_ctx->pfs = idata->rekey->pfs;
4078 /* Perform rekey protocol. Will call the final callback after the
4079 protocol is over. */
4080 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4081 &protocol, proto_ctx, silc_server_rekey_final);
4082 sock->protocol = protocol;
4084 /* Run the protocol */
4085 silc_protocol_execute(protocol, server->schedule, 0, 0);
4087 /* Re-register re-key timeout */
4088 silc_schedule_task_add(server->schedule, sock->sock,
4089 silc_server_rekey_callback,
4090 context, idata->rekey->timeout, 0,
4091 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4094 /* The final callback for the REKEY protocol. This will actually take the
4095 new key material into use. */
4097 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4099 SilcProtocol protocol = (SilcProtocol)context;
4100 SilcServerRekeyInternalContext *ctx =
4101 (SilcServerRekeyInternalContext *)protocol->context;
4102 SilcServer server = (SilcServer)ctx->server;
4103 SilcSocketConnection sock = ctx->sock;
4105 SILC_LOG_DEBUG(("Start"));
4107 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4108 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4109 /* Error occured during protocol */
4110 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4111 silc_protocol_cancel(protocol, server->schedule);
4112 silc_protocol_free(protocol);
4113 sock->protocol = NULL;
4115 silc_packet_context_free(ctx->packet);
4117 silc_ske_free(ctx->ske);
4122 /* Purge the outgoing data queue to assure that all rekey packets really
4123 go to the network before we quit the protocol. */
4124 silc_server_packet_queue_purge(server, sock);
4127 silc_protocol_free(protocol);
4128 sock->protocol = NULL;
4130 silc_packet_context_free(ctx->packet);
4132 silc_ske_free(ctx->ske);