5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
91 silc_rng_free(server->rng);
93 silc_pkcs_free(server->pkcs);
94 if (server->pending_commands)
95 silc_dlist_uninit(server->pending_commands);
97 silc_idlist_del_server(server->local_list, server->id_entry);
99 silc_idcache_free(server->local_list->clients);
100 silc_idcache_free(server->local_list->servers);
101 silc_idcache_free(server->local_list->channels);
102 silc_idcache_free(server->global_list->clients);
103 silc_idcache_free(server->global_list->servers);
104 silc_idcache_free(server->global_list->channels);
106 silc_free(server->sockets);
111 /* Opens a listening port.
112 XXX This function will become more general and will support multiple
115 static bool silc_server_listen(SilcServer server, int *sock)
118 *sock = silc_net_create_server(server->config->server_info->port,
119 server->config->server_info->server_ip);
121 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
122 server->config->server_info->server_ip,
123 server->config->server_info->port));
129 /* Initializes the entire SILC server. This is called always before running
130 the server. This is called only once at the initialization of the program.
131 This binds the server to its listenning port. After this function returns
132 one should call silc_server_run to start the server. This returns TRUE
133 when everything is ok to run the server. Configuration file must be
134 read and parsed before calling this. */
136 bool silc_server_init(SilcServer server)
140 SilcServerEntry id_entry;
141 SilcIDListPurge purge;
143 SILC_LOG_DEBUG(("Initializing server"));
145 assert(server->config);
147 /* Set public and private keys */
148 if (!server->config->server_info ||
149 !server->config->server_info->public_key ||
150 !server->config->server_info->private_key) {
151 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
155 /* Steal public and private key from the config object */
156 server->public_key = server->config->server_info->public_key;
157 server->private_key = server->config->server_info->private_key;
158 server->config->server_info->public_key = NULL;
159 server->config->server_info->private_key = NULL;
161 /* Register all configured ciphers, PKCS and hash functions. */
162 if (!silc_server_config_register_ciphers(server))
163 silc_cipher_register_default();
164 if (!silc_server_config_register_pkcs(server))
165 silc_pkcs_register_default();
166 if (!silc_server_config_register_hashfuncs(server))
167 silc_hash_register_default();
168 if (!silc_server_config_register_hmacs(server))
169 silc_hmac_register_default();
171 /* Initialize random number generator for the server. */
172 server->rng = silc_rng_alloc();
173 silc_rng_init(server->rng);
174 silc_rng_global_init(server->rng);
176 /* Initialize hash functions for server to use */
177 silc_hash_alloc("md5", &server->md5hash);
178 silc_hash_alloc("sha1", &server->sha1hash);
180 /* Allocate PKCS context for local public and private keys */
181 silc_pkcs_alloc(server->public_key->name, &server->pkcs);
182 silc_pkcs_public_key_set(server->pkcs, server->public_key);
183 silc_pkcs_private_key_set(server->pkcs, server->private_key);
185 /* Initialize the scheduler */
186 server->schedule = silc_schedule_init(server->config->param.connections_max);
187 if (!server->schedule)
190 /* First, register log files configuration for error output */
191 silc_server_config_setlogfiles(server);
193 /* Initialize ID caches */
194 server->local_list->clients =
195 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
196 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
197 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
199 /* These are allocated for normal server as well as these hold some
200 global information that the server has fetched from its router. For
201 router these are used as they are supposed to be used on router. */
202 server->global_list->clients =
203 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
204 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
205 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
207 /* Create a listening server */
208 if (!silc_server_listen(server, &sock))
211 /* Allocate the entire socket list that is used in server. Eventually
212 all connections will have entry in this table (it is a table of
213 pointers to the actual object that is allocated individually
215 server->sockets = silc_calloc(server->config->param.connections_max,
216 sizeof(*server->sockets));
219 SilcSocketConnection newsocket = NULL;
221 /* Set socket to non-blocking mode */
222 silc_net_set_socket_nonblock(sock);
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
234 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
257 server->config->server_info->server_name = NULL;
259 /* Add ourselves to the server list. We don't have a router yet
260 beacuse we haven't established a route yet. It will be done later.
261 For now, NULL is sent as router. This allocates new entry to
264 silc_idlist_add_server(server->local_list, strdup(server->server_name),
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
279 /* Register protocols */
280 silc_server_protocols_register();
282 /* Add the first task to the scheduler. This is task that is executed by
283 timeout. It expires as soon as the caller calls silc_server_run. This
284 task performs authentication protocol and key exchange with our
286 silc_schedule_task_add(server->schedule, sock,
287 silc_server_connect_to_router,
288 (void *)server, 0, 1,
290 SILC_TASK_PRI_NORMAL);
292 /* Add listener task to the scheduler. This task receives new connections
293 to the server. This task remains on the queue until the end of the
295 silc_schedule_task_add(server->schedule, sock,
296 silc_server_accept_new_connection,
297 (void *)server, 0, 0,
299 SILC_TASK_PRI_NORMAL);
300 server->listenning = TRUE;
302 /* If server connections has been configured then we must be router as
303 normal server cannot have server connections, only router connections. */
304 if (server->config->servers) {
305 SilcServerConfigServer *ptr = server->config->servers;
307 server->server_type = SILC_ROUTER;
309 if (ptr->backup_router) {
310 server->server_type = SILC_BACKUP_ROUTER;
311 server->backup_router = TRUE;
312 server->id_entry->server_type = SILC_BACKUP_ROUTER;
319 /* Register the ID Cache purge task. This periodically purges the ID cache
320 and removes the expired cache entries. */
322 /* Clients local list */
323 purge = silc_calloc(1, sizeof(*purge));
324 purge->cache = server->local_list->clients;
325 purge->schedule = server->schedule;
326 purge->timeout = 600;
327 silc_schedule_task_add(purge->schedule, 0,
329 (void *)purge, purge->timeout, 0,
330 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
332 /* Clients global list */
333 purge = silc_calloc(1, sizeof(*purge));
334 purge->cache = server->global_list->clients;
335 purge->schedule = server->schedule;
336 purge->timeout = 300;
337 silc_schedule_task_add(purge->schedule, 0,
339 (void *)purge, purge->timeout, 0,
340 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
342 SILC_LOG_DEBUG(("Server initialized"));
344 /* We are done here, return succesfully */
348 silc_net_close_server(sock);
352 /* This function basically reads the config file again and switches the config
353 object pointed by the server object. After that, we have to fix various
354 things such as the server_name and the listening ports.
355 Keep in mind that we no longer have the root privileges at this point. */
357 bool silc_server_rehash(SilcServer server)
359 SilcServerConfig newconfig;
361 /* Reset the logging system */
362 silc_log_quick = TRUE;
363 silc_log_flush_all();
365 /* Start the main rehash phase (read again the config file) */
366 SILC_LOG_INFO(("Rehashing server"));
367 newconfig = silc_server_config_alloc(server->config_file);
370 SILC_LOG_ERROR(("Rehash FAILED."));
373 silc_server_config_unref(&server->config_ref);
374 server->config = newconfig;
375 silc_server_config_ref(&server->config_ref, newconfig, (void *) newconfig);
377 /* Fix the server_name field */
378 if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
379 /* We don't need any update */
380 silc_free(newconfig->server_info->server_name);
381 newconfig->server_info->server_name = NULL;
383 silc_free(server->server_name);
384 server->server_name = newconfig->server_info->server_name;
385 newconfig->server_info->server_name = NULL;
387 /* Update the idcache list with a fresh pointer */
388 silc_free(server->id_entry->server_name);
389 server->id_entry->server_name = strdup(server->server_name);
390 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
391 silc_idcache_add(server->local_list->servers, server->id_entry->server_name,
392 server->id_entry->id, server->id_entry, 0, NULL);
395 silc_server_config_setlogfiles(server);
397 /* XXX There is still to implement the publickey change and modules
398 adding (we can't allow modules removing since we can't know which
399 one are actually in use */
404 /* Drop root privileges. If some system call fails, die. */
406 void silc_server_drop(SilcServer server)
408 /* Are we executing silcd as root or a regular user? */
410 SILC_LOG_DEBUG(("Server started as user"));
417 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
419 /* Get the values given for user and group in configuration file */
420 user = server->config->server_info->user;
421 group = server->config->server_info->group;
423 if (!user || !group) {
424 fprintf(stderr, "Error:"
425 "\tSILC server must not be run as root. For the security of your\n"
426 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
427 "\tuser account. Modify the ServerInfo configuration section to run\n"
428 "\tthe server as non-root user.\n");
432 /* Check whether the user/group does not begin with a number */
433 if (isdigit(user[0]) || isdigit(group[0])) {
434 SILC_LOG_DEBUG(("User and/or group starts with a number"));
435 fprintf(stderr, "Invalid user and/or group information\n");
436 fprintf(stderr, "Please assign them as names, not numbers\n");
440 if (!(pw = getpwnam(user))) {
441 fprintf(stderr, "Error: No such user %s found.\n", user);
444 if (!(gr = getgrnam(group))) {
445 fprintf(stderr, "Error: No such group %s found.\n", group);
449 /* Check whether user and/or group is set to root. If yes, exit
450 immediately. Otherwise, setgid and setuid server to user.group */
451 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
452 fprintf(stderr, "Error:"
453 "\tSILC server must not be run as root. For the security of your\n"
454 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
455 "\tuser account. Modify the ServerInfo configuration section to run\n"
456 "\tthe server as non-root user.\n");
460 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
461 if (setgid(gr->gr_gid) != 0) {
462 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
466 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
467 SILC_LOG_DEBUG(("Removing supplementary groups"));
468 if (setgroups(0, NULL) != 0) {
469 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
472 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
473 if (initgroups(user, gr->gr_gid) != 0) {
474 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
475 "Exiting.\n", user, gr->gr_gid);
479 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
480 if (setuid(pw->pw_uid) != 0) {
481 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
488 /* Fork server to background */
490 void silc_server_daemonise(SilcServer server)
494 SILC_LOG_DEBUG(("Forking SILC server to background"));
496 if ((i = fork()) < 0) {
497 fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
501 if (i) /* Kill the parent */
504 server->background = TRUE;
507 /* XXX close stdin, stdout, stderr -- before this, check that all writes
508 to stderr are changed to SILC_SERVER_LOG_ERROR() */
511 /* The heart of the server. This runs the scheduler thus runs the server.
512 When this returns the server has been stopped and the program will
515 void silc_server_run(SilcServer server)
517 SILC_LOG_INFO(("SILC Server started"));
519 /* Start the scheduler, the heart of the SILC server. When this returns
520 the program will be terminated. */
521 silc_schedule(server->schedule);
524 /* Stops the SILC server. This function is used to shutdown the server.
525 This is usually called after the scheduler has returned. After stopping
526 the server one should call silc_server_free. */
528 void silc_server_stop(SilcServer server)
530 SILC_LOG_DEBUG(("Stopping server"));
532 if (server->schedule) {
533 silc_schedule_stop(server->schedule);
534 silc_schedule_uninit(server->schedule);
535 server->schedule = NULL;
538 silc_server_protocols_unregister();
540 SILC_LOG_DEBUG(("Server stopped"));
543 /* Function that is called when the network connection to a router has
544 been established. This will continue with the key exchange protocol
545 with the remote router. */
547 void silc_server_start_key_exchange(SilcServer server,
548 SilcServerConnection sconn,
551 SilcSocketConnection newsocket;
552 SilcProtocol protocol;
553 SilcServerKEInternalContext *proto_ctx;
554 SilcServerConfigRouter *conn =
555 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
558 /* Cancel any possible retry timeouts */
559 silc_schedule_task_del_by_callback(server->schedule,
560 silc_server_connect_router);
562 /* Set socket options */
563 silc_net_set_socket_nonblock(sock);
564 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
566 /* Create socket connection for the connection. Even though we
567 know that we are connecting to a router we will mark the socket
568 to be unknown connection until we have executed authentication
570 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
571 server->sockets[sock] = newsocket;
572 newsocket->hostname = strdup(sconn->remote_host);
573 newsocket->ip = strdup(sconn->remote_host);
574 newsocket->port = sconn->remote_port;
575 sconn->sock = newsocket;
577 /* Allocate internal protocol context. This is sent as context
579 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
580 proto_ctx->server = (void *)server;
581 proto_ctx->context = (void *)sconn;
582 proto_ctx->sock = newsocket;
583 proto_ctx->rng = server->rng;
584 proto_ctx->responder = FALSE;
586 /* Set Key Exchange flags from configuration, but fall back to global
588 SILC_GET_SKE_FLAGS(conn, proto_ctx);
589 if (server->config->param.key_exchange_pfs)
590 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
592 /* Perform key exchange protocol. silc_server_connect_to_router_second
593 will be called after the protocol is finished. */
594 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
595 &protocol, proto_ctx,
596 silc_server_connect_to_router_second);
597 newsocket->protocol = protocol;
599 /* Register a timeout task that will be executed if the protocol
600 is not executed within set limit. */
601 proto_ctx->timeout_task =
602 silc_schedule_task_add(server->schedule, sock,
603 silc_server_timeout_remote,
604 server, server->config->key_exchange_timeout, 0,
608 /* Register the connection for network input and output. This sets
609 that scheduler will listen for incoming packets for this connection
610 and sets that outgoing packets may be sent to this connection as
611 well. However, this doesn't set the scheduler for outgoing traffic,
612 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
613 later when outgoing data is available. */
614 context = (void *)server;
615 SILC_REGISTER_CONNECTION_FOR_IO(sock);
617 /* Run the protocol */
618 silc_protocol_execute(protocol, server->schedule, 0, 0);
621 /* Timeout callback that will be called to retry connecting to remote
622 router. This is used by both normal and router server. This will wait
623 before retrying the connecting. The timeout is generated by exponential
624 backoff algorithm. */
626 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
628 SilcServerConnection sconn = (SilcServerConnection)context;
629 SilcServer server = sconn->server;
630 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
631 SilcServerConfigConnParams *param =
632 (conn->param ? conn->param : &server->config->param);
634 SILC_LOG_INFO(("Retrying connecting to a router"));
636 /* Calculate next timeout */
637 if (sconn->retry_count >= 1) {
638 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
639 if (sconn->retry_timeout > param->reconnect_interval_max)
640 sconn->retry_timeout = param->reconnect_interval_max;
642 sconn->retry_timeout = param->reconnect_interval;
644 sconn->retry_count++;
645 sconn->retry_timeout = sconn->retry_timeout +
646 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
648 /* If we've reached max retry count, give up. */
649 if ((sconn->retry_count > param->reconnect_count) &&
650 !param->reconnect_keep_trying) {
651 SILC_LOG_ERROR(("Could not connect to router, giving up"));
652 silc_server_config_unref(&sconn->conn);
653 silc_free(sconn->remote_host);
654 silc_free(sconn->backup_replace_ip);
659 /* we will lookup a fresh pointer later */
660 silc_server_config_unref(&sconn->conn);
662 /* Wait one before retrying */
663 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
664 context, sconn->retry_timeout, 0,
665 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
668 /* Generic routine to use connect to a router. */
670 SILC_TASK_CALLBACK(silc_server_connect_router)
672 SilcServerConnection sconn = (SilcServerConnection)context;
673 SilcServer server = sconn->server;
674 SilcServerConfigRouter *rconn;
677 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
678 (sconn->backup ? "backup router" : "router"),
679 sconn->remote_host, sconn->remote_port));
681 server->router_connect = time(NULL);
682 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
685 SILC_LOG_INFO(("Unconfigured server, giving up"));
686 silc_free(sconn->remote_host);
687 silc_free(sconn->backup_replace_ip);
691 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
693 /* Connect to remote host */
694 sock = silc_net_create_connection(server->config->server_info->server_ip,
698 SILC_LOG_ERROR(("Could not connect to router %s:%d",
699 sconn->remote_host, sconn->remote_port));
700 if (!sconn->no_reconnect)
701 silc_schedule_task_add(server->schedule, 0,
702 silc_server_connect_to_router_retry,
703 context, 0, 1, SILC_TASK_TIMEOUT,
704 SILC_TASK_PRI_NORMAL);
706 silc_server_config_unref(&sconn->conn);
710 /* Continue with key exchange protocol */
711 silc_server_start_key_exchange(server, sconn, sock);
714 /* This function connects to our primary router or if we are a router this
715 establishes all our primary routes. This is called at the start of the
716 server to do authentication and key exchange with our router - called
719 SILC_TASK_CALLBACK(silc_server_connect_to_router)
721 SilcServer server = (SilcServer)context;
722 SilcServerConnection sconn;
723 SilcServerConfigRouter *ptr;
725 SILC_LOG_DEBUG(("Connecting to router(s)"));
727 if (server->server_type == SILC_SERVER) {
728 SILC_LOG_DEBUG(("We are normal server"));
729 } else if (server->server_type == SILC_ROUTER) {
730 SILC_LOG_DEBUG(("We are router"));
732 SILC_LOG_DEBUG(("We are backup router/normal server"));
735 if (!server->config->routers) {
736 /* There wasn't a configured router, we will continue but we don't
737 have a connection to outside world. We will be standalone server. */
738 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
739 server->standalone = TRUE;
743 /* Create the connections to all our routes */
744 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
746 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
747 ptr->backup_router ? "Backup router" : "Router",
748 ptr->initiator ? "Initiator" : "Responder",
749 ptr->host, ptr->port));
751 if (ptr->initiator) {
752 /* Allocate connection object for hold connection specific stuff. */
753 sconn = silc_calloc(1, sizeof(*sconn));
754 sconn->server = server;
755 sconn->remote_host = strdup(ptr->host);
756 sconn->remote_port = ptr->port;
757 sconn->backup = ptr->backup_router;
759 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
760 sconn->backup_replace_port = ptr->backup_replace_port;
763 if (!server->router_conn && !sconn->backup)
764 server->router_conn = sconn;
766 silc_schedule_task_add(server->schedule, fd,
767 silc_server_connect_router,
768 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
769 SILC_TASK_PRI_NORMAL);
774 /* Second part of connecting to router(s). Key exchange protocol has been
775 executed and now we will execute authentication protocol. */
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
779 SilcProtocol protocol = (SilcProtocol)context;
780 SilcServerKEInternalContext *ctx =
781 (SilcServerKEInternalContext *)protocol->context;
782 SilcServer server = (SilcServer)ctx->server;
783 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784 SilcSocketConnection sock = ctx->sock;
785 SilcServerConnAuthInternalContext *proto_ctx;
786 SilcServerConfigRouter *conn = NULL;
788 SILC_LOG_DEBUG(("Start"));
790 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
791 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
792 /* Error occured during protocol */
793 silc_protocol_free(protocol);
794 sock->protocol = NULL;
795 silc_ske_free_key_material(ctx->keymat);
797 silc_packet_context_free(ctx->packet);
799 silc_ske_free(ctx->ske);
800 silc_free(ctx->dest_id);
801 silc_server_config_unref(&ctx->cconfig);
802 silc_server_config_unref(&ctx->sconfig);
803 silc_server_config_unref(&ctx->rconfig);
805 silc_server_config_unref(&sconn->conn);
806 silc_free(sconn->remote_host);
807 silc_free(sconn->backup_replace_ip);
809 silc_schedule_task_del_by_callback(server->schedule,
810 silc_server_failure_callback);
811 silc_server_disconnect_remote(server, sock, "Server closed connection: "
812 "Key exchange failed");
816 /* We now have the key material as the result of the key exchange
817 protocol. Take the key material into use. Free the raw key material
818 as soon as we've set them into use. */
819 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
820 ctx->sock, ctx->keymat,
821 ctx->ske->prop->cipher,
822 ctx->ske->prop->pkcs,
823 ctx->ske->prop->hash,
824 ctx->ske->prop->hmac,
825 ctx->ske->prop->group,
827 silc_protocol_free(protocol);
828 sock->protocol = NULL;
829 silc_ske_free_key_material(ctx->keymat);
831 silc_packet_context_free(ctx->packet);
833 silc_ske_free(ctx->ske);
834 silc_free(ctx->dest_id);
836 silc_server_config_unref(&sconn->conn);
837 silc_free(sconn->remote_host);
838 silc_free(sconn->backup_replace_ip);
840 silc_schedule_task_del_by_callback(server->schedule,
841 silc_server_failure_callback);
842 silc_server_disconnect_remote(server, sock, "Server closed connection: "
843 "Key exchange failed");
846 silc_ske_free_key_material(ctx->keymat);
848 /* Allocate internal context for the authentication protocol. This
849 is sent as context for the protocol. */
850 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
851 proto_ctx->server = (void *)server;
852 proto_ctx->context = (void *)sconn;
853 proto_ctx->sock = sock;
854 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
855 proto_ctx->dest_id_type = ctx->dest_id_type;
856 proto_ctx->dest_id = ctx->dest_id;
858 /* Resolve the authentication method used in this connection. Check if
859 we find a match from user configured connections */
860 if (!sconn->conn.ref_ptr)
861 conn = silc_server_config_find_router_conn(server, sock->hostname,
864 conn = sconn->conn.ref_ptr;
867 /* Match found. Use the configured authentication method. Take only
868 the passphrase, since for public key auth we automatically use
869 our local key pair. */
870 if (conn->passphrase) {
871 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
872 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
874 proto_ctx->auth_data = strdup(conn->passphrase);
875 proto_ctx->auth_data_len = strlen(conn->passphrase);
876 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
878 } else if (conn->publickeys) {
879 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
881 proto_ctx->auth_meth = SILC_AUTH_NONE;
884 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
885 sock->hostname, sock->ip, sock->port));
886 silc_protocol_free(protocol);
887 sock->protocol = NULL;
889 silc_packet_context_free(ctx->packet);
891 silc_ske_free(ctx->ske);
892 silc_free(ctx->dest_id);
894 silc_schedule_task_del_by_callback(server->schedule,
895 silc_server_failure_callback);
896 silc_server_disconnect_remote(server, sock, "Server closed connection: "
897 "Key exchange failed");
901 /* Free old protocol as it is finished now */
902 silc_protocol_free(protocol);
904 silc_packet_context_free(ctx->packet);
906 sock->protocol = NULL;
908 /* Allocate the authentication protocol. This is allocated here
909 but we won't start it yet. We will be receiving party of this
910 protocol thus we will wait that connecting party will make
912 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
913 &sock->protocol, proto_ctx,
914 silc_server_connect_to_router_final);
916 /* Register timeout task. If the protocol is not executed inside
917 this timelimit the connection will be terminated. */
918 proto_ctx->timeout_task =
919 silc_schedule_task_add(server->schedule, sock->sock,
920 silc_server_timeout_remote,
922 server->config->conn_auth_timeout, 0,
926 /* Run the protocol */
927 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
930 /* Finalizes the connection to router. Registers a server task to the
931 queue so that we can accept new connections. */
933 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
935 SilcProtocol protocol = (SilcProtocol)context;
936 SilcServerConnAuthInternalContext *ctx =
937 (SilcServerConnAuthInternalContext *)protocol->context;
938 SilcServer server = (SilcServer)ctx->server;
939 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
940 SilcSocketConnection sock = ctx->sock;
941 SilcServerEntry id_entry;
943 SilcServerHBContext hb_context;
944 unsigned char *id_string;
946 SilcIDListData idata;
947 SilcServerConfigRouter *conn = NULL;
948 SilcServerConfigConnParams *param = NULL;
950 SILC_LOG_DEBUG(("Start"));
952 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
953 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
954 /* Error occured during protocol */
955 silc_free(ctx->dest_id);
956 silc_server_disconnect_remote(server, sock, "Server closed connection: "
957 "Authentication failed");
961 /* Add a task to the queue. This task receives new connections to the
962 server. This task remains on the queue until the end of the program. */
963 if (!server->listenning && !sconn->backup) {
964 silc_schedule_task_add(server->schedule, server->sock,
965 silc_server_accept_new_connection,
966 (void *)server, 0, 0,
968 SILC_TASK_PRI_NORMAL);
969 server->listenning = TRUE;
972 /* Send NEW_SERVER packet to the router. We will become registered
973 to the SILC network after sending this packet. */
974 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
975 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
976 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
977 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
978 silc_buffer_format(packet,
979 SILC_STR_UI_SHORT(id_len),
980 SILC_STR_UI_XNSTRING(id_string, id_len),
981 SILC_STR_UI_SHORT(strlen(server->server_name)),
982 SILC_STR_UI_XNSTRING(server->server_name,
983 strlen(server->server_name)),
986 /* Send the packet */
987 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
988 packet->data, packet->len, TRUE);
989 silc_buffer_free(packet);
990 silc_free(id_string);
992 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
994 /* Check that we do not have this ID already */
995 id_entry = silc_idlist_find_server_by_id(server->local_list,
996 ctx->dest_id, TRUE, NULL);
998 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1000 id_entry = silc_idlist_find_server_by_id(server->global_list,
1001 ctx->dest_id, TRUE, NULL);
1003 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1006 SILC_LOG_DEBUG(("New server id(%s)",
1007 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1009 /* Add the connected router to global server list */
1010 id_entry = silc_idlist_add_server(server->global_list,
1011 strdup(sock->hostname),
1012 SILC_ROUTER, ctx->dest_id, NULL, sock);
1014 silc_free(ctx->dest_id);
1015 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1016 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1017 "Authentication failed");
1021 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1022 silc_free(sock->user_data);
1023 sock->user_data = (void *)id_entry;
1024 sock->type = SILC_SOCKET_TYPE_ROUTER;
1025 idata = (SilcIDListData)sock->user_data;
1026 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1028 conn = sconn->conn.ref_ptr;
1029 param = &server->config->param;
1030 if (conn && conn->param)
1031 param = conn->param;
1033 /* Perform keepalive. The `hb_context' will be freed automatically
1034 when finally calling the silc_socket_free function. */
1035 hb_context = silc_calloc(1, sizeof(*hb_context));
1036 hb_context->server = server;
1037 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1038 silc_server_perform_heartbeat,
1041 /* Register re-key timeout */
1042 idata->rekey->timeout = param->key_exchange_rekey;
1043 idata->rekey->context = (void *)server;
1044 silc_schedule_task_add(server->schedule, sock->sock,
1045 silc_server_rekey_callback,
1046 (void *)sock, idata->rekey->timeout, 0,
1047 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1049 if (!sconn->backup) {
1050 /* Mark this router our primary router if we're still standalone */
1051 if (server->standalone) {
1052 server->id_entry->router = id_entry;
1053 server->router = id_entry;
1054 server->standalone = FALSE;
1056 /* If we are router then announce our possible servers. */
1057 if (server->server_type == SILC_ROUTER)
1058 silc_server_announce_servers(server, FALSE, 0,
1059 server->router->connection);
1061 /* Announce our clients and channels to the router */
1062 silc_server_announce_clients(server, 0, server->router->connection);
1063 silc_server_announce_channels(server, 0, server->router->connection);
1066 /* Add this server to be our backup router */
1067 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1068 sconn->backup_replace_port, FALSE);
1071 sock->protocol = NULL;
1073 /* Call the completion callback to indicate that we've connected to
1075 if (sconn->callback)
1076 (*sconn->callback)(server, id_entry, sconn->callback_context);
1079 /* Free the temporary connection data context */
1081 silc_server_config_unref(&sconn->conn);
1082 silc_free(sconn->remote_host);
1083 silc_free(sconn->backup_replace_ip);
1086 if (sconn == server->router_conn)
1087 server->router_conn = NULL;
1089 /* Free the protocol object */
1090 if (sock->protocol == protocol)
1091 sock->protocol = NULL;
1092 silc_protocol_free(protocol);
1094 silc_packet_context_free(ctx->packet);
1096 silc_ske_free(ctx->ske);
1097 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1098 silc_free(ctx->auth_data);
1102 /* Host lookup callback that is called after the incoming connection's
1103 IP and FQDN lookup is performed. This will actually check the acceptance
1104 of the incoming connection and will register the key exchange protocol
1105 for this connection. */
1108 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1111 SilcServer server = (SilcServer)context;
1112 SilcServerKEInternalContext *proto_ctx;
1113 SilcServerConfigClient *cconfig = NULL;
1114 SilcServerConfigServer *sconfig = NULL;
1115 SilcServerConfigRouter *rconfig = NULL;
1116 SilcServerConfigDeny *deny;
1119 SILC_LOG_DEBUG(("Start"));
1121 /* Check whether we could resolve both IP and FQDN. */
1122 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1123 server->config->require_reverse_lookup)) {
1124 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1125 sock->hostname ? sock->hostname :
1126 sock->ip ? sock->ip : ""));
1127 server->stat.conn_failures++;
1128 silc_server_disconnect_remote(server, sock,
1129 "Server closed connection: Unknown host");
1133 /* Register the connection for network input and output. This sets
1134 that scheduler will listen for incoming packets for this connection
1135 and sets that outgoing packets may be sent to this connection as well.
1136 However, this doesn't set the scheduler for outgoing traffic, it
1137 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1138 later when outgoing data is available. */
1139 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1141 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1144 port = server->sockets[server->sock]->port; /* Listenning port */
1146 /* Check whether this connection is denied to connect to us. */
1147 deny = silc_server_config_find_denied(server, sock->ip);
1149 deny = silc_server_config_find_denied(server, sock->hostname);
1151 /* The connection is denied */
1152 SILC_LOG_INFO(("Connection %s (%s) is denied",
1153 sock->hostname, sock->ip));
1154 silc_server_disconnect_remote(server, sock, deny->reason ?
1156 "Server closed connection: "
1157 "Connection refused");
1158 server->stat.conn_failures++;
1162 /* Check whether we have configured this sort of connection at all. We
1163 have to check all configurations since we don't know what type of
1164 connection this is. */
1165 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1166 cconfig = silc_server_config_find_client(server, sock->hostname);
1167 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1168 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1169 if (server->server_type == SILC_ROUTER) {
1170 if (!(rconfig = silc_server_config_find_router_conn(server,
1172 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1175 if (!cconfig && !sconfig && !rconfig) {
1176 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1178 silc_server_disconnect_remote(server, sock,
1179 "Server closed connection: "
1180 "Connection refused");
1181 server->stat.conn_failures++;
1185 /* The connection is allowed */
1187 /* Allocate internal context for key exchange protocol. This is
1188 sent as context for the protocol. */
1189 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1190 proto_ctx->server = context;
1191 proto_ctx->sock = sock;
1192 proto_ctx->rng = server->rng;
1193 proto_ctx->responder = TRUE;
1194 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1195 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1196 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1198 /* Take flags for key exchange. Since we do not know what type of connection
1199 this is, we go through all found configurations and use the global ones
1200 as well. This will result always into strictest key exchange flags. */
1201 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1202 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1203 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1204 if (server->config->param.key_exchange_pfs)
1205 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1207 /* Prepare the connection for key exchange protocol. We allocate the
1208 protocol but will not start it yet. The connector will be the
1209 initiator of the protocol thus we will wait for initiation from
1210 there before we start the protocol. */
1211 server->stat.auth_attempts++;
1212 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1213 &sock->protocol, proto_ctx,
1214 silc_server_accept_new_connection_second);
1216 /* Register a timeout task that will be executed if the connector
1217 will not start the key exchange protocol within specified timeout
1218 and the connection will be closed. */
1219 proto_ctx->timeout_task =
1220 silc_schedule_task_add(server->schedule, sock->sock,
1221 silc_server_timeout_remote,
1222 context, server->config->key_exchange_timeout, 0,
1227 /* Accepts new connections to the server. Accepting new connections are
1228 done in three parts to make it async. */
1230 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1232 SilcServer server = (SilcServer)context;
1233 SilcSocketConnection newsocket;
1236 SILC_LOG_DEBUG(("Accepting new connection"));
1238 server->stat.conn_attempts++;
1240 sock = silc_net_accept_connection(server->sock);
1242 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1243 server->stat.conn_failures++;
1247 /* Check for maximum allowed connections */
1248 if (sock > server->config->param.connections_max) {
1249 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1250 server->stat.conn_failures++;
1251 silc_net_close_connection(sock);
1255 /* Set socket options */
1256 silc_net_set_socket_nonblock(sock);
1257 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1259 /* We don't create a ID yet, since we don't know what type of connection
1260 this is yet. But, we do add the connection to the socket table. */
1261 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1262 server->sockets[sock] = newsocket;
1264 /* Perform asynchronous host lookup. This will lookup the IP and the
1265 FQDN of the remote connection. After the lookup is done the connection
1266 is accepted further. */
1267 silc_socket_host_lookup(newsocket, TRUE,
1268 silc_server_accept_new_connection_lookup, context,
1272 /* Second part of accepting new connection. Key exchange protocol has been
1273 performed and now it is time to do little connection authentication
1274 protocol to figure out whether this connection is client or server
1275 and whether it has right to access this server (especially server
1276 connections needs to be authenticated). */
1278 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1280 SilcProtocol protocol = (SilcProtocol)context;
1281 SilcServerKEInternalContext *ctx =
1282 (SilcServerKEInternalContext *)protocol->context;
1283 SilcServer server = (SilcServer)ctx->server;
1284 SilcSocketConnection sock = ctx->sock;
1285 SilcServerConnAuthInternalContext *proto_ctx;
1287 SILC_LOG_DEBUG(("Start"));
1289 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1290 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1291 /* Error occured during protocol */
1292 silc_protocol_free(protocol);
1293 sock->protocol = NULL;
1294 silc_ske_free_key_material(ctx->keymat);
1296 silc_packet_context_free(ctx->packet);
1298 silc_ske_free(ctx->ske);
1299 silc_free(ctx->dest_id);
1300 silc_server_config_unref(&ctx->cconfig);
1301 silc_server_config_unref(&ctx->sconfig);
1302 silc_server_config_unref(&ctx->rconfig);
1304 silc_schedule_task_del_by_callback(server->schedule,
1305 silc_server_failure_callback);
1306 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1307 "Key exchange failed");
1308 server->stat.auth_failures++;
1312 /* We now have the key material as the result of the key exchange
1313 protocol. Take the key material into use. Free the raw key material
1314 as soon as we've set them into use. */
1315 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1316 ctx->sock, ctx->keymat,
1317 ctx->ske->prop->cipher,
1318 ctx->ske->prop->pkcs,
1319 ctx->ske->prop->hash,
1320 ctx->ske->prop->hmac,
1321 ctx->ske->prop->group,
1323 silc_protocol_free(protocol);
1324 sock->protocol = NULL;
1325 silc_ske_free_key_material(ctx->keymat);
1327 silc_packet_context_free(ctx->packet);
1329 silc_ske_free(ctx->ske);
1330 silc_free(ctx->dest_id);
1331 silc_server_config_unref(&ctx->cconfig);
1332 silc_server_config_unref(&ctx->sconfig);
1333 silc_server_config_unref(&ctx->rconfig);
1335 silc_schedule_task_del_by_callback(server->schedule,
1336 silc_server_failure_callback);
1337 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1338 "Key exchange failed");
1339 server->stat.auth_failures++;
1342 silc_ske_free_key_material(ctx->keymat);
1344 /* Allocate internal context for the authentication protocol. This
1345 is sent as context for the protocol. */
1346 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1347 proto_ctx->server = (void *)server;
1348 proto_ctx->sock = sock;
1349 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1350 proto_ctx->responder = TRUE;
1351 proto_ctx->dest_id_type = ctx->dest_id_type;
1352 proto_ctx->dest_id = ctx->dest_id;
1353 proto_ctx->cconfig = ctx->cconfig;
1354 proto_ctx->sconfig = ctx->sconfig;
1355 proto_ctx->rconfig = ctx->rconfig;
1357 /* Free old protocol as it is finished now */
1358 silc_protocol_free(protocol);
1360 silc_packet_context_free(ctx->packet);
1362 sock->protocol = NULL;
1364 /* Allocate the authentication protocol. This is allocated here
1365 but we won't start it yet. We will be receiving party of this
1366 protocol thus we will wait that connecting party will make
1367 their first move. */
1368 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1369 &sock->protocol, proto_ctx,
1370 silc_server_accept_new_connection_final);
1372 /* Register timeout task. If the protocol is not executed inside
1373 this timelimit the connection will be terminated. */
1374 proto_ctx->timeout_task =
1375 silc_schedule_task_add(server->schedule, sock->sock,
1376 silc_server_timeout_remote,
1378 server->config->conn_auth_timeout, 0,
1383 /* Final part of accepting new connection. The connection has now
1384 been authenticated and keys has been exchanged. We also know whether
1385 this is client or server connection. */
1387 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1389 SilcProtocol protocol = (SilcProtocol)context;
1390 SilcServerConnAuthInternalContext *ctx =
1391 (SilcServerConnAuthInternalContext *)protocol->context;
1392 SilcServer server = (SilcServer)ctx->server;
1393 SilcSocketConnection sock = ctx->sock;
1394 SilcServerHBContext hb_context;
1395 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1397 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1399 SILC_LOG_DEBUG(("Start"));
1401 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1402 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1403 /* Error occured during protocol */
1404 silc_protocol_free(protocol);
1405 sock->protocol = NULL;
1407 silc_packet_context_free(ctx->packet);
1409 silc_ske_free(ctx->ske);
1410 silc_free(ctx->dest_id);
1411 silc_server_config_unref(&ctx->cconfig);
1412 silc_server_config_unref(&ctx->sconfig);
1413 silc_server_config_unref(&ctx->rconfig);
1415 silc_schedule_task_del_by_callback(server->schedule,
1416 silc_server_failure_callback);
1417 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1418 "Authentication failed");
1419 server->stat.auth_failures++;
1423 entry->data.last_receive = time(NULL);
1425 switch (ctx->conn_type) {
1426 case SILC_SOCKET_TYPE_CLIENT:
1428 SilcClientEntry client;
1429 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1431 /* Verify whether this connection is after all allowed to connect */
1432 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1433 &server->config->param,
1434 conn->param, ctx->ske)) {
1435 server->stat.auth_failures++;
1439 SILC_LOG_DEBUG(("Remote host is client"));
1440 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1443 /* Add the client to the client ID cache. The nickname and Client ID
1444 and other information is created after we have received NEW_CLIENT
1445 packet from client. */
1446 client = silc_idlist_add_client(server->local_list,
1447 NULL, NULL, NULL, NULL, NULL, sock, 0);
1449 SILC_LOG_ERROR(("Could not add new client to cache"));
1450 silc_free(sock->user_data);
1451 silc_server_disconnect_remote(server, sock,
1452 "Server closed connection: "
1453 "Authentication failed");
1454 server->stat.auth_failures++;
1459 server->stat.my_clients++;
1460 server->stat.clients++;
1461 if (server->server_type == SILC_ROUTER)
1462 server->stat.cell_clients++;
1464 /* Get connection parameters */
1466 if (conn->param->keepalive_secs)
1467 hearbeat_timeout = conn->param->keepalive_secs;
1470 id_entry = (void *)client;
1473 case SILC_SOCKET_TYPE_SERVER:
1474 case SILC_SOCKET_TYPE_ROUTER:
1476 SilcServerEntry new_server;
1477 bool initiator = FALSE;
1478 bool backup_local = FALSE;
1479 bool backup_router = FALSE;
1480 char *backup_replace_ip = NULL;
1481 SilcUInt16 backup_replace_port = 0;
1482 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1483 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1485 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1486 /* Verify whether this connection is after all allowed to connect */
1487 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1488 &server->config->param,
1489 rconn ? rconn->param : NULL,
1491 server->stat.auth_failures++;
1497 if (rconn->param->keepalive_secs)
1498 hearbeat_timeout = rconn->param->keepalive_secs;
1501 initiator = rconn->initiator;
1502 backup_local = rconn->backup_local;
1503 backup_router = rconn->backup_router;
1504 backup_replace_ip = rconn->backup_replace_ip;
1505 backup_replace_port = rconn->backup_replace_port;
1509 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1510 /* Verify whether this connection is after all allowed to connect */
1511 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1512 &server->config->param,
1513 sconn ? sconn->param : NULL,
1515 server->stat.auth_failures++;
1520 if (sconn->param->keepalive_secs)
1521 hearbeat_timeout = sconn->param->keepalive_secs;
1524 backup_router = sconn->backup_router;
1528 SILC_LOG_DEBUG(("Remote host is %s",
1529 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1530 "server" : (backup_router ?
1531 "backup router" : "router")));
1532 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1533 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1534 "server" : (backup_router ?
1535 "backup router" : "router")));
1537 /* Add the server into server cache. The server name and Server ID
1538 is updated after we have received NEW_SERVER packet from the
1539 server. We mark ourselves as router for this server if we really
1542 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1543 server->local_list : (backup_router ?
1544 server->local_list :
1545 server->global_list)),
1547 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1548 SILC_SERVER : SILC_ROUTER),
1550 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1551 server->id_entry : (backup_router ?
1552 server->id_entry : NULL)),
1555 SILC_LOG_ERROR(("Could not add new server to cache"));
1556 silc_free(sock->user_data);
1557 silc_server_disconnect_remote(server, sock,
1558 "Server closed connection: "
1559 "Authentication failed");
1560 server->stat.auth_failures++;
1565 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1566 server->stat.my_servers++;
1568 server->stat.my_routers++;
1569 server->stat.servers++;
1571 id_entry = (void *)new_server;
1573 /* If the incoming connection is router and marked as backup router
1574 then add it to be one of our backups */
1575 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1576 silc_server_backup_add(server, new_server, backup_replace_ip,
1577 backup_replace_port, backup_local);
1579 /* Change it back to SERVER type since that's what it really is. */
1581 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1583 new_server->server_type = SILC_BACKUP_ROUTER;
1586 /* Check whether this connection is to be our primary router connection
1587 if we do not already have the primary route. */
1588 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1589 if (silc_server_config_is_primary_route(server) && !initiator)
1592 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1593 server->standalone = FALSE;
1594 if (!server->id_entry->router) {
1595 server->id_entry->router = id_entry;
1596 server->router = id_entry;
1607 sock->type = ctx->conn_type;
1609 /* Add the common data structure to the ID entry. */
1610 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1612 /* Add to sockets internal pointer for fast referencing */
1613 silc_free(sock->user_data);
1614 sock->user_data = id_entry;
1616 /* Connection has been fully established now. Everything is ok. */
1617 SILC_LOG_DEBUG(("New connection authenticated"));
1619 /* Perform keepalive. The `hb_context' will be freed automatically
1620 when finally calling the silc_socket_free function. */
1621 hb_context = silc_calloc(1, sizeof(*hb_context));
1622 hb_context->server = server;
1623 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1624 silc_server_perform_heartbeat,
1628 silc_schedule_task_del_by_callback(server->schedule,
1629 silc_server_failure_callback);
1630 silc_protocol_free(protocol);
1632 silc_packet_context_free(ctx->packet);
1634 silc_ske_free(ctx->ske);
1635 silc_free(ctx->dest_id);
1636 silc_server_config_unref(&ctx->cconfig);
1637 silc_server_config_unref(&ctx->sconfig);
1638 silc_server_config_unref(&ctx->rconfig);
1640 sock->protocol = NULL;
1643 /* This function is used to read packets from network and send packets to
1644 network. This is usually a generic task. */
1646 SILC_TASK_CALLBACK(silc_server_packet_process)
1648 SilcServer server = (SilcServer)context;
1649 SilcSocketConnection sock = server->sockets[fd];
1650 SilcIDListData idata;
1651 SilcCipher cipher = NULL;
1652 SilcHmac hmac = NULL;
1653 SilcUInt32 sequence = 0;
1659 SILC_LOG_DEBUG(("Processing packet"));
1661 /* Packet sending */
1663 if (type == SILC_TASK_WRITE) {
1664 /* Do not send data to disconnected connection */
1665 if (SILC_IS_DISCONNECTED(sock))
1668 server->stat.packets_sent++;
1670 /* Send the packet */
1671 ret = silc_packet_send(sock, TRUE);
1673 /* If returned -2 could not write to connection now, will do
1679 SILC_LOG_ERROR(("Error sending packet to connection "
1680 "%s:%d [%s]", sock->hostname, sock->port,
1681 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1682 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1683 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1688 /* The packet has been sent and now it is time to set the connection
1689 back to only for input. When there is again some outgoing data
1690 available for this connection it will be set for output as well.
1691 This call clears the output setting and sets it only for input. */
1692 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1693 SILC_UNSET_OUTBUF_PENDING(sock);
1695 silc_buffer_clear(sock->outbuf);
1699 /* Packet receiving */
1701 /* Read some data from connection */
1702 ret = silc_packet_receive(sock);
1706 SILC_LOG_ERROR(("Error receiving packet from connection "
1707 "%s:%d [%s] %s", sock->hostname, sock->port,
1708 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1709 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1710 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1711 "Router"), strerror(errno)));
1717 SILC_LOG_DEBUG(("Read EOF"));
1719 /* If connection is disconnecting already we will finally
1720 close the connection */
1721 if (SILC_IS_DISCONNECTING(sock)) {
1722 if (sock->user_data)
1723 silc_server_free_sock_user_data(server, sock, NULL);
1724 silc_server_close_connection(server, sock);
1728 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1729 SILC_SET_DISCONNECTING(sock);
1731 if (sock->user_data) {
1733 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1734 silc_server_free_sock_user_data(server, sock, tmp);
1736 silc_server_free_sock_user_data(server, sock, NULL);
1737 } else if (server->router_conn && server->router_conn->sock == sock &&
1738 !server->router && server->standalone)
1739 silc_schedule_task_add(server->schedule, 0,
1740 silc_server_connect_to_router,
1743 SILC_TASK_PRI_NORMAL);
1745 silc_server_close_connection(server, sock);
1749 /* If connection is disconnecting or disconnected we will ignore
1751 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1752 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1756 server->stat.packets_received++;
1758 /* Get keys and stuff from ID entry */
1759 idata = (SilcIDListData)sock->user_data;
1761 cipher = idata->receive_key;
1762 hmac = idata->hmac_receive;
1763 sequence = idata->psn_receive;
1766 /* Process the packet. This will call the parser that will then
1767 decrypt and parse the packet. */
1768 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1769 TRUE : FALSE, cipher, hmac, sequence,
1770 silc_server_packet_parse, server);
1772 /* If this socket connection is not authenticated yet and the packet
1773 processing failed we will drop the connection since it can be
1774 a malicious flooder. */
1775 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1776 (!sock->protocol || sock->protocol->protocol->type ==
1777 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1778 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1779 SILC_SET_DISCONNECTING(sock);
1781 if (sock->user_data)
1782 silc_server_free_sock_user_data(server, sock, NULL);
1783 silc_server_close_connection(server, sock);
1787 /* Parses whole packet, received earlier. */
1789 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1791 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1792 SilcServer server = (SilcServer)parse_ctx->context;
1793 SilcSocketConnection sock = parse_ctx->sock;
1794 SilcPacketContext *packet = parse_ctx->packet;
1795 SilcIDListData idata = (SilcIDListData)sock->user_data;
1798 SILC_LOG_DEBUG(("Start"));
1800 /* Parse the packet */
1801 if (parse_ctx->normal)
1802 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1804 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1806 /* If entry is disabled ignore what we got. */
1807 if (ret != SILC_PACKET_RESUME_ROUTER &&
1808 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1809 SILC_LOG_DEBUG(("Connection is disabled"));
1813 if (ret == SILC_PACKET_NONE)
1816 /* Check that the the current client ID is same as in the client's packet. */
1817 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1818 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1819 if (client && client->id) {
1820 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1821 packet->src_id_type);
1822 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1830 if (server->server_type == SILC_ROUTER) {
1831 /* Route the packet if it is not destined to us. Other ID types but
1832 server are handled separately after processing them. */
1833 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1834 packet->dst_id_type == SILC_ID_SERVER &&
1835 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1836 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1838 /* Route the packet to fastest route for the destination ID */
1839 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1840 packet->dst_id_type);
1843 silc_server_packet_route(server,
1844 silc_server_route_get(server, id,
1845 packet->dst_id_type),
1852 /* Parse the incoming packet type */
1853 silc_server_packet_parse_type(server, sock, packet);
1855 if (server->server_type == SILC_ROUTER) {
1856 /* Broadcast packet if it is marked as broadcast packet and it is
1857 originated from router and we are router. */
1858 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1859 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1860 !server->standalone) {
1861 /* Broadcast to our primary route */
1862 silc_server_packet_broadcast(server, server->router->connection, packet);
1864 /* If we have backup routers then we need to feed all broadcast
1865 data to those servers. */
1866 silc_server_backup_broadcast(server, sock, packet);
1871 silc_packet_context_free(packet);
1872 silc_free(parse_ctx);
1875 /* Parser callback called by silc_packet_receive_process. This merely
1876 registers timeout that will handle the actual parsing when appropriate. */
1878 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1881 SilcServer server = (SilcServer)context;
1882 SilcSocketConnection sock = parser_context->sock;
1883 SilcIDListData idata = (SilcIDListData)sock->user_data;
1886 idata->psn_receive = parser_context->packet->sequence + 1;
1888 /* If protocol for this connection is key exchange or rekey then we'll
1889 process all packets synchronously, since there might be packets in
1890 queue that we are not able to decrypt without first processing the
1891 packets before them. */
1892 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1893 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1894 (sock->protocol && sock->protocol->protocol &&
1895 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1896 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1897 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1900 /* Reprocess data since we'll return FALSE here. This is because
1901 the idata->receive_key might have become valid in the last packet
1902 and we want to call this processor with valid cipher. */
1904 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1905 TRUE : FALSE, idata->receive_key,
1906 idata->hmac_receive, idata->psn_receive,
1907 silc_server_packet_parse, server);
1909 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1910 TRUE : FALSE, NULL, NULL, 0,
1911 silc_server_packet_parse, server);
1915 switch (sock->type) {
1916 case SILC_SOCKET_TYPE_UNKNOWN:
1917 case SILC_SOCKET_TYPE_CLIENT:
1918 /* Parse the packet with timeout */
1919 silc_schedule_task_add(server->schedule, sock->sock,
1920 silc_server_packet_parse_real,
1921 (void *)parser_context, 0, 100000,
1923 SILC_TASK_PRI_NORMAL);
1925 case SILC_SOCKET_TYPE_SERVER:
1926 case SILC_SOCKET_TYPE_ROUTER:
1927 /* Packets from servers are parsed immediately */
1928 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1938 /* Parses the packet type and calls what ever routines the packet type
1939 requires. This is done for all incoming packets. */
1941 void silc_server_packet_parse_type(SilcServer server,
1942 SilcSocketConnection sock,
1943 SilcPacketContext *packet)
1945 SilcPacketType type = packet->type;
1946 SilcIDListData idata = (SilcIDListData)sock->user_data;
1948 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1950 /* Parse the packet type */
1952 case SILC_PACKET_DISCONNECT:
1953 SILC_LOG_DEBUG(("Disconnect packet"));
1954 if (packet->flags & SILC_PACKET_FLAG_LIST)
1956 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1957 /* Duplicate to null terminate the string. */
1958 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1959 SILC_LOG_ERROR(("%s", message));
1964 case SILC_PACKET_SUCCESS:
1966 * Success received for something. For now we can have only
1967 * one protocol for connection executing at once hence this
1968 * success message is for whatever protocol is executing currently.
1970 SILC_LOG_DEBUG(("Success packet"));
1971 if (packet->flags & SILC_PACKET_FLAG_LIST)
1974 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1977 case SILC_PACKET_FAILURE:
1979 * Failure received for something. For now we can have only
1980 * one protocol for connection executing at once hence this
1981 * failure message is for whatever protocol is executing currently.
1983 SILC_LOG_DEBUG(("Failure packet"));
1984 if (packet->flags & SILC_PACKET_FLAG_LIST)
1986 if (sock->protocol) {
1987 SilcServerFailureContext f;
1988 f = silc_calloc(1, sizeof(*f));
1992 /* We will wait 5 seconds to process this failure packet */
1993 silc_schedule_task_add(server->schedule, sock->sock,
1994 silc_server_failure_callback, (void *)f, 5, 0,
1995 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1999 case SILC_PACKET_REJECT:
2000 SILC_LOG_DEBUG(("Reject packet"));
2001 if (packet->flags & SILC_PACKET_FLAG_LIST)
2006 case SILC_PACKET_NOTIFY:
2008 * Received notify packet. Server can receive notify packets from
2009 * router. Server then relays the notify messages to clients if needed.
2011 SILC_LOG_DEBUG(("Notify packet"));
2012 if (packet->flags & SILC_PACKET_FLAG_LIST)
2013 silc_server_notify_list(server, sock, packet);
2015 silc_server_notify(server, sock, packet);
2021 case SILC_PACKET_CHANNEL_MESSAGE:
2023 * Received channel message. Channel messages are special packets
2024 * (although probably most common ones) thus they are handled
2027 SILC_LOG_DEBUG(("Channel Message packet"));
2028 if (packet->flags & SILC_PACKET_FLAG_LIST)
2030 idata->last_receive = time(NULL);
2031 silc_server_channel_message(server, sock, packet);
2034 case SILC_PACKET_CHANNEL_KEY:
2036 * Received key for channel. As channels are created by the router
2037 * the keys are as well. We will distribute the key to all of our
2038 * locally connected clients on the particular channel. Router
2039 * never receives this channel and thus is ignored.
2041 SILC_LOG_DEBUG(("Channel Key packet"));
2042 if (packet->flags & SILC_PACKET_FLAG_LIST)
2044 silc_server_channel_key(server, sock, packet);
2050 case SILC_PACKET_COMMAND:
2052 * Recived command. Processes the command request and allocates the
2053 * command context and calls the command.
2055 SILC_LOG_DEBUG(("Command packet"));
2056 if (packet->flags & SILC_PACKET_FLAG_LIST)
2058 silc_server_command_process(server, sock, packet);
2061 case SILC_PACKET_COMMAND_REPLY:
2063 * Received command reply packet. Received command reply to command. It
2064 * may be reply to command sent by us or reply to command sent by client
2065 * that we've routed further.
2067 SILC_LOG_DEBUG(("Command Reply packet"));
2068 if (packet->flags & SILC_PACKET_FLAG_LIST)
2070 silc_server_command_reply(server, sock, packet);
2074 * Private Message packets
2076 case SILC_PACKET_PRIVATE_MESSAGE:
2078 * Received private message packet. The packet is coming from either
2081 SILC_LOG_DEBUG(("Private Message packet"));
2082 if (packet->flags & SILC_PACKET_FLAG_LIST)
2084 idata->last_receive = time(NULL);
2085 silc_server_private_message(server, sock, packet);
2088 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2090 * Private message key packet.
2092 if (packet->flags & SILC_PACKET_FLAG_LIST)
2094 silc_server_private_message_key(server, sock, packet);
2098 * Key Exchange protocol packets
2100 case SILC_PACKET_KEY_EXCHANGE:
2101 SILC_LOG_DEBUG(("KE packet"));
2102 if (packet->flags & SILC_PACKET_FLAG_LIST)
2105 if (sock->protocol && sock->protocol->protocol &&
2106 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2107 SilcServerKEInternalContext *proto_ctx =
2108 (SilcServerKEInternalContext *)sock->protocol->context;
2110 proto_ctx->packet = silc_packet_context_dup(packet);
2112 /* Let the protocol handle the packet */
2113 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2115 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2116 "protocol active, packet dropped."));
2120 case SILC_PACKET_KEY_EXCHANGE_1:
2121 SILC_LOG_DEBUG(("KE 1 packet"));
2122 if (packet->flags & SILC_PACKET_FLAG_LIST)
2125 if (sock->protocol && sock->protocol->protocol &&
2126 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2127 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2129 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2130 SilcServerRekeyInternalContext *proto_ctx =
2131 (SilcServerRekeyInternalContext *)sock->protocol->context;
2133 if (proto_ctx->packet)
2134 silc_packet_context_free(proto_ctx->packet);
2136 proto_ctx->packet = silc_packet_context_dup(packet);
2138 /* Let the protocol handle the packet */
2139 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2141 SilcServerKEInternalContext *proto_ctx =
2142 (SilcServerKEInternalContext *)sock->protocol->context;
2144 if (proto_ctx->packet)
2145 silc_packet_context_free(proto_ctx->packet);
2147 proto_ctx->packet = silc_packet_context_dup(packet);
2148 proto_ctx->dest_id_type = packet->src_id_type;
2149 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2150 packet->src_id_type);
2151 if (!proto_ctx->dest_id)
2154 /* Let the protocol handle the packet */
2155 silc_protocol_execute(sock->protocol, server->schedule,
2159 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2160 "protocol active, packet dropped."));
2164 case SILC_PACKET_KEY_EXCHANGE_2:
2165 SILC_LOG_DEBUG(("KE 2 packet"));
2166 if (packet->flags & SILC_PACKET_FLAG_LIST)
2169 if (sock->protocol && sock->protocol->protocol &&
2170 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2171 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2173 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2174 SilcServerRekeyInternalContext *proto_ctx =
2175 (SilcServerRekeyInternalContext *)sock->protocol->context;
2177 if (proto_ctx->packet)
2178 silc_packet_context_free(proto_ctx->packet);
2180 proto_ctx->packet = silc_packet_context_dup(packet);
2182 /* Let the protocol handle the packet */
2183 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2185 SilcServerKEInternalContext *proto_ctx =
2186 (SilcServerKEInternalContext *)sock->protocol->context;
2188 if (proto_ctx->packet)
2189 silc_packet_context_free(proto_ctx->packet);
2191 proto_ctx->packet = silc_packet_context_dup(packet);
2192 proto_ctx->dest_id_type = packet->src_id_type;
2193 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2194 packet->src_id_type);
2195 if (!proto_ctx->dest_id)
2198 /* Let the protocol handle the packet */
2199 silc_protocol_execute(sock->protocol, server->schedule,
2203 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2204 "protocol active, packet dropped."));
2208 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2210 * Connection authentication request packet. When we receive this packet
2211 * we will send to the other end information about our mandatory
2212 * authentication method for the connection. This packet maybe received
2215 SILC_LOG_DEBUG(("Connection authentication request packet"));
2216 if (packet->flags & SILC_PACKET_FLAG_LIST)
2218 silc_server_connection_auth_request(server, sock, packet);
2222 * Connection Authentication protocol packets
2224 case SILC_PACKET_CONNECTION_AUTH:
2225 /* Start of the authentication protocol. We receive here the
2226 authentication data and will verify it. */
2227 SILC_LOG_DEBUG(("Connection auth packet"));
2228 if (packet->flags & SILC_PACKET_FLAG_LIST)
2231 if (sock->protocol && sock->protocol->protocol->type
2232 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2234 SilcServerConnAuthInternalContext *proto_ctx =
2235 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2237 proto_ctx->packet = silc_packet_context_dup(packet);
2239 /* Let the protocol handle the packet */
2240 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2242 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2243 "protocol active, packet dropped."));
2247 case SILC_PACKET_NEW_ID:
2249 * Received New ID packet. This includes some new ID that has been
2250 * created. It may be for client, server or channel. This is the way
2251 * to distribute information about new registered entities in the
2254 SILC_LOG_DEBUG(("New ID packet"));
2255 if (packet->flags & SILC_PACKET_FLAG_LIST)
2256 silc_server_new_id_list(server, sock, packet);
2258 silc_server_new_id(server, sock, packet);
2261 case SILC_PACKET_NEW_CLIENT:
2263 * Received new client packet. This includes client information that
2264 * we will use to create initial client ID. After creating new
2265 * ID we will send it to the client.
2267 SILC_LOG_DEBUG(("New Client packet"));
2268 if (packet->flags & SILC_PACKET_FLAG_LIST)
2270 silc_server_new_client(server, sock, packet);
2273 case SILC_PACKET_NEW_SERVER:
2275 * Received new server packet. This includes Server ID and some other
2276 * information that we may save. This is received after server has
2279 SILC_LOG_DEBUG(("New Server packet"));
2280 if (packet->flags & SILC_PACKET_FLAG_LIST)
2282 silc_server_new_server(server, sock, packet);
2285 case SILC_PACKET_NEW_CHANNEL:
2287 * Received new channel packet. Information about new channel in the
2288 * network are distributed using this packet.
2290 SILC_LOG_DEBUG(("New Channel packet"));
2291 if (packet->flags & SILC_PACKET_FLAG_LIST)
2292 silc_server_new_channel_list(server, sock, packet);
2294 silc_server_new_channel(server, sock, packet);
2297 case SILC_PACKET_HEARTBEAT:
2299 * Received heartbeat.
2301 SILC_LOG_DEBUG(("Heartbeat packet"));
2302 if (packet->flags & SILC_PACKET_FLAG_LIST)
2306 case SILC_PACKET_KEY_AGREEMENT:
2308 * Received heartbeat.
2310 SILC_LOG_DEBUG(("Key agreement packet"));
2311 if (packet->flags & SILC_PACKET_FLAG_LIST)
2313 silc_server_key_agreement(server, sock, packet);
2316 case SILC_PACKET_REKEY:
2318 * Received re-key packet. The sender wants to regenerate the session
2321 SILC_LOG_DEBUG(("Re-key packet"));
2322 if (packet->flags & SILC_PACKET_FLAG_LIST)
2324 silc_server_rekey(server, sock, packet);
2327 case SILC_PACKET_REKEY_DONE:
2329 * The re-key is done.
2331 SILC_LOG_DEBUG(("Re-key done packet"));
2332 if (packet->flags & SILC_PACKET_FLAG_LIST)
2335 if (sock->protocol && sock->protocol->protocol &&
2336 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2338 SilcServerRekeyInternalContext *proto_ctx =
2339 (SilcServerRekeyInternalContext *)sock->protocol->context;
2341 if (proto_ctx->packet)
2342 silc_packet_context_free(proto_ctx->packet);
2344 proto_ctx->packet = silc_packet_context_dup(packet);
2346 /* Let the protocol handle the packet */
2347 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2349 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2350 "protocol active, packet dropped."));
2354 case SILC_PACKET_FTP:
2356 SILC_LOG_DEBUG(("FTP packet"));
2357 if (packet->flags & SILC_PACKET_FLAG_LIST)
2359 silc_server_ftp(server, sock, packet);
2362 case SILC_PACKET_RESUME_ROUTER:
2363 /* Resume router packet received. This packet is received for backup
2364 router resuming protocol. */
2365 SILC_LOG_DEBUG(("Resume router packet"));
2366 if (packet->flags & SILC_PACKET_FLAG_LIST)
2368 silc_server_backup_resume_router(server, sock, packet);
2372 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2378 /* Creates connection to a remote router. */
2380 void silc_server_create_connection(SilcServer server,
2381 const char *remote_host, SilcUInt32 port)
2383 SilcServerConnection sconn;
2385 /* Allocate connection object for hold connection specific stuff. */
2386 sconn = silc_calloc(1, sizeof(*sconn));
2387 sconn->server = server;
2388 sconn->remote_host = strdup(remote_host);
2389 sconn->remote_port = port;
2390 sconn->no_reconnect = TRUE;
2392 silc_schedule_task_add(server->schedule, 0,
2393 silc_server_connect_router,
2394 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2395 SILC_TASK_PRI_NORMAL);
2398 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2400 silc_socket_free((SilcSocketConnection)context);
2403 /* Closes connection to socket connection */
2405 void silc_server_close_connection(SilcServer server,
2406 SilcSocketConnection sock)
2408 if (!server->sockets[sock->sock])
2411 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2413 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2414 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2415 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2418 /* We won't listen for this connection anymore */
2419 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2421 /* Unregister all tasks */
2422 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2424 /* Close the actual connection */
2425 silc_net_close_connection(sock->sock);
2426 server->sockets[sock->sock] = NULL;
2428 /* If sock->user_data is NULL then we'll check for active protocols
2429 here since the silc_server_free_sock_user_data has not been called
2430 for this connection. */
2431 if (!sock->user_data) {
2432 /* If any protocol is active cancel its execution. It will call
2433 the final callback which will finalize the disconnection. */
2434 if (sock->protocol) {
2435 silc_protocol_cancel(sock->protocol, server->schedule);
2436 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2437 silc_protocol_execute_final(sock->protocol, server->schedule);
2438 sock->protocol = NULL;
2443 silc_schedule_task_add(server->schedule, 0,
2444 silc_server_close_connection_final,
2445 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2446 SILC_TASK_PRI_NORMAL);
2449 /* Sends disconnect message to remote connection and disconnects the
2452 void silc_server_disconnect_remote(SilcServer server,
2453 SilcSocketConnection sock,
2454 const char *fmt, ...)
2457 unsigned char buf[4096];
2462 memset(buf, 0, sizeof(buf));
2464 vsprintf(buf, fmt, ap);
2467 SILC_LOG_DEBUG(("Disconnecting remote host"));
2469 /* Notify remote end that the conversation is over. The notify message
2470 is tried to be sent immediately. */
2471 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2472 buf, strlen(buf), TRUE);
2473 silc_server_packet_queue_purge(server, sock);
2475 /* Mark the connection to be disconnected */
2476 SILC_SET_DISCONNECTED(sock);
2477 silc_server_close_connection(server, sock);
2482 SilcClientEntry client;
2483 } *FreeClientInternal;
2485 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2487 FreeClientInternal i = (FreeClientInternal)context;
2489 silc_idlist_del_data(i->client);
2490 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2494 /* Frees client data and notifies about client's signoff. */
2496 void silc_server_free_client_data(SilcServer server,
2497 SilcSocketConnection sock,
2498 SilcClientEntry client,
2500 const char *signoff)
2502 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2504 /* If there is pending outgoing data for the client then purge it
2505 to the network before removing the client entry. */
2506 silc_server_packet_queue_purge(server, sock);
2511 /* Send SIGNOFF notify to routers. */
2512 if (notify && !server->standalone && server->router)
2513 silc_server_send_notify_signoff(server, server->router->connection,
2514 server->server_type == SILC_SERVER ?
2515 FALSE : TRUE, client->id, signoff);
2517 /* Remove client from all channels */
2519 silc_server_remove_from_channels(server, NULL, client,
2520 TRUE, (char *)signoff, TRUE);
2522 silc_server_remove_from_channels(server, NULL, client,
2523 FALSE, NULL, FALSE);
2525 /* Update statistics */
2526 server->stat.my_clients--;
2527 server->stat.clients--;
2528 if (server->server_type == SILC_ROUTER)
2529 server->stat.cell_clients--;
2530 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2531 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2533 /* We will not delete the client entry right away. We will take it
2534 into history (for WHOWAS command) for 5 minutes */
2537 silc_schedule_task_add(server->schedule, 0,
2538 silc_server_free_client_data_timeout,
2540 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2541 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2542 client->router = NULL;
2543 client->connection = NULL;
2547 /* Frees user_data pointer from socket connection object. This also sends
2548 appropriate notify packets to the network to inform about leaving
2551 void silc_server_free_sock_user_data(SilcServer server,
2552 SilcSocketConnection sock,
2553 const char *signoff_message)
2555 SILC_LOG_DEBUG(("Start"));
2557 switch (sock->type) {
2558 case SILC_SOCKET_TYPE_CLIENT:
2560 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2561 silc_server_free_client_data(server, sock, user_data, TRUE,
2565 case SILC_SOCKET_TYPE_SERVER:
2566 case SILC_SOCKET_TYPE_ROUTER:
2568 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2569 SilcServerEntry backup_router = NULL;
2572 backup_router = silc_server_backup_get(server, user_data->id);
2574 /* If this was our primary router connection then we're lost to
2575 the outside world. */
2576 if (server->router == user_data) {
2577 /* Check whether we have a backup router connection */
2578 if (!backup_router || backup_router == user_data) {
2579 silc_schedule_task_add(server->schedule, 0,
2580 silc_server_connect_to_router,
2583 SILC_TASK_PRI_NORMAL);
2585 server->id_entry->router = NULL;
2586 server->router = NULL;
2587 server->standalone = TRUE;
2588 backup_router = NULL;
2590 SILC_LOG_INFO(("New primary router is backup router %s",
2591 backup_router->server_name));
2592 SILC_LOG_DEBUG(("New primary router is backup router %s",
2593 backup_router->server_name));
2594 server->id_entry->router = backup_router;
2595 server->router = backup_router;
2596 server->router_connect = time(0);
2597 server->backup_primary = TRUE;
2598 if (server->server_type == SILC_BACKUP_ROUTER) {
2599 server->server_type = SILC_ROUTER;
2601 /* We'll need to constantly try to reconnect to the primary
2602 router so that we'll see when it comes back online. */
2603 silc_server_backup_reconnect(server, sock->ip, sock->port,
2604 silc_server_backup_connected,
2608 /* Mark this connection as replaced */
2609 silc_server_backup_replaced_add(server, user_data->id,
2612 } else if (backup_router) {
2613 SILC_LOG_INFO(("Enabling the use of backup router %s",
2614 backup_router->server_name));
2615 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2616 backup_router->server_name));
2618 /* Mark this connection as replaced */
2619 silc_server_backup_replaced_add(server, user_data->id,
2623 if (!backup_router) {
2624 /* Free all client entries that this server owns as they will
2625 become invalid now as well. */
2627 silc_server_remove_clients_by_server(server, user_data, TRUE);
2628 if (server->server_type == SILC_SERVER)
2629 silc_server_remove_channels_by_server(server, user_data);
2631 /* Update the client entries of this server to the new backup
2632 router. This also removes the clients that *really* was owned
2633 by the primary router and went down with the router. */
2634 silc_server_update_clients_by_server(server, user_data, backup_router,
2636 silc_server_update_servers_by_server(server, user_data, backup_router);
2637 if (server->server_type == SILC_SERVER)
2638 silc_server_update_channels_by_server(server, user_data,
2642 /* Free the server entry */
2643 silc_server_backup_del(server, user_data);
2644 silc_server_backup_replaced_del(server, user_data);
2645 silc_idlist_del_data(user_data);
2646 if (!silc_idlist_del_server(server->local_list, user_data))
2647 silc_idlist_del_server(server->global_list, user_data);
2648 server->stat.my_servers--;
2649 server->stat.servers--;
2650 if (server->server_type == SILC_ROUTER)
2651 server->stat.cell_servers--;
2653 if (backup_router) {
2654 /* Announce all of our stuff that was created about 5 minutes ago.
2655 The backup router knows all the other stuff already. */
2656 if (server->server_type == SILC_ROUTER)
2657 silc_server_announce_servers(server, FALSE, time(0) - 300,
2658 backup_router->connection);
2660 /* Announce our clients and channels to the router */
2661 silc_server_announce_clients(server, time(0) - 300,
2662 backup_router->connection);
2663 silc_server_announce_channels(server, time(0) - 300,
2664 backup_router->connection);
2670 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2672 silc_idlist_del_data(user_data);
2673 silc_free(user_data);
2678 /* If any protocol is active cancel its execution */
2679 if (sock->protocol) {
2680 silc_protocol_cancel(sock->protocol, server->schedule);
2681 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2682 silc_protocol_execute_final(sock->protocol, server->schedule);
2683 sock->protocol = NULL;
2686 sock->user_data = NULL;
2689 /* Removes client from all channels it has joined. This is used when client
2690 connection is disconnected. If the client on a channel is last, the
2691 channel is removed as well. This sends the SIGNOFF notify types. */
2693 void silc_server_remove_from_channels(SilcServer server,
2694 SilcSocketConnection sock,
2695 SilcClientEntry client,
2697 char *signoff_message,
2700 SilcChannelEntry channel;
2701 SilcChannelClientEntry chl;
2702 SilcHashTableList htl;
2705 SILC_LOG_DEBUG(("Start"));
2707 if (!client || !client->id)
2710 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2712 /* Remove the client from all channels. The client is removed from
2713 the channels' user list. */
2714 silc_hash_table_list(client->channels, &htl);
2715 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2716 channel = chl->channel;
2718 /* Remove channel from client's channel list */
2719 silc_hash_table_del(client->channels, channel);
2721 /* Remove channel if there is no users anymore */
2722 if (server->server_type == SILC_ROUTER &&
2723 silc_hash_table_count(channel->user_list) < 2) {
2725 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2726 if (silc_idlist_del_channel(server->local_list, channel))
2727 server->stat.my_channels--;
2729 silc_idlist_del_channel(server->global_list, channel);
2733 /* Remove client from channel's client list */
2734 silc_hash_table_del(channel->user_list, chl->client);
2735 channel->user_count--;
2737 /* If there is no global users on the channel anymore mark the channel
2738 as local channel. Do not check if the removed client is local client. */
2739 if (server->server_type != SILC_ROUTER && channel->global_users &&
2740 chl->client->router && !silc_server_channel_has_global(channel))
2741 channel->global_users = FALSE;
2744 server->stat.my_chanclients--;
2746 /* If there is not at least one local user on the channel then we don't
2747 need the channel entry anymore, we can remove it safely. */
2748 if (server->server_type != SILC_ROUTER &&
2749 !silc_server_channel_has_local(channel)) {
2750 /* Notify about leaving client if this channel has global users. */
2751 if (notify && channel->global_users)
2752 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2753 SILC_NOTIFY_TYPE_SIGNOFF,
2754 signoff_message ? 2 : 1,
2755 clidp->data, clidp->len,
2756 signoff_message, signoff_message ?
2757 strlen(signoff_message) : 0);
2760 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2762 if (channel->founder_key) {
2763 /* The founder auth data exists, do not remove the channel entry */
2764 SilcChannelClientEntry chl2;
2765 SilcHashTableList htl2;
2767 channel->disabled = TRUE;
2769 silc_hash_table_list(channel->user_list, &htl2);
2770 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2771 silc_hash_table_del(chl2->client->channels, channel);
2772 silc_hash_table_del(channel->user_list, chl2->client);
2773 channel->user_count--;
2776 silc_hash_table_list_reset(&htl2);
2780 /* Remove the channel entry */
2781 if (silc_idlist_del_channel(server->local_list, channel))
2782 server->stat.my_channels--;
2784 silc_idlist_del_channel(server->global_list, channel);
2788 /* Send notify to channel about client leaving SILC and thus
2789 the entire channel. */
2791 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2792 SILC_NOTIFY_TYPE_SIGNOFF,
2793 signoff_message ? 2 : 1,
2794 clidp->data, clidp->len,
2795 signoff_message, signoff_message ?
2796 strlen(signoff_message) : 0);
2798 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2799 /* Re-generate channel key */
2800 if (!silc_server_create_channel_key(server, channel, 0))
2803 /* Send the channel key to the channel. The key of course is not sent
2804 to the client who was removed from the channel. */
2805 silc_server_send_channel_key(server, client->connection, channel,
2806 server->server_type == SILC_ROUTER ?
2807 FALSE : !server->standalone);
2812 silc_hash_table_list_reset(&htl);
2813 silc_buffer_free(clidp);
2816 /* Removes client from one channel. This is used for example when client
2817 calls LEAVE command to remove itself from the channel. Returns TRUE
2818 if channel still exists and FALSE if the channel is removed when
2819 last client leaves the channel. If `notify' is FALSE notify messages
2822 int silc_server_remove_from_one_channel(SilcServer server,
2823 SilcSocketConnection sock,
2824 SilcChannelEntry channel,
2825 SilcClientEntry client,
2828 SilcChannelClientEntry chl;
2831 SILC_LOG_DEBUG(("Start"));
2833 /* Get the entry to the channel, if this client is not on the channel
2835 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2838 /* Remove the client from the channel. The client is removed from
2839 the channel's user list. */
2841 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2843 /* Remove channel from client's channel list */
2844 silc_hash_table_del(client->channels, chl->channel);
2846 /* Remove channel if there is no users anymore */
2847 if (server->server_type == SILC_ROUTER &&
2848 silc_hash_table_count(channel->user_list) < 2) {
2850 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2851 if (silc_idlist_del_channel(server->local_list, channel))
2852 server->stat.my_channels--;
2854 silc_idlist_del_channel(server->global_list, channel);
2855 silc_buffer_free(clidp);
2859 /* Remove client from channel's client list */
2860 silc_hash_table_del(channel->user_list, chl->client);
2861 channel->user_count--;
2863 /* If there is no global users on the channel anymore mark the channel
2864 as local channel. Do not check if the client is local client. */
2865 if (server->server_type != SILC_ROUTER && channel->global_users &&
2866 chl->client->router && !silc_server_channel_has_global(channel))
2867 channel->global_users = FALSE;
2870 server->stat.my_chanclients--;
2872 /* If there is not at least one local user on the channel then we don't
2873 need the channel entry anymore, we can remove it safely. */
2874 if (server->server_type != SILC_ROUTER &&
2875 !silc_server_channel_has_local(channel)) {
2876 /* Notify about leaving client if this channel has global users. */
2877 if (notify && channel->global_users)
2878 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2879 SILC_NOTIFY_TYPE_LEAVE, 1,
2880 clidp->data, clidp->len);
2882 silc_buffer_free(clidp);
2885 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2887 if (channel->founder_key) {
2888 /* The founder auth data exists, do not remove the channel entry */
2889 SilcChannelClientEntry chl2;
2890 SilcHashTableList htl2;
2892 channel->disabled = TRUE;
2894 silc_hash_table_list(channel->user_list, &htl2);
2895 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2896 silc_hash_table_del(chl2->client->channels, channel);
2897 silc_hash_table_del(channel->user_list, chl2->client);
2898 channel->user_count--;
2901 silc_hash_table_list_reset(&htl2);
2905 /* Remove the channel entry */
2906 if (silc_idlist_del_channel(server->local_list, channel))
2907 server->stat.my_channels--;
2909 silc_idlist_del_channel(server->global_list, channel);
2913 /* Send notify to channel about client leaving the channel */
2915 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2916 SILC_NOTIFY_TYPE_LEAVE, 1,
2917 clidp->data, clidp->len);
2919 silc_buffer_free(clidp);
2923 /* Timeout callback. This is called if connection is idle or for some
2924 other reason is not responding within some period of time. This
2925 disconnects the remote end. */
2927 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2929 SilcServer server = (SilcServer)context;
2930 SilcSocketConnection sock = server->sockets[fd];
2932 SILC_LOG_DEBUG(("Start"));
2937 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2938 sock->hostname, sock->ip));
2940 /* If we have protocol active we must assure that we call the protocol's
2941 final callback so that all the memory is freed. */
2942 if (sock->protocol) {
2943 silc_protocol_cancel(sock->protocol, server->schedule);
2944 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2945 silc_protocol_execute_final(sock->protocol, server->schedule);
2946 sock->protocol = NULL;
2950 if (sock->user_data)
2951 silc_server_free_sock_user_data(server, sock, NULL);
2953 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2954 "Connection timeout");
2957 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2958 function may be used only by router. In real SILC network all channels
2959 are created by routers thus this function is never used by normal
2962 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2963 SilcServerID *router_id,
2969 SilcChannelID *channel_id;
2970 SilcChannelEntry entry;
2974 SILC_LOG_DEBUG(("Creating new channel"));
2977 cipher = SILC_DEFAULT_CIPHER;
2979 hmac = SILC_DEFAULT_HMAC;
2981 /* Allocate cipher */
2982 if (!silc_cipher_alloc(cipher, &key))
2986 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2987 silc_cipher_free(key);
2991 channel_name = strdup(channel_name);
2993 /* Create the channel ID */
2994 if (!silc_id_create_channel_id(server, router_id, server->rng,
2996 silc_free(channel_name);
2997 silc_cipher_free(key);
2998 silc_hmac_free(newhmac);
3002 /* Create the channel */
3003 entry = silc_idlist_add_channel(server->local_list, channel_name,
3004 SILC_CHANNEL_MODE_NONE, channel_id,
3005 NULL, key, newhmac, 0);
3007 silc_free(channel_name);
3008 silc_cipher_free(key);
3009 silc_hmac_free(newhmac);
3010 silc_free(channel_id);
3014 entry->cipher = strdup(cipher);
3015 entry->hmac_name = strdup(hmac);
3017 /* Now create the actual key material */
3018 if (!silc_server_create_channel_key(server, entry,
3019 silc_cipher_get_key_len(key) / 8)) {
3020 silc_idlist_del_channel(server->local_list, entry);
3024 /* Notify other routers about the new channel. We send the packet
3025 to our primary route. */
3026 if (broadcast && server->standalone == FALSE)
3027 silc_server_send_new_channel(server, server->router->connection, TRUE,
3028 channel_name, entry->id,
3029 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3032 server->stat.my_channels++;
3037 /* Same as above but creates the channel with Channel ID `channel_id. */
3040 silc_server_create_new_channel_with_id(SilcServer server,
3044 SilcChannelID *channel_id,
3047 SilcChannelEntry entry;
3051 SILC_LOG_DEBUG(("Creating new channel"));
3054 cipher = SILC_DEFAULT_CIPHER;
3056 hmac = SILC_DEFAULT_HMAC;
3058 /* Allocate cipher */
3059 if (!silc_cipher_alloc(cipher, &key))
3063 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3064 silc_cipher_free(key);
3068 channel_name = strdup(channel_name);
3070 /* Create the channel */
3071 entry = silc_idlist_add_channel(server->local_list, channel_name,
3072 SILC_CHANNEL_MODE_NONE, channel_id,
3073 NULL, key, newhmac, 0);
3075 silc_cipher_free(key);
3076 silc_hmac_free(newhmac);
3077 silc_free(channel_name);
3081 /* Now create the actual key material */
3082 if (!silc_server_create_channel_key(server, entry,
3083 silc_cipher_get_key_len(key) / 8)) {
3084 silc_idlist_del_channel(server->local_list, entry);
3088 /* Notify other routers about the new channel. We send the packet
3089 to our primary route. */
3090 if (broadcast && server->standalone == FALSE)
3091 silc_server_send_new_channel(server, server->router->connection, TRUE,
3092 channel_name, entry->id,
3093 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3096 server->stat.my_channels++;
3101 /* Channel's key re-key timeout callback. */
3103 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3105 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3106 SilcServer server = (SilcServer)rekey->context;
3110 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3113 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3116 /* Generates new channel key. This is used to create the initial channel key
3117 but also to re-generate new key for channel. If `key_len' is provided
3118 it is the bytes of the key length. */
3120 bool silc_server_create_channel_key(SilcServer server,
3121 SilcChannelEntry channel,
3125 unsigned char channel_key[32], hash[32];
3128 SILC_LOG_DEBUG(("Generating channel key"));
3130 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3131 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3135 if (!channel->channel_key)
3136 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3137 channel->channel_key = NULL;
3143 else if (channel->key_len)
3144 len = channel->key_len / 8;
3146 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3148 /* Create channel key */
3149 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3152 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3154 /* Remove old key if exists */
3156 memset(channel->key, 0, channel->key_len / 8);
3157 silc_free(channel->key);
3161 channel->key_len = len * 8;
3162 channel->key = silc_memdup(channel_key, len);
3163 memset(channel_key, 0, sizeof(channel_key));
3165 /* Generate HMAC key from the channel key data and set it */
3167 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3168 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3169 silc_hmac_set_key(channel->hmac, hash,
3170 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3171 memset(hash, 0, sizeof(hash));
3173 if (server->server_type == SILC_ROUTER) {
3174 if (!channel->rekey)
3175 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3176 channel->rekey->context = (void *)server;
3177 channel->rekey->channel = channel;
3178 channel->rekey->key_len = key_len;
3179 if (channel->rekey->task)
3180 silc_schedule_task_del(server->schedule, channel->rekey->task);
3182 channel->rekey->task =
3183 silc_schedule_task_add(server->schedule, 0,
3184 silc_server_channel_key_rekey,
3185 (void *)channel->rekey,
3186 server->config->channel_rekey_secs, 0,
3188 SILC_TASK_PRI_NORMAL);
3194 /* Saves the channel key found in the encoded `key_payload' buffer. This
3195 function is used when we receive Channel Key Payload and also when we're
3196 processing JOIN command reply. Returns entry to the channel. */
3198 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3199 SilcBuffer key_payload,
3200 SilcChannelEntry channel)
3202 SilcChannelKeyPayload payload = NULL;
3203 SilcChannelID *id = NULL;
3204 unsigned char *tmp, hash[32];
3208 SILC_LOG_DEBUG(("Start"));
3210 /* Decode channel key payload */
3211 payload = silc_channel_key_payload_parse(key_payload->data,
3214 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3219 /* Get the channel entry */
3222 /* Get channel ID */
3223 tmp = silc_channel_key_get_id(payload, &tmp_len);
3224 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3230 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3232 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3234 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3235 silc_id_render(id, SILC_ID_CHANNEL)));
3241 tmp = silc_channel_key_get_key(payload, &tmp_len);
3247 cipher = silc_channel_key_get_cipher(payload, NULL);
3253 /* Remove old key if exists */
3255 memset(channel->key, 0, channel->key_len / 8);
3256 silc_free(channel->key);
3257 silc_cipher_free(channel->channel_key);
3260 /* Create new cipher */
3261 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3262 channel->channel_key = NULL;
3267 if (channel->cipher)
3268 silc_free(channel->cipher);
3269 channel->cipher = strdup(cipher);
3272 channel->key_len = tmp_len * 8;
3273 channel->key = silc_memdup(tmp, tmp_len);
3274 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3276 /* Generate HMAC key from the channel key data and set it */
3278 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3279 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3280 silc_hmac_set_key(channel->hmac, hash,
3281 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3283 memset(hash, 0, sizeof(hash));
3284 memset(tmp, 0, tmp_len);
3286 if (server->server_type == SILC_ROUTER) {
3287 if (!channel->rekey)
3288 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3289 channel->rekey->context = (void *)server;
3290 channel->rekey->channel = channel;
3291 if (channel->rekey->task)
3292 silc_schedule_task_del(server->schedule, channel->rekey->task);
3294 channel->rekey->task =
3295 silc_schedule_task_add(server->schedule, 0,
3296 silc_server_channel_key_rekey,
3297 (void *)channel->rekey,
3298 server->config->channel_rekey_secs, 0,
3300 SILC_TASK_PRI_NORMAL);
3306 silc_channel_key_payload_free(payload);
3311 /* Heartbeat callback. This function is set as argument for the
3312 silc_socket_set_heartbeat function. The library will call this function
3313 at the set time interval. */
3315 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3318 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3320 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3322 /* Send the heartbeat */
3323 silc_server_send_heartbeat(hb->server, sock);
3326 /* Returns assembled of all servers in the given ID list. The packet's
3327 form is dictated by the New ID payload. */
3329 static void silc_server_announce_get_servers(SilcServer server,
3330 SilcServerEntry remote,
3332 SilcBuffer *servers,
3333 unsigned long creation_time)
3335 SilcIDCacheList list;
3336 SilcIDCacheEntry id_cache;
3337 SilcServerEntry entry;
3340 /* Go through all clients in the list */
3341 if (silc_idcache_get_all(id_list->servers, &list)) {
3342 if (silc_idcache_list_first(list, &id_cache)) {
3344 entry = (SilcServerEntry)id_cache->context;
3346 /* Do not announce the one we've sending our announcements and
3347 do not announce ourself. Also check the creation time if it's
3349 if ((entry == remote) || (entry == server->id_entry) ||
3350 (creation_time && entry->data.created < creation_time)) {
3351 if (!silc_idcache_list_next(list, &id_cache))
3356 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3358 *servers = silc_buffer_realloc(*servers,
3360 (*servers)->truelen + idp->len :
3362 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3363 silc_buffer_put(*servers, idp->data, idp->len);
3364 silc_buffer_pull(*servers, idp->len);
3365 silc_buffer_free(idp);
3367 if (!silc_idcache_list_next(list, &id_cache))
3372 silc_idcache_list_free(list);
3377 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3383 p = silc_notify_payload_encode(notify, argc, ap);
3389 /* This function is used by router to announce existing servers to our
3390 primary router when we've connected to it. If `creation_time' is non-zero
3391 then only the servers that has been created after the `creation_time'
3392 will be announced. */
3394 void silc_server_announce_servers(SilcServer server, bool global,
3395 unsigned long creation_time,
3396 SilcSocketConnection remote)
3398 SilcBuffer servers = NULL;
3400 SILC_LOG_DEBUG(("Announcing servers"));
3402 /* Get servers in local list */
3403 silc_server_announce_get_servers(server, remote->user_data,
3404 server->local_list, &servers,
3408 /* Get servers in global list */
3409 silc_server_announce_get_servers(server, remote->user_data,
3410 server->global_list, &servers,
3414 silc_buffer_push(servers, servers->data - servers->head);
3415 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3417 /* Send the packet */
3418 silc_server_packet_send(server, remote,
3419 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3420 servers->data, servers->len, TRUE);
3422 silc_buffer_free(servers);
3426 /* Returns assembled packet of all clients in the given ID list. The
3427 packet's form is dictated by the New ID Payload. */
3429 static void silc_server_announce_get_clients(SilcServer server,
3431 SilcBuffer *clients,
3433 unsigned long creation_time)
3435 SilcIDCacheList list;
3436 SilcIDCacheEntry id_cache;
3437 SilcClientEntry client;
3440 unsigned char mode[4];
3442 /* Go through all clients in the list */
3443 if (silc_idcache_get_all(id_list->clients, &list)) {
3444 if (silc_idcache_list_first(list, &id_cache)) {
3446 client = (SilcClientEntry)id_cache->context;
3448 if (creation_time && client->data.created < creation_time) {
3449 if (!silc_idcache_list_next(list, &id_cache))
3454 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3456 *clients = silc_buffer_realloc(*clients,
3458 (*clients)->truelen + idp->len :
3460 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3461 silc_buffer_put(*clients, idp->data, idp->len);
3462 silc_buffer_pull(*clients, idp->len);
3464 SILC_PUT32_MSB(client->mode, mode);
3465 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3466 2, idp->data, idp->len,
3468 *umodes = silc_buffer_realloc(*umodes,
3470 (*umodes)->truelen + tmp->len :
3472 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3473 silc_buffer_put(*umodes, tmp->data, tmp->len);
3474 silc_buffer_pull(*umodes, tmp->len);
3475 silc_buffer_free(tmp);
3477 silc_buffer_free(idp);
3479 if (!silc_idcache_list_next(list, &id_cache))
3484 silc_idcache_list_free(list);
3488 /* This function is used to announce our existing clients to our router
3489 when we've connected to it. If `creation_time' is non-zero then only
3490 the clients that has been created after the `creation_time' will be
3493 void silc_server_announce_clients(SilcServer server,
3494 unsigned long creation_time,
3495 SilcSocketConnection remote)
3497 SilcBuffer clients = NULL;
3498 SilcBuffer umodes = NULL;
3500 SILC_LOG_DEBUG(("Announcing clients"));
3502 /* Get clients in local list */
3503 silc_server_announce_get_clients(server, server->local_list,
3504 &clients, &umodes, creation_time);
3506 /* As router we announce our global list as well */
3507 if (server->server_type == SILC_ROUTER)
3508 silc_server_announce_get_clients(server, server->global_list,
3509 &clients, &umodes, creation_time);
3512 silc_buffer_push(clients, clients->data - clients->head);
3513 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3515 /* Send the packet */
3516 silc_server_packet_send(server, remote,
3517 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3518 clients->data, clients->len, TRUE);
3520 silc_buffer_free(clients);
3524 silc_buffer_push(umodes, umodes->data - umodes->head);
3525 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3527 /* Send the packet */
3528 silc_server_packet_send(server, remote,
3529 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3530 umodes->data, umodes->len, TRUE);
3532 silc_buffer_free(umodes);
3536 /* Returns channel's topic for announcing it */
3538 void silc_server_announce_get_channel_topic(SilcServer server,
3539 SilcChannelEntry channel,
3544 if (channel->topic) {
3545 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3546 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3547 chidp->data, chidp->len,
3549 strlen(channel->topic));
3550 silc_buffer_free(chidp);
3554 /* Returns assembled packets for channel users of the `channel'. */
3556 void silc_server_announce_get_channel_users(SilcServer server,
3557 SilcChannelEntry channel,
3558 SilcBuffer *channel_users,
3559 SilcBuffer *channel_users_modes)
3561 SilcChannelClientEntry chl;
3562 SilcHashTableList htl;
3563 SilcBuffer chidp, clidp;
3566 unsigned char mode[4];
3568 SILC_LOG_DEBUG(("Start"));
3570 /* Now find all users on the channel */
3571 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3572 silc_hash_table_list(channel->user_list, &htl);
3573 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3574 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3577 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3578 clidp->data, clidp->len,
3579 chidp->data, chidp->len);
3582 silc_buffer_realloc(*channel_users,
3584 (*channel_users)->truelen + len : len));
3585 silc_buffer_pull_tail(*channel_users,
3586 ((*channel_users)->end -
3587 (*channel_users)->data));
3589 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3590 silc_buffer_pull(*channel_users, len);
3591 silc_buffer_free(tmp);
3593 /* CUMODE notify for mode change on the channel */
3594 SILC_PUT32_MSB(chl->mode, mode);
3595 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3596 3, clidp->data, clidp->len,
3598 clidp->data, clidp->len);
3600 *channel_users_modes =
3601 silc_buffer_realloc(*channel_users_modes,
3602 (*channel_users_modes ?
3603 (*channel_users_modes)->truelen + len : len));
3604 silc_buffer_pull_tail(*channel_users_modes,
3605 ((*channel_users_modes)->end -
3606 (*channel_users_modes)->data));
3608 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3609 silc_buffer_pull(*channel_users_modes, len);
3610 silc_buffer_free(tmp);
3612 silc_buffer_free(clidp);
3614 silc_hash_table_list_reset(&htl);
3615 silc_buffer_free(chidp);
3618 /* Returns assembled packets for all channels and users on those channels
3619 from the given ID List. The packets are in the form dictated by the
3620 New Channel and New Channel User payloads. */
3622 void silc_server_announce_get_channels(SilcServer server,
3624 SilcBuffer *channels,
3625 SilcBuffer *channel_users,
3626 SilcBuffer **channel_users_modes,
3627 SilcUInt32 *channel_users_modes_c,
3628 SilcBuffer **channel_topics,
3629 SilcChannelID ***channel_ids,
3630 unsigned long creation_time)
3632 SilcIDCacheList list;
3633 SilcIDCacheEntry id_cache;
3634 SilcChannelEntry channel;
3637 SilcUInt16 name_len;
3639 int i = *channel_users_modes_c;
3642 SILC_LOG_DEBUG(("Start"));
3644 /* Go through all channels in the list */
3645 if (silc_idcache_get_all(id_list->channels, &list)) {
3646 if (silc_idcache_list_first(list, &id_cache)) {
3648 channel = (SilcChannelEntry)id_cache->context;
3650 if (creation_time && channel->created < creation_time)
3655 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3656 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3657 name_len = strlen(channel->channel_name);
3660 len = 4 + name_len + id_len + 4;
3662 silc_buffer_realloc(*channels,
3663 (*channels ? (*channels)->truelen +
3665 silc_buffer_pull_tail(*channels,
3666 ((*channels)->end - (*channels)->data));
3667 silc_buffer_format(*channels,
3668 SILC_STR_UI_SHORT(name_len),
3669 SILC_STR_UI_XNSTRING(channel->channel_name,
3671 SILC_STR_UI_SHORT(id_len),
3672 SILC_STR_UI_XNSTRING(cid, id_len),
3673 SILC_STR_UI_INT(channel->mode),
3675 silc_buffer_pull(*channels, len);
3678 /* Channel user modes */
3679 *channel_users_modes = silc_realloc(*channel_users_modes,
3680 sizeof(**channel_users_modes) *
3682 (*channel_users_modes)[i] = NULL;
3683 *channel_ids = silc_realloc(*channel_ids,
3684 sizeof(**channel_ids) * (i + 1));
3685 (*channel_ids)[i] = NULL;
3686 silc_server_announce_get_channel_users(server, channel,
3688 &(*channel_users_modes)[i]);
3689 (*channel_ids)[i] = channel->id;
3691 /* Channel's topic */
3692 *channel_topics = silc_realloc(*channel_topics,
3693 sizeof(**channel_topics) * (i + 1));
3694 (*channel_topics)[i] = NULL;
3695 silc_server_announce_get_channel_topic(server, channel,
3696 &(*channel_topics)[i]);
3699 if (!silc_idcache_list_next(list, &id_cache))
3703 *channel_users_modes_c += i;
3706 silc_idcache_list_free(list);
3710 /* This function is used to announce our existing channels to our router
3711 when we've connected to it. This also announces the users on the
3712 channels to the router. If the `creation_time' is non-zero only the
3713 channels that was created after the `creation_time' are announced.
3714 Note that the channel users are still announced even if the `creation_time'
3717 void silc_server_announce_channels(SilcServer server,
3718 unsigned long creation_time,
3719 SilcSocketConnection remote)
3721 SilcBuffer channels = NULL, channel_users = NULL;
3722 SilcBuffer *channel_users_modes = NULL;
3723 SilcBuffer *channel_topics = NULL;
3724 SilcUInt32 channel_users_modes_c = 0;
3725 SilcChannelID **channel_ids = NULL;
3727 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3729 /* Get channels and channel users in local list */
3730 silc_server_announce_get_channels(server, server->local_list,
3731 &channels, &channel_users,
3732 &channel_users_modes,
3733 &channel_users_modes_c,
3735 &channel_ids, creation_time);
3737 /* Get channels and channel users in global list */
3738 if (server->server_type != SILC_SERVER)
3739 silc_server_announce_get_channels(server, server->global_list,
3740 &channels, &channel_users,
3741 &channel_users_modes,
3742 &channel_users_modes_c,
3744 &channel_ids, creation_time);
3747 silc_buffer_push(channels, channels->data - channels->head);
3748 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3750 /* Send the packet */
3751 silc_server_packet_send(server, remote,
3752 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3753 channels->data, channels->len,
3756 silc_buffer_free(channels);
3759 if (channel_users) {
3760 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3761 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3762 channel_users->len);
3764 /* Send the packet */
3765 silc_server_packet_send(server, remote,
3766 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3767 channel_users->data, channel_users->len,
3770 silc_buffer_free(channel_users);
3773 if (channel_users_modes) {
3776 for (i = 0; i < channel_users_modes_c; i++) {
3777 if (!channel_users_modes[i])
3779 silc_buffer_push(channel_users_modes[i],
3780 channel_users_modes[i]->data -
3781 channel_users_modes[i]->head);
3782 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3783 channel_users_modes[i]->len);
3784 silc_server_packet_send_dest(server, remote,
3785 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3786 channel_ids[i], SILC_ID_CHANNEL,
3787 channel_users_modes[i]->data,
3788 channel_users_modes[i]->len,
3790 silc_buffer_free(channel_users_modes[i]);
3792 silc_free(channel_users_modes);
3795 if (channel_topics) {
3798 for (i = 0; i < channel_users_modes_c; i++) {
3799 if (!channel_topics[i])
3802 silc_buffer_push(channel_topics[i],
3803 channel_topics[i]->data -
3804 channel_topics[i]->head);
3805 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3806 channel_topics[i]->len);
3807 silc_server_packet_send_dest(server, remote,
3808 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3809 channel_ids[i], SILC_ID_CHANNEL,
3810 channel_topics[i]->data,
3811 channel_topics[i]->len,
3813 silc_buffer_free(channel_topics[i]);
3815 silc_free(channel_topics);
3818 silc_free(channel_ids);
3821 /* Failure timeout callback. If this is called then we will immediately
3822 process the received failure. We always process the failure with timeout
3823 since we do not want to blindly trust to received failure packets.
3824 This won't be called (the timeout is cancelled) if the failure was
3825 bogus (it is bogus if remote does not close the connection after sending
3828 SILC_TASK_CALLBACK(silc_server_failure_callback)
3830 SilcServerFailureContext f = (SilcServerFailureContext)context;
3832 if (f->sock->protocol) {
3833 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3834 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3840 /* Assembles user list and users mode list from the `channel'. */
3842 void silc_server_get_users_on_channel(SilcServer server,
3843 SilcChannelEntry channel,
3844 SilcBuffer *user_list,
3845 SilcBuffer *mode_list,
3846 SilcUInt32 *user_count)
3848 SilcChannelClientEntry chl;
3849 SilcHashTableList htl;
3850 SilcBuffer client_id_list;
3851 SilcBuffer client_mode_list;
3853 SilcUInt32 list_count = 0, len = 0;
3855 silc_hash_table_list(channel->user_list, &htl);
3856 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3857 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3858 silc_hash_table_list_reset(&htl);
3860 client_id_list = silc_buffer_alloc(len);
3862 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3863 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3864 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3866 silc_hash_table_list(channel->user_list, &htl);
3867 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3869 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3870 silc_buffer_put(client_id_list, idp->data, idp->len);
3871 silc_buffer_pull(client_id_list, idp->len);
3872 silc_buffer_free(idp);
3874 /* Client's mode on channel */
3875 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3876 silc_buffer_pull(client_mode_list, 4);
3880 silc_hash_table_list_reset(&htl);
3881 silc_buffer_push(client_id_list,
3882 client_id_list->data - client_id_list->head);
3883 silc_buffer_push(client_mode_list,
3884 client_mode_list->data - client_mode_list->head);
3886 *user_list = client_id_list;
3887 *mode_list = client_mode_list;
3888 *user_count = list_count;
3891 /* Saves users and their modes to the `channel'. */
3893 void silc_server_save_users_on_channel(SilcServer server,
3894 SilcSocketConnection sock,
3895 SilcChannelEntry channel,
3896 SilcClientID *noadd,
3897 SilcBuffer user_list,
3898 SilcBuffer mode_list,
3899 SilcUInt32 user_count)
3904 SilcClientID *client_id;
3905 SilcClientEntry client;
3906 SilcIDCacheEntry cache;
3909 SILC_LOG_DEBUG(("Start"));
3911 for (i = 0; i < user_count; i++) {
3913 SILC_GET16_MSB(idp_len, user_list->data + 2);
3915 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3916 silc_buffer_pull(user_list, idp_len);
3921 SILC_GET32_MSB(mode, mode_list->data);
3922 silc_buffer_pull(mode_list, 4);
3924 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3925 silc_free(client_id);
3931 /* Check if we have this client cached already. */
3932 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3933 server->server_type, &cache);
3935 client = silc_idlist_find_client_by_id(server->global_list,
3936 client_id, server->server_type,
3941 /* If router did not find such Client ID in its lists then this must
3942 be bogus client or some router in the net is buggy. */
3943 if (server->server_type == SILC_ROUTER) {
3944 silc_free(client_id);
3948 /* We don't have that client anywhere, add it. The client is added
3949 to global list since server didn't have it in the lists so it must be
3951 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3952 silc_id_dup(client_id, SILC_ID_CLIENT),
3953 sock->user_data, NULL, 0);
3955 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3956 silc_free(client_id);
3960 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3962 /* Found, if it is from global list we'll assure that we won't
3963 expire it now that the entry is on channel. */
3968 silc_free(client_id);
3970 if (!silc_server_client_on_channel(client, channel, NULL)) {
3971 /* Client was not on the channel, add it. */
3972 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3973 chl->client = client;
3975 chl->channel = channel;
3976 silc_hash_table_add(channel->user_list, chl->client, chl);
3977 silc_hash_table_add(client->channels, chl->channel, chl);
3978 channel->user_count++;
3983 /* Lookups route to the client indicated by the `id_data'. The connection
3984 object and internal data object is returned. Returns NULL if route
3985 could not be found to the client. If the `client_id' is specified then
3986 it is used and the `id_data' is ignored. */
3988 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3989 unsigned char *id_data,
3991 SilcClientID *client_id,
3992 SilcIDListData *idata)
3995 SilcClientEntry client;
3997 SILC_LOG_DEBUG(("Start"));
3999 /* Decode destination Client ID */
4001 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4003 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4007 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4010 /* If the destination belongs to our server we don't have to route
4011 the packet anywhere but to send it to the local destination. */
4012 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4016 /* If we are router and the client has router then the client is in
4017 our cell but not directly connected to us. */
4018 if (server->server_type == SILC_ROUTER && client->router) {
4019 /* We are of course in this case the client's router thus the route
4020 to the client is the server who owns the client. So, we will send
4021 the packet to that server. */
4023 *idata = (SilcIDListData)client->router;
4024 return client->router->connection;
4027 /* Seems that client really is directly connected to us */
4029 *idata = (SilcIDListData)client;
4030 return client->connection;
4033 /* Destination belongs to someone not in this server. If we are normal
4034 server our action is to send the packet to our router. */
4035 if (server->server_type != SILC_ROUTER && !server->standalone) {
4038 *idata = (SilcIDListData)server->router;
4039 return server->router->connection;
4042 /* We are router and we will perform route lookup for the destination
4043 and send the packet to fastest route. */
4044 if (server->server_type == SILC_ROUTER && !server->standalone) {
4045 /* Check first that the ID is valid */
4046 client = silc_idlist_find_client_by_id(server->global_list, id,
4049 SilcSocketConnection dst_sock;
4051 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4055 *idata = (SilcIDListData)dst_sock->user_data;
4064 /* Encodes and returns channel list of channels the `client' has joined.
4065 Secret channels are not put to the list. */
4067 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4068 SilcClientEntry client)
4070 SilcBuffer buffer = NULL;
4071 SilcChannelEntry channel;
4072 SilcChannelClientEntry chl;
4073 SilcHashTableList htl;
4076 SilcUInt16 name_len;
4079 silc_hash_table_list(client->channels, &htl);
4080 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4081 channel = chl->channel;
4083 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4084 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4087 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4088 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4089 name_len = strlen(channel->channel_name);
4091 len = 4 + name_len + id_len + 4;
4092 buffer = silc_buffer_realloc(buffer,
4093 (buffer ? (buffer)->truelen + len : len));
4094 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4095 silc_buffer_format(buffer,
4096 SILC_STR_UI_SHORT(name_len),
4097 SILC_STR_UI_XNSTRING(channel->channel_name,
4099 SILC_STR_UI_SHORT(id_len),
4100 SILC_STR_UI_XNSTRING(cid, id_len),
4101 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4103 silc_buffer_pull(buffer, len);
4106 silc_hash_table_list_reset(&htl);
4109 silc_buffer_push(buffer, buffer->data - buffer->head);
4114 /* Finds client entry by Client ID and if it is not found then resolves
4115 it using WHOIS command. */
4117 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4118 SilcClientID *client_id,
4121 SilcClientEntry client;
4126 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4129 client = silc_idlist_find_client_by_id(server->global_list,
4130 client_id, TRUE, NULL);
4131 if (!client && server->server_type == SILC_ROUTER)
4135 if (!client && server->standalone)
4138 if (!client || !client->nickname || !client->username) {
4139 SilcBuffer buffer, idp;
4141 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4142 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4143 client->resolve_cmd_ident = ++server->cmd_ident;
4145 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4146 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4147 server->cmd_ident, 1,
4148 3, idp->data, idp->len);
4149 silc_server_packet_send(server, client ? client->router->connection :
4150 server->router->connection,
4151 SILC_PACKET_COMMAND, 0,
4152 buffer->data, buffer->len, FALSE);
4153 silc_buffer_free(idp);
4154 silc_buffer_free(buffer);
4165 /* A timeout callback for the re-key. We will be the initiator of the
4168 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4170 SilcSocketConnection sock = (SilcSocketConnection)context;
4171 SilcIDListData idata = (SilcIDListData)sock->user_data;
4172 SilcServer server = (SilcServer)idata->rekey->context;
4173 SilcProtocol protocol;
4174 SilcServerRekeyInternalContext *proto_ctx;
4176 SILC_LOG_DEBUG(("Start"));
4178 /* Allocate internal protocol context. This is sent as context
4180 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4181 proto_ctx->server = (void *)server;
4182 proto_ctx->sock = sock;
4183 proto_ctx->responder = FALSE;
4184 proto_ctx->pfs = idata->rekey->pfs;
4186 /* Perform rekey protocol. Will call the final callback after the
4187 protocol is over. */
4188 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4189 &protocol, proto_ctx, silc_server_rekey_final);
4190 sock->protocol = protocol;
4192 /* Run the protocol */
4193 silc_protocol_execute(protocol, server->schedule, 0, 0);
4195 /* Re-register re-key timeout */
4196 silc_schedule_task_add(server->schedule, sock->sock,
4197 silc_server_rekey_callback,
4198 context, idata->rekey->timeout, 0,
4199 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4202 /* The final callback for the REKEY protocol. This will actually take the
4203 new key material into use. */
4205 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4207 SilcProtocol protocol = (SilcProtocol)context;
4208 SilcServerRekeyInternalContext *ctx =
4209 (SilcServerRekeyInternalContext *)protocol->context;
4210 SilcServer server = (SilcServer)ctx->server;
4211 SilcSocketConnection sock = ctx->sock;
4213 SILC_LOG_DEBUG(("Start"));
4215 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4216 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4217 /* Error occured during protocol */
4218 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4219 silc_protocol_cancel(protocol, server->schedule);
4220 silc_protocol_free(protocol);
4221 sock->protocol = NULL;
4223 silc_packet_context_free(ctx->packet);
4225 silc_ske_free(ctx->ske);
4230 /* Purge the outgoing data queue to assure that all rekey packets really
4231 go to the network before we quit the protocol. */
4232 silc_server_packet_queue_purge(server, sock);
4235 silc_protocol_free(protocol);
4236 sock->protocol = NULL;
4238 silc_packet_context_free(ctx->packet);
4240 silc_ske_free(ctx->ske);