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);
47 SILC_TASK_CALLBACK(silc_server_get_stats);
49 /* Allocates a new SILC server object. This has to be done before the server
50 can be used. After allocation one must call silc_server_init to initialize
51 the server. The new allocated server object is returned to the new_server
54 int silc_server_alloc(SilcServer *new_server)
58 SILC_LOG_DEBUG(("Allocating new server object"));
60 server = silc_calloc(1, sizeof(*server));
61 server->server_type = SILC_SERVER;
62 server->standalone = TRUE;
63 server->local_list = silc_calloc(1, sizeof(*server->local_list));
64 server->global_list = silc_calloc(1, sizeof(*server->global_list));
65 server->pending_commands = silc_dlist_init();
67 server->sim = silc_dlist_init();
75 /* Free's the SILC server object. This is called at the very end before
78 void silc_server_free(SilcServer server)
87 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
88 silc_dlist_del(server->sim, sim);
91 silc_dlist_uninit(server->sim);
95 silc_server_config_unref(&server->config_ref);
97 silc_rng_free(server->rng);
99 silc_pkcs_free(server->pkcs);
100 if (server->public_key)
101 silc_pkcs_public_key_free(server->public_key);
102 if (server->private_key)
103 silc_pkcs_private_key_free(server->private_key);
104 if (server->pending_commands)
105 silc_dlist_uninit(server->pending_commands);
106 if (server->id_entry)
107 silc_idlist_del_server(server->local_list, server->id_entry);
109 silc_idcache_free(server->local_list->clients);
110 silc_idcache_free(server->local_list->servers);
111 silc_idcache_free(server->local_list->channels);
112 silc_idcache_free(server->global_list->clients);
113 silc_idcache_free(server->global_list->servers);
114 silc_idcache_free(server->global_list->channels);
115 silc_hash_table_free(server->watcher_list);
117 silc_hash_free(server->md5hash);
118 silc_hash_free(server->sha1hash);
119 silc_hmac_unregister_all();
120 silc_hash_unregister_all();
121 silc_cipher_unregister_all();
122 silc_pkcs_unregister_all();
124 silc_free(server->local_list);
125 silc_free(server->global_list);
126 silc_free(server->server_name);
127 silc_free(server->id_string);
128 silc_free(server->purge_i);
129 silc_free(server->purge_g);
133 /* Creates a new server listener. */
135 static bool silc_server_listen(SilcServer server, const char *server_ip,
136 SilcUInt16 port, int *sock)
138 *sock = silc_net_create_server(port, server_ip);
140 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
147 /* Adds a secondary listener. */
149 bool silc_server_init_secondary(SilcServer server)
151 int sock = 0, sock_list[server->config->param.connections_max];
152 SilcSocketConnection newsocket = NULL;
153 SilcServerConfigServerInfoInterface *interface;
155 for (interface = server->config->server_info->secondary; interface;
156 interface = interface->next, sock++) {
158 if (!silc_server_listen(server,
159 interface->server_ip, interface->port, &sock_list[sock]))
162 /* Set socket to non-blocking mode */
163 silc_net_set_socket_nonblock(sock_list[sock]);
165 /* Add ourselves also to the socket table. The entry allocated above
166 is sent as argument for fast referencing in the future. */
167 silc_socket_alloc(sock_list[sock],
168 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
169 server->sockets[sock_list[sock]] = newsocket;
170 SILC_SET_LISTENER(newsocket);
172 /* Perform name and address lookups to resolve the listenning address
174 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
176 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
178 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
179 newsocket->hostname ? newsocket->hostname :
180 newsocket->ip ? newsocket->ip : ""));
181 server->stat.conn_failures++;
184 if (!newsocket->hostname)
185 newsocket->hostname = strdup(newsocket->ip);
187 newsocket->port = silc_net_get_local_port(sock);
189 newsocket->user_data = (void *)server->id_entry;
190 silc_schedule_task_add(server->schedule, sock_list[sock],
191 silc_server_accept_new_connection,
192 (void *)server, 0, 0,
194 SILC_TASK_PRI_NORMAL);
200 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
204 /* Initializes the entire SILC server. This is called always before running
205 the server. This is called only once at the initialization of the program.
206 This binds the server to its listenning port. After this function returns
207 one should call silc_server_run to start the server. This returns TRUE
208 when everything is ok to run the server. Configuration file must be
209 read and parsed before calling this. */
211 bool silc_server_init(SilcServer server)
215 SilcServerEntry id_entry;
216 SilcIDListPurge purge;
217 SilcSocketConnection newsocket = NULL;
219 SILC_LOG_DEBUG(("Initializing server"));
221 server->starttime = time(NULL);
223 /* Take config object for us */
224 silc_server_config_ref(&server->config_ref, server->config,
227 /* Steal public and private key from the config object */
228 server->public_key = server->config->server_info->public_key;
229 server->private_key = server->config->server_info->private_key;
230 server->config->server_info->public_key = NULL;
231 server->config->server_info->private_key = NULL;
233 /* Register all configured ciphers, PKCS and hash functions. */
234 if (!silc_server_config_register_ciphers(server))
235 silc_cipher_register_default();
236 if (!silc_server_config_register_pkcs(server))
237 silc_pkcs_register_default();
238 if (!silc_server_config_register_hashfuncs(server))
239 silc_hash_register_default();
240 if (!silc_server_config_register_hmacs(server))
241 silc_hmac_register_default();
243 /* Initialize random number generator for the server. */
244 server->rng = silc_rng_alloc();
245 silc_rng_init(server->rng);
246 silc_rng_global_init(server->rng);
248 /* Initialize hash functions for server to use */
249 silc_hash_alloc("md5", &server->md5hash);
250 silc_hash_alloc("sha1", &server->sha1hash);
252 /* Allocate PKCS context for local public and private keys */
253 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
255 silc_pkcs_public_key_set(server->pkcs, server->public_key);
256 silc_pkcs_private_key_set(server->pkcs, server->private_key);
258 /* Initialize the scheduler */
259 server->schedule = silc_schedule_init(server->config->param.connections_max);
260 if (!server->schedule)
263 /* First, register log files configuration for error output */
264 silc_server_config_setlogfiles(server);
266 /* Initialize ID caches */
267 server->local_list->clients =
268 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
269 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
270 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
272 /* These are allocated for normal server as well as these hold some
273 global information that the server has fetched from its router. For
274 router these are used as they are supposed to be used on router. */
275 server->global_list->clients =
276 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
277 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
278 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
280 /* Init watcher list */
281 server->watcher_list =
282 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
283 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
285 if (!server->watcher_list)
288 /* Create a listening server */
289 if (!silc_server_listen(server,
290 server->config->server_info->primary == NULL ? NULL :
291 server->config->server_info->primary->server_ip,
292 server->config->server_info->primary == NULL ? 0 :
293 server->config->server_info->primary->port,
297 /* Set socket to non-blocking mode */
298 silc_net_set_socket_nonblock(sock);
301 /* Allocate the entire socket list that is used in server. Eventually
302 all connections will have entry in this table (it is a table of
303 pointers to the actual object that is allocated individually
305 server->sockets = silc_calloc(server->config->param.connections_max,
306 sizeof(*server->sockets));
307 if (!server->sockets)
310 /* Add ourselves also to the socket table. The entry allocated above
311 is sent as argument for fast referencing in the future. */
312 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
313 server->sockets[sock] = newsocket;
314 SILC_SET_LISTENER(newsocket);
316 /* Perform name and address lookups to resolve the listenning address
318 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
320 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
322 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
323 newsocket->hostname ? newsocket->hostname :
324 newsocket->ip ? newsocket->ip : ""));
325 server->stat.conn_failures++;
328 if (!newsocket->hostname)
329 newsocket->hostname = strdup(newsocket->ip);
331 newsocket->port = silc_net_get_local_port(sock);
333 /* Create a Server ID for the server. */
334 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
339 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
340 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
341 server->server_name = server->config->server_info->server_name;
342 server->config->server_info->server_name = NULL;
344 /* Add ourselves to the server list. We don't have a router yet
345 beacuse we haven't established a route yet. It will be done later.
346 For now, NULL is sent as router. This allocates new entry to
349 silc_idlist_add_server(server->local_list, strdup(server->server_name),
350 server->server_type, server->id, NULL, NULL);
352 SILC_LOG_ERROR(("Could not add ourselves to cache"));
355 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
357 /* Put the allocated socket pointer also to the entry allocated above
358 for fast back-referencing to the socket list. */
359 newsocket->user_data = (void *)id_entry;
360 id_entry->connection = (void *)newsocket;
361 server->id_entry = id_entry;
363 /* Register protocols */
364 silc_server_protocols_register();
366 /* Add the first task to the scheduler. This is task that is executed by
367 timeout. It expires as soon as the caller calls silc_server_run. This
368 task performs authentication protocol and key exchange with our
370 silc_schedule_task_add(server->schedule, 0,
371 silc_server_connect_to_router,
372 (void *)server, 0, 1,
374 SILC_TASK_PRI_NORMAL);
376 /* Add listener task to the scheduler. This task receives new connections
377 to the server. This task remains on the queue until the end of the
379 silc_schedule_task_add(server->schedule, sock,
380 silc_server_accept_new_connection,
381 (void *)server, 0, 0,
383 SILC_TASK_PRI_NORMAL);
385 if (silc_server_init_secondary(server) == FALSE)
388 server->listenning = TRUE;
390 /* If server connections has been configured then we must be router as
391 normal server cannot have server connections, only router connections. */
392 if (server->config->servers) {
393 SilcServerConfigServer *ptr = server->config->servers;
395 server->server_type = SILC_ROUTER;
397 if (ptr->backup_router) {
398 server->server_type = SILC_BACKUP_ROUTER;
399 server->backup_router = TRUE;
400 server->id_entry->server_type = SILC_BACKUP_ROUTER;
407 /* Register the ID Cache purge task. This periodically purges the ID cache
408 and removes the expired cache entries. */
410 /* Clients local list */
411 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
412 purge->cache = server->local_list->clients;
413 purge->schedule = server->schedule;
414 purge->timeout = 600;
415 silc_schedule_task_add(purge->schedule, 0,
417 (void *)purge, purge->timeout, 0,
418 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
420 /* Clients global list */
421 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
422 purge->cache = server->global_list->clients;
423 purge->schedule = server->schedule;
424 purge->timeout = 300;
425 silc_schedule_task_add(purge->schedule, 0,
427 (void *)purge, purge->timeout, 0,
428 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
430 /* If we are normal server we'll retrieve network statisticial information
431 once in a while from the router. */
432 if (server->server_type == SILC_SERVER)
433 silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
434 server, 10, 0, SILC_TASK_TIMEOUT,
437 if (server->server_type == SILC_ROUTER)
438 server->stat.routers++;
440 SILC_LOG_DEBUG(("Server initialized"));
442 /* We are done here, return succesfully */
446 silc_server_config_unref(&server->config_ref);
447 silc_net_close_server(sock);
451 /* This function basically reads the config file again and switches the config
452 object pointed by the server object. After that, we have to fix various
453 things such as the server_name and the listening ports.
454 Keep in mind that we no longer have the root privileges at this point. */
456 bool silc_server_rehash(SilcServer server)
458 SilcServerConfig newconfig;
460 SILC_LOG_INFO(("Rehashing server"));
462 /* Reset the logging system */
463 silc_log_quick = TRUE;
464 silc_log_flush_all();
466 /* Start the main rehash phase (read again the config file) */
467 newconfig = silc_server_config_alloc(server->config_file);
469 SILC_LOG_ERROR(("Rehash FAILED."));
473 /* Reinit scheduler if necessary */
474 if (newconfig->param.connections_max > server->config->param.connections_max)
475 if (!silc_schedule_reinit(server->schedule,
476 newconfig->param.connections_max))
479 /* Fix the server_name field */
480 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
481 silc_free(server->server_name);
482 server->server_name = newconfig->server_info->server_name;
483 newconfig->server_info->server_name = NULL;
485 /* Update the idcache list with a fresh pointer */
486 silc_free(server->id_entry->server_name);
487 server->id_entry->server_name = strdup(server->server_name);
488 if (!silc_idcache_del_by_context(server->local_list->servers,
491 if (!silc_idcache_add(server->local_list->servers,
492 server->id_entry->server_name,
493 server->id_entry->id, server->id_entry, 0, NULL))
498 silc_server_config_setlogfiles(server);
500 /* Change new key pair if necessary */
501 if (newconfig->server_info->public_key &&
502 !silc_pkcs_public_key_compare(server->public_key,
503 newconfig->server_info->public_key)) {
504 silc_pkcs_public_key_free(server->public_key);
505 silc_pkcs_private_key_free(server->private_key);
506 server->public_key = newconfig->server_info->public_key;
507 server->private_key = newconfig->server_info->private_key;
508 newconfig->server_info->public_key = NULL;
509 newconfig->server_info->private_key = NULL;
511 /* Allocate PKCS context for local public and private keys */
512 silc_pkcs_free(server->pkcs);
513 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
515 silc_pkcs_public_key_set(server->pkcs, server->public_key);
516 silc_pkcs_private_key_set(server->pkcs, server->private_key);
519 /* Go through all configured routers after rehash */
520 silc_schedule_task_add(server->schedule, 0,
521 silc_server_connect_to_router,
522 (void *)server, 0, 1,
524 SILC_TASK_PRI_NORMAL);
526 /* Check whether our router status has changed */
527 if (newconfig->servers) {
528 SilcServerConfigServer *ptr = newconfig->servers;
530 server->server_type = SILC_ROUTER;
532 if (ptr->backup_router) {
533 server->server_type = SILC_BACKUP_ROUTER;
534 server->backup_router = TRUE;
535 server->id_entry->server_type = SILC_BACKUP_ROUTER;
542 /* Our old config is gone now. We'll unreference our reference made in
543 silc_server_init and then destroy it since we are destroying it
544 underneath the application (layer which called silc_server_init). */
545 silc_server_config_unref(&server->config_ref);
546 silc_server_config_destroy(server->config);
548 /* Take new config context */
549 server->config = newconfig;
550 silc_server_config_ref(&server->config_ref, server->config, server->config);
552 SILC_LOG_DEBUG(("Server rehashed"));
557 /* The heart of the server. This runs the scheduler thus runs the server.
558 When this returns the server has been stopped and the program will
561 void silc_server_run(SilcServer server)
563 SILC_LOG_INFO(("SILC Server started"));
565 /* Start the scheduler, the heart of the SILC server. When this returns
566 the program will be terminated. */
567 silc_schedule(server->schedule);
570 /* Stops the SILC server. This function is used to shutdown the server.
571 This is usually called after the scheduler has returned. After stopping
572 the server one should call silc_server_free. */
574 void silc_server_stop(SilcServer server)
576 SILC_LOG_DEBUG(("Stopping server"));
578 if (server->schedule) {
581 /* Close all connections */
582 for (i = 0; i < server->config->param.connections_max; i++) {
583 if (!server->sockets[i])
585 if (!SILC_IS_LISTENER(server->sockets[i])) {
586 silc_schedule_task_del_by_context(server->schedule,
588 silc_server_disconnect_remote(server, server->sockets[i],
590 "Server is shutting down");
592 silc_socket_free(server->sockets[i]);
593 server->sockets[i] = NULL;
597 /* We are not connected to network anymore */
598 server->standalone = TRUE;
600 silc_schedule_stop(server->schedule);
601 silc_schedule_uninit(server->schedule);
602 server->schedule = NULL;
604 silc_free(server->sockets);
605 server->sockets = NULL;
608 silc_server_protocols_unregister();
610 SILC_LOG_DEBUG(("Server stopped"));
613 /* Function that is called when the network connection to a router has
614 been established. This will continue with the key exchange protocol
615 with the remote router. */
617 void silc_server_start_key_exchange(SilcServer server,
618 SilcServerConnection sconn,
621 SilcSocketConnection newsocket;
622 SilcProtocol protocol;
623 SilcServerKEInternalContext *proto_ctx;
624 SilcServerConfigRouter *conn =
625 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
628 /* Cancel any possible retry timeouts */
629 silc_schedule_task_del_by_callback(server->schedule,
630 silc_server_connect_to_router_retry);
632 /* Set socket options */
633 silc_net_set_socket_nonblock(sock);
634 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
636 /* Create socket connection for the connection. Even though we
637 know that we are connecting to a router we will mark the socket
638 to be unknown connection until we have executed authentication
640 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
641 server->sockets[sock] = newsocket;
642 newsocket->hostname = strdup(sconn->remote_host);
643 newsocket->ip = strdup(sconn->remote_host);
644 newsocket->port = sconn->remote_port;
645 sconn->sock = newsocket;
647 /* Allocate internal protocol context. This is sent as context
649 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
650 proto_ctx->server = (void *)server;
651 proto_ctx->context = (void *)sconn;
652 proto_ctx->sock = newsocket;
653 proto_ctx->rng = server->rng;
654 proto_ctx->responder = FALSE;
656 /* Set Key Exchange flags from configuration, but fall back to global
658 SILC_GET_SKE_FLAGS(conn, proto_ctx);
659 if (server->config->param.key_exchange_pfs)
660 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
662 /* Perform key exchange protocol. silc_server_connect_to_router_second
663 will be called after the protocol is finished. */
664 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
665 &protocol, proto_ctx,
666 silc_server_connect_to_router_second);
667 newsocket->protocol = protocol;
669 /* Register a timeout task that will be executed if the protocol
670 is not executed within set limit. */
671 proto_ctx->timeout_task =
672 silc_schedule_task_add(server->schedule, sock,
673 silc_server_timeout_remote,
674 server, server->config->key_exchange_timeout, 0,
678 /* Register the connection for network input and output. This sets
679 that scheduler will listen for incoming packets for this connection
680 and sets that outgoing packets may be sent to this connection as
681 well. However, this doesn't set the scheduler for outgoing traffic,
682 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
683 later when outgoing data is available. */
684 context = (void *)server;
685 SILC_REGISTER_CONNECTION_FOR_IO(sock);
687 /* Run the protocol */
688 silc_protocol_execute(protocol, server->schedule, 0, 0);
691 /* Timeout callback that will be called to retry connecting to remote
692 router. This is used by both normal and router server. This will wait
693 before retrying the connecting. The timeout is generated by exponential
694 backoff algorithm. */
696 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
698 SilcServerConnection sconn = (SilcServerConnection)context;
699 SilcServer server = sconn->server;
700 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
701 SilcServerConfigConnParams *param =
702 (conn->param ? conn->param : &server->config->param);
704 SILC_LOG_INFO(("Retrying connecting to a router"));
706 /* Calculate next timeout */
707 if (sconn->retry_count >= 1) {
708 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
709 if (sconn->retry_timeout > param->reconnect_interval_max)
710 sconn->retry_timeout = param->reconnect_interval_max;
712 sconn->retry_timeout = param->reconnect_interval;
714 sconn->retry_count++;
715 sconn->retry_timeout = sconn->retry_timeout +
716 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
718 /* If we've reached max retry count, give up. */
719 if ((sconn->retry_count > param->reconnect_count) &&
720 !param->reconnect_keep_trying) {
721 SILC_LOG_ERROR(("Could not connect to router, giving up"));
722 silc_server_config_unref(&sconn->conn);
723 silc_free(sconn->remote_host);
724 silc_free(sconn->backup_replace_ip);
729 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
730 sconn->retry_timeout));
732 /* We will lookup a fresh pointer later */
733 silc_server_config_unref(&sconn->conn);
735 /* Wait one before retrying */
736 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
737 context, sconn->retry_timeout, 0,
738 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
741 /* Generic routine to use connect to a router. */
743 SILC_TASK_CALLBACK(silc_server_connect_router)
745 SilcServerConnection sconn = (SilcServerConnection)context;
746 SilcServer server = sconn->server;
747 SilcServerConfigRouter *rconn;
750 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
751 (sconn->backup ? "backup router" : "router"),
752 sconn->remote_host, sconn->remote_port));
754 server->router_connect = time(NULL);
755 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
758 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
759 (sconn->backup ? "backup router" : "router"),
760 sconn->remote_host, sconn->remote_port));
761 silc_free(sconn->remote_host);
762 silc_free(sconn->backup_replace_ip);
766 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
768 /* Connect to remote host */
769 sock = silc_net_create_connection(
770 (!server->config->server_info->primary ? NULL :
771 server->config->server_info->primary->server_ip),
772 sconn->remote_port, sconn->remote_host);
774 SILC_LOG_ERROR(("Could not connect to router %s:%d",
775 sconn->remote_host, sconn->remote_port));
776 if (!sconn->no_reconnect)
777 silc_schedule_task_add(server->schedule, 0,
778 silc_server_connect_to_router_retry,
779 context, 0, 1, SILC_TASK_TIMEOUT,
780 SILC_TASK_PRI_NORMAL);
782 silc_server_config_unref(&sconn->conn);
786 /* Continue with key exchange protocol */
787 silc_server_start_key_exchange(server, sconn, sock);
790 /* This function connects to our primary router or if we are a router this
791 establishes all our primary routes. This is called at the start of the
792 server to do authentication and key exchange with our router - called
795 SILC_TASK_CALLBACK(silc_server_connect_to_router)
797 SilcServer server = (SilcServer)context;
798 SilcServerConnection sconn;
799 SilcServerConfigRouter *ptr;
801 SILC_LOG_DEBUG(("Connecting to router(s)"));
803 if (server->server_type == SILC_SERVER) {
804 SILC_LOG_DEBUG(("We are normal server"));
805 } else if (server->server_type == SILC_ROUTER) {
806 SILC_LOG_DEBUG(("We are router"));
808 SILC_LOG_DEBUG(("We are backup router/normal server"));
811 if (!server->config->routers) {
812 /* There wasn't a configured router, we will continue but we don't
813 have a connection to outside world. We will be standalone server. */
814 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
815 server->standalone = TRUE;
819 /* Cancel any possible retry timeouts */
820 silc_schedule_task_del_by_callback(server->schedule,
821 silc_server_connect_router);
822 silc_schedule_task_del_by_callback(server->schedule,
823 silc_server_connect_to_router_retry);
825 /* Create the connections to all our routes */
826 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
828 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
829 ptr->backup_router ? "Backup router" : "Router",
830 ptr->initiator ? "Initiator" : "Responder",
831 ptr->host, ptr->port));
833 if (ptr->initiator) {
834 /* Check whether we are connected to this host already */
835 if (silc_server_num_sockets_by_remote(server,
836 silc_net_is_ip(ptr->host) ?
838 silc_net_is_ip(ptr->host) ?
839 NULL : ptr->host, ptr->port,
840 SILC_SOCKET_TYPE_ROUTER)) {
841 SILC_LOG_DEBUG(("We are already connected to this router"));
845 /* Allocate connection object for hold connection specific stuff. */
846 sconn = silc_calloc(1, sizeof(*sconn));
847 sconn->server = server;
848 sconn->remote_host = strdup(ptr->host);
849 sconn->remote_port = ptr->port;
850 sconn->backup = ptr->backup_router;
852 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
853 sconn->backup_replace_port = ptr->backup_replace_port;
856 if (!server->router_conn && !sconn->backup)
857 server->router_conn = sconn;
859 silc_schedule_task_add(server->schedule, 0,
860 silc_server_connect_router,
861 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
862 SILC_TASK_PRI_NORMAL);
867 /* Second part of connecting to router(s). Key exchange protocol has been
868 executed and now we will execute authentication protocol. */
870 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
872 SilcProtocol protocol = (SilcProtocol)context;
873 SilcServerKEInternalContext *ctx =
874 (SilcServerKEInternalContext *)protocol->context;
875 SilcServer server = (SilcServer)ctx->server;
876 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
877 SilcSocketConnection sock = ctx->sock;
878 SilcServerConnAuthInternalContext *proto_ctx;
879 SilcServerConfigRouter *conn = NULL;
881 SILC_LOG_DEBUG(("Start"));
883 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
884 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
885 /* Error occured during protocol */
886 silc_protocol_free(protocol);
887 sock->protocol = NULL;
888 silc_ske_free_key_material(ctx->keymat);
890 silc_packet_context_free(ctx->packet);
892 silc_ske_free(ctx->ske);
893 silc_free(ctx->dest_id);
895 silc_schedule_task_del_by_callback(server->schedule,
896 silc_server_failure_callback);
897 silc_server_disconnect_remote(server, sock,
898 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
900 /* Try reconnecting if configuration wants it */
901 if (!sconn->no_reconnect) {
902 silc_schedule_task_add(server->schedule, 0,
903 silc_server_connect_to_router_retry,
904 sconn, 0, 1, SILC_TASK_TIMEOUT,
905 SILC_TASK_PRI_NORMAL);
908 silc_server_config_unref(&sconn->conn);
909 silc_free(sconn->remote_host);
910 silc_free(sconn->backup_replace_ip);
915 /* We now have the key material as the result of the key exchange
916 protocol. Take the key material into use. Free the raw key material
917 as soon as we've set them into use. */
918 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
919 ctx->sock, ctx->keymat,
920 ctx->ske->prop->cipher,
921 ctx->ske->prop->pkcs,
922 ctx->ske->prop->hash,
923 ctx->ske->prop->hmac,
924 ctx->ske->prop->group,
926 silc_protocol_free(protocol);
927 sock->protocol = NULL;
928 silc_ske_free_key_material(ctx->keymat);
930 silc_packet_context_free(ctx->packet);
932 silc_ske_free(ctx->ske);
933 silc_free(ctx->dest_id);
935 silc_schedule_task_del_by_callback(server->schedule,
936 silc_server_failure_callback);
937 silc_server_disconnect_remote(server, sock,
938 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
940 /* Try reconnecting if configuration wants it */
941 if (!sconn->no_reconnect) {
942 silc_schedule_task_add(server->schedule, 0,
943 silc_server_connect_to_router_retry,
944 sconn, 0, 1, SILC_TASK_TIMEOUT,
945 SILC_TASK_PRI_NORMAL);
948 silc_server_config_unref(&sconn->conn);
949 silc_free(sconn->remote_host);
950 silc_free(sconn->backup_replace_ip);
954 silc_ske_free_key_material(ctx->keymat);
956 /* Allocate internal context for the authentication protocol. This
957 is sent as context for the protocol. */
958 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
959 proto_ctx->server = (void *)server;
960 proto_ctx->context = (void *)sconn;
961 proto_ctx->sock = sock;
962 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
963 proto_ctx->dest_id_type = ctx->dest_id_type;
964 proto_ctx->dest_id = ctx->dest_id;
966 /* Resolve the authentication method used in this connection. Check if
967 we find a match from user configured connections */
968 if (!sconn->conn.ref_ptr)
969 conn = silc_server_config_find_router_conn(server, sock->hostname,
972 conn = sconn->conn.ref_ptr;
975 /* Match found. Use the configured authentication method. Take only
976 the passphrase, since for public key auth we automatically use
977 our local key pair. */
978 if (conn->passphrase) {
979 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
980 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
982 proto_ctx->auth_data = strdup(conn->passphrase);
983 proto_ctx->auth_data_len = strlen(conn->passphrase);
984 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
986 } else if (conn->publickeys) {
987 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
989 proto_ctx->auth_meth = SILC_AUTH_NONE;
992 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
993 sock->hostname, sock->ip, sock->port));
994 silc_protocol_free(protocol);
995 sock->protocol = NULL;
997 silc_packet_context_free(ctx->packet);
999 silc_ske_free(ctx->ske);
1000 silc_free(ctx->dest_id);
1002 silc_server_config_unref(&sconn->conn);
1003 silc_free(sconn->remote_host);
1004 silc_free(sconn->backup_replace_ip);
1006 silc_schedule_task_del_by_callback(server->schedule,
1007 silc_server_failure_callback);
1008 silc_server_disconnect_remote(server, sock,
1009 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1013 /* Free old protocol as it is finished now */
1014 silc_protocol_free(protocol);
1016 silc_packet_context_free(ctx->packet);
1018 sock->protocol = NULL;
1020 /* Allocate the authentication protocol. This is allocated here
1021 but we won't start it yet. We will be receiving party of this
1022 protocol thus we will wait that connecting party will make
1023 their first move. */
1024 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1025 &sock->protocol, proto_ctx,
1026 silc_server_connect_to_router_final);
1028 /* Register timeout task. If the protocol is not executed inside
1029 this timelimit the connection will be terminated. */
1030 proto_ctx->timeout_task =
1031 silc_schedule_task_add(server->schedule, sock->sock,
1032 silc_server_timeout_remote,
1034 server->config->conn_auth_timeout, 0,
1038 /* Run the protocol */
1039 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1042 /* Finalizes the connection to router. Registers a server task to the
1043 queue so that we can accept new connections. */
1045 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1047 SilcProtocol protocol = (SilcProtocol)context;
1048 SilcServerConnAuthInternalContext *ctx =
1049 (SilcServerConnAuthInternalContext *)protocol->context;
1050 SilcServer server = (SilcServer)ctx->server;
1051 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1052 SilcSocketConnection sock = ctx->sock;
1053 SilcServerEntry id_entry;
1055 SilcServerHBContext hb_context;
1056 unsigned char *id_string;
1058 SilcIDListData idata;
1059 SilcServerConfigRouter *conn = NULL;
1060 SilcServerConfigConnParams *param = NULL;
1062 SILC_LOG_DEBUG(("Start"));
1064 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1065 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1066 /* Error occured during protocol */
1067 silc_free(ctx->dest_id);
1068 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1071 /* Try reconnecting if configuration wants it */
1072 if (!sconn->no_reconnect) {
1073 silc_schedule_task_add(server->schedule, 0,
1074 silc_server_connect_to_router_retry,
1075 sconn, 0, 1, SILC_TASK_TIMEOUT,
1076 SILC_TASK_PRI_NORMAL);
1083 /* Add a task to the queue. This task receives new connections to the
1084 server. This task remains on the queue until the end of the program. */
1085 if (!server->listenning && !sconn->backup) {
1086 silc_schedule_task_add(server->schedule, server->sock,
1087 silc_server_accept_new_connection,
1088 (void *)server, 0, 0,
1090 SILC_TASK_PRI_NORMAL);
1091 server->listenning = TRUE;
1094 /* Send NEW_SERVER packet to the router. We will become registered
1095 to the SILC network after sending this packet. */
1096 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1097 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1098 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1099 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1100 silc_buffer_format(packet,
1101 SILC_STR_UI_SHORT(id_len),
1102 SILC_STR_UI_XNSTRING(id_string, id_len),
1103 SILC_STR_UI_SHORT(strlen(server->server_name)),
1104 SILC_STR_UI_XNSTRING(server->server_name,
1105 strlen(server->server_name)),
1108 /* Send the packet */
1109 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1110 packet->data, packet->len, TRUE);
1111 silc_buffer_free(packet);
1112 silc_free(id_string);
1114 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1116 /* Check that we do not have this ID already */
1117 id_entry = silc_idlist_find_server_by_id(server->local_list,
1118 ctx->dest_id, TRUE, NULL);
1120 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1122 id_entry = silc_idlist_find_server_by_id(server->global_list,
1123 ctx->dest_id, TRUE, NULL);
1125 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1128 SILC_LOG_DEBUG(("New server id(%s)",
1129 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1131 /* Add the connected router to global server list */
1132 id_entry = silc_idlist_add_server(server->global_list,
1133 strdup(sock->hostname),
1134 SILC_ROUTER, ctx->dest_id, NULL, sock);
1136 silc_free(ctx->dest_id);
1137 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1138 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1143 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1144 silc_free(sock->user_data);
1145 sock->user_data = (void *)id_entry;
1146 sock->type = SILC_SOCKET_TYPE_ROUTER;
1147 idata = (SilcIDListData)sock->user_data;
1148 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1150 conn = sconn->conn.ref_ptr;
1151 param = &server->config->param;
1152 if (conn && conn->param)
1153 param = conn->param;
1155 /* Perform keepalive. The `hb_context' will be freed automatically
1156 when finally calling the silc_socket_free function. */
1157 hb_context = silc_calloc(1, sizeof(*hb_context));
1158 hb_context->server = server;
1159 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1160 silc_server_perform_heartbeat,
1163 /* Register re-key timeout */
1164 idata->rekey->timeout = param->key_exchange_rekey;
1165 idata->rekey->context = (void *)server;
1166 silc_schedule_task_add(server->schedule, sock->sock,
1167 silc_server_rekey_callback,
1168 (void *)sock, idata->rekey->timeout, 0,
1169 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1171 if (!sconn->backup) {
1172 /* Mark this router our primary router if we're still standalone */
1173 if (server->standalone) {
1174 server->id_entry->router = id_entry;
1175 server->router = id_entry;
1176 server->standalone = FALSE;
1178 /* If we are router then announce our possible servers. */
1179 if (server->server_type == SILC_ROUTER)
1180 silc_server_announce_servers(server, FALSE, 0,
1181 SILC_PRIMARY_ROUTE(server));
1183 /* Announce our clients and channels to the router */
1184 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1185 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1187 /* If we are backup router then this primary router is whom we are
1189 if (server->server_type == SILC_BACKUP_ROUTER)
1190 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1193 /* Add this server to be our backup router */
1194 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1195 sconn->backup_replace_port, FALSE);
1198 sock->protocol = NULL;
1200 /* Call the completion callback to indicate that we've connected to
1202 if (sconn->callback)
1203 (*sconn->callback)(server, id_entry, sconn->callback_context);
1206 /* Free the temporary connection data context */
1208 silc_server_config_unref(&sconn->conn);
1209 silc_free(sconn->remote_host);
1210 silc_free(sconn->backup_replace_ip);
1213 if (sconn == server->router_conn)
1214 server->router_conn = NULL;
1217 /* Free the protocol object */
1218 if (sock->protocol == protocol)
1219 sock->protocol = NULL;
1220 silc_protocol_free(protocol);
1222 silc_packet_context_free(ctx->packet);
1224 silc_ske_free(ctx->ske);
1225 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1226 silc_free(ctx->auth_data);
1230 /* Host lookup callback that is called after the incoming connection's
1231 IP and FQDN lookup is performed. This will actually check the acceptance
1232 of the incoming connection and will register the key exchange protocol
1233 for this connection. */
1236 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1239 SilcServerKEInternalContext *proto_ctx =
1240 (SilcServerKEInternalContext *)context;
1241 SilcServer server = (SilcServer)proto_ctx->server;
1242 SilcServerConfigClient *cconfig = NULL;
1243 SilcServerConfigServer *sconfig = NULL;
1244 SilcServerConfigRouter *rconfig = NULL;
1245 SilcServerConfigDeny *deny;
1248 context = (void *)server;
1250 /* Check whether we could resolve both IP and FQDN. */
1251 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1252 server->config->require_reverse_lookup)) {
1253 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1254 sock->hostname ? sock->hostname :
1255 sock->ip ? sock->ip : ""));
1256 server->stat.conn_failures++;
1257 silc_server_disconnect_remote(server, sock,
1258 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1259 "Unknown host or IP");
1260 silc_free(proto_ctx);
1264 /* Register the connection for network input and output. This sets
1265 that scheduler will listen for incoming packets for this connection
1266 and sets that outgoing packets may be sent to this connection as well.
1267 However, this doesn't set the scheduler for outgoing traffic, it
1268 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1269 later when outgoing data is available. */
1270 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1272 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1275 /* Listenning port */
1276 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1277 silc_server_disconnect_remote(server, sock,
1278 SILC_STATUS_ERR_RESOURCE_LIMIT,
1279 "Connection refused");
1280 server->stat.conn_failures++;
1281 silc_free(proto_ctx);
1284 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1286 /* Check whether this connection is denied to connect to us. */
1287 deny = silc_server_config_find_denied(server, sock->ip);
1289 deny = silc_server_config_find_denied(server, sock->hostname);
1291 /* The connection is denied */
1292 SILC_LOG_INFO(("Connection %s (%s) is denied",
1293 sock->hostname, sock->ip));
1294 silc_server_disconnect_remote(server, sock,
1295 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1297 server->stat.conn_failures++;
1298 silc_free(proto_ctx);
1302 /* Check whether we have configured this sort of connection at all. We
1303 have to check all configurations since we don't know what type of
1304 connection this is. */
1305 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1306 cconfig = silc_server_config_find_client(server, sock->hostname);
1307 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1308 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1309 if (server->server_type == SILC_ROUTER) {
1310 if (!(rconfig = silc_server_config_find_router_conn(server,
1311 sock->ip, sock->port)))
1312 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1315 if (!cconfig && !sconfig && !rconfig) {
1316 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1318 silc_server_disconnect_remote(server, sock,
1319 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1320 server->stat.conn_failures++;
1321 silc_free(proto_ctx);
1325 /* The connection is allowed */
1327 /* Set internal context for key exchange protocol. This is
1328 sent as context for the protocol. */
1329 proto_ctx->sock = sock;
1330 proto_ctx->rng = server->rng;
1331 proto_ctx->responder = TRUE;
1332 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1333 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1334 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1336 /* Take flags for key exchange. Since we do not know what type of connection
1337 this is, we go through all found configurations and use the global ones
1338 as well. This will result always into strictest key exchange flags. */
1339 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1340 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1341 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1342 if (server->config->param.key_exchange_pfs)
1343 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1345 /* Prepare the connection for key exchange protocol. We allocate the
1346 protocol but will not start it yet. The connector will be the
1347 initiator of the protocol thus we will wait for initiation from
1348 there before we start the protocol. */
1349 server->stat.auth_attempts++;
1350 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1351 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1352 &sock->protocol, proto_ctx,
1353 silc_server_accept_new_connection_second);
1355 /* Register a timeout task that will be executed if the connector
1356 will not start the key exchange protocol within specified timeout
1357 and the connection will be closed. */
1358 proto_ctx->timeout_task =
1359 silc_schedule_task_add(server->schedule, sock->sock,
1360 silc_server_timeout_remote,
1362 server->config->key_exchange_timeout, 0,
1367 /* Accepts new connections to the server. Accepting new connections are
1368 done in three parts to make it async. */
1370 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1372 SilcServer server = (SilcServer)context;
1373 SilcSocketConnection newsocket;
1374 SilcServerKEInternalContext *proto_ctx;
1377 SILC_LOG_DEBUG(("Accepting new connection"));
1379 server->stat.conn_attempts++;
1381 sock = silc_net_accept_connection(fd);
1383 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1384 server->stat.conn_failures++;
1388 /* Check for maximum allowed connections */
1389 if (sock > server->config->param.connections_max) {
1390 SILC_LOG_ERROR(("Refusing connection, server is full"));
1391 server->stat.conn_failures++;
1392 silc_net_close_connection(sock);
1396 /* Set socket options */
1397 silc_net_set_socket_nonblock(sock);
1398 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1400 /* We don't create a ID yet, since we don't know what type of connection
1401 this is yet. But, we do add the connection to the socket table. */
1402 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1403 server->sockets[sock] = newsocket;
1405 /* Perform asynchronous host lookup. This will lookup the IP and the
1406 FQDN of the remote connection. After the lookup is done the connection
1407 is accepted further. */
1408 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1409 proto_ctx->server = server;
1410 proto_ctx->context = (void *)fd;
1411 silc_socket_host_lookup(newsocket, TRUE,
1412 silc_server_accept_new_connection_lookup,
1413 (void *)proto_ctx, server->schedule);
1416 /* Second part of accepting new connection. Key exchange protocol has been
1417 performed and now it is time to do little connection authentication
1418 protocol to figure out whether this connection is client or server
1419 and whether it has right to access this server (especially server
1420 connections needs to be authenticated). */
1422 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1424 SilcProtocol protocol = (SilcProtocol)context;
1425 SilcServerKEInternalContext *ctx =
1426 (SilcServerKEInternalContext *)protocol->context;
1427 SilcServer server = (SilcServer)ctx->server;
1428 SilcSocketConnection sock = ctx->sock;
1429 SilcServerConnAuthInternalContext *proto_ctx;
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_LOG_DEBUG(("Error key exchange protocol"));
1437 silc_protocol_free(protocol);
1438 sock->protocol = NULL;
1439 silc_ske_free_key_material(ctx->keymat);
1441 silc_packet_context_free(ctx->packet);
1443 silc_ske_free(ctx->ske);
1444 silc_free(ctx->dest_id);
1445 silc_server_config_unref(&ctx->cconfig);
1446 silc_server_config_unref(&ctx->sconfig);
1447 silc_server_config_unref(&ctx->rconfig);
1449 silc_schedule_task_del_by_callback(server->schedule,
1450 silc_server_failure_callback);
1451 silc_server_disconnect_remote(server, sock,
1452 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1454 server->stat.auth_failures++;
1458 /* We now have the key material as the result of the key exchange
1459 protocol. Take the key material into use. Free the raw key material
1460 as soon as we've set them into use. */
1461 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1462 ctx->sock, ctx->keymat,
1463 ctx->ske->prop->cipher,
1464 ctx->ske->prop->pkcs,
1465 ctx->ske->prop->hash,
1466 ctx->ske->prop->hmac,
1467 ctx->ske->prop->group,
1469 SILC_LOG_ERROR(("Error setting key material in use"));
1470 silc_protocol_free(protocol);
1471 sock->protocol = NULL;
1472 silc_ske_free_key_material(ctx->keymat);
1474 silc_packet_context_free(ctx->packet);
1476 silc_ske_free(ctx->ske);
1477 silc_free(ctx->dest_id);
1478 silc_server_config_unref(&ctx->cconfig);
1479 silc_server_config_unref(&ctx->sconfig);
1480 silc_server_config_unref(&ctx->rconfig);
1482 silc_schedule_task_del_by_callback(server->schedule,
1483 silc_server_failure_callback);
1484 silc_server_disconnect_remote(server, sock,
1485 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1486 server->stat.auth_failures++;
1489 silc_ske_free_key_material(ctx->keymat);
1491 /* Allocate internal context for the authentication protocol. This
1492 is sent as context for the protocol. */
1493 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1494 proto_ctx->server = (void *)server;
1495 proto_ctx->sock = sock;
1496 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1497 proto_ctx->responder = TRUE;
1498 proto_ctx->dest_id_type = ctx->dest_id_type;
1499 proto_ctx->dest_id = ctx->dest_id;
1500 proto_ctx->cconfig = ctx->cconfig;
1501 proto_ctx->sconfig = ctx->sconfig;
1502 proto_ctx->rconfig = ctx->rconfig;
1504 /* Free old protocol as it is finished now */
1505 silc_protocol_free(protocol);
1507 silc_packet_context_free(ctx->packet);
1509 sock->protocol = NULL;
1511 /* Allocate the authentication protocol. This is allocated here
1512 but we won't start it yet. We will be receiving party of this
1513 protocol thus we will wait that connecting party will make
1514 their first move. */
1515 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1516 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1517 &sock->protocol, proto_ctx,
1518 silc_server_accept_new_connection_final);
1520 /* Register timeout task. If the protocol is not executed inside
1521 this timelimit the connection will be terminated. */
1522 proto_ctx->timeout_task =
1523 silc_schedule_task_add(server->schedule, sock->sock,
1524 silc_server_timeout_remote,
1526 server->config->conn_auth_timeout, 0,
1531 /* Final part of accepting new connection. The connection has now
1532 been authenticated and keys has been exchanged. We also know whether
1533 this is client or server connection. */
1535 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1537 SilcProtocol protocol = (SilcProtocol)context;
1538 SilcServerConnAuthInternalContext *ctx =
1539 (SilcServerConnAuthInternalContext *)protocol->context;
1540 SilcServer server = (SilcServer)ctx->server;
1541 SilcSocketConnection sock = ctx->sock;
1542 SilcServerHBContext hb_context;
1543 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1545 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1547 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1548 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1549 /* Error occured during protocol */
1550 SILC_LOG_DEBUG(("Error during authentication protocol"));
1551 silc_protocol_free(protocol);
1552 sock->protocol = NULL;
1554 silc_packet_context_free(ctx->packet);
1556 silc_ske_free(ctx->ske);
1557 silc_free(ctx->dest_id);
1558 silc_server_config_unref(&ctx->cconfig);
1559 silc_server_config_unref(&ctx->sconfig);
1560 silc_server_config_unref(&ctx->rconfig);
1562 silc_schedule_task_del_by_callback(server->schedule,
1563 silc_server_failure_callback);
1564 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1566 server->stat.auth_failures++;
1570 entry->data.last_receive = time(NULL);
1572 switch (ctx->conn_type) {
1573 case SILC_SOCKET_TYPE_CLIENT:
1575 SilcClientEntry client;
1576 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1578 /* Verify whether this connection is after all allowed to connect */
1579 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1580 &server->config->param,
1581 conn->param, ctx->ske)) {
1582 server->stat.auth_failures++;
1586 SILC_LOG_DEBUG(("Remote host is client"));
1587 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1590 /* Add the client to the client ID cache. The nickname and Client ID
1591 and other information is created after we have received NEW_CLIENT
1592 packet from client. */
1593 client = silc_idlist_add_client(server->local_list,
1594 NULL, NULL, NULL, NULL, NULL, sock, 0);
1596 SILC_LOG_ERROR(("Could not add new client to cache"));
1597 silc_free(sock->user_data);
1598 silc_server_disconnect_remote(server, sock,
1599 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1600 server->stat.auth_failures++;
1603 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1606 server->stat.my_clients++;
1607 server->stat.clients++;
1608 server->stat.cell_clients++;
1610 /* Get connection parameters */
1612 if (conn->param->keepalive_secs)
1613 hearbeat_timeout = conn->param->keepalive_secs;
1616 id_entry = (void *)client;
1619 case SILC_SOCKET_TYPE_SERVER:
1620 case SILC_SOCKET_TYPE_ROUTER:
1622 SilcServerEntry new_server;
1623 bool initiator = FALSE;
1624 bool backup_local = FALSE;
1625 bool backup_router = FALSE;
1626 char *backup_replace_ip = NULL;
1627 SilcUInt16 backup_replace_port = 0;
1628 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1629 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1631 /* If we are backup router and this is incoming server connection
1632 and we do not have connection to primary router, do not allow
1634 if (server->server_type == SILC_BACKUP_ROUTER &&
1635 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1636 !SILC_PRIMARY_ROUTE(server)) {
1637 SILC_LOG_INFO(("Will not accept server connection because we do "
1638 "not have primary router connection established"));
1639 silc_server_disconnect_remote(server, sock,
1640 SILC_STATUS_ERR_PERM_DENIED,
1641 "We do not have connection to primary "
1642 "router established, try later");
1643 silc_free(sock->user_data);
1644 server->stat.auth_failures++;
1648 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1649 /* Verify whether this connection is after all allowed to connect */
1650 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1651 &server->config->param,
1652 rconn ? rconn->param : NULL,
1654 silc_free(sock->user_data);
1655 server->stat.auth_failures++;
1661 if (rconn->param->keepalive_secs)
1662 hearbeat_timeout = rconn->param->keepalive_secs;
1665 initiator = rconn->initiator;
1666 backup_local = rconn->backup_local;
1667 backup_router = rconn->backup_router;
1668 backup_replace_ip = rconn->backup_replace_ip;
1669 backup_replace_port = rconn->backup_replace_port;
1673 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1674 /* Verify whether this connection is after all allowed to connect */
1675 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1676 &server->config->param,
1677 sconn ? sconn->param : NULL,
1679 silc_free(sock->user_data);
1680 server->stat.auth_failures++;
1685 if (sconn->param->keepalive_secs)
1686 hearbeat_timeout = sconn->param->keepalive_secs;
1689 backup_router = sconn->backup_router;
1693 SILC_LOG_DEBUG(("Remote host is %s",
1694 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1695 "server" : (backup_router ?
1696 "backup router" : "router")));
1697 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1698 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1699 "server" : (backup_router ?
1700 "backup router" : "router")));
1702 /* Add the server into server cache. The server name and Server ID
1703 is updated after we have received NEW_SERVER packet from the
1704 server. We mark ourselves as router for this server if we really
1707 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1708 server->local_list : (backup_router ?
1709 server->local_list :
1710 server->global_list)),
1712 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1713 SILC_SERVER : SILC_ROUTER),
1715 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1716 server->id_entry : (backup_router ?
1717 server->id_entry : NULL)),
1720 SILC_LOG_ERROR(("Could not add new server to cache"));
1721 silc_free(sock->user_data);
1722 silc_server_disconnect_remote(server, sock,
1723 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1724 server->stat.auth_failures++;
1727 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1729 id_entry = (void *)new_server;
1731 /* If the incoming connection is router and marked as backup router
1732 then add it to be one of our backups */
1733 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1734 silc_server_backup_add(server, new_server, backup_replace_ip,
1735 backup_replace_port, backup_local);
1737 /* Change it back to SERVER type since that's what it really is. */
1739 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1741 new_server->server_type = SILC_BACKUP_ROUTER;
1745 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1746 server->stat.my_servers++;
1748 server->stat.my_routers++;
1749 server->stat.routers++;
1751 server->stat.servers++;
1753 /* Check whether this connection is to be our primary router connection
1754 if we do not already have the primary route. */
1755 if (!backup_router &&
1756 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1757 if (silc_server_config_is_primary_route(server) && !initiator)
1760 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1761 server->standalone = FALSE;
1762 if (!server->id_entry->router) {
1763 server->id_entry->router = id_entry;
1764 server->router = id_entry;
1775 sock->type = ctx->conn_type;
1777 /* Add the common data structure to the ID entry. */
1778 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1780 /* Add to sockets internal pointer for fast referencing */
1781 silc_free(sock->user_data);
1782 sock->user_data = id_entry;
1784 /* Connection has been fully established now. Everything is ok. */
1785 SILC_LOG_DEBUG(("New connection authenticated"));
1787 /* Perform keepalive. The `hb_context' will be freed automatically
1788 when finally calling the silc_socket_free function. */
1789 hb_context = silc_calloc(1, sizeof(*hb_context));
1790 hb_context->server = server;
1791 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1792 silc_server_perform_heartbeat,
1796 silc_schedule_task_del_by_callback(server->schedule,
1797 silc_server_failure_callback);
1798 silc_protocol_free(protocol);
1800 silc_packet_context_free(ctx->packet);
1802 silc_ske_free(ctx->ske);
1803 silc_free(ctx->dest_id);
1804 silc_server_config_unref(&ctx->cconfig);
1805 silc_server_config_unref(&ctx->sconfig);
1806 silc_server_config_unref(&ctx->rconfig);
1808 sock->protocol = NULL;
1811 /* This function is used to read packets from network and send packets to
1812 network. This is usually a generic task. */
1814 SILC_TASK_CALLBACK(silc_server_packet_process)
1816 SilcServer server = (SilcServer)context;
1817 SilcSocketConnection sock = server->sockets[fd];
1818 SilcIDListData idata;
1819 SilcCipher cipher = NULL;
1820 SilcHmac hmac = NULL;
1821 SilcUInt32 sequence = 0;
1825 SILC_LOG_DEBUG(("Unknown socket connection"));
1829 /* Packet sending */
1831 if (type == SILC_TASK_WRITE) {
1832 /* Do not send data to disconnected connection */
1833 if (SILC_IS_DISCONNECTED(sock)) {
1834 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
1838 server->stat.packets_sent++;
1840 /* Send the packet */
1841 ret = silc_packet_send(sock, TRUE);
1843 /* If returned -2 could not write to connection now, will do
1849 SILC_LOG_ERROR(("Error sending packet to connection "
1850 "%s:%d [%s]", sock->hostname, sock->port,
1851 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1852 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1853 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1858 /* The packet has been sent and now it is time to set the connection
1859 back to only for input. When there is again some outgoing data
1860 available for this connection it will be set for output as well.
1861 This call clears the output setting and sets it only for input. */
1862 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1863 SILC_UNSET_OUTBUF_PENDING(sock);
1865 silc_buffer_clear(sock->outbuf);
1869 /* Packet receiving */
1871 /* Read some data from connection */
1872 ret = silc_packet_receive(sock);
1876 SILC_LOG_ERROR(("Error receiving packet from connection "
1877 "%s:%d [%s] %s", sock->hostname, sock->port,
1878 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1879 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1880 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1881 "Router"), strerror(errno)));
1887 SILC_LOG_DEBUG(("Read EOF"));
1889 /* If connection is disconnecting already we will finally
1890 close the connection */
1891 if (SILC_IS_DISCONNECTING(sock)) {
1892 if (sock->user_data)
1893 silc_server_free_sock_user_data(server, sock, NULL);
1894 silc_server_close_connection(server, sock);
1898 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1899 SILC_SET_DISCONNECTING(sock);
1901 if (sock->user_data) {
1903 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1904 silc_server_free_sock_user_data(server, sock, tmp);
1906 silc_server_free_sock_user_data(server, sock, NULL);
1907 } else if (server->router_conn && server->router_conn->sock == sock &&
1908 !server->router && server->standalone)
1909 silc_schedule_task_add(server->schedule, 0,
1910 silc_server_connect_to_router,
1913 SILC_TASK_PRI_NORMAL);
1915 silc_server_close_connection(server, sock);
1919 /* If connection is disconnecting or disconnected we will ignore
1921 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1922 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1926 /* Get keys and stuff from ID entry */
1927 idata = (SilcIDListData)sock->user_data;
1929 cipher = idata->receive_key;
1930 hmac = idata->hmac_receive;
1931 sequence = idata->psn_receive;
1934 /* Process the packet. This will call the parser that will then
1935 decrypt and parse the packet. */
1936 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1937 TRUE : FALSE, cipher, hmac, sequence,
1938 silc_server_packet_parse, server);
1940 /* If this socket connection is not authenticated yet and the packet
1941 processing failed we will drop the connection since it can be
1942 a malicious flooder. */
1943 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1944 (!sock->protocol || sock->protocol->protocol->type ==
1945 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1946 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1947 SILC_SET_DISCONNECTING(sock);
1949 if (sock->user_data)
1950 silc_server_free_sock_user_data(server, sock, NULL);
1951 silc_server_close_connection(server, sock);
1955 /* Parses whole packet, received earlier. */
1957 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1959 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1960 SilcServer server = (SilcServer)parse_ctx->context;
1961 SilcSocketConnection sock = parse_ctx->sock;
1962 SilcPacketContext *packet = parse_ctx->packet;
1963 SilcIDListData idata = (SilcIDListData)sock->user_data;
1966 server->stat.packets_received++;
1968 /* Parse the packet */
1969 if (parse_ctx->normal)
1970 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1972 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1974 /* If entry is disabled ignore what we got. */
1975 if (ret != SILC_PACKET_RESUME_ROUTER &&
1976 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1977 SILC_LOG_DEBUG(("Connection is disabled"));
1981 if (ret == SILC_PACKET_NONE) {
1982 SILC_LOG_DEBUG(("Error parsing packet"));
1986 /* Check that the the current client ID is same as in the client's packet. */
1987 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1988 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1989 if (client && client->id) {
1990 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1991 packet->src_id_type);
1992 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1994 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2001 if (server->server_type == SILC_ROUTER) {
2002 /* Route the packet if it is not destined to us. Other ID types but
2003 server are handled separately after processing them. */
2004 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2005 packet->dst_id_type == SILC_ID_SERVER &&
2006 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2007 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2009 /* Route the packet to fastest route for the destination ID */
2010 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2011 packet->dst_id_type);
2014 silc_server_packet_route(server,
2015 silc_server_route_get(server, id,
2016 packet->dst_id_type),
2023 /* Parse the incoming packet type */
2024 silc_server_packet_parse_type(server, sock, packet);
2026 /* Broadcast packet if it is marked as broadcast packet and it is
2027 originated from router and we are router. */
2028 if (server->server_type == SILC_ROUTER &&
2029 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2030 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2031 /* Broadcast to our primary route */
2032 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2034 /* If we have backup routers then we need to feed all broadcast
2035 data to those servers. */
2036 silc_server_backup_broadcast(server, sock, packet);
2040 silc_packet_context_free(packet);
2041 silc_free(parse_ctx);
2044 /* Parser callback called by silc_packet_receive_process. This merely
2045 registers timeout that will handle the actual parsing when appropriate. */
2047 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2050 SilcServer server = (SilcServer)context;
2051 SilcSocketConnection sock = parser_context->sock;
2052 SilcIDListData idata = (SilcIDListData)sock->user_data;
2055 idata->psn_receive = parser_context->packet->sequence + 1;
2057 /* If protocol for this connection is key exchange or rekey then we'll
2058 process all packets synchronously, since there might be packets in
2059 queue that we are not able to decrypt without first processing the
2060 packets before them. */
2061 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2062 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2063 (sock->protocol && sock->protocol->protocol &&
2064 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2065 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2066 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2069 /* Reprocess data since we'll return FALSE here. This is because
2070 the idata->receive_key might have become valid in the last packet
2071 and we want to call this processor with valid cipher. */
2073 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2074 TRUE : FALSE, idata->receive_key,
2075 idata->hmac_receive, idata->psn_receive,
2076 silc_server_packet_parse, server);
2078 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2079 TRUE : FALSE, NULL, NULL, 0,
2080 silc_server_packet_parse, server);
2084 switch (sock->type) {
2085 case SILC_SOCKET_TYPE_UNKNOWN:
2086 case SILC_SOCKET_TYPE_CLIENT:
2087 /* Parse the packet with timeout */
2088 silc_schedule_task_add(server->schedule, sock->sock,
2089 silc_server_packet_parse_real,
2090 (void *)parser_context, 0, 100000,
2092 SILC_TASK_PRI_NORMAL);
2094 case SILC_SOCKET_TYPE_SERVER:
2095 case SILC_SOCKET_TYPE_ROUTER:
2096 /* Packets from servers are parsed immediately */
2097 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2107 /* Parses the packet type and calls what ever routines the packet type
2108 requires. This is done for all incoming packets. */
2110 void silc_server_packet_parse_type(SilcServer server,
2111 SilcSocketConnection sock,
2112 SilcPacketContext *packet)
2114 SilcPacketType type = packet->type;
2115 SilcIDListData idata = (SilcIDListData)sock->user_data;
2117 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2118 silc_get_packet_name(type), packet->flags));
2120 /* Parse the packet type */
2122 case SILC_PACKET_DISCONNECT:
2125 char *message = NULL;
2127 if (packet->flags & SILC_PACKET_FLAG_LIST)
2129 if (packet->buffer->len < 1)
2132 status = (SilcStatus)packet->buffer->data[0];
2133 if (packet->buffer->len > 1 &&
2134 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2135 message = silc_memdup(packet->buffer->data + 1,
2136 packet->buffer->len - 1);
2138 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2139 sock->ip, sock->hostname,
2140 silc_get_status_message(status), status,
2141 message ? message : ""));
2146 case SILC_PACKET_SUCCESS:
2148 * Success received for something. For now we can have only
2149 * one protocol for connection executing at once hence this
2150 * success message is for whatever protocol is executing currently.
2152 if (packet->flags & SILC_PACKET_FLAG_LIST)
2155 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2158 case SILC_PACKET_FAILURE:
2160 * Failure received for something. For now we can have only
2161 * one protocol for connection executing at once hence this
2162 * failure message is for whatever protocol is executing currently.
2164 if (packet->flags & SILC_PACKET_FLAG_LIST)
2166 if (sock->protocol) {
2167 SilcServerFailureContext f;
2168 f = silc_calloc(1, sizeof(*f));
2172 /* We will wait 5 seconds to process this failure packet */
2173 silc_schedule_task_add(server->schedule, sock->sock,
2174 silc_server_failure_callback, (void *)f, 5, 0,
2175 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2179 case SILC_PACKET_REJECT:
2180 if (packet->flags & SILC_PACKET_FLAG_LIST)
2185 case SILC_PACKET_NOTIFY:
2187 * Received notify packet. Server can receive notify packets from
2188 * router. Server then relays the notify messages to clients if needed.
2190 if (packet->flags & SILC_PACKET_FLAG_LIST)
2191 silc_server_notify_list(server, sock, packet);
2193 silc_server_notify(server, sock, packet);
2199 case SILC_PACKET_CHANNEL_MESSAGE:
2201 * Received channel message. Channel messages are special packets
2202 * (although probably most common ones) thus they are handled
2205 if (packet->flags & SILC_PACKET_FLAG_LIST)
2207 idata->last_receive = time(NULL);
2208 silc_server_channel_message(server, sock, packet);
2211 case SILC_PACKET_CHANNEL_KEY:
2213 * Received key for channel. As channels are created by the router
2214 * the keys are as well. We will distribute the key to all of our
2215 * locally connected clients on the particular channel. Router
2216 * never receives this channel and thus is ignored.
2218 if (packet->flags & SILC_PACKET_FLAG_LIST)
2220 silc_server_channel_key(server, sock, packet);
2226 case SILC_PACKET_COMMAND:
2228 * Recived command. Processes the command request and allocates the
2229 * command context and calls the command.
2231 if (packet->flags & SILC_PACKET_FLAG_LIST)
2233 silc_server_command_process(server, sock, packet);
2236 case SILC_PACKET_COMMAND_REPLY:
2238 * Received command reply packet. Received command reply to command. It
2239 * may be reply to command sent by us or reply to command sent by client
2240 * that we've routed further.
2242 if (packet->flags & SILC_PACKET_FLAG_LIST)
2244 silc_server_command_reply(server, sock, packet);
2248 * Private Message packets
2250 case SILC_PACKET_PRIVATE_MESSAGE:
2252 * Received private message packet. The packet is coming from either
2255 if (packet->flags & SILC_PACKET_FLAG_LIST)
2257 idata->last_receive = time(NULL);
2258 silc_server_private_message(server, sock, packet);
2261 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2263 * Private message key packet.
2265 if (packet->flags & SILC_PACKET_FLAG_LIST)
2267 silc_server_private_message_key(server, sock, packet);
2271 * Key Exchange protocol packets
2273 case SILC_PACKET_KEY_EXCHANGE:
2274 if (packet->flags & SILC_PACKET_FLAG_LIST)
2277 if (sock->protocol && sock->protocol->protocol &&
2278 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2279 SilcServerKEInternalContext *proto_ctx =
2280 (SilcServerKEInternalContext *)sock->protocol->context;
2282 proto_ctx->packet = silc_packet_context_dup(packet);
2284 /* Let the protocol handle the packet */
2285 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2287 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2288 "protocol active, packet dropped."));
2292 case SILC_PACKET_KEY_EXCHANGE_1:
2293 if (packet->flags & SILC_PACKET_FLAG_LIST)
2296 if (sock->protocol && sock->protocol->protocol &&
2297 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2298 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2300 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2301 SilcServerRekeyInternalContext *proto_ctx =
2302 (SilcServerRekeyInternalContext *)sock->protocol->context;
2304 if (proto_ctx->packet)
2305 silc_packet_context_free(proto_ctx->packet);
2307 proto_ctx->packet = silc_packet_context_dup(packet);
2309 /* Let the protocol handle the packet */
2310 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2312 SilcServerKEInternalContext *proto_ctx =
2313 (SilcServerKEInternalContext *)sock->protocol->context;
2315 if (proto_ctx->packet)
2316 silc_packet_context_free(proto_ctx->packet);
2318 proto_ctx->packet = silc_packet_context_dup(packet);
2319 proto_ctx->dest_id_type = packet->src_id_type;
2320 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2321 packet->src_id_type);
2322 if (!proto_ctx->dest_id)
2325 /* Let the protocol handle the packet */
2326 silc_protocol_execute(sock->protocol, server->schedule,
2330 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2331 "protocol active, packet dropped."));
2335 case SILC_PACKET_KEY_EXCHANGE_2:
2336 if (packet->flags & SILC_PACKET_FLAG_LIST)
2339 if (sock->protocol && sock->protocol->protocol &&
2340 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2341 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2343 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2344 SilcServerRekeyInternalContext *proto_ctx =
2345 (SilcServerRekeyInternalContext *)sock->protocol->context;
2347 if (proto_ctx->packet)
2348 silc_packet_context_free(proto_ctx->packet);
2350 proto_ctx->packet = silc_packet_context_dup(packet);
2352 /* Let the protocol handle the packet */
2353 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2355 SilcServerKEInternalContext *proto_ctx =
2356 (SilcServerKEInternalContext *)sock->protocol->context;
2358 if (proto_ctx->packet)
2359 silc_packet_context_free(proto_ctx->packet);
2361 proto_ctx->packet = silc_packet_context_dup(packet);
2362 proto_ctx->dest_id_type = packet->src_id_type;
2363 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2364 packet->src_id_type);
2365 if (!proto_ctx->dest_id)
2368 /* Let the protocol handle the packet */
2369 silc_protocol_execute(sock->protocol, server->schedule,
2373 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2374 "protocol active, packet dropped."));
2378 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2380 * Connection authentication request packet. When we receive this packet
2381 * we will send to the other end information about our mandatory
2382 * authentication method for the connection. This packet maybe received
2385 if (packet->flags & SILC_PACKET_FLAG_LIST)
2387 silc_server_connection_auth_request(server, sock, packet);
2391 * Connection Authentication protocol packets
2393 case SILC_PACKET_CONNECTION_AUTH:
2394 /* Start of the authentication protocol. We receive here the
2395 authentication data and will verify it. */
2396 if (packet->flags & SILC_PACKET_FLAG_LIST)
2399 if (sock->protocol && sock->protocol->protocol->type
2400 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2402 SilcServerConnAuthInternalContext *proto_ctx =
2403 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2405 proto_ctx->packet = silc_packet_context_dup(packet);
2407 /* Let the protocol handle the packet */
2408 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2410 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2411 "protocol active, packet dropped."));
2415 case SILC_PACKET_NEW_ID:
2417 * Received New ID packet. This includes some new ID that has been
2418 * created. It may be for client, server or channel. This is the way
2419 * to distribute information about new registered entities in the
2422 if (packet->flags & SILC_PACKET_FLAG_LIST)
2423 silc_server_new_id_list(server, sock, packet);
2425 silc_server_new_id(server, sock, packet);
2428 case SILC_PACKET_NEW_CLIENT:
2430 * Received new client packet. This includes client information that
2431 * we will use to create initial client ID. After creating new
2432 * ID we will send it to the client.
2434 if (packet->flags & SILC_PACKET_FLAG_LIST)
2436 silc_server_new_client(server, sock, packet);
2439 case SILC_PACKET_NEW_SERVER:
2441 * Received new server packet. This includes Server ID and some other
2442 * information that we may save. This is received after server has
2445 if (packet->flags & SILC_PACKET_FLAG_LIST)
2447 silc_server_new_server(server, sock, packet);
2450 case SILC_PACKET_NEW_CHANNEL:
2452 * Received new channel packet. Information about new channel in the
2453 * network are distributed using this packet.
2455 if (packet->flags & SILC_PACKET_FLAG_LIST)
2456 silc_server_new_channel_list(server, sock, packet);
2458 silc_server_new_channel(server, sock, packet);
2461 case SILC_PACKET_HEARTBEAT:
2463 * Received heartbeat.
2465 if (packet->flags & SILC_PACKET_FLAG_LIST)
2469 case SILC_PACKET_KEY_AGREEMENT:
2471 * Received heartbeat.
2473 if (packet->flags & SILC_PACKET_FLAG_LIST)
2475 silc_server_key_agreement(server, sock, packet);
2478 case SILC_PACKET_REKEY:
2480 * Received re-key packet. The sender wants to regenerate the session
2483 if (packet->flags & SILC_PACKET_FLAG_LIST)
2485 silc_server_rekey(server, sock, packet);
2488 case SILC_PACKET_REKEY_DONE:
2490 * The re-key is done.
2492 if (packet->flags & SILC_PACKET_FLAG_LIST)
2495 if (sock->protocol && sock->protocol->protocol &&
2496 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2498 SilcServerRekeyInternalContext *proto_ctx =
2499 (SilcServerRekeyInternalContext *)sock->protocol->context;
2501 if (proto_ctx->packet)
2502 silc_packet_context_free(proto_ctx->packet);
2504 proto_ctx->packet = silc_packet_context_dup(packet);
2506 /* Let the protocol handle the packet */
2507 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2509 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2510 "protocol active, packet dropped."));
2514 case SILC_PACKET_FTP:
2516 if (packet->flags & SILC_PACKET_FLAG_LIST)
2518 silc_server_ftp(server, sock, packet);
2521 case SILC_PACKET_RESUME_CLIENT:
2523 if (packet->flags & SILC_PACKET_FLAG_LIST)
2525 silc_server_resume_client(server, sock, packet);
2528 case SILC_PACKET_RESUME_ROUTER:
2529 /* Resume router packet received. This packet is received for backup
2530 router resuming protocol. */
2531 if (packet->flags & SILC_PACKET_FLAG_LIST)
2533 silc_server_backup_resume_router(server, sock, packet);
2537 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2542 /* Creates connection to a remote router. */
2544 void silc_server_create_connection(SilcServer server,
2545 const char *remote_host, SilcUInt32 port)
2547 SilcServerConnection sconn;
2549 /* Allocate connection object for hold connection specific stuff. */
2550 sconn = silc_calloc(1, sizeof(*sconn));
2551 sconn->server = server;
2552 sconn->remote_host = strdup(remote_host);
2553 sconn->remote_port = port;
2554 sconn->no_reconnect = TRUE;
2556 silc_schedule_task_add(server->schedule, 0,
2557 silc_server_connect_router,
2558 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2559 SILC_TASK_PRI_NORMAL);
2562 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2564 silc_socket_free(context);
2567 /* Closes connection to socket connection */
2569 void silc_server_close_connection(SilcServer server,
2570 SilcSocketConnection sock)
2572 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2573 silc_socket_free(sock);
2577 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2579 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2580 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2581 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2584 /* We won't listen for this connection anymore */
2585 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2587 /* Unregister all tasks */
2588 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2590 /* Close the actual connection */
2591 silc_net_close_connection(sock->sock);
2592 server->sockets[sock->sock] = NULL;
2594 /* If sock->user_data is NULL then we'll check for active protocols
2595 here since the silc_server_free_sock_user_data has not been called
2596 for this connection. */
2597 if (!sock->user_data) {
2598 /* If any protocol is active cancel its execution. It will call
2599 the final callback which will finalize the disconnection. */
2600 if (sock->protocol) {
2601 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2602 silc_protocol_cancel(sock->protocol, server->schedule);
2603 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2604 silc_protocol_execute_final(sock->protocol, server->schedule);
2605 sock->protocol = NULL;
2610 silc_schedule_task_add(server->schedule, 0,
2611 silc_server_close_connection_final,
2612 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2613 SILC_TASK_PRI_NORMAL);
2616 /* Sends disconnect message to remote connection and disconnects the
2619 void silc_server_disconnect_remote(SilcServer server,
2620 SilcSocketConnection sock,
2621 SilcStatus status, ...)
2624 unsigned char buf[512];
2632 memset(buf, 0, sizeof(buf));
2633 va_start(ap, status);
2634 cp = va_arg(ap, char *);
2636 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2641 SILC_LOG_DEBUG(("Disconnecting remote host"));
2643 /* Notify remote end that the conversation is over. The notify message
2644 is tried to be sent immediately. */
2648 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2650 buffer = silc_buffer_alloc_size(len);
2654 buffer->data[0] = status;
2656 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2658 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2659 buffer->data, buffer->len, TRUE);
2660 silc_buffer_free(buffer);
2663 silc_server_packet_queue_purge(server, sock);
2665 /* Mark the connection to be disconnected */
2666 SILC_SET_DISCONNECTED(sock);
2667 silc_server_close_connection(server, sock);
2672 SilcClientEntry client;
2673 } *FreeClientInternal;
2675 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2677 FreeClientInternal i = (FreeClientInternal)context;
2679 silc_idlist_del_data(i->client);
2680 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2684 /* Frees client data and notifies about client's signoff. */
2686 void silc_server_free_client_data(SilcServer server,
2687 SilcSocketConnection sock,
2688 SilcClientEntry client,
2690 const char *signoff)
2692 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2694 SILC_LOG_DEBUG(("Freeing client data"));
2697 if (!client->router && !client->connection &&
2698 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2699 SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2700 SILC_LOG_ERROR(("****** Contact Pekka"));
2701 SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2706 /* If there is pending outgoing data for the client then purge it
2707 to the network before removing the client entry. */
2708 silc_server_packet_queue_purge(server, sock);
2711 /* Check if anyone is watching this nickname */
2712 if (server->server_type == SILC_ROUTER)
2713 silc_server_check_watcher_list(server, client, NULL,
2714 SILC_NOTIFY_TYPE_SIGNOFF);
2716 /* Send SIGNOFF notify to routers. */
2718 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2719 SILC_BROADCAST(server), client->id,
2723 /* Remove client from all channels */
2725 silc_server_remove_from_channels(server, NULL, client,
2726 TRUE, (char *)signoff, TRUE);
2728 silc_server_remove_from_channels(server, NULL, client,
2729 FALSE, NULL, FALSE);
2731 /* Remove this client from watcher list if it is */
2732 silc_server_del_from_watcher_list(server, client);
2734 /* Update statistics */
2735 server->stat.my_clients--;
2736 server->stat.clients--;
2737 if (server->stat.cell_clients)
2738 server->stat.cell_clients--;
2739 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2740 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2741 silc_schedule_task_del_by_context(server->schedule, client);
2743 /* We will not delete the client entry right away. We will take it
2744 into history (for WHOWAS command) for 5 minutes */
2747 silc_schedule_task_add(server->schedule, 0,
2748 silc_server_free_client_data_timeout,
2750 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2751 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2753 client->router = NULL;
2754 client->connection = NULL;
2757 /* Frees user_data pointer from socket connection object. This also sends
2758 appropriate notify packets to the network to inform about leaving
2761 void silc_server_free_sock_user_data(SilcServer server,
2762 SilcSocketConnection sock,
2763 const char *signoff_message)
2765 switch (sock->type) {
2766 case SILC_SOCKET_TYPE_CLIENT:
2768 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2769 silc_server_free_client_data(server, sock, user_data, TRUE,
2773 case SILC_SOCKET_TYPE_SERVER:
2774 case SILC_SOCKET_TYPE_ROUTER:
2776 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2777 SilcServerEntry backup_router = NULL;
2779 SILC_LOG_DEBUG(("Freeing server data"));
2782 backup_router = silc_server_backup_get(server, user_data->id);
2784 /* If this was our primary router connection then we're lost to
2785 the outside world. */
2786 if (server->router == user_data) {
2787 /* Check whether we have a backup router connection */
2788 if (!backup_router || backup_router == user_data) {
2789 silc_schedule_task_add(server->schedule, 0,
2790 silc_server_connect_to_router,
2793 SILC_TASK_PRI_NORMAL);
2795 server->id_entry->router = NULL;
2796 server->router = NULL;
2797 server->standalone = TRUE;
2798 backup_router = NULL;
2800 if (server->id_entry == backup_router) {
2801 SILC_LOG_INFO(("We are now new router in this cell"));
2802 SILC_LOG_DEBUG(("We are now new router in this cell"));
2804 SILC_LOG_INFO(("New primary router is backup router %s",
2805 backup_router->server_name));
2806 SILC_LOG_DEBUG(("New primary router is backup router %s",
2807 backup_router->server_name));
2809 if (server->id_entry != backup_router) {
2810 server->id_entry->router = backup_router;
2811 server->router = backup_router;
2812 server->router_connect = time(0);
2813 server->backup_primary = TRUE;
2815 server->id_entry->router = NULL;
2816 server->router = NULL;
2817 server->standalone = TRUE;
2820 if (server->server_type == SILC_BACKUP_ROUTER) {
2821 server->server_type = SILC_ROUTER;
2823 /* We'll need to constantly try to reconnect to the primary
2824 router so that we'll see when it comes back online. */
2825 silc_server_backup_reconnect(server, sock->ip, sock->port,
2826 silc_server_backup_connected,
2830 /* Mark this connection as replaced */
2831 silc_server_backup_replaced_add(server, user_data->id,
2834 } else if (backup_router) {
2835 SILC_LOG_INFO(("Enabling the use of backup router %s",
2836 backup_router->server_name));
2837 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2838 backup_router->server_name));
2840 /* Mark this connection as replaced */
2841 silc_server_backup_replaced_add(server, user_data->id,
2845 if (!backup_router) {
2846 /* As router, remove clients and channels always. As normal server
2847 remove only if it is our primary router. Other connections
2848 may be backup routers and these normal server don't handle here. */
2849 if (server->server_type != SILC_SERVER ||
2850 server->standalone || sock == SILC_PRIMARY_ROUTE(server)) {
2851 /* Free all client entries that this server owns as they will
2852 become invalid now as well. */
2853 silc_server_remove_clients_by_server(server, user_data, TRUE);
2854 if (server->server_type == SILC_SERVER)
2855 silc_server_remove_channels_by_server(server, user_data);
2858 /* Update the client entries of this server to the new backup
2859 router. This also removes the clients that *really* was owned
2860 by the primary router and went down with the router. */
2861 silc_server_update_clients_by_server(server, user_data, backup_router,
2863 silc_server_update_servers_by_server(server, user_data, backup_router,
2865 if (server->server_type == SILC_SERVER)
2866 silc_server_update_channels_by_server(server, user_data,
2870 /* Free the server entry */
2871 silc_server_backup_del(server, user_data);
2872 silc_server_backup_replaced_del(server, user_data);
2873 silc_idlist_del_data(user_data);
2874 if (!silc_idlist_del_server(server->local_list, user_data))
2875 silc_idlist_del_server(server->global_list, user_data);
2876 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2877 server->stat.my_servers--;
2879 server->stat.my_routers--;
2880 server->stat.routers--;
2882 server->stat.servers--;
2883 if (server->server_type == SILC_ROUTER)
2884 server->stat.cell_servers--;
2886 if (backup_router && backup_router != server->id_entry) {
2887 /* Announce all of our stuff that was created about 5 minutes ago.
2888 The backup router knows all the other stuff already. */
2889 if (server->server_type == SILC_ROUTER)
2890 silc_server_announce_servers(server, FALSE, time(0) - 300,
2891 backup_router->connection);
2893 /* Announce our clients and channels to the router */
2894 silc_server_announce_clients(server, time(0) - 300,
2895 backup_router->connection);
2896 silc_server_announce_channels(server, time(0) - 300,
2897 backup_router->connection);
2903 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2905 SILC_LOG_DEBUG(("Freeing unknown connection data"));
2907 silc_idlist_del_data(user_data);
2908 silc_free(user_data);
2913 /* If any protocol is active cancel its execution */
2914 if (sock->protocol) {
2915 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2916 silc_protocol_cancel(sock->protocol, server->schedule);
2917 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2918 silc_protocol_execute_final(sock->protocol, server->schedule);
2919 sock->protocol = NULL;
2922 sock->user_data = NULL;
2925 /* Removes client from all channels it has joined. This is used when client
2926 connection is disconnected. If the client on a channel is last, the
2927 channel is removed as well. This sends the SIGNOFF notify types. */
2929 void silc_server_remove_from_channels(SilcServer server,
2930 SilcSocketConnection sock,
2931 SilcClientEntry client,
2933 const char *signoff_message,
2936 SilcChannelEntry channel;
2937 SilcChannelClientEntry chl;
2938 SilcHashTableList htl;
2939 SilcBuffer clidp = NULL;
2944 SILC_LOG_DEBUG(("Removing client from joined channels"));
2946 if (notify && !client->id)
2950 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2955 /* Remove the client from all channels. The client is removed from
2956 the channels' user list. */
2957 silc_hash_table_list(client->channels, &htl);
2958 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2959 channel = chl->channel;
2961 /* Remove channel if this is last client leaving the channel, unless
2962 the channel is permanent. */
2963 if (server->server_type == SILC_ROUTER &&
2964 silc_hash_table_count(channel->user_list) < 2) {
2965 silc_server_channel_delete(server, channel);
2969 silc_hash_table_del(client->channels, channel);
2970 silc_hash_table_del(channel->user_list, chl->client);
2971 channel->user_count--;
2973 /* If there is no global users on the channel anymore mark the channel
2974 as local channel. Do not check if the removed client is local client. */
2975 if (server->server_type != SILC_ROUTER && channel->global_users &&
2976 chl->client->router && !silc_server_channel_has_global(channel))
2977 channel->global_users = FALSE;
2981 /* Update statistics */
2982 if (SILC_IS_LOCAL(client))
2983 server->stat.my_chanclients--;
2984 if (server->server_type == SILC_ROUTER) {
2985 server->stat.cell_chanclients--;
2986 server->stat.chanclients--;
2989 /* If there is not at least one local user on the channel then we don't
2990 need the channel entry anymore, we can remove it safely, unless the
2991 channel is permanent channel */
2992 if (server->server_type != SILC_ROUTER &&
2993 !silc_server_channel_has_local(channel)) {
2994 /* Notify about leaving client if this channel has global users. */
2995 if (notify && channel->global_users)
2996 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2997 SILC_NOTIFY_TYPE_SIGNOFF,
2998 signoff_message ? 2 : 1,
2999 clidp->data, clidp->len,
3000 signoff_message, signoff_message ?
3001 strlen(signoff_message) : 0);
3003 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3004 silc_server_channel_delete(server, channel);
3008 /* Send notify to channel about client leaving SILC and channel too */
3010 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3011 SILC_NOTIFY_TYPE_SIGNOFF,
3012 signoff_message ? 2 : 1,
3013 clidp->data, clidp->len,
3014 signoff_message, signoff_message ?
3015 strlen(signoff_message) : 0);
3017 /* Re-generate channel key if needed */
3018 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3019 if (!silc_server_create_channel_key(server, channel, 0))
3022 /* Send the channel key to the channel. The key of course is not sent
3023 to the client who was removed from the channel. */
3024 silc_server_send_channel_key(server, client->connection, channel,
3025 server->server_type == SILC_ROUTER ?
3026 FALSE : !server->standalone);
3030 silc_hash_table_list_reset(&htl);
3032 silc_buffer_free(clidp);
3035 /* Removes client from one channel. This is used for example when client
3036 calls LEAVE command to remove itself from the channel. Returns TRUE
3037 if channel still exists and FALSE if the channel is removed when
3038 last client leaves the channel. If `notify' is FALSE notify messages
3041 bool silc_server_remove_from_one_channel(SilcServer server,
3042 SilcSocketConnection sock,
3043 SilcChannelEntry channel,
3044 SilcClientEntry client,
3047 SilcChannelClientEntry chl;
3050 SILC_LOG_DEBUG(("Removing %s from channel %s",
3051 silc_id_render(client->id, SILC_ID_CLIENT),
3052 channel->channel_name));
3054 /* Get the entry to the channel, if this client is not on the channel
3056 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3059 /* Remove channel if this is last client leaving the channel, unless
3060 the channel is permanent. */
3061 if (server->server_type == SILC_ROUTER &&
3062 silc_hash_table_count(channel->user_list) < 2) {
3063 silc_server_channel_delete(server, channel);
3067 silc_hash_table_del(client->channels, chl->channel);
3068 silc_hash_table_del(channel->user_list, chl->client);
3069 channel->user_count--;
3071 /* If there is no global users on the channel anymore mark the channel
3072 as local channel. Do not check if the client is local client. */
3073 if (server->server_type != SILC_ROUTER && channel->global_users &&
3074 chl->client->router && !silc_server_channel_has_global(channel))
3075 channel->global_users = FALSE;
3079 /* Update statistics */
3080 if (SILC_IS_LOCAL(client))
3081 server->stat.my_chanclients--;
3082 if (server->server_type == SILC_ROUTER) {
3083 server->stat.cell_chanclients--;
3084 server->stat.chanclients--;
3087 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3091 /* If there is not at least one local user on the channel then we don't
3092 need the channel entry anymore, we can remove it safely, unless the
3093 channel is permanent channel */
3094 if (server->server_type != SILC_ROUTER &&
3095 !silc_server_channel_has_local(channel)) {
3096 /* Notify about leaving client if this channel has global users. */
3097 if (notify && channel->global_users)
3098 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3099 SILC_NOTIFY_TYPE_LEAVE, 1,
3100 clidp->data, clidp->len);
3102 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3103 silc_server_channel_delete(server, channel);
3104 silc_buffer_free(clidp);
3108 /* Send notify to channel about client leaving the channel */
3110 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3111 SILC_NOTIFY_TYPE_LEAVE, 1,
3112 clidp->data, clidp->len);
3114 silc_buffer_free(clidp);
3118 /* Timeout callback. This is called if connection is idle or for some
3119 other reason is not responding within some period of time. This
3120 disconnects the remote end. */
3122 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3124 SilcServer server = (SilcServer)context;
3125 SilcSocketConnection sock = server->sockets[fd];
3126 SilcProtocolType protocol = 0;
3128 SILC_LOG_DEBUG(("Start"));
3133 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3134 sock->hostname, sock->ip));
3136 /* If we have protocol active we must assure that we call the protocol's
3137 final callback so that all the memory is freed. */
3138 if (sock->protocol) {
3139 protocol = sock->protocol->protocol->type;
3140 silc_protocol_cancel(sock->protocol, server->schedule);
3141 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3142 silc_protocol_execute_final(sock->protocol, server->schedule);
3143 sock->protocol = NULL;
3147 if (sock->user_data)
3148 silc_server_free_sock_user_data(server, sock, NULL);
3150 silc_server_disconnect_remote(server, sock,
3152 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3153 SILC_STATUS_ERR_AUTH_FAILED :
3154 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3155 "Connection timeout");
3158 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3159 function may be used only by router. In real SILC network all channels
3160 are created by routers thus this function is never used by normal
3163 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3164 SilcServerID *router_id,
3170 SilcChannelID *channel_id;
3171 SilcChannelEntry entry;
3175 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3178 cipher = SILC_DEFAULT_CIPHER;
3180 hmac = SILC_DEFAULT_HMAC;
3182 /* Allocate cipher */
3183 if (!silc_cipher_alloc(cipher, &key))
3187 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3188 silc_cipher_free(key);
3192 channel_name = strdup(channel_name);
3194 /* Create the channel ID */
3195 if (!silc_id_create_channel_id(server, router_id, server->rng,
3197 silc_free(channel_name);
3198 silc_cipher_free(key);
3199 silc_hmac_free(newhmac);
3203 /* Create the channel */
3204 entry = silc_idlist_add_channel(server->local_list, channel_name,
3205 SILC_CHANNEL_MODE_NONE, channel_id,
3206 NULL, key, newhmac, 0);
3208 silc_free(channel_name);
3209 silc_cipher_free(key);
3210 silc_hmac_free(newhmac);
3211 silc_free(channel_id);
3215 entry->cipher = strdup(cipher);
3216 entry->hmac_name = strdup(hmac);
3218 /* Now create the actual key material */
3219 if (!silc_server_create_channel_key(server, entry,
3220 silc_cipher_get_key_len(key) / 8)) {
3221 silc_idlist_del_channel(server->local_list, entry);
3225 /* Notify other routers about the new channel. We send the packet
3226 to our primary route. */
3228 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3229 channel_name, entry->id,
3230 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3233 /* Distribute to backup routers */
3234 if (broadcast && server->server_type == SILC_ROUTER) {
3237 SilcUInt32 name_len = strlen(channel_name);
3238 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3239 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3241 packet = silc_channel_payload_encode(channel_name, name_len,
3242 cid, channel_id_len, entry->mode);
3243 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3244 packet->data, packet->len, FALSE, TRUE);
3246 silc_buffer_free(packet);
3249 server->stat.my_channels++;
3250 if (server->server_type == SILC_ROUTER) {
3251 server->stat.channels++;
3252 server->stat.cell_channels++;
3253 entry->users_resolved = TRUE;
3259 /* Same as above but creates the channel with Channel ID `channel_id. */
3262 silc_server_create_new_channel_with_id(SilcServer server,
3266 SilcChannelID *channel_id,
3269 SilcChannelEntry entry;
3273 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3276 cipher = SILC_DEFAULT_CIPHER;
3278 hmac = SILC_DEFAULT_HMAC;
3280 /* Allocate cipher */
3281 if (!silc_cipher_alloc(cipher, &key))
3285 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3286 silc_cipher_free(key);
3290 channel_name = strdup(channel_name);
3292 /* Create the channel */
3293 entry = silc_idlist_add_channel(server->local_list, channel_name,
3294 SILC_CHANNEL_MODE_NONE, channel_id,
3295 NULL, key, newhmac, 0);
3297 silc_cipher_free(key);
3298 silc_hmac_free(newhmac);
3299 silc_free(channel_name);
3303 /* Now create the actual key material */
3304 if (!silc_server_create_channel_key(server, entry,
3305 silc_cipher_get_key_len(key) / 8)) {
3306 silc_idlist_del_channel(server->local_list, entry);
3310 /* Notify other routers about the new channel. We send the packet
3311 to our primary route. */
3313 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3314 channel_name, entry->id,
3315 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3318 /* Distribute to backup routers */
3319 if (broadcast && server->server_type == SILC_ROUTER) {
3322 SilcUInt32 name_len = strlen(channel_name);
3323 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3324 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3326 packet = silc_channel_payload_encode(channel_name, name_len,
3327 cid, channel_id_len, entry->mode);
3328 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3329 packet->data, packet->len, FALSE, TRUE);
3331 silc_buffer_free(packet);
3334 server->stat.my_channels++;
3335 if (server->server_type == SILC_ROUTER) {
3336 server->stat.channels++;
3337 server->stat.cell_channels++;
3338 entry->users_resolved = TRUE;
3344 /* Channel's key re-key timeout callback. */
3346 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3348 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3349 SilcServer server = (SilcServer)rekey->context;
3353 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3356 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3359 /* Generates new channel key. This is used to create the initial channel key
3360 but also to re-generate new key for channel. If `key_len' is provided
3361 it is the bytes of the key length. */
3363 bool silc_server_create_channel_key(SilcServer server,
3364 SilcChannelEntry channel,
3368 unsigned char channel_key[32], hash[32];
3371 SILC_LOG_DEBUG(("Generating channel key"));
3373 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3374 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3378 if (!channel->channel_key)
3379 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3380 channel->channel_key = NULL;
3386 else if (channel->key_len)
3387 len = channel->key_len / 8;
3389 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3391 /* Create channel key */
3392 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3395 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3397 /* Remove old key if exists */
3399 memset(channel->key, 0, channel->key_len / 8);
3400 silc_free(channel->key);
3404 channel->key_len = len * 8;
3405 channel->key = silc_memdup(channel_key, len);
3406 memset(channel_key, 0, sizeof(channel_key));
3408 /* Generate HMAC key from the channel key data and set it */
3410 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3411 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3412 silc_hmac_set_key(channel->hmac, hash,
3413 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3414 memset(hash, 0, sizeof(hash));
3416 if (server->server_type == SILC_ROUTER) {
3417 if (!channel->rekey)
3418 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3419 channel->rekey->context = (void *)server;
3420 channel->rekey->channel = channel;
3421 channel->rekey->key_len = key_len;
3422 if (channel->rekey->task)
3423 silc_schedule_task_del(server->schedule, channel->rekey->task);
3425 channel->rekey->task =
3426 silc_schedule_task_add(server->schedule, 0,
3427 silc_server_channel_key_rekey,
3428 (void *)channel->rekey,
3429 server->config->channel_rekey_secs, 0,
3431 SILC_TASK_PRI_NORMAL);
3437 /* Saves the channel key found in the encoded `key_payload' buffer. This
3438 function is used when we receive Channel Key Payload and also when we're
3439 processing JOIN command reply. Returns entry to the channel. */
3441 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3442 SilcBuffer key_payload,
3443 SilcChannelEntry channel)
3445 SilcChannelKeyPayload payload = NULL;
3446 SilcChannelID *id = NULL;
3447 unsigned char *tmp, hash[32];
3451 SILC_LOG_DEBUG(("Saving new channel key"));
3453 /* Decode channel key payload */
3454 payload = silc_channel_key_payload_parse(key_payload->data,
3457 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3462 /* Get the channel entry */
3465 /* Get channel ID */
3466 tmp = silc_channel_key_get_id(payload, &tmp_len);
3467 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3473 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3475 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3477 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3478 silc_id_render(id, SILC_ID_CHANNEL)));
3484 tmp = silc_channel_key_get_key(payload, &tmp_len);
3490 cipher = silc_channel_key_get_cipher(payload, NULL);
3496 /* Remove old key if exists */
3498 memset(channel->key, 0, channel->key_len / 8);
3499 silc_free(channel->key);
3500 silc_cipher_free(channel->channel_key);
3503 /* Create new cipher */
3504 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3505 channel->channel_key = NULL;
3510 if (channel->cipher)
3511 silc_free(channel->cipher);
3512 channel->cipher = strdup(cipher);
3515 channel->key_len = tmp_len * 8;
3516 channel->key = silc_memdup(tmp, tmp_len);
3517 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3519 /* Generate HMAC key from the channel key data and set it */
3521 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3522 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3523 silc_hmac_set_key(channel->hmac, hash,
3524 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3526 memset(hash, 0, sizeof(hash));
3527 memset(tmp, 0, tmp_len);
3529 if (server->server_type == SILC_ROUTER) {
3530 if (!channel->rekey)
3531 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3532 channel->rekey->context = (void *)server;
3533 channel->rekey->channel = channel;
3534 if (channel->rekey->task)
3535 silc_schedule_task_del(server->schedule, channel->rekey->task);
3537 channel->rekey->task =
3538 silc_schedule_task_add(server->schedule, 0,
3539 silc_server_channel_key_rekey,
3540 (void *)channel->rekey,
3541 server->config->channel_rekey_secs, 0,
3543 SILC_TASK_PRI_NORMAL);
3549 silc_channel_key_payload_free(payload);
3554 /* Heartbeat callback. This function is set as argument for the
3555 silc_socket_set_heartbeat function. The library will call this function
3556 at the set time interval. */
3558 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3561 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3563 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3565 /* Send the heartbeat */
3566 silc_server_send_heartbeat(hb->server, sock);
3569 /* Returns assembled of all servers in the given ID list. The packet's
3570 form is dictated by the New ID payload. */
3572 static void silc_server_announce_get_servers(SilcServer server,
3573 SilcServerEntry remote,
3575 SilcBuffer *servers,
3576 unsigned long creation_time)
3578 SilcIDCacheList list;
3579 SilcIDCacheEntry id_cache;
3580 SilcServerEntry entry;
3583 /* Go through all clients in the list */
3584 if (silc_idcache_get_all(id_list->servers, &list)) {
3585 if (silc_idcache_list_first(list, &id_cache)) {
3587 entry = (SilcServerEntry)id_cache->context;
3589 /* Do not announce the one we've sending our announcements and
3590 do not announce ourself. Also check the creation time if it's
3592 if ((entry == remote) || (entry == server->id_entry) ||
3593 (creation_time && entry->data.created < creation_time)) {
3594 if (!silc_idcache_list_next(list, &id_cache))
3599 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3601 *servers = silc_buffer_realloc(*servers,
3603 (*servers)->truelen + idp->len :
3605 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3606 silc_buffer_put(*servers, idp->data, idp->len);
3607 silc_buffer_pull(*servers, idp->len);
3608 silc_buffer_free(idp);
3610 if (!silc_idcache_list_next(list, &id_cache))
3615 silc_idcache_list_free(list);
3620 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3626 p = silc_notify_payload_encode(notify, argc, ap);
3632 /* This function is used by router to announce existing servers to our
3633 primary router when we've connected to it. If `creation_time' is non-zero
3634 then only the servers that has been created after the `creation_time'
3635 will be announced. */
3637 void silc_server_announce_servers(SilcServer server, bool global,
3638 unsigned long creation_time,
3639 SilcSocketConnection remote)
3641 SilcBuffer servers = NULL;
3643 SILC_LOG_DEBUG(("Announcing servers"));
3645 /* Get servers in local list */
3646 silc_server_announce_get_servers(server, remote->user_data,
3647 server->local_list, &servers,
3651 /* Get servers in global list */
3652 silc_server_announce_get_servers(server, remote->user_data,
3653 server->global_list, &servers,
3657 silc_buffer_push(servers, servers->data - servers->head);
3658 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3660 /* Send the packet */
3661 silc_server_packet_send(server, remote,
3662 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3663 servers->data, servers->len, TRUE);
3665 silc_buffer_free(servers);
3669 /* Returns assembled packet of all clients in the given ID list. The
3670 packet's form is dictated by the New ID Payload. */
3672 static void silc_server_announce_get_clients(SilcServer server,
3674 SilcBuffer *clients,
3676 unsigned long creation_time)
3678 SilcIDCacheList list;
3679 SilcIDCacheEntry id_cache;
3680 SilcClientEntry client;
3683 unsigned char mode[4];
3685 /* Go through all clients in the list */
3686 if (silc_idcache_get_all(id_list->clients, &list)) {
3687 if (silc_idcache_list_first(list, &id_cache)) {
3689 client = (SilcClientEntry)id_cache->context;
3691 if (creation_time && client->data.created < creation_time) {
3692 if (!silc_idcache_list_next(list, &id_cache))
3697 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3699 *clients = silc_buffer_realloc(*clients,
3701 (*clients)->truelen + idp->len :
3703 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3704 silc_buffer_put(*clients, idp->data, idp->len);
3705 silc_buffer_pull(*clients, idp->len);
3707 SILC_PUT32_MSB(client->mode, mode);
3709 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3710 2, idp->data, idp->len,
3712 *umodes = silc_buffer_realloc(*umodes,
3714 (*umodes)->truelen + tmp->len :
3716 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3717 silc_buffer_put(*umodes, tmp->data, tmp->len);
3718 silc_buffer_pull(*umodes, tmp->len);
3719 silc_buffer_free(tmp);
3721 silc_buffer_free(idp);
3723 if (!silc_idcache_list_next(list, &id_cache))
3728 silc_idcache_list_free(list);
3732 /* This function is used to announce our existing clients to our router
3733 when we've connected to it. If `creation_time' is non-zero then only
3734 the clients that has been created after the `creation_time' will be
3737 void silc_server_announce_clients(SilcServer server,
3738 unsigned long creation_time,
3739 SilcSocketConnection remote)
3741 SilcBuffer clients = NULL;
3742 SilcBuffer umodes = NULL;
3744 SILC_LOG_DEBUG(("Announcing clients"));
3746 /* Get clients in local list */
3747 silc_server_announce_get_clients(server, server->local_list,
3748 &clients, &umodes, creation_time);
3750 /* As router we announce our global list as well */
3751 if (server->server_type == SILC_ROUTER)
3752 silc_server_announce_get_clients(server, server->global_list,
3753 &clients, &umodes, creation_time);
3756 silc_buffer_push(clients, clients->data - clients->head);
3757 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3759 /* Send the packet */
3760 silc_server_packet_send(server, remote,
3761 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3762 clients->data, clients->len, TRUE);
3764 silc_buffer_free(clients);
3768 silc_buffer_push(umodes, umodes->data - umodes->head);
3769 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3771 /* Send the packet */
3772 silc_server_packet_send(server, remote,
3773 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3774 umodes->data, umodes->len, TRUE);
3776 silc_buffer_free(umodes);
3780 /* Returns channel's topic for announcing it */
3782 void silc_server_announce_get_channel_topic(SilcServer server,
3783 SilcChannelEntry channel,
3788 if (channel->topic) {
3789 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3790 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3791 chidp->data, chidp->len,
3793 strlen(channel->topic));
3794 silc_buffer_free(chidp);
3798 /* Returns assembled packets for channel users of the `channel'. */
3800 void silc_server_announce_get_channel_users(SilcServer server,
3801 SilcChannelEntry channel,
3802 SilcBuffer *channel_modes,
3803 SilcBuffer *channel_users,
3804 SilcBuffer *channel_users_modes)
3806 SilcChannelClientEntry chl;
3807 SilcHashTableList htl;
3808 SilcBuffer chidp, clidp, csidp;
3811 unsigned char mode[4], *fkey = NULL;
3812 SilcUInt32 fkey_len = 0;
3815 SILC_LOG_DEBUG(("Start"));
3817 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3818 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3821 SILC_PUT32_MSB(channel->mode, mode);
3822 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3823 if (channel->founder_key)
3824 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3826 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3827 6, csidp->data, csidp->len,
3830 hmac, hmac ? strlen(hmac) : 0,
3831 channel->passphrase,
3832 channel->passphrase ?
3833 strlen(channel->passphrase) : 0,
3837 silc_buffer_realloc(*channel_modes,
3839 (*channel_modes)->truelen + len : len));
3840 silc_buffer_pull_tail(*channel_modes,
3841 ((*channel_modes)->end -
3842 (*channel_modes)->data));
3843 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3844 silc_buffer_pull(*channel_modes, len);
3845 silc_buffer_free(tmp);
3850 /* Now find all users on the channel */
3851 silc_hash_table_list(channel->user_list, &htl);
3852 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3853 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3856 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3857 clidp->data, clidp->len,
3858 chidp->data, chidp->len);
3861 silc_buffer_realloc(*channel_users,
3863 (*channel_users)->truelen + len : len));
3864 silc_buffer_pull_tail(*channel_users,
3865 ((*channel_users)->end -
3866 (*channel_users)->data));
3868 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3869 silc_buffer_pull(*channel_users, len);
3870 silc_buffer_free(tmp);
3872 /* CUMODE notify for mode change on the channel */
3873 SILC_PUT32_MSB(chl->mode, mode);
3874 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3875 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3876 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3877 4, csidp->data, csidp->len,
3879 clidp->data, clidp->len,
3882 *channel_users_modes =
3883 silc_buffer_realloc(*channel_users_modes,
3884 (*channel_users_modes ?
3885 (*channel_users_modes)->truelen + len : len));
3886 silc_buffer_pull_tail(*channel_users_modes,
3887 ((*channel_users_modes)->end -
3888 (*channel_users_modes)->data));
3890 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3891 silc_buffer_pull(*channel_users_modes, len);
3892 silc_buffer_free(tmp);
3896 silc_buffer_free(clidp);
3898 silc_hash_table_list_reset(&htl);
3899 silc_buffer_free(chidp);
3900 silc_buffer_free(csidp);
3903 /* Returns assembled packets for all channels and users on those channels
3904 from the given ID List. The packets are in the form dictated by the
3905 New Channel and New Channel User payloads. */
3907 void silc_server_announce_get_channels(SilcServer server,
3909 SilcBuffer *channels,
3910 SilcBuffer **channel_modes,
3911 SilcBuffer *channel_users,
3912 SilcBuffer **channel_users_modes,
3913 SilcUInt32 *channel_users_modes_c,
3914 SilcBuffer **channel_topics,
3915 SilcChannelID ***channel_ids,
3916 unsigned long creation_time)
3918 SilcIDCacheList list;
3919 SilcIDCacheEntry id_cache;
3920 SilcChannelEntry channel;
3923 SilcUInt16 name_len;
3925 int i = *channel_users_modes_c;
3928 SILC_LOG_DEBUG(("Start"));
3930 /* Go through all channels in the list */
3931 if (silc_idcache_get_all(id_list->channels, &list)) {
3932 if (silc_idcache_list_first(list, &id_cache)) {
3934 channel = (SilcChannelEntry)id_cache->context;
3936 if (creation_time && channel->created < creation_time)
3941 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3942 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3943 name_len = strlen(channel->channel_name);
3946 len = 4 + name_len + id_len + 4;
3948 silc_buffer_realloc(*channels,
3949 (*channels ? (*channels)->truelen +
3951 silc_buffer_pull_tail(*channels,
3952 ((*channels)->end - (*channels)->data));
3953 silc_buffer_format(*channels,
3954 SILC_STR_UI_SHORT(name_len),
3955 SILC_STR_UI_XNSTRING(channel->channel_name,
3957 SILC_STR_UI_SHORT(id_len),
3958 SILC_STR_UI_XNSTRING(cid, id_len),
3959 SILC_STR_UI_INT(channel->mode),
3961 silc_buffer_pull(*channels, len);
3964 /* Channel user modes */
3965 *channel_users_modes = silc_realloc(*channel_users_modes,
3966 sizeof(**channel_users_modes) *
3968 (*channel_users_modes)[i] = NULL;
3969 *channel_modes = silc_realloc(*channel_modes,
3970 sizeof(**channel_modes) * (i + 1));
3971 (*channel_modes)[i] = NULL;
3972 *channel_ids = silc_realloc(*channel_ids,
3973 sizeof(**channel_ids) * (i + 1));
3974 (*channel_ids)[i] = NULL;
3975 silc_server_announce_get_channel_users(server, channel,
3976 &(*channel_modes)[i],
3978 &(*channel_users_modes)[i]);
3979 (*channel_ids)[i] = channel->id;
3981 /* Channel's topic */
3982 *channel_topics = silc_realloc(*channel_topics,
3983 sizeof(**channel_topics) * (i + 1));
3984 (*channel_topics)[i] = NULL;
3985 silc_server_announce_get_channel_topic(server, channel,
3986 &(*channel_topics)[i]);
3989 if (!silc_idcache_list_next(list, &id_cache))
3993 *channel_users_modes_c += i;
3996 silc_idcache_list_free(list);
4000 /* This function is used to announce our existing channels to our router
4001 when we've connected to it. This also announces the users on the
4002 channels to the router. If the `creation_time' is non-zero only the
4003 channels that was created after the `creation_time' are announced.
4004 Note that the channel users are still announced even if the `creation_time'
4007 void silc_server_announce_channels(SilcServer server,
4008 unsigned long creation_time,
4009 SilcSocketConnection remote)
4011 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4012 SilcBuffer *channel_users_modes = NULL;
4013 SilcBuffer *channel_topics = NULL;
4014 SilcUInt32 channel_users_modes_c = 0;
4015 SilcChannelID **channel_ids = NULL;
4017 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4019 /* Get channels and channel users in local list */
4020 silc_server_announce_get_channels(server, server->local_list,
4021 &channels, &channel_modes,
4023 &channel_users_modes,
4024 &channel_users_modes_c,
4026 &channel_ids, creation_time);
4028 /* Get channels and channel users in global list */
4029 if (server->server_type != SILC_SERVER)
4030 silc_server_announce_get_channels(server, server->global_list,
4031 &channels, &channel_modes,
4033 &channel_users_modes,
4034 &channel_users_modes_c,
4036 &channel_ids, creation_time);
4039 silc_buffer_push(channels, channels->data - channels->head);
4040 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4042 /* Send the packet */
4043 silc_server_packet_send(server, remote,
4044 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4045 channels->data, channels->len,
4048 silc_buffer_free(channels);
4051 if (channel_users) {
4052 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4053 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4054 channel_users->len);
4056 /* Send the packet */
4057 silc_server_packet_send(server, remote,
4058 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4059 channel_users->data, channel_users->len,
4062 silc_buffer_free(channel_users);
4065 if (channel_modes) {
4068 for (i = 0; i < channel_users_modes_c; i++) {
4069 if (!channel_modes[i])
4071 silc_buffer_push(channel_modes[i],
4072 channel_modes[i]->data -
4073 channel_modes[i]->head);
4074 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4075 channel_modes[i]->len);
4076 silc_server_packet_send_dest(server, remote,
4077 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4078 channel_ids[i], SILC_ID_CHANNEL,
4079 channel_modes[i]->data,
4080 channel_modes[i]->len,
4082 silc_buffer_free(channel_modes[i]);
4084 silc_free(channel_modes);
4087 if (channel_users_modes) {
4090 for (i = 0; i < channel_users_modes_c; i++) {
4091 if (!channel_users_modes[i])
4093 silc_buffer_push(channel_users_modes[i],
4094 channel_users_modes[i]->data -
4095 channel_users_modes[i]->head);
4096 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4097 channel_users_modes[i]->len);
4098 silc_server_packet_send_dest(server, remote,
4099 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4100 channel_ids[i], SILC_ID_CHANNEL,
4101 channel_users_modes[i]->data,
4102 channel_users_modes[i]->len,
4104 silc_buffer_free(channel_users_modes[i]);
4106 silc_free(channel_users_modes);
4109 if (channel_topics) {
4112 for (i = 0; i < channel_users_modes_c; i++) {
4113 if (!channel_topics[i])
4116 silc_buffer_push(channel_topics[i],
4117 channel_topics[i]->data -
4118 channel_topics[i]->head);
4119 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4120 channel_topics[i]->len);
4121 silc_server_packet_send_dest(server, remote,
4122 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4123 channel_ids[i], SILC_ID_CHANNEL,
4124 channel_topics[i]->data,
4125 channel_topics[i]->len,
4127 silc_buffer_free(channel_topics[i]);
4129 silc_free(channel_topics);
4132 silc_free(channel_ids);
4135 /* Failure timeout callback. If this is called then we will immediately
4136 process the received failure. We always process the failure with timeout
4137 since we do not want to blindly trust to received failure packets.
4138 This won't be called (the timeout is cancelled) if the failure was
4139 bogus (it is bogus if remote does not close the connection after sending
4142 SILC_TASK_CALLBACK(silc_server_failure_callback)
4144 SilcServerFailureContext f = (SilcServerFailureContext)context;
4146 if (f->sock->protocol) {
4147 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4148 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4154 /* Assembles user list and users mode list from the `channel'. */
4156 bool silc_server_get_users_on_channel(SilcServer server,
4157 SilcChannelEntry channel,
4158 SilcBuffer *user_list,
4159 SilcBuffer *mode_list,
4160 SilcUInt32 *user_count)
4162 SilcChannelClientEntry chl;
4163 SilcHashTableList htl;
4164 SilcBuffer client_id_list;
4165 SilcBuffer client_mode_list;
4167 SilcUInt32 list_count = 0, len = 0;
4169 if (!silc_hash_table_count(channel->user_list))
4172 silc_hash_table_list(channel->user_list, &htl);
4173 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4174 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4175 silc_hash_table_list_reset(&htl);
4177 client_id_list = silc_buffer_alloc(len);
4179 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4180 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4181 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4183 silc_hash_table_list(channel->user_list, &htl);
4184 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4186 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4187 silc_buffer_put(client_id_list, idp->data, idp->len);
4188 silc_buffer_pull(client_id_list, idp->len);
4189 silc_buffer_free(idp);
4191 /* Client's mode on channel */
4192 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4193 silc_buffer_pull(client_mode_list, 4);
4197 silc_hash_table_list_reset(&htl);
4198 silc_buffer_push(client_id_list,
4199 client_id_list->data - client_id_list->head);
4200 silc_buffer_push(client_mode_list,
4201 client_mode_list->data - client_mode_list->head);
4203 *user_list = client_id_list;
4204 *mode_list = client_mode_list;
4205 *user_count = list_count;
4209 /* Saves users and their modes to the `channel'. */
4211 void silc_server_save_users_on_channel(SilcServer server,
4212 SilcSocketConnection sock,
4213 SilcChannelEntry channel,
4214 SilcClientID *noadd,
4215 SilcBuffer user_list,
4216 SilcBuffer mode_list,
4217 SilcUInt32 user_count)
4222 SilcClientID *client_id;
4223 SilcClientEntry client;
4224 SilcIDCacheEntry cache;
4225 SilcChannelClientEntry chl;
4228 SILC_LOG_DEBUG(("Start"));
4230 for (i = 0; i < user_count; i++) {
4232 SILC_GET16_MSB(idp_len, user_list->data + 2);
4234 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4235 silc_buffer_pull(user_list, idp_len);
4240 SILC_GET32_MSB(mode, mode_list->data);
4241 silc_buffer_pull(mode_list, 4);
4243 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4244 silc_free(client_id);
4250 /* Check if we have this client cached already. */
4251 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4252 server->server_type, &cache);
4254 client = silc_idlist_find_client_by_id(server->global_list,
4255 client_id, server->server_type,
4260 /* If router did not find such Client ID in its lists then this must
4261 be bogus client or some router in the net is buggy. */
4262 if (server->server_type == SILC_ROUTER) {
4263 silc_free(client_id);
4267 /* We don't have that client anywhere, add it. The client is added
4268 to global list since server didn't have it in the lists so it must be
4270 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4271 silc_id_dup(client_id, SILC_ID_CLIENT),
4272 sock->user_data, NULL, 0);
4274 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4275 silc_free(client_id);
4279 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4281 /* Found, if it is from global list we'll assure that we won't
4282 expire it now that the entry is on channel. */
4287 silc_free(client_id);
4289 if (!silc_server_client_on_channel(client, channel, &chl)) {
4290 /* Client was not on the channel, add it. */
4291 chl = silc_calloc(1, sizeof(*chl));
4292 chl->client = client;
4294 chl->channel = channel;
4295 silc_hash_table_add(channel->user_list, chl->client, chl);
4296 silc_hash_table_add(client->channels, chl->channel, chl);
4297 channel->user_count++;
4305 /* Saves channels and channels user modes to the `client'. Removes
4306 the client from those channels that are not sent in the list but
4309 void silc_server_save_user_channels(SilcServer server,
4310 SilcSocketConnection sock,
4311 SilcClientEntry client,
4312 SilcBuffer channels,
4313 SilcBuffer channels_user_modes)
4316 SilcUInt32 *chumodes;
4317 SilcChannelPayload entry;
4318 SilcChannelEntry channel;
4319 SilcChannelID *channel_id;
4320 SilcChannelClientEntry chl;
4321 SilcHashTable ht = NULL;
4322 SilcHashTableList htl;
4326 if (!channels ||!channels_user_modes)
4329 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4330 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4332 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4333 NULL, NULL, NULL, TRUE);
4334 silc_dlist_start(ch);
4335 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4336 /* Check if we have this channel, and add it if we don't have it.
4337 Also add the client on the channel unless it is there already. */
4338 channel_id = silc_channel_get_id_parse(entry);
4339 channel = silc_idlist_find_channel_by_id(server->local_list,
4342 channel = silc_idlist_find_channel_by_id(server->global_list,
4345 if (server->server_type != SILC_SERVER) {
4346 silc_free(channel_id);
4351 /* We don't have that channel anywhere, add it. */
4352 name = silc_channel_get_name(entry, NULL);
4353 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4354 channel_id, server->router,
4357 silc_free(channel_id);
4364 channel->mode = silc_channel_get_mode(entry);
4366 /* Add the client on the channel */
4367 if (!silc_server_client_on_channel(client, channel, &chl)) {
4368 chl = silc_calloc(1, sizeof(*chl));
4369 chl->client = client;
4370 chl->mode = chumodes[i++];
4371 chl->channel = channel;
4372 silc_hash_table_add(channel->user_list, chl->client, chl);
4373 silc_hash_table_add(client->channels, chl->channel, chl);
4374 channel->user_count++;
4377 chl->mode = chumodes[i++];
4380 silc_hash_table_add(ht, channel, channel);
4381 silc_free(channel_id);
4383 silc_channel_payload_list_free(ch);
4384 silc_free(chumodes);
4388 /* Go through the list again and remove client from channels that
4389 are no part of the list. */
4391 silc_hash_table_list(client->channels, &htl);
4392 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4393 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4394 silc_hash_table_del(chl->channel->user_list, chl->client);
4395 silc_hash_table_del(chl->client->channels, chl->channel);
4399 silc_hash_table_list_reset(&htl);
4400 silc_hash_table_free(ht);
4402 silc_hash_table_list(client->channels, &htl);
4403 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4404 silc_hash_table_del(chl->channel->user_list, chl->client);
4405 silc_hash_table_del(chl->client->channels, chl->channel);
4408 silc_hash_table_list_reset(&htl);
4412 /* Lookups route to the client indicated by the `id_data'. The connection
4413 object and internal data object is returned. Returns NULL if route
4414 could not be found to the client. If the `client_id' is specified then
4415 it is used and the `id_data' is ignored. */
4417 SilcSocketConnection
4418 silc_server_get_client_route(SilcServer server,
4419 unsigned char *id_data,
4421 SilcClientID *client_id,
4422 SilcIDListData *idata,
4423 SilcClientEntry *client_entry)
4426 SilcClientEntry client;
4428 SILC_LOG_DEBUG(("Start"));
4431 *client_entry = NULL;
4433 /* Decode destination Client ID */
4435 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4437 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4441 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4444 /* If the destination belongs to our server we don't have to route
4445 the packet anywhere but to send it to the local destination. */
4446 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4450 /* If we are router and the client has router then the client is in
4451 our cell but not directly connected to us. */
4452 if (server->server_type == SILC_ROUTER && client->router) {
4453 /* We are of course in this case the client's router thus the route
4454 to the client is the server who owns the client. So, we will send
4455 the packet to that server. */
4457 *idata = (SilcIDListData)client->router;
4458 return client->router->connection;
4461 /* Seems that client really is directly connected to us */
4463 *idata = (SilcIDListData)client;
4465 *client_entry = client;
4466 return client->connection;
4469 /* Destination belongs to someone not in this server. If we are normal
4470 server our action is to send the packet to our router. */
4471 if (server->server_type != SILC_ROUTER && !server->standalone) {
4474 *idata = (SilcIDListData)server->router;
4475 return SILC_PRIMARY_ROUTE(server);
4478 /* We are router and we will perform route lookup for the destination
4479 and send the packet to fastest route. */
4480 if (server->server_type == SILC_ROUTER && !server->standalone) {
4481 /* Check first that the ID is valid */
4482 client = silc_idlist_find_client_by_id(server->global_list, id,
4485 SilcSocketConnection dst_sock;
4487 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4491 *idata = (SilcIDListData)dst_sock->user_data;
4500 /* Encodes and returns channel list of channels the `client' has joined.
4501 Secret channels are not put to the list. */
4503 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4504 SilcClientEntry client,
4507 SilcBuffer *user_mode_list)
4509 SilcBuffer buffer = NULL;
4510 SilcChannelEntry channel;
4511 SilcChannelClientEntry chl;
4512 SilcHashTableList htl;
4515 SilcUInt16 name_len;
4519 *user_mode_list = NULL;
4521 silc_hash_table_list(client->channels, &htl);
4522 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4523 channel = chl->channel;
4525 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4527 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4530 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4531 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4532 name_len = strlen(channel->channel_name);
4534 len = 4 + name_len + id_len + 4;
4535 buffer = silc_buffer_realloc(buffer,
4536 (buffer ? buffer->truelen + len : len));
4537 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4538 silc_buffer_format(buffer,
4539 SILC_STR_UI_SHORT(name_len),
4540 SILC_STR_UI_XNSTRING(channel->channel_name,
4542 SILC_STR_UI_SHORT(id_len),
4543 SILC_STR_UI_XNSTRING(cid, id_len),
4544 SILC_STR_UI_INT(chl->channel->mode),
4546 silc_buffer_pull(buffer, len);
4549 if (user_mode_list) {
4550 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4552 (*user_mode_list)->truelen + 4 :
4554 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4555 (*user_mode_list)->data));
4556 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4557 silc_buffer_pull(*user_mode_list, 4);
4560 silc_hash_table_list_reset(&htl);
4563 silc_buffer_push(buffer, buffer->data - buffer->head);
4564 if (user_mode_list && *user_mode_list)
4565 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4566 (*user_mode_list)->head));
4571 /* Finds client entry by Client ID and if it is not found then resolves
4572 it using WHOIS command. */
4574 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4575 SilcClientID *client_id,
4576 bool always_resolve,
4579 SilcClientEntry client;
4584 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4587 client = silc_idlist_find_client_by_id(server->global_list,
4588 client_id, TRUE, NULL);
4589 if (!client && server->server_type == SILC_ROUTER)
4593 if (!client && server->standalone)
4596 if (!client || !client->nickname || !client->username ||
4598 SilcBuffer buffer, idp;
4601 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4602 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4603 client->resolve_cmd_ident = ++server->cmd_ident;
4606 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4607 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4608 server->cmd_ident, 1,
4609 4, idp->data, idp->len);
4610 silc_server_packet_send(server, client ? client->router->connection :
4611 SILC_PRIMARY_ROUTE(server),
4612 SILC_PACKET_COMMAND, 0,
4613 buffer->data, buffer->len, FALSE);
4614 silc_buffer_free(idp);
4615 silc_buffer_free(buffer);
4626 /* A timeout callback for the re-key. We will be the initiator of the
4629 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4631 SilcSocketConnection sock = (SilcSocketConnection)context;
4632 SilcIDListData idata = (SilcIDListData)sock->user_data;
4633 SilcServer server = (SilcServer)idata->rekey->context;
4634 SilcProtocol protocol;
4635 SilcServerRekeyInternalContext *proto_ctx;
4637 SILC_LOG_DEBUG(("Start"));
4639 /* Allocate internal protocol context. This is sent as context
4641 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4642 proto_ctx->server = (void *)server;
4643 proto_ctx->sock = sock;
4644 proto_ctx->responder = FALSE;
4645 proto_ctx->pfs = idata->rekey->pfs;
4647 /* Perform rekey protocol. Will call the final callback after the
4648 protocol is over. */
4649 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4650 &protocol, proto_ctx, silc_server_rekey_final);
4651 sock->protocol = protocol;
4653 /* Run the protocol */
4654 silc_protocol_execute(protocol, server->schedule, 0, 0);
4656 /* Re-register re-key timeout */
4657 silc_schedule_task_add(server->schedule, sock->sock,
4658 silc_server_rekey_callback,
4659 context, idata->rekey->timeout, 0,
4660 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4663 /* The final callback for the REKEY protocol. This will actually take the
4664 new key material into use. */
4666 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4668 SilcProtocol protocol = (SilcProtocol)context;
4669 SilcServerRekeyInternalContext *ctx =
4670 (SilcServerRekeyInternalContext *)protocol->context;
4671 SilcServer server = (SilcServer)ctx->server;
4672 SilcSocketConnection sock = ctx->sock;
4674 SILC_LOG_DEBUG(("Start"));
4676 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4677 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4678 /* Error occured during protocol */
4679 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4680 silc_protocol_cancel(protocol, server->schedule);
4681 silc_protocol_free(protocol);
4682 sock->protocol = NULL;
4684 silc_packet_context_free(ctx->packet);
4686 silc_ske_free(ctx->ske);
4691 /* Purge the outgoing data queue to assure that all rekey packets really
4692 go to the network before we quit the protocol. */
4693 silc_server_packet_queue_purge(server, sock);
4696 silc_protocol_free(protocol);
4697 sock->protocol = NULL;
4699 silc_packet_context_free(ctx->packet);
4701 silc_ske_free(ctx->ske);
4705 /* Task callback used to retrieve network statistical information from
4706 router server once in a while. */
4708 SILC_TASK_CALLBACK(silc_server_get_stats)
4710 SilcServer server = (SilcServer)context;
4711 SilcBuffer idp, packet;
4713 SILC_LOG_DEBUG(("Retrieving stats from router"));
4715 if (!server->standalone) {
4716 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4717 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4718 ++server->cmd_ident, 1,
4719 1, idp->data, idp->len);
4720 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4721 SILC_PACKET_COMMAND, 0, packet->data,
4722 packet->len, FALSE);
4723 silc_buffer_free(packet);
4724 silc_buffer_free(idp);
4727 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4728 server, 120, 0, SILC_TASK_TIMEOUT,