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 /* Create the connections to all our routes */
736 ptr = server->config->routers;
739 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
740 ptr->backup_router ? "Backup router" : "Router",
741 ptr->initiator ? "Initiator" : "Responder",
742 ptr->host, ptr->port));
744 if (ptr->initiator) {
745 /* Allocate connection object for hold connection specific stuff. */
746 sconn = silc_calloc(1, sizeof(*sconn));
747 sconn->server = server;
748 sconn->remote_host = strdup(ptr->host);
749 sconn->remote_port = ptr->port;
750 sconn->backup = ptr->backup_router;
752 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
753 sconn->backup_replace_port = ptr->backup_replace_port;
756 if (!server->router_conn && !sconn->backup)
757 server->router_conn = sconn;
759 silc_schedule_task_add(server->schedule, fd,
760 silc_server_connect_router,
761 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
762 SILC_TASK_PRI_NORMAL);
771 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
773 /* There wasn't a configured router, we will continue but we don't
774 have a connection to outside world. We will be standalone server. */
775 server->standalone = TRUE;
778 /* Second part of connecting to router(s). Key exchange protocol has been
779 executed and now we will execute authentication protocol. */
781 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
783 SilcProtocol protocol = (SilcProtocol)context;
784 SilcServerKEInternalContext *ctx =
785 (SilcServerKEInternalContext *)protocol->context;
786 SilcServer server = (SilcServer)ctx->server;
787 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
788 SilcSocketConnection sock = ctx->sock;
789 SilcServerConnAuthInternalContext *proto_ctx;
790 SilcServerConfigRouter *conn = NULL;
792 SILC_LOG_DEBUG(("Start"));
794 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
795 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
796 /* Error occured during protocol */
797 silc_protocol_free(protocol);
798 sock->protocol = NULL;
799 silc_ske_free_key_material(ctx->keymat);
801 silc_packet_context_free(ctx->packet);
803 silc_ske_free(ctx->ske);
804 silc_free(ctx->dest_id);
805 silc_server_config_unref(&ctx->cconfig);
806 silc_server_config_unref(&ctx->sconfig);
807 silc_server_config_unref(&ctx->rconfig);
809 silc_server_config_unref(&sconn->conn);
810 silc_free(sconn->remote_host);
811 silc_free(sconn->backup_replace_ip);
813 silc_schedule_task_del_by_callback(server->schedule,
814 silc_server_failure_callback);
815 silc_server_disconnect_remote(server, sock, "Server closed connection: "
816 "Key exchange failed");
820 /* We now have the key material as the result of the key exchange
821 protocol. Take the key material into use. Free the raw key material
822 as soon as we've set them into use. */
823 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
824 ctx->sock, ctx->keymat,
825 ctx->ske->prop->cipher,
826 ctx->ske->prop->pkcs,
827 ctx->ske->prop->hash,
828 ctx->ske->prop->hmac,
829 ctx->ske->prop->group,
831 silc_protocol_free(protocol);
832 sock->protocol = NULL;
833 silc_ske_free_key_material(ctx->keymat);
835 silc_packet_context_free(ctx->packet);
837 silc_ske_free(ctx->ske);
838 silc_free(ctx->dest_id);
840 silc_server_config_unref(&sconn->conn);
841 silc_free(sconn->remote_host);
842 silc_free(sconn->backup_replace_ip);
844 silc_schedule_task_del_by_callback(server->schedule,
845 silc_server_failure_callback);
846 silc_server_disconnect_remote(server, sock, "Server closed connection: "
847 "Key exchange failed");
850 silc_ske_free_key_material(ctx->keymat);
852 /* Allocate internal context for the authentication protocol. This
853 is sent as context for the protocol. */
854 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
855 proto_ctx->server = (void *)server;
856 proto_ctx->context = (void *)sconn;
857 proto_ctx->sock = sock;
858 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
859 proto_ctx->dest_id_type = ctx->dest_id_type;
860 proto_ctx->dest_id = ctx->dest_id;
862 /* Resolve the authentication method used in this connection. Check if
863 we find a match from user configured connections */
864 if (!sconn->conn.ref_ptr)
865 conn = silc_server_config_find_router_conn(server, sock->hostname,
868 conn = sconn->conn.ref_ptr;
871 /* Match found. Use the configured authentication method. Take only
872 the passphrase, since for public key auth we automatically use
873 our local key pair. */
874 if (conn->passphrase) {
875 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
876 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
878 proto_ctx->auth_data = strdup(conn->passphrase);
879 proto_ctx->auth_data_len = strlen(conn->passphrase);
880 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
882 } else if (conn->publickeys) {
883 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
885 proto_ctx->auth_meth = SILC_AUTH_NONE;
888 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
889 sock->hostname, sock->ip, sock->port));
890 silc_protocol_free(protocol);
891 sock->protocol = NULL;
893 silc_packet_context_free(ctx->packet);
895 silc_ske_free(ctx->ske);
896 silc_free(ctx->dest_id);
898 silc_schedule_task_del_by_callback(server->schedule,
899 silc_server_failure_callback);
900 silc_server_disconnect_remote(server, sock, "Server closed connection: "
901 "Key exchange failed");
905 /* Free old protocol as it is finished now */
906 silc_protocol_free(protocol);
908 silc_packet_context_free(ctx->packet);
910 sock->protocol = NULL;
912 /* Allocate the authentication protocol. This is allocated here
913 but we won't start it yet. We will be receiving party of this
914 protocol thus we will wait that connecting party will make
916 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
917 &sock->protocol, proto_ctx,
918 silc_server_connect_to_router_final);
920 /* Register timeout task. If the protocol is not executed inside
921 this timelimit the connection will be terminated. */
922 proto_ctx->timeout_task =
923 silc_schedule_task_add(server->schedule, sock->sock,
924 silc_server_timeout_remote,
926 server->config->conn_auth_timeout, 0,
930 /* Run the protocol */
931 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
934 /* Finalizes the connection to router. Registers a server task to the
935 queue so that we can accept new connections. */
937 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
939 SilcProtocol protocol = (SilcProtocol)context;
940 SilcServerConnAuthInternalContext *ctx =
941 (SilcServerConnAuthInternalContext *)protocol->context;
942 SilcServer server = (SilcServer)ctx->server;
943 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
944 SilcSocketConnection sock = ctx->sock;
945 SilcServerEntry id_entry;
947 SilcServerHBContext hb_context;
948 unsigned char *id_string;
950 SilcIDListData idata;
951 SilcServerConfigRouter *conn = NULL;
952 SilcServerConfigConnParams *param = NULL;
954 SILC_LOG_DEBUG(("Start"));
956 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
957 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
958 /* Error occured during protocol */
959 silc_free(ctx->dest_id);
960 silc_server_disconnect_remote(server, sock, "Server closed connection: "
961 "Authentication failed");
965 /* Add a task to the queue. This task receives new connections to the
966 server. This task remains on the queue until the end of the program. */
967 if (!server->listenning && !sconn->backup) {
968 silc_schedule_task_add(server->schedule, server->sock,
969 silc_server_accept_new_connection,
970 (void *)server, 0, 0,
972 SILC_TASK_PRI_NORMAL);
973 server->listenning = TRUE;
976 /* Send NEW_SERVER packet to the router. We will become registered
977 to the SILC network after sending this packet. */
978 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
979 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
980 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
981 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
982 silc_buffer_format(packet,
983 SILC_STR_UI_SHORT(id_len),
984 SILC_STR_UI_XNSTRING(id_string, id_len),
985 SILC_STR_UI_SHORT(strlen(server->server_name)),
986 SILC_STR_UI_XNSTRING(server->server_name,
987 strlen(server->server_name)),
990 /* Send the packet */
991 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
992 packet->data, packet->len, TRUE);
993 silc_buffer_free(packet);
994 silc_free(id_string);
996 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
998 /* Check that we do not have this ID already */
999 id_entry = silc_idlist_find_server_by_id(server->local_list,
1000 ctx->dest_id, TRUE, NULL);
1002 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1004 id_entry = silc_idlist_find_server_by_id(server->global_list,
1005 ctx->dest_id, TRUE, NULL);
1007 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1010 SILC_LOG_DEBUG(("New server id(%s)",
1011 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1013 /* Add the connected router to global server list */
1014 id_entry = silc_idlist_add_server(server->global_list,
1015 strdup(sock->hostname),
1016 SILC_ROUTER, ctx->dest_id, NULL, sock);
1018 silc_free(ctx->dest_id);
1019 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1020 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1021 "Authentication failed");
1025 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1026 silc_free(sock->user_data);
1027 sock->user_data = (void *)id_entry;
1028 sock->type = SILC_SOCKET_TYPE_ROUTER;
1029 idata = (SilcIDListData)sock->user_data;
1030 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1032 conn = sconn->conn.ref_ptr;
1033 param = &server->config->param;
1034 if (conn && conn->param)
1035 param = conn->param;
1037 /* Perform keepalive. The `hb_context' will be freed automatically
1038 when finally calling the silc_socket_free function. */
1039 hb_context = silc_calloc(1, sizeof(*hb_context));
1040 hb_context->server = server;
1041 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1042 silc_server_perform_heartbeat,
1045 /* Register re-key timeout */
1046 idata->rekey->timeout = param->key_exchange_rekey;
1047 idata->rekey->context = (void *)server;
1048 silc_schedule_task_add(server->schedule, sock->sock,
1049 silc_server_rekey_callback,
1050 (void *)sock, idata->rekey->timeout, 0,
1051 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1053 if (!sconn->backup) {
1054 /* Mark this router our primary router if we're still standalone */
1055 if (server->standalone) {
1056 server->id_entry->router = id_entry;
1057 server->router = id_entry;
1058 server->standalone = FALSE;
1060 /* If we are router then announce our possible servers. */
1061 if (server->server_type == SILC_ROUTER)
1062 silc_server_announce_servers(server, FALSE, 0,
1063 server->router->connection);
1065 /* Announce our clients and channels to the router */
1066 silc_server_announce_clients(server, 0, server->router->connection);
1067 silc_server_announce_channels(server, 0, server->router->connection);
1070 /* Add this server to be our backup router */
1071 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1072 sconn->backup_replace_port, FALSE);
1075 sock->protocol = NULL;
1077 /* Call the completion callback to indicate that we've connected to
1079 if (sconn->callback)
1080 (*sconn->callback)(server, id_entry, sconn->callback_context);
1083 /* Free the temporary connection data context */
1085 silc_server_config_unref(&sconn->conn);
1086 silc_free(sconn->remote_host);
1087 silc_free(sconn->backup_replace_ip);
1090 if (sconn == server->router_conn)
1091 server->router_conn = NULL;
1093 /* Free the protocol object */
1094 if (sock->protocol == protocol)
1095 sock->protocol = NULL;
1096 silc_protocol_free(protocol);
1098 silc_packet_context_free(ctx->packet);
1100 silc_ske_free(ctx->ske);
1101 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1102 silc_free(ctx->auth_data);
1106 /* Host lookup callback that is called after the incoming connection's
1107 IP and FQDN lookup is performed. This will actually check the acceptance
1108 of the incoming connection and will register the key exchange protocol
1109 for this connection. */
1112 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1115 SilcServer server = (SilcServer)context;
1116 SilcServerKEInternalContext *proto_ctx;
1117 SilcServerConfigClient *cconfig = NULL;
1118 SilcServerConfigServer *sconfig = NULL;
1119 SilcServerConfigRouter *rconfig = NULL;
1120 SilcServerConfigDeny *deny;
1123 SILC_LOG_DEBUG(("Start"));
1125 /* Check whether we could resolve both IP and FQDN. */
1126 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1127 server->config->require_reverse_lookup)) {
1128 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1129 sock->hostname ? sock->hostname :
1130 sock->ip ? sock->ip : ""));
1131 server->stat.conn_failures++;
1132 silc_server_disconnect_remote(server, sock,
1133 "Server closed connection: Unknown host");
1137 /* Register the connection for network input and output. This sets
1138 that scheduler will listen for incoming packets for this connection
1139 and sets that outgoing packets may be sent to this connection as well.
1140 However, this doesn't set the scheduler for outgoing traffic, it
1141 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1142 later when outgoing data is available. */
1143 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1145 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1148 port = server->sockets[server->sock]->port; /* Listenning port */
1150 /* Check whether this connection is denied to connect to us. */
1151 deny = silc_server_config_find_denied(server, sock->ip);
1153 deny = silc_server_config_find_denied(server, sock->hostname);
1155 /* The connection is denied */
1156 SILC_LOG_INFO(("Connection %s (%s) is denied",
1157 sock->hostname, sock->ip));
1158 silc_server_disconnect_remote(server, sock, deny->reason ?
1160 "Server closed connection: "
1161 "Connection refused");
1162 server->stat.conn_failures++;
1166 /* Check whether we have configured this sort of connection at all. We
1167 have to check all configurations since we don't know what type of
1168 connection this is. */
1169 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1170 cconfig = silc_server_config_find_client(server, sock->hostname);
1171 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1172 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1173 if (server->server_type == SILC_ROUTER) {
1174 if (!(rconfig = silc_server_config_find_router_conn(server,
1176 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1179 if (!cconfig && !sconfig && !rconfig) {
1180 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1182 silc_server_disconnect_remote(server, sock,
1183 "Server closed connection: "
1184 "Connection refused");
1185 server->stat.conn_failures++;
1189 /* The connection is allowed */
1191 /* Allocate internal context for key exchange protocol. This is
1192 sent as context for the protocol. */
1193 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1194 proto_ctx->server = context;
1195 proto_ctx->sock = sock;
1196 proto_ctx->rng = server->rng;
1197 proto_ctx->responder = TRUE;
1198 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1199 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1200 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1202 /* Take flags for key exchange. Since we do not know what type of connection
1203 this is, we go through all found configurations and use the global ones
1204 as well. This will result always into strictest key exchange flags. */
1205 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1206 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1207 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1208 if (server->config->param.key_exchange_pfs)
1209 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1211 /* Prepare the connection for key exchange protocol. We allocate the
1212 protocol but will not start it yet. The connector will be the
1213 initiator of the protocol thus we will wait for initiation from
1214 there before we start the protocol. */
1215 server->stat.auth_attempts++;
1216 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1217 &sock->protocol, proto_ctx,
1218 silc_server_accept_new_connection_second);
1220 /* Register a timeout task that will be executed if the connector
1221 will not start the key exchange protocol within specified timeout
1222 and the connection will be closed. */
1223 proto_ctx->timeout_task =
1224 silc_schedule_task_add(server->schedule, sock->sock,
1225 silc_server_timeout_remote,
1226 context, server->config->key_exchange_timeout, 0,
1231 /* Accepts new connections to the server. Accepting new connections are
1232 done in three parts to make it async. */
1234 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1236 SilcServer server = (SilcServer)context;
1237 SilcSocketConnection newsocket;
1240 SILC_LOG_DEBUG(("Accepting new connection"));
1242 server->stat.conn_attempts++;
1244 sock = silc_net_accept_connection(server->sock);
1246 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1247 server->stat.conn_failures++;
1251 /* Check for maximum allowed connections */
1252 if (sock > server->config->param.connections_max) {
1253 SILC_LOG_ERROR(("Refusing connection, server is full, try again later"));
1254 server->stat.conn_failures++;
1255 silc_net_close_connection(sock);
1259 /* Set socket options */
1260 silc_net_set_socket_nonblock(sock);
1261 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1263 /* We don't create a ID yet, since we don't know what type of connection
1264 this is yet. But, we do add the connection to the socket table. */
1265 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1266 server->sockets[sock] = newsocket;
1268 /* Perform asynchronous host lookup. This will lookup the IP and the
1269 FQDN of the remote connection. After the lookup is done the connection
1270 is accepted further. */
1271 silc_socket_host_lookup(newsocket, TRUE,
1272 silc_server_accept_new_connection_lookup, context,
1276 /* Second part of accepting new connection. Key exchange protocol has been
1277 performed and now it is time to do little connection authentication
1278 protocol to figure out whether this connection is client or server
1279 and whether it has right to access this server (especially server
1280 connections needs to be authenticated). */
1282 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1284 SilcProtocol protocol = (SilcProtocol)context;
1285 SilcServerKEInternalContext *ctx =
1286 (SilcServerKEInternalContext *)protocol->context;
1287 SilcServer server = (SilcServer)ctx->server;
1288 SilcSocketConnection sock = ctx->sock;
1289 SilcServerConnAuthInternalContext *proto_ctx;
1291 SILC_LOG_DEBUG(("Start"));
1293 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1294 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1295 /* Error occured during protocol */
1296 silc_protocol_free(protocol);
1297 sock->protocol = NULL;
1298 silc_ske_free_key_material(ctx->keymat);
1300 silc_packet_context_free(ctx->packet);
1302 silc_ske_free(ctx->ske);
1303 silc_free(ctx->dest_id);
1304 silc_server_config_unref(&ctx->cconfig);
1305 silc_server_config_unref(&ctx->sconfig);
1306 silc_server_config_unref(&ctx->rconfig);
1308 silc_schedule_task_del_by_callback(server->schedule,
1309 silc_server_failure_callback);
1310 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1311 "Key exchange failed");
1312 server->stat.auth_failures++;
1316 /* We now have the key material as the result of the key exchange
1317 protocol. Take the key material into use. Free the raw key material
1318 as soon as we've set them into use. */
1319 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1320 ctx->sock, ctx->keymat,
1321 ctx->ske->prop->cipher,
1322 ctx->ske->prop->pkcs,
1323 ctx->ske->prop->hash,
1324 ctx->ske->prop->hmac,
1325 ctx->ske->prop->group,
1327 silc_protocol_free(protocol);
1328 sock->protocol = NULL;
1329 silc_ske_free_key_material(ctx->keymat);
1331 silc_packet_context_free(ctx->packet);
1333 silc_ske_free(ctx->ske);
1334 silc_free(ctx->dest_id);
1335 silc_server_config_unref(&ctx->cconfig);
1336 silc_server_config_unref(&ctx->sconfig);
1337 silc_server_config_unref(&ctx->rconfig);
1339 silc_schedule_task_del_by_callback(server->schedule,
1340 silc_server_failure_callback);
1341 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1342 "Key exchange failed");
1343 server->stat.auth_failures++;
1346 silc_ske_free_key_material(ctx->keymat);
1348 /* Allocate internal context for the authentication protocol. This
1349 is sent as context for the protocol. */
1350 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1351 proto_ctx->server = (void *)server;
1352 proto_ctx->sock = sock;
1353 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1354 proto_ctx->responder = TRUE;
1355 proto_ctx->dest_id_type = ctx->dest_id_type;
1356 proto_ctx->dest_id = ctx->dest_id;
1357 proto_ctx->cconfig = ctx->cconfig;
1358 proto_ctx->sconfig = ctx->sconfig;
1359 proto_ctx->rconfig = ctx->rconfig;
1361 /* Free old protocol as it is finished now */
1362 silc_protocol_free(protocol);
1364 silc_packet_context_free(ctx->packet);
1366 sock->protocol = NULL;
1368 /* Allocate the authentication protocol. This is allocated here
1369 but we won't start it yet. We will be receiving party of this
1370 protocol thus we will wait that connecting party will make
1371 their first move. */
1372 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1373 &sock->protocol, proto_ctx,
1374 silc_server_accept_new_connection_final);
1376 /* Register timeout task. If the protocol is not executed inside
1377 this timelimit the connection will be terminated. */
1378 proto_ctx->timeout_task =
1379 silc_schedule_task_add(server->schedule, sock->sock,
1380 silc_server_timeout_remote,
1382 server->config->conn_auth_timeout, 0,
1387 /* Final part of accepting new connection. The connection has now
1388 been authenticated and keys has been exchanged. We also know whether
1389 this is client or server connection. */
1391 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1393 SilcProtocol protocol = (SilcProtocol)context;
1394 SilcServerConnAuthInternalContext *ctx =
1395 (SilcServerConnAuthInternalContext *)protocol->context;
1396 SilcServer server = (SilcServer)ctx->server;
1397 SilcSocketConnection sock = ctx->sock;
1398 SilcServerHBContext hb_context;
1399 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1401 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1403 SILC_LOG_DEBUG(("Start"));
1405 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1406 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1407 /* Error occured during protocol */
1408 silc_protocol_free(protocol);
1409 sock->protocol = NULL;
1411 silc_packet_context_free(ctx->packet);
1413 silc_ske_free(ctx->ske);
1414 silc_free(ctx->dest_id);
1415 silc_server_config_unref(&ctx->cconfig);
1416 silc_server_config_unref(&ctx->sconfig);
1417 silc_server_config_unref(&ctx->rconfig);
1419 silc_schedule_task_del_by_callback(server->schedule,
1420 silc_server_failure_callback);
1421 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1422 "Authentication failed");
1423 server->stat.auth_failures++;
1427 entry->data.last_receive = time(NULL);
1429 switch (ctx->conn_type) {
1430 case SILC_SOCKET_TYPE_CLIENT:
1432 SilcClientEntry client;
1433 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1435 /* Verify whether this connection is after all allowed to connect */
1436 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1437 &server->config->param,
1438 conn->param, ctx->ske)) {
1439 server->stat.auth_failures++;
1443 SILC_LOG_DEBUG(("Remote host is client"));
1444 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1447 /* Add the client to the client ID cache. The nickname and Client ID
1448 and other information is created after we have received NEW_CLIENT
1449 packet from client. */
1450 client = silc_idlist_add_client(server->local_list,
1451 NULL, NULL, NULL, NULL, NULL, sock, 0);
1453 SILC_LOG_ERROR(("Could not add new client to cache"));
1454 silc_free(sock->user_data);
1455 silc_server_disconnect_remote(server, sock,
1456 "Server closed connection: "
1457 "Authentication failed");
1458 server->stat.auth_failures++;
1463 server->stat.my_clients++;
1464 server->stat.clients++;
1465 if (server->server_type == SILC_ROUTER)
1466 server->stat.cell_clients++;
1468 /* Get connection parameters */
1470 if (conn->param->keepalive_secs)
1471 hearbeat_timeout = conn->param->keepalive_secs;
1474 id_entry = (void *)client;
1477 case SILC_SOCKET_TYPE_SERVER:
1478 case SILC_SOCKET_TYPE_ROUTER:
1480 SilcServerEntry new_server;
1481 bool initiator = FALSE;
1482 bool backup_local = FALSE;
1483 bool backup_router = FALSE;
1484 char *backup_replace_ip = NULL;
1485 SilcUInt16 backup_replace_port = 0;
1486 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1487 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1489 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1490 /* Verify whether this connection is after all allowed to connect */
1491 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1492 &server->config->param,
1493 rconn ? rconn->param : NULL,
1495 server->stat.auth_failures++;
1501 if (rconn->param->keepalive_secs)
1502 hearbeat_timeout = rconn->param->keepalive_secs;
1505 initiator = rconn->initiator;
1506 backup_local = rconn->backup_local;
1507 backup_router = rconn->backup_router;
1508 backup_replace_ip = rconn->backup_replace_ip;
1509 backup_replace_port = rconn->backup_replace_port;
1513 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1514 /* Verify whether this connection is after all allowed to connect */
1515 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1516 &server->config->param,
1517 sconn ? sconn->param : NULL,
1519 server->stat.auth_failures++;
1524 if (sconn->param->keepalive_secs)
1525 hearbeat_timeout = sconn->param->keepalive_secs;
1528 backup_router = sconn->backup_router;
1532 SILC_LOG_DEBUG(("Remote host is %s",
1533 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1534 "server" : (backup_router ?
1535 "backup router" : "router")));
1536 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1537 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1538 "server" : (backup_router ?
1539 "backup router" : "router")));
1541 /* Add the server into server cache. The server name and Server ID
1542 is updated after we have received NEW_SERVER packet from the
1543 server. We mark ourselves as router for this server if we really
1546 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1547 server->local_list : (backup_router ?
1548 server->local_list :
1549 server->global_list)),
1551 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1552 SILC_SERVER : SILC_ROUTER),
1554 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1555 server->id_entry : (backup_router ?
1556 server->id_entry : NULL)),
1559 SILC_LOG_ERROR(("Could not add new server to cache"));
1560 silc_free(sock->user_data);
1561 silc_server_disconnect_remote(server, sock,
1562 "Server closed connection: "
1563 "Authentication failed");
1564 server->stat.auth_failures++;
1569 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1570 server->stat.my_servers++;
1572 server->stat.my_routers++;
1573 server->stat.servers++;
1575 id_entry = (void *)new_server;
1577 /* If the incoming connection is router and marked as backup router
1578 then add it to be one of our backups */
1579 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1580 silc_server_backup_add(server, new_server, backup_replace_ip,
1581 backup_replace_port, backup_local);
1583 /* Change it back to SERVER type since that's what it really is. */
1585 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1587 new_server->server_type = SILC_BACKUP_ROUTER;
1590 /* Check whether this connection is to be our primary router connection
1591 if we do not already have the primary route. */
1592 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1593 if (silc_server_config_is_primary_route(server) && !initiator)
1596 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1597 server->standalone = FALSE;
1598 if (!server->id_entry->router) {
1599 server->id_entry->router = id_entry;
1600 server->router = id_entry;
1611 sock->type = ctx->conn_type;
1613 /* Add the common data structure to the ID entry. */
1614 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1616 /* Add to sockets internal pointer for fast referencing */
1617 silc_free(sock->user_data);
1618 sock->user_data = id_entry;
1620 /* Connection has been fully established now. Everything is ok. */
1621 SILC_LOG_DEBUG(("New connection authenticated"));
1623 /* Perform keepalive. The `hb_context' will be freed automatically
1624 when finally calling the silc_socket_free function. */
1625 hb_context = silc_calloc(1, sizeof(*hb_context));
1626 hb_context->server = server;
1627 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1628 silc_server_perform_heartbeat,
1632 silc_schedule_task_del_by_callback(server->schedule,
1633 silc_server_failure_callback);
1634 silc_protocol_free(protocol);
1636 silc_packet_context_free(ctx->packet);
1638 silc_ske_free(ctx->ske);
1639 silc_free(ctx->dest_id);
1640 silc_server_config_unref(&ctx->cconfig);
1641 silc_server_config_unref(&ctx->sconfig);
1642 silc_server_config_unref(&ctx->rconfig);
1644 sock->protocol = NULL;
1647 /* This function is used to read packets from network and send packets to
1648 network. This is usually a generic task. */
1650 SILC_TASK_CALLBACK(silc_server_packet_process)
1652 SilcServer server = (SilcServer)context;
1653 SilcSocketConnection sock = server->sockets[fd];
1654 SilcIDListData idata;
1655 SilcCipher cipher = NULL;
1656 SilcHmac hmac = NULL;
1657 SilcUInt32 sequence = 0;
1663 SILC_LOG_DEBUG(("Processing packet"));
1665 /* Packet sending */
1667 if (type == SILC_TASK_WRITE) {
1668 /* Do not send data to disconnected connection */
1669 if (SILC_IS_DISCONNECTED(sock))
1672 server->stat.packets_sent++;
1674 /* Send the packet */
1675 ret = silc_packet_send(sock, TRUE);
1677 /* If returned -2 could not write to connection now, will do
1683 SILC_LOG_ERROR(("Error sending packet to connection "
1684 "%s:%d [%s]", sock->hostname, sock->port,
1685 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1686 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1687 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1692 /* The packet has been sent and now it is time to set the connection
1693 back to only for input. When there is again some outgoing data
1694 available for this connection it will be set for output as well.
1695 This call clears the output setting and sets it only for input. */
1696 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1697 SILC_UNSET_OUTBUF_PENDING(sock);
1699 silc_buffer_clear(sock->outbuf);
1703 /* Packet receiving */
1705 /* Read some data from connection */
1706 ret = silc_packet_receive(sock);
1710 SILC_LOG_ERROR(("Error receiving packet from connection "
1711 "%s:%d [%s] %s", sock->hostname, sock->port,
1712 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1713 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1714 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1715 "Router"), strerror(errno)));
1721 SILC_LOG_DEBUG(("Read EOF"));
1723 /* If connection is disconnecting already we will finally
1724 close the connection */
1725 if (SILC_IS_DISCONNECTING(sock)) {
1726 if (sock->user_data)
1727 silc_server_free_sock_user_data(server, sock, NULL);
1728 silc_server_close_connection(server, sock);
1732 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1733 SILC_SET_DISCONNECTING(sock);
1735 if (sock->user_data) {
1737 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1738 silc_server_free_sock_user_data(server, sock, tmp);
1740 silc_server_free_sock_user_data(server, sock, NULL);
1741 } else if (server->router_conn && server->router_conn->sock == sock &&
1742 !server->router && server->standalone)
1743 silc_schedule_task_add(server->schedule, 0,
1744 silc_server_connect_to_router,
1747 SILC_TASK_PRI_NORMAL);
1749 silc_server_close_connection(server, sock);
1753 /* If connection is disconnecting or disconnected we will ignore
1755 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1756 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1760 server->stat.packets_received++;
1762 /* Get keys and stuff from ID entry */
1763 idata = (SilcIDListData)sock->user_data;
1765 cipher = idata->receive_key;
1766 hmac = idata->hmac_receive;
1767 sequence = idata->psn_receive;
1770 /* Process the packet. This will call the parser that will then
1771 decrypt and parse the packet. */
1772 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1773 TRUE : FALSE, cipher, hmac, sequence,
1774 silc_server_packet_parse, server);
1776 /* If this socket connection is not authenticated yet and the packet
1777 processing failed we will drop the connection since it can be
1778 a malicious flooder. */
1779 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1780 (!sock->protocol || sock->protocol->protocol->type ==
1781 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1782 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1783 SILC_SET_DISCONNECTING(sock);
1785 if (sock->user_data)
1786 silc_server_free_sock_user_data(server, sock, NULL);
1787 silc_server_close_connection(server, sock);
1791 /* Parses whole packet, received earlier. */
1793 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1795 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1796 SilcServer server = (SilcServer)parse_ctx->context;
1797 SilcSocketConnection sock = parse_ctx->sock;
1798 SilcPacketContext *packet = parse_ctx->packet;
1799 SilcIDListData idata = (SilcIDListData)sock->user_data;
1802 SILC_LOG_DEBUG(("Start"));
1804 /* Parse the packet */
1805 if (parse_ctx->normal)
1806 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1808 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1810 /* If entry is disabled ignore what we got. */
1811 if (ret != SILC_PACKET_RESUME_ROUTER &&
1812 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1813 SILC_LOG_DEBUG(("Connection is disabled"));
1817 if (ret == SILC_PACKET_NONE)
1820 /* Check that the the current client ID is same as in the client's packet. */
1821 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1822 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1823 if (client && client->id) {
1824 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1825 packet->src_id_type);
1826 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1834 if (server->server_type == SILC_ROUTER) {
1835 /* Route the packet if it is not destined to us. Other ID types but
1836 server are handled separately after processing them. */
1837 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1838 packet->dst_id_type == SILC_ID_SERVER &&
1839 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1840 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1842 /* Route the packet to fastest route for the destination ID */
1843 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1844 packet->dst_id_type);
1847 silc_server_packet_route(server,
1848 silc_server_route_get(server, id,
1849 packet->dst_id_type),
1856 /* Parse the incoming packet type */
1857 silc_server_packet_parse_type(server, sock, packet);
1859 if (server->server_type == SILC_ROUTER) {
1860 /* Broadcast packet if it is marked as broadcast packet and it is
1861 originated from router and we are router. */
1862 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1863 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1864 !server->standalone) {
1865 /* Broadcast to our primary route */
1866 silc_server_packet_broadcast(server, server->router->connection, packet);
1868 /* If we have backup routers then we need to feed all broadcast
1869 data to those servers. */
1870 silc_server_backup_broadcast(server, sock, packet);
1875 silc_packet_context_free(packet);
1876 silc_free(parse_ctx);
1879 /* Parser callback called by silc_packet_receive_process. This merely
1880 registers timeout that will handle the actual parsing when appropriate. */
1882 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1885 SilcServer server = (SilcServer)context;
1886 SilcSocketConnection sock = parser_context->sock;
1887 SilcIDListData idata = (SilcIDListData)sock->user_data;
1890 idata->psn_receive = parser_context->packet->sequence + 1;
1892 /* If protocol for this connection is key exchange or rekey then we'll
1893 process all packets synchronously, since there might be packets in
1894 queue that we are not able to decrypt without first processing the
1895 packets before them. */
1896 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1897 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1898 (sock->protocol && sock->protocol->protocol &&
1899 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1900 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1901 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1904 /* Reprocess data since we'll return FALSE here. This is because
1905 the idata->receive_key might have become valid in the last packet
1906 and we want to call this processor with valid cipher. */
1908 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1909 TRUE : FALSE, idata->receive_key,
1910 idata->hmac_receive, idata->psn_receive,
1911 silc_server_packet_parse, server);
1913 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1914 TRUE : FALSE, NULL, NULL, 0,
1915 silc_server_packet_parse, server);
1919 switch (sock->type) {
1920 case SILC_SOCKET_TYPE_UNKNOWN:
1921 case SILC_SOCKET_TYPE_CLIENT:
1922 /* Parse the packet with timeout */
1923 silc_schedule_task_add(server->schedule, sock->sock,
1924 silc_server_packet_parse_real,
1925 (void *)parser_context, 0, 100000,
1927 SILC_TASK_PRI_NORMAL);
1929 case SILC_SOCKET_TYPE_SERVER:
1930 case SILC_SOCKET_TYPE_ROUTER:
1931 /* Packets from servers are parsed immediately */
1932 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1942 /* Parses the packet type and calls what ever routines the packet type
1943 requires. This is done for all incoming packets. */
1945 void silc_server_packet_parse_type(SilcServer server,
1946 SilcSocketConnection sock,
1947 SilcPacketContext *packet)
1949 SilcPacketType type = packet->type;
1950 SilcIDListData idata = (SilcIDListData)sock->user_data;
1952 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1954 /* Parse the packet type */
1956 case SILC_PACKET_DISCONNECT:
1957 SILC_LOG_DEBUG(("Disconnect packet"));
1958 if (packet->flags & SILC_PACKET_FLAG_LIST)
1960 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1961 /* Duplicate to null terminate the string. */
1962 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1963 SILC_LOG_ERROR(("%s", message));
1968 case SILC_PACKET_SUCCESS:
1970 * Success received for something. For now we can have only
1971 * one protocol for connection executing at once hence this
1972 * success message is for whatever protocol is executing currently.
1974 SILC_LOG_DEBUG(("Success packet"));
1975 if (packet->flags & SILC_PACKET_FLAG_LIST)
1978 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1981 case SILC_PACKET_FAILURE:
1983 * Failure received for something. For now we can have only
1984 * one protocol for connection executing at once hence this
1985 * failure message is for whatever protocol is executing currently.
1987 SILC_LOG_DEBUG(("Failure packet"));
1988 if (packet->flags & SILC_PACKET_FLAG_LIST)
1990 if (sock->protocol) {
1991 SilcServerFailureContext f;
1992 f = silc_calloc(1, sizeof(*f));
1996 /* We will wait 5 seconds to process this failure packet */
1997 silc_schedule_task_add(server->schedule, sock->sock,
1998 silc_server_failure_callback, (void *)f, 5, 0,
1999 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2003 case SILC_PACKET_REJECT:
2004 SILC_LOG_DEBUG(("Reject packet"));
2005 if (packet->flags & SILC_PACKET_FLAG_LIST)
2010 case SILC_PACKET_NOTIFY:
2012 * Received notify packet. Server can receive notify packets from
2013 * router. Server then relays the notify messages to clients if needed.
2015 SILC_LOG_DEBUG(("Notify packet"));
2016 if (packet->flags & SILC_PACKET_FLAG_LIST)
2017 silc_server_notify_list(server, sock, packet);
2019 silc_server_notify(server, sock, packet);
2025 case SILC_PACKET_CHANNEL_MESSAGE:
2027 * Received channel message. Channel messages are special packets
2028 * (although probably most common ones) thus they are handled
2031 SILC_LOG_DEBUG(("Channel Message packet"));
2032 if (packet->flags & SILC_PACKET_FLAG_LIST)
2034 idata->last_receive = time(NULL);
2035 silc_server_channel_message(server, sock, packet);
2038 case SILC_PACKET_CHANNEL_KEY:
2040 * Received key for channel. As channels are created by the router
2041 * the keys are as well. We will distribute the key to all of our
2042 * locally connected clients on the particular channel. Router
2043 * never receives this channel and thus is ignored.
2045 SILC_LOG_DEBUG(("Channel Key packet"));
2046 if (packet->flags & SILC_PACKET_FLAG_LIST)
2048 silc_server_channel_key(server, sock, packet);
2054 case SILC_PACKET_COMMAND:
2056 * Recived command. Processes the command request and allocates the
2057 * command context and calls the command.
2059 SILC_LOG_DEBUG(("Command packet"));
2060 if (packet->flags & SILC_PACKET_FLAG_LIST)
2062 silc_server_command_process(server, sock, packet);
2065 case SILC_PACKET_COMMAND_REPLY:
2067 * Received command reply packet. Received command reply to command. It
2068 * may be reply to command sent by us or reply to command sent by client
2069 * that we've routed further.
2071 SILC_LOG_DEBUG(("Command Reply packet"));
2072 if (packet->flags & SILC_PACKET_FLAG_LIST)
2074 silc_server_command_reply(server, sock, packet);
2078 * Private Message packets
2080 case SILC_PACKET_PRIVATE_MESSAGE:
2082 * Received private message packet. The packet is coming from either
2085 SILC_LOG_DEBUG(("Private Message packet"));
2086 if (packet->flags & SILC_PACKET_FLAG_LIST)
2088 idata->last_receive = time(NULL);
2089 silc_server_private_message(server, sock, packet);
2092 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2094 * Private message key packet.
2096 if (packet->flags & SILC_PACKET_FLAG_LIST)
2098 silc_server_private_message_key(server, sock, packet);
2102 * Key Exchange protocol packets
2104 case SILC_PACKET_KEY_EXCHANGE:
2105 SILC_LOG_DEBUG(("KE packet"));
2106 if (packet->flags & SILC_PACKET_FLAG_LIST)
2109 if (sock->protocol && sock->protocol->protocol &&
2110 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2111 SilcServerKEInternalContext *proto_ctx =
2112 (SilcServerKEInternalContext *)sock->protocol->context;
2114 proto_ctx->packet = silc_packet_context_dup(packet);
2116 /* Let the protocol handle the packet */
2117 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2119 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2120 "protocol active, packet dropped."));
2124 case SILC_PACKET_KEY_EXCHANGE_1:
2125 SILC_LOG_DEBUG(("KE 1 packet"));
2126 if (packet->flags & SILC_PACKET_FLAG_LIST)
2129 if (sock->protocol && sock->protocol->protocol &&
2130 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2131 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2133 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2134 SilcServerRekeyInternalContext *proto_ctx =
2135 (SilcServerRekeyInternalContext *)sock->protocol->context;
2137 if (proto_ctx->packet)
2138 silc_packet_context_free(proto_ctx->packet);
2140 proto_ctx->packet = silc_packet_context_dup(packet);
2142 /* Let the protocol handle the packet */
2143 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2145 SilcServerKEInternalContext *proto_ctx =
2146 (SilcServerKEInternalContext *)sock->protocol->context;
2148 if (proto_ctx->packet)
2149 silc_packet_context_free(proto_ctx->packet);
2151 proto_ctx->packet = silc_packet_context_dup(packet);
2152 proto_ctx->dest_id_type = packet->src_id_type;
2153 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2154 packet->src_id_type);
2155 if (!proto_ctx->dest_id)
2158 /* Let the protocol handle the packet */
2159 silc_protocol_execute(sock->protocol, server->schedule,
2163 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2164 "protocol active, packet dropped."));
2168 case SILC_PACKET_KEY_EXCHANGE_2:
2169 SILC_LOG_DEBUG(("KE 2 packet"));
2170 if (packet->flags & SILC_PACKET_FLAG_LIST)
2173 if (sock->protocol && sock->protocol->protocol &&
2174 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2175 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2177 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2178 SilcServerRekeyInternalContext *proto_ctx =
2179 (SilcServerRekeyInternalContext *)sock->protocol->context;
2181 if (proto_ctx->packet)
2182 silc_packet_context_free(proto_ctx->packet);
2184 proto_ctx->packet = silc_packet_context_dup(packet);
2186 /* Let the protocol handle the packet */
2187 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2189 SilcServerKEInternalContext *proto_ctx =
2190 (SilcServerKEInternalContext *)sock->protocol->context;
2192 if (proto_ctx->packet)
2193 silc_packet_context_free(proto_ctx->packet);
2195 proto_ctx->packet = silc_packet_context_dup(packet);
2196 proto_ctx->dest_id_type = packet->src_id_type;
2197 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2198 packet->src_id_type);
2199 if (!proto_ctx->dest_id)
2202 /* Let the protocol handle the packet */
2203 silc_protocol_execute(sock->protocol, server->schedule,
2207 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2208 "protocol active, packet dropped."));
2212 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2214 * Connection authentication request packet. When we receive this packet
2215 * we will send to the other end information about our mandatory
2216 * authentication method for the connection. This packet maybe received
2219 SILC_LOG_DEBUG(("Connection authentication request packet"));
2220 if (packet->flags & SILC_PACKET_FLAG_LIST)
2222 silc_server_connection_auth_request(server, sock, packet);
2226 * Connection Authentication protocol packets
2228 case SILC_PACKET_CONNECTION_AUTH:
2229 /* Start of the authentication protocol. We receive here the
2230 authentication data and will verify it. */
2231 SILC_LOG_DEBUG(("Connection auth packet"));
2232 if (packet->flags & SILC_PACKET_FLAG_LIST)
2235 if (sock->protocol && sock->protocol->protocol->type
2236 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2238 SilcServerConnAuthInternalContext *proto_ctx =
2239 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2241 proto_ctx->packet = silc_packet_context_dup(packet);
2243 /* Let the protocol handle the packet */
2244 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2246 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2247 "protocol active, packet dropped."));
2251 case SILC_PACKET_NEW_ID:
2253 * Received New ID packet. This includes some new ID that has been
2254 * created. It may be for client, server or channel. This is the way
2255 * to distribute information about new registered entities in the
2258 SILC_LOG_DEBUG(("New ID packet"));
2259 if (packet->flags & SILC_PACKET_FLAG_LIST)
2260 silc_server_new_id_list(server, sock, packet);
2262 silc_server_new_id(server, sock, packet);
2265 case SILC_PACKET_NEW_CLIENT:
2267 * Received new client packet. This includes client information that
2268 * we will use to create initial client ID. After creating new
2269 * ID we will send it to the client.
2271 SILC_LOG_DEBUG(("New Client packet"));
2272 if (packet->flags & SILC_PACKET_FLAG_LIST)
2274 silc_server_new_client(server, sock, packet);
2277 case SILC_PACKET_NEW_SERVER:
2279 * Received new server packet. This includes Server ID and some other
2280 * information that we may save. This is received after server has
2283 SILC_LOG_DEBUG(("New Server packet"));
2284 if (packet->flags & SILC_PACKET_FLAG_LIST)
2286 silc_server_new_server(server, sock, packet);
2289 case SILC_PACKET_NEW_CHANNEL:
2291 * Received new channel packet. Information about new channel in the
2292 * network are distributed using this packet.
2294 SILC_LOG_DEBUG(("New Channel packet"));
2295 if (packet->flags & SILC_PACKET_FLAG_LIST)
2296 silc_server_new_channel_list(server, sock, packet);
2298 silc_server_new_channel(server, sock, packet);
2301 case SILC_PACKET_HEARTBEAT:
2303 * Received heartbeat.
2305 SILC_LOG_DEBUG(("Heartbeat packet"));
2306 if (packet->flags & SILC_PACKET_FLAG_LIST)
2310 case SILC_PACKET_KEY_AGREEMENT:
2312 * Received heartbeat.
2314 SILC_LOG_DEBUG(("Key agreement packet"));
2315 if (packet->flags & SILC_PACKET_FLAG_LIST)
2317 silc_server_key_agreement(server, sock, packet);
2320 case SILC_PACKET_REKEY:
2322 * Received re-key packet. The sender wants to regenerate the session
2325 SILC_LOG_DEBUG(("Re-key packet"));
2326 if (packet->flags & SILC_PACKET_FLAG_LIST)
2328 silc_server_rekey(server, sock, packet);
2331 case SILC_PACKET_REKEY_DONE:
2333 * The re-key is done.
2335 SILC_LOG_DEBUG(("Re-key done packet"));
2336 if (packet->flags & SILC_PACKET_FLAG_LIST)
2339 if (sock->protocol && sock->protocol->protocol &&
2340 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2342 SilcServerRekeyInternalContext *proto_ctx =
2343 (SilcServerRekeyInternalContext *)sock->protocol->context;
2345 if (proto_ctx->packet)
2346 silc_packet_context_free(proto_ctx->packet);
2348 proto_ctx->packet = silc_packet_context_dup(packet);
2350 /* Let the protocol handle the packet */
2351 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2353 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2354 "protocol active, packet dropped."));
2358 case SILC_PACKET_FTP:
2360 SILC_LOG_DEBUG(("FTP packet"));
2361 if (packet->flags & SILC_PACKET_FLAG_LIST)
2363 silc_server_ftp(server, sock, packet);
2366 case SILC_PACKET_RESUME_ROUTER:
2367 /* Resume router packet received. This packet is received for backup
2368 router resuming protocol. */
2369 SILC_LOG_DEBUG(("Resume router packet"));
2370 if (packet->flags & SILC_PACKET_FLAG_LIST)
2372 silc_server_backup_resume_router(server, sock, packet);
2376 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2382 /* Creates connection to a remote router. */
2384 void silc_server_create_connection(SilcServer server,
2385 const char *remote_host, SilcUInt32 port)
2387 SilcServerConnection sconn;
2389 /* Allocate connection object for hold connection specific stuff. */
2390 sconn = silc_calloc(1, sizeof(*sconn));
2391 sconn->server = server;
2392 sconn->remote_host = strdup(remote_host);
2393 sconn->remote_port = port;
2394 sconn->no_reconnect = TRUE;
2396 silc_schedule_task_add(server->schedule, 0,
2397 silc_server_connect_router,
2398 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2399 SILC_TASK_PRI_NORMAL);
2402 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2404 silc_socket_free((SilcSocketConnection)context);
2407 /* Closes connection to socket connection */
2409 void silc_server_close_connection(SilcServer server,
2410 SilcSocketConnection sock)
2412 if (!server->sockets[sock->sock])
2415 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2417 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2418 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2419 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2422 /* We won't listen for this connection anymore */
2423 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2425 /* Unregister all tasks */
2426 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2428 /* Close the actual connection */
2429 silc_net_close_connection(sock->sock);
2430 server->sockets[sock->sock] = NULL;
2432 /* If sock->user_data is NULL then we'll check for active protocols
2433 here since the silc_server_free_sock_user_data has not been called
2434 for this connection. */
2435 if (!sock->user_data) {
2436 /* If any protocol is active cancel its execution. It will call
2437 the final callback which will finalize the disconnection. */
2438 if (sock->protocol) {
2439 silc_protocol_cancel(sock->protocol, server->schedule);
2440 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2441 silc_protocol_execute_final(sock->protocol, server->schedule);
2442 sock->protocol = NULL;
2447 silc_schedule_task_add(server->schedule, 0,
2448 silc_server_close_connection_final,
2449 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2450 SILC_TASK_PRI_NORMAL);
2453 /* Sends disconnect message to remote connection and disconnects the
2456 void silc_server_disconnect_remote(SilcServer server,
2457 SilcSocketConnection sock,
2458 const char *fmt, ...)
2461 unsigned char buf[4096];
2466 memset(buf, 0, sizeof(buf));
2468 vsprintf(buf, fmt, ap);
2471 SILC_LOG_DEBUG(("Disconnecting remote host"));
2473 /* Notify remote end that the conversation is over. The notify message
2474 is tried to be sent immediately. */
2475 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2476 buf, strlen(buf), TRUE);
2477 silc_server_packet_queue_purge(server, sock);
2479 /* Mark the connection to be disconnected */
2480 SILC_SET_DISCONNECTED(sock);
2481 silc_server_close_connection(server, sock);
2486 SilcClientEntry client;
2487 } *FreeClientInternal;
2489 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2491 FreeClientInternal i = (FreeClientInternal)context;
2493 silc_idlist_del_data(i->client);
2494 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2498 /* Frees client data and notifies about client's signoff. */
2500 void silc_server_free_client_data(SilcServer server,
2501 SilcSocketConnection sock,
2502 SilcClientEntry client,
2504 const char *signoff)
2506 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2508 /* If there is pending outgoing data for the client then purge it
2509 to the network before removing the client entry. */
2510 silc_server_packet_queue_purge(server, sock);
2515 /* Send SIGNOFF notify to routers. */
2516 if (notify && !server->standalone && server->router)
2517 silc_server_send_notify_signoff(server, server->router->connection,
2518 server->server_type == SILC_SERVER ?
2519 FALSE : TRUE, client->id, signoff);
2521 /* Remove client from all channels */
2523 silc_server_remove_from_channels(server, NULL, client,
2524 TRUE, (char *)signoff, TRUE);
2526 silc_server_remove_from_channels(server, NULL, client,
2527 FALSE, NULL, FALSE);
2529 /* Update statistics */
2530 server->stat.my_clients--;
2531 server->stat.clients--;
2532 if (server->server_type == SILC_ROUTER)
2533 server->stat.cell_clients--;
2534 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2535 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2537 /* We will not delete the client entry right away. We will take it
2538 into history (for WHOWAS command) for 5 minutes */
2541 silc_schedule_task_add(server->schedule, 0,
2542 silc_server_free_client_data_timeout,
2544 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2545 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2546 client->router = NULL;
2547 client->connection = NULL;
2551 /* Frees user_data pointer from socket connection object. This also sends
2552 appropriate notify packets to the network to inform about leaving
2555 void silc_server_free_sock_user_data(SilcServer server,
2556 SilcSocketConnection sock,
2557 const char *signoff_message)
2559 SILC_LOG_DEBUG(("Start"));
2561 switch (sock->type) {
2562 case SILC_SOCKET_TYPE_CLIENT:
2564 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2565 silc_server_free_client_data(server, sock, user_data, TRUE,
2569 case SILC_SOCKET_TYPE_SERVER:
2570 case SILC_SOCKET_TYPE_ROUTER:
2572 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2573 SilcServerEntry backup_router = NULL;
2576 backup_router = silc_server_backup_get(server, user_data->id);
2578 /* If this was our primary router connection then we're lost to
2579 the outside world. */
2580 if (server->router == user_data) {
2581 /* Check whether we have a backup router connection */
2582 if (!backup_router || backup_router == user_data) {
2583 silc_schedule_task_add(server->schedule, 0,
2584 silc_server_connect_to_router,
2587 SILC_TASK_PRI_NORMAL);
2589 server->id_entry->router = NULL;
2590 server->router = NULL;
2591 server->standalone = TRUE;
2592 backup_router = NULL;
2594 SILC_LOG_INFO(("New primary router is backup router %s",
2595 backup_router->server_name));
2596 SILC_LOG_DEBUG(("New primary router is backup router %s",
2597 backup_router->server_name));
2598 server->id_entry->router = backup_router;
2599 server->router = backup_router;
2600 server->router_connect = time(0);
2601 server->backup_primary = TRUE;
2602 if (server->server_type == SILC_BACKUP_ROUTER) {
2603 server->server_type = SILC_ROUTER;
2605 /* We'll need to constantly try to reconnect to the primary
2606 router so that we'll see when it comes back online. */
2607 silc_server_backup_reconnect(server, sock->ip, sock->port,
2608 silc_server_backup_connected,
2612 /* Mark this connection as replaced */
2613 silc_server_backup_replaced_add(server, user_data->id,
2616 } else if (backup_router) {
2617 SILC_LOG_INFO(("Enabling the use of backup router %s",
2618 backup_router->server_name));
2619 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2620 backup_router->server_name));
2622 /* Mark this connection as replaced */
2623 silc_server_backup_replaced_add(server, user_data->id,
2627 if (!backup_router) {
2628 /* Free all client entries that this server owns as they will
2629 become invalid now as well. */
2631 silc_server_remove_clients_by_server(server, user_data, TRUE);
2632 if (server->server_type == SILC_SERVER)
2633 silc_server_remove_channels_by_server(server, user_data);
2635 /* Update the client entries of this server to the new backup
2636 router. This also removes the clients that *really* was owned
2637 by the primary router and went down with the router. */
2638 silc_server_update_clients_by_server(server, user_data, backup_router,
2640 silc_server_update_servers_by_server(server, user_data, backup_router);
2641 if (server->server_type == SILC_SERVER)
2642 silc_server_update_channels_by_server(server, user_data,
2646 /* Free the server entry */
2647 silc_server_backup_del(server, user_data);
2648 silc_server_backup_replaced_del(server, user_data);
2649 silc_idlist_del_data(user_data);
2650 if (!silc_idlist_del_server(server->local_list, user_data))
2651 silc_idlist_del_server(server->global_list, user_data);
2652 server->stat.my_servers--;
2653 server->stat.servers--;
2654 if (server->server_type == SILC_ROUTER)
2655 server->stat.cell_servers--;
2657 if (backup_router) {
2658 /* Announce all of our stuff that was created about 5 minutes ago.
2659 The backup router knows all the other stuff already. */
2660 if (server->server_type == SILC_ROUTER)
2661 silc_server_announce_servers(server, FALSE, time(0) - 300,
2662 backup_router->connection);
2664 /* Announce our clients and channels to the router */
2665 silc_server_announce_clients(server, time(0) - 300,
2666 backup_router->connection);
2667 silc_server_announce_channels(server, time(0) - 300,
2668 backup_router->connection);
2674 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2676 silc_idlist_del_data(user_data);
2677 silc_free(user_data);
2682 /* If any protocol is active cancel its execution */
2683 if (sock->protocol) {
2684 silc_protocol_cancel(sock->protocol, server->schedule);
2685 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2686 silc_protocol_execute_final(sock->protocol, server->schedule);
2687 sock->protocol = NULL;
2690 sock->user_data = NULL;
2693 /* Removes client from all channels it has joined. This is used when client
2694 connection is disconnected. If the client on a channel is last, the
2695 channel is removed as well. This sends the SIGNOFF notify types. */
2697 void silc_server_remove_from_channels(SilcServer server,
2698 SilcSocketConnection sock,
2699 SilcClientEntry client,
2701 char *signoff_message,
2704 SilcChannelEntry channel;
2705 SilcChannelClientEntry chl;
2706 SilcHashTableList htl;
2709 SILC_LOG_DEBUG(("Start"));
2711 if (!client || !client->id)
2714 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2716 /* Remove the client from all channels. The client is removed from
2717 the channels' user list. */
2718 silc_hash_table_list(client->channels, &htl);
2719 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2720 channel = chl->channel;
2722 /* Remove channel from client's channel list */
2723 silc_hash_table_del(client->channels, channel);
2725 /* Remove channel if there is no users anymore */
2726 if (server->server_type == SILC_ROUTER &&
2727 silc_hash_table_count(channel->user_list) < 2) {
2729 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2730 if (silc_idlist_del_channel(server->local_list, channel))
2731 server->stat.my_channels--;
2733 silc_idlist_del_channel(server->global_list, channel);
2737 /* Remove client from channel's client list */
2738 silc_hash_table_del(channel->user_list, chl->client);
2739 channel->user_count--;
2741 /* If there is no global users on the channel anymore mark the channel
2742 as local channel. Do not check if the removed client is local client. */
2743 if (server->server_type != SILC_ROUTER && channel->global_users &&
2744 chl->client->router && !silc_server_channel_has_global(channel))
2745 channel->global_users = FALSE;
2748 server->stat.my_chanclients--;
2750 /* If there is not at least one local user on the channel then we don't
2751 need the channel entry anymore, we can remove it safely. */
2752 if (server->server_type != SILC_ROUTER &&
2753 !silc_server_channel_has_local(channel)) {
2754 /* Notify about leaving client if this channel has global users. */
2755 if (notify && channel->global_users)
2756 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2757 SILC_NOTIFY_TYPE_SIGNOFF,
2758 signoff_message ? 2 : 1,
2759 clidp->data, clidp->len,
2760 signoff_message, signoff_message ?
2761 strlen(signoff_message) : 0);
2764 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2766 if (channel->founder_key) {
2767 /* The founder auth data exists, do not remove the channel entry */
2768 SilcChannelClientEntry chl2;
2769 SilcHashTableList htl2;
2771 channel->disabled = TRUE;
2773 silc_hash_table_list(channel->user_list, &htl2);
2774 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2775 silc_hash_table_del(chl2->client->channels, channel);
2776 silc_hash_table_del(channel->user_list, chl2->client);
2777 channel->user_count--;
2780 silc_hash_table_list_reset(&htl2);
2784 /* Remove the channel entry */
2785 if (silc_idlist_del_channel(server->local_list, channel))
2786 server->stat.my_channels--;
2788 silc_idlist_del_channel(server->global_list, channel);
2792 /* Send notify to channel about client leaving SILC and thus
2793 the entire channel. */
2795 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2796 SILC_NOTIFY_TYPE_SIGNOFF,
2797 signoff_message ? 2 : 1,
2798 clidp->data, clidp->len,
2799 signoff_message, signoff_message ?
2800 strlen(signoff_message) : 0);
2802 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2803 /* Re-generate channel key */
2804 if (!silc_server_create_channel_key(server, channel, 0))
2807 /* Send the channel key to the channel. The key of course is not sent
2808 to the client who was removed from the channel. */
2809 silc_server_send_channel_key(server, client->connection, channel,
2810 server->server_type == SILC_ROUTER ?
2811 FALSE : !server->standalone);
2816 silc_hash_table_list_reset(&htl);
2817 silc_buffer_free(clidp);
2820 /* Removes client from one channel. This is used for example when client
2821 calls LEAVE command to remove itself from the channel. Returns TRUE
2822 if channel still exists and FALSE if the channel is removed when
2823 last client leaves the channel. If `notify' is FALSE notify messages
2826 int silc_server_remove_from_one_channel(SilcServer server,
2827 SilcSocketConnection sock,
2828 SilcChannelEntry channel,
2829 SilcClientEntry client,
2832 SilcChannelClientEntry chl;
2835 SILC_LOG_DEBUG(("Start"));
2837 /* Get the entry to the channel, if this client is not on the channel
2839 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2842 /* Remove the client from the channel. The client is removed from
2843 the channel's user list. */
2845 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2847 /* Remove channel from client's channel list */
2848 silc_hash_table_del(client->channels, chl->channel);
2850 /* Remove channel if there is no users anymore */
2851 if (server->server_type == SILC_ROUTER &&
2852 silc_hash_table_count(channel->user_list) < 2) {
2854 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2855 if (silc_idlist_del_channel(server->local_list, channel))
2856 server->stat.my_channels--;
2858 silc_idlist_del_channel(server->global_list, channel);
2859 silc_buffer_free(clidp);
2863 /* Remove client from channel's client list */
2864 silc_hash_table_del(channel->user_list, chl->client);
2865 channel->user_count--;
2867 /* If there is no global users on the channel anymore mark the channel
2868 as local channel. Do not check if the client is local client. */
2869 if (server->server_type != SILC_ROUTER && channel->global_users &&
2870 chl->client->router && !silc_server_channel_has_global(channel))
2871 channel->global_users = FALSE;
2874 server->stat.my_chanclients--;
2876 /* If there is not at least one local user on the channel then we don't
2877 need the channel entry anymore, we can remove it safely. */
2878 if (server->server_type != SILC_ROUTER &&
2879 !silc_server_channel_has_local(channel)) {
2880 /* Notify about leaving client if this channel has global users. */
2881 if (notify && channel->global_users)
2882 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2883 SILC_NOTIFY_TYPE_LEAVE, 1,
2884 clidp->data, clidp->len);
2886 silc_buffer_free(clidp);
2889 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2891 if (channel->founder_key) {
2892 /* The founder auth data exists, do not remove the channel entry */
2893 SilcChannelClientEntry chl2;
2894 SilcHashTableList htl2;
2896 channel->disabled = TRUE;
2898 silc_hash_table_list(channel->user_list, &htl2);
2899 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2900 silc_hash_table_del(chl2->client->channels, channel);
2901 silc_hash_table_del(channel->user_list, chl2->client);
2902 channel->user_count--;
2905 silc_hash_table_list_reset(&htl2);
2909 /* Remove the channel entry */
2910 if (silc_idlist_del_channel(server->local_list, channel))
2911 server->stat.my_channels--;
2913 silc_idlist_del_channel(server->global_list, channel);
2917 /* Send notify to channel about client leaving the channel */
2919 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2920 SILC_NOTIFY_TYPE_LEAVE, 1,
2921 clidp->data, clidp->len);
2923 silc_buffer_free(clidp);
2927 /* Timeout callback. This is called if connection is idle or for some
2928 other reason is not responding within some period of time. This
2929 disconnects the remote end. */
2931 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2933 SilcServer server = (SilcServer)context;
2934 SilcSocketConnection sock = server->sockets[fd];
2936 SILC_LOG_DEBUG(("Start"));
2941 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2942 sock->hostname, sock->ip));
2944 /* If we have protocol active we must assure that we call the protocol's
2945 final callback so that all the memory is freed. */
2946 if (sock->protocol) {
2947 silc_protocol_cancel(sock->protocol, server->schedule);
2948 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2949 silc_protocol_execute_final(sock->protocol, server->schedule);
2950 sock->protocol = NULL;
2954 if (sock->user_data)
2955 silc_server_free_sock_user_data(server, sock, NULL);
2957 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2958 "Connection timeout");
2961 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2962 function may be used only by router. In real SILC network all channels
2963 are created by routers thus this function is never used by normal
2966 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2967 SilcServerID *router_id,
2973 SilcChannelID *channel_id;
2974 SilcChannelEntry entry;
2978 SILC_LOG_DEBUG(("Creating new channel"));
2981 cipher = SILC_DEFAULT_CIPHER;
2983 hmac = SILC_DEFAULT_HMAC;
2985 /* Allocate cipher */
2986 if (!silc_cipher_alloc(cipher, &key))
2990 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2991 silc_cipher_free(key);
2995 channel_name = strdup(channel_name);
2997 /* Create the channel ID */
2998 if (!silc_id_create_channel_id(server, router_id, server->rng,
3000 silc_free(channel_name);
3001 silc_cipher_free(key);
3002 silc_hmac_free(newhmac);
3006 /* Create the channel */
3007 entry = silc_idlist_add_channel(server->local_list, channel_name,
3008 SILC_CHANNEL_MODE_NONE, channel_id,
3009 NULL, key, newhmac, 0);
3011 silc_free(channel_name);
3012 silc_cipher_free(key);
3013 silc_hmac_free(newhmac);
3014 silc_free(channel_id);
3018 entry->cipher = strdup(cipher);
3019 entry->hmac_name = strdup(hmac);
3021 /* Now create the actual key material */
3022 if (!silc_server_create_channel_key(server, entry,
3023 silc_cipher_get_key_len(key) / 8)) {
3024 silc_idlist_del_channel(server->local_list, entry);
3028 /* Notify other routers about the new channel. We send the packet
3029 to our primary route. */
3030 if (broadcast && server->standalone == FALSE)
3031 silc_server_send_new_channel(server, server->router->connection, TRUE,
3032 channel_name, entry->id,
3033 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3036 server->stat.my_channels++;
3041 /* Same as above but creates the channel with Channel ID `channel_id. */
3044 silc_server_create_new_channel_with_id(SilcServer server,
3048 SilcChannelID *channel_id,
3051 SilcChannelEntry entry;
3055 SILC_LOG_DEBUG(("Creating new channel"));
3058 cipher = SILC_DEFAULT_CIPHER;
3060 hmac = SILC_DEFAULT_HMAC;
3062 /* Allocate cipher */
3063 if (!silc_cipher_alloc(cipher, &key))
3067 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3068 silc_cipher_free(key);
3072 channel_name = strdup(channel_name);
3074 /* Create the channel */
3075 entry = silc_idlist_add_channel(server->local_list, channel_name,
3076 SILC_CHANNEL_MODE_NONE, channel_id,
3077 NULL, key, newhmac, 0);
3079 silc_cipher_free(key);
3080 silc_hmac_free(newhmac);
3081 silc_free(channel_name);
3085 /* Now create the actual key material */
3086 if (!silc_server_create_channel_key(server, entry,
3087 silc_cipher_get_key_len(key) / 8)) {
3088 silc_idlist_del_channel(server->local_list, entry);
3092 /* Notify other routers about the new channel. We send the packet
3093 to our primary route. */
3094 if (broadcast && server->standalone == FALSE)
3095 silc_server_send_new_channel(server, server->router->connection, TRUE,
3096 channel_name, entry->id,
3097 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3100 server->stat.my_channels++;
3105 /* Channel's key re-key timeout callback. */
3107 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3109 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3110 SilcServer server = (SilcServer)rekey->context;
3114 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3117 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3120 /* Generates new channel key. This is used to create the initial channel key
3121 but also to re-generate new key for channel. If `key_len' is provided
3122 it is the bytes of the key length. */
3124 bool silc_server_create_channel_key(SilcServer server,
3125 SilcChannelEntry channel,
3129 unsigned char channel_key[32], hash[32];
3132 SILC_LOG_DEBUG(("Generating channel key"));
3134 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3135 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3139 if (!channel->channel_key)
3140 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3141 channel->channel_key = NULL;
3147 else if (channel->key_len)
3148 len = channel->key_len / 8;
3150 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3152 /* Create channel key */
3153 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3156 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3158 /* Remove old key if exists */
3160 memset(channel->key, 0, channel->key_len / 8);
3161 silc_free(channel->key);
3165 channel->key_len = len * 8;
3166 channel->key = silc_memdup(channel_key, len);
3167 memset(channel_key, 0, sizeof(channel_key));
3169 /* Generate HMAC key from the channel key data and set it */
3171 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3172 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3173 silc_hmac_set_key(channel->hmac, hash,
3174 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3175 memset(hash, 0, sizeof(hash));
3177 if (server->server_type == SILC_ROUTER) {
3178 if (!channel->rekey)
3179 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3180 channel->rekey->context = (void *)server;
3181 channel->rekey->channel = channel;
3182 channel->rekey->key_len = key_len;
3183 if (channel->rekey->task)
3184 silc_schedule_task_del(server->schedule, channel->rekey->task);
3186 channel->rekey->task =
3187 silc_schedule_task_add(server->schedule, 0,
3188 silc_server_channel_key_rekey,
3189 (void *)channel->rekey,
3190 server->config->channel_rekey_secs, 0,
3192 SILC_TASK_PRI_NORMAL);
3198 /* Saves the channel key found in the encoded `key_payload' buffer. This
3199 function is used when we receive Channel Key Payload and also when we're
3200 processing JOIN command reply. Returns entry to the channel. */
3202 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3203 SilcBuffer key_payload,
3204 SilcChannelEntry channel)
3206 SilcChannelKeyPayload payload = NULL;
3207 SilcChannelID *id = NULL;
3208 unsigned char *tmp, hash[32];
3212 SILC_LOG_DEBUG(("Start"));
3214 /* Decode channel key payload */
3215 payload = silc_channel_key_payload_parse(key_payload->data,
3218 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3223 /* Get the channel entry */
3226 /* Get channel ID */
3227 tmp = silc_channel_key_get_id(payload, &tmp_len);
3228 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3234 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3236 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3238 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3239 silc_id_render(id, SILC_ID_CHANNEL)));
3245 tmp = silc_channel_key_get_key(payload, &tmp_len);
3251 cipher = silc_channel_key_get_cipher(payload, NULL);
3257 /* Remove old key if exists */
3259 memset(channel->key, 0, channel->key_len / 8);
3260 silc_free(channel->key);
3261 silc_cipher_free(channel->channel_key);
3264 /* Create new cipher */
3265 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3266 channel->channel_key = NULL;
3271 if (channel->cipher)
3272 silc_free(channel->cipher);
3273 channel->cipher = strdup(cipher);
3276 channel->key_len = tmp_len * 8;
3277 channel->key = silc_memdup(tmp, tmp_len);
3278 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3280 /* Generate HMAC key from the channel key data and set it */
3282 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3283 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3284 silc_hmac_set_key(channel->hmac, hash,
3285 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3287 memset(hash, 0, sizeof(hash));
3288 memset(tmp, 0, tmp_len);
3290 if (server->server_type == SILC_ROUTER) {
3291 if (!channel->rekey)
3292 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3293 channel->rekey->context = (void *)server;
3294 channel->rekey->channel = channel;
3295 if (channel->rekey->task)
3296 silc_schedule_task_del(server->schedule, channel->rekey->task);
3298 channel->rekey->task =
3299 silc_schedule_task_add(server->schedule, 0,
3300 silc_server_channel_key_rekey,
3301 (void *)channel->rekey,
3302 server->config->channel_rekey_secs, 0,
3304 SILC_TASK_PRI_NORMAL);
3310 silc_channel_key_payload_free(payload);
3315 /* Heartbeat callback. This function is set as argument for the
3316 silc_socket_set_heartbeat function. The library will call this function
3317 at the set time interval. */
3319 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3322 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3324 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3326 /* Send the heartbeat */
3327 silc_server_send_heartbeat(hb->server, sock);
3330 /* Returns assembled of all servers in the given ID list. The packet's
3331 form is dictated by the New ID payload. */
3333 static void silc_server_announce_get_servers(SilcServer server,
3334 SilcServerEntry remote,
3336 SilcBuffer *servers,
3337 unsigned long creation_time)
3339 SilcIDCacheList list;
3340 SilcIDCacheEntry id_cache;
3341 SilcServerEntry entry;
3344 /* Go through all clients in the list */
3345 if (silc_idcache_get_all(id_list->servers, &list)) {
3346 if (silc_idcache_list_first(list, &id_cache)) {
3348 entry = (SilcServerEntry)id_cache->context;
3350 /* Do not announce the one we've sending our announcements and
3351 do not announce ourself. Also check the creation time if it's
3353 if ((entry == remote) || (entry == server->id_entry) ||
3354 (creation_time && entry->data.created < creation_time)) {
3355 if (!silc_idcache_list_next(list, &id_cache))
3360 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3362 *servers = silc_buffer_realloc(*servers,
3364 (*servers)->truelen + idp->len :
3366 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3367 silc_buffer_put(*servers, idp->data, idp->len);
3368 silc_buffer_pull(*servers, idp->len);
3369 silc_buffer_free(idp);
3371 if (!silc_idcache_list_next(list, &id_cache))
3376 silc_idcache_list_free(list);
3381 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3387 p = silc_notify_payload_encode(notify, argc, ap);
3393 /* This function is used by router to announce existing servers to our
3394 primary router when we've connected to it. If `creation_time' is non-zero
3395 then only the servers that has been created after the `creation_time'
3396 will be announced. */
3398 void silc_server_announce_servers(SilcServer server, bool global,
3399 unsigned long creation_time,
3400 SilcSocketConnection remote)
3402 SilcBuffer servers = NULL;
3404 SILC_LOG_DEBUG(("Announcing servers"));
3406 /* Get servers in local list */
3407 silc_server_announce_get_servers(server, remote->user_data,
3408 server->local_list, &servers,
3412 /* Get servers in global list */
3413 silc_server_announce_get_servers(server, remote->user_data,
3414 server->global_list, &servers,
3418 silc_buffer_push(servers, servers->data - servers->head);
3419 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3421 /* Send the packet */
3422 silc_server_packet_send(server, remote,
3423 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3424 servers->data, servers->len, TRUE);
3426 silc_buffer_free(servers);
3430 /* Returns assembled packet of all clients in the given ID list. The
3431 packet's form is dictated by the New ID Payload. */
3433 static void silc_server_announce_get_clients(SilcServer server,
3435 SilcBuffer *clients,
3437 unsigned long creation_time)
3439 SilcIDCacheList list;
3440 SilcIDCacheEntry id_cache;
3441 SilcClientEntry client;
3444 unsigned char mode[4];
3446 /* Go through all clients in the list */
3447 if (silc_idcache_get_all(id_list->clients, &list)) {
3448 if (silc_idcache_list_first(list, &id_cache)) {
3450 client = (SilcClientEntry)id_cache->context;
3452 if (creation_time && client->data.created < creation_time) {
3453 if (!silc_idcache_list_next(list, &id_cache))
3458 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3460 *clients = silc_buffer_realloc(*clients,
3462 (*clients)->truelen + idp->len :
3464 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3465 silc_buffer_put(*clients, idp->data, idp->len);
3466 silc_buffer_pull(*clients, idp->len);
3468 SILC_PUT32_MSB(client->mode, mode);
3469 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3470 2, idp->data, idp->len,
3472 *umodes = silc_buffer_realloc(*umodes,
3474 (*umodes)->truelen + tmp->len :
3476 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3477 silc_buffer_put(*umodes, tmp->data, tmp->len);
3478 silc_buffer_pull(*umodes, tmp->len);
3479 silc_buffer_free(tmp);
3481 silc_buffer_free(idp);
3483 if (!silc_idcache_list_next(list, &id_cache))
3488 silc_idcache_list_free(list);
3492 /* This function is used to announce our existing clients to our router
3493 when we've connected to it. If `creation_time' is non-zero then only
3494 the clients that has been created after the `creation_time' will be
3497 void silc_server_announce_clients(SilcServer server,
3498 unsigned long creation_time,
3499 SilcSocketConnection remote)
3501 SilcBuffer clients = NULL;
3502 SilcBuffer umodes = NULL;
3504 SILC_LOG_DEBUG(("Announcing clients"));
3506 /* Get clients in local list */
3507 silc_server_announce_get_clients(server, server->local_list,
3508 &clients, &umodes, creation_time);
3510 /* As router we announce our global list as well */
3511 if (server->server_type == SILC_ROUTER)
3512 silc_server_announce_get_clients(server, server->global_list,
3513 &clients, &umodes, creation_time);
3516 silc_buffer_push(clients, clients->data - clients->head);
3517 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3519 /* Send the packet */
3520 silc_server_packet_send(server, remote,
3521 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3522 clients->data, clients->len, TRUE);
3524 silc_buffer_free(clients);
3528 silc_buffer_push(umodes, umodes->data - umodes->head);
3529 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3531 /* Send the packet */
3532 silc_server_packet_send(server, remote,
3533 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3534 umodes->data, umodes->len, TRUE);
3536 silc_buffer_free(umodes);
3540 /* Returns channel's topic for announcing it */
3542 void silc_server_announce_get_channel_topic(SilcServer server,
3543 SilcChannelEntry channel,
3548 if (channel->topic) {
3549 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3550 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3551 chidp->data, chidp->len,
3553 strlen(channel->topic));
3554 silc_buffer_free(chidp);
3558 /* Returns assembled packets for channel users of the `channel'. */
3560 void silc_server_announce_get_channel_users(SilcServer server,
3561 SilcChannelEntry channel,
3562 SilcBuffer *channel_users,
3563 SilcBuffer *channel_users_modes)
3565 SilcChannelClientEntry chl;
3566 SilcHashTableList htl;
3567 SilcBuffer chidp, clidp;
3570 unsigned char mode[4];
3572 SILC_LOG_DEBUG(("Start"));
3574 /* Now find all users on the channel */
3575 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3576 silc_hash_table_list(channel->user_list, &htl);
3577 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3578 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3581 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3582 clidp->data, clidp->len,
3583 chidp->data, chidp->len);
3586 silc_buffer_realloc(*channel_users,
3588 (*channel_users)->truelen + len : len));
3589 silc_buffer_pull_tail(*channel_users,
3590 ((*channel_users)->end -
3591 (*channel_users)->data));
3593 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3594 silc_buffer_pull(*channel_users, len);
3595 silc_buffer_free(tmp);
3597 /* CUMODE notify for mode change on the channel */
3598 SILC_PUT32_MSB(chl->mode, mode);
3599 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3600 3, clidp->data, clidp->len,
3602 clidp->data, clidp->len);
3604 *channel_users_modes =
3605 silc_buffer_realloc(*channel_users_modes,
3606 (*channel_users_modes ?
3607 (*channel_users_modes)->truelen + len : len));
3608 silc_buffer_pull_tail(*channel_users_modes,
3609 ((*channel_users_modes)->end -
3610 (*channel_users_modes)->data));
3612 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3613 silc_buffer_pull(*channel_users_modes, len);
3614 silc_buffer_free(tmp);
3616 silc_buffer_free(clidp);
3618 silc_hash_table_list_reset(&htl);
3619 silc_buffer_free(chidp);
3622 /* Returns assembled packets for all channels and users on those channels
3623 from the given ID List. The packets are in the form dictated by the
3624 New Channel and New Channel User payloads. */
3626 void silc_server_announce_get_channels(SilcServer server,
3628 SilcBuffer *channels,
3629 SilcBuffer *channel_users,
3630 SilcBuffer **channel_users_modes,
3631 SilcUInt32 *channel_users_modes_c,
3632 SilcBuffer **channel_topics,
3633 SilcChannelID ***channel_ids,
3634 unsigned long creation_time)
3636 SilcIDCacheList list;
3637 SilcIDCacheEntry id_cache;
3638 SilcChannelEntry channel;
3641 SilcUInt16 name_len;
3643 int i = *channel_users_modes_c;
3646 SILC_LOG_DEBUG(("Start"));
3648 /* Go through all channels in the list */
3649 if (silc_idcache_get_all(id_list->channels, &list)) {
3650 if (silc_idcache_list_first(list, &id_cache)) {
3652 channel = (SilcChannelEntry)id_cache->context;
3654 if (creation_time && channel->created < creation_time)
3659 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3660 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3661 name_len = strlen(channel->channel_name);
3664 len = 4 + name_len + id_len + 4;
3666 silc_buffer_realloc(*channels,
3667 (*channels ? (*channels)->truelen +
3669 silc_buffer_pull_tail(*channels,
3670 ((*channels)->end - (*channels)->data));
3671 silc_buffer_format(*channels,
3672 SILC_STR_UI_SHORT(name_len),
3673 SILC_STR_UI_XNSTRING(channel->channel_name,
3675 SILC_STR_UI_SHORT(id_len),
3676 SILC_STR_UI_XNSTRING(cid, id_len),
3677 SILC_STR_UI_INT(channel->mode),
3679 silc_buffer_pull(*channels, len);
3682 /* Channel user modes */
3683 *channel_users_modes = silc_realloc(*channel_users_modes,
3684 sizeof(**channel_users_modes) *
3686 (*channel_users_modes)[i] = NULL;
3687 *channel_ids = silc_realloc(*channel_ids,
3688 sizeof(**channel_ids) * (i + 1));
3689 (*channel_ids)[i] = NULL;
3690 silc_server_announce_get_channel_users(server, channel,
3692 &(*channel_users_modes)[i]);
3693 (*channel_ids)[i] = channel->id;
3695 /* Channel's topic */
3696 *channel_topics = silc_realloc(*channel_topics,
3697 sizeof(**channel_topics) * (i + 1));
3698 (*channel_topics)[i] = NULL;
3699 silc_server_announce_get_channel_topic(server, channel,
3700 &(*channel_topics)[i]);
3703 if (!silc_idcache_list_next(list, &id_cache))
3707 *channel_users_modes_c += i;
3710 silc_idcache_list_free(list);
3714 /* This function is used to announce our existing channels to our router
3715 when we've connected to it. This also announces the users on the
3716 channels to the router. If the `creation_time' is non-zero only the
3717 channels that was created after the `creation_time' are announced.
3718 Note that the channel users are still announced even if the `creation_time'
3721 void silc_server_announce_channels(SilcServer server,
3722 unsigned long creation_time,
3723 SilcSocketConnection remote)
3725 SilcBuffer channels = NULL, channel_users = NULL;
3726 SilcBuffer *channel_users_modes = NULL;
3727 SilcBuffer *channel_topics = NULL;
3728 SilcUInt32 channel_users_modes_c = 0;
3729 SilcChannelID **channel_ids = NULL;
3731 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3733 /* Get channels and channel users in local list */
3734 silc_server_announce_get_channels(server, server->local_list,
3735 &channels, &channel_users,
3736 &channel_users_modes,
3737 &channel_users_modes_c,
3739 &channel_ids, creation_time);
3741 /* Get channels and channel users in global list */
3742 if (server->server_type != SILC_SERVER)
3743 silc_server_announce_get_channels(server, server->global_list,
3744 &channels, &channel_users,
3745 &channel_users_modes,
3746 &channel_users_modes_c,
3748 &channel_ids, creation_time);
3751 silc_buffer_push(channels, channels->data - channels->head);
3752 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3754 /* Send the packet */
3755 silc_server_packet_send(server, remote,
3756 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3757 channels->data, channels->len,
3760 silc_buffer_free(channels);
3763 if (channel_users) {
3764 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3765 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3766 channel_users->len);
3768 /* Send the packet */
3769 silc_server_packet_send(server, remote,
3770 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3771 channel_users->data, channel_users->len,
3774 silc_buffer_free(channel_users);
3777 if (channel_users_modes) {
3780 for (i = 0; i < channel_users_modes_c; i++) {
3781 if (!channel_users_modes[i])
3783 silc_buffer_push(channel_users_modes[i],
3784 channel_users_modes[i]->data -
3785 channel_users_modes[i]->head);
3786 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3787 channel_users_modes[i]->len);
3788 silc_server_packet_send_dest(server, remote,
3789 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3790 channel_ids[i], SILC_ID_CHANNEL,
3791 channel_users_modes[i]->data,
3792 channel_users_modes[i]->len,
3794 silc_buffer_free(channel_users_modes[i]);
3796 silc_free(channel_users_modes);
3799 if (channel_topics) {
3802 for (i = 0; i < channel_users_modes_c; i++) {
3803 if (!channel_topics[i])
3806 silc_buffer_push(channel_topics[i],
3807 channel_topics[i]->data -
3808 channel_topics[i]->head);
3809 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3810 channel_topics[i]->len);
3811 silc_server_packet_send_dest(server, remote,
3812 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3813 channel_ids[i], SILC_ID_CHANNEL,
3814 channel_topics[i]->data,
3815 channel_topics[i]->len,
3817 silc_buffer_free(channel_topics[i]);
3819 silc_free(channel_topics);
3822 silc_free(channel_ids);
3825 /* Failure timeout callback. If this is called then we will immediately
3826 process the received failure. We always process the failure with timeout
3827 since we do not want to blindly trust to received failure packets.
3828 This won't be called (the timeout is cancelled) if the failure was
3829 bogus (it is bogus if remote does not close the connection after sending
3832 SILC_TASK_CALLBACK(silc_server_failure_callback)
3834 SilcServerFailureContext f = (SilcServerFailureContext)context;
3836 if (f->sock->protocol) {
3837 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3838 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3844 /* Assembles user list and users mode list from the `channel'. */
3846 void silc_server_get_users_on_channel(SilcServer server,
3847 SilcChannelEntry channel,
3848 SilcBuffer *user_list,
3849 SilcBuffer *mode_list,
3850 SilcUInt32 *user_count)
3852 SilcChannelClientEntry chl;
3853 SilcHashTableList htl;
3854 SilcBuffer client_id_list;
3855 SilcBuffer client_mode_list;
3857 SilcUInt32 list_count = 0, len = 0;
3859 silc_hash_table_list(channel->user_list, &htl);
3860 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3861 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3862 silc_hash_table_list_reset(&htl);
3864 client_id_list = silc_buffer_alloc(len);
3866 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3867 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3868 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3870 silc_hash_table_list(channel->user_list, &htl);
3871 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3873 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3874 silc_buffer_put(client_id_list, idp->data, idp->len);
3875 silc_buffer_pull(client_id_list, idp->len);
3876 silc_buffer_free(idp);
3878 /* Client's mode on channel */
3879 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3880 silc_buffer_pull(client_mode_list, 4);
3884 silc_hash_table_list_reset(&htl);
3885 silc_buffer_push(client_id_list,
3886 client_id_list->data - client_id_list->head);
3887 silc_buffer_push(client_mode_list,
3888 client_mode_list->data - client_mode_list->head);
3890 *user_list = client_id_list;
3891 *mode_list = client_mode_list;
3892 *user_count = list_count;
3895 /* Saves users and their modes to the `channel'. */
3897 void silc_server_save_users_on_channel(SilcServer server,
3898 SilcSocketConnection sock,
3899 SilcChannelEntry channel,
3900 SilcClientID *noadd,
3901 SilcBuffer user_list,
3902 SilcBuffer mode_list,
3903 SilcUInt32 user_count)
3908 SilcClientID *client_id;
3909 SilcClientEntry client;
3910 SilcIDCacheEntry cache;
3913 SILC_LOG_DEBUG(("Start"));
3915 for (i = 0; i < user_count; i++) {
3917 SILC_GET16_MSB(idp_len, user_list->data + 2);
3919 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3920 silc_buffer_pull(user_list, idp_len);
3925 SILC_GET32_MSB(mode, mode_list->data);
3926 silc_buffer_pull(mode_list, 4);
3928 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3929 silc_free(client_id);
3935 /* Check if we have this client cached already. */
3936 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3937 server->server_type, &cache);
3939 client = silc_idlist_find_client_by_id(server->global_list,
3940 client_id, server->server_type,
3945 /* If router did not find such Client ID in its lists then this must
3946 be bogus client or some router in the net is buggy. */
3947 if (server->server_type == SILC_ROUTER) {
3948 silc_free(client_id);
3952 /* We don't have that client anywhere, add it. The client is added
3953 to global list since server didn't have it in the lists so it must be
3955 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3956 silc_id_dup(client_id, SILC_ID_CLIENT),
3957 sock->user_data, NULL, 0);
3959 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3960 silc_free(client_id);
3964 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3966 /* Found, if it is from global list we'll assure that we won't
3967 expire it now that the entry is on channel. */
3972 silc_free(client_id);
3974 if (!silc_server_client_on_channel(client, channel, NULL)) {
3975 /* Client was not on the channel, add it. */
3976 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3977 chl->client = client;
3979 chl->channel = channel;
3980 silc_hash_table_add(channel->user_list, chl->client, chl);
3981 silc_hash_table_add(client->channels, chl->channel, chl);
3982 channel->user_count++;
3987 /* Lookups route to the client indicated by the `id_data'. The connection
3988 object and internal data object is returned. Returns NULL if route
3989 could not be found to the client. If the `client_id' is specified then
3990 it is used and the `id_data' is ignored. */
3992 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3993 unsigned char *id_data,
3995 SilcClientID *client_id,
3996 SilcIDListData *idata)
3999 SilcClientEntry client;
4001 SILC_LOG_DEBUG(("Start"));
4003 /* Decode destination Client ID */
4005 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4007 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4011 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4014 /* If the destination belongs to our server we don't have to route
4015 the packet anywhere but to send it to the local destination. */
4016 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4020 /* If we are router and the client has router then the client is in
4021 our cell but not directly connected to us. */
4022 if (server->server_type == SILC_ROUTER && client->router) {
4023 /* We are of course in this case the client's router thus the route
4024 to the client is the server who owns the client. So, we will send
4025 the packet to that server. */
4027 *idata = (SilcIDListData)client->router;
4028 return client->router->connection;
4031 /* Seems that client really is directly connected to us */
4033 *idata = (SilcIDListData)client;
4034 return client->connection;
4037 /* Destination belongs to someone not in this server. If we are normal
4038 server our action is to send the packet to our router. */
4039 if (server->server_type != SILC_ROUTER && !server->standalone) {
4042 *idata = (SilcIDListData)server->router;
4043 return server->router->connection;
4046 /* We are router and we will perform route lookup for the destination
4047 and send the packet to fastest route. */
4048 if (server->server_type == SILC_ROUTER && !server->standalone) {
4049 /* Check first that the ID is valid */
4050 client = silc_idlist_find_client_by_id(server->global_list, id,
4053 SilcSocketConnection dst_sock;
4055 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4059 *idata = (SilcIDListData)dst_sock->user_data;
4068 /* Encodes and returns channel list of channels the `client' has joined.
4069 Secret channels are not put to the list. */
4071 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4072 SilcClientEntry client)
4074 SilcBuffer buffer = NULL;
4075 SilcChannelEntry channel;
4076 SilcChannelClientEntry chl;
4077 SilcHashTableList htl;
4080 SilcUInt16 name_len;
4083 silc_hash_table_list(client->channels, &htl);
4084 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4085 channel = chl->channel;
4087 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4088 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4091 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4092 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4093 name_len = strlen(channel->channel_name);
4095 len = 4 + name_len + id_len + 4;
4096 buffer = silc_buffer_realloc(buffer,
4097 (buffer ? (buffer)->truelen + len : len));
4098 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4099 silc_buffer_format(buffer,
4100 SILC_STR_UI_SHORT(name_len),
4101 SILC_STR_UI_XNSTRING(channel->channel_name,
4103 SILC_STR_UI_SHORT(id_len),
4104 SILC_STR_UI_XNSTRING(cid, id_len),
4105 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4107 silc_buffer_pull(buffer, len);
4110 silc_hash_table_list_reset(&htl);
4113 silc_buffer_push(buffer, buffer->data - buffer->head);
4118 /* Finds client entry by Client ID and if it is not found then resolves
4119 it using WHOIS command. */
4121 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4122 SilcClientID *client_id,
4125 SilcClientEntry client;
4130 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4133 client = silc_idlist_find_client_by_id(server->global_list,
4134 client_id, TRUE, NULL);
4135 if (!client && server->server_type == SILC_ROUTER)
4139 if (!client && server->standalone)
4142 if (!client || !client->nickname || !client->username) {
4143 SilcBuffer buffer, idp;
4145 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4146 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4147 client->resolve_cmd_ident = ++server->cmd_ident;
4149 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4150 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4151 server->cmd_ident, 1,
4152 3, idp->data, idp->len);
4153 silc_server_packet_send(server, client ? client->router->connection :
4154 server->router->connection,
4155 SILC_PACKET_COMMAND, 0,
4156 buffer->data, buffer->len, FALSE);
4157 silc_buffer_free(idp);
4158 silc_buffer_free(buffer);
4169 /* A timeout callback for the re-key. We will be the initiator of the
4172 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4174 SilcSocketConnection sock = (SilcSocketConnection)context;
4175 SilcIDListData idata = (SilcIDListData)sock->user_data;
4176 SilcServer server = (SilcServer)idata->rekey->context;
4177 SilcProtocol protocol;
4178 SilcServerRekeyInternalContext *proto_ctx;
4180 SILC_LOG_DEBUG(("Start"));
4182 /* Allocate internal protocol context. This is sent as context
4184 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4185 proto_ctx->server = (void *)server;
4186 proto_ctx->sock = sock;
4187 proto_ctx->responder = FALSE;
4188 proto_ctx->pfs = idata->rekey->pfs;
4190 /* Perform rekey protocol. Will call the final callback after the
4191 protocol is over. */
4192 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4193 &protocol, proto_ctx, silc_server_rekey_final);
4194 sock->protocol = protocol;
4196 /* Run the protocol */
4197 silc_protocol_execute(protocol, server->schedule, 0, 0);
4199 /* Re-register re-key timeout */
4200 silc_schedule_task_add(server->schedule, sock->sock,
4201 silc_server_rekey_callback,
4202 context, idata->rekey->timeout, 0,
4203 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4206 /* The final callback for the REKEY protocol. This will actually take the
4207 new key material into use. */
4209 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4211 SilcProtocol protocol = (SilcProtocol)context;
4212 SilcServerRekeyInternalContext *ctx =
4213 (SilcServerRekeyInternalContext *)protocol->context;
4214 SilcServer server = (SilcServer)ctx->server;
4215 SilcSocketConnection sock = ctx->sock;
4217 SILC_LOG_DEBUG(("Start"));
4219 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4220 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4221 /* Error occured during protocol */
4222 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4223 silc_protocol_cancel(protocol, server->schedule);
4224 silc_protocol_free(protocol);
4225 sock->protocol = NULL;
4227 silc_packet_context_free(ctx->packet);
4229 silc_ske_free(ctx->ske);
4234 /* Purge the outgoing data queue to assure that all rekey packets really
4235 go to the network before we quit the protocol. */
4236 silc_server_packet_queue_purge(server, sock);
4239 silc_protocol_free(protocol);
4240 sock->protocol = NULL;
4242 silc_packet_context_free(ctx->packet);
4244 silc_ske_free(ctx->ske);