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->public_key)
95 silc_pkcs_public_key_free(server->public_key);
96 if (server->private_key)
97 silc_pkcs_private_key_free(server->private_key);
98 if (server->pending_commands)
99 silc_dlist_uninit(server->pending_commands);
100 if (server->id_entry)
101 silc_idlist_del_server(server->local_list, server->id_entry);
103 silc_idcache_free(server->local_list->clients);
104 silc_idcache_free(server->local_list->servers);
105 silc_idcache_free(server->local_list->channels);
106 silc_idcache_free(server->global_list->clients);
107 silc_idcache_free(server->global_list->servers);
108 silc_idcache_free(server->global_list->channels);
110 silc_free(server->sockets);
115 /* Opens a listening port.
116 XXX This function will become more general and will support multiple
119 static bool silc_server_listen(SilcServer server, int *sock)
122 *sock = silc_net_create_server(server->config->server_info->port,
123 server->config->server_info->server_ip);
125 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
126 server->config->server_info->server_ip,
127 server->config->server_info->port));
133 /* Initializes the entire SILC server. This is called always before running
134 the server. This is called only once at the initialization of the program.
135 This binds the server to its listenning port. After this function returns
136 one should call silc_server_run to start the server. This returns TRUE
137 when everything is ok to run the server. Configuration file must be
138 read and parsed before calling this. */
140 bool silc_server_init(SilcServer server)
144 SilcServerEntry id_entry;
145 SilcIDListPurge purge;
146 SilcSocketConnection newsocket = NULL;
148 SILC_LOG_DEBUG(("Initializing server"));
150 assert(server->config);
152 /* Set public and private keys */
153 if (!server->config->server_info ||
154 !server->config->server_info->public_key ||
155 !server->config->server_info->private_key) {
156 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
160 /* Steal public and private key from the config object */
161 server->public_key = server->config->server_info->public_key;
162 server->private_key = server->config->server_info->private_key;
163 server->config->server_info->public_key = NULL;
164 server->config->server_info->private_key = NULL;
166 /* Register all configured ciphers, PKCS and hash functions. */
167 if (!silc_server_config_register_ciphers(server))
168 silc_cipher_register_default();
169 if (!silc_server_config_register_pkcs(server))
170 silc_pkcs_register_default();
171 if (!silc_server_config_register_hashfuncs(server))
172 silc_hash_register_default();
173 if (!silc_server_config_register_hmacs(server))
174 silc_hmac_register_default();
176 /* Initialize random number generator for the server. */
177 server->rng = silc_rng_alloc();
178 silc_rng_init(server->rng);
179 silc_rng_global_init(server->rng);
181 /* Initialize hash functions for server to use */
182 silc_hash_alloc("md5", &server->md5hash);
183 silc_hash_alloc("sha1", &server->sha1hash);
185 /* Allocate PKCS context for local public and private keys */
186 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
188 silc_pkcs_public_key_set(server->pkcs, server->public_key);
189 silc_pkcs_private_key_set(server->pkcs, server->private_key);
191 /* Initialize the scheduler */
192 server->schedule = silc_schedule_init(server->config->param.connections_max);
193 if (!server->schedule)
196 /* First, register log files configuration for error output */
197 silc_server_config_setlogfiles(server);
199 /* Initialize ID caches */
200 server->local_list->clients =
201 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
202 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
203 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
205 /* These are allocated for normal server as well as these hold some
206 global information that the server has fetched from its router. For
207 router these are used as they are supposed to be used on router. */
208 server->global_list->clients =
209 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
210 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
211 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
213 /* Create a listening server */
214 if (!silc_server_listen(server, &sock))
217 /* Set socket to non-blocking mode */
218 silc_net_set_socket_nonblock(sock);
221 /* Allocate the entire socket list that is used in server. Eventually
222 all connections will have entry in this table (it is a table of
223 pointers to the actual object that is allocated individually
225 server->sockets = silc_calloc(server->config->param.connections_max,
226 sizeof(*server->sockets));
227 if (!server->sockets)
230 /* Add ourselves also to the socket table. The entry allocated above
231 is sent as argument for fast referencing in the future. */
232 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
233 server->sockets[sock] = newsocket;
235 /* Perform name and address lookups to resolve the listenning address
237 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
239 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
241 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
242 newsocket->hostname ? newsocket->hostname :
243 newsocket->ip ? newsocket->ip : ""));
244 server->stat.conn_failures++;
247 if (!newsocket->hostname)
248 newsocket->hostname = strdup(newsocket->ip);
250 newsocket->port = silc_net_get_local_port(sock);
252 /* Create a Server ID for the server. */
253 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
258 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
259 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
260 server->id_type = SILC_ID_SERVER;
261 server->server_name = server->config->server_info->server_name;
262 server->config->server_info->server_name = NULL;
264 /* Add ourselves to the server list. We don't have a router yet
265 beacuse we haven't established a route yet. It will be done later.
266 For now, NULL is sent as router. This allocates new entry to
269 silc_idlist_add_server(server->local_list, strdup(server->server_name),
270 server->server_type, server->id, NULL, NULL);
272 SILC_LOG_ERROR(("Could not add ourselves to cache"));
275 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
277 /* Put the allocated socket pointer also to the entry allocated above
278 for fast back-referencing to the socket list. */
279 newsocket->user_data = (void *)id_entry;
280 id_entry->connection = (void *)newsocket;
281 server->id_entry = id_entry;
283 /* Register protocols */
284 silc_server_protocols_register();
286 /* Add the first task to the scheduler. This is task that is executed by
287 timeout. It expires as soon as the caller calls silc_server_run. This
288 task performs authentication protocol and key exchange with our
290 silc_schedule_task_add(server->schedule, sock,
291 silc_server_connect_to_router,
292 (void *)server, 0, 1,
294 SILC_TASK_PRI_NORMAL);
296 /* Add listener task to the scheduler. This task receives new connections
297 to the server. This task remains on the queue until the end of the
299 silc_schedule_task_add(server->schedule, sock,
300 silc_server_accept_new_connection,
301 (void *)server, 0, 0,
303 SILC_TASK_PRI_NORMAL);
304 server->listenning = TRUE;
306 /* If server connections has been configured then we must be router as
307 normal server cannot have server connections, only router connections. */
308 if (server->config->servers) {
309 SilcServerConfigServer *ptr = server->config->servers;
311 server->server_type = SILC_ROUTER;
313 if (ptr->backup_router) {
314 server->server_type = SILC_BACKUP_ROUTER;
315 server->backup_router = TRUE;
316 server->id_entry->server_type = SILC_BACKUP_ROUTER;
323 /* Register the ID Cache purge task. This periodically purges the ID cache
324 and removes the expired cache entries. */
326 /* Clients local list */
327 purge = silc_calloc(1, sizeof(*purge));
328 purge->cache = server->local_list->clients;
329 purge->schedule = server->schedule;
330 purge->timeout = 600;
331 silc_schedule_task_add(purge->schedule, 0,
333 (void *)purge, purge->timeout, 0,
334 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
336 /* Clients global list */
337 purge = silc_calloc(1, sizeof(*purge));
338 purge->cache = server->global_list->clients;
339 purge->schedule = server->schedule;
340 purge->timeout = 300;
341 silc_schedule_task_add(purge->schedule, 0,
343 (void *)purge, purge->timeout, 0,
344 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
346 SILC_LOG_DEBUG(("Server initialized"));
348 /* We are done here, return succesfully */
352 silc_net_close_server(sock);
356 /* This function basically reads the config file again and switches the config
357 object pointed by the server object. After that, we have to fix various
358 things such as the server_name and the listening ports.
359 Keep in mind that we no longer have the root privileges at this point. */
361 bool silc_server_rehash(SilcServer server)
363 SilcServerConfig newconfig;
365 /* Reset the logging system */
366 silc_log_quick = TRUE;
367 silc_log_flush_all();
369 /* Start the main rehash phase (read again the config file) */
370 SILC_LOG_INFO(("Rehashing server"));
371 newconfig = silc_server_config_alloc(server, server->config_file);
373 SILC_LOG_ERROR(("Rehash FAILED."));
377 /* Destroy old config context. This is destroyed if no one is referencing
379 silc_server_config_destroy(server->config);
380 server->config = newconfig;
382 /* Set public and private keys */
383 if (!server->config->server_info ||
384 !server->config->server_info->public_key ||
385 !server->config->server_info->private_key) {
386 SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
390 /* Fix the server_name field */
391 if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
392 /* We don't need any update */
393 silc_free(newconfig->server_info->server_name);
394 newconfig->server_info->server_name = NULL;
396 silc_free(server->server_name);
397 server->server_name = newconfig->server_info->server_name;
398 newconfig->server_info->server_name = NULL;
400 /* Update the idcache list with a fresh pointer */
401 silc_free(server->id_entry->server_name);
402 server->id_entry->server_name = strdup(server->server_name);
403 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
404 silc_idcache_add(server->local_list->servers,
405 server->id_entry->server_name,
406 server->id_entry->id, server->id_entry, 0, NULL);
409 silc_server_config_setlogfiles(server);
411 /* Change new key pair if necessary */
412 if (server->config->server_info->public_key &&
413 !silc_pkcs_public_key_compare(server->public_key,
414 server->config->server_info->public_key)) {
415 silc_pkcs_public_key_free(server->public_key);
416 silc_pkcs_private_key_free(server->private_key);
417 server->public_key = server->config->server_info->public_key;
418 server->private_key = server->config->server_info->private_key;
419 server->config->server_info->public_key = NULL;
420 server->config->server_info->private_key = NULL;
422 /* Allocate PKCS context for local public and private keys */
423 silc_pkcs_free(server->pkcs);
424 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
426 silc_pkcs_public_key_set(server->pkcs, server->public_key);
427 silc_pkcs_private_key_set(server->pkcs, server->private_key);
433 /* Drop root privileges. If some system call fails, die. */
435 void silc_server_drop(SilcServer server)
437 /* Are we executing silcd as root or a regular user? */
439 SILC_LOG_DEBUG(("Server started as user"));
446 SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
448 /* Get the values given for user and group in configuration file */
449 user = server->config->server_info->user;
450 group = server->config->server_info->group;
452 if (!user || !group) {
453 fprintf(stderr, "Error:"
454 "\tSILC server must not be run as root. For the security of your\n"
455 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
456 "\tuser account. Modify the ServerInfo configuration section to run\n"
457 "\tthe server as non-root user.\n");
461 /* Check whether the user/group does not begin with a number */
462 if (isdigit(user[0]) || isdigit(group[0])) {
463 SILC_LOG_DEBUG(("User and/or group starts with a number"));
464 fprintf(stderr, "Invalid user and/or group information\n");
465 fprintf(stderr, "Please assign them as names, not numbers\n");
469 if (!(pw = getpwnam(user))) {
470 fprintf(stderr, "Error: No such user %s found.\n", user);
473 if (!(gr = getgrnam(group))) {
474 fprintf(stderr, "Error: No such group %s found.\n", group);
478 /* Check whether user and/or group is set to root. If yes, exit
479 immediately. Otherwise, setgid and setuid server to user.group */
480 if ((gr->gr_gid == 0) || (pw->pw_uid == 0)) {
481 fprintf(stderr, "Error:"
482 "\tSILC server must not be run as root. For the security of your\n"
483 "\tsystem it is strongly suggested that you run SILC under dedicated\n"
484 "\tuser account. Modify the ServerInfo configuration section to run\n"
485 "\tthe server as non-root user.\n");
489 SILC_LOG_DEBUG(("Changing to group %s (gid=%u)", group, gr->gr_gid));
490 if (setgid(gr->gr_gid) != 0) {
491 fprintf(stderr, "Error: Failed setgid() to %s (gid=%u). Exiting.\n",
495 #if defined HAVE_SETGROUPS && defined HAVE_INITGROUPS
496 SILC_LOG_DEBUG(("Removing supplementary groups"));
497 if (setgroups(0, NULL) != 0) {
498 fprintf(stderr, "Error: Failed setgroups() to NULL. Exiting.\n");
501 SILC_LOG_DEBUG(("Setting supplementary groups for user %s", user));
502 if (initgroups(user, gr->gr_gid) != 0) {
503 fprintf(stderr, "Error: Failed initgroups() for user %s (gid=%u). "
504 "Exiting.\n", user, gr->gr_gid);
508 SILC_LOG_DEBUG(("Changing to user %s (uid=%u)", user, pw->pw_uid));
509 if (setuid(pw->pw_uid) != 0) {
510 fprintf(stderr, "Error: Failed to setuid() to %s (gid=%u). Exiting.\n",
517 /* Fork server to background */
519 void silc_server_daemonise(SilcServer server)
523 SILC_LOG_DEBUG(("Forking SILC server to background"));
525 if ((i = fork()) < 0) {
526 fprintf(stderr, "Error: fork() failed: %s\n", strerror(errno));
530 if (i) /* Kill the parent */
533 server->background = TRUE;
536 /* XXX close stdin, stdout, stderr -- before this, check that all writes
537 to stderr are changed to SILC_SERVER_LOG_ERROR() */
540 /* The heart of the server. This runs the scheduler thus runs the server.
541 When this returns the server has been stopped and the program will
544 void silc_server_run(SilcServer server)
546 SILC_LOG_INFO(("SILC Server started"));
548 /* Start the scheduler, the heart of the SILC server. When this returns
549 the program will be terminated. */
550 silc_schedule(server->schedule);
553 /* Stops the SILC server. This function is used to shutdown the server.
554 This is usually called after the scheduler has returned. After stopping
555 the server one should call silc_server_free. */
557 void silc_server_stop(SilcServer server)
559 SILC_LOG_DEBUG(("Stopping server"));
561 if (server->schedule) {
562 silc_schedule_stop(server->schedule);
563 silc_schedule_uninit(server->schedule);
564 server->schedule = NULL;
567 silc_server_protocols_unregister();
569 SILC_LOG_DEBUG(("Server stopped"));
572 /* Function that is called when the network connection to a router has
573 been established. This will continue with the key exchange protocol
574 with the remote router. */
576 void silc_server_start_key_exchange(SilcServer server,
577 SilcServerConnection sconn,
580 SilcSocketConnection newsocket;
581 SilcProtocol protocol;
582 SilcServerKEInternalContext *proto_ctx;
583 SilcServerConfigRouter *conn =
584 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
587 /* Cancel any possible retry timeouts */
588 silc_schedule_task_del_by_callback(server->schedule,
589 silc_server_connect_router);
591 /* Set socket options */
592 silc_net_set_socket_nonblock(sock);
593 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
595 /* Create socket connection for the connection. Even though we
596 know that we are connecting to a router we will mark the socket
597 to be unknown connection until we have executed authentication
599 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
600 server->sockets[sock] = newsocket;
601 newsocket->hostname = strdup(sconn->remote_host);
602 newsocket->ip = strdup(sconn->remote_host);
603 newsocket->port = sconn->remote_port;
604 sconn->sock = newsocket;
606 /* Allocate internal protocol context. This is sent as context
608 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
609 proto_ctx->server = (void *)server;
610 proto_ctx->context = (void *)sconn;
611 proto_ctx->sock = newsocket;
612 proto_ctx->rng = server->rng;
613 proto_ctx->responder = FALSE;
615 /* Set Key Exchange flags from configuration, but fall back to global
617 SILC_GET_SKE_FLAGS(conn, proto_ctx);
618 if (server->config->param.key_exchange_pfs)
619 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
621 /* Perform key exchange protocol. silc_server_connect_to_router_second
622 will be called after the protocol is finished. */
623 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
624 &protocol, proto_ctx,
625 silc_server_connect_to_router_second);
626 newsocket->protocol = protocol;
628 /* Register a timeout task that will be executed if the protocol
629 is not executed within set limit. */
630 proto_ctx->timeout_task =
631 silc_schedule_task_add(server->schedule, sock,
632 silc_server_timeout_remote,
633 server, server->config->key_exchange_timeout, 0,
637 /* Register the connection for network input and output. This sets
638 that scheduler will listen for incoming packets for this connection
639 and sets that outgoing packets may be sent to this connection as
640 well. However, this doesn't set the scheduler for outgoing traffic,
641 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
642 later when outgoing data is available. */
643 context = (void *)server;
644 SILC_REGISTER_CONNECTION_FOR_IO(sock);
646 /* Run the protocol */
647 silc_protocol_execute(protocol, server->schedule, 0, 0);
650 /* Timeout callback that will be called to retry connecting to remote
651 router. This is used by both normal and router server. This will wait
652 before retrying the connecting. The timeout is generated by exponential
653 backoff algorithm. */
655 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
657 SilcServerConnection sconn = (SilcServerConnection)context;
658 SilcServer server = sconn->server;
659 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
660 SilcServerConfigConnParams *param =
661 (conn->param ? conn->param : &server->config->param);
663 SILC_LOG_INFO(("Retrying connecting to a router"));
665 /* Calculate next timeout */
666 if (sconn->retry_count >= 1) {
667 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
668 if (sconn->retry_timeout > param->reconnect_interval_max)
669 sconn->retry_timeout = param->reconnect_interval_max;
671 sconn->retry_timeout = param->reconnect_interval;
673 sconn->retry_count++;
674 sconn->retry_timeout = sconn->retry_timeout +
675 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
677 /* If we've reached max retry count, give up. */
678 if ((sconn->retry_count > param->reconnect_count) &&
679 !param->reconnect_keep_trying) {
680 SILC_LOG_ERROR(("Could not connect to router, giving up"));
681 silc_server_config_unref(&sconn->conn);
682 silc_free(sconn->remote_host);
683 silc_free(sconn->backup_replace_ip);
688 /* We will lookup a fresh pointer later */
689 silc_server_config_unref(&sconn->conn);
691 /* Wait one before retrying */
692 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
693 context, sconn->retry_timeout, 0,
694 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
697 /* Generic routine to use connect to a router. */
699 SILC_TASK_CALLBACK(silc_server_connect_router)
701 SilcServerConnection sconn = (SilcServerConnection)context;
702 SilcServer server = sconn->server;
703 SilcServerConfigRouter *rconn;
706 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
707 (sconn->backup ? "backup router" : "router"),
708 sconn->remote_host, sconn->remote_port));
710 server->router_connect = time(NULL);
711 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
714 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
715 (sconn->backup ? "backup router" : "router"),
716 sconn->remote_host, sconn->remote_port));
717 silc_free(sconn->remote_host);
718 silc_free(sconn->backup_replace_ip);
722 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
724 /* Connect to remote host */
725 sock = silc_net_create_connection(server->config->server_info->server_ip,
729 SILC_LOG_ERROR(("Could not connect to router %s:%d",
730 sconn->remote_host, sconn->remote_port));
731 if (!sconn->no_reconnect)
732 silc_schedule_task_add(server->schedule, 0,
733 silc_server_connect_to_router_retry,
734 context, 0, 1, SILC_TASK_TIMEOUT,
735 SILC_TASK_PRI_NORMAL);
737 silc_server_config_unref(&sconn->conn);
741 /* Continue with key exchange protocol */
742 silc_server_start_key_exchange(server, sconn, sock);
745 /* This function connects to our primary router or if we are a router this
746 establishes all our primary routes. This is called at the start of the
747 server to do authentication and key exchange with our router - called
750 SILC_TASK_CALLBACK(silc_server_connect_to_router)
752 SilcServer server = (SilcServer)context;
753 SilcServerConnection sconn;
754 SilcServerConfigRouter *ptr;
756 SILC_LOG_DEBUG(("Connecting to router(s)"));
758 if (server->server_type == SILC_SERVER) {
759 SILC_LOG_DEBUG(("We are normal server"));
760 } else if (server->server_type == SILC_ROUTER) {
761 SILC_LOG_DEBUG(("We are router"));
763 SILC_LOG_DEBUG(("We are backup router/normal server"));
766 if (!server->config->routers) {
767 /* There wasn't a configured router, we will continue but we don't
768 have a connection to outside world. We will be standalone server. */
769 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
770 server->standalone = TRUE;
774 /* Create the connections to all our routes */
775 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
777 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
778 ptr->backup_router ? "Backup router" : "Router",
779 ptr->initiator ? "Initiator" : "Responder",
780 ptr->host, ptr->port));
782 if (ptr->initiator) {
783 /* Allocate connection object for hold connection specific stuff. */
784 sconn = silc_calloc(1, sizeof(*sconn));
785 sconn->server = server;
786 sconn->remote_host = strdup(ptr->host);
787 sconn->remote_port = ptr->port;
788 sconn->backup = ptr->backup_router;
790 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
791 sconn->backup_replace_port = ptr->backup_replace_port;
794 if (!server->router_conn && !sconn->backup)
795 server->router_conn = sconn;
797 silc_schedule_task_add(server->schedule, fd,
798 silc_server_connect_router,
799 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
800 SILC_TASK_PRI_NORMAL);
805 /* Second part of connecting to router(s). Key exchange protocol has been
806 executed and now we will execute authentication protocol. */
808 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
810 SilcProtocol protocol = (SilcProtocol)context;
811 SilcServerKEInternalContext *ctx =
812 (SilcServerKEInternalContext *)protocol->context;
813 SilcServer server = (SilcServer)ctx->server;
814 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
815 SilcSocketConnection sock = ctx->sock;
816 SilcServerConnAuthInternalContext *proto_ctx;
817 SilcServerConfigRouter *conn = NULL;
819 SILC_LOG_DEBUG(("Start"));
821 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
822 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
823 /* Error occured during protocol */
824 silc_protocol_free(protocol);
825 sock->protocol = NULL;
826 silc_ske_free_key_material(ctx->keymat);
828 silc_packet_context_free(ctx->packet);
830 silc_ske_free(ctx->ske);
831 silc_free(ctx->dest_id);
833 silc_server_config_unref(&sconn->conn);
834 silc_free(sconn->remote_host);
835 silc_free(sconn->backup_replace_ip);
837 silc_schedule_task_del_by_callback(server->schedule,
838 silc_server_failure_callback);
839 silc_server_disconnect_remote(server, sock, "Server closed connection: "
840 "Key exchange failed");
844 /* We now have the key material as the result of the key exchange
845 protocol. Take the key material into use. Free the raw key material
846 as soon as we've set them into use. */
847 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
848 ctx->sock, ctx->keymat,
849 ctx->ske->prop->cipher,
850 ctx->ske->prop->pkcs,
851 ctx->ske->prop->hash,
852 ctx->ske->prop->hmac,
853 ctx->ske->prop->group,
855 silc_protocol_free(protocol);
856 sock->protocol = NULL;
857 silc_ske_free_key_material(ctx->keymat);
859 silc_packet_context_free(ctx->packet);
861 silc_ske_free(ctx->ske);
862 silc_free(ctx->dest_id);
864 silc_server_config_unref(&sconn->conn);
865 silc_free(sconn->remote_host);
866 silc_free(sconn->backup_replace_ip);
868 silc_schedule_task_del_by_callback(server->schedule,
869 silc_server_failure_callback);
870 silc_server_disconnect_remote(server, sock, "Server closed connection: "
871 "Key exchange failed");
874 silc_ske_free_key_material(ctx->keymat);
876 /* Allocate internal context for the authentication protocol. This
877 is sent as context for the protocol. */
878 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
879 proto_ctx->server = (void *)server;
880 proto_ctx->context = (void *)sconn;
881 proto_ctx->sock = sock;
882 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
883 proto_ctx->dest_id_type = ctx->dest_id_type;
884 proto_ctx->dest_id = ctx->dest_id;
886 /* Resolve the authentication method used in this connection. Check if
887 we find a match from user configured connections */
888 if (!sconn->conn.ref_ptr)
889 conn = silc_server_config_find_router_conn(server, sock->hostname,
892 conn = sconn->conn.ref_ptr;
895 /* Match found. Use the configured authentication method. Take only
896 the passphrase, since for public key auth we automatically use
897 our local key pair. */
898 if (conn->passphrase) {
899 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
900 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
902 proto_ctx->auth_data = strdup(conn->passphrase);
903 proto_ctx->auth_data_len = strlen(conn->passphrase);
904 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
906 } else if (conn->publickeys) {
907 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
909 proto_ctx->auth_meth = SILC_AUTH_NONE;
912 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
913 sock->hostname, sock->ip, sock->port));
914 silc_protocol_free(protocol);
915 sock->protocol = NULL;
917 silc_packet_context_free(ctx->packet);
919 silc_ske_free(ctx->ske);
920 silc_free(ctx->dest_id);
922 silc_server_config_unref(&sconn->conn);
923 silc_free(sconn->remote_host);
924 silc_free(sconn->backup_replace_ip);
926 silc_schedule_task_del_by_callback(server->schedule,
927 silc_server_failure_callback);
928 silc_server_disconnect_remote(server, sock, "Server closed connection: "
929 "Key exchange failed");
933 /* Free old protocol as it is finished now */
934 silc_protocol_free(protocol);
936 silc_packet_context_free(ctx->packet);
938 sock->protocol = NULL;
940 /* Allocate the authentication protocol. This is allocated here
941 but we won't start it yet. We will be receiving party of this
942 protocol thus we will wait that connecting party will make
944 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
945 &sock->protocol, proto_ctx,
946 silc_server_connect_to_router_final);
948 /* Register timeout task. If the protocol is not executed inside
949 this timelimit the connection will be terminated. */
950 proto_ctx->timeout_task =
951 silc_schedule_task_add(server->schedule, sock->sock,
952 silc_server_timeout_remote,
954 server->config->conn_auth_timeout, 0,
958 /* Run the protocol */
959 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
962 /* Finalizes the connection to router. Registers a server task to the
963 queue so that we can accept new connections. */
965 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
967 SilcProtocol protocol = (SilcProtocol)context;
968 SilcServerConnAuthInternalContext *ctx =
969 (SilcServerConnAuthInternalContext *)protocol->context;
970 SilcServer server = (SilcServer)ctx->server;
971 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
972 SilcSocketConnection sock = ctx->sock;
973 SilcServerEntry id_entry;
975 SilcServerHBContext hb_context;
976 unsigned char *id_string;
978 SilcIDListData idata;
979 SilcServerConfigRouter *conn = NULL;
980 SilcServerConfigConnParams *param = NULL;
982 SILC_LOG_DEBUG(("Start"));
984 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
985 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
986 /* Error occured during protocol */
987 silc_free(ctx->dest_id);
988 silc_server_disconnect_remote(server, sock, "Server closed connection: "
989 "Authentication failed");
993 /* Add a task to the queue. This task receives new connections to the
994 server. This task remains on the queue until the end of the program. */
995 if (!server->listenning && !sconn->backup) {
996 silc_schedule_task_add(server->schedule, server->sock,
997 silc_server_accept_new_connection,
998 (void *)server, 0, 0,
1000 SILC_TASK_PRI_NORMAL);
1001 server->listenning = TRUE;
1004 /* Send NEW_SERVER packet to the router. We will become registered
1005 to the SILC network after sending this packet. */
1006 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1007 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1008 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1009 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1010 silc_buffer_format(packet,
1011 SILC_STR_UI_SHORT(id_len),
1012 SILC_STR_UI_XNSTRING(id_string, id_len),
1013 SILC_STR_UI_SHORT(strlen(server->server_name)),
1014 SILC_STR_UI_XNSTRING(server->server_name,
1015 strlen(server->server_name)),
1018 /* Send the packet */
1019 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1020 packet->data, packet->len, TRUE);
1021 silc_buffer_free(packet);
1022 silc_free(id_string);
1024 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1026 /* Check that we do not have this ID already */
1027 id_entry = silc_idlist_find_server_by_id(server->local_list,
1028 ctx->dest_id, TRUE, NULL);
1030 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1032 id_entry = silc_idlist_find_server_by_id(server->global_list,
1033 ctx->dest_id, TRUE, NULL);
1035 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1038 SILC_LOG_DEBUG(("New server id(%s)",
1039 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1041 /* Add the connected router to global server list */
1042 id_entry = silc_idlist_add_server(server->global_list,
1043 strdup(sock->hostname),
1044 SILC_ROUTER, ctx->dest_id, NULL, sock);
1046 silc_free(ctx->dest_id);
1047 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1048 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1049 "Authentication failed");
1053 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1054 silc_free(sock->user_data);
1055 sock->user_data = (void *)id_entry;
1056 sock->type = SILC_SOCKET_TYPE_ROUTER;
1057 idata = (SilcIDListData)sock->user_data;
1058 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1060 conn = sconn->conn.ref_ptr;
1061 param = &server->config->param;
1062 if (conn && conn->param)
1063 param = conn->param;
1065 /* Perform keepalive. The `hb_context' will be freed automatically
1066 when finally calling the silc_socket_free function. */
1067 hb_context = silc_calloc(1, sizeof(*hb_context));
1068 hb_context->server = server;
1069 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1070 silc_server_perform_heartbeat,
1073 /* Register re-key timeout */
1074 idata->rekey->timeout = param->key_exchange_rekey;
1075 idata->rekey->context = (void *)server;
1076 silc_schedule_task_add(server->schedule, sock->sock,
1077 silc_server_rekey_callback,
1078 (void *)sock, idata->rekey->timeout, 0,
1079 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1081 if (!sconn->backup) {
1082 /* Mark this router our primary router if we're still standalone */
1083 if (server->standalone) {
1084 server->id_entry->router = id_entry;
1085 server->router = id_entry;
1086 server->standalone = FALSE;
1088 /* If we are router then announce our possible servers. */
1089 if (server->server_type == SILC_ROUTER)
1090 silc_server_announce_servers(server, FALSE, 0,
1091 server->router->connection);
1093 /* Announce our clients and channels to the router */
1094 silc_server_announce_clients(server, 0, server->router->connection);
1095 silc_server_announce_channels(server, 0, server->router->connection);
1098 /* Add this server to be our backup router */
1099 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1100 sconn->backup_replace_port, FALSE);
1103 sock->protocol = NULL;
1105 /* Call the completion callback to indicate that we've connected to
1107 if (sconn->callback)
1108 (*sconn->callback)(server, id_entry, sconn->callback_context);
1111 /* Free the temporary connection data context */
1113 silc_server_config_unref(&sconn->conn);
1114 silc_free(sconn->remote_host);
1115 silc_free(sconn->backup_replace_ip);
1118 if (sconn == server->router_conn)
1119 server->router_conn = NULL;
1121 /* Free the protocol object */
1122 if (sock->protocol == protocol)
1123 sock->protocol = NULL;
1124 silc_protocol_free(protocol);
1126 silc_packet_context_free(ctx->packet);
1128 silc_ske_free(ctx->ske);
1129 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1130 silc_free(ctx->auth_data);
1134 /* Host lookup callback that is called after the incoming connection's
1135 IP and FQDN lookup is performed. This will actually check the acceptance
1136 of the incoming connection and will register the key exchange protocol
1137 for this connection. */
1140 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1143 SilcServer server = (SilcServer)context;
1144 SilcServerKEInternalContext *proto_ctx;
1145 SilcServerConfigClient *cconfig = NULL;
1146 SilcServerConfigServer *sconfig = NULL;
1147 SilcServerConfigRouter *rconfig = NULL;
1148 SilcServerConfigDeny *deny;
1151 SILC_LOG_DEBUG(("Start"));
1153 /* Check whether we could resolve both IP and FQDN. */
1154 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1155 server->config->require_reverse_lookup)) {
1156 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1157 sock->hostname ? sock->hostname :
1158 sock->ip ? sock->ip : ""));
1159 server->stat.conn_failures++;
1160 silc_server_disconnect_remote(server, sock,
1161 "Server closed connection: Unknown host");
1165 /* Register the connection for network input and output. This sets
1166 that scheduler will listen for incoming packets for this connection
1167 and sets that outgoing packets may be sent to this connection as well.
1168 However, this doesn't set the scheduler for outgoing traffic, it
1169 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1170 later when outgoing data is available. */
1171 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1173 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1176 port = server->sockets[server->sock]->port; /* Listenning port */
1178 /* Check whether this connection is denied to connect to us. */
1179 deny = silc_server_config_find_denied(server, sock->ip);
1181 deny = silc_server_config_find_denied(server, sock->hostname);
1183 /* The connection is denied */
1184 SILC_LOG_INFO(("Connection %s (%s) is denied",
1185 sock->hostname, sock->ip));
1186 silc_server_disconnect_remote(server, sock, deny->reason ?
1188 "Server closed connection: "
1189 "Connection refused");
1190 server->stat.conn_failures++;
1194 /* Check whether we have configured this sort of connection at all. We
1195 have to check all configurations since we don't know what type of
1196 connection this is. */
1197 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1198 cconfig = silc_server_config_find_client(server, sock->hostname);
1199 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1200 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1201 if (server->server_type == SILC_ROUTER) {
1202 if (!(rconfig = silc_server_config_find_router_conn(server,
1204 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1207 if (!cconfig && !sconfig && !rconfig) {
1208 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1210 silc_server_disconnect_remote(server, sock,
1211 "Server closed connection: "
1212 "Connection refused");
1213 server->stat.conn_failures++;
1217 /* The connection is allowed */
1219 /* Allocate internal context for key exchange protocol. This is
1220 sent as context for the protocol. */
1221 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1222 proto_ctx->server = context;
1223 proto_ctx->sock = sock;
1224 proto_ctx->rng = server->rng;
1225 proto_ctx->responder = TRUE;
1226 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1227 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1228 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1230 /* Take flags for key exchange. Since we do not know what type of connection
1231 this is, we go through all found configurations and use the global ones
1232 as well. This will result always into strictest key exchange flags. */
1233 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1234 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1235 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1236 if (server->config->param.key_exchange_pfs)
1237 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1239 /* Prepare the connection for key exchange protocol. We allocate the
1240 protocol but will not start it yet. The connector will be the
1241 initiator of the protocol thus we will wait for initiation from
1242 there before we start the protocol. */
1243 server->stat.auth_attempts++;
1244 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1245 &sock->protocol, proto_ctx,
1246 silc_server_accept_new_connection_second);
1248 /* Register a timeout task that will be executed if the connector
1249 will not start the key exchange protocol within specified timeout
1250 and the connection will be closed. */
1251 proto_ctx->timeout_task =
1252 silc_schedule_task_add(server->schedule, sock->sock,
1253 silc_server_timeout_remote,
1254 context, server->config->key_exchange_timeout, 0,
1259 /* Accepts new connections to the server. Accepting new connections are
1260 done in three parts to make it async. */
1262 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1264 SilcServer server = (SilcServer)context;
1265 SilcSocketConnection newsocket;
1268 SILC_LOG_DEBUG(("Accepting new connection"));
1270 server->stat.conn_attempts++;
1272 sock = silc_net_accept_connection(server->sock);
1274 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1275 server->stat.conn_failures++;
1279 /* Check for maximum allowed connections */
1280 if (sock > server->config->param.connections_max) {
1281 SILC_LOG_ERROR(("Refusing connection, server is full"));
1282 server->stat.conn_failures++;
1283 silc_net_close_connection(sock);
1287 /* Set socket options */
1288 silc_net_set_socket_nonblock(sock);
1289 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1291 /* We don't create a ID yet, since we don't know what type of connection
1292 this is yet. But, we do add the connection to the socket table. */
1293 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1294 server->sockets[sock] = newsocket;
1296 /* Perform asynchronous host lookup. This will lookup the IP and the
1297 FQDN of the remote connection. After the lookup is done the connection
1298 is accepted further. */
1299 silc_socket_host_lookup(newsocket, TRUE,
1300 silc_server_accept_new_connection_lookup, context,
1304 /* Second part of accepting new connection. Key exchange protocol has been
1305 performed and now it is time to do little connection authentication
1306 protocol to figure out whether this connection is client or server
1307 and whether it has right to access this server (especially server
1308 connections needs to be authenticated). */
1310 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1312 SilcProtocol protocol = (SilcProtocol)context;
1313 SilcServerKEInternalContext *ctx =
1314 (SilcServerKEInternalContext *)protocol->context;
1315 SilcServer server = (SilcServer)ctx->server;
1316 SilcSocketConnection sock = ctx->sock;
1317 SilcServerConnAuthInternalContext *proto_ctx;
1319 SILC_LOG_DEBUG(("Start"));
1321 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1322 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1323 /* Error occured during protocol */
1324 silc_protocol_free(protocol);
1325 sock->protocol = NULL;
1326 silc_ske_free_key_material(ctx->keymat);
1328 silc_packet_context_free(ctx->packet);
1330 silc_ske_free(ctx->ske);
1331 silc_free(ctx->dest_id);
1332 silc_server_config_unref(&ctx->cconfig);
1333 silc_server_config_unref(&ctx->sconfig);
1334 silc_server_config_unref(&ctx->rconfig);
1336 silc_schedule_task_del_by_callback(server->schedule,
1337 silc_server_failure_callback);
1338 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1339 "Key exchange failed");
1340 server->stat.auth_failures++;
1344 /* We now have the key material as the result of the key exchange
1345 protocol. Take the key material into use. Free the raw key material
1346 as soon as we've set them into use. */
1347 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1348 ctx->sock, ctx->keymat,
1349 ctx->ske->prop->cipher,
1350 ctx->ske->prop->pkcs,
1351 ctx->ske->prop->hash,
1352 ctx->ske->prop->hmac,
1353 ctx->ske->prop->group,
1355 silc_protocol_free(protocol);
1356 sock->protocol = NULL;
1357 silc_ske_free_key_material(ctx->keymat);
1359 silc_packet_context_free(ctx->packet);
1361 silc_ske_free(ctx->ske);
1362 silc_free(ctx->dest_id);
1363 silc_server_config_unref(&ctx->cconfig);
1364 silc_server_config_unref(&ctx->sconfig);
1365 silc_server_config_unref(&ctx->rconfig);
1367 silc_schedule_task_del_by_callback(server->schedule,
1368 silc_server_failure_callback);
1369 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1370 "Key exchange failed");
1371 server->stat.auth_failures++;
1374 silc_ske_free_key_material(ctx->keymat);
1376 /* Allocate internal context for the authentication protocol. This
1377 is sent as context for the protocol. */
1378 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1379 proto_ctx->server = (void *)server;
1380 proto_ctx->sock = sock;
1381 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1382 proto_ctx->responder = TRUE;
1383 proto_ctx->dest_id_type = ctx->dest_id_type;
1384 proto_ctx->dest_id = ctx->dest_id;
1385 proto_ctx->cconfig = ctx->cconfig;
1386 proto_ctx->sconfig = ctx->sconfig;
1387 proto_ctx->rconfig = ctx->rconfig;
1389 /* Free old protocol as it is finished now */
1390 silc_protocol_free(protocol);
1392 silc_packet_context_free(ctx->packet);
1394 sock->protocol = NULL;
1396 /* Allocate the authentication protocol. This is allocated here
1397 but we won't start it yet. We will be receiving party of this
1398 protocol thus we will wait that connecting party will make
1399 their first move. */
1400 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1401 &sock->protocol, proto_ctx,
1402 silc_server_accept_new_connection_final);
1404 /* Register timeout task. If the protocol is not executed inside
1405 this timelimit the connection will be terminated. */
1406 proto_ctx->timeout_task =
1407 silc_schedule_task_add(server->schedule, sock->sock,
1408 silc_server_timeout_remote,
1410 server->config->conn_auth_timeout, 0,
1415 /* Final part of accepting new connection. The connection has now
1416 been authenticated and keys has been exchanged. We also know whether
1417 this is client or server connection. */
1419 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1421 SilcProtocol protocol = (SilcProtocol)context;
1422 SilcServerConnAuthInternalContext *ctx =
1423 (SilcServerConnAuthInternalContext *)protocol->context;
1424 SilcServer server = (SilcServer)ctx->server;
1425 SilcSocketConnection sock = ctx->sock;
1426 SilcServerHBContext hb_context;
1427 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1429 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1431 SILC_LOG_DEBUG(("Start"));
1433 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1434 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1435 /* Error occured during protocol */
1436 silc_protocol_free(protocol);
1437 sock->protocol = NULL;
1439 silc_packet_context_free(ctx->packet);
1441 silc_ske_free(ctx->ske);
1442 silc_free(ctx->dest_id);
1443 silc_server_config_unref(&ctx->cconfig);
1444 silc_server_config_unref(&ctx->sconfig);
1445 silc_server_config_unref(&ctx->rconfig);
1447 silc_schedule_task_del_by_callback(server->schedule,
1448 silc_server_failure_callback);
1449 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1450 "Authentication failed");
1451 server->stat.auth_failures++;
1455 entry->data.last_receive = time(NULL);
1457 switch (ctx->conn_type) {
1458 case SILC_SOCKET_TYPE_CLIENT:
1460 SilcClientEntry client;
1461 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1463 /* Verify whether this connection is after all allowed to connect */
1464 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1465 &server->config->param,
1466 conn->param, ctx->ske)) {
1467 server->stat.auth_failures++;
1471 SILC_LOG_DEBUG(("Remote host is client"));
1472 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1475 /* Add the client to the client ID cache. The nickname and Client ID
1476 and other information is created after we have received NEW_CLIENT
1477 packet from client. */
1478 client = silc_idlist_add_client(server->local_list,
1479 NULL, NULL, NULL, NULL, NULL, sock, 0);
1481 SILC_LOG_ERROR(("Could not add new client to cache"));
1482 silc_free(sock->user_data);
1483 silc_server_disconnect_remote(server, sock,
1484 "Server closed connection: "
1485 "Authentication failed");
1486 server->stat.auth_failures++;
1491 server->stat.my_clients++;
1492 server->stat.clients++;
1493 if (server->server_type == SILC_ROUTER)
1494 server->stat.cell_clients++;
1496 /* Get connection parameters */
1498 if (conn->param->keepalive_secs)
1499 hearbeat_timeout = conn->param->keepalive_secs;
1502 id_entry = (void *)client;
1505 case SILC_SOCKET_TYPE_SERVER:
1506 case SILC_SOCKET_TYPE_ROUTER:
1508 SilcServerEntry new_server;
1509 bool initiator = FALSE;
1510 bool backup_local = FALSE;
1511 bool backup_router = FALSE;
1512 char *backup_replace_ip = NULL;
1513 SilcUInt16 backup_replace_port = 0;
1514 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1515 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1517 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1518 /* Verify whether this connection is after all allowed to connect */
1519 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1520 &server->config->param,
1521 rconn ? rconn->param : NULL,
1523 server->stat.auth_failures++;
1529 if (rconn->param->keepalive_secs)
1530 hearbeat_timeout = rconn->param->keepalive_secs;
1533 initiator = rconn->initiator;
1534 backup_local = rconn->backup_local;
1535 backup_router = rconn->backup_router;
1536 backup_replace_ip = rconn->backup_replace_ip;
1537 backup_replace_port = rconn->backup_replace_port;
1541 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1542 /* Verify whether this connection is after all allowed to connect */
1543 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1544 &server->config->param,
1545 sconn ? sconn->param : NULL,
1547 server->stat.auth_failures++;
1552 if (sconn->param->keepalive_secs)
1553 hearbeat_timeout = sconn->param->keepalive_secs;
1556 backup_router = sconn->backup_router;
1560 SILC_LOG_DEBUG(("Remote host is %s",
1561 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1562 "server" : (backup_router ?
1563 "backup router" : "router")));
1564 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1565 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1566 "server" : (backup_router ?
1567 "backup router" : "router")));
1569 /* Add the server into server cache. The server name and Server ID
1570 is updated after we have received NEW_SERVER packet from the
1571 server. We mark ourselves as router for this server if we really
1574 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1575 server->local_list : (backup_router ?
1576 server->local_list :
1577 server->global_list)),
1579 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1580 SILC_SERVER : SILC_ROUTER),
1582 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1583 server->id_entry : (backup_router ?
1584 server->id_entry : NULL)),
1587 SILC_LOG_ERROR(("Could not add new server to cache"));
1588 silc_free(sock->user_data);
1589 silc_server_disconnect_remote(server, sock,
1590 "Server closed connection: "
1591 "Authentication failed");
1592 server->stat.auth_failures++;
1597 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1598 server->stat.my_servers++;
1600 server->stat.my_routers++;
1601 server->stat.servers++;
1603 id_entry = (void *)new_server;
1605 /* If the incoming connection is router and marked as backup router
1606 then add it to be one of our backups */
1607 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1608 silc_server_backup_add(server, new_server, backup_replace_ip,
1609 backup_replace_port, backup_local);
1611 /* Change it back to SERVER type since that's what it really is. */
1613 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1615 new_server->server_type = SILC_BACKUP_ROUTER;
1618 /* Check whether this connection is to be our primary router connection
1619 if we do not already have the primary route. */
1620 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1621 if (silc_server_config_is_primary_route(server) && !initiator)
1624 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1625 server->standalone = FALSE;
1626 if (!server->id_entry->router) {
1627 server->id_entry->router = id_entry;
1628 server->router = id_entry;
1639 sock->type = ctx->conn_type;
1641 /* Add the common data structure to the ID entry. */
1642 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1644 /* Add to sockets internal pointer for fast referencing */
1645 silc_free(sock->user_data);
1646 sock->user_data = id_entry;
1648 /* Connection has been fully established now. Everything is ok. */
1649 SILC_LOG_DEBUG(("New connection authenticated"));
1651 /* Perform keepalive. The `hb_context' will be freed automatically
1652 when finally calling the silc_socket_free function. */
1653 hb_context = silc_calloc(1, sizeof(*hb_context));
1654 hb_context->server = server;
1655 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1656 silc_server_perform_heartbeat,
1660 silc_schedule_task_del_by_callback(server->schedule,
1661 silc_server_failure_callback);
1662 silc_protocol_free(protocol);
1664 silc_packet_context_free(ctx->packet);
1666 silc_ske_free(ctx->ske);
1667 silc_free(ctx->dest_id);
1668 silc_server_config_unref(&ctx->cconfig);
1669 silc_server_config_unref(&ctx->sconfig);
1670 silc_server_config_unref(&ctx->rconfig);
1672 sock->protocol = NULL;
1675 /* This function is used to read packets from network and send packets to
1676 network. This is usually a generic task. */
1678 SILC_TASK_CALLBACK(silc_server_packet_process)
1680 SilcServer server = (SilcServer)context;
1681 SilcSocketConnection sock = server->sockets[fd];
1682 SilcIDListData idata;
1683 SilcCipher cipher = NULL;
1684 SilcHmac hmac = NULL;
1685 SilcUInt32 sequence = 0;
1691 SILC_LOG_DEBUG(("Processing packet"));
1693 /* Packet sending */
1695 if (type == SILC_TASK_WRITE) {
1696 /* Do not send data to disconnected connection */
1697 if (SILC_IS_DISCONNECTED(sock))
1700 server->stat.packets_sent++;
1702 /* Send the packet */
1703 ret = silc_packet_send(sock, TRUE);
1705 /* If returned -2 could not write to connection now, will do
1711 SILC_LOG_ERROR(("Error sending packet to connection "
1712 "%s:%d [%s]", sock->hostname, sock->port,
1713 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1714 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1715 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1720 /* The packet has been sent and now it is time to set the connection
1721 back to only for input. When there is again some outgoing data
1722 available for this connection it will be set for output as well.
1723 This call clears the output setting and sets it only for input. */
1724 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1725 SILC_UNSET_OUTBUF_PENDING(sock);
1727 silc_buffer_clear(sock->outbuf);
1731 /* Packet receiving */
1733 /* Read some data from connection */
1734 ret = silc_packet_receive(sock);
1738 SILC_LOG_ERROR(("Error receiving packet from connection "
1739 "%s:%d [%s] %s", sock->hostname, sock->port,
1740 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1741 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1742 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1743 "Router"), strerror(errno)));
1749 SILC_LOG_DEBUG(("Read EOF"));
1751 /* If connection is disconnecting already we will finally
1752 close the connection */
1753 if (SILC_IS_DISCONNECTING(sock)) {
1754 if (sock->user_data)
1755 silc_server_free_sock_user_data(server, sock, NULL);
1756 silc_server_close_connection(server, sock);
1760 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1761 SILC_SET_DISCONNECTING(sock);
1763 if (sock->user_data) {
1765 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1766 silc_server_free_sock_user_data(server, sock, tmp);
1768 silc_server_free_sock_user_data(server, sock, NULL);
1769 } else if (server->router_conn && server->router_conn->sock == sock &&
1770 !server->router && server->standalone)
1771 silc_schedule_task_add(server->schedule, 0,
1772 silc_server_connect_to_router,
1775 SILC_TASK_PRI_NORMAL);
1777 silc_server_close_connection(server, sock);
1781 /* If connection is disconnecting or disconnected we will ignore
1783 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1784 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1788 server->stat.packets_received++;
1790 /* Get keys and stuff from ID entry */
1791 idata = (SilcIDListData)sock->user_data;
1793 cipher = idata->receive_key;
1794 hmac = idata->hmac_receive;
1795 sequence = idata->psn_receive;
1798 /* Process the packet. This will call the parser that will then
1799 decrypt and parse the packet. */
1800 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1801 TRUE : FALSE, cipher, hmac, sequence,
1802 silc_server_packet_parse, server);
1804 /* If this socket connection is not authenticated yet and the packet
1805 processing failed we will drop the connection since it can be
1806 a malicious flooder. */
1807 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1808 (!sock->protocol || sock->protocol->protocol->type ==
1809 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1810 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1811 SILC_SET_DISCONNECTING(sock);
1813 if (sock->user_data)
1814 silc_server_free_sock_user_data(server, sock, NULL);
1815 silc_server_close_connection(server, sock);
1819 /* Parses whole packet, received earlier. */
1821 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1823 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1824 SilcServer server = (SilcServer)parse_ctx->context;
1825 SilcSocketConnection sock = parse_ctx->sock;
1826 SilcPacketContext *packet = parse_ctx->packet;
1827 SilcIDListData idata = (SilcIDListData)sock->user_data;
1830 SILC_LOG_DEBUG(("Start"));
1832 /* Parse the packet */
1833 if (parse_ctx->normal)
1834 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1836 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1838 /* If entry is disabled ignore what we got. */
1839 if (ret != SILC_PACKET_RESUME_ROUTER &&
1840 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1841 SILC_LOG_DEBUG(("Connection is disabled"));
1845 if (ret == SILC_PACKET_NONE)
1848 /* Check that the the current client ID is same as in the client's packet. */
1849 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1850 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1851 if (client && client->id) {
1852 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1853 packet->src_id_type);
1854 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1862 if (server->server_type == SILC_ROUTER) {
1863 /* Route the packet if it is not destined to us. Other ID types but
1864 server are handled separately after processing them. */
1865 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1866 packet->dst_id_type == SILC_ID_SERVER &&
1867 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1868 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1870 /* Route the packet to fastest route for the destination ID */
1871 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1872 packet->dst_id_type);
1875 silc_server_packet_route(server,
1876 silc_server_route_get(server, id,
1877 packet->dst_id_type),
1884 /* Parse the incoming packet type */
1885 silc_server_packet_parse_type(server, sock, packet);
1887 if (server->server_type == SILC_ROUTER) {
1888 /* Broadcast packet if it is marked as broadcast packet and it is
1889 originated from router and we are router. */
1890 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1891 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1892 !server->standalone) {
1893 /* Broadcast to our primary route */
1894 silc_server_packet_broadcast(server, server->router->connection, packet);
1896 /* If we have backup routers then we need to feed all broadcast
1897 data to those servers. */
1898 silc_server_backup_broadcast(server, sock, packet);
1903 silc_packet_context_free(packet);
1904 silc_free(parse_ctx);
1907 /* Parser callback called by silc_packet_receive_process. This merely
1908 registers timeout that will handle the actual parsing when appropriate. */
1910 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1913 SilcServer server = (SilcServer)context;
1914 SilcSocketConnection sock = parser_context->sock;
1915 SilcIDListData idata = (SilcIDListData)sock->user_data;
1918 idata->psn_receive = parser_context->packet->sequence + 1;
1920 /* If protocol for this connection is key exchange or rekey then we'll
1921 process all packets synchronously, since there might be packets in
1922 queue that we are not able to decrypt without first processing the
1923 packets before them. */
1924 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1925 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1926 (sock->protocol && sock->protocol->protocol &&
1927 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1928 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1929 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1932 /* Reprocess data since we'll return FALSE here. This is because
1933 the idata->receive_key might have become valid in the last packet
1934 and we want to call this processor with valid cipher. */
1936 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1937 TRUE : FALSE, idata->receive_key,
1938 idata->hmac_receive, idata->psn_receive,
1939 silc_server_packet_parse, server);
1941 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1942 TRUE : FALSE, NULL, NULL, 0,
1943 silc_server_packet_parse, server);
1947 switch (sock->type) {
1948 case SILC_SOCKET_TYPE_UNKNOWN:
1949 case SILC_SOCKET_TYPE_CLIENT:
1950 /* Parse the packet with timeout */
1951 silc_schedule_task_add(server->schedule, sock->sock,
1952 silc_server_packet_parse_real,
1953 (void *)parser_context, 0, 100000,
1955 SILC_TASK_PRI_NORMAL);
1957 case SILC_SOCKET_TYPE_SERVER:
1958 case SILC_SOCKET_TYPE_ROUTER:
1959 /* Packets from servers are parsed immediately */
1960 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1970 /* Parses the packet type and calls what ever routines the packet type
1971 requires. This is done for all incoming packets. */
1973 void silc_server_packet_parse_type(SilcServer server,
1974 SilcSocketConnection sock,
1975 SilcPacketContext *packet)
1977 SilcPacketType type = packet->type;
1978 SilcIDListData idata = (SilcIDListData)sock->user_data;
1980 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1982 /* Parse the packet type */
1984 case SILC_PACKET_DISCONNECT:
1985 SILC_LOG_DEBUG(("Disconnect packet"));
1986 if (packet->flags & SILC_PACKET_FLAG_LIST)
1988 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1989 /* Duplicate to null terminate the string. */
1990 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1991 SILC_LOG_ERROR(("%s", message));
1996 case SILC_PACKET_SUCCESS:
1998 * Success received for something. For now we can have only
1999 * one protocol for connection executing at once hence this
2000 * success message is for whatever protocol is executing currently.
2002 SILC_LOG_DEBUG(("Success packet"));
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2006 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2009 case SILC_PACKET_FAILURE:
2011 * Failure received for something. For now we can have only
2012 * one protocol for connection executing at once hence this
2013 * failure message is for whatever protocol is executing currently.
2015 SILC_LOG_DEBUG(("Failure packet"));
2016 if (packet->flags & SILC_PACKET_FLAG_LIST)
2018 if (sock->protocol) {
2019 SilcServerFailureContext f;
2020 f = silc_calloc(1, sizeof(*f));
2024 /* We will wait 5 seconds to process this failure packet */
2025 silc_schedule_task_add(server->schedule, sock->sock,
2026 silc_server_failure_callback, (void *)f, 5, 0,
2027 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2031 case SILC_PACKET_REJECT:
2032 SILC_LOG_DEBUG(("Reject packet"));
2033 if (packet->flags & SILC_PACKET_FLAG_LIST)
2038 case SILC_PACKET_NOTIFY:
2040 * Received notify packet. Server can receive notify packets from
2041 * router. Server then relays the notify messages to clients if needed.
2043 SILC_LOG_DEBUG(("Notify packet"));
2044 if (packet->flags & SILC_PACKET_FLAG_LIST)
2045 silc_server_notify_list(server, sock, packet);
2047 silc_server_notify(server, sock, packet);
2053 case SILC_PACKET_CHANNEL_MESSAGE:
2055 * Received channel message. Channel messages are special packets
2056 * (although probably most common ones) thus they are handled
2059 SILC_LOG_DEBUG(("Channel Message packet"));
2060 if (packet->flags & SILC_PACKET_FLAG_LIST)
2062 idata->last_receive = time(NULL);
2063 silc_server_channel_message(server, sock, packet);
2066 case SILC_PACKET_CHANNEL_KEY:
2068 * Received key for channel. As channels are created by the router
2069 * the keys are as well. We will distribute the key to all of our
2070 * locally connected clients on the particular channel. Router
2071 * never receives this channel and thus is ignored.
2073 SILC_LOG_DEBUG(("Channel Key packet"));
2074 if (packet->flags & SILC_PACKET_FLAG_LIST)
2076 silc_server_channel_key(server, sock, packet);
2082 case SILC_PACKET_COMMAND:
2084 * Recived command. Processes the command request and allocates the
2085 * command context and calls the command.
2087 SILC_LOG_DEBUG(("Command packet"));
2088 if (packet->flags & SILC_PACKET_FLAG_LIST)
2090 silc_server_command_process(server, sock, packet);
2093 case SILC_PACKET_COMMAND_REPLY:
2095 * Received command reply packet. Received command reply to command. It
2096 * may be reply to command sent by us or reply to command sent by client
2097 * that we've routed further.
2099 SILC_LOG_DEBUG(("Command Reply packet"));
2100 if (packet->flags & SILC_PACKET_FLAG_LIST)
2102 silc_server_command_reply(server, sock, packet);
2106 * Private Message packets
2108 case SILC_PACKET_PRIVATE_MESSAGE:
2110 * Received private message packet. The packet is coming from either
2113 SILC_LOG_DEBUG(("Private Message packet"));
2114 if (packet->flags & SILC_PACKET_FLAG_LIST)
2116 idata->last_receive = time(NULL);
2117 silc_server_private_message(server, sock, packet);
2120 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2122 * Private message key packet.
2124 if (packet->flags & SILC_PACKET_FLAG_LIST)
2126 silc_server_private_message_key(server, sock, packet);
2130 * Key Exchange protocol packets
2132 case SILC_PACKET_KEY_EXCHANGE:
2133 SILC_LOG_DEBUG(("KE packet"));
2134 if (packet->flags & SILC_PACKET_FLAG_LIST)
2137 if (sock->protocol && sock->protocol->protocol &&
2138 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2139 SilcServerKEInternalContext *proto_ctx =
2140 (SilcServerKEInternalContext *)sock->protocol->context;
2142 proto_ctx->packet = silc_packet_context_dup(packet);
2144 /* Let the protocol handle the packet */
2145 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2147 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2148 "protocol active, packet dropped."));
2152 case SILC_PACKET_KEY_EXCHANGE_1:
2153 SILC_LOG_DEBUG(("KE 1 packet"));
2154 if (packet->flags & SILC_PACKET_FLAG_LIST)
2157 if (sock->protocol && sock->protocol->protocol &&
2158 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2159 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2161 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2162 SilcServerRekeyInternalContext *proto_ctx =
2163 (SilcServerRekeyInternalContext *)sock->protocol->context;
2165 if (proto_ctx->packet)
2166 silc_packet_context_free(proto_ctx->packet);
2168 proto_ctx->packet = silc_packet_context_dup(packet);
2170 /* Let the protocol handle the packet */
2171 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2173 SilcServerKEInternalContext *proto_ctx =
2174 (SilcServerKEInternalContext *)sock->protocol->context;
2176 if (proto_ctx->packet)
2177 silc_packet_context_free(proto_ctx->packet);
2179 proto_ctx->packet = silc_packet_context_dup(packet);
2180 proto_ctx->dest_id_type = packet->src_id_type;
2181 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2182 packet->src_id_type);
2183 if (!proto_ctx->dest_id)
2186 /* Let the protocol handle the packet */
2187 silc_protocol_execute(sock->protocol, server->schedule,
2191 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2192 "protocol active, packet dropped."));
2196 case SILC_PACKET_KEY_EXCHANGE_2:
2197 SILC_LOG_DEBUG(("KE 2 packet"));
2198 if (packet->flags & SILC_PACKET_FLAG_LIST)
2201 if (sock->protocol && sock->protocol->protocol &&
2202 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2203 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2205 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2206 SilcServerRekeyInternalContext *proto_ctx =
2207 (SilcServerRekeyInternalContext *)sock->protocol->context;
2209 if (proto_ctx->packet)
2210 silc_packet_context_free(proto_ctx->packet);
2212 proto_ctx->packet = silc_packet_context_dup(packet);
2214 /* Let the protocol handle the packet */
2215 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2217 SilcServerKEInternalContext *proto_ctx =
2218 (SilcServerKEInternalContext *)sock->protocol->context;
2220 if (proto_ctx->packet)
2221 silc_packet_context_free(proto_ctx->packet);
2223 proto_ctx->packet = silc_packet_context_dup(packet);
2224 proto_ctx->dest_id_type = packet->src_id_type;
2225 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2226 packet->src_id_type);
2227 if (!proto_ctx->dest_id)
2230 /* Let the protocol handle the packet */
2231 silc_protocol_execute(sock->protocol, server->schedule,
2235 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2236 "protocol active, packet dropped."));
2240 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2242 * Connection authentication request packet. When we receive this packet
2243 * we will send to the other end information about our mandatory
2244 * authentication method for the connection. This packet maybe received
2247 SILC_LOG_DEBUG(("Connection authentication request packet"));
2248 if (packet->flags & SILC_PACKET_FLAG_LIST)
2250 silc_server_connection_auth_request(server, sock, packet);
2254 * Connection Authentication protocol packets
2256 case SILC_PACKET_CONNECTION_AUTH:
2257 /* Start of the authentication protocol. We receive here the
2258 authentication data and will verify it. */
2259 SILC_LOG_DEBUG(("Connection auth packet"));
2260 if (packet->flags & SILC_PACKET_FLAG_LIST)
2263 if (sock->protocol && sock->protocol->protocol->type
2264 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2266 SilcServerConnAuthInternalContext *proto_ctx =
2267 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2269 proto_ctx->packet = silc_packet_context_dup(packet);
2271 /* Let the protocol handle the packet */
2272 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2274 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2275 "protocol active, packet dropped."));
2279 case SILC_PACKET_NEW_ID:
2281 * Received New ID packet. This includes some new ID that has been
2282 * created. It may be for client, server or channel. This is the way
2283 * to distribute information about new registered entities in the
2286 SILC_LOG_DEBUG(("New ID packet"));
2287 if (packet->flags & SILC_PACKET_FLAG_LIST)
2288 silc_server_new_id_list(server, sock, packet);
2290 silc_server_new_id(server, sock, packet);
2293 case SILC_PACKET_NEW_CLIENT:
2295 * Received new client packet. This includes client information that
2296 * we will use to create initial client ID. After creating new
2297 * ID we will send it to the client.
2299 SILC_LOG_DEBUG(("New Client packet"));
2300 if (packet->flags & SILC_PACKET_FLAG_LIST)
2302 silc_server_new_client(server, sock, packet);
2305 case SILC_PACKET_NEW_SERVER:
2307 * Received new server packet. This includes Server ID and some other
2308 * information that we may save. This is received after server has
2311 SILC_LOG_DEBUG(("New Server packet"));
2312 if (packet->flags & SILC_PACKET_FLAG_LIST)
2314 silc_server_new_server(server, sock, packet);
2317 case SILC_PACKET_NEW_CHANNEL:
2319 * Received new channel packet. Information about new channel in the
2320 * network are distributed using this packet.
2322 SILC_LOG_DEBUG(("New Channel packet"));
2323 if (packet->flags & SILC_PACKET_FLAG_LIST)
2324 silc_server_new_channel_list(server, sock, packet);
2326 silc_server_new_channel(server, sock, packet);
2329 case SILC_PACKET_HEARTBEAT:
2331 * Received heartbeat.
2333 SILC_LOG_DEBUG(("Heartbeat packet"));
2334 if (packet->flags & SILC_PACKET_FLAG_LIST)
2338 case SILC_PACKET_KEY_AGREEMENT:
2340 * Received heartbeat.
2342 SILC_LOG_DEBUG(("Key agreement packet"));
2343 if (packet->flags & SILC_PACKET_FLAG_LIST)
2345 silc_server_key_agreement(server, sock, packet);
2348 case SILC_PACKET_REKEY:
2350 * Received re-key packet. The sender wants to regenerate the session
2353 SILC_LOG_DEBUG(("Re-key packet"));
2354 if (packet->flags & SILC_PACKET_FLAG_LIST)
2356 silc_server_rekey(server, sock, packet);
2359 case SILC_PACKET_REKEY_DONE:
2361 * The re-key is done.
2363 SILC_LOG_DEBUG(("Re-key done packet"));
2364 if (packet->flags & SILC_PACKET_FLAG_LIST)
2367 if (sock->protocol && sock->protocol->protocol &&
2368 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2370 SilcServerRekeyInternalContext *proto_ctx =
2371 (SilcServerRekeyInternalContext *)sock->protocol->context;
2373 if (proto_ctx->packet)
2374 silc_packet_context_free(proto_ctx->packet);
2376 proto_ctx->packet = silc_packet_context_dup(packet);
2378 /* Let the protocol handle the packet */
2379 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2381 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2382 "protocol active, packet dropped."));
2386 case SILC_PACKET_FTP:
2388 SILC_LOG_DEBUG(("FTP packet"));
2389 if (packet->flags & SILC_PACKET_FLAG_LIST)
2391 silc_server_ftp(server, sock, packet);
2394 case SILC_PACKET_RESUME_ROUTER:
2395 /* Resume router packet received. This packet is received for backup
2396 router resuming protocol. */
2397 SILC_LOG_DEBUG(("Resume router packet"));
2398 if (packet->flags & SILC_PACKET_FLAG_LIST)
2400 silc_server_backup_resume_router(server, sock, packet);
2404 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2410 /* Creates connection to a remote router. */
2412 void silc_server_create_connection(SilcServer server,
2413 const char *remote_host, SilcUInt32 port)
2415 SilcServerConnection sconn;
2417 /* Allocate connection object for hold connection specific stuff. */
2418 sconn = silc_calloc(1, sizeof(*sconn));
2419 sconn->server = server;
2420 sconn->remote_host = strdup(remote_host);
2421 sconn->remote_port = port;
2422 sconn->no_reconnect = TRUE;
2424 silc_schedule_task_add(server->schedule, 0,
2425 silc_server_connect_router,
2426 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2427 SILC_TASK_PRI_NORMAL);
2430 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2432 silc_socket_free((SilcSocketConnection)context);
2435 /* Closes connection to socket connection */
2437 void silc_server_close_connection(SilcServer server,
2438 SilcSocketConnection sock)
2440 if (!server->sockets[sock->sock])
2443 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2445 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2446 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2447 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2450 /* We won't listen for this connection anymore */
2451 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2453 /* Unregister all tasks */
2454 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2456 /* Close the actual connection */
2457 silc_net_close_connection(sock->sock);
2458 server->sockets[sock->sock] = NULL;
2460 /* If sock->user_data is NULL then we'll check for active protocols
2461 here since the silc_server_free_sock_user_data has not been called
2462 for this connection. */
2463 if (!sock->user_data) {
2464 /* If any protocol is active cancel its execution. It will call
2465 the final callback which will finalize the disconnection. */
2466 if (sock->protocol) {
2467 silc_protocol_cancel(sock->protocol, server->schedule);
2468 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2469 silc_protocol_execute_final(sock->protocol, server->schedule);
2470 sock->protocol = NULL;
2475 silc_schedule_task_add(server->schedule, 0,
2476 silc_server_close_connection_final,
2477 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2478 SILC_TASK_PRI_NORMAL);
2481 /* Sends disconnect message to remote connection and disconnects the
2484 void silc_server_disconnect_remote(SilcServer server,
2485 SilcSocketConnection sock,
2486 const char *fmt, ...)
2489 unsigned char buf[4096];
2494 memset(buf, 0, sizeof(buf));
2496 vsprintf(buf, fmt, ap);
2499 SILC_LOG_DEBUG(("Disconnecting remote host"));
2501 /* Notify remote end that the conversation is over. The notify message
2502 is tried to be sent immediately. */
2503 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2504 buf, strlen(buf), TRUE);
2505 silc_server_packet_queue_purge(server, sock);
2507 /* Mark the connection to be disconnected */
2508 SILC_SET_DISCONNECTED(sock);
2509 silc_server_close_connection(server, sock);
2514 SilcClientEntry client;
2515 } *FreeClientInternal;
2517 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2519 FreeClientInternal i = (FreeClientInternal)context;
2521 silc_idlist_del_data(i->client);
2522 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2526 /* Frees client data and notifies about client's signoff. */
2528 void silc_server_free_client_data(SilcServer server,
2529 SilcSocketConnection sock,
2530 SilcClientEntry client,
2532 const char *signoff)
2534 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2536 /* If there is pending outgoing data for the client then purge it
2537 to the network before removing the client entry. */
2538 silc_server_packet_queue_purge(server, sock);
2543 /* Send SIGNOFF notify to routers. */
2544 if (notify && !server->standalone && server->router)
2545 silc_server_send_notify_signoff(server, server->router->connection,
2546 server->server_type == SILC_SERVER ?
2547 FALSE : TRUE, client->id, signoff);
2549 /* Remove client from all channels */
2551 silc_server_remove_from_channels(server, NULL, client,
2552 TRUE, (char *)signoff, TRUE);
2554 silc_server_remove_from_channels(server, NULL, client,
2555 FALSE, NULL, FALSE);
2557 /* Update statistics */
2558 server->stat.my_clients--;
2559 server->stat.clients--;
2560 if (server->server_type == SILC_ROUTER)
2561 server->stat.cell_clients--;
2562 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2563 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2565 /* We will not delete the client entry right away. We will take it
2566 into history (for WHOWAS command) for 5 minutes */
2569 silc_schedule_task_add(server->schedule, 0,
2570 silc_server_free_client_data_timeout,
2572 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2573 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2574 client->router = NULL;
2575 client->connection = NULL;
2579 /* Frees user_data pointer from socket connection object. This also sends
2580 appropriate notify packets to the network to inform about leaving
2583 void silc_server_free_sock_user_data(SilcServer server,
2584 SilcSocketConnection sock,
2585 const char *signoff_message)
2587 SILC_LOG_DEBUG(("Start"));
2589 switch (sock->type) {
2590 case SILC_SOCKET_TYPE_CLIENT:
2592 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2593 silc_server_free_client_data(server, sock, user_data, TRUE,
2597 case SILC_SOCKET_TYPE_SERVER:
2598 case SILC_SOCKET_TYPE_ROUTER:
2600 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2601 SilcServerEntry backup_router = NULL;
2604 backup_router = silc_server_backup_get(server, user_data->id);
2606 /* If this was our primary router connection then we're lost to
2607 the outside world. */
2608 if (server->router == user_data) {
2609 /* Check whether we have a backup router connection */
2610 if (!backup_router || backup_router == user_data) {
2611 silc_schedule_task_add(server->schedule, 0,
2612 silc_server_connect_to_router,
2615 SILC_TASK_PRI_NORMAL);
2617 server->id_entry->router = NULL;
2618 server->router = NULL;
2619 server->standalone = TRUE;
2620 backup_router = NULL;
2622 SILC_LOG_INFO(("New primary router is backup router %s",
2623 backup_router->server_name));
2624 SILC_LOG_DEBUG(("New primary router is backup router %s",
2625 backup_router->server_name));
2626 server->id_entry->router = backup_router;
2627 server->router = backup_router;
2628 server->router_connect = time(0);
2629 server->backup_primary = TRUE;
2630 if (server->server_type == SILC_BACKUP_ROUTER) {
2631 server->server_type = SILC_ROUTER;
2633 /* We'll need to constantly try to reconnect to the primary
2634 router so that we'll see when it comes back online. */
2635 silc_server_backup_reconnect(server, sock->ip, sock->port,
2636 silc_server_backup_connected,
2640 /* Mark this connection as replaced */
2641 silc_server_backup_replaced_add(server, user_data->id,
2644 } else if (backup_router) {
2645 SILC_LOG_INFO(("Enabling the use of backup router %s",
2646 backup_router->server_name));
2647 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2648 backup_router->server_name));
2650 /* Mark this connection as replaced */
2651 silc_server_backup_replaced_add(server, user_data->id,
2655 if (!backup_router) {
2656 /* Free all client entries that this server owns as they will
2657 become invalid now as well. */
2659 silc_server_remove_clients_by_server(server, user_data, TRUE);
2660 if (server->server_type == SILC_SERVER)
2661 silc_server_remove_channels_by_server(server, user_data);
2663 /* Update the client entries of this server to the new backup
2664 router. This also removes the clients that *really* was owned
2665 by the primary router and went down with the router. */
2666 silc_server_update_clients_by_server(server, user_data, backup_router,
2668 silc_server_update_servers_by_server(server, user_data, backup_router);
2669 if (server->server_type == SILC_SERVER)
2670 silc_server_update_channels_by_server(server, user_data,
2674 /* Free the server entry */
2675 silc_server_backup_del(server, user_data);
2676 silc_server_backup_replaced_del(server, user_data);
2677 silc_idlist_del_data(user_data);
2678 if (!silc_idlist_del_server(server->local_list, user_data))
2679 silc_idlist_del_server(server->global_list, user_data);
2680 server->stat.my_servers--;
2681 server->stat.servers--;
2682 if (server->server_type == SILC_ROUTER)
2683 server->stat.cell_servers--;
2685 if (backup_router) {
2686 /* Announce all of our stuff that was created about 5 minutes ago.
2687 The backup router knows all the other stuff already. */
2688 if (server->server_type == SILC_ROUTER)
2689 silc_server_announce_servers(server, FALSE, time(0) - 300,
2690 backup_router->connection);
2692 /* Announce our clients and channels to the router */
2693 silc_server_announce_clients(server, time(0) - 300,
2694 backup_router->connection);
2695 silc_server_announce_channels(server, time(0) - 300,
2696 backup_router->connection);
2702 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2704 silc_idlist_del_data(user_data);
2705 silc_free(user_data);
2710 /* If any protocol is active cancel its execution */
2711 if (sock->protocol) {
2712 silc_protocol_cancel(sock->protocol, server->schedule);
2713 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2714 silc_protocol_execute_final(sock->protocol, server->schedule);
2715 sock->protocol = NULL;
2718 sock->user_data = NULL;
2721 /* Removes client from all channels it has joined. This is used when client
2722 connection is disconnected. If the client on a channel is last, the
2723 channel is removed as well. This sends the SIGNOFF notify types. */
2725 void silc_server_remove_from_channels(SilcServer server,
2726 SilcSocketConnection sock,
2727 SilcClientEntry client,
2729 char *signoff_message,
2732 SilcChannelEntry channel;
2733 SilcChannelClientEntry chl;
2734 SilcHashTableList htl;
2737 SILC_LOG_DEBUG(("Start"));
2739 if (!client || !client->id)
2742 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2744 /* Remove the client from all channels. The client is removed from
2745 the channels' user list. */
2746 silc_hash_table_list(client->channels, &htl);
2747 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2748 channel = chl->channel;
2750 /* Remove channel from client's channel list */
2751 silc_hash_table_del(client->channels, channel);
2753 /* Remove channel if there is no users anymore */
2754 if (server->server_type == SILC_ROUTER &&
2755 silc_hash_table_count(channel->user_list) < 2) {
2757 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2758 if (silc_idlist_del_channel(server->local_list, channel))
2759 server->stat.my_channels--;
2761 silc_idlist_del_channel(server->global_list, channel);
2765 /* Remove client from channel's client list */
2766 silc_hash_table_del(channel->user_list, chl->client);
2767 channel->user_count--;
2769 /* If there is no global users on the channel anymore mark the channel
2770 as local channel. Do not check if the removed client is local client. */
2771 if (server->server_type != SILC_ROUTER && channel->global_users &&
2772 chl->client->router && !silc_server_channel_has_global(channel))
2773 channel->global_users = FALSE;
2776 server->stat.my_chanclients--;
2778 /* If there is not at least one local user on the channel then we don't
2779 need the channel entry anymore, we can remove it safely. */
2780 if (server->server_type != SILC_ROUTER &&
2781 !silc_server_channel_has_local(channel)) {
2782 /* Notify about leaving client if this channel has global users. */
2783 if (notify && channel->global_users)
2784 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2785 SILC_NOTIFY_TYPE_SIGNOFF,
2786 signoff_message ? 2 : 1,
2787 clidp->data, clidp->len,
2788 signoff_message, signoff_message ?
2789 strlen(signoff_message) : 0);
2792 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2794 if (channel->founder_key) {
2795 /* The founder auth data exists, do not remove the channel entry */
2796 SilcChannelClientEntry chl2;
2797 SilcHashTableList htl2;
2799 channel->disabled = TRUE;
2801 silc_hash_table_list(channel->user_list, &htl2);
2802 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2803 silc_hash_table_del(chl2->client->channels, channel);
2804 silc_hash_table_del(channel->user_list, chl2->client);
2805 channel->user_count--;
2808 silc_hash_table_list_reset(&htl2);
2812 /* Remove the channel entry */
2813 if (silc_idlist_del_channel(server->local_list, channel))
2814 server->stat.my_channels--;
2816 silc_idlist_del_channel(server->global_list, channel);
2820 /* Send notify to channel about client leaving SILC and thus
2821 the entire channel. */
2823 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2824 SILC_NOTIFY_TYPE_SIGNOFF,
2825 signoff_message ? 2 : 1,
2826 clidp->data, clidp->len,
2827 signoff_message, signoff_message ?
2828 strlen(signoff_message) : 0);
2830 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2831 /* Re-generate channel key */
2832 if (!silc_server_create_channel_key(server, channel, 0))
2835 /* Send the channel key to the channel. The key of course is not sent
2836 to the client who was removed from the channel. */
2837 silc_server_send_channel_key(server, client->connection, channel,
2838 server->server_type == SILC_ROUTER ?
2839 FALSE : !server->standalone);
2844 silc_hash_table_list_reset(&htl);
2845 silc_buffer_free(clidp);
2848 /* Removes client from one channel. This is used for example when client
2849 calls LEAVE command to remove itself from the channel. Returns TRUE
2850 if channel still exists and FALSE if the channel is removed when
2851 last client leaves the channel. If `notify' is FALSE notify messages
2854 int silc_server_remove_from_one_channel(SilcServer server,
2855 SilcSocketConnection sock,
2856 SilcChannelEntry channel,
2857 SilcClientEntry client,
2860 SilcChannelClientEntry chl;
2863 SILC_LOG_DEBUG(("Start"));
2865 /* Get the entry to the channel, if this client is not on the channel
2867 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2870 /* Remove the client from the channel. The client is removed from
2871 the channel's user list. */
2873 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2875 /* Remove channel from client's channel list */
2876 silc_hash_table_del(client->channels, chl->channel);
2878 /* Remove channel if there is no users anymore */
2879 if (server->server_type == SILC_ROUTER &&
2880 silc_hash_table_count(channel->user_list) < 2) {
2882 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2883 if (silc_idlist_del_channel(server->local_list, channel))
2884 server->stat.my_channels--;
2886 silc_idlist_del_channel(server->global_list, channel);
2887 silc_buffer_free(clidp);
2891 /* Remove client from channel's client list */
2892 silc_hash_table_del(channel->user_list, chl->client);
2893 channel->user_count--;
2895 /* If there is no global users on the channel anymore mark the channel
2896 as local channel. Do not check if the client is local client. */
2897 if (server->server_type != SILC_ROUTER && channel->global_users &&
2898 chl->client->router && !silc_server_channel_has_global(channel))
2899 channel->global_users = FALSE;
2902 server->stat.my_chanclients--;
2904 /* If there is not at least one local user on the channel then we don't
2905 need the channel entry anymore, we can remove it safely. */
2906 if (server->server_type != SILC_ROUTER &&
2907 !silc_server_channel_has_local(channel)) {
2908 /* Notify about leaving client if this channel has global users. */
2909 if (notify && channel->global_users)
2910 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2911 SILC_NOTIFY_TYPE_LEAVE, 1,
2912 clidp->data, clidp->len);
2914 silc_buffer_free(clidp);
2917 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2919 if (channel->founder_key) {
2920 /* The founder auth data exists, do not remove the channel entry */
2921 SilcChannelClientEntry chl2;
2922 SilcHashTableList htl2;
2924 channel->disabled = TRUE;
2926 silc_hash_table_list(channel->user_list, &htl2);
2927 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2928 silc_hash_table_del(chl2->client->channels, channel);
2929 silc_hash_table_del(channel->user_list, chl2->client);
2930 channel->user_count--;
2933 silc_hash_table_list_reset(&htl2);
2937 /* Remove the channel entry */
2938 if (silc_idlist_del_channel(server->local_list, channel))
2939 server->stat.my_channels--;
2941 silc_idlist_del_channel(server->global_list, channel);
2945 /* Send notify to channel about client leaving the channel */
2947 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2948 SILC_NOTIFY_TYPE_LEAVE, 1,
2949 clidp->data, clidp->len);
2951 silc_buffer_free(clidp);
2955 /* Timeout callback. This is called if connection is idle or for some
2956 other reason is not responding within some period of time. This
2957 disconnects the remote end. */
2959 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2961 SilcServer server = (SilcServer)context;
2962 SilcSocketConnection sock = server->sockets[fd];
2964 SILC_LOG_DEBUG(("Start"));
2969 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2970 sock->hostname, sock->ip));
2972 /* If we have protocol active we must assure that we call the protocol's
2973 final callback so that all the memory is freed. */
2974 if (sock->protocol) {
2975 silc_protocol_cancel(sock->protocol, server->schedule);
2976 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2977 silc_protocol_execute_final(sock->protocol, server->schedule);
2978 sock->protocol = NULL;
2982 if (sock->user_data)
2983 silc_server_free_sock_user_data(server, sock, NULL);
2985 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2986 "Connection timeout");
2989 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2990 function may be used only by router. In real SILC network all channels
2991 are created by routers thus this function is never used by normal
2994 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2995 SilcServerID *router_id,
3001 SilcChannelID *channel_id;
3002 SilcChannelEntry entry;
3006 SILC_LOG_DEBUG(("Creating new channel"));
3009 cipher = SILC_DEFAULT_CIPHER;
3011 hmac = SILC_DEFAULT_HMAC;
3013 /* Allocate cipher */
3014 if (!silc_cipher_alloc(cipher, &key))
3018 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3019 silc_cipher_free(key);
3023 channel_name = strdup(channel_name);
3025 /* Create the channel ID */
3026 if (!silc_id_create_channel_id(server, router_id, server->rng,
3028 silc_free(channel_name);
3029 silc_cipher_free(key);
3030 silc_hmac_free(newhmac);
3034 /* Create the channel */
3035 entry = silc_idlist_add_channel(server->local_list, channel_name,
3036 SILC_CHANNEL_MODE_NONE, channel_id,
3037 NULL, key, newhmac, 0);
3039 silc_free(channel_name);
3040 silc_cipher_free(key);
3041 silc_hmac_free(newhmac);
3042 silc_free(channel_id);
3046 entry->cipher = strdup(cipher);
3047 entry->hmac_name = strdup(hmac);
3049 /* Now create the actual key material */
3050 if (!silc_server_create_channel_key(server, entry,
3051 silc_cipher_get_key_len(key) / 8)) {
3052 silc_idlist_del_channel(server->local_list, entry);
3056 /* Notify other routers about the new channel. We send the packet
3057 to our primary route. */
3058 if (broadcast && server->standalone == FALSE)
3059 silc_server_send_new_channel(server, server->router->connection, TRUE,
3060 channel_name, entry->id,
3061 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3064 server->stat.my_channels++;
3069 /* Same as above but creates the channel with Channel ID `channel_id. */
3072 silc_server_create_new_channel_with_id(SilcServer server,
3076 SilcChannelID *channel_id,
3079 SilcChannelEntry entry;
3083 SILC_LOG_DEBUG(("Creating new channel"));
3086 cipher = SILC_DEFAULT_CIPHER;
3088 hmac = SILC_DEFAULT_HMAC;
3090 /* Allocate cipher */
3091 if (!silc_cipher_alloc(cipher, &key))
3095 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3096 silc_cipher_free(key);
3100 channel_name = strdup(channel_name);
3102 /* Create the channel */
3103 entry = silc_idlist_add_channel(server->local_list, channel_name,
3104 SILC_CHANNEL_MODE_NONE, channel_id,
3105 NULL, key, newhmac, 0);
3107 silc_cipher_free(key);
3108 silc_hmac_free(newhmac);
3109 silc_free(channel_name);
3113 /* Now create the actual key material */
3114 if (!silc_server_create_channel_key(server, entry,
3115 silc_cipher_get_key_len(key) / 8)) {
3116 silc_idlist_del_channel(server->local_list, entry);
3120 /* Notify other routers about the new channel. We send the packet
3121 to our primary route. */
3122 if (broadcast && server->standalone == FALSE)
3123 silc_server_send_new_channel(server, server->router->connection, TRUE,
3124 channel_name, entry->id,
3125 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3128 server->stat.my_channels++;
3133 /* Channel's key re-key timeout callback. */
3135 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3137 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3138 SilcServer server = (SilcServer)rekey->context;
3142 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3145 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3148 /* Generates new channel key. This is used to create the initial channel key
3149 but also to re-generate new key for channel. If `key_len' is provided
3150 it is the bytes of the key length. */
3152 bool silc_server_create_channel_key(SilcServer server,
3153 SilcChannelEntry channel,
3157 unsigned char channel_key[32], hash[32];
3160 SILC_LOG_DEBUG(("Generating channel key"));
3162 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3163 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3167 if (!channel->channel_key)
3168 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3169 channel->channel_key = NULL;
3175 else if (channel->key_len)
3176 len = channel->key_len / 8;
3178 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3180 /* Create channel key */
3181 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3184 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3186 /* Remove old key if exists */
3188 memset(channel->key, 0, channel->key_len / 8);
3189 silc_free(channel->key);
3193 channel->key_len = len * 8;
3194 channel->key = silc_memdup(channel_key, len);
3195 memset(channel_key, 0, sizeof(channel_key));
3197 /* Generate HMAC key from the channel key data and set it */
3199 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3200 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3201 silc_hmac_set_key(channel->hmac, hash,
3202 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3203 memset(hash, 0, sizeof(hash));
3205 if (server->server_type == SILC_ROUTER) {
3206 if (!channel->rekey)
3207 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3208 channel->rekey->context = (void *)server;
3209 channel->rekey->channel = channel;
3210 channel->rekey->key_len = key_len;
3211 if (channel->rekey->task)
3212 silc_schedule_task_del(server->schedule, channel->rekey->task);
3214 channel->rekey->task =
3215 silc_schedule_task_add(server->schedule, 0,
3216 silc_server_channel_key_rekey,
3217 (void *)channel->rekey,
3218 server->config->channel_rekey_secs, 0,
3220 SILC_TASK_PRI_NORMAL);
3226 /* Saves the channel key found in the encoded `key_payload' buffer. This
3227 function is used when we receive Channel Key Payload and also when we're
3228 processing JOIN command reply. Returns entry to the channel. */
3230 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3231 SilcBuffer key_payload,
3232 SilcChannelEntry channel)
3234 SilcChannelKeyPayload payload = NULL;
3235 SilcChannelID *id = NULL;
3236 unsigned char *tmp, hash[32];
3240 SILC_LOG_DEBUG(("Start"));
3242 /* Decode channel key payload */
3243 payload = silc_channel_key_payload_parse(key_payload->data,
3246 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3251 /* Get the channel entry */
3254 /* Get channel ID */
3255 tmp = silc_channel_key_get_id(payload, &tmp_len);
3256 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3262 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3264 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3266 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3267 silc_id_render(id, SILC_ID_CHANNEL)));
3273 tmp = silc_channel_key_get_key(payload, &tmp_len);
3279 cipher = silc_channel_key_get_cipher(payload, NULL);
3285 /* Remove old key if exists */
3287 memset(channel->key, 0, channel->key_len / 8);
3288 silc_free(channel->key);
3289 silc_cipher_free(channel->channel_key);
3292 /* Create new cipher */
3293 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3294 channel->channel_key = NULL;
3299 if (channel->cipher)
3300 silc_free(channel->cipher);
3301 channel->cipher = strdup(cipher);
3304 channel->key_len = tmp_len * 8;
3305 channel->key = silc_memdup(tmp, tmp_len);
3306 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3308 /* Generate HMAC key from the channel key data and set it */
3310 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3311 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3312 silc_hmac_set_key(channel->hmac, hash,
3313 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3315 memset(hash, 0, sizeof(hash));
3316 memset(tmp, 0, tmp_len);
3318 if (server->server_type == SILC_ROUTER) {
3319 if (!channel->rekey)
3320 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3321 channel->rekey->context = (void *)server;
3322 channel->rekey->channel = channel;
3323 if (channel->rekey->task)
3324 silc_schedule_task_del(server->schedule, channel->rekey->task);
3326 channel->rekey->task =
3327 silc_schedule_task_add(server->schedule, 0,
3328 silc_server_channel_key_rekey,
3329 (void *)channel->rekey,
3330 server->config->channel_rekey_secs, 0,
3332 SILC_TASK_PRI_NORMAL);
3338 silc_channel_key_payload_free(payload);
3343 /* Heartbeat callback. This function is set as argument for the
3344 silc_socket_set_heartbeat function. The library will call this function
3345 at the set time interval. */
3347 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3350 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3352 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3354 /* Send the heartbeat */
3355 silc_server_send_heartbeat(hb->server, sock);
3358 /* Returns assembled of all servers in the given ID list. The packet's
3359 form is dictated by the New ID payload. */
3361 static void silc_server_announce_get_servers(SilcServer server,
3362 SilcServerEntry remote,
3364 SilcBuffer *servers,
3365 unsigned long creation_time)
3367 SilcIDCacheList list;
3368 SilcIDCacheEntry id_cache;
3369 SilcServerEntry entry;
3372 /* Go through all clients in the list */
3373 if (silc_idcache_get_all(id_list->servers, &list)) {
3374 if (silc_idcache_list_first(list, &id_cache)) {
3376 entry = (SilcServerEntry)id_cache->context;
3378 /* Do not announce the one we've sending our announcements and
3379 do not announce ourself. Also check the creation time if it's
3381 if ((entry == remote) || (entry == server->id_entry) ||
3382 (creation_time && entry->data.created < creation_time)) {
3383 if (!silc_idcache_list_next(list, &id_cache))
3388 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3390 *servers = silc_buffer_realloc(*servers,
3392 (*servers)->truelen + idp->len :
3394 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3395 silc_buffer_put(*servers, idp->data, idp->len);
3396 silc_buffer_pull(*servers, idp->len);
3397 silc_buffer_free(idp);
3399 if (!silc_idcache_list_next(list, &id_cache))
3404 silc_idcache_list_free(list);
3409 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3415 p = silc_notify_payload_encode(notify, argc, ap);
3421 /* This function is used by router to announce existing servers to our
3422 primary router when we've connected to it. If `creation_time' is non-zero
3423 then only the servers that has been created after the `creation_time'
3424 will be announced. */
3426 void silc_server_announce_servers(SilcServer server, bool global,
3427 unsigned long creation_time,
3428 SilcSocketConnection remote)
3430 SilcBuffer servers = NULL;
3432 SILC_LOG_DEBUG(("Announcing servers"));
3434 /* Get servers in local list */
3435 silc_server_announce_get_servers(server, remote->user_data,
3436 server->local_list, &servers,
3440 /* Get servers in global list */
3441 silc_server_announce_get_servers(server, remote->user_data,
3442 server->global_list, &servers,
3446 silc_buffer_push(servers, servers->data - servers->head);
3447 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3449 /* Send the packet */
3450 silc_server_packet_send(server, remote,
3451 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3452 servers->data, servers->len, TRUE);
3454 silc_buffer_free(servers);
3458 /* Returns assembled packet of all clients in the given ID list. The
3459 packet's form is dictated by the New ID Payload. */
3461 static void silc_server_announce_get_clients(SilcServer server,
3463 SilcBuffer *clients,
3465 unsigned long creation_time)
3467 SilcIDCacheList list;
3468 SilcIDCacheEntry id_cache;
3469 SilcClientEntry client;
3472 unsigned char mode[4];
3474 /* Go through all clients in the list */
3475 if (silc_idcache_get_all(id_list->clients, &list)) {
3476 if (silc_idcache_list_first(list, &id_cache)) {
3478 client = (SilcClientEntry)id_cache->context;
3480 if (creation_time && client->data.created < creation_time) {
3481 if (!silc_idcache_list_next(list, &id_cache))
3486 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3488 *clients = silc_buffer_realloc(*clients,
3490 (*clients)->truelen + idp->len :
3492 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3493 silc_buffer_put(*clients, idp->data, idp->len);
3494 silc_buffer_pull(*clients, idp->len);
3496 SILC_PUT32_MSB(client->mode, mode);
3497 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3498 2, idp->data, idp->len,
3500 *umodes = silc_buffer_realloc(*umodes,
3502 (*umodes)->truelen + tmp->len :
3504 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3505 silc_buffer_put(*umodes, tmp->data, tmp->len);
3506 silc_buffer_pull(*umodes, tmp->len);
3507 silc_buffer_free(tmp);
3509 silc_buffer_free(idp);
3511 if (!silc_idcache_list_next(list, &id_cache))
3516 silc_idcache_list_free(list);
3520 /* This function is used to announce our existing clients to our router
3521 when we've connected to it. If `creation_time' is non-zero then only
3522 the clients that has been created after the `creation_time' will be
3525 void silc_server_announce_clients(SilcServer server,
3526 unsigned long creation_time,
3527 SilcSocketConnection remote)
3529 SilcBuffer clients = NULL;
3530 SilcBuffer umodes = NULL;
3532 SILC_LOG_DEBUG(("Announcing clients"));
3534 /* Get clients in local list */
3535 silc_server_announce_get_clients(server, server->local_list,
3536 &clients, &umodes, creation_time);
3538 /* As router we announce our global list as well */
3539 if (server->server_type == SILC_ROUTER)
3540 silc_server_announce_get_clients(server, server->global_list,
3541 &clients, &umodes, creation_time);
3544 silc_buffer_push(clients, clients->data - clients->head);
3545 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3547 /* Send the packet */
3548 silc_server_packet_send(server, remote,
3549 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3550 clients->data, clients->len, TRUE);
3552 silc_buffer_free(clients);
3556 silc_buffer_push(umodes, umodes->data - umodes->head);
3557 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3559 /* Send the packet */
3560 silc_server_packet_send(server, remote,
3561 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3562 umodes->data, umodes->len, TRUE);
3564 silc_buffer_free(umodes);
3568 /* Returns channel's topic for announcing it */
3570 void silc_server_announce_get_channel_topic(SilcServer server,
3571 SilcChannelEntry channel,
3576 if (channel->topic) {
3577 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3578 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3579 chidp->data, chidp->len,
3581 strlen(channel->topic));
3582 silc_buffer_free(chidp);
3586 /* Returns assembled packets for channel users of the `channel'. */
3588 void silc_server_announce_get_channel_users(SilcServer server,
3589 SilcChannelEntry channel,
3590 SilcBuffer *channel_users,
3591 SilcBuffer *channel_users_modes)
3593 SilcChannelClientEntry chl;
3594 SilcHashTableList htl;
3595 SilcBuffer chidp, clidp;
3598 unsigned char mode[4];
3600 SILC_LOG_DEBUG(("Start"));
3602 /* Now find all users on the channel */
3603 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3604 silc_hash_table_list(channel->user_list, &htl);
3605 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3606 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3609 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3610 clidp->data, clidp->len,
3611 chidp->data, chidp->len);
3614 silc_buffer_realloc(*channel_users,
3616 (*channel_users)->truelen + len : len));
3617 silc_buffer_pull_tail(*channel_users,
3618 ((*channel_users)->end -
3619 (*channel_users)->data));
3621 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3622 silc_buffer_pull(*channel_users, len);
3623 silc_buffer_free(tmp);
3625 /* CUMODE notify for mode change on the channel */
3626 SILC_PUT32_MSB(chl->mode, mode);
3627 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3628 3, clidp->data, clidp->len,
3630 clidp->data, clidp->len);
3632 *channel_users_modes =
3633 silc_buffer_realloc(*channel_users_modes,
3634 (*channel_users_modes ?
3635 (*channel_users_modes)->truelen + len : len));
3636 silc_buffer_pull_tail(*channel_users_modes,
3637 ((*channel_users_modes)->end -
3638 (*channel_users_modes)->data));
3640 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3641 silc_buffer_pull(*channel_users_modes, len);
3642 silc_buffer_free(tmp);
3644 silc_buffer_free(clidp);
3646 silc_hash_table_list_reset(&htl);
3647 silc_buffer_free(chidp);
3650 /* Returns assembled packets for all channels and users on those channels
3651 from the given ID List. The packets are in the form dictated by the
3652 New Channel and New Channel User payloads. */
3654 void silc_server_announce_get_channels(SilcServer server,
3656 SilcBuffer *channels,
3657 SilcBuffer *channel_users,
3658 SilcBuffer **channel_users_modes,
3659 SilcUInt32 *channel_users_modes_c,
3660 SilcBuffer **channel_topics,
3661 SilcChannelID ***channel_ids,
3662 unsigned long creation_time)
3664 SilcIDCacheList list;
3665 SilcIDCacheEntry id_cache;
3666 SilcChannelEntry channel;
3669 SilcUInt16 name_len;
3671 int i = *channel_users_modes_c;
3674 SILC_LOG_DEBUG(("Start"));
3676 /* Go through all channels in the list */
3677 if (silc_idcache_get_all(id_list->channels, &list)) {
3678 if (silc_idcache_list_first(list, &id_cache)) {
3680 channel = (SilcChannelEntry)id_cache->context;
3682 if (creation_time && channel->created < creation_time)
3687 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3688 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3689 name_len = strlen(channel->channel_name);
3692 len = 4 + name_len + id_len + 4;
3694 silc_buffer_realloc(*channels,
3695 (*channels ? (*channels)->truelen +
3697 silc_buffer_pull_tail(*channels,
3698 ((*channels)->end - (*channels)->data));
3699 silc_buffer_format(*channels,
3700 SILC_STR_UI_SHORT(name_len),
3701 SILC_STR_UI_XNSTRING(channel->channel_name,
3703 SILC_STR_UI_SHORT(id_len),
3704 SILC_STR_UI_XNSTRING(cid, id_len),
3705 SILC_STR_UI_INT(channel->mode),
3707 silc_buffer_pull(*channels, len);
3710 /* Channel user modes */
3711 *channel_users_modes = silc_realloc(*channel_users_modes,
3712 sizeof(**channel_users_modes) *
3714 (*channel_users_modes)[i] = NULL;
3715 *channel_ids = silc_realloc(*channel_ids,
3716 sizeof(**channel_ids) * (i + 1));
3717 (*channel_ids)[i] = NULL;
3718 silc_server_announce_get_channel_users(server, channel,
3720 &(*channel_users_modes)[i]);
3721 (*channel_ids)[i] = channel->id;
3723 /* Channel's topic */
3724 *channel_topics = silc_realloc(*channel_topics,
3725 sizeof(**channel_topics) * (i + 1));
3726 (*channel_topics)[i] = NULL;
3727 silc_server_announce_get_channel_topic(server, channel,
3728 &(*channel_topics)[i]);
3731 if (!silc_idcache_list_next(list, &id_cache))
3735 *channel_users_modes_c += i;
3738 silc_idcache_list_free(list);
3742 /* This function is used to announce our existing channels to our router
3743 when we've connected to it. This also announces the users on the
3744 channels to the router. If the `creation_time' is non-zero only the
3745 channels that was created after the `creation_time' are announced.
3746 Note that the channel users are still announced even if the `creation_time'
3749 void silc_server_announce_channels(SilcServer server,
3750 unsigned long creation_time,
3751 SilcSocketConnection remote)
3753 SilcBuffer channels = NULL, channel_users = NULL;
3754 SilcBuffer *channel_users_modes = NULL;
3755 SilcBuffer *channel_topics = NULL;
3756 SilcUInt32 channel_users_modes_c = 0;
3757 SilcChannelID **channel_ids = NULL;
3759 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3761 /* Get channels and channel users in local list */
3762 silc_server_announce_get_channels(server, server->local_list,
3763 &channels, &channel_users,
3764 &channel_users_modes,
3765 &channel_users_modes_c,
3767 &channel_ids, creation_time);
3769 /* Get channels and channel users in global list */
3770 if (server->server_type != SILC_SERVER)
3771 silc_server_announce_get_channels(server, server->global_list,
3772 &channels, &channel_users,
3773 &channel_users_modes,
3774 &channel_users_modes_c,
3776 &channel_ids, creation_time);
3779 silc_buffer_push(channels, channels->data - channels->head);
3780 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3782 /* Send the packet */
3783 silc_server_packet_send(server, remote,
3784 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3785 channels->data, channels->len,
3788 silc_buffer_free(channels);
3791 if (channel_users) {
3792 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3793 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3794 channel_users->len);
3796 /* Send the packet */
3797 silc_server_packet_send(server, remote,
3798 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3799 channel_users->data, channel_users->len,
3802 silc_buffer_free(channel_users);
3805 if (channel_users_modes) {
3808 for (i = 0; i < channel_users_modes_c; i++) {
3809 if (!channel_users_modes[i])
3811 silc_buffer_push(channel_users_modes[i],
3812 channel_users_modes[i]->data -
3813 channel_users_modes[i]->head);
3814 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3815 channel_users_modes[i]->len);
3816 silc_server_packet_send_dest(server, remote,
3817 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3818 channel_ids[i], SILC_ID_CHANNEL,
3819 channel_users_modes[i]->data,
3820 channel_users_modes[i]->len,
3822 silc_buffer_free(channel_users_modes[i]);
3824 silc_free(channel_users_modes);
3827 if (channel_topics) {
3830 for (i = 0; i < channel_users_modes_c; i++) {
3831 if (!channel_topics[i])
3834 silc_buffer_push(channel_topics[i],
3835 channel_topics[i]->data -
3836 channel_topics[i]->head);
3837 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3838 channel_topics[i]->len);
3839 silc_server_packet_send_dest(server, remote,
3840 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3841 channel_ids[i], SILC_ID_CHANNEL,
3842 channel_topics[i]->data,
3843 channel_topics[i]->len,
3845 silc_buffer_free(channel_topics[i]);
3847 silc_free(channel_topics);
3850 silc_free(channel_ids);
3853 /* Failure timeout callback. If this is called then we will immediately
3854 process the received failure. We always process the failure with timeout
3855 since we do not want to blindly trust to received failure packets.
3856 This won't be called (the timeout is cancelled) if the failure was
3857 bogus (it is bogus if remote does not close the connection after sending
3860 SILC_TASK_CALLBACK(silc_server_failure_callback)
3862 SilcServerFailureContext f = (SilcServerFailureContext)context;
3864 if (f->sock->protocol) {
3865 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3866 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3872 /* Assembles user list and users mode list from the `channel'. */
3874 void silc_server_get_users_on_channel(SilcServer server,
3875 SilcChannelEntry channel,
3876 SilcBuffer *user_list,
3877 SilcBuffer *mode_list,
3878 SilcUInt32 *user_count)
3880 SilcChannelClientEntry chl;
3881 SilcHashTableList htl;
3882 SilcBuffer client_id_list;
3883 SilcBuffer client_mode_list;
3885 SilcUInt32 list_count = 0, len = 0;
3887 silc_hash_table_list(channel->user_list, &htl);
3888 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3889 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3890 silc_hash_table_list_reset(&htl);
3892 client_id_list = silc_buffer_alloc(len);
3894 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3895 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3896 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3898 silc_hash_table_list(channel->user_list, &htl);
3899 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3901 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3902 silc_buffer_put(client_id_list, idp->data, idp->len);
3903 silc_buffer_pull(client_id_list, idp->len);
3904 silc_buffer_free(idp);
3906 /* Client's mode on channel */
3907 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3908 silc_buffer_pull(client_mode_list, 4);
3912 silc_hash_table_list_reset(&htl);
3913 silc_buffer_push(client_id_list,
3914 client_id_list->data - client_id_list->head);
3915 silc_buffer_push(client_mode_list,
3916 client_mode_list->data - client_mode_list->head);
3918 *user_list = client_id_list;
3919 *mode_list = client_mode_list;
3920 *user_count = list_count;
3923 /* Saves users and their modes to the `channel'. */
3925 void silc_server_save_users_on_channel(SilcServer server,
3926 SilcSocketConnection sock,
3927 SilcChannelEntry channel,
3928 SilcClientID *noadd,
3929 SilcBuffer user_list,
3930 SilcBuffer mode_list,
3931 SilcUInt32 user_count)
3936 SilcClientID *client_id;
3937 SilcClientEntry client;
3938 SilcIDCacheEntry cache;
3941 SILC_LOG_DEBUG(("Start"));
3943 for (i = 0; i < user_count; i++) {
3945 SILC_GET16_MSB(idp_len, user_list->data + 2);
3947 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3948 silc_buffer_pull(user_list, idp_len);
3953 SILC_GET32_MSB(mode, mode_list->data);
3954 silc_buffer_pull(mode_list, 4);
3956 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3957 silc_free(client_id);
3963 /* Check if we have this client cached already. */
3964 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3965 server->server_type, &cache);
3967 client = silc_idlist_find_client_by_id(server->global_list,
3968 client_id, server->server_type,
3973 /* If router did not find such Client ID in its lists then this must
3974 be bogus client or some router in the net is buggy. */
3975 if (server->server_type == SILC_ROUTER) {
3976 silc_free(client_id);
3980 /* We don't have that client anywhere, add it. The client is added
3981 to global list since server didn't have it in the lists so it must be
3983 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3984 silc_id_dup(client_id, SILC_ID_CLIENT),
3985 sock->user_data, NULL, 0);
3987 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3988 silc_free(client_id);
3992 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3994 /* Found, if it is from global list we'll assure that we won't
3995 expire it now that the entry is on channel. */
4000 silc_free(client_id);
4002 if (!silc_server_client_on_channel(client, channel, NULL)) {
4003 /* Client was not on the channel, add it. */
4004 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
4005 chl->client = client;
4007 chl->channel = channel;
4008 silc_hash_table_add(channel->user_list, chl->client, chl);
4009 silc_hash_table_add(client->channels, chl->channel, chl);
4010 channel->user_count++;
4015 /* Lookups route to the client indicated by the `id_data'. The connection
4016 object and internal data object is returned. Returns NULL if route
4017 could not be found to the client. If the `client_id' is specified then
4018 it is used and the `id_data' is ignored. */
4020 SilcSocketConnection silc_server_get_client_route(SilcServer server,
4021 unsigned char *id_data,
4023 SilcClientID *client_id,
4024 SilcIDListData *idata)
4027 SilcClientEntry client;
4029 SILC_LOG_DEBUG(("Start"));
4031 /* Decode destination Client ID */
4033 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4035 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4039 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4042 /* If the destination belongs to our server we don't have to route
4043 the packet anywhere but to send it to the local destination. */
4044 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4048 /* If we are router and the client has router then the client is in
4049 our cell but not directly connected to us. */
4050 if (server->server_type == SILC_ROUTER && client->router) {
4051 /* We are of course in this case the client's router thus the route
4052 to the client is the server who owns the client. So, we will send
4053 the packet to that server. */
4055 *idata = (SilcIDListData)client->router;
4056 return client->router->connection;
4059 /* Seems that client really is directly connected to us */
4061 *idata = (SilcIDListData)client;
4062 return client->connection;
4065 /* Destination belongs to someone not in this server. If we are normal
4066 server our action is to send the packet to our router. */
4067 if (server->server_type != SILC_ROUTER && !server->standalone) {
4070 *idata = (SilcIDListData)server->router;
4071 return server->router->connection;
4074 /* We are router and we will perform route lookup for the destination
4075 and send the packet to fastest route. */
4076 if (server->server_type == SILC_ROUTER && !server->standalone) {
4077 /* Check first that the ID is valid */
4078 client = silc_idlist_find_client_by_id(server->global_list, id,
4081 SilcSocketConnection dst_sock;
4083 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4087 *idata = (SilcIDListData)dst_sock->user_data;
4096 /* Encodes and returns channel list of channels the `client' has joined.
4097 Secret channels are not put to the list. */
4099 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4100 SilcClientEntry client)
4102 SilcBuffer buffer = NULL;
4103 SilcChannelEntry channel;
4104 SilcChannelClientEntry chl;
4105 SilcHashTableList htl;
4108 SilcUInt16 name_len;
4111 silc_hash_table_list(client->channels, &htl);
4112 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4113 channel = chl->channel;
4115 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4116 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4119 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4120 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4121 name_len = strlen(channel->channel_name);
4123 len = 4 + name_len + id_len + 4;
4124 buffer = silc_buffer_realloc(buffer,
4125 (buffer ? (buffer)->truelen + len : len));
4126 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4127 silc_buffer_format(buffer,
4128 SILC_STR_UI_SHORT(name_len),
4129 SILC_STR_UI_XNSTRING(channel->channel_name,
4131 SILC_STR_UI_SHORT(id_len),
4132 SILC_STR_UI_XNSTRING(cid, id_len),
4133 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4135 silc_buffer_pull(buffer, len);
4138 silc_hash_table_list_reset(&htl);
4141 silc_buffer_push(buffer, buffer->data - buffer->head);
4146 /* Finds client entry by Client ID and if it is not found then resolves
4147 it using WHOIS command. */
4149 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4150 SilcClientID *client_id,
4153 SilcClientEntry client;
4158 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4161 client = silc_idlist_find_client_by_id(server->global_list,
4162 client_id, TRUE, NULL);
4163 if (!client && server->server_type == SILC_ROUTER)
4167 if (!client && server->standalone)
4170 if (!client || !client->nickname || !client->username) {
4171 SilcBuffer buffer, idp;
4173 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4174 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4175 client->resolve_cmd_ident = ++server->cmd_ident;
4177 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4178 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4179 server->cmd_ident, 1,
4180 3, idp->data, idp->len);
4181 silc_server_packet_send(server, client ? client->router->connection :
4182 server->router->connection,
4183 SILC_PACKET_COMMAND, 0,
4184 buffer->data, buffer->len, FALSE);
4185 silc_buffer_free(idp);
4186 silc_buffer_free(buffer);
4197 /* A timeout callback for the re-key. We will be the initiator of the
4200 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4202 SilcSocketConnection sock = (SilcSocketConnection)context;
4203 SilcIDListData idata = (SilcIDListData)sock->user_data;
4204 SilcServer server = (SilcServer)idata->rekey->context;
4205 SilcProtocol protocol;
4206 SilcServerRekeyInternalContext *proto_ctx;
4208 SILC_LOG_DEBUG(("Start"));
4210 /* Allocate internal protocol context. This is sent as context
4212 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4213 proto_ctx->server = (void *)server;
4214 proto_ctx->sock = sock;
4215 proto_ctx->responder = FALSE;
4216 proto_ctx->pfs = idata->rekey->pfs;
4218 /* Perform rekey protocol. Will call the final callback after the
4219 protocol is over. */
4220 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4221 &protocol, proto_ctx, silc_server_rekey_final);
4222 sock->protocol = protocol;
4224 /* Run the protocol */
4225 silc_protocol_execute(protocol, server->schedule, 0, 0);
4227 /* Re-register re-key timeout */
4228 silc_schedule_task_add(server->schedule, sock->sock,
4229 silc_server_rekey_callback,
4230 context, idata->rekey->timeout, 0,
4231 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4234 /* The final callback for the REKEY protocol. This will actually take the
4235 new key material into use. */
4237 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4239 SilcProtocol protocol = (SilcProtocol)context;
4240 SilcServerRekeyInternalContext *ctx =
4241 (SilcServerRekeyInternalContext *)protocol->context;
4242 SilcServer server = (SilcServer)ctx->server;
4243 SilcSocketConnection sock = ctx->sock;
4245 SILC_LOG_DEBUG(("Start"));
4247 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4248 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4249 /* Error occured during protocol */
4250 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4251 silc_protocol_cancel(protocol, server->schedule);
4252 silc_protocol_free(protocol);
4253 sock->protocol = NULL;
4255 silc_packet_context_free(ctx->packet);
4257 silc_ske_free(ctx->ske);
4262 /* Purge the outgoing data queue to assure that all rekey packets really
4263 go to the network before we quit the protocol. */
4264 silc_server_packet_queue_purge(server, sock);
4267 silc_protocol_free(protocol);
4268 sock->protocol = NULL;
4270 silc_packet_context_free(ctx->packet);
4272 silc_ske_free(ctx->ske);