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);
90 silc_server_config_unref(&server->config_ref);
92 silc_rng_free(server->rng);
94 silc_pkcs_free(server->pkcs);
95 if (server->public_key)
96 silc_pkcs_public_key_free(server->public_key);
97 if (server->private_key)
98 silc_pkcs_private_key_free(server->private_key);
99 if (server->pending_commands)
100 silc_dlist_uninit(server->pending_commands);
101 if (server->id_entry)
102 silc_idlist_del_server(server->local_list, server->id_entry);
104 silc_idcache_free(server->local_list->clients);
105 silc_idcache_free(server->local_list->servers);
106 silc_idcache_free(server->local_list->channels);
107 silc_idcache_free(server->global_list->clients);
108 silc_idcache_free(server->global_list->servers);
109 silc_idcache_free(server->global_list->channels);
111 silc_free(server->sockets);
116 /* Opens a listening port.
117 XXX This function will become more general and will support multiple
120 static bool silc_server_listen(SilcServer server, int *sock)
123 *sock = silc_net_create_server(server->config->server_info->port,
124 server->config->server_info->server_ip);
126 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
127 server->config->server_info->server_ip,
128 server->config->server_info->port));
134 /* Initializes the entire SILC server. This is called always before running
135 the server. This is called only once at the initialization of the program.
136 This binds the server to its listenning port. After this function returns
137 one should call silc_server_run to start the server. This returns TRUE
138 when everything is ok to run the server. Configuration file must be
139 read and parsed before calling this. */
141 bool silc_server_init(SilcServer server)
145 SilcServerEntry id_entry;
146 SilcIDListPurge purge;
147 SilcSocketConnection newsocket = NULL;
149 SILC_LOG_DEBUG(("Initializing server"));
151 assert(server->config);
153 silc_server_config_ref(&server->config_ref, server->config,
156 /* Set public and private keys */
157 if (!server->config->server_info ||
158 !server->config->server_info->public_key ||
159 !server->config->server_info->private_key) {
160 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
164 /* Steal public and private key from the config object */
165 server->public_key = server->config->server_info->public_key;
166 server->private_key = server->config->server_info->private_key;
167 server->config->server_info->public_key = NULL;
168 server->config->server_info->private_key = NULL;
170 /* Register all configured ciphers, PKCS and hash functions. */
171 if (!silc_server_config_register_ciphers(server))
172 silc_cipher_register_default();
173 if (!silc_server_config_register_pkcs(server))
174 silc_pkcs_register_default();
175 if (!silc_server_config_register_hashfuncs(server))
176 silc_hash_register_default();
177 if (!silc_server_config_register_hmacs(server))
178 silc_hmac_register_default();
180 /* Initialize random number generator for the server. */
181 server->rng = silc_rng_alloc();
182 silc_rng_init(server->rng);
183 silc_rng_global_init(server->rng);
185 /* Initialize hash functions for server to use */
186 silc_hash_alloc("md5", &server->md5hash);
187 silc_hash_alloc("sha1", &server->sha1hash);
189 /* Allocate PKCS context for local public and private keys */
190 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
192 silc_pkcs_public_key_set(server->pkcs, server->public_key);
193 silc_pkcs_private_key_set(server->pkcs, server->private_key);
195 /* Initialize the scheduler */
196 server->schedule = silc_schedule_init(server->config->param.connections_max);
197 if (!server->schedule)
200 /* First, register log files configuration for error output */
201 silc_server_config_setlogfiles(server);
203 /* Initialize ID caches */
204 server->local_list->clients =
205 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
206 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
207 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
209 /* These are allocated for normal server as well as these hold some
210 global information that the server has fetched from its router. For
211 router these are used as they are supposed to be used on router. */
212 server->global_list->clients =
213 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
214 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
215 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
217 /* Create a listening server */
218 if (!silc_server_listen(server, &sock))
221 /* Set socket to non-blocking mode */
222 silc_net_set_socket_nonblock(sock);
225 /* Allocate the entire socket list that is used in server. Eventually
226 all connections will have entry in this table (it is a table of
227 pointers to the actual object that is allocated individually
229 server->sockets = silc_calloc(server->config->param.connections_max,
230 sizeof(*server->sockets));
231 if (!server->sockets)
234 /* Add ourselves also to the socket table. The entry allocated above
235 is sent as argument for fast referencing in the future. */
236 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
237 server->sockets[sock] = newsocket;
239 /* Perform name and address lookups to resolve the listenning address
241 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
243 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
245 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
246 newsocket->hostname ? newsocket->hostname :
247 newsocket->ip ? newsocket->ip : ""));
248 server->stat.conn_failures++;
251 if (!newsocket->hostname)
252 newsocket->hostname = strdup(newsocket->ip);
254 newsocket->port = silc_net_get_local_port(sock);
256 /* Create a Server ID for the server. */
257 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
262 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
263 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
264 server->id_type = SILC_ID_SERVER;
265 server->server_name = server->config->server_info->server_name;
266 server->config->server_info->server_name = NULL;
268 /* Add ourselves to the server list. We don't have a router yet
269 beacuse we haven't established a route yet. It will be done later.
270 For now, NULL is sent as router. This allocates new entry to
273 silc_idlist_add_server(server->local_list, strdup(server->server_name),
274 server->server_type, server->id, NULL, NULL);
276 SILC_LOG_ERROR(("Could not add ourselves to cache"));
279 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
281 /* Put the allocated socket pointer also to the entry allocated above
282 for fast back-referencing to the socket list. */
283 newsocket->user_data = (void *)id_entry;
284 id_entry->connection = (void *)newsocket;
285 server->id_entry = id_entry;
287 /* Register protocols */
288 silc_server_protocols_register();
290 /* Add the first task to the scheduler. This is task that is executed by
291 timeout. It expires as soon as the caller calls silc_server_run. This
292 task performs authentication protocol and key exchange with our
294 silc_schedule_task_add(server->schedule, sock,
295 silc_server_connect_to_router,
296 (void *)server, 0, 1,
298 SILC_TASK_PRI_NORMAL);
300 /* Add listener task to the scheduler. This task receives new connections
301 to the server. This task remains on the queue until the end of the
303 silc_schedule_task_add(server->schedule, sock,
304 silc_server_accept_new_connection,
305 (void *)server, 0, 0,
307 SILC_TASK_PRI_NORMAL);
308 server->listenning = TRUE;
310 /* If server connections has been configured then we must be router as
311 normal server cannot have server connections, only router connections. */
312 if (server->config->servers) {
313 SilcServerConfigServer *ptr = server->config->servers;
315 server->server_type = SILC_ROUTER;
317 if (ptr->backup_router) {
318 server->server_type = SILC_BACKUP_ROUTER;
319 server->backup_router = TRUE;
320 server->id_entry->server_type = SILC_BACKUP_ROUTER;
327 /* Register the ID Cache purge task. This periodically purges the ID cache
328 and removes the expired cache entries. */
330 /* Clients local list */
331 purge = silc_calloc(1, sizeof(*purge));
332 purge->cache = server->local_list->clients;
333 purge->schedule = server->schedule;
334 purge->timeout = 600;
335 silc_schedule_task_add(purge->schedule, 0,
337 (void *)purge, purge->timeout, 0,
338 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
340 /* Clients global list */
341 purge = silc_calloc(1, sizeof(*purge));
342 purge->cache = server->global_list->clients;
343 purge->schedule = server->schedule;
344 purge->timeout = 300;
345 silc_schedule_task_add(purge->schedule, 0,
347 (void *)purge, purge->timeout, 0,
348 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
350 SILC_LOG_DEBUG(("Server initialized"));
352 /* We are done here, return succesfully */
356 silc_net_close_server(sock);
360 /* This function basically reads the config file again and switches the config
361 object pointed by the server object. After that, we have to fix various
362 things such as the server_name and the listening ports.
363 Keep in mind that we no longer have the root privileges at this point. */
365 bool silc_server_rehash(SilcServer server)
367 SilcServerConfig newconfig;
369 /* Our old config is gone now. We'll unreference our reference made in
370 silc_server_init and then destroy it since we are destroying it
371 underneath the application (layer which called silc_server_init). */
372 silc_server_config_unref(&server->config_ref);
373 silc_server_config_destroy(server->config);
375 /* Reset the logging system */
376 silc_log_quick = TRUE;
377 silc_log_flush_all();
379 /* Start the main rehash phase (read again the config file) */
380 SILC_LOG_INFO(("Rehashing server"));
381 newconfig = silc_server_config_alloc(server->config_file);
383 SILC_LOG_ERROR(("Rehash FAILED."));
387 /* Take new config context */
388 server->config = newconfig;
389 silc_server_config_ref(&server->config_ref, server->config, server->config);
391 /* Set public and private keys */
392 if (!server->config->server_info ||
393 !server->config->server_info->public_key ||
394 !server->config->server_info->private_key) {
395 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
399 /* Fix the server_name field */
400 if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
401 /* We don't need any update */
402 silc_free(newconfig->server_info->server_name);
403 newconfig->server_info->server_name = NULL;
405 silc_free(server->server_name);
406 server->server_name = newconfig->server_info->server_name;
407 newconfig->server_info->server_name = NULL;
409 /* Update the idcache list with a fresh pointer */
410 silc_free(server->id_entry->server_name);
411 server->id_entry->server_name = strdup(server->server_name);
412 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
413 silc_idcache_add(server->local_list->servers,
414 server->id_entry->server_name,
415 server->id_entry->id, server->id_entry, 0, NULL);
418 silc_server_config_setlogfiles(server);
420 /* Change new key pair if necessary */
421 if (server->config->server_info->public_key &&
422 !silc_pkcs_public_key_compare(server->public_key,
423 server->config->server_info->public_key)) {
424 silc_pkcs_public_key_free(server->public_key);
425 silc_pkcs_private_key_free(server->private_key);
426 server->public_key = server->config->server_info->public_key;
427 server->private_key = server->config->server_info->private_key;
428 server->config->server_info->public_key = NULL;
429 server->config->server_info->private_key = NULL;
431 /* Allocate PKCS context for local public and private keys */
432 silc_pkcs_free(server->pkcs);
433 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
435 silc_pkcs_public_key_set(server->pkcs, server->public_key);
436 silc_pkcs_private_key_set(server->pkcs, server->private_key);
442 /* Drop root privileges. If some system call fails, die. */
444 void silc_server_drop(SilcServer server)
446 /* Are we executing silcd as root or a regular user? */
448 SILC_LOG_DEBUG(("Server started as user"));
455 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
457 /* Get the values given for user and group in configuration file */
458 user = server->config->server_info->user;
459 group = server->config->server_info->group;
461 if (!user || !group) {
462 fprintf(stderr, "Error:"
463 "\tSILC server must not be run as root. For the security of your\n"
464 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
465 "\tuser account. Modify the ServerInfo configuration section to run\n"
466 "\tthe server as non-root user.\n");
470 /* Check whether the user/group does not begin with a number */
471 if (isdigit(user[0]) || isdigit(group[0])) {
472 SILC_LOG_DEBUG(("User and/or group starts with a number"));
473 fprintf(stderr, "Invalid user and/or group information\n");
474 fprintf(stderr, "Please assign them as names, not numbers\n");
478 if (!(pw = getpwnam(user))) {
479 fprintf(stderr, "Error: No such user %s found.\n", user);
482 if (!(gr = getgrnam(group))) {
483 fprintf(stderr, "Error: No such group %s found.\n", group);
487 /* Check whether user and/or group is set to root. If yes, exit
488 immediately. Otherwise, setgid and setuid server to user.group */
489 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
490 fprintf(stderr, "Error:"
491 "\tSILC server must not be run as root. For the security of your\n"
492 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
493 "\tuser account. Modify the ServerInfo configuration section to run\n"
494 "\tthe server as non-root user.\n");
498 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
499 if (setgid(gr->gr_gid) != 0) {
500 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
504 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
505 SILC_LOG_DEBUG(("Removing supplementary groups"));
506 if (setgroups(0, NULL) != 0) {
507 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
510 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
511 if (initgroups(user, gr->gr_gid) != 0) {
512 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
513 "Exiting.\n", user, gr->gr_gid);
517 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
518 if (setuid(pw->pw_uid) != 0) {
519 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
526 /* Fork server to background */
528 void silc_server_daemonise(SilcServer server)
532 SILC_LOG_DEBUG(("Forking SILC server to background"));
534 if ((i = fork()) < 0) {
535 fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
539 if (i) /* Kill the parent */
542 server->background = TRUE;
545 /* XXX close stdin, stdout, stderr -- before this, check that all writes
546 to stderr are changed to SILC_SERVER_LOG_ERROR() */
549 /* The heart of the server. This runs the scheduler thus runs the server.
550 When this returns the server has been stopped and the program will
553 void silc_server_run(SilcServer server)
555 SILC_LOG_INFO(("SILC Server started"));
557 /* Start the scheduler, the heart of the SILC server. When this returns
558 the program will be terminated. */
559 silc_schedule(server->schedule);
562 /* Stops the SILC server. This function is used to shutdown the server.
563 This is usually called after the scheduler has returned. After stopping
564 the server one should call silc_server_free. */
566 void silc_server_stop(SilcServer server)
568 SILC_LOG_DEBUG(("Stopping server"));
570 if (server->schedule) {
571 silc_schedule_stop(server->schedule);
572 silc_schedule_uninit(server->schedule);
573 server->schedule = NULL;
576 silc_server_protocols_unregister();
578 SILC_LOG_DEBUG(("Server stopped"));
581 /* Function that is called when the network connection to a router has
582 been established. This will continue with the key exchange protocol
583 with the remote router. */
585 void silc_server_start_key_exchange(SilcServer server,
586 SilcServerConnection sconn,
589 SilcSocketConnection newsocket;
590 SilcProtocol protocol;
591 SilcServerKEInternalContext *proto_ctx;
592 SilcServerConfigRouter *conn =
593 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
596 /* Cancel any possible retry timeouts */
597 silc_schedule_task_del_by_callback(server->schedule,
598 silc_server_connect_router);
600 /* Set socket options */
601 silc_net_set_socket_nonblock(sock);
602 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
604 /* Create socket connection for the connection. Even though we
605 know that we are connecting to a router we will mark the socket
606 to be unknown connection until we have executed authentication
608 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
609 server->sockets[sock] = newsocket;
610 newsocket->hostname = strdup(sconn->remote_host);
611 newsocket->ip = strdup(sconn->remote_host);
612 newsocket->port = sconn->remote_port;
613 sconn->sock = newsocket;
615 /* Allocate internal protocol context. This is sent as context
617 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
618 proto_ctx->server = (void *)server;
619 proto_ctx->context = (void *)sconn;
620 proto_ctx->sock = newsocket;
621 proto_ctx->rng = server->rng;
622 proto_ctx->responder = FALSE;
624 /* Set Key Exchange flags from configuration, but fall back to global
626 SILC_GET_SKE_FLAGS(conn, proto_ctx);
627 if (server->config->param.key_exchange_pfs)
628 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
630 /* Perform key exchange protocol. silc_server_connect_to_router_second
631 will be called after the protocol is finished. */
632 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
633 &protocol, proto_ctx,
634 silc_server_connect_to_router_second);
635 newsocket->protocol = protocol;
637 /* Register a timeout task that will be executed if the protocol
638 is not executed within set limit. */
639 proto_ctx->timeout_task =
640 silc_schedule_task_add(server->schedule, sock,
641 silc_server_timeout_remote,
642 server, server->config->key_exchange_timeout, 0,
646 /* Register the connection for network input and output. This sets
647 that scheduler will listen for incoming packets for this connection
648 and sets that outgoing packets may be sent to this connection as
649 well. However, this doesn't set the scheduler for outgoing traffic,
650 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
651 later when outgoing data is available. */
652 context = (void *)server;
653 SILC_REGISTER_CONNECTION_FOR_IO(sock);
655 /* Run the protocol */
656 silc_protocol_execute(protocol, server->schedule, 0, 0);
659 /* Timeout callback that will be called to retry connecting to remote
660 router. This is used by both normal and router server. This will wait
661 before retrying the connecting. The timeout is generated by exponential
662 backoff algorithm. */
664 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
666 SilcServerConnection sconn = (SilcServerConnection)context;
667 SilcServer server = sconn->server;
668 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
669 SilcServerConfigConnParams *param =
670 (conn->param ? conn->param : &server->config->param);
672 SILC_LOG_INFO(("Retrying connecting to a router"));
674 /* Calculate next timeout */
675 if (sconn->retry_count >= 1) {
676 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
677 if (sconn->retry_timeout > param->reconnect_interval_max)
678 sconn->retry_timeout = param->reconnect_interval_max;
680 sconn->retry_timeout = param->reconnect_interval;
682 sconn->retry_count++;
683 sconn->retry_timeout = sconn->retry_timeout +
684 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
686 /* If we've reached max retry count, give up. */
687 if ((sconn->retry_count > param->reconnect_count) &&
688 !param->reconnect_keep_trying) {
689 SILC_LOG_ERROR(("Could not connect to router, giving up"));
690 silc_server_config_unref(&sconn->conn);
691 silc_free(sconn->remote_host);
692 silc_free(sconn->backup_replace_ip);
697 /* We will lookup a fresh pointer later */
698 silc_server_config_unref(&sconn->conn);
700 /* Wait one before retrying */
701 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
702 context, sconn->retry_timeout, 0,
703 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
706 /* Generic routine to use connect to a router. */
708 SILC_TASK_CALLBACK(silc_server_connect_router)
710 SilcServerConnection sconn = (SilcServerConnection)context;
711 SilcServer server = sconn->server;
712 SilcServerConfigRouter *rconn;
715 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
716 (sconn->backup ? "backup router" : "router"),
717 sconn->remote_host, sconn->remote_port));
719 server->router_connect = time(NULL);
720 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
723 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
724 (sconn->backup ? "backup router" : "router"),
725 sconn->remote_host, sconn->remote_port));
726 silc_free(sconn->remote_host);
727 silc_free(sconn->backup_replace_ip);
731 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
733 /* Connect to remote host */
734 sock = silc_net_create_connection(server->config->server_info->server_ip,
738 SILC_LOG_ERROR(("Could not connect to router %s:%d",
739 sconn->remote_host, sconn->remote_port));
740 if (!sconn->no_reconnect)
741 silc_schedule_task_add(server->schedule, 0,
742 silc_server_connect_to_router_retry,
743 context, 0, 1, SILC_TASK_TIMEOUT,
744 SILC_TASK_PRI_NORMAL);
746 silc_server_config_unref(&sconn->conn);
750 /* Continue with key exchange protocol */
751 silc_server_start_key_exchange(server, sconn, sock);
754 /* This function connects to our primary router or if we are a router this
755 establishes all our primary routes. This is called at the start of the
756 server to do authentication and key exchange with our router - called
759 SILC_TASK_CALLBACK(silc_server_connect_to_router)
761 SilcServer server = (SilcServer)context;
762 SilcServerConnection sconn;
763 SilcServerConfigRouter *ptr;
765 SILC_LOG_DEBUG(("Connecting to router(s)"));
767 if (server->server_type == SILC_SERVER) {
768 SILC_LOG_DEBUG(("We are normal server"));
769 } else if (server->server_type == SILC_ROUTER) {
770 SILC_LOG_DEBUG(("We are router"));
772 SILC_LOG_DEBUG(("We are backup router/normal server"));
775 if (!server->config->routers) {
776 /* There wasn't a configured router, we will continue but we don't
777 have a connection to outside world. We will be standalone server. */
778 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
779 server->standalone = TRUE;
783 /* Create the connections to all our routes */
784 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
786 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
787 ptr->backup_router ? "Backup router" : "Router",
788 ptr->initiator ? "Initiator" : "Responder",
789 ptr->host, ptr->port));
791 if (ptr->initiator) {
792 /* Allocate connection object for hold connection specific stuff. */
793 sconn = silc_calloc(1, sizeof(*sconn));
794 sconn->server = server;
795 sconn->remote_host = strdup(ptr->host);
796 sconn->remote_port = ptr->port;
797 sconn->backup = ptr->backup_router;
799 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
800 sconn->backup_replace_port = ptr->backup_replace_port;
803 if (!server->router_conn && !sconn->backup)
804 server->router_conn = sconn;
806 silc_schedule_task_add(server->schedule, fd,
807 silc_server_connect_router,
808 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
809 SILC_TASK_PRI_NORMAL);
814 /* Second part of connecting to router(s). Key exchange protocol has been
815 executed and now we will execute authentication protocol. */
817 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
819 SilcProtocol protocol = (SilcProtocol)context;
820 SilcServerKEInternalContext *ctx =
821 (SilcServerKEInternalContext *)protocol->context;
822 SilcServer server = (SilcServer)ctx->server;
823 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
824 SilcSocketConnection sock = ctx->sock;
825 SilcServerConnAuthInternalContext *proto_ctx;
826 SilcServerConfigRouter *conn = NULL;
828 SILC_LOG_DEBUG(("Start"));
830 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
831 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
832 /* Error occured during protocol */
833 silc_protocol_free(protocol);
834 sock->protocol = NULL;
835 silc_ske_free_key_material(ctx->keymat);
837 silc_packet_context_free(ctx->packet);
839 silc_ske_free(ctx->ske);
840 silc_free(ctx->dest_id);
842 silc_server_config_unref(&sconn->conn);
843 silc_free(sconn->remote_host);
844 silc_free(sconn->backup_replace_ip);
846 silc_schedule_task_del_by_callback(server->schedule,
847 silc_server_failure_callback);
848 silc_server_disconnect_remote(server, sock, "Server closed connection: "
849 "Key exchange failed");
853 /* We now have the key material as the result of the key exchange
854 protocol. Take the key material into use. Free the raw key material
855 as soon as we've set them into use. */
856 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
857 ctx->sock, ctx->keymat,
858 ctx->ske->prop->cipher,
859 ctx->ske->prop->pkcs,
860 ctx->ske->prop->hash,
861 ctx->ske->prop->hmac,
862 ctx->ske->prop->group,
864 silc_protocol_free(protocol);
865 sock->protocol = NULL;
866 silc_ske_free_key_material(ctx->keymat);
868 silc_packet_context_free(ctx->packet);
870 silc_ske_free(ctx->ske);
871 silc_free(ctx->dest_id);
873 silc_server_config_unref(&sconn->conn);
874 silc_free(sconn->remote_host);
875 silc_free(sconn->backup_replace_ip);
877 silc_schedule_task_del_by_callback(server->schedule,
878 silc_server_failure_callback);
879 silc_server_disconnect_remote(server, sock, "Server closed connection: "
880 "Key exchange failed");
883 silc_ske_free_key_material(ctx->keymat);
885 /* Allocate internal context for the authentication protocol. This
886 is sent as context for the protocol. */
887 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
888 proto_ctx->server = (void *)server;
889 proto_ctx->context = (void *)sconn;
890 proto_ctx->sock = sock;
891 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
892 proto_ctx->dest_id_type = ctx->dest_id_type;
893 proto_ctx->dest_id = ctx->dest_id;
895 /* Resolve the authentication method used in this connection. Check if
896 we find a match from user configured connections */
897 if (!sconn->conn.ref_ptr)
898 conn = silc_server_config_find_router_conn(server, sock->hostname,
901 conn = sconn->conn.ref_ptr;
904 /* Match found. Use the configured authentication method. Take only
905 the passphrase, since for public key auth we automatically use
906 our local key pair. */
907 if (conn->passphrase) {
908 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
909 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
911 proto_ctx->auth_data = strdup(conn->passphrase);
912 proto_ctx->auth_data_len = strlen(conn->passphrase);
913 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
915 } else if (conn->publickeys) {
916 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
918 proto_ctx->auth_meth = SILC_AUTH_NONE;
921 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
922 sock->hostname, sock->ip, sock->port));
923 silc_protocol_free(protocol);
924 sock->protocol = NULL;
926 silc_packet_context_free(ctx->packet);
928 silc_ske_free(ctx->ske);
929 silc_free(ctx->dest_id);
931 silc_server_config_unref(&sconn->conn);
932 silc_free(sconn->remote_host);
933 silc_free(sconn->backup_replace_ip);
935 silc_schedule_task_del_by_callback(server->schedule,
936 silc_server_failure_callback);
937 silc_server_disconnect_remote(server, sock, "Server closed connection: "
938 "Key exchange failed");
942 /* Free old protocol as it is finished now */
943 silc_protocol_free(protocol);
945 silc_packet_context_free(ctx->packet);
947 sock->protocol = NULL;
949 /* Allocate the authentication protocol. This is allocated here
950 but we won't start it yet. We will be receiving party of this
951 protocol thus we will wait that connecting party will make
953 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
954 &sock->protocol, proto_ctx,
955 silc_server_connect_to_router_final);
957 /* Register timeout task. If the protocol is not executed inside
958 this timelimit the connection will be terminated. */
959 proto_ctx->timeout_task =
960 silc_schedule_task_add(server->schedule, sock->sock,
961 silc_server_timeout_remote,
963 server->config->conn_auth_timeout, 0,
967 /* Run the protocol */
968 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
971 /* Finalizes the connection to router. Registers a server task to the
972 queue so that we can accept new connections. */
974 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
976 SilcProtocol protocol = (SilcProtocol)context;
977 SilcServerConnAuthInternalContext *ctx =
978 (SilcServerConnAuthInternalContext *)protocol->context;
979 SilcServer server = (SilcServer)ctx->server;
980 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
981 SilcSocketConnection sock = ctx->sock;
982 SilcServerEntry id_entry;
984 SilcServerHBContext hb_context;
985 unsigned char *id_string;
987 SilcIDListData idata;
988 SilcServerConfigRouter *conn = NULL;
989 SilcServerConfigConnParams *param = NULL;
991 SILC_LOG_DEBUG(("Start"));
993 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
994 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
995 /* Error occured during protocol */
996 silc_free(ctx->dest_id);
997 silc_server_disconnect_remote(server, sock, "Server closed connection: "
998 "Authentication failed");
1002 /* Add a task to the queue. This task receives new connections to the
1003 server. This task remains on the queue until the end of the program. */
1004 if (!server->listenning && !sconn->backup) {
1005 silc_schedule_task_add(server->schedule, server->sock,
1006 silc_server_accept_new_connection,
1007 (void *)server, 0, 0,
1009 SILC_TASK_PRI_NORMAL);
1010 server->listenning = TRUE;
1013 /* Send NEW_SERVER packet to the router. We will become registered
1014 to the SILC network after sending this packet. */
1015 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1016 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1017 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1018 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1019 silc_buffer_format(packet,
1020 SILC_STR_UI_SHORT(id_len),
1021 SILC_STR_UI_XNSTRING(id_string, id_len),
1022 SILC_STR_UI_SHORT(strlen(server->server_name)),
1023 SILC_STR_UI_XNSTRING(server->server_name,
1024 strlen(server->server_name)),
1027 /* Send the packet */
1028 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1029 packet->data, packet->len, TRUE);
1030 silc_buffer_free(packet);
1031 silc_free(id_string);
1033 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1035 /* Check that we do not have this ID already */
1036 id_entry = silc_idlist_find_server_by_id(server->local_list,
1037 ctx->dest_id, TRUE, NULL);
1039 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1041 id_entry = silc_idlist_find_server_by_id(server->global_list,
1042 ctx->dest_id, TRUE, NULL);
1044 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1047 SILC_LOG_DEBUG(("New server id(%s)",
1048 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1050 /* Add the connected router to global server list */
1051 id_entry = silc_idlist_add_server(server->global_list,
1052 strdup(sock->hostname),
1053 SILC_ROUTER, ctx->dest_id, NULL, sock);
1055 silc_free(ctx->dest_id);
1056 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1057 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1058 "Authentication failed");
1062 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1063 silc_free(sock->user_data);
1064 sock->user_data = (void *)id_entry;
1065 sock->type = SILC_SOCKET_TYPE_ROUTER;
1066 idata = (SilcIDListData)sock->user_data;
1067 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1069 conn = sconn->conn.ref_ptr;
1070 param = &server->config->param;
1071 if (conn && conn->param)
1072 param = conn->param;
1074 /* Perform keepalive. The `hb_context' will be freed automatically
1075 when finally calling the silc_socket_free function. */
1076 hb_context = silc_calloc(1, sizeof(*hb_context));
1077 hb_context->server = server;
1078 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1079 silc_server_perform_heartbeat,
1082 /* Register re-key timeout */
1083 idata->rekey->timeout = param->key_exchange_rekey;
1084 idata->rekey->context = (void *)server;
1085 silc_schedule_task_add(server->schedule, sock->sock,
1086 silc_server_rekey_callback,
1087 (void *)sock, idata->rekey->timeout, 0,
1088 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1090 if (!sconn->backup) {
1091 /* Mark this router our primary router if we're still standalone */
1092 if (server->standalone) {
1093 server->id_entry->router = id_entry;
1094 server->router = id_entry;
1095 server->standalone = FALSE;
1097 /* If we are router then announce our possible servers. */
1098 if (server->server_type == SILC_ROUTER)
1099 silc_server_announce_servers(server, FALSE, 0,
1100 server->router->connection);
1102 /* Announce our clients and channels to the router */
1103 silc_server_announce_clients(server, 0, server->router->connection);
1104 silc_server_announce_channels(server, 0, server->router->connection);
1107 /* Add this server to be our backup router */
1108 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1109 sconn->backup_replace_port, FALSE);
1112 sock->protocol = NULL;
1114 /* Call the completion callback to indicate that we've connected to
1116 if (sconn->callback)
1117 (*sconn->callback)(server, id_entry, sconn->callback_context);
1120 /* Free the temporary connection data context */
1122 silc_server_config_unref(&sconn->conn);
1123 silc_free(sconn->remote_host);
1124 silc_free(sconn->backup_replace_ip);
1127 if (sconn == server->router_conn)
1128 server->router_conn = NULL;
1130 /* Free the protocol object */
1131 if (sock->protocol == protocol)
1132 sock->protocol = NULL;
1133 silc_protocol_free(protocol);
1135 silc_packet_context_free(ctx->packet);
1137 silc_ske_free(ctx->ske);
1138 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1139 silc_free(ctx->auth_data);
1143 /* Host lookup callback that is called after the incoming connection's
1144 IP and FQDN lookup is performed. This will actually check the acceptance
1145 of the incoming connection and will register the key exchange protocol
1146 for this connection. */
1149 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1152 SilcServer server = (SilcServer)context;
1153 SilcServerKEInternalContext *proto_ctx;
1154 SilcServerConfigClient *cconfig = NULL;
1155 SilcServerConfigServer *sconfig = NULL;
1156 SilcServerConfigRouter *rconfig = NULL;
1157 SilcServerConfigDeny *deny;
1160 SILC_LOG_DEBUG(("Start"));
1162 /* Check whether we could resolve both IP and FQDN. */
1163 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1164 server->config->require_reverse_lookup)) {
1165 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1166 sock->hostname ? sock->hostname :
1167 sock->ip ? sock->ip : ""));
1168 server->stat.conn_failures++;
1169 silc_server_disconnect_remote(server, sock,
1170 "Server closed connection: Unknown host");
1174 /* Register the connection for network input and output. This sets
1175 that scheduler will listen for incoming packets for this connection
1176 and sets that outgoing packets may be sent to this connection as well.
1177 However, this doesn't set the scheduler for outgoing traffic, it
1178 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1179 later when outgoing data is available. */
1180 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1182 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1185 port = server->sockets[server->sock]->port; /* Listenning port */
1187 /* Check whether this connection is denied to connect to us. */
1188 deny = silc_server_config_find_denied(server, sock->ip);
1190 deny = silc_server_config_find_denied(server, sock->hostname);
1192 /* The connection is denied */
1193 SILC_LOG_INFO(("Connection %s (%s) is denied",
1194 sock->hostname, sock->ip));
1195 silc_server_disconnect_remote(server, sock, deny->reason ?
1197 "Server closed connection: "
1198 "Connection refused");
1199 server->stat.conn_failures++;
1203 /* Check whether we have configured this sort of connection at all. We
1204 have to check all configurations since we don't know what type of
1205 connection this is. */
1206 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1207 cconfig = silc_server_config_find_client(server, sock->hostname);
1208 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1209 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1210 if (server->server_type == SILC_ROUTER) {
1211 if (!(rconfig = silc_server_config_find_router_conn(server,
1213 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1216 if (!cconfig && !sconfig && !rconfig) {
1217 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1219 silc_server_disconnect_remote(server, sock,
1220 "Server closed connection: "
1221 "Connection refused");
1222 server->stat.conn_failures++;
1226 /* The connection is allowed */
1228 /* Allocate internal context for key exchange protocol. This is
1229 sent as context for the protocol. */
1230 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1231 proto_ctx->server = context;
1232 proto_ctx->sock = sock;
1233 proto_ctx->rng = server->rng;
1234 proto_ctx->responder = TRUE;
1235 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1236 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1237 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1239 /* Take flags for key exchange. Since we do not know what type of connection
1240 this is, we go through all found configurations and use the global ones
1241 as well. This will result always into strictest key exchange flags. */
1242 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1243 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1244 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1245 if (server->config->param.key_exchange_pfs)
1246 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1248 /* Prepare the connection for key exchange protocol. We allocate the
1249 protocol but will not start it yet. The connector will be the
1250 initiator of the protocol thus we will wait for initiation from
1251 there before we start the protocol. */
1252 server->stat.auth_attempts++;
1253 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1254 &sock->protocol, proto_ctx,
1255 silc_server_accept_new_connection_second);
1257 /* Register a timeout task that will be executed if the connector
1258 will not start the key exchange protocol within specified timeout
1259 and the connection will be closed. */
1260 proto_ctx->timeout_task =
1261 silc_schedule_task_add(server->schedule, sock->sock,
1262 silc_server_timeout_remote,
1263 context, server->config->key_exchange_timeout, 0,
1268 /* Accepts new connections to the server. Accepting new connections are
1269 done in three parts to make it async. */
1271 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1273 SilcServer server = (SilcServer)context;
1274 SilcSocketConnection newsocket;
1277 SILC_LOG_DEBUG(("Accepting new connection"));
1279 server->stat.conn_attempts++;
1281 sock = silc_net_accept_connection(server->sock);
1283 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1284 server->stat.conn_failures++;
1288 /* Check for maximum allowed connections */
1289 if (sock > server->config->param.connections_max) {
1290 SILC_LOG_ERROR(("Refusing connection, server is full"));
1291 server->stat.conn_failures++;
1292 silc_net_close_connection(sock);
1296 /* Set socket options */
1297 silc_net_set_socket_nonblock(sock);
1298 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1300 /* We don't create a ID yet, since we don't know what type of connection
1301 this is yet. But, we do add the connection to the socket table. */
1302 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1303 server->sockets[sock] = newsocket;
1305 /* Perform asynchronous host lookup. This will lookup the IP and the
1306 FQDN of the remote connection. After the lookup is done the connection
1307 is accepted further. */
1308 silc_socket_host_lookup(newsocket, TRUE,
1309 silc_server_accept_new_connection_lookup, context,
1313 /* Second part of accepting new connection. Key exchange protocol has been
1314 performed and now it is time to do little connection authentication
1315 protocol to figure out whether this connection is client or server
1316 and whether it has right to access this server (especially server
1317 connections needs to be authenticated). */
1319 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1321 SilcProtocol protocol = (SilcProtocol)context;
1322 SilcServerKEInternalContext *ctx =
1323 (SilcServerKEInternalContext *)protocol->context;
1324 SilcServer server = (SilcServer)ctx->server;
1325 SilcSocketConnection sock = ctx->sock;
1326 SilcServerConnAuthInternalContext *proto_ctx;
1328 SILC_LOG_DEBUG(("Start"));
1330 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1331 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1332 /* Error occured during protocol */
1333 silc_protocol_free(protocol);
1334 sock->protocol = NULL;
1335 silc_ske_free_key_material(ctx->keymat);
1337 silc_packet_context_free(ctx->packet);
1339 silc_ske_free(ctx->ske);
1340 silc_free(ctx->dest_id);
1341 silc_server_config_unref(&ctx->cconfig);
1342 silc_server_config_unref(&ctx->sconfig);
1343 silc_server_config_unref(&ctx->rconfig);
1345 silc_schedule_task_del_by_callback(server->schedule,
1346 silc_server_failure_callback);
1347 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1348 "Key exchange failed");
1349 server->stat.auth_failures++;
1353 /* We now have the key material as the result of the key exchange
1354 protocol. Take the key material into use. Free the raw key material
1355 as soon as we've set them into use. */
1356 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1357 ctx->sock, ctx->keymat,
1358 ctx->ske->prop->cipher,
1359 ctx->ske->prop->pkcs,
1360 ctx->ske->prop->hash,
1361 ctx->ske->prop->hmac,
1362 ctx->ske->prop->group,
1364 silc_protocol_free(protocol);
1365 sock->protocol = NULL;
1366 silc_ske_free_key_material(ctx->keymat);
1368 silc_packet_context_free(ctx->packet);
1370 silc_ske_free(ctx->ske);
1371 silc_free(ctx->dest_id);
1372 silc_server_config_unref(&ctx->cconfig);
1373 silc_server_config_unref(&ctx->sconfig);
1374 silc_server_config_unref(&ctx->rconfig);
1376 silc_schedule_task_del_by_callback(server->schedule,
1377 silc_server_failure_callback);
1378 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1379 "Key exchange failed");
1380 server->stat.auth_failures++;
1383 silc_ske_free_key_material(ctx->keymat);
1385 /* Allocate internal context for the authentication protocol. This
1386 is sent as context for the protocol. */
1387 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1388 proto_ctx->server = (void *)server;
1389 proto_ctx->sock = sock;
1390 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1391 proto_ctx->responder = TRUE;
1392 proto_ctx->dest_id_type = ctx->dest_id_type;
1393 proto_ctx->dest_id = ctx->dest_id;
1394 proto_ctx->cconfig = ctx->cconfig;
1395 proto_ctx->sconfig = ctx->sconfig;
1396 proto_ctx->rconfig = ctx->rconfig;
1398 /* Free old protocol as it is finished now */
1399 silc_protocol_free(protocol);
1401 silc_packet_context_free(ctx->packet);
1403 sock->protocol = NULL;
1405 /* Allocate the authentication protocol. This is allocated here
1406 but we won't start it yet. We will be receiving party of this
1407 protocol thus we will wait that connecting party will make
1408 their first move. */
1409 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1410 &sock->protocol, proto_ctx,
1411 silc_server_accept_new_connection_final);
1413 /* Register timeout task. If the protocol is not executed inside
1414 this timelimit the connection will be terminated. */
1415 proto_ctx->timeout_task =
1416 silc_schedule_task_add(server->schedule, sock->sock,
1417 silc_server_timeout_remote,
1419 server->config->conn_auth_timeout, 0,
1424 /* Final part of accepting new connection. The connection has now
1425 been authenticated and keys has been exchanged. We also know whether
1426 this is client or server connection. */
1428 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1430 SilcProtocol protocol = (SilcProtocol)context;
1431 SilcServerConnAuthInternalContext *ctx =
1432 (SilcServerConnAuthInternalContext *)protocol->context;
1433 SilcServer server = (SilcServer)ctx->server;
1434 SilcSocketConnection sock = ctx->sock;
1435 SilcServerHBContext hb_context;
1436 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1438 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1440 SILC_LOG_DEBUG(("Start"));
1442 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1443 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1444 /* Error occured during protocol */
1445 silc_protocol_free(protocol);
1446 sock->protocol = NULL;
1448 silc_packet_context_free(ctx->packet);
1450 silc_ske_free(ctx->ske);
1451 silc_free(ctx->dest_id);
1452 silc_server_config_unref(&ctx->cconfig);
1453 silc_server_config_unref(&ctx->sconfig);
1454 silc_server_config_unref(&ctx->rconfig);
1456 silc_schedule_task_del_by_callback(server->schedule,
1457 silc_server_failure_callback);
1458 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1459 "Authentication failed");
1460 server->stat.auth_failures++;
1464 entry->data.last_receive = time(NULL);
1466 switch (ctx->conn_type) {
1467 case SILC_SOCKET_TYPE_CLIENT:
1469 SilcClientEntry client;
1470 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1472 /* Verify whether this connection is after all allowed to connect */
1473 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1474 &server->config->param,
1475 conn->param, ctx->ske)) {
1476 server->stat.auth_failures++;
1480 SILC_LOG_DEBUG(("Remote host is client"));
1481 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1484 /* Add the client to the client ID cache. The nickname and Client ID
1485 and other information is created after we have received NEW_CLIENT
1486 packet from client. */
1487 client = silc_idlist_add_client(server->local_list,
1488 NULL, NULL, NULL, NULL, NULL, sock, 0);
1490 SILC_LOG_ERROR(("Could not add new client to cache"));
1491 silc_free(sock->user_data);
1492 silc_server_disconnect_remote(server, sock,
1493 "Server closed connection: "
1494 "Authentication failed");
1495 server->stat.auth_failures++;
1500 server->stat.my_clients++;
1501 server->stat.clients++;
1502 if (server->server_type == SILC_ROUTER)
1503 server->stat.cell_clients++;
1505 /* Get connection parameters */
1507 if (conn->param->keepalive_secs)
1508 hearbeat_timeout = conn->param->keepalive_secs;
1511 id_entry = (void *)client;
1514 case SILC_SOCKET_TYPE_SERVER:
1515 case SILC_SOCKET_TYPE_ROUTER:
1517 SilcServerEntry new_server;
1518 bool initiator = FALSE;
1519 bool backup_local = FALSE;
1520 bool backup_router = FALSE;
1521 char *backup_replace_ip = NULL;
1522 SilcUInt16 backup_replace_port = 0;
1523 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1524 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1526 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1527 /* Verify whether this connection is after all allowed to connect */
1528 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1529 &server->config->param,
1530 rconn ? rconn->param : NULL,
1532 server->stat.auth_failures++;
1538 if (rconn->param->keepalive_secs)
1539 hearbeat_timeout = rconn->param->keepalive_secs;
1542 initiator = rconn->initiator;
1543 backup_local = rconn->backup_local;
1544 backup_router = rconn->backup_router;
1545 backup_replace_ip = rconn->backup_replace_ip;
1546 backup_replace_port = rconn->backup_replace_port;
1550 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1551 /* Verify whether this connection is after all allowed to connect */
1552 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1553 &server->config->param,
1554 sconn ? sconn->param : NULL,
1556 server->stat.auth_failures++;
1561 if (sconn->param->keepalive_secs)
1562 hearbeat_timeout = sconn->param->keepalive_secs;
1565 backup_router = sconn->backup_router;
1569 SILC_LOG_DEBUG(("Remote host is %s",
1570 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1571 "server" : (backup_router ?
1572 "backup router" : "router")));
1573 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1574 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1575 "server" : (backup_router ?
1576 "backup router" : "router")));
1578 /* Add the server into server cache. The server name and Server ID
1579 is updated after we have received NEW_SERVER packet from the
1580 server. We mark ourselves as router for this server if we really
1583 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1584 server->local_list : (backup_router ?
1585 server->local_list :
1586 server->global_list)),
1588 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1589 SILC_SERVER : SILC_ROUTER),
1591 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1592 server->id_entry : (backup_router ?
1593 server->id_entry : NULL)),
1596 SILC_LOG_ERROR(("Could not add new server to cache"));
1597 silc_free(sock->user_data);
1598 silc_server_disconnect_remote(server, sock,
1599 "Server closed connection: "
1600 "Authentication failed");
1601 server->stat.auth_failures++;
1606 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1607 server->stat.my_servers++;
1609 server->stat.my_routers++;
1610 server->stat.servers++;
1612 id_entry = (void *)new_server;
1614 /* If the incoming connection is router and marked as backup router
1615 then add it to be one of our backups */
1616 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1617 silc_server_backup_add(server, new_server, backup_replace_ip,
1618 backup_replace_port, backup_local);
1620 /* Change it back to SERVER type since that's what it really is. */
1622 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1624 new_server->server_type = SILC_BACKUP_ROUTER;
1627 /* Check whether this connection is to be our primary router connection
1628 if we do not already have the primary route. */
1629 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1630 if (silc_server_config_is_primary_route(server) && !initiator)
1633 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1634 server->standalone = FALSE;
1635 if (!server->id_entry->router) {
1636 server->id_entry->router = id_entry;
1637 server->router = id_entry;
1648 sock->type = ctx->conn_type;
1650 /* Add the common data structure to the ID entry. */
1651 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1653 /* Add to sockets internal pointer for fast referencing */
1654 silc_free(sock->user_data);
1655 sock->user_data = id_entry;
1657 /* Connection has been fully established now. Everything is ok. */
1658 SILC_LOG_DEBUG(("New connection authenticated"));
1660 /* Perform keepalive. The `hb_context' will be freed automatically
1661 when finally calling the silc_socket_free function. */
1662 hb_context = silc_calloc(1, sizeof(*hb_context));
1663 hb_context->server = server;
1664 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1665 silc_server_perform_heartbeat,
1669 silc_schedule_task_del_by_callback(server->schedule,
1670 silc_server_failure_callback);
1671 silc_protocol_free(protocol);
1673 silc_packet_context_free(ctx->packet);
1675 silc_ske_free(ctx->ske);
1676 silc_free(ctx->dest_id);
1677 silc_server_config_unref(&ctx->cconfig);
1678 silc_server_config_unref(&ctx->sconfig);
1679 silc_server_config_unref(&ctx->rconfig);
1681 sock->protocol = NULL;
1684 /* This function is used to read packets from network and send packets to
1685 network. This is usually a generic task. */
1687 SILC_TASK_CALLBACK(silc_server_packet_process)
1689 SilcServer server = (SilcServer)context;
1690 SilcSocketConnection sock = server->sockets[fd];
1691 SilcIDListData idata;
1692 SilcCipher cipher = NULL;
1693 SilcHmac hmac = NULL;
1694 SilcUInt32 sequence = 0;
1700 SILC_LOG_DEBUG(("Processing packet"));
1702 /* Packet sending */
1704 if (type == SILC_TASK_WRITE) {
1705 /* Do not send data to disconnected connection */
1706 if (SILC_IS_DISCONNECTED(sock))
1709 server->stat.packets_sent++;
1711 /* Send the packet */
1712 ret = silc_packet_send(sock, TRUE);
1714 /* If returned -2 could not write to connection now, will do
1720 SILC_LOG_ERROR(("Error sending packet to connection "
1721 "%s:%d [%s]", sock->hostname, sock->port,
1722 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1723 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1724 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1729 /* The packet has been sent and now it is time to set the connection
1730 back to only for input. When there is again some outgoing data
1731 available for this connection it will be set for output as well.
1732 This call clears the output setting and sets it only for input. */
1733 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1734 SILC_UNSET_OUTBUF_PENDING(sock);
1736 silc_buffer_clear(sock->outbuf);
1740 /* Packet receiving */
1742 /* Read some data from connection */
1743 ret = silc_packet_receive(sock);
1747 SILC_LOG_ERROR(("Error receiving packet from connection "
1748 "%s:%d [%s] %s", sock->hostname, sock->port,
1749 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1750 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1751 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1752 "Router"), strerror(errno)));
1758 SILC_LOG_DEBUG(("Read EOF"));
1760 /* If connection is disconnecting already we will finally
1761 close the connection */
1762 if (SILC_IS_DISCONNECTING(sock)) {
1763 if (sock->user_data)
1764 silc_server_free_sock_user_data(server, sock, NULL);
1765 silc_server_close_connection(server, sock);
1769 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1770 SILC_SET_DISCONNECTING(sock);
1772 if (sock->user_data) {
1774 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1775 silc_server_free_sock_user_data(server, sock, tmp);
1777 silc_server_free_sock_user_data(server, sock, NULL);
1778 } else if (server->router_conn && server->router_conn->sock == sock &&
1779 !server->router && server->standalone)
1780 silc_schedule_task_add(server->schedule, 0,
1781 silc_server_connect_to_router,
1784 SILC_TASK_PRI_NORMAL);
1786 silc_server_close_connection(server, sock);
1790 /* If connection is disconnecting or disconnected we will ignore
1792 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1793 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1797 server->stat.packets_received++;
1799 /* Get keys and stuff from ID entry */
1800 idata = (SilcIDListData)sock->user_data;
1802 cipher = idata->receive_key;
1803 hmac = idata->hmac_receive;
1804 sequence = idata->psn_receive;
1807 /* Process the packet. This will call the parser that will then
1808 decrypt and parse the packet. */
1809 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1810 TRUE : FALSE, cipher, hmac, sequence,
1811 silc_server_packet_parse, server);
1813 /* If this socket connection is not authenticated yet and the packet
1814 processing failed we will drop the connection since it can be
1815 a malicious flooder. */
1816 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1817 (!sock->protocol || sock->protocol->protocol->type ==
1818 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1819 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1820 SILC_SET_DISCONNECTING(sock);
1822 if (sock->user_data)
1823 silc_server_free_sock_user_data(server, sock, NULL);
1824 silc_server_close_connection(server, sock);
1828 /* Parses whole packet, received earlier. */
1830 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1832 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1833 SilcServer server = (SilcServer)parse_ctx->context;
1834 SilcSocketConnection sock = parse_ctx->sock;
1835 SilcPacketContext *packet = parse_ctx->packet;
1836 SilcIDListData idata = (SilcIDListData)sock->user_data;
1839 SILC_LOG_DEBUG(("Start"));
1841 /* Parse the packet */
1842 if (parse_ctx->normal)
1843 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1845 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1847 /* If entry is disabled ignore what we got. */
1848 if (ret != SILC_PACKET_RESUME_ROUTER &&
1849 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1850 SILC_LOG_DEBUG(("Connection is disabled"));
1854 if (ret == SILC_PACKET_NONE)
1857 /* Check that the the current client ID is same as in the client's packet. */
1858 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1859 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1860 if (client && client->id) {
1861 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1862 packet->src_id_type);
1863 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1871 if (server->server_type == SILC_ROUTER) {
1872 /* Route the packet if it is not destined to us. Other ID types but
1873 server are handled separately after processing them. */
1874 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1875 packet->dst_id_type == SILC_ID_SERVER &&
1876 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1877 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1879 /* Route the packet to fastest route for the destination ID */
1880 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1881 packet->dst_id_type);
1884 silc_server_packet_route(server,
1885 silc_server_route_get(server, id,
1886 packet->dst_id_type),
1893 /* Parse the incoming packet type */
1894 silc_server_packet_parse_type(server, sock, packet);
1896 if (server->server_type == SILC_ROUTER) {
1897 /* Broadcast packet if it is marked as broadcast packet and it is
1898 originated from router and we are router. */
1899 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1900 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1901 !server->standalone) {
1902 /* Broadcast to our primary route */
1903 silc_server_packet_broadcast(server, server->router->connection, packet);
1905 /* If we have backup routers then we need to feed all broadcast
1906 data to those servers. */
1907 silc_server_backup_broadcast(server, sock, packet);
1912 silc_packet_context_free(packet);
1913 silc_free(parse_ctx);
1916 /* Parser callback called by silc_packet_receive_process. This merely
1917 registers timeout that will handle the actual parsing when appropriate. */
1919 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1922 SilcServer server = (SilcServer)context;
1923 SilcSocketConnection sock = parser_context->sock;
1924 SilcIDListData idata = (SilcIDListData)sock->user_data;
1927 idata->psn_receive = parser_context->packet->sequence + 1;
1929 /* If protocol for this connection is key exchange or rekey then we'll
1930 process all packets synchronously, since there might be packets in
1931 queue that we are not able to decrypt without first processing the
1932 packets before them. */
1933 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1934 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1935 (sock->protocol && sock->protocol->protocol &&
1936 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1937 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1938 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1941 /* Reprocess data since we'll return FALSE here. This is because
1942 the idata->receive_key might have become valid in the last packet
1943 and we want to call this processor with valid cipher. */
1945 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1946 TRUE : FALSE, idata->receive_key,
1947 idata->hmac_receive, idata->psn_receive,
1948 silc_server_packet_parse, server);
1950 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1951 TRUE : FALSE, NULL, NULL, 0,
1952 silc_server_packet_parse, server);
1956 switch (sock->type) {
1957 case SILC_SOCKET_TYPE_UNKNOWN:
1958 case SILC_SOCKET_TYPE_CLIENT:
1959 /* Parse the packet with timeout */
1960 silc_schedule_task_add(server->schedule, sock->sock,
1961 silc_server_packet_parse_real,
1962 (void *)parser_context, 0, 100000,
1964 SILC_TASK_PRI_NORMAL);
1966 case SILC_SOCKET_TYPE_SERVER:
1967 case SILC_SOCKET_TYPE_ROUTER:
1968 /* Packets from servers are parsed immediately */
1969 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1979 /* Parses the packet type and calls what ever routines the packet type
1980 requires. This is done for all incoming packets. */
1982 void silc_server_packet_parse_type(SilcServer server,
1983 SilcSocketConnection sock,
1984 SilcPacketContext *packet)
1986 SilcPacketType type = packet->type;
1987 SilcIDListData idata = (SilcIDListData)sock->user_data;
1989 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1991 /* Parse the packet type */
1993 case SILC_PACKET_DISCONNECT:
1994 SILC_LOG_DEBUG(("Disconnect packet"));
1995 if (packet->flags & SILC_PACKET_FLAG_LIST)
1997 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1998 /* Duplicate to null terminate the string. */
1999 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
2000 SILC_LOG_ERROR(("%s", message));
2005 case SILC_PACKET_SUCCESS:
2007 * Success received for something. For now we can have only
2008 * one protocol for connection executing at once hence this
2009 * success message is for whatever protocol is executing currently.
2011 SILC_LOG_DEBUG(("Success packet"));
2012 if (packet->flags & SILC_PACKET_FLAG_LIST)
2015 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2018 case SILC_PACKET_FAILURE:
2020 * Failure received for something. For now we can have only
2021 * one protocol for connection executing at once hence this
2022 * failure message is for whatever protocol is executing currently.
2024 SILC_LOG_DEBUG(("Failure packet"));
2025 if (packet->flags & SILC_PACKET_FLAG_LIST)
2027 if (sock->protocol) {
2028 SilcServerFailureContext f;
2029 f = silc_calloc(1, sizeof(*f));
2033 /* We will wait 5 seconds to process this failure packet */
2034 silc_schedule_task_add(server->schedule, sock->sock,
2035 silc_server_failure_callback, (void *)f, 5, 0,
2036 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2040 case SILC_PACKET_REJECT:
2041 SILC_LOG_DEBUG(("Reject packet"));
2042 if (packet->flags & SILC_PACKET_FLAG_LIST)
2047 case SILC_PACKET_NOTIFY:
2049 * Received notify packet. Server can receive notify packets from
2050 * router. Server then relays the notify messages to clients if needed.
2052 SILC_LOG_DEBUG(("Notify packet"));
2053 if (packet->flags & SILC_PACKET_FLAG_LIST)
2054 silc_server_notify_list(server, sock, packet);
2056 silc_server_notify(server, sock, packet);
2062 case SILC_PACKET_CHANNEL_MESSAGE:
2064 * Received channel message. Channel messages are special packets
2065 * (although probably most common ones) thus they are handled
2068 SILC_LOG_DEBUG(("Channel Message packet"));
2069 if (packet->flags & SILC_PACKET_FLAG_LIST)
2071 idata->last_receive = time(NULL);
2072 silc_server_channel_message(server, sock, packet);
2075 case SILC_PACKET_CHANNEL_KEY:
2077 * Received key for channel. As channels are created by the router
2078 * the keys are as well. We will distribute the key to all of our
2079 * locally connected clients on the particular channel. Router
2080 * never receives this channel and thus is ignored.
2082 SILC_LOG_DEBUG(("Channel Key packet"));
2083 if (packet->flags & SILC_PACKET_FLAG_LIST)
2085 silc_server_channel_key(server, sock, packet);
2091 case SILC_PACKET_COMMAND:
2093 * Recived command. Processes the command request and allocates the
2094 * command context and calls the command.
2096 SILC_LOG_DEBUG(("Command packet"));
2097 if (packet->flags & SILC_PACKET_FLAG_LIST)
2099 silc_server_command_process(server, sock, packet);
2102 case SILC_PACKET_COMMAND_REPLY:
2104 * Received command reply packet. Received command reply to command. It
2105 * may be reply to command sent by us or reply to command sent by client
2106 * that we've routed further.
2108 SILC_LOG_DEBUG(("Command Reply packet"));
2109 if (packet->flags & SILC_PACKET_FLAG_LIST)
2111 silc_server_command_reply(server, sock, packet);
2115 * Private Message packets
2117 case SILC_PACKET_PRIVATE_MESSAGE:
2119 * Received private message packet. The packet is coming from either
2122 SILC_LOG_DEBUG(("Private Message packet"));
2123 if (packet->flags & SILC_PACKET_FLAG_LIST)
2125 idata->last_receive = time(NULL);
2126 silc_server_private_message(server, sock, packet);
2129 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2131 * Private message key packet.
2133 if (packet->flags & SILC_PACKET_FLAG_LIST)
2135 silc_server_private_message_key(server, sock, packet);
2139 * Key Exchange protocol packets
2141 case SILC_PACKET_KEY_EXCHANGE:
2142 SILC_LOG_DEBUG(("KE packet"));
2143 if (packet->flags & SILC_PACKET_FLAG_LIST)
2146 if (sock->protocol && sock->protocol->protocol &&
2147 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2148 SilcServerKEInternalContext *proto_ctx =
2149 (SilcServerKEInternalContext *)sock->protocol->context;
2151 proto_ctx->packet = silc_packet_context_dup(packet);
2153 /* Let the protocol handle the packet */
2154 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2156 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2157 "protocol active, packet dropped."));
2161 case SILC_PACKET_KEY_EXCHANGE_1:
2162 SILC_LOG_DEBUG(("KE 1 packet"));
2163 if (packet->flags & SILC_PACKET_FLAG_LIST)
2166 if (sock->protocol && sock->protocol->protocol &&
2167 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2168 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2170 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2171 SilcServerRekeyInternalContext *proto_ctx =
2172 (SilcServerRekeyInternalContext *)sock->protocol->context;
2174 if (proto_ctx->packet)
2175 silc_packet_context_free(proto_ctx->packet);
2177 proto_ctx->packet = silc_packet_context_dup(packet);
2179 /* Let the protocol handle the packet */
2180 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2182 SilcServerKEInternalContext *proto_ctx =
2183 (SilcServerKEInternalContext *)sock->protocol->context;
2185 if (proto_ctx->packet)
2186 silc_packet_context_free(proto_ctx->packet);
2188 proto_ctx->packet = silc_packet_context_dup(packet);
2189 proto_ctx->dest_id_type = packet->src_id_type;
2190 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2191 packet->src_id_type);
2192 if (!proto_ctx->dest_id)
2195 /* Let the protocol handle the packet */
2196 silc_protocol_execute(sock->protocol, server->schedule,
2200 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2201 "protocol active, packet dropped."));
2205 case SILC_PACKET_KEY_EXCHANGE_2:
2206 SILC_LOG_DEBUG(("KE 2 packet"));
2207 if (packet->flags & SILC_PACKET_FLAG_LIST)
2210 if (sock->protocol && sock->protocol->protocol &&
2211 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2212 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2214 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2215 SilcServerRekeyInternalContext *proto_ctx =
2216 (SilcServerRekeyInternalContext *)sock->protocol->context;
2218 if (proto_ctx->packet)
2219 silc_packet_context_free(proto_ctx->packet);
2221 proto_ctx->packet = silc_packet_context_dup(packet);
2223 /* Let the protocol handle the packet */
2224 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2226 SilcServerKEInternalContext *proto_ctx =
2227 (SilcServerKEInternalContext *)sock->protocol->context;
2229 if (proto_ctx->packet)
2230 silc_packet_context_free(proto_ctx->packet);
2232 proto_ctx->packet = silc_packet_context_dup(packet);
2233 proto_ctx->dest_id_type = packet->src_id_type;
2234 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2235 packet->src_id_type);
2236 if (!proto_ctx->dest_id)
2239 /* Let the protocol handle the packet */
2240 silc_protocol_execute(sock->protocol, server->schedule,
2244 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2245 "protocol active, packet dropped."));
2249 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2251 * Connection authentication request packet. When we receive this packet
2252 * we will send to the other end information about our mandatory
2253 * authentication method for the connection. This packet maybe received
2256 SILC_LOG_DEBUG(("Connection authentication request packet"));
2257 if (packet->flags & SILC_PACKET_FLAG_LIST)
2259 silc_server_connection_auth_request(server, sock, packet);
2263 * Connection Authentication protocol packets
2265 case SILC_PACKET_CONNECTION_AUTH:
2266 /* Start of the authentication protocol. We receive here the
2267 authentication data and will verify it. */
2268 SILC_LOG_DEBUG(("Connection auth packet"));
2269 if (packet->flags & SILC_PACKET_FLAG_LIST)
2272 if (sock->protocol && sock->protocol->protocol->type
2273 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2275 SilcServerConnAuthInternalContext *proto_ctx =
2276 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2278 proto_ctx->packet = silc_packet_context_dup(packet);
2280 /* Let the protocol handle the packet */
2281 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2283 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2284 "protocol active, packet dropped."));
2288 case SILC_PACKET_NEW_ID:
2290 * Received New ID packet. This includes some new ID that has been
2291 * created. It may be for client, server or channel. This is the way
2292 * to distribute information about new registered entities in the
2295 SILC_LOG_DEBUG(("New ID packet"));
2296 if (packet->flags & SILC_PACKET_FLAG_LIST)
2297 silc_server_new_id_list(server, sock, packet);
2299 silc_server_new_id(server, sock, packet);
2302 case SILC_PACKET_NEW_CLIENT:
2304 * Received new client packet. This includes client information that
2305 * we will use to create initial client ID. After creating new
2306 * ID we will send it to the client.
2308 SILC_LOG_DEBUG(("New Client packet"));
2309 if (packet->flags & SILC_PACKET_FLAG_LIST)
2311 silc_server_new_client(server, sock, packet);
2314 case SILC_PACKET_NEW_SERVER:
2316 * Received new server packet. This includes Server ID and some other
2317 * information that we may save. This is received after server has
2320 SILC_LOG_DEBUG(("New Server packet"));
2321 if (packet->flags & SILC_PACKET_FLAG_LIST)
2323 silc_server_new_server(server, sock, packet);
2326 case SILC_PACKET_NEW_CHANNEL:
2328 * Received new channel packet. Information about new channel in the
2329 * network are distributed using this packet.
2331 SILC_LOG_DEBUG(("New Channel packet"));
2332 if (packet->flags & SILC_PACKET_FLAG_LIST)
2333 silc_server_new_channel_list(server, sock, packet);
2335 silc_server_new_channel(server, sock, packet);
2338 case SILC_PACKET_HEARTBEAT:
2340 * Received heartbeat.
2342 SILC_LOG_DEBUG(("Heartbeat packet"));
2343 if (packet->flags & SILC_PACKET_FLAG_LIST)
2347 case SILC_PACKET_KEY_AGREEMENT:
2349 * Received heartbeat.
2351 SILC_LOG_DEBUG(("Key agreement packet"));
2352 if (packet->flags & SILC_PACKET_FLAG_LIST)
2354 silc_server_key_agreement(server, sock, packet);
2357 case SILC_PACKET_REKEY:
2359 * Received re-key packet. The sender wants to regenerate the session
2362 SILC_LOG_DEBUG(("Re-key packet"));
2363 if (packet->flags & SILC_PACKET_FLAG_LIST)
2365 silc_server_rekey(server, sock, packet);
2368 case SILC_PACKET_REKEY_DONE:
2370 * The re-key is done.
2372 SILC_LOG_DEBUG(("Re-key done packet"));
2373 if (packet->flags & SILC_PACKET_FLAG_LIST)
2376 if (sock->protocol && sock->protocol->protocol &&
2377 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2379 SilcServerRekeyInternalContext *proto_ctx =
2380 (SilcServerRekeyInternalContext *)sock->protocol->context;
2382 if (proto_ctx->packet)
2383 silc_packet_context_free(proto_ctx->packet);
2385 proto_ctx->packet = silc_packet_context_dup(packet);
2387 /* Let the protocol handle the packet */
2388 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2390 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2391 "protocol active, packet dropped."));
2395 case SILC_PACKET_FTP:
2397 SILC_LOG_DEBUG(("FTP packet"));
2398 if (packet->flags & SILC_PACKET_FLAG_LIST)
2400 silc_server_ftp(server, sock, packet);
2403 case SILC_PACKET_RESUME_ROUTER:
2404 /* Resume router packet received. This packet is received for backup
2405 router resuming protocol. */
2406 SILC_LOG_DEBUG(("Resume router packet"));
2407 if (packet->flags & SILC_PACKET_FLAG_LIST)
2409 silc_server_backup_resume_router(server, sock, packet);
2413 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2419 /* Creates connection to a remote router. */
2421 void silc_server_create_connection(SilcServer server,
2422 const char *remote_host, SilcUInt32 port)
2424 SilcServerConnection sconn;
2426 /* Allocate connection object for hold connection specific stuff. */
2427 sconn = silc_calloc(1, sizeof(*sconn));
2428 sconn->server = server;
2429 sconn->remote_host = strdup(remote_host);
2430 sconn->remote_port = port;
2431 sconn->no_reconnect = TRUE;
2433 silc_schedule_task_add(server->schedule, 0,
2434 silc_server_connect_router,
2435 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2436 SILC_TASK_PRI_NORMAL);
2439 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2441 silc_socket_free((SilcSocketConnection)context);
2444 /* Closes connection to socket connection */
2446 void silc_server_close_connection(SilcServer server,
2447 SilcSocketConnection sock)
2449 if (!server->sockets[sock->sock])
2452 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2454 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2455 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2456 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2459 /* We won't listen for this connection anymore */
2460 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2462 /* Unregister all tasks */
2463 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2465 /* Close the actual connection */
2466 silc_net_close_connection(sock->sock);
2467 server->sockets[sock->sock] = NULL;
2469 /* If sock->user_data is NULL then we'll check for active protocols
2470 here since the silc_server_free_sock_user_data has not been called
2471 for this connection. */
2472 if (!sock->user_data) {
2473 /* If any protocol is active cancel its execution. It will call
2474 the final callback which will finalize the disconnection. */
2475 if (sock->protocol) {
2476 silc_protocol_cancel(sock->protocol, server->schedule);
2477 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2478 silc_protocol_execute_final(sock->protocol, server->schedule);
2479 sock->protocol = NULL;
2484 silc_schedule_task_add(server->schedule, 0,
2485 silc_server_close_connection_final,
2486 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2487 SILC_TASK_PRI_NORMAL);
2490 /* Sends disconnect message to remote connection and disconnects the
2493 void silc_server_disconnect_remote(SilcServer server,
2494 SilcSocketConnection sock,
2495 const char *fmt, ...)
2498 unsigned char buf[4096];
2503 memset(buf, 0, sizeof(buf));
2505 vsprintf(buf, fmt, ap);
2508 SILC_LOG_DEBUG(("Disconnecting remote host"));
2510 /* Notify remote end that the conversation is over. The notify message
2511 is tried to be sent immediately. */
2512 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2513 buf, strlen(buf), TRUE);
2514 silc_server_packet_queue_purge(server, sock);
2516 /* Mark the connection to be disconnected */
2517 SILC_SET_DISCONNECTED(sock);
2518 silc_server_close_connection(server, sock);
2523 SilcClientEntry client;
2524 } *FreeClientInternal;
2526 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2528 FreeClientInternal i = (FreeClientInternal)context;
2530 silc_idlist_del_data(i->client);
2531 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2535 /* Frees client data and notifies about client's signoff. */
2537 void silc_server_free_client_data(SilcServer server,
2538 SilcSocketConnection sock,
2539 SilcClientEntry client,
2541 const char *signoff)
2543 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2545 /* If there is pending outgoing data for the client then purge it
2546 to the network before removing the client entry. */
2547 silc_server_packet_queue_purge(server, sock);
2552 /* Send SIGNOFF notify to routers. */
2553 if (notify && !server->standalone && server->router)
2554 silc_server_send_notify_signoff(server, server->router->connection,
2555 server->server_type == SILC_SERVER ?
2556 FALSE : TRUE, client->id, signoff);
2558 /* Remove client from all channels */
2560 silc_server_remove_from_channels(server, NULL, client,
2561 TRUE, (char *)signoff, TRUE);
2563 silc_server_remove_from_channels(server, NULL, client,
2564 FALSE, NULL, FALSE);
2566 /* Update statistics */
2567 server->stat.my_clients--;
2568 server->stat.clients--;
2569 if (server->server_type == SILC_ROUTER)
2570 server->stat.cell_clients--;
2571 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2572 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2574 /* We will not delete the client entry right away. We will take it
2575 into history (for WHOWAS command) for 5 minutes */
2578 silc_schedule_task_add(server->schedule, 0,
2579 silc_server_free_client_data_timeout,
2581 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2582 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2583 client->router = NULL;
2584 client->connection = NULL;
2588 /* Frees user_data pointer from socket connection object. This also sends
2589 appropriate notify packets to the network to inform about leaving
2592 void silc_server_free_sock_user_data(SilcServer server,
2593 SilcSocketConnection sock,
2594 const char *signoff_message)
2596 SILC_LOG_DEBUG(("Start"));
2598 switch (sock->type) {
2599 case SILC_SOCKET_TYPE_CLIENT:
2601 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2602 silc_server_free_client_data(server, sock, user_data, TRUE,
2606 case SILC_SOCKET_TYPE_SERVER:
2607 case SILC_SOCKET_TYPE_ROUTER:
2609 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2610 SilcServerEntry backup_router = NULL;
2613 backup_router = silc_server_backup_get(server, user_data->id);
2615 /* If this was our primary router connection then we're lost to
2616 the outside world. */
2617 if (server->router == user_data) {
2618 /* Check whether we have a backup router connection */
2619 if (!backup_router || backup_router == user_data) {
2620 silc_schedule_task_add(server->schedule, 0,
2621 silc_server_connect_to_router,
2624 SILC_TASK_PRI_NORMAL);
2626 server->id_entry->router = NULL;
2627 server->router = NULL;
2628 server->standalone = TRUE;
2629 backup_router = NULL;
2631 SILC_LOG_INFO(("New primary router is backup router %s",
2632 backup_router->server_name));
2633 SILC_LOG_DEBUG(("New primary router is backup router %s",
2634 backup_router->server_name));
2635 server->id_entry->router = backup_router;
2636 server->router = backup_router;
2637 server->router_connect = time(0);
2638 server->backup_primary = TRUE;
2639 if (server->server_type == SILC_BACKUP_ROUTER) {
2640 server->server_type = SILC_ROUTER;
2642 /* We'll need to constantly try to reconnect to the primary
2643 router so that we'll see when it comes back online. */
2644 silc_server_backup_reconnect(server, sock->ip, sock->port,
2645 silc_server_backup_connected,
2649 /* Mark this connection as replaced */
2650 silc_server_backup_replaced_add(server, user_data->id,
2653 } else if (backup_router) {
2654 SILC_LOG_INFO(("Enabling the use of backup router %s",
2655 backup_router->server_name));
2656 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2657 backup_router->server_name));
2659 /* Mark this connection as replaced */
2660 silc_server_backup_replaced_add(server, user_data->id,
2664 if (!backup_router) {
2665 /* Free all client entries that this server owns as they will
2666 become invalid now as well. */
2668 silc_server_remove_clients_by_server(server, user_data, TRUE);
2669 if (server->server_type == SILC_SERVER)
2670 silc_server_remove_channels_by_server(server, user_data);
2672 /* Update the client entries of this server to the new backup
2673 router. This also removes the clients that *really* was owned
2674 by the primary router and went down with the router. */
2675 silc_server_update_clients_by_server(server, user_data, backup_router,
2677 silc_server_update_servers_by_server(server, user_data, backup_router);
2678 if (server->server_type == SILC_SERVER)
2679 silc_server_update_channels_by_server(server, user_data,
2683 /* Free the server entry */
2684 silc_server_backup_del(server, user_data);
2685 silc_server_backup_replaced_del(server, user_data);
2686 silc_idlist_del_data(user_data);
2687 if (!silc_idlist_del_server(server->local_list, user_data))
2688 silc_idlist_del_server(server->global_list, user_data);
2689 server->stat.my_servers--;
2690 server->stat.servers--;
2691 if (server->server_type == SILC_ROUTER)
2692 server->stat.cell_servers--;
2694 if (backup_router) {
2695 /* Announce all of our stuff that was created about 5 minutes ago.
2696 The backup router knows all the other stuff already. */
2697 if (server->server_type == SILC_ROUTER)
2698 silc_server_announce_servers(server, FALSE, time(0) - 300,
2699 backup_router->connection);
2701 /* Announce our clients and channels to the router */
2702 silc_server_announce_clients(server, time(0) - 300,
2703 backup_router->connection);
2704 silc_server_announce_channels(server, time(0) - 300,
2705 backup_router->connection);
2711 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2713 silc_idlist_del_data(user_data);
2714 silc_free(user_data);
2719 /* If any protocol is active cancel its execution */
2720 if (sock->protocol) {
2721 silc_protocol_cancel(sock->protocol, server->schedule);
2722 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2723 silc_protocol_execute_final(sock->protocol, server->schedule);
2724 sock->protocol = NULL;
2727 sock->user_data = NULL;
2730 /* Removes client from all channels it has joined. This is used when client
2731 connection is disconnected. If the client on a channel is last, the
2732 channel is removed as well. This sends the SIGNOFF notify types. */
2734 void silc_server_remove_from_channels(SilcServer server,
2735 SilcSocketConnection sock,
2736 SilcClientEntry client,
2738 char *signoff_message,
2741 SilcChannelEntry channel;
2742 SilcChannelClientEntry chl;
2743 SilcHashTableList htl;
2746 SILC_LOG_DEBUG(("Start"));
2748 if (!client || !client->id)
2751 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2753 /* Remove the client from all channels. The client is removed from
2754 the channels' user list. */
2755 silc_hash_table_list(client->channels, &htl);
2756 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2757 channel = chl->channel;
2759 /* Remove channel from client's channel list */
2760 silc_hash_table_del(client->channels, channel);
2762 /* Remove channel if there is no users anymore */
2763 if (server->server_type == SILC_ROUTER &&
2764 silc_hash_table_count(channel->user_list) < 2) {
2766 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2767 if (silc_idlist_del_channel(server->local_list, channel))
2768 server->stat.my_channels--;
2770 silc_idlist_del_channel(server->global_list, channel);
2774 /* Remove client from channel's client list */
2775 silc_hash_table_del(channel->user_list, chl->client);
2776 channel->user_count--;
2778 /* If there is no global users on the channel anymore mark the channel
2779 as local channel. Do not check if the removed client is local client. */
2780 if (server->server_type != SILC_ROUTER && channel->global_users &&
2781 chl->client->router && !silc_server_channel_has_global(channel))
2782 channel->global_users = FALSE;
2785 server->stat.my_chanclients--;
2787 /* If there is not at least one local user on the channel then we don't
2788 need the channel entry anymore, we can remove it safely. */
2789 if (server->server_type != SILC_ROUTER &&
2790 !silc_server_channel_has_local(channel)) {
2791 /* Notify about leaving client if this channel has global users. */
2792 if (notify && channel->global_users)
2793 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2794 SILC_NOTIFY_TYPE_SIGNOFF,
2795 signoff_message ? 2 : 1,
2796 clidp->data, clidp->len,
2797 signoff_message, signoff_message ?
2798 strlen(signoff_message) : 0);
2801 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2803 if (channel->founder_key) {
2804 /* The founder auth data exists, do not remove the channel entry */
2805 SilcChannelClientEntry chl2;
2806 SilcHashTableList htl2;
2808 channel->disabled = TRUE;
2810 silc_hash_table_list(channel->user_list, &htl2);
2811 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2812 silc_hash_table_del(chl2->client->channels, channel);
2813 silc_hash_table_del(channel->user_list, chl2->client);
2814 channel->user_count--;
2817 silc_hash_table_list_reset(&htl2);
2821 /* Remove the channel entry */
2822 if (silc_idlist_del_channel(server->local_list, channel))
2823 server->stat.my_channels--;
2825 silc_idlist_del_channel(server->global_list, channel);
2829 /* Send notify to channel about client leaving SILC and thus
2830 the entire channel. */
2832 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2833 SILC_NOTIFY_TYPE_SIGNOFF,
2834 signoff_message ? 2 : 1,
2835 clidp->data, clidp->len,
2836 signoff_message, signoff_message ?
2837 strlen(signoff_message) : 0);
2839 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2840 /* Re-generate channel key */
2841 if (!silc_server_create_channel_key(server, channel, 0))
2844 /* Send the channel key to the channel. The key of course is not sent
2845 to the client who was removed from the channel. */
2846 silc_server_send_channel_key(server, client->connection, channel,
2847 server->server_type == SILC_ROUTER ?
2848 FALSE : !server->standalone);
2853 silc_hash_table_list_reset(&htl);
2854 silc_buffer_free(clidp);
2857 /* Removes client from one channel. This is used for example when client
2858 calls LEAVE command to remove itself from the channel. Returns TRUE
2859 if channel still exists and FALSE if the channel is removed when
2860 last client leaves the channel. If `notify' is FALSE notify messages
2863 int silc_server_remove_from_one_channel(SilcServer server,
2864 SilcSocketConnection sock,
2865 SilcChannelEntry channel,
2866 SilcClientEntry client,
2869 SilcChannelClientEntry chl;
2872 SILC_LOG_DEBUG(("Start"));
2874 /* Get the entry to the channel, if this client is not on the channel
2876 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2879 /* Remove the client from the channel. The client is removed from
2880 the channel's user list. */
2882 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2884 /* Remove channel from client's channel list */
2885 silc_hash_table_del(client->channels, chl->channel);
2887 /* Remove channel if there is no users anymore */
2888 if (server->server_type == SILC_ROUTER &&
2889 silc_hash_table_count(channel->user_list) < 2) {
2891 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2892 if (silc_idlist_del_channel(server->local_list, channel))
2893 server->stat.my_channels--;
2895 silc_idlist_del_channel(server->global_list, channel);
2896 silc_buffer_free(clidp);
2900 /* Remove client from channel's client list */
2901 silc_hash_table_del(channel->user_list, chl->client);
2902 channel->user_count--;
2904 /* If there is no global users on the channel anymore mark the channel
2905 as local channel. Do not check if the client is local client. */
2906 if (server->server_type != SILC_ROUTER && channel->global_users &&
2907 chl->client->router && !silc_server_channel_has_global(channel))
2908 channel->global_users = FALSE;
2911 server->stat.my_chanclients--;
2913 /* If there is not at least one local user on the channel then we don't
2914 need the channel entry anymore, we can remove it safely. */
2915 if (server->server_type != SILC_ROUTER &&
2916 !silc_server_channel_has_local(channel)) {
2917 /* Notify about leaving client if this channel has global users. */
2918 if (notify && channel->global_users)
2919 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2920 SILC_NOTIFY_TYPE_LEAVE, 1,
2921 clidp->data, clidp->len);
2923 silc_buffer_free(clidp);
2926 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2928 if (channel->founder_key) {
2929 /* The founder auth data exists, do not remove the channel entry */
2930 SilcChannelClientEntry chl2;
2931 SilcHashTableList htl2;
2933 channel->disabled = TRUE;
2935 silc_hash_table_list(channel->user_list, &htl2);
2936 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2937 silc_hash_table_del(chl2->client->channels, channel);
2938 silc_hash_table_del(channel->user_list, chl2->client);
2939 channel->user_count--;
2942 silc_hash_table_list_reset(&htl2);
2946 /* Remove the channel entry */
2947 if (silc_idlist_del_channel(server->local_list, channel))
2948 server->stat.my_channels--;
2950 silc_idlist_del_channel(server->global_list, channel);
2954 /* Send notify to channel about client leaving the channel */
2956 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2957 SILC_NOTIFY_TYPE_LEAVE, 1,
2958 clidp->data, clidp->len);
2960 silc_buffer_free(clidp);
2964 /* Timeout callback. This is called if connection is idle or for some
2965 other reason is not responding within some period of time. This
2966 disconnects the remote end. */
2968 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2970 SilcServer server = (SilcServer)context;
2971 SilcSocketConnection sock = server->sockets[fd];
2973 SILC_LOG_DEBUG(("Start"));
2978 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2979 sock->hostname, sock->ip));
2981 /* If we have protocol active we must assure that we call the protocol's
2982 final callback so that all the memory is freed. */
2983 if (sock->protocol) {
2984 silc_protocol_cancel(sock->protocol, server->schedule);
2985 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2986 silc_protocol_execute_final(sock->protocol, server->schedule);
2987 sock->protocol = NULL;
2991 if (sock->user_data)
2992 silc_server_free_sock_user_data(server, sock, NULL);
2994 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2995 "Connection timeout");
2998 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2999 function may be used only by router. In real SILC network all channels
3000 are created by routers thus this function is never used by normal
3003 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3004 SilcServerID *router_id,
3010 SilcChannelID *channel_id;
3011 SilcChannelEntry entry;
3015 SILC_LOG_DEBUG(("Creating new channel"));
3018 cipher = SILC_DEFAULT_CIPHER;
3020 hmac = SILC_DEFAULT_HMAC;
3022 /* Allocate cipher */
3023 if (!silc_cipher_alloc(cipher, &key))
3027 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3028 silc_cipher_free(key);
3032 channel_name = strdup(channel_name);
3034 /* Create the channel ID */
3035 if (!silc_id_create_channel_id(server, router_id, server->rng,
3037 silc_free(channel_name);
3038 silc_cipher_free(key);
3039 silc_hmac_free(newhmac);
3043 /* Create the channel */
3044 entry = silc_idlist_add_channel(server->local_list, channel_name,
3045 SILC_CHANNEL_MODE_NONE, channel_id,
3046 NULL, key, newhmac, 0);
3048 silc_free(channel_name);
3049 silc_cipher_free(key);
3050 silc_hmac_free(newhmac);
3051 silc_free(channel_id);
3055 entry->cipher = strdup(cipher);
3056 entry->hmac_name = strdup(hmac);
3058 /* Now create the actual key material */
3059 if (!silc_server_create_channel_key(server, entry,
3060 silc_cipher_get_key_len(key) / 8)) {
3061 silc_idlist_del_channel(server->local_list, entry);
3065 /* Notify other routers about the new channel. We send the packet
3066 to our primary route. */
3067 if (broadcast && server->standalone == FALSE)
3068 silc_server_send_new_channel(server, server->router->connection, TRUE,
3069 channel_name, entry->id,
3070 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3073 server->stat.my_channels++;
3078 /* Same as above but creates the channel with Channel ID `channel_id. */
3081 silc_server_create_new_channel_with_id(SilcServer server,
3085 SilcChannelID *channel_id,
3088 SilcChannelEntry entry;
3092 SILC_LOG_DEBUG(("Creating new channel"));
3095 cipher = SILC_DEFAULT_CIPHER;
3097 hmac = SILC_DEFAULT_HMAC;
3099 /* Allocate cipher */
3100 if (!silc_cipher_alloc(cipher, &key))
3104 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3105 silc_cipher_free(key);
3109 channel_name = strdup(channel_name);
3111 /* Create the channel */
3112 entry = silc_idlist_add_channel(server->local_list, channel_name,
3113 SILC_CHANNEL_MODE_NONE, channel_id,
3114 NULL, key, newhmac, 0);
3116 silc_cipher_free(key);
3117 silc_hmac_free(newhmac);
3118 silc_free(channel_name);
3122 /* Now create the actual key material */
3123 if (!silc_server_create_channel_key(server, entry,
3124 silc_cipher_get_key_len(key) / 8)) {
3125 silc_idlist_del_channel(server->local_list, entry);
3129 /* Notify other routers about the new channel. We send the packet
3130 to our primary route. */
3131 if (broadcast && server->standalone == FALSE)
3132 silc_server_send_new_channel(server, server->router->connection, TRUE,
3133 channel_name, entry->id,
3134 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3137 server->stat.my_channels++;
3142 /* Channel's key re-key timeout callback. */
3144 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3146 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3147 SilcServer server = (SilcServer)rekey->context;
3151 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3154 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3157 /* Generates new channel key. This is used to create the initial channel key
3158 but also to re-generate new key for channel. If `key_len' is provided
3159 it is the bytes of the key length. */
3161 bool silc_server_create_channel_key(SilcServer server,
3162 SilcChannelEntry channel,
3166 unsigned char channel_key[32], hash[32];
3169 SILC_LOG_DEBUG(("Generating channel key"));
3171 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3172 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3176 if (!channel->channel_key)
3177 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3178 channel->channel_key = NULL;
3184 else if (channel->key_len)
3185 len = channel->key_len / 8;
3187 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3189 /* Create channel key */
3190 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3193 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3195 /* Remove old key if exists */
3197 memset(channel->key, 0, channel->key_len / 8);
3198 silc_free(channel->key);
3202 channel->key_len = len * 8;
3203 channel->key = silc_memdup(channel_key, len);
3204 memset(channel_key, 0, sizeof(channel_key));
3206 /* Generate HMAC key from the channel key data and set it */
3208 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3209 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3210 silc_hmac_set_key(channel->hmac, hash,
3211 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3212 memset(hash, 0, sizeof(hash));
3214 if (server->server_type == SILC_ROUTER) {
3215 if (!channel->rekey)
3216 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3217 channel->rekey->context = (void *)server;
3218 channel->rekey->channel = channel;
3219 channel->rekey->key_len = key_len;
3220 if (channel->rekey->task)
3221 silc_schedule_task_del(server->schedule, channel->rekey->task);
3223 channel->rekey->task =
3224 silc_schedule_task_add(server->schedule, 0,
3225 silc_server_channel_key_rekey,
3226 (void *)channel->rekey,
3227 server->config->channel_rekey_secs, 0,
3229 SILC_TASK_PRI_NORMAL);
3235 /* Saves the channel key found in the encoded `key_payload' buffer. This
3236 function is used when we receive Channel Key Payload and also when we're
3237 processing JOIN command reply. Returns entry to the channel. */
3239 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3240 SilcBuffer key_payload,
3241 SilcChannelEntry channel)
3243 SilcChannelKeyPayload payload = NULL;
3244 SilcChannelID *id = NULL;
3245 unsigned char *tmp, hash[32];
3249 SILC_LOG_DEBUG(("Start"));
3251 /* Decode channel key payload */
3252 payload = silc_channel_key_payload_parse(key_payload->data,
3255 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3260 /* Get the channel entry */
3263 /* Get channel ID */
3264 tmp = silc_channel_key_get_id(payload, &tmp_len);
3265 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3271 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3273 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3275 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3276 silc_id_render(id, SILC_ID_CHANNEL)));
3282 tmp = silc_channel_key_get_key(payload, &tmp_len);
3288 cipher = silc_channel_key_get_cipher(payload, NULL);
3294 /* Remove old key if exists */
3296 memset(channel->key, 0, channel->key_len / 8);
3297 silc_free(channel->key);
3298 silc_cipher_free(channel->channel_key);
3301 /* Create new cipher */
3302 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3303 channel->channel_key = NULL;
3308 if (channel->cipher)
3309 silc_free(channel->cipher);
3310 channel->cipher = strdup(cipher);
3313 channel->key_len = tmp_len * 8;
3314 channel->key = silc_memdup(tmp, tmp_len);
3315 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3317 /* Generate HMAC key from the channel key data and set it */
3319 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3320 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3321 silc_hmac_set_key(channel->hmac, hash,
3322 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3324 memset(hash, 0, sizeof(hash));
3325 memset(tmp, 0, tmp_len);
3327 if (server->server_type == SILC_ROUTER) {
3328 if (!channel->rekey)
3329 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3330 channel->rekey->context = (void *)server;
3331 channel->rekey->channel = channel;
3332 if (channel->rekey->task)
3333 silc_schedule_task_del(server->schedule, channel->rekey->task);
3335 channel->rekey->task =
3336 silc_schedule_task_add(server->schedule, 0,
3337 silc_server_channel_key_rekey,
3338 (void *)channel->rekey,
3339 server->config->channel_rekey_secs, 0,
3341 SILC_TASK_PRI_NORMAL);
3347 silc_channel_key_payload_free(payload);
3352 /* Heartbeat callback. This function is set as argument for the
3353 silc_socket_set_heartbeat function. The library will call this function
3354 at the set time interval. */
3356 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3359 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3361 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3363 /* Send the heartbeat */
3364 silc_server_send_heartbeat(hb->server, sock);
3367 /* Returns assembled of all servers in the given ID list. The packet's
3368 form is dictated by the New ID payload. */
3370 static void silc_server_announce_get_servers(SilcServer server,
3371 SilcServerEntry remote,
3373 SilcBuffer *servers,
3374 unsigned long creation_time)
3376 SilcIDCacheList list;
3377 SilcIDCacheEntry id_cache;
3378 SilcServerEntry entry;
3381 /* Go through all clients in the list */
3382 if (silc_idcache_get_all(id_list->servers, &list)) {
3383 if (silc_idcache_list_first(list, &id_cache)) {
3385 entry = (SilcServerEntry)id_cache->context;
3387 /* Do not announce the one we've sending our announcements and
3388 do not announce ourself. Also check the creation time if it's
3390 if ((entry == remote) || (entry == server->id_entry) ||
3391 (creation_time && entry->data.created < creation_time)) {
3392 if (!silc_idcache_list_next(list, &id_cache))
3397 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3399 *servers = silc_buffer_realloc(*servers,
3401 (*servers)->truelen + idp->len :
3403 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3404 silc_buffer_put(*servers, idp->data, idp->len);
3405 silc_buffer_pull(*servers, idp->len);
3406 silc_buffer_free(idp);
3408 if (!silc_idcache_list_next(list, &id_cache))
3413 silc_idcache_list_free(list);
3418 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3424 p = silc_notify_payload_encode(notify, argc, ap);
3430 /* This function is used by router to announce existing servers to our
3431 primary router when we've connected to it. If `creation_time' is non-zero
3432 then only the servers that has been created after the `creation_time'
3433 will be announced. */
3435 void silc_server_announce_servers(SilcServer server, bool global,
3436 unsigned long creation_time,
3437 SilcSocketConnection remote)
3439 SilcBuffer servers = NULL;
3441 SILC_LOG_DEBUG(("Announcing servers"));
3443 /* Get servers in local list */
3444 silc_server_announce_get_servers(server, remote->user_data,
3445 server->local_list, &servers,
3449 /* Get servers in global list */
3450 silc_server_announce_get_servers(server, remote->user_data,
3451 server->global_list, &servers,
3455 silc_buffer_push(servers, servers->data - servers->head);
3456 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3458 /* Send the packet */
3459 silc_server_packet_send(server, remote,
3460 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3461 servers->data, servers->len, TRUE);
3463 silc_buffer_free(servers);
3467 /* Returns assembled packet of all clients in the given ID list. The
3468 packet's form is dictated by the New ID Payload. */
3470 static void silc_server_announce_get_clients(SilcServer server,
3472 SilcBuffer *clients,
3474 unsigned long creation_time)
3476 SilcIDCacheList list;
3477 SilcIDCacheEntry id_cache;
3478 SilcClientEntry client;
3481 unsigned char mode[4];
3483 /* Go through all clients in the list */
3484 if (silc_idcache_get_all(id_list->clients, &list)) {
3485 if (silc_idcache_list_first(list, &id_cache)) {
3487 client = (SilcClientEntry)id_cache->context;
3489 if (creation_time && client->data.created < creation_time) {
3490 if (!silc_idcache_list_next(list, &id_cache))
3495 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3497 *clients = silc_buffer_realloc(*clients,
3499 (*clients)->truelen + idp->len :
3501 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3502 silc_buffer_put(*clients, idp->data, idp->len);
3503 silc_buffer_pull(*clients, idp->len);
3505 SILC_PUT32_MSB(client->mode, mode);
3506 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3507 2, idp->data, idp->len,
3509 *umodes = silc_buffer_realloc(*umodes,
3511 (*umodes)->truelen + tmp->len :
3513 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3514 silc_buffer_put(*umodes, tmp->data, tmp->len);
3515 silc_buffer_pull(*umodes, tmp->len);
3516 silc_buffer_free(tmp);
3518 silc_buffer_free(idp);
3520 if (!silc_idcache_list_next(list, &id_cache))
3525 silc_idcache_list_free(list);
3529 /* This function is used to announce our existing clients to our router
3530 when we've connected to it. If `creation_time' is non-zero then only
3531 the clients that has been created after the `creation_time' will be
3534 void silc_server_announce_clients(SilcServer server,
3535 unsigned long creation_time,
3536 SilcSocketConnection remote)
3538 SilcBuffer clients = NULL;
3539 SilcBuffer umodes = NULL;
3541 SILC_LOG_DEBUG(("Announcing clients"));
3543 /* Get clients in local list */
3544 silc_server_announce_get_clients(server, server->local_list,
3545 &clients, &umodes, creation_time);
3547 /* As router we announce our global list as well */
3548 if (server->server_type == SILC_ROUTER)
3549 silc_server_announce_get_clients(server, server->global_list,
3550 &clients, &umodes, creation_time);
3553 silc_buffer_push(clients, clients->data - clients->head);
3554 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3556 /* Send the packet */
3557 silc_server_packet_send(server, remote,
3558 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3559 clients->data, clients->len, TRUE);
3561 silc_buffer_free(clients);
3565 silc_buffer_push(umodes, umodes->data - umodes->head);
3566 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3568 /* Send the packet */
3569 silc_server_packet_send(server, remote,
3570 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3571 umodes->data, umodes->len, TRUE);
3573 silc_buffer_free(umodes);
3577 /* Returns channel's topic for announcing it */
3579 void silc_server_announce_get_channel_topic(SilcServer server,
3580 SilcChannelEntry channel,
3585 if (channel->topic) {
3586 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3587 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3588 chidp->data, chidp->len,
3590 strlen(channel->topic));
3591 silc_buffer_free(chidp);
3595 /* Returns assembled packets for channel users of the `channel'. */
3597 void silc_server_announce_get_channel_users(SilcServer server,
3598 SilcChannelEntry channel,
3599 SilcBuffer *channel_users,
3600 SilcBuffer *channel_users_modes)
3602 SilcChannelClientEntry chl;
3603 SilcHashTableList htl;
3604 SilcBuffer chidp, clidp;
3607 unsigned char mode[4];
3609 SILC_LOG_DEBUG(("Start"));
3611 /* Now find all users on the channel */
3612 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3613 silc_hash_table_list(channel->user_list, &htl);
3614 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3615 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3618 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3619 clidp->data, clidp->len,
3620 chidp->data, chidp->len);
3623 silc_buffer_realloc(*channel_users,
3625 (*channel_users)->truelen + len : len));
3626 silc_buffer_pull_tail(*channel_users,
3627 ((*channel_users)->end -
3628 (*channel_users)->data));
3630 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3631 silc_buffer_pull(*channel_users, len);
3632 silc_buffer_free(tmp);
3634 /* CUMODE notify for mode change on the channel */
3635 SILC_PUT32_MSB(chl->mode, mode);
3636 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3637 3, clidp->data, clidp->len,
3639 clidp->data, clidp->len);
3641 *channel_users_modes =
3642 silc_buffer_realloc(*channel_users_modes,
3643 (*channel_users_modes ?
3644 (*channel_users_modes)->truelen + len : len));
3645 silc_buffer_pull_tail(*channel_users_modes,
3646 ((*channel_users_modes)->end -
3647 (*channel_users_modes)->data));
3649 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3650 silc_buffer_pull(*channel_users_modes, len);
3651 silc_buffer_free(tmp);
3653 silc_buffer_free(clidp);
3655 silc_hash_table_list_reset(&htl);
3656 silc_buffer_free(chidp);
3659 /* Returns assembled packets for all channels and users on those channels
3660 from the given ID List. The packets are in the form dictated by the
3661 New Channel and New Channel User payloads. */
3663 void silc_server_announce_get_channels(SilcServer server,
3665 SilcBuffer *channels,
3666 SilcBuffer *channel_users,
3667 SilcBuffer **channel_users_modes,
3668 SilcUInt32 *channel_users_modes_c,
3669 SilcBuffer **channel_topics,
3670 SilcChannelID ***channel_ids,
3671 unsigned long creation_time)
3673 SilcIDCacheList list;
3674 SilcIDCacheEntry id_cache;
3675 SilcChannelEntry channel;
3678 SilcUInt16 name_len;
3680 int i = *channel_users_modes_c;
3683 SILC_LOG_DEBUG(("Start"));
3685 /* Go through all channels in the list */
3686 if (silc_idcache_get_all(id_list->channels, &list)) {
3687 if (silc_idcache_list_first(list, &id_cache)) {
3689 channel = (SilcChannelEntry)id_cache->context;
3691 if (creation_time && channel->created < creation_time)
3696 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3697 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3698 name_len = strlen(channel->channel_name);
3701 len = 4 + name_len + id_len + 4;
3703 silc_buffer_realloc(*channels,
3704 (*channels ? (*channels)->truelen +
3706 silc_buffer_pull_tail(*channels,
3707 ((*channels)->end - (*channels)->data));
3708 silc_buffer_format(*channels,
3709 SILC_STR_UI_SHORT(name_len),
3710 SILC_STR_UI_XNSTRING(channel->channel_name,
3712 SILC_STR_UI_SHORT(id_len),
3713 SILC_STR_UI_XNSTRING(cid, id_len),
3714 SILC_STR_UI_INT(channel->mode),
3716 silc_buffer_pull(*channels, len);
3719 /* Channel user modes */
3720 *channel_users_modes = silc_realloc(*channel_users_modes,
3721 sizeof(**channel_users_modes) *
3723 (*channel_users_modes)[i] = NULL;
3724 *channel_ids = silc_realloc(*channel_ids,
3725 sizeof(**channel_ids) * (i + 1));
3726 (*channel_ids)[i] = NULL;
3727 silc_server_announce_get_channel_users(server, channel,
3729 &(*channel_users_modes)[i]);
3730 (*channel_ids)[i] = channel->id;
3732 /* Channel's topic */
3733 *channel_topics = silc_realloc(*channel_topics,
3734 sizeof(**channel_topics) * (i + 1));
3735 (*channel_topics)[i] = NULL;
3736 silc_server_announce_get_channel_topic(server, channel,
3737 &(*channel_topics)[i]);
3740 if (!silc_idcache_list_next(list, &id_cache))
3744 *channel_users_modes_c += i;
3747 silc_idcache_list_free(list);
3751 /* This function is used to announce our existing channels to our router
3752 when we've connected to it. This also announces the users on the
3753 channels to the router. If the `creation_time' is non-zero only the
3754 channels that was created after the `creation_time' are announced.
3755 Note that the channel users are still announced even if the `creation_time'
3758 void silc_server_announce_channels(SilcServer server,
3759 unsigned long creation_time,
3760 SilcSocketConnection remote)
3762 SilcBuffer channels = NULL, channel_users = NULL;
3763 SilcBuffer *channel_users_modes = NULL;
3764 SilcBuffer *channel_topics = NULL;
3765 SilcUInt32 channel_users_modes_c = 0;
3766 SilcChannelID **channel_ids = NULL;
3768 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3770 /* Get channels and channel users in local list */
3771 silc_server_announce_get_channels(server, server->local_list,
3772 &channels, &channel_users,
3773 &channel_users_modes,
3774 &channel_users_modes_c,
3776 &channel_ids, creation_time);
3778 /* Get channels and channel users in global list */
3779 if (server->server_type != SILC_SERVER)
3780 silc_server_announce_get_channels(server, server->global_list,
3781 &channels, &channel_users,
3782 &channel_users_modes,
3783 &channel_users_modes_c,
3785 &channel_ids, creation_time);
3788 silc_buffer_push(channels, channels->data - channels->head);
3789 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3791 /* Send the packet */
3792 silc_server_packet_send(server, remote,
3793 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3794 channels->data, channels->len,
3797 silc_buffer_free(channels);
3800 if (channel_users) {
3801 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3802 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3803 channel_users->len);
3805 /* Send the packet */
3806 silc_server_packet_send(server, remote,
3807 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3808 channel_users->data, channel_users->len,
3811 silc_buffer_free(channel_users);
3814 if (channel_users_modes) {
3817 for (i = 0; i < channel_users_modes_c; i++) {
3818 if (!channel_users_modes[i])
3820 silc_buffer_push(channel_users_modes[i],
3821 channel_users_modes[i]->data -
3822 channel_users_modes[i]->head);
3823 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3824 channel_users_modes[i]->len);
3825 silc_server_packet_send_dest(server, remote,
3826 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3827 channel_ids[i], SILC_ID_CHANNEL,
3828 channel_users_modes[i]->data,
3829 channel_users_modes[i]->len,
3831 silc_buffer_free(channel_users_modes[i]);
3833 silc_free(channel_users_modes);
3836 if (channel_topics) {
3839 for (i = 0; i < channel_users_modes_c; i++) {
3840 if (!channel_topics[i])
3843 silc_buffer_push(channel_topics[i],
3844 channel_topics[i]->data -
3845 channel_topics[i]->head);
3846 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3847 channel_topics[i]->len);
3848 silc_server_packet_send_dest(server, remote,
3849 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3850 channel_ids[i], SILC_ID_CHANNEL,
3851 channel_topics[i]->data,
3852 channel_topics[i]->len,
3854 silc_buffer_free(channel_topics[i]);
3856 silc_free(channel_topics);
3859 silc_free(channel_ids);
3862 /* Failure timeout callback. If this is called then we will immediately
3863 process the received failure. We always process the failure with timeout
3864 since we do not want to blindly trust to received failure packets.
3865 This won't be called (the timeout is cancelled) if the failure was
3866 bogus (it is bogus if remote does not close the connection after sending
3869 SILC_TASK_CALLBACK(silc_server_failure_callback)
3871 SilcServerFailureContext f = (SilcServerFailureContext)context;
3873 if (f->sock->protocol) {
3874 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3875 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3881 /* Assembles user list and users mode list from the `channel'. */
3883 void silc_server_get_users_on_channel(SilcServer server,
3884 SilcChannelEntry channel,
3885 SilcBuffer *user_list,
3886 SilcBuffer *mode_list,
3887 SilcUInt32 *user_count)
3889 SilcChannelClientEntry chl;
3890 SilcHashTableList htl;
3891 SilcBuffer client_id_list;
3892 SilcBuffer client_mode_list;
3894 SilcUInt32 list_count = 0, len = 0;
3896 silc_hash_table_list(channel->user_list, &htl);
3897 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3898 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3899 silc_hash_table_list_reset(&htl);
3901 client_id_list = silc_buffer_alloc(len);
3903 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3904 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3905 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3907 silc_hash_table_list(channel->user_list, &htl);
3908 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3910 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3911 silc_buffer_put(client_id_list, idp->data, idp->len);
3912 silc_buffer_pull(client_id_list, idp->len);
3913 silc_buffer_free(idp);
3915 /* Client's mode on channel */
3916 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3917 silc_buffer_pull(client_mode_list, 4);
3921 silc_hash_table_list_reset(&htl);
3922 silc_buffer_push(client_id_list,
3923 client_id_list->data - client_id_list->head);
3924 silc_buffer_push(client_mode_list,
3925 client_mode_list->data - client_mode_list->head);
3927 *user_list = client_id_list;
3928 *mode_list = client_mode_list;
3929 *user_count = list_count;
3932 /* Saves users and their modes to the `channel'. */
3934 void silc_server_save_users_on_channel(SilcServer server,
3935 SilcSocketConnection sock,
3936 SilcChannelEntry channel,
3937 SilcClientID *noadd,
3938 SilcBuffer user_list,
3939 SilcBuffer mode_list,
3940 SilcUInt32 user_count)
3945 SilcClientID *client_id;
3946 SilcClientEntry client;
3947 SilcIDCacheEntry cache;
3950 SILC_LOG_DEBUG(("Start"));
3952 for (i = 0; i < user_count; i++) {
3954 SILC_GET16_MSB(idp_len, user_list->data + 2);
3956 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3957 silc_buffer_pull(user_list, idp_len);
3962 SILC_GET32_MSB(mode, mode_list->data);
3963 silc_buffer_pull(mode_list, 4);
3965 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3966 silc_free(client_id);
3972 /* Check if we have this client cached already. */
3973 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3974 server->server_type, &cache);
3976 client = silc_idlist_find_client_by_id(server->global_list,
3977 client_id, server->server_type,
3982 /* If router did not find such Client ID in its lists then this must
3983 be bogus client or some router in the net is buggy. */
3984 if (server->server_type == SILC_ROUTER) {
3985 silc_free(client_id);
3989 /* We don't have that client anywhere, add it. The client is added
3990 to global list since server didn't have it in the lists so it must be
3992 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3993 silc_id_dup(client_id, SILC_ID_CLIENT),
3994 sock->user_data, NULL, 0);
3996 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3997 silc_free(client_id);
4001 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4003 /* Found, if it is from global list we'll assure that we won't
4004 expire it now that the entry is on channel. */
4009 silc_free(client_id);
4011 if (!silc_server_client_on_channel(client, channel, NULL)) {
4012 /* Client was not on the channel, add it. */
4013 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
4014 chl->client = client;
4016 chl->channel = channel;
4017 silc_hash_table_add(channel->user_list, chl->client, chl);
4018 silc_hash_table_add(client->channels, chl->channel, chl);
4019 channel->user_count++;
4024 /* Lookups route to the client indicated by the `id_data'. The connection
4025 object and internal data object is returned. Returns NULL if route
4026 could not be found to the client. If the `client_id' is specified then
4027 it is used and the `id_data' is ignored. */
4029 SilcSocketConnection silc_server_get_client_route(SilcServer server,
4030 unsigned char *id_data,
4032 SilcClientID *client_id,
4033 SilcIDListData *idata)
4036 SilcClientEntry client;
4038 SILC_LOG_DEBUG(("Start"));
4040 /* Decode destination Client ID */
4042 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4044 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4048 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4051 /* If the destination belongs to our server we don't have to route
4052 the packet anywhere but to send it to the local destination. */
4053 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4057 /* If we are router and the client has router then the client is in
4058 our cell but not directly connected to us. */
4059 if (server->server_type == SILC_ROUTER && client->router) {
4060 /* We are of course in this case the client's router thus the route
4061 to the client is the server who owns the client. So, we will send
4062 the packet to that server. */
4064 *idata = (SilcIDListData)client->router;
4065 return client->router->connection;
4068 /* Seems that client really is directly connected to us */
4070 *idata = (SilcIDListData)client;
4071 return client->connection;
4074 /* Destination belongs to someone not in this server. If we are normal
4075 server our action is to send the packet to our router. */
4076 if (server->server_type != SILC_ROUTER && !server->standalone) {
4079 *idata = (SilcIDListData)server->router;
4080 return server->router->connection;
4083 /* We are router and we will perform route lookup for the destination
4084 and send the packet to fastest route. */
4085 if (server->server_type == SILC_ROUTER && !server->standalone) {
4086 /* Check first that the ID is valid */
4087 client = silc_idlist_find_client_by_id(server->global_list, id,
4090 SilcSocketConnection dst_sock;
4092 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4096 *idata = (SilcIDListData)dst_sock->user_data;
4105 /* Encodes and returns channel list of channels the `client' has joined.
4106 Secret channels are not put to the list. */
4108 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4109 SilcClientEntry client)
4111 SilcBuffer buffer = NULL;
4112 SilcChannelEntry channel;
4113 SilcChannelClientEntry chl;
4114 SilcHashTableList htl;
4117 SilcUInt16 name_len;
4120 silc_hash_table_list(client->channels, &htl);
4121 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4122 channel = chl->channel;
4124 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4125 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4128 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4129 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4130 name_len = strlen(channel->channel_name);
4132 len = 4 + name_len + id_len + 4;
4133 buffer = silc_buffer_realloc(buffer,
4134 (buffer ? (buffer)->truelen + len : len));
4135 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4136 silc_buffer_format(buffer,
4137 SILC_STR_UI_SHORT(name_len),
4138 SILC_STR_UI_XNSTRING(channel->channel_name,
4140 SILC_STR_UI_SHORT(id_len),
4141 SILC_STR_UI_XNSTRING(cid, id_len),
4142 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4144 silc_buffer_pull(buffer, len);
4147 silc_hash_table_list_reset(&htl);
4150 silc_buffer_push(buffer, buffer->data - buffer->head);
4155 /* Finds client entry by Client ID and if it is not found then resolves
4156 it using WHOIS command. */
4158 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4159 SilcClientID *client_id,
4162 SilcClientEntry client;
4167 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4170 client = silc_idlist_find_client_by_id(server->global_list,
4171 client_id, TRUE, NULL);
4172 if (!client && server->server_type == SILC_ROUTER)
4176 if (!client && server->standalone)
4179 if (!client || !client->nickname || !client->username) {
4180 SilcBuffer buffer, idp;
4182 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4183 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4184 client->resolve_cmd_ident = ++server->cmd_ident;
4186 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4187 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4188 server->cmd_ident, 1,
4189 3, idp->data, idp->len);
4190 silc_server_packet_send(server, client ? client->router->connection :
4191 server->router->connection,
4192 SILC_PACKET_COMMAND, 0,
4193 buffer->data, buffer->len, FALSE);
4194 silc_buffer_free(idp);
4195 silc_buffer_free(buffer);
4206 /* A timeout callback for the re-key. We will be the initiator of the
4209 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4211 SilcSocketConnection sock = (SilcSocketConnection)context;
4212 SilcIDListData idata = (SilcIDListData)sock->user_data;
4213 SilcServer server = (SilcServer)idata->rekey->context;
4214 SilcProtocol protocol;
4215 SilcServerRekeyInternalContext *proto_ctx;
4217 SILC_LOG_DEBUG(("Start"));
4219 /* Allocate internal protocol context. This is sent as context
4221 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4222 proto_ctx->server = (void *)server;
4223 proto_ctx->sock = sock;
4224 proto_ctx->responder = FALSE;
4225 proto_ctx->pfs = idata->rekey->pfs;
4227 /* Perform rekey protocol. Will call the final callback after the
4228 protocol is over. */
4229 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4230 &protocol, proto_ctx, silc_server_rekey_final);
4231 sock->protocol = protocol;
4233 /* Run the protocol */
4234 silc_protocol_execute(protocol, server->schedule, 0, 0);
4236 /* Re-register re-key timeout */
4237 silc_schedule_task_add(server->schedule, sock->sock,
4238 silc_server_rekey_callback,
4239 context, idata->rekey->timeout, 0,
4240 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4243 /* The final callback for the REKEY protocol. This will actually take the
4244 new key material into use. */
4246 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4248 SilcProtocol protocol = (SilcProtocol)context;
4249 SilcServerRekeyInternalContext *ctx =
4250 (SilcServerRekeyInternalContext *)protocol->context;
4251 SilcServer server = (SilcServer)ctx->server;
4252 SilcSocketConnection sock = ctx->sock;
4254 SILC_LOG_DEBUG(("Start"));
4256 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4257 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4258 /* Error occured during protocol */
4259 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4260 silc_protocol_cancel(protocol, server->schedule);
4261 silc_protocol_free(protocol);
4262 sock->protocol = NULL;
4264 silc_packet_context_free(ctx->packet);
4266 silc_ske_free(ctx->ske);
4271 /* Purge the outgoing data queue to assure that all rekey packets really
4272 go to the network before we quit the protocol. */
4273 silc_server_packet_queue_purge(server, sock);
4276 silc_protocol_free(protocol);
4277 sock->protocol = NULL;
4279 silc_packet_context_free(ctx->packet);
4281 silc_ske_free(ctx->ske);