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 /* We will lookup a fresh pointer later */
730 silc_server_config_unref(&sconn->conn);
732 /* Wait one before retrying */
733 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
734 context, sconn->retry_timeout, 0,
735 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
738 /* Generic routine to use connect to a router. */
740 SILC_TASK_CALLBACK(silc_server_connect_router)
742 SilcServerConnection sconn = (SilcServerConnection)context;
743 SilcServer server = sconn->server;
744 SilcServerConfigRouter *rconn;
747 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
748 (sconn->backup ? "backup router" : "router"),
749 sconn->remote_host, sconn->remote_port));
751 server->router_connect = time(NULL);
752 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
755 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
756 (sconn->backup ? "backup router" : "router"),
757 sconn->remote_host, sconn->remote_port));
758 silc_free(sconn->remote_host);
759 silc_free(sconn->backup_replace_ip);
763 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
765 /* Connect to remote host */
766 sock = silc_net_create_connection(
767 (!server->config->server_info->primary ? NULL :
768 server->config->server_info->primary->server_ip),
769 sconn->remote_port, sconn->remote_host);
771 SILC_LOG_ERROR(("Could not connect to router %s:%d",
772 sconn->remote_host, sconn->remote_port));
773 if (!sconn->no_reconnect)
774 silc_schedule_task_add(server->schedule, 0,
775 silc_server_connect_to_router_retry,
776 context, 0, 1, SILC_TASK_TIMEOUT,
777 SILC_TASK_PRI_NORMAL);
779 silc_server_config_unref(&sconn->conn);
783 /* Continue with key exchange protocol */
784 silc_server_start_key_exchange(server, sconn, sock);
787 /* This function connects to our primary router or if we are a router this
788 establishes all our primary routes. This is called at the start of the
789 server to do authentication and key exchange with our router - called
792 SILC_TASK_CALLBACK(silc_server_connect_to_router)
794 SilcServer server = (SilcServer)context;
795 SilcServerConnection sconn;
796 SilcServerConfigRouter *ptr;
798 SILC_LOG_DEBUG(("Connecting to router(s)"));
800 if (server->server_type == SILC_SERVER) {
801 SILC_LOG_DEBUG(("We are normal server"));
802 } else if (server->server_type == SILC_ROUTER) {
803 SILC_LOG_DEBUG(("We are router"));
805 SILC_LOG_DEBUG(("We are backup router/normal server"));
808 if (!server->config->routers) {
809 /* There wasn't a configured router, we will continue but we don't
810 have a connection to outside world. We will be standalone server. */
811 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
812 server->standalone = TRUE;
816 /* Cancel any possible retry timeouts */
817 silc_schedule_task_del_by_callback(server->schedule,
818 silc_server_connect_router);
819 silc_schedule_task_del_by_callback(server->schedule,
820 silc_server_connect_to_router_retry);
822 /* Create the connections to all our routes */
823 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
825 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
826 ptr->backup_router ? "Backup router" : "Router",
827 ptr->initiator ? "Initiator" : "Responder",
828 ptr->host, ptr->port));
830 if (ptr->initiator) {
831 /* Check whether we are connected to this host already */
832 if (silc_server_num_sockets_by_remote(server,
833 silc_net_is_ip(ptr->host) ?
835 silc_net_is_ip(ptr->host) ?
836 NULL : ptr->host, ptr->port,
837 SILC_SOCKET_TYPE_ROUTER)) {
838 SILC_LOG_DEBUG(("We are already connected to this router"));
842 /* Allocate connection object for hold connection specific stuff. */
843 sconn = silc_calloc(1, sizeof(*sconn));
844 sconn->server = server;
845 sconn->remote_host = strdup(ptr->host);
846 sconn->remote_port = ptr->port;
847 sconn->backup = ptr->backup_router;
849 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
850 sconn->backup_replace_port = ptr->backup_replace_port;
853 if (!server->router_conn && !sconn->backup)
854 server->router_conn = sconn;
856 silc_schedule_task_add(server->schedule, 0,
857 silc_server_connect_router,
858 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
859 SILC_TASK_PRI_NORMAL);
864 /* Second part of connecting to router(s). Key exchange protocol has been
865 executed and now we will execute authentication protocol. */
867 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
869 SilcProtocol protocol = (SilcProtocol)context;
870 SilcServerKEInternalContext *ctx =
871 (SilcServerKEInternalContext *)protocol->context;
872 SilcServer server = (SilcServer)ctx->server;
873 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
874 SilcSocketConnection sock = ctx->sock;
875 SilcServerConnAuthInternalContext *proto_ctx;
876 SilcServerConfigRouter *conn = NULL;
878 SILC_LOG_DEBUG(("Start"));
880 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
881 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
882 /* Error occured during protocol */
883 silc_protocol_free(protocol);
884 sock->protocol = NULL;
885 silc_ske_free_key_material(ctx->keymat);
887 silc_packet_context_free(ctx->packet);
889 silc_ske_free(ctx->ske);
890 silc_free(ctx->dest_id);
892 silc_server_config_unref(&sconn->conn);
893 silc_free(sconn->remote_host);
894 silc_free(sconn->backup_replace_ip);
896 silc_schedule_task_del_by_callback(server->schedule,
897 silc_server_failure_callback);
898 silc_server_disconnect_remote(server, sock,
899 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
903 /* We now have the key material as the result of the key exchange
904 protocol. Take the key material into use. Free the raw key material
905 as soon as we've set them into use. */
906 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
907 ctx->sock, ctx->keymat,
908 ctx->ske->prop->cipher,
909 ctx->ske->prop->pkcs,
910 ctx->ske->prop->hash,
911 ctx->ske->prop->hmac,
912 ctx->ske->prop->group,
914 silc_protocol_free(protocol);
915 sock->protocol = NULL;
916 silc_ske_free_key_material(ctx->keymat);
918 silc_packet_context_free(ctx->packet);
920 silc_ske_free(ctx->ske);
921 silc_free(ctx->dest_id);
923 silc_server_config_unref(&sconn->conn);
924 silc_free(sconn->remote_host);
925 silc_free(sconn->backup_replace_ip);
927 silc_schedule_task_del_by_callback(server->schedule,
928 silc_server_failure_callback);
929 silc_server_disconnect_remote(server, sock,
930 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
933 silc_ske_free_key_material(ctx->keymat);
935 /* Allocate internal context for the authentication protocol. This
936 is sent as context for the protocol. */
937 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
938 proto_ctx->server = (void *)server;
939 proto_ctx->context = (void *)sconn;
940 proto_ctx->sock = sock;
941 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
942 proto_ctx->dest_id_type = ctx->dest_id_type;
943 proto_ctx->dest_id = ctx->dest_id;
945 /* Resolve the authentication method used in this connection. Check if
946 we find a match from user configured connections */
947 if (!sconn->conn.ref_ptr)
948 conn = silc_server_config_find_router_conn(server, sock->hostname,
951 conn = sconn->conn.ref_ptr;
954 /* Match found. Use the configured authentication method. Take only
955 the passphrase, since for public key auth we automatically use
956 our local key pair. */
957 if (conn->passphrase) {
958 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
959 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
961 proto_ctx->auth_data = strdup(conn->passphrase);
962 proto_ctx->auth_data_len = strlen(conn->passphrase);
963 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
965 } else if (conn->publickeys) {
966 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
968 proto_ctx->auth_meth = SILC_AUTH_NONE;
971 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
972 sock->hostname, sock->ip, sock->port));
973 silc_protocol_free(protocol);
974 sock->protocol = NULL;
976 silc_packet_context_free(ctx->packet);
978 silc_ske_free(ctx->ske);
979 silc_free(ctx->dest_id);
981 silc_server_config_unref(&sconn->conn);
982 silc_free(sconn->remote_host);
983 silc_free(sconn->backup_replace_ip);
985 silc_schedule_task_del_by_callback(server->schedule,
986 silc_server_failure_callback);
987 silc_server_disconnect_remote(server, sock,
988 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
992 /* Free old protocol as it is finished now */
993 silc_protocol_free(protocol);
995 silc_packet_context_free(ctx->packet);
997 sock->protocol = NULL;
999 /* Allocate the authentication protocol. This is allocated here
1000 but we won't start it yet. We will be receiving party of this
1001 protocol thus we will wait that connecting party will make
1002 their first move. */
1003 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1004 &sock->protocol, proto_ctx,
1005 silc_server_connect_to_router_final);
1007 /* Register timeout task. If the protocol is not executed inside
1008 this timelimit the connection will be terminated. */
1009 proto_ctx->timeout_task =
1010 silc_schedule_task_add(server->schedule, sock->sock,
1011 silc_server_timeout_remote,
1013 server->config->conn_auth_timeout, 0,
1017 /* Run the protocol */
1018 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1021 /* Finalizes the connection to router. Registers a server task to the
1022 queue so that we can accept new connections. */
1024 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1026 SilcProtocol protocol = (SilcProtocol)context;
1027 SilcServerConnAuthInternalContext *ctx =
1028 (SilcServerConnAuthInternalContext *)protocol->context;
1029 SilcServer server = (SilcServer)ctx->server;
1030 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1031 SilcSocketConnection sock = ctx->sock;
1032 SilcServerEntry id_entry;
1034 SilcServerHBContext hb_context;
1035 unsigned char *id_string;
1037 SilcIDListData idata;
1038 SilcServerConfigRouter *conn = NULL;
1039 SilcServerConfigConnParams *param = NULL;
1041 SILC_LOG_DEBUG(("Start"));
1043 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1044 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1045 /* Error occured during protocol */
1046 silc_free(ctx->dest_id);
1047 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1052 /* Add a task to the queue. This task receives new connections to the
1053 server. This task remains on the queue until the end of the program. */
1054 if (!server->listenning && !sconn->backup) {
1055 silc_schedule_task_add(server->schedule, server->sock,
1056 silc_server_accept_new_connection,
1057 (void *)server, 0, 0,
1059 SILC_TASK_PRI_NORMAL);
1060 server->listenning = TRUE;
1063 /* Send NEW_SERVER packet to the router. We will become registered
1064 to the SILC network after sending this packet. */
1065 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1066 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1067 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1068 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1069 silc_buffer_format(packet,
1070 SILC_STR_UI_SHORT(id_len),
1071 SILC_STR_UI_XNSTRING(id_string, id_len),
1072 SILC_STR_UI_SHORT(strlen(server->server_name)),
1073 SILC_STR_UI_XNSTRING(server->server_name,
1074 strlen(server->server_name)),
1077 /* Send the packet */
1078 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1079 packet->data, packet->len, TRUE);
1080 silc_buffer_free(packet);
1081 silc_free(id_string);
1083 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1085 /* Check that we do not have this ID already */
1086 id_entry = silc_idlist_find_server_by_id(server->local_list,
1087 ctx->dest_id, TRUE, NULL);
1089 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1091 id_entry = silc_idlist_find_server_by_id(server->global_list,
1092 ctx->dest_id, TRUE, NULL);
1094 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1097 SILC_LOG_DEBUG(("New server id(%s)",
1098 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1100 /* Add the connected router to global server list */
1101 id_entry = silc_idlist_add_server(server->global_list,
1102 strdup(sock->hostname),
1103 SILC_ROUTER, ctx->dest_id, NULL, sock);
1105 silc_free(ctx->dest_id);
1106 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1107 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1112 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1113 silc_free(sock->user_data);
1114 sock->user_data = (void *)id_entry;
1115 sock->type = SILC_SOCKET_TYPE_ROUTER;
1116 idata = (SilcIDListData)sock->user_data;
1117 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1119 conn = sconn->conn.ref_ptr;
1120 param = &server->config->param;
1121 if (conn && conn->param)
1122 param = conn->param;
1124 /* Perform keepalive. The `hb_context' will be freed automatically
1125 when finally calling the silc_socket_free function. */
1126 hb_context = silc_calloc(1, sizeof(*hb_context));
1127 hb_context->server = server;
1128 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1129 silc_server_perform_heartbeat,
1132 /* Register re-key timeout */
1133 idata->rekey->timeout = param->key_exchange_rekey;
1134 idata->rekey->context = (void *)server;
1135 silc_schedule_task_add(server->schedule, sock->sock,
1136 silc_server_rekey_callback,
1137 (void *)sock, idata->rekey->timeout, 0,
1138 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1140 if (!sconn->backup) {
1141 /* Mark this router our primary router if we're still standalone */
1142 if (server->standalone) {
1143 server->id_entry->router = id_entry;
1144 server->router = id_entry;
1145 server->standalone = FALSE;
1147 /* If we are router then announce our possible servers. */
1148 if (server->server_type == SILC_ROUTER)
1149 silc_server_announce_servers(server, FALSE, 0,
1150 server->router->connection);
1152 /* Announce our clients and channels to the router */
1153 silc_server_announce_clients(server, 0, server->router->connection);
1154 silc_server_announce_channels(server, 0, server->router->connection);
1156 #ifdef BACKUP_SINGLE_ROUTER
1157 /* If we are backup router then this primary router is whom we are
1159 if (server->server_type == SILC_BACKUP_ROUTER)
1160 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1161 #endif /* BACKUP_SINGLE_ROUTER */
1164 /* Add this server to be our backup router */
1165 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1166 sconn->backup_replace_port, FALSE);
1169 sock->protocol = NULL;
1171 /* Call the completion callback to indicate that we've connected to
1173 if (sconn->callback)
1174 (*sconn->callback)(server, id_entry, sconn->callback_context);
1177 /* Free the temporary connection data context */
1179 silc_server_config_unref(&sconn->conn);
1180 silc_free(sconn->remote_host);
1181 silc_free(sconn->backup_replace_ip);
1184 if (sconn == server->router_conn)
1185 server->router_conn = NULL;
1187 /* Free the protocol object */
1188 if (sock->protocol == protocol)
1189 sock->protocol = NULL;
1190 silc_protocol_free(protocol);
1192 silc_packet_context_free(ctx->packet);
1194 silc_ske_free(ctx->ske);
1195 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1196 silc_free(ctx->auth_data);
1200 /* Host lookup callback that is called after the incoming connection's
1201 IP and FQDN lookup is performed. This will actually check the acceptance
1202 of the incoming connection and will register the key exchange protocol
1203 for this connection. */
1206 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1209 SilcServerKEInternalContext *proto_ctx =
1210 (SilcServerKEInternalContext *)context;
1211 SilcServer server = (SilcServer)proto_ctx->server;
1212 SilcServerConfigClient *cconfig = NULL;
1213 SilcServerConfigServer *sconfig = NULL;
1214 SilcServerConfigRouter *rconfig = NULL;
1215 SilcServerConfigDeny *deny;
1218 context = (void *)server;
1220 /* Check whether we could resolve both IP and FQDN. */
1221 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1222 server->config->require_reverse_lookup)) {
1223 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1224 sock->hostname ? sock->hostname :
1225 sock->ip ? sock->ip : ""));
1226 server->stat.conn_failures++;
1227 silc_server_disconnect_remote(server, sock,
1228 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1229 "Unknown host or IP");
1230 silc_free(proto_ctx);
1234 /* Register the connection for network input and output. This sets
1235 that scheduler will listen for incoming packets for this connection
1236 and sets that outgoing packets may be sent to this connection as well.
1237 However, this doesn't set the scheduler for outgoing traffic, it
1238 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1239 later when outgoing data is available. */
1240 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1242 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1245 /* Listenning port */
1246 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1247 silc_server_disconnect_remote(server, sock,
1248 SILC_STATUS_ERR_RESOURCE_LIMIT,
1249 "Connection refused");
1250 server->stat.conn_failures++;
1251 silc_free(proto_ctx);
1254 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1256 /* Check whether this connection is denied to connect to us. */
1257 deny = silc_server_config_find_denied(server, sock->ip);
1259 deny = silc_server_config_find_denied(server, sock->hostname);
1261 /* The connection is denied */
1262 SILC_LOG_INFO(("Connection %s (%s) is denied",
1263 sock->hostname, sock->ip));
1264 silc_server_disconnect_remote(server, sock,
1265 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1267 server->stat.conn_failures++;
1268 silc_free(proto_ctx);
1272 /* Check whether we have configured this sort of connection at all. We
1273 have to check all configurations since we don't know what type of
1274 connection this is. */
1275 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1276 cconfig = silc_server_config_find_client(server, sock->hostname);
1277 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1278 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1279 if (server->server_type == SILC_ROUTER) {
1280 if (!(rconfig = silc_server_config_find_router_conn(server,
1281 sock->ip, sock->port)))
1282 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1285 if (!cconfig && !sconfig && !rconfig) {
1286 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1288 silc_server_disconnect_remote(server, sock,
1289 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1290 server->stat.conn_failures++;
1291 silc_free(proto_ctx);
1295 /* The connection is allowed */
1297 /* Set internal context for key exchange protocol. This is
1298 sent as context for the protocol. */
1299 proto_ctx->sock = sock;
1300 proto_ctx->rng = server->rng;
1301 proto_ctx->responder = TRUE;
1302 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1303 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1304 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1306 /* Take flags for key exchange. Since we do not know what type of connection
1307 this is, we go through all found configurations and use the global ones
1308 as well. This will result always into strictest key exchange flags. */
1309 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1310 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1311 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1312 if (server->config->param.key_exchange_pfs)
1313 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1315 /* Prepare the connection for key exchange protocol. We allocate the
1316 protocol but will not start it yet. The connector will be the
1317 initiator of the protocol thus we will wait for initiation from
1318 there before we start the protocol. */
1319 server->stat.auth_attempts++;
1320 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1321 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1322 &sock->protocol, proto_ctx,
1323 silc_server_accept_new_connection_second);
1325 /* Register a timeout task that will be executed if the connector
1326 will not start the key exchange protocol within specified timeout
1327 and the connection will be closed. */
1328 proto_ctx->timeout_task =
1329 silc_schedule_task_add(server->schedule, sock->sock,
1330 silc_server_timeout_remote,
1332 server->config->key_exchange_timeout, 0,
1337 /* Accepts new connections to the server. Accepting new connections are
1338 done in three parts to make it async. */
1340 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1342 SilcServer server = (SilcServer)context;
1343 SilcSocketConnection newsocket;
1344 SilcServerKEInternalContext *proto_ctx;
1347 SILC_LOG_DEBUG(("Accepting new connection"));
1349 server->stat.conn_attempts++;
1351 sock = silc_net_accept_connection(fd);
1353 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1354 server->stat.conn_failures++;
1358 /* Check for maximum allowed connections */
1359 if (sock > server->config->param.connections_max) {
1360 SILC_LOG_ERROR(("Refusing connection, server is full"));
1361 server->stat.conn_failures++;
1362 silc_net_close_connection(sock);
1366 /* Set socket options */
1367 silc_net_set_socket_nonblock(sock);
1368 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1370 /* We don't create a ID yet, since we don't know what type of connection
1371 this is yet. But, we do add the connection to the socket table. */
1372 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1373 server->sockets[sock] = newsocket;
1375 /* Perform asynchronous host lookup. This will lookup the IP and the
1376 FQDN of the remote connection. After the lookup is done the connection
1377 is accepted further. */
1378 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1379 proto_ctx->server = server;
1380 proto_ctx->context = (void *)fd;
1381 silc_socket_host_lookup(newsocket, TRUE,
1382 silc_server_accept_new_connection_lookup,
1383 (void *)proto_ctx, server->schedule);
1386 /* Second part of accepting new connection. Key exchange protocol has been
1387 performed and now it is time to do little connection authentication
1388 protocol to figure out whether this connection is client or server
1389 and whether it has right to access this server (especially server
1390 connections needs to be authenticated). */
1392 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1394 SilcProtocol protocol = (SilcProtocol)context;
1395 SilcServerKEInternalContext *ctx =
1396 (SilcServerKEInternalContext *)protocol->context;
1397 SilcServer server = (SilcServer)ctx->server;
1398 SilcSocketConnection sock = ctx->sock;
1399 SilcServerConnAuthInternalContext *proto_ctx;
1401 SILC_LOG_DEBUG(("Start"));
1403 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1404 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1405 /* Error occured during protocol */
1406 SILC_LOG_DEBUG(("Error key exchange protocol"));
1407 silc_protocol_free(protocol);
1408 sock->protocol = NULL;
1409 silc_ske_free_key_material(ctx->keymat);
1411 silc_packet_context_free(ctx->packet);
1413 silc_ske_free(ctx->ske);
1414 silc_free(ctx->dest_id);
1415 silc_server_config_unref(&ctx->cconfig);
1416 silc_server_config_unref(&ctx->sconfig);
1417 silc_server_config_unref(&ctx->rconfig);
1419 silc_schedule_task_del_by_callback(server->schedule,
1420 silc_server_failure_callback);
1421 silc_server_disconnect_remote(server, sock,
1422 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1424 server->stat.auth_failures++;
1428 /* We now have the key material as the result of the key exchange
1429 protocol. Take the key material into use. Free the raw key material
1430 as soon as we've set them into use. */
1431 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1432 ctx->sock, ctx->keymat,
1433 ctx->ske->prop->cipher,
1434 ctx->ske->prop->pkcs,
1435 ctx->ske->prop->hash,
1436 ctx->ske->prop->hmac,
1437 ctx->ske->prop->group,
1439 SILC_LOG_ERROR(("Error setting key material in use"));
1440 silc_protocol_free(protocol);
1441 sock->protocol = NULL;
1442 silc_ske_free_key_material(ctx->keymat);
1444 silc_packet_context_free(ctx->packet);
1446 silc_ske_free(ctx->ske);
1447 silc_free(ctx->dest_id);
1448 silc_server_config_unref(&ctx->cconfig);
1449 silc_server_config_unref(&ctx->sconfig);
1450 silc_server_config_unref(&ctx->rconfig);
1452 silc_schedule_task_del_by_callback(server->schedule,
1453 silc_server_failure_callback);
1454 silc_server_disconnect_remote(server, sock,
1455 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1456 server->stat.auth_failures++;
1459 silc_ske_free_key_material(ctx->keymat);
1461 /* Allocate internal context for the authentication protocol. This
1462 is sent as context for the protocol. */
1463 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1464 proto_ctx->server = (void *)server;
1465 proto_ctx->sock = sock;
1466 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1467 proto_ctx->responder = TRUE;
1468 proto_ctx->dest_id_type = ctx->dest_id_type;
1469 proto_ctx->dest_id = ctx->dest_id;
1470 proto_ctx->cconfig = ctx->cconfig;
1471 proto_ctx->sconfig = ctx->sconfig;
1472 proto_ctx->rconfig = ctx->rconfig;
1474 /* Free old protocol as it is finished now */
1475 silc_protocol_free(protocol);
1477 silc_packet_context_free(ctx->packet);
1479 sock->protocol = NULL;
1481 /* Allocate the authentication protocol. This is allocated here
1482 but we won't start it yet. We will be receiving party of this
1483 protocol thus we will wait that connecting party will make
1484 their first move. */
1485 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1486 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1487 &sock->protocol, proto_ctx,
1488 silc_server_accept_new_connection_final);
1490 /* Register timeout task. If the protocol is not executed inside
1491 this timelimit the connection will be terminated. */
1492 proto_ctx->timeout_task =
1493 silc_schedule_task_add(server->schedule, sock->sock,
1494 silc_server_timeout_remote,
1496 server->config->conn_auth_timeout, 0,
1501 /* Final part of accepting new connection. The connection has now
1502 been authenticated and keys has been exchanged. We also know whether
1503 this is client or server connection. */
1505 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1507 SilcProtocol protocol = (SilcProtocol)context;
1508 SilcServerConnAuthInternalContext *ctx =
1509 (SilcServerConnAuthInternalContext *)protocol->context;
1510 SilcServer server = (SilcServer)ctx->server;
1511 SilcSocketConnection sock = ctx->sock;
1512 SilcServerHBContext hb_context;
1513 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1515 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1517 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1518 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1519 /* Error occured during protocol */
1520 SILC_LOG_DEBUG(("Error during authentication protocol"));
1521 silc_protocol_free(protocol);
1522 sock->protocol = NULL;
1524 silc_packet_context_free(ctx->packet);
1526 silc_ske_free(ctx->ske);
1527 silc_free(ctx->dest_id);
1528 silc_server_config_unref(&ctx->cconfig);
1529 silc_server_config_unref(&ctx->sconfig);
1530 silc_server_config_unref(&ctx->rconfig);
1532 silc_schedule_task_del_by_callback(server->schedule,
1533 silc_server_failure_callback);
1534 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1536 server->stat.auth_failures++;
1540 entry->data.last_receive = time(NULL);
1542 switch (ctx->conn_type) {
1543 case SILC_SOCKET_TYPE_CLIENT:
1545 SilcClientEntry client;
1546 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1548 /* Verify whether this connection is after all allowed to connect */
1549 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1550 &server->config->param,
1551 conn->param, ctx->ske)) {
1552 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1554 silc_server_disconnect_remote(server, sock,
1555 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1557 server->stat.auth_failures++;
1561 SILC_LOG_DEBUG(("Remote host is client"));
1562 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1565 /* Add the client to the client ID cache. The nickname and Client ID
1566 and other information is created after we have received NEW_CLIENT
1567 packet from client. */
1568 client = silc_idlist_add_client(server->local_list,
1569 NULL, NULL, NULL, NULL, NULL, sock, 0);
1571 SILC_LOG_ERROR(("Could not add new client to cache"));
1572 silc_free(sock->user_data);
1573 silc_server_disconnect_remote(server, sock,
1574 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1575 server->stat.auth_failures++;
1580 server->stat.my_clients++;
1581 server->stat.clients++;
1582 server->stat.cell_clients++;
1584 /* Get connection parameters */
1586 if (conn->param->keepalive_secs)
1587 hearbeat_timeout = conn->param->keepalive_secs;
1590 id_entry = (void *)client;
1593 case SILC_SOCKET_TYPE_SERVER:
1594 case SILC_SOCKET_TYPE_ROUTER:
1596 SilcServerEntry new_server;
1597 bool initiator = FALSE;
1598 bool backup_local = FALSE;
1599 bool backup_router = FALSE;
1600 char *backup_replace_ip = NULL;
1601 SilcUInt16 backup_replace_port = 0;
1602 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1603 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1605 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1606 /* Verify whether this connection is after all allowed to connect */
1607 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1608 &server->config->param,
1609 rconn ? rconn->param : NULL,
1611 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1613 silc_server_disconnect_remote(server, sock,
1614 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1616 server->stat.auth_failures++;
1622 if (rconn->param->keepalive_secs)
1623 hearbeat_timeout = rconn->param->keepalive_secs;
1626 initiator = rconn->initiator;
1627 backup_local = rconn->backup_local;
1628 backup_router = rconn->backup_router;
1629 backup_replace_ip = rconn->backup_replace_ip;
1630 backup_replace_port = rconn->backup_replace_port;
1634 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1635 /* Verify whether this connection is after all allowed to connect */
1636 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1637 &server->config->param,
1638 sconn ? sconn->param : NULL,
1640 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1642 silc_server_disconnect_remote(server, sock,
1643 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1645 server->stat.auth_failures++;
1650 if (sconn->param->keepalive_secs)
1651 hearbeat_timeout = sconn->param->keepalive_secs;
1654 backup_router = sconn->backup_router;
1658 SILC_LOG_DEBUG(("Remote host is %s",
1659 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1660 "server" : (backup_router ?
1661 "backup router" : "router")));
1662 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1663 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1664 "server" : (backup_router ?
1665 "backup router" : "router")));
1667 /* Add the server into server cache. The server name and Server ID
1668 is updated after we have received NEW_SERVER packet from the
1669 server. We mark ourselves as router for this server if we really
1672 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1673 server->local_list : (backup_router ?
1674 server->local_list :
1675 server->global_list)),
1677 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1678 SILC_SERVER : SILC_ROUTER),
1680 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1681 server->id_entry : (backup_router ?
1682 server->id_entry : NULL)),
1685 SILC_LOG_ERROR(("Could not add new server to cache"));
1686 silc_free(sock->user_data);
1687 silc_server_disconnect_remote(server, sock,
1688 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1689 server->stat.auth_failures++;
1694 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1695 server->stat.my_servers++;
1697 server->stat.my_routers++;
1698 server->stat.routers++;
1700 server->stat.servers++;
1702 id_entry = (void *)new_server;
1704 /* If the incoming connection is router and marked as backup router
1705 then add it to be one of our backups */
1706 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1707 silc_server_backup_add(server, new_server, backup_replace_ip,
1708 backup_replace_port, backup_local);
1710 /* Change it back to SERVER type since that's what it really is. */
1712 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1714 new_server->server_type = SILC_BACKUP_ROUTER;
1717 /* Check whether this connection is to be our primary router connection
1718 if we do not already have the primary route. */
1719 if (!backup_router &&
1720 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1721 if (silc_server_config_is_primary_route(server) && !initiator)
1724 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1725 server->standalone = FALSE;
1726 if (!server->id_entry->router) {
1727 server->id_entry->router = id_entry;
1728 server->router = id_entry;
1739 sock->type = ctx->conn_type;
1741 /* Add the common data structure to the ID entry. */
1742 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1744 /* Add to sockets internal pointer for fast referencing */
1745 silc_free(sock->user_data);
1746 sock->user_data = id_entry;
1748 /* Connection has been fully established now. Everything is ok. */
1749 SILC_LOG_DEBUG(("New connection authenticated"));
1751 /* Perform keepalive. The `hb_context' will be freed automatically
1752 when finally calling the silc_socket_free function. */
1753 hb_context = silc_calloc(1, sizeof(*hb_context));
1754 hb_context->server = server;
1755 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1756 silc_server_perform_heartbeat,
1760 silc_schedule_task_del_by_callback(server->schedule,
1761 silc_server_failure_callback);
1762 silc_protocol_free(protocol);
1764 silc_packet_context_free(ctx->packet);
1766 silc_ske_free(ctx->ske);
1767 silc_free(ctx->dest_id);
1768 silc_server_config_unref(&ctx->cconfig);
1769 silc_server_config_unref(&ctx->sconfig);
1770 silc_server_config_unref(&ctx->rconfig);
1772 sock->protocol = NULL;
1775 /* This function is used to read packets from network and send packets to
1776 network. This is usually a generic task. */
1778 SILC_TASK_CALLBACK(silc_server_packet_process)
1780 SilcServer server = (SilcServer)context;
1781 SilcSocketConnection sock = server->sockets[fd];
1782 SilcIDListData idata;
1783 SilcCipher cipher = NULL;
1784 SilcHmac hmac = NULL;
1785 SilcUInt32 sequence = 0;
1789 SILC_LOG_DEBUG(("Unknown socket connection"));
1793 /* Packet sending */
1795 if (type == SILC_TASK_WRITE) {
1796 /* Do not send data to disconnected connection */
1797 if (SILC_IS_DISCONNECTED(sock)) {
1798 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
1802 server->stat.packets_sent++;
1804 /* Send the packet */
1805 ret = silc_packet_send(sock, TRUE);
1807 /* If returned -2 could not write to connection now, will do
1813 SILC_LOG_ERROR(("Error sending packet to connection "
1814 "%s:%d [%s]", sock->hostname, sock->port,
1815 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1816 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1817 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1822 /* The packet has been sent and now it is time to set the connection
1823 back to only for input. When there is again some outgoing data
1824 available for this connection it will be set for output as well.
1825 This call clears the output setting and sets it only for input. */
1826 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1827 SILC_UNSET_OUTBUF_PENDING(sock);
1829 silc_buffer_clear(sock->outbuf);
1833 /* Packet receiving */
1835 /* Read some data from connection */
1836 ret = silc_packet_receive(sock);
1840 SILC_LOG_ERROR(("Error receiving packet from connection "
1841 "%s:%d [%s] %s", sock->hostname, sock->port,
1842 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1843 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1844 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1845 "Router"), strerror(errno)));
1851 SILC_LOG_DEBUG(("Read EOF"));
1853 /* If connection is disconnecting already we will finally
1854 close the connection */
1855 if (SILC_IS_DISCONNECTING(sock)) {
1856 if (sock->user_data)
1857 silc_server_free_sock_user_data(server, sock, NULL);
1858 silc_server_close_connection(server, sock);
1862 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1863 SILC_SET_DISCONNECTING(sock);
1865 if (sock->user_data) {
1867 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1868 silc_server_free_sock_user_data(server, sock, tmp);
1870 silc_server_free_sock_user_data(server, sock, NULL);
1871 } else if (server->router_conn && server->router_conn->sock == sock &&
1872 !server->router && server->standalone)
1873 silc_schedule_task_add(server->schedule, 0,
1874 silc_server_connect_to_router,
1877 SILC_TASK_PRI_NORMAL);
1879 silc_server_close_connection(server, sock);
1883 /* If connection is disconnecting or disconnected we will ignore
1885 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1886 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1890 server->stat.packets_received++;
1892 /* Get keys and stuff from ID entry */
1893 idata = (SilcIDListData)sock->user_data;
1895 cipher = idata->receive_key;
1896 hmac = idata->hmac_receive;
1897 sequence = idata->psn_receive;
1900 /* Process the packet. This will call the parser that will then
1901 decrypt and parse the packet. */
1902 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1903 TRUE : FALSE, cipher, hmac, sequence,
1904 silc_server_packet_parse, server);
1906 /* If this socket connection is not authenticated yet and the packet
1907 processing failed we will drop the connection since it can be
1908 a malicious flooder. */
1909 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1910 (!sock->protocol || sock->protocol->protocol->type ==
1911 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1912 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1913 SILC_SET_DISCONNECTING(sock);
1915 if (sock->user_data)
1916 silc_server_free_sock_user_data(server, sock, NULL);
1917 silc_server_close_connection(server, sock);
1921 /* Parses whole packet, received earlier. */
1923 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1925 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1926 SilcServer server = (SilcServer)parse_ctx->context;
1927 SilcSocketConnection sock = parse_ctx->sock;
1928 SilcPacketContext *packet = parse_ctx->packet;
1929 SilcIDListData idata = (SilcIDListData)sock->user_data;
1932 SILC_LOG_DEBUG(("Parsing packet"));
1934 /* Parse the packet */
1935 if (parse_ctx->normal)
1936 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1938 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1940 /* If entry is disabled ignore what we got. */
1941 if (ret != SILC_PACKET_RESUME_ROUTER &&
1942 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1943 SILC_LOG_DEBUG(("Connection is disabled"));
1947 if (ret == SILC_PACKET_NONE)
1950 /* Check that the the current client ID is same as in the client's packet. */
1951 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1952 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1953 if (client && client->id) {
1954 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1955 packet->src_id_type);
1956 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1964 if (server->server_type == SILC_ROUTER) {
1965 /* Route the packet if it is not destined to us. Other ID types but
1966 server are handled separately after processing them. */
1967 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1968 packet->dst_id_type == SILC_ID_SERVER &&
1969 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1970 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1972 /* Route the packet to fastest route for the destination ID */
1973 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1974 packet->dst_id_type);
1977 silc_server_packet_route(server,
1978 silc_server_route_get(server, id,
1979 packet->dst_id_type),
1986 /* Parse the incoming packet type */
1987 silc_server_packet_parse_type(server, sock, packet);
1989 if (server->server_type == SILC_ROUTER) {
1990 /* Broadcast packet if it is marked as broadcast packet and it is
1991 originated from router and we are router. */
1992 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1993 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1994 !server->standalone) {
1995 /* Broadcast to our primary route */
1996 silc_server_packet_broadcast(server, server->router->connection, packet);
1998 /* If we have backup routers then we need to feed all broadcast
1999 data to those servers. */
2000 silc_server_backup_broadcast(server, sock, packet);
2005 silc_packet_context_free(packet);
2006 silc_free(parse_ctx);
2009 /* Parser callback called by silc_packet_receive_process. This merely
2010 registers timeout that will handle the actual parsing when appropriate. */
2012 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2015 SilcServer server = (SilcServer)context;
2016 SilcSocketConnection sock = parser_context->sock;
2017 SilcIDListData idata = (SilcIDListData)sock->user_data;
2020 idata->psn_receive = parser_context->packet->sequence + 1;
2022 /* If protocol for this connection is key exchange or rekey then we'll
2023 process all packets synchronously, since there might be packets in
2024 queue that we are not able to decrypt without first processing the
2025 packets before them. */
2026 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2027 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2028 (sock->protocol && sock->protocol->protocol &&
2029 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2030 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2031 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2034 /* Reprocess data since we'll return FALSE here. This is because
2035 the idata->receive_key might have become valid in the last packet
2036 and we want to call this processor with valid cipher. */
2038 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2039 TRUE : FALSE, idata->receive_key,
2040 idata->hmac_receive, idata->psn_receive,
2041 silc_server_packet_parse, server);
2043 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2044 TRUE : FALSE, NULL, NULL, 0,
2045 silc_server_packet_parse, server);
2049 switch (sock->type) {
2050 case SILC_SOCKET_TYPE_UNKNOWN:
2051 case SILC_SOCKET_TYPE_CLIENT:
2052 /* Parse the packet with timeout */
2053 silc_schedule_task_add(server->schedule, sock->sock,
2054 silc_server_packet_parse_real,
2055 (void *)parser_context, 0, 100000,
2057 SILC_TASK_PRI_NORMAL);
2059 case SILC_SOCKET_TYPE_SERVER:
2060 case SILC_SOCKET_TYPE_ROUTER:
2061 /* Packets from servers are parsed immediately */
2062 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2072 /* Parses the packet type and calls what ever routines the packet type
2073 requires. This is done for all incoming packets. */
2075 void silc_server_packet_parse_type(SilcServer server,
2076 SilcSocketConnection sock,
2077 SilcPacketContext *packet)
2079 SilcPacketType type = packet->type;
2080 SilcIDListData idata = (SilcIDListData)sock->user_data;
2082 /* Parse the packet type */
2084 case SILC_PACKET_DISCONNECT:
2087 char *message = NULL;
2089 SILC_LOG_DEBUG(("Disconnect packet"));
2091 if (packet->flags & SILC_PACKET_FLAG_LIST)
2093 if (packet->buffer->len < 1)
2096 status = (SilcStatus)packet->buffer->data[0];
2097 if (packet->buffer->len > 1 &&
2098 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2099 message = silc_memdup(packet->buffer->data + 1,
2100 packet->buffer->len - 1);
2102 SILC_LOG_ERROR(("Disconnected by %s (%s): %s (%d) %s",
2103 sock->ip, sock->hostname,
2104 silc_get_status_message(status), status,
2105 message ? message : ""));
2110 case SILC_PACKET_SUCCESS:
2112 * Success received for something. For now we can have only
2113 * one protocol for connection executing at once hence this
2114 * success message is for whatever protocol is executing currently.
2116 SILC_LOG_DEBUG(("Success packet"));
2117 if (packet->flags & SILC_PACKET_FLAG_LIST)
2120 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2123 case SILC_PACKET_FAILURE:
2125 * Failure received for something. For now we can have only
2126 * one protocol for connection executing at once hence this
2127 * failure message is for whatever protocol is executing currently.
2129 SILC_LOG_DEBUG(("Failure packet"));
2130 if (packet->flags & SILC_PACKET_FLAG_LIST)
2132 if (sock->protocol) {
2133 SilcServerFailureContext f;
2134 f = silc_calloc(1, sizeof(*f));
2138 /* We will wait 5 seconds to process this failure packet */
2139 silc_schedule_task_add(server->schedule, sock->sock,
2140 silc_server_failure_callback, (void *)f, 5, 0,
2141 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2145 case SILC_PACKET_REJECT:
2146 SILC_LOG_DEBUG(("Reject packet"));
2147 if (packet->flags & SILC_PACKET_FLAG_LIST)
2152 case SILC_PACKET_NOTIFY:
2154 * Received notify packet. Server can receive notify packets from
2155 * router. Server then relays the notify messages to clients if needed.
2157 SILC_LOG_DEBUG(("Notify packet"));
2158 if (packet->flags & SILC_PACKET_FLAG_LIST)
2159 silc_server_notify_list(server, sock, packet);
2161 silc_server_notify(server, sock, packet);
2167 case SILC_PACKET_CHANNEL_MESSAGE:
2169 * Received channel message. Channel messages are special packets
2170 * (although probably most common ones) thus they are handled
2173 SILC_LOG_DEBUG(("Channel Message packet"));
2174 if (packet->flags & SILC_PACKET_FLAG_LIST)
2176 idata->last_receive = time(NULL);
2177 silc_server_channel_message(server, sock, packet);
2180 case SILC_PACKET_CHANNEL_KEY:
2182 * Received key for channel. As channels are created by the router
2183 * the keys are as well. We will distribute the key to all of our
2184 * locally connected clients on the particular channel. Router
2185 * never receives this channel and thus is ignored.
2187 SILC_LOG_DEBUG(("Channel Key packet"));
2188 if (packet->flags & SILC_PACKET_FLAG_LIST)
2190 silc_server_channel_key(server, sock, packet);
2196 case SILC_PACKET_COMMAND:
2198 * Recived command. Processes the command request and allocates the
2199 * command context and calls the command.
2201 SILC_LOG_DEBUG(("Command packet"));
2202 if (packet->flags & SILC_PACKET_FLAG_LIST)
2204 silc_server_command_process(server, sock, packet);
2207 case SILC_PACKET_COMMAND_REPLY:
2209 * Received command reply packet. Received command reply to command. It
2210 * may be reply to command sent by us or reply to command sent by client
2211 * that we've routed further.
2213 SILC_LOG_DEBUG(("Command Reply packet"));
2214 if (packet->flags & SILC_PACKET_FLAG_LIST)
2216 silc_server_command_reply(server, sock, packet);
2220 * Private Message packets
2222 case SILC_PACKET_PRIVATE_MESSAGE:
2224 * Received private message packet. The packet is coming from either
2227 SILC_LOG_DEBUG(("Private Message packet"));
2228 if (packet->flags & SILC_PACKET_FLAG_LIST)
2230 idata->last_receive = time(NULL);
2231 silc_server_private_message(server, sock, packet);
2234 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2236 * Private message key packet.
2238 if (packet->flags & SILC_PACKET_FLAG_LIST)
2240 silc_server_private_message_key(server, sock, packet);
2244 * Key Exchange protocol packets
2246 case SILC_PACKET_KEY_EXCHANGE:
2247 SILC_LOG_DEBUG(("KE packet"));
2248 if (packet->flags & SILC_PACKET_FLAG_LIST)
2251 if (sock->protocol && sock->protocol->protocol &&
2252 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2253 SilcServerKEInternalContext *proto_ctx =
2254 (SilcServerKEInternalContext *)sock->protocol->context;
2256 proto_ctx->packet = silc_packet_context_dup(packet);
2258 /* Let the protocol handle the packet */
2259 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2261 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2262 "protocol active, packet dropped."));
2266 case SILC_PACKET_KEY_EXCHANGE_1:
2267 SILC_LOG_DEBUG(("KE 1 packet"));
2268 if (packet->flags & SILC_PACKET_FLAG_LIST)
2271 if (sock->protocol && sock->protocol->protocol &&
2272 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2273 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2275 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2276 SilcServerRekeyInternalContext *proto_ctx =
2277 (SilcServerRekeyInternalContext *)sock->protocol->context;
2279 if (proto_ctx->packet)
2280 silc_packet_context_free(proto_ctx->packet);
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, 0);
2287 SilcServerKEInternalContext *proto_ctx =
2288 (SilcServerKEInternalContext *)sock->protocol->context;
2290 if (proto_ctx->packet)
2291 silc_packet_context_free(proto_ctx->packet);
2293 proto_ctx->packet = silc_packet_context_dup(packet);
2294 proto_ctx->dest_id_type = packet->src_id_type;
2295 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2296 packet->src_id_type);
2297 if (!proto_ctx->dest_id)
2300 /* Let the protocol handle the packet */
2301 silc_protocol_execute(sock->protocol, server->schedule,
2305 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2306 "protocol active, packet dropped."));
2310 case SILC_PACKET_KEY_EXCHANGE_2:
2311 SILC_LOG_DEBUG(("KE 2 packet"));
2312 if (packet->flags & SILC_PACKET_FLAG_LIST)
2315 if (sock->protocol && sock->protocol->protocol &&
2316 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2317 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2319 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2320 SilcServerRekeyInternalContext *proto_ctx =
2321 (SilcServerRekeyInternalContext *)sock->protocol->context;
2323 if (proto_ctx->packet)
2324 silc_packet_context_free(proto_ctx->packet);
2326 proto_ctx->packet = silc_packet_context_dup(packet);
2328 /* Let the protocol handle the packet */
2329 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2331 SilcServerKEInternalContext *proto_ctx =
2332 (SilcServerKEInternalContext *)sock->protocol->context;
2334 if (proto_ctx->packet)
2335 silc_packet_context_free(proto_ctx->packet);
2337 proto_ctx->packet = silc_packet_context_dup(packet);
2338 proto_ctx->dest_id_type = packet->src_id_type;
2339 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2340 packet->src_id_type);
2341 if (!proto_ctx->dest_id)
2344 /* Let the protocol handle the packet */
2345 silc_protocol_execute(sock->protocol, server->schedule,
2349 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2350 "protocol active, packet dropped."));
2354 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2356 * Connection authentication request packet. When we receive this packet
2357 * we will send to the other end information about our mandatory
2358 * authentication method for the connection. This packet maybe received
2361 SILC_LOG_DEBUG(("Connection authentication request packet"));
2362 if (packet->flags & SILC_PACKET_FLAG_LIST)
2364 silc_server_connection_auth_request(server, sock, packet);
2368 * Connection Authentication protocol packets
2370 case SILC_PACKET_CONNECTION_AUTH:
2371 /* Start of the authentication protocol. We receive here the
2372 authentication data and will verify it. */
2373 SILC_LOG_DEBUG(("Connection auth packet"));
2374 if (packet->flags & SILC_PACKET_FLAG_LIST)
2377 if (sock->protocol && sock->protocol->protocol->type
2378 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2380 SilcServerConnAuthInternalContext *proto_ctx =
2381 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2383 proto_ctx->packet = silc_packet_context_dup(packet);
2385 /* Let the protocol handle the packet */
2386 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2388 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2389 "protocol active, packet dropped."));
2393 case SILC_PACKET_NEW_ID:
2395 * Received New ID packet. This includes some new ID that has been
2396 * created. It may be for client, server or channel. This is the way
2397 * to distribute information about new registered entities in the
2400 SILC_LOG_DEBUG(("New ID packet"));
2401 if (packet->flags & SILC_PACKET_FLAG_LIST)
2402 silc_server_new_id_list(server, sock, packet);
2404 silc_server_new_id(server, sock, packet);
2407 case SILC_PACKET_NEW_CLIENT:
2409 * Received new client packet. This includes client information that
2410 * we will use to create initial client ID. After creating new
2411 * ID we will send it to the client.
2413 SILC_LOG_DEBUG(("New Client packet"));
2414 if (packet->flags & SILC_PACKET_FLAG_LIST)
2416 silc_server_new_client(server, sock, packet);
2419 case SILC_PACKET_NEW_SERVER:
2421 * Received new server packet. This includes Server ID and some other
2422 * information that we may save. This is received after server has
2425 SILC_LOG_DEBUG(("New Server packet"));
2426 if (packet->flags & SILC_PACKET_FLAG_LIST)
2428 silc_server_new_server(server, sock, packet);
2431 case SILC_PACKET_NEW_CHANNEL:
2433 * Received new channel packet. Information about new channel in the
2434 * network are distributed using this packet.
2436 SILC_LOG_DEBUG(("New Channel packet"));
2437 if (packet->flags & SILC_PACKET_FLAG_LIST)
2438 silc_server_new_channel_list(server, sock, packet);
2440 silc_server_new_channel(server, sock, packet);
2443 case SILC_PACKET_HEARTBEAT:
2445 * Received heartbeat.
2447 SILC_LOG_DEBUG(("Heartbeat packet"));
2448 if (packet->flags & SILC_PACKET_FLAG_LIST)
2452 case SILC_PACKET_KEY_AGREEMENT:
2454 * Received heartbeat.
2456 SILC_LOG_DEBUG(("Key agreement packet"));
2457 if (packet->flags & SILC_PACKET_FLAG_LIST)
2459 silc_server_key_agreement(server, sock, packet);
2462 case SILC_PACKET_REKEY:
2464 * Received re-key packet. The sender wants to regenerate the session
2467 SILC_LOG_DEBUG(("Re-key packet"));
2468 if (packet->flags & SILC_PACKET_FLAG_LIST)
2470 silc_server_rekey(server, sock, packet);
2473 case SILC_PACKET_REKEY_DONE:
2475 * The re-key is done.
2477 SILC_LOG_DEBUG(("Re-key done packet"));
2478 if (packet->flags & SILC_PACKET_FLAG_LIST)
2481 if (sock->protocol && sock->protocol->protocol &&
2482 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2484 SilcServerRekeyInternalContext *proto_ctx =
2485 (SilcServerRekeyInternalContext *)sock->protocol->context;
2487 if (proto_ctx->packet)
2488 silc_packet_context_free(proto_ctx->packet);
2490 proto_ctx->packet = silc_packet_context_dup(packet);
2492 /* Let the protocol handle the packet */
2493 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2495 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2496 "protocol active, packet dropped."));
2500 case SILC_PACKET_FTP:
2502 SILC_LOG_DEBUG(("FTP packet"));
2503 if (packet->flags & SILC_PACKET_FLAG_LIST)
2505 silc_server_ftp(server, sock, packet);
2508 case SILC_PACKET_RESUME_CLIENT:
2510 SILC_LOG_DEBUG(("Resume Client packet"));
2511 if (packet->flags & SILC_PACKET_FLAG_LIST)
2513 silc_server_resume_client(server, sock, packet);
2516 case SILC_PACKET_RESUME_ROUTER:
2517 /* Resume router packet received. This packet is received for backup
2518 router resuming protocol. */
2519 SILC_LOG_DEBUG(("Resume router packet"));
2520 if (packet->flags & SILC_PACKET_FLAG_LIST)
2522 silc_server_backup_resume_router(server, sock, packet);
2526 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2531 /* Creates connection to a remote router. */
2533 void silc_server_create_connection(SilcServer server,
2534 const char *remote_host, SilcUInt32 port)
2536 SilcServerConnection sconn;
2538 /* Allocate connection object for hold connection specific stuff. */
2539 sconn = silc_calloc(1, sizeof(*sconn));
2540 sconn->server = server;
2541 sconn->remote_host = strdup(remote_host);
2542 sconn->remote_port = port;
2543 sconn->no_reconnect = TRUE;
2545 silc_schedule_task_add(server->schedule, 0,
2546 silc_server_connect_router,
2547 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2548 SILC_TASK_PRI_NORMAL);
2551 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2553 silc_socket_free((SilcSocketConnection)context);
2556 /* Closes connection to socket connection */
2558 void silc_server_close_connection(SilcServer server,
2559 SilcSocketConnection sock)
2561 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2562 silc_socket_free(sock);
2566 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2568 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2569 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2570 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2573 /* We won't listen for this connection anymore */
2574 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2576 /* Unregister all tasks */
2577 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2579 /* Close the actual connection */
2580 silc_net_close_connection(sock->sock);
2581 server->sockets[sock->sock] = NULL;
2583 /* If sock->user_data is NULL then we'll check for active protocols
2584 here since the silc_server_free_sock_user_data has not been called
2585 for this connection. */
2586 if (!sock->user_data) {
2587 /* If any protocol is active cancel its execution. It will call
2588 the final callback which will finalize the disconnection. */
2589 if (sock->protocol) {
2590 silc_protocol_cancel(sock->protocol, server->schedule);
2591 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2592 silc_protocol_execute_final(sock->protocol, server->schedule);
2593 sock->protocol = NULL;
2598 silc_schedule_task_add(server->schedule, 0,
2599 silc_server_close_connection_final,
2600 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2601 SILC_TASK_PRI_NORMAL);
2604 /* Sends disconnect message to remote connection and disconnects the
2607 void silc_server_disconnect_remote(SilcServer server,
2608 SilcSocketConnection sock,
2609 SilcStatus status, ...)
2612 unsigned char buf[512];
2620 memset(buf, 0, sizeof(buf));
2621 va_start(ap, status);
2622 cp = va_arg(ap, char *);
2624 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2629 SILC_LOG_DEBUG(("Disconnecting remote host"));
2631 /* Notify remote end that the conversation is over. The notify message
2632 is tried to be sent immediately. */
2636 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2638 buffer = silc_buffer_alloc_size(len);
2642 buffer->data[0] = status;
2644 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2646 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2647 buffer->data, buffer->len, TRUE);
2648 silc_buffer_free(buffer);
2651 silc_server_packet_queue_purge(server, sock);
2653 /* Mark the connection to be disconnected */
2654 SILC_SET_DISCONNECTED(sock);
2655 silc_server_close_connection(server, sock);
2660 SilcClientEntry client;
2661 } *FreeClientInternal;
2663 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2665 FreeClientInternal i = (FreeClientInternal)context;
2667 silc_idlist_del_data(i->client);
2668 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2672 /* Frees client data and notifies about client's signoff. */
2674 void silc_server_free_client_data(SilcServer server,
2675 SilcSocketConnection sock,
2676 SilcClientEntry client,
2678 const char *signoff)
2680 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2682 /* If there is pending outgoing data for the client then purge it
2683 to the network before removing the client entry. */
2684 silc_server_packet_queue_purge(server, sock);
2687 /* Check if anyone is watching this nickname */
2688 if (server->server_type == SILC_ROUTER)
2689 silc_server_check_watcher_list(server, client, NULL,
2690 SILC_NOTIFY_TYPE_SIGNOFF);
2692 /* Send SIGNOFF notify to routers. */
2693 if (notify && !server->standalone && server->router)
2694 silc_server_send_notify_signoff(server, server->router->connection,
2695 server->server_type == SILC_SERVER ?
2696 FALSE : TRUE, client->id, signoff);
2698 /* Remove client from all channels */
2700 silc_server_remove_from_channels(server, NULL, client,
2701 TRUE, (char *)signoff, TRUE);
2703 silc_server_remove_from_channels(server, NULL, client,
2704 FALSE, NULL, FALSE);
2706 /* Remove this client from watcher list if it is */
2707 silc_server_del_from_watcher_list(server, client);
2710 /* Update statistics */
2711 server->stat.my_clients--;
2712 server->stat.clients--;
2713 if (server->stat.cell_clients)
2714 server->stat.cell_clients--;
2715 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2716 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2717 silc_schedule_task_del_by_context(server->schedule, client);
2719 /* We will not delete the client entry right away. We will take it
2720 into history (for WHOWAS command) for 5 minutes */
2723 silc_schedule_task_add(server->schedule, 0,
2724 silc_server_free_client_data_timeout,
2726 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2727 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2729 client->router = NULL;
2730 client->connection = NULL;
2733 /* Frees user_data pointer from socket connection object. This also sends
2734 appropriate notify packets to the network to inform about leaving
2737 void silc_server_free_sock_user_data(SilcServer server,
2738 SilcSocketConnection sock,
2739 const char *signoff_message)
2741 SILC_LOG_DEBUG(("Start"));
2743 switch (sock->type) {
2744 case SILC_SOCKET_TYPE_CLIENT:
2746 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2747 silc_server_free_client_data(server, sock, user_data, TRUE,
2751 case SILC_SOCKET_TYPE_SERVER:
2752 case SILC_SOCKET_TYPE_ROUTER:
2754 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2755 SilcServerEntry backup_router = NULL;
2758 backup_router = silc_server_backup_get(server, user_data->id);
2760 /* If this was our primary router connection then we're lost to
2761 the outside world. */
2762 if (server->router == user_data) {
2763 /* Check whether we have a backup router connection */
2764 if (!backup_router || backup_router == user_data) {
2765 silc_schedule_task_add(server->schedule, 0,
2766 silc_server_connect_to_router,
2769 SILC_TASK_PRI_NORMAL);
2771 server->id_entry->router = NULL;
2772 server->router = NULL;
2773 server->standalone = TRUE;
2774 backup_router = NULL;
2776 SILC_LOG_INFO(("New primary router is backup router %s",
2777 backup_router->server_name));
2778 SILC_LOG_DEBUG(("New primary router is backup router %s",
2779 backup_router->server_name));
2780 #ifdef BACKUP_SINGLE_ROUTER
2781 if (server->id_entry != backup_router) {
2782 #endif /* BACKUP_SINGLE_ROUTER */
2783 server->id_entry->router = backup_router;
2784 server->router = backup_router;
2785 server->router_connect = time(0);
2786 server->backup_primary = TRUE;
2787 #ifdef BACKUP_SINGLE_ROUTER
2789 server->id_entry->router = NULL;
2790 server->router = NULL;
2791 server->standalone = TRUE;
2793 #endif /* BACKUP_SINGLE_ROUTER */
2795 if (server->server_type == SILC_BACKUP_ROUTER) {
2796 server->server_type = SILC_ROUTER;
2798 /* We'll need to constantly try to reconnect to the primary
2799 router so that we'll see when it comes back online. */
2800 silc_server_backup_reconnect(server, sock->ip, sock->port,
2801 silc_server_backup_connected,
2805 /* Mark this connection as replaced */
2806 silc_server_backup_replaced_add(server, user_data->id,
2809 } else if (backup_router) {
2810 SILC_LOG_INFO(("Enabling the use of backup router %s",
2811 backup_router->server_name));
2812 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2813 backup_router->server_name));
2815 /* Mark this connection as replaced */
2816 silc_server_backup_replaced_add(server, user_data->id,
2820 if (!backup_router) {
2821 /* Free all client entries that this server owns as they will
2822 become invalid now as well. */
2824 silc_server_remove_clients_by_server(server, user_data, TRUE);
2825 if (server->server_type == SILC_SERVER)
2826 silc_server_remove_channels_by_server(server, user_data);
2828 /* Update the client entries of this server to the new backup
2829 router. This also removes the clients that *really* was owned
2830 by the primary router and went down with the router. */
2831 silc_server_update_clients_by_server(server, user_data, backup_router,
2833 silc_server_update_servers_by_server(server, user_data, backup_router);
2834 if (server->server_type == SILC_SERVER)
2835 silc_server_update_channels_by_server(server, user_data,
2839 /* Free the server entry */
2840 silc_server_backup_del(server, user_data);
2841 silc_server_backup_replaced_del(server, user_data);
2842 silc_idlist_del_data(user_data);
2843 if (!silc_idlist_del_server(server->local_list, user_data))
2844 silc_idlist_del_server(server->global_list, user_data);
2845 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2846 server->stat.my_servers--;
2848 server->stat.my_routers--;
2849 server->stat.routers--;
2851 server->stat.servers--;
2852 if (server->server_type == SILC_ROUTER)
2853 server->stat.cell_servers--;
2855 if (backup_router) {
2856 /* Announce all of our stuff that was created about 5 minutes ago.
2857 The backup router knows all the other stuff already. */
2858 if (server->server_type == SILC_ROUTER)
2859 silc_server_announce_servers(server, FALSE, time(0) - 300,
2860 backup_router->connection);
2862 /* Announce our clients and channels to the router */
2863 silc_server_announce_clients(server, time(0) - 300,
2864 backup_router->connection);
2865 silc_server_announce_channels(server, time(0) - 300,
2866 backup_router->connection);
2872 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2874 silc_idlist_del_data(user_data);
2875 silc_free(user_data);
2880 /* If any protocol is active cancel its execution */
2881 if (sock->protocol) {
2882 silc_protocol_cancel(sock->protocol, server->schedule);
2883 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2884 silc_protocol_execute_final(sock->protocol, server->schedule);
2885 sock->protocol = NULL;
2888 sock->user_data = NULL;
2891 /* Removes client from all channels it has joined. This is used when client
2892 connection is disconnected. If the client on a channel is last, the
2893 channel is removed as well. This sends the SIGNOFF notify types. */
2895 void silc_server_remove_from_channels(SilcServer server,
2896 SilcSocketConnection sock,
2897 SilcClientEntry client,
2899 const char *signoff_message,
2902 SilcChannelEntry channel;
2903 SilcChannelClientEntry chl;
2904 SilcHashTableList htl;
2907 SILC_LOG_DEBUG(("Start"));
2909 if (!client || !client->id)
2912 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2916 /* Remove the client from all channels. The client is removed from
2917 the channels' user list. */
2918 silc_hash_table_list(client->channels, &htl);
2919 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2920 channel = chl->channel;
2922 /* Remove channel if this is last client leaving the channel, unless
2923 the channel is permanent. */
2924 if (server->server_type == SILC_ROUTER &&
2925 silc_hash_table_count(channel->user_list) < 2) {
2926 silc_server_channel_delete(server, channel);
2930 silc_hash_table_del(client->channels, channel);
2931 silc_hash_table_del(channel->user_list, chl->client);
2932 channel->user_count--;
2934 /* If there is no global users on the channel anymore mark the channel
2935 as local channel. Do not check if the removed client is local client. */
2936 if (server->server_type != SILC_ROUTER && channel->global_users &&
2937 chl->client->router && !silc_server_channel_has_global(channel))
2938 channel->global_users = FALSE;
2942 /* Update statistics */
2943 if (client->connection)
2944 server->stat.my_chanclients--;
2945 if (server->server_type == SILC_ROUTER) {
2946 server->stat.cell_chanclients--;
2947 server->stat.chanclients--;
2950 /* If there is not at least one local user on the channel then we don't
2951 need the channel entry anymore, we can remove it safely, unless the
2952 channel is permanent channel */
2953 if (server->server_type != SILC_ROUTER &&
2954 !silc_server_channel_has_local(channel)) {
2955 /* Notify about leaving client if this channel has global users. */
2956 if (notify && channel->global_users)
2957 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2958 SILC_NOTIFY_TYPE_SIGNOFF,
2959 signoff_message ? 2 : 1,
2960 clidp->data, clidp->len,
2961 signoff_message, signoff_message ?
2962 strlen(signoff_message) : 0);
2964 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2965 silc_server_channel_delete(server, channel);
2969 /* Send notify to channel about client leaving SILC and channel too */
2971 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2972 SILC_NOTIFY_TYPE_SIGNOFF,
2973 signoff_message ? 2 : 1,
2974 clidp->data, clidp->len,
2975 signoff_message, signoff_message ?
2976 strlen(signoff_message) : 0);
2978 /* Re-generate channel key if needed */
2979 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2980 if (!silc_server_create_channel_key(server, channel, 0))
2983 /* Send the channel key to the channel. The key of course is not sent
2984 to the client who was removed from the channel. */
2985 silc_server_send_channel_key(server, client->connection, channel,
2986 server->server_type == SILC_ROUTER ?
2987 FALSE : !server->standalone);
2991 silc_hash_table_list_reset(&htl);
2992 silc_buffer_free(clidp);
2995 /* Removes client from one channel. This is used for example when client
2996 calls LEAVE command to remove itself from the channel. Returns TRUE
2997 if channel still exists and FALSE if the channel is removed when
2998 last client leaves the channel. If `notify' is FALSE notify messages
3001 bool silc_server_remove_from_one_channel(SilcServer server,
3002 SilcSocketConnection sock,
3003 SilcChannelEntry channel,
3004 SilcClientEntry client,
3007 SilcChannelClientEntry chl;
3010 SILC_LOG_DEBUG(("Removing %s from channel %s",
3011 silc_id_render(client->id, SILC_ID_CLIENT),
3012 channel->channel_name));
3014 /* Get the entry to the channel, if this client is not on the channel
3016 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3019 /* Remove channel if this is last client leaving the channel, unless
3020 the channel is permanent. */
3021 if (server->server_type == SILC_ROUTER &&
3022 silc_hash_table_count(channel->user_list) < 2) {
3023 silc_server_channel_delete(server, channel);
3027 silc_hash_table_del(client->channels, chl->channel);
3028 silc_hash_table_del(channel->user_list, chl->client);
3029 channel->user_count--;
3031 /* If there is no global users on the channel anymore mark the channel
3032 as local channel. Do not check if the client is local client. */
3033 if (server->server_type != SILC_ROUTER && channel->global_users &&
3034 chl->client->router && !silc_server_channel_has_global(channel))
3035 channel->global_users = FALSE;
3039 /* Update statistics */
3040 if (client->connection)
3041 server->stat.my_chanclients--;
3042 if (server->server_type == SILC_ROUTER) {
3043 server->stat.cell_chanclients--;
3044 server->stat.chanclients--;
3047 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3051 /* If there is not at least one local user on the channel then we don't
3052 need the channel entry anymore, we can remove it safely, unless the
3053 channel is permanent channel */
3054 if (server->server_type != SILC_ROUTER &&
3055 !silc_server_channel_has_local(channel)) {
3056 /* Notify about leaving client if this channel has global users. */
3057 if (notify && channel->global_users)
3058 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3059 SILC_NOTIFY_TYPE_LEAVE, 1,
3060 clidp->data, clidp->len);
3062 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3063 silc_server_channel_delete(server, channel);
3064 silc_buffer_free(clidp);
3068 /* Send notify to channel about client leaving the channel */
3070 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3071 SILC_NOTIFY_TYPE_LEAVE, 1,
3072 clidp->data, clidp->len);
3074 silc_buffer_free(clidp);
3078 /* Timeout callback. This is called if connection is idle or for some
3079 other reason is not responding within some period of time. This
3080 disconnects the remote end. */
3082 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3084 SilcServer server = (SilcServer)context;
3085 SilcSocketConnection sock = server->sockets[fd];
3086 SilcProtocolType protocol = 0;
3088 SILC_LOG_DEBUG(("Start"));
3093 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3094 sock->hostname, sock->ip));
3096 /* If we have protocol active we must assure that we call the protocol's
3097 final callback so that all the memory is freed. */
3098 if (sock->protocol) {
3099 protocol = sock->protocol->protocol->type;
3100 silc_protocol_cancel(sock->protocol, server->schedule);
3101 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3102 silc_protocol_execute_final(sock->protocol, server->schedule);
3103 sock->protocol = NULL;
3107 if (sock->user_data)
3108 silc_server_free_sock_user_data(server, sock, NULL);
3110 silc_server_disconnect_remote(server, sock,
3112 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3113 SILC_STATUS_ERR_AUTH_FAILED :
3114 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3115 "Connection timeout");
3118 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3119 function may be used only by router. In real SILC network all channels
3120 are created by routers thus this function is never used by normal
3123 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3124 SilcServerID *router_id,
3130 SilcChannelID *channel_id;
3131 SilcChannelEntry entry;
3135 SILC_LOG_DEBUG(("Creating new channel"));
3138 cipher = SILC_DEFAULT_CIPHER;
3140 hmac = SILC_DEFAULT_HMAC;
3142 /* Allocate cipher */
3143 if (!silc_cipher_alloc(cipher, &key))
3147 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3148 silc_cipher_free(key);
3152 channel_name = strdup(channel_name);
3154 /* Create the channel ID */
3155 if (!silc_id_create_channel_id(server, router_id, server->rng,
3157 silc_free(channel_name);
3158 silc_cipher_free(key);
3159 silc_hmac_free(newhmac);
3163 /* Create the channel */
3164 entry = silc_idlist_add_channel(server->local_list, channel_name,
3165 SILC_CHANNEL_MODE_NONE, channel_id,
3166 NULL, key, newhmac, 0);
3168 silc_free(channel_name);
3169 silc_cipher_free(key);
3170 silc_hmac_free(newhmac);
3171 silc_free(channel_id);
3175 entry->cipher = strdup(cipher);
3176 entry->hmac_name = strdup(hmac);
3178 /* Now create the actual key material */
3179 if (!silc_server_create_channel_key(server, entry,
3180 silc_cipher_get_key_len(key) / 8)) {
3181 silc_idlist_del_channel(server->local_list, entry);
3185 /* Notify other routers about the new channel. We send the packet
3186 to our primary route. */
3187 if (broadcast && server->standalone == FALSE)
3188 silc_server_send_new_channel(server, server->router->connection, TRUE,
3189 channel_name, entry->id,
3190 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3193 /* Distribute to backup routers */
3194 if (broadcast && server->server_type == SILC_ROUTER) {
3197 SilcUInt32 name_len = strlen(channel_name);
3198 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3199 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3201 packet = silc_channel_payload_encode(channel_name, name_len,
3202 cid, channel_id_len, entry->mode);
3203 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3204 packet->data, packet->len, FALSE, TRUE);
3206 silc_buffer_free(packet);
3209 server->stat.my_channels++;
3210 if (server->server_type == SILC_ROUTER) {
3211 server->stat.channels++;
3212 server->stat.cell_channels++;
3213 entry->users_resolved = TRUE;
3219 /* Same as above but creates the channel with Channel ID `channel_id. */
3222 silc_server_create_new_channel_with_id(SilcServer server,
3226 SilcChannelID *channel_id,
3229 SilcChannelEntry entry;
3233 SILC_LOG_DEBUG(("Creating new channel"));
3236 cipher = SILC_DEFAULT_CIPHER;
3238 hmac = SILC_DEFAULT_HMAC;
3240 /* Allocate cipher */
3241 if (!silc_cipher_alloc(cipher, &key))
3245 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3246 silc_cipher_free(key);
3250 channel_name = strdup(channel_name);
3252 /* Create the channel */
3253 entry = silc_idlist_add_channel(server->local_list, channel_name,
3254 SILC_CHANNEL_MODE_NONE, channel_id,
3255 NULL, key, newhmac, 0);
3257 silc_cipher_free(key);
3258 silc_hmac_free(newhmac);
3259 silc_free(channel_name);
3263 /* Now create the actual key material */
3264 if (!silc_server_create_channel_key(server, entry,
3265 silc_cipher_get_key_len(key) / 8)) {
3266 silc_idlist_del_channel(server->local_list, entry);
3270 /* Notify other routers about the new channel. We send the packet
3271 to our primary route. */
3272 if (broadcast && server->standalone == FALSE)
3273 silc_server_send_new_channel(server, server->router->connection, TRUE,
3274 channel_name, entry->id,
3275 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3278 /* Distribute to backup routers */
3279 if (broadcast && server->server_type == SILC_ROUTER) {
3282 SilcUInt32 name_len = strlen(channel_name);
3283 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3284 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3286 packet = silc_channel_payload_encode(channel_name, name_len,
3287 cid, channel_id_len, entry->mode);
3288 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3289 packet->data, packet->len, FALSE, TRUE);
3291 silc_buffer_free(packet);
3294 server->stat.my_channels++;
3295 if (server->server_type == SILC_ROUTER) {
3296 server->stat.channels++;
3297 server->stat.cell_channels++;
3298 entry->users_resolved = TRUE;
3304 /* Channel's key re-key timeout callback. */
3306 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3308 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3309 SilcServer server = (SilcServer)rekey->context;
3313 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3316 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3319 /* Generates new channel key. This is used to create the initial channel key
3320 but also to re-generate new key for channel. If `key_len' is provided
3321 it is the bytes of the key length. */
3323 bool silc_server_create_channel_key(SilcServer server,
3324 SilcChannelEntry channel,
3328 unsigned char channel_key[32], hash[32];
3331 SILC_LOG_DEBUG(("Generating channel key"));
3333 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3334 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3338 if (!channel->channel_key)
3339 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3340 channel->channel_key = NULL;
3346 else if (channel->key_len)
3347 len = channel->key_len / 8;
3349 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3351 /* Create channel key */
3352 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3355 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3357 /* Remove old key if exists */
3359 memset(channel->key, 0, channel->key_len / 8);
3360 silc_free(channel->key);
3364 channel->key_len = len * 8;
3365 channel->key = silc_memdup(channel_key, len);
3366 memset(channel_key, 0, sizeof(channel_key));
3368 /* Generate HMAC key from the channel key data and set it */
3370 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3371 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3372 silc_hmac_set_key(channel->hmac, hash,
3373 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3374 memset(hash, 0, sizeof(hash));
3376 if (server->server_type == SILC_ROUTER) {
3377 if (!channel->rekey)
3378 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3379 channel->rekey->context = (void *)server;
3380 channel->rekey->channel = channel;
3381 channel->rekey->key_len = key_len;
3382 if (channel->rekey->task)
3383 silc_schedule_task_del(server->schedule, channel->rekey->task);
3385 channel->rekey->task =
3386 silc_schedule_task_add(server->schedule, 0,
3387 silc_server_channel_key_rekey,
3388 (void *)channel->rekey,
3389 server->config->channel_rekey_secs, 0,
3391 SILC_TASK_PRI_NORMAL);
3397 /* Saves the channel key found in the encoded `key_payload' buffer. This
3398 function is used when we receive Channel Key Payload and also when we're
3399 processing JOIN command reply. Returns entry to the channel. */
3401 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3402 SilcBuffer key_payload,
3403 SilcChannelEntry channel)
3405 SilcChannelKeyPayload payload = NULL;
3406 SilcChannelID *id = NULL;
3407 unsigned char *tmp, hash[32];
3411 SILC_LOG_DEBUG(("Start"));
3413 /* Decode channel key payload */
3414 payload = silc_channel_key_payload_parse(key_payload->data,
3417 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3422 /* Get the channel entry */
3425 /* Get channel ID */
3426 tmp = silc_channel_key_get_id(payload, &tmp_len);
3427 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3433 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3435 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3437 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3438 silc_id_render(id, SILC_ID_CHANNEL)));
3444 tmp = silc_channel_key_get_key(payload, &tmp_len);
3450 cipher = silc_channel_key_get_cipher(payload, NULL);
3456 /* Remove old key if exists */
3458 memset(channel->key, 0, channel->key_len / 8);
3459 silc_free(channel->key);
3460 silc_cipher_free(channel->channel_key);
3463 /* Create new cipher */
3464 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3465 channel->channel_key = NULL;
3470 if (channel->cipher)
3471 silc_free(channel->cipher);
3472 channel->cipher = strdup(cipher);
3475 channel->key_len = tmp_len * 8;
3476 channel->key = silc_memdup(tmp, tmp_len);
3477 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3479 /* Generate HMAC key from the channel key data and set it */
3481 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3482 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3483 silc_hmac_set_key(channel->hmac, hash,
3484 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3486 memset(hash, 0, sizeof(hash));
3487 memset(tmp, 0, tmp_len);
3489 if (server->server_type == SILC_ROUTER) {
3490 if (!channel->rekey)
3491 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3492 channel->rekey->context = (void *)server;
3493 channel->rekey->channel = channel;
3494 if (channel->rekey->task)
3495 silc_schedule_task_del(server->schedule, channel->rekey->task);
3497 channel->rekey->task =
3498 silc_schedule_task_add(server->schedule, 0,
3499 silc_server_channel_key_rekey,
3500 (void *)channel->rekey,
3501 server->config->channel_rekey_secs, 0,
3503 SILC_TASK_PRI_NORMAL);
3509 silc_channel_key_payload_free(payload);
3514 /* Heartbeat callback. This function is set as argument for the
3515 silc_socket_set_heartbeat function. The library will call this function
3516 at the set time interval. */
3518 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3521 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3523 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3525 /* Send the heartbeat */
3526 silc_server_send_heartbeat(hb->server, sock);
3529 /* Returns assembled of all servers in the given ID list. The packet's
3530 form is dictated by the New ID payload. */
3532 static void silc_server_announce_get_servers(SilcServer server,
3533 SilcServerEntry remote,
3535 SilcBuffer *servers,
3536 unsigned long creation_time)
3538 SilcIDCacheList list;
3539 SilcIDCacheEntry id_cache;
3540 SilcServerEntry entry;
3543 /* Go through all clients in the list */
3544 if (silc_idcache_get_all(id_list->servers, &list)) {
3545 if (silc_idcache_list_first(list, &id_cache)) {
3547 entry = (SilcServerEntry)id_cache->context;
3549 /* Do not announce the one we've sending our announcements and
3550 do not announce ourself. Also check the creation time if it's
3552 if ((entry == remote) || (entry == server->id_entry) ||
3553 (creation_time && entry->data.created < creation_time)) {
3554 if (!silc_idcache_list_next(list, &id_cache))
3559 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3561 *servers = silc_buffer_realloc(*servers,
3563 (*servers)->truelen + idp->len :
3565 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3566 silc_buffer_put(*servers, idp->data, idp->len);
3567 silc_buffer_pull(*servers, idp->len);
3568 silc_buffer_free(idp);
3570 if (!silc_idcache_list_next(list, &id_cache))
3575 silc_idcache_list_free(list);
3580 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3586 p = silc_notify_payload_encode(notify, argc, ap);
3592 /* This function is used by router to announce existing servers to our
3593 primary router when we've connected to it. If `creation_time' is non-zero
3594 then only the servers that has been created after the `creation_time'
3595 will be announced. */
3597 void silc_server_announce_servers(SilcServer server, bool global,
3598 unsigned long creation_time,
3599 SilcSocketConnection remote)
3601 SilcBuffer servers = NULL;
3603 SILC_LOG_DEBUG(("Announcing servers"));
3605 /* Get servers in local list */
3606 silc_server_announce_get_servers(server, remote->user_data,
3607 server->local_list, &servers,
3611 /* Get servers in global list */
3612 silc_server_announce_get_servers(server, remote->user_data,
3613 server->global_list, &servers,
3617 silc_buffer_push(servers, servers->data - servers->head);
3618 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3620 /* Send the packet */
3621 silc_server_packet_send(server, remote,
3622 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3623 servers->data, servers->len, TRUE);
3625 silc_buffer_free(servers);
3629 /* Returns assembled packet of all clients in the given ID list. The
3630 packet's form is dictated by the New ID Payload. */
3632 static void silc_server_announce_get_clients(SilcServer server,
3634 SilcBuffer *clients,
3636 unsigned long creation_time)
3638 SilcIDCacheList list;
3639 SilcIDCacheEntry id_cache;
3640 SilcClientEntry client;
3643 unsigned char mode[4];
3645 /* Go through all clients in the list */
3646 if (silc_idcache_get_all(id_list->clients, &list)) {
3647 if (silc_idcache_list_first(list, &id_cache)) {
3649 client = (SilcClientEntry)id_cache->context;
3651 if (creation_time && client->data.created < creation_time) {
3652 if (!silc_idcache_list_next(list, &id_cache))
3657 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3659 *clients = silc_buffer_realloc(*clients,
3661 (*clients)->truelen + idp->len :
3663 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3664 silc_buffer_put(*clients, idp->data, idp->len);
3665 silc_buffer_pull(*clients, idp->len);
3667 SILC_PUT32_MSB(client->mode, mode);
3668 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3669 2, idp->data, idp->len,
3671 *umodes = silc_buffer_realloc(*umodes,
3673 (*umodes)->truelen + tmp->len :
3675 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3676 silc_buffer_put(*umodes, tmp->data, tmp->len);
3677 silc_buffer_pull(*umodes, tmp->len);
3678 silc_buffer_free(tmp);
3680 silc_buffer_free(idp);
3682 if (!silc_idcache_list_next(list, &id_cache))
3687 silc_idcache_list_free(list);
3691 /* This function is used to announce our existing clients to our router
3692 when we've connected to it. If `creation_time' is non-zero then only
3693 the clients that has been created after the `creation_time' will be
3696 void silc_server_announce_clients(SilcServer server,
3697 unsigned long creation_time,
3698 SilcSocketConnection remote)
3700 SilcBuffer clients = NULL;
3701 SilcBuffer umodes = NULL;
3703 SILC_LOG_DEBUG(("Announcing clients"));
3705 /* Get clients in local list */
3706 silc_server_announce_get_clients(server, server->local_list,
3707 &clients, &umodes, creation_time);
3709 /* As router we announce our global list as well */
3710 if (server->server_type == SILC_ROUTER)
3711 silc_server_announce_get_clients(server, server->global_list,
3712 &clients, &umodes, creation_time);
3715 silc_buffer_push(clients, clients->data - clients->head);
3716 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3718 /* Send the packet */
3719 silc_server_packet_send(server, remote,
3720 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3721 clients->data, clients->len, TRUE);
3723 silc_buffer_free(clients);
3727 silc_buffer_push(umodes, umodes->data - umodes->head);
3728 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3730 /* Send the packet */
3731 silc_server_packet_send(server, remote,
3732 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3733 umodes->data, umodes->len, TRUE);
3735 silc_buffer_free(umodes);
3739 /* Returns channel's topic for announcing it */
3741 void silc_server_announce_get_channel_topic(SilcServer server,
3742 SilcChannelEntry channel,
3747 if (channel->topic) {
3748 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3749 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3750 chidp->data, chidp->len,
3752 strlen(channel->topic));
3753 silc_buffer_free(chidp);
3757 /* Returns assembled packets for channel users of the `channel'. */
3759 void silc_server_announce_get_channel_users(SilcServer server,
3760 SilcChannelEntry channel,
3761 SilcBuffer *channel_modes,
3762 SilcBuffer *channel_users,
3763 SilcBuffer *channel_users_modes)
3765 SilcChannelClientEntry chl;
3766 SilcHashTableList htl;
3767 SilcBuffer chidp, clidp, csidp;
3770 unsigned char mode[4], *fkey = NULL;
3771 SilcUInt32 fkey_len = 0;
3774 SILC_LOG_DEBUG(("Start"));
3776 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3777 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3780 SILC_PUT32_MSB(channel->mode, mode);
3781 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3782 if (channel->founder_key)
3783 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3785 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3786 6, csidp->data, csidp->len,
3789 hmac, hmac ? strlen(hmac) : 0,
3790 channel->passphrase,
3791 channel->passphrase ?
3792 strlen(channel->passphrase) : 0,
3796 silc_buffer_realloc(*channel_modes,
3798 (*channel_modes)->truelen + len : len));
3799 silc_buffer_pull_tail(*channel_modes,
3800 ((*channel_modes)->end -
3801 (*channel_modes)->data));
3802 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3803 silc_buffer_pull(*channel_modes, len);
3804 silc_buffer_free(tmp);
3809 /* Now find all users on the channel */
3810 silc_hash_table_list(channel->user_list, &htl);
3811 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3812 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3815 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3816 clidp->data, clidp->len,
3817 chidp->data, chidp->len);
3820 silc_buffer_realloc(*channel_users,
3822 (*channel_users)->truelen + len : len));
3823 silc_buffer_pull_tail(*channel_users,
3824 ((*channel_users)->end -
3825 (*channel_users)->data));
3827 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3828 silc_buffer_pull(*channel_users, len);
3829 silc_buffer_free(tmp);
3831 /* CUMODE notify for mode change on the channel */
3832 SILC_PUT32_MSB(chl->mode, mode);
3833 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3834 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3835 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3836 4, csidp->data, csidp->len,
3838 clidp->data, clidp->len,
3841 *channel_users_modes =
3842 silc_buffer_realloc(*channel_users_modes,
3843 (*channel_users_modes ?
3844 (*channel_users_modes)->truelen + len : len));
3845 silc_buffer_pull_tail(*channel_users_modes,
3846 ((*channel_users_modes)->end -
3847 (*channel_users_modes)->data));
3849 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3850 silc_buffer_pull(*channel_users_modes, len);
3851 silc_buffer_free(tmp);
3855 silc_buffer_free(clidp);
3857 silc_hash_table_list_reset(&htl);
3858 silc_buffer_free(chidp);
3859 silc_buffer_free(csidp);
3862 /* Returns assembled packets for all channels and users on those channels
3863 from the given ID List. The packets are in the form dictated by the
3864 New Channel and New Channel User payloads. */
3866 void silc_server_announce_get_channels(SilcServer server,
3868 SilcBuffer *channels,
3869 SilcBuffer **channel_modes,
3870 SilcBuffer *channel_users,
3871 SilcBuffer **channel_users_modes,
3872 SilcUInt32 *channel_users_modes_c,
3873 SilcBuffer **channel_topics,
3874 SilcChannelID ***channel_ids,
3875 unsigned long creation_time)
3877 SilcIDCacheList list;
3878 SilcIDCacheEntry id_cache;
3879 SilcChannelEntry channel;
3882 SilcUInt16 name_len;
3884 int i = *channel_users_modes_c;
3887 SILC_LOG_DEBUG(("Start"));
3889 /* Go through all channels in the list */
3890 if (silc_idcache_get_all(id_list->channels, &list)) {
3891 if (silc_idcache_list_first(list, &id_cache)) {
3893 channel = (SilcChannelEntry)id_cache->context;
3895 if (creation_time && channel->created < creation_time)
3900 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3901 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3902 name_len = strlen(channel->channel_name);
3905 len = 4 + name_len + id_len + 4;
3907 silc_buffer_realloc(*channels,
3908 (*channels ? (*channels)->truelen +
3910 silc_buffer_pull_tail(*channels,
3911 ((*channels)->end - (*channels)->data));
3912 silc_buffer_format(*channels,
3913 SILC_STR_UI_SHORT(name_len),
3914 SILC_STR_UI_XNSTRING(channel->channel_name,
3916 SILC_STR_UI_SHORT(id_len),
3917 SILC_STR_UI_XNSTRING(cid, id_len),
3918 SILC_STR_UI_INT(channel->mode),
3920 silc_buffer_pull(*channels, len);
3923 /* Channel user modes */
3924 *channel_users_modes = silc_realloc(*channel_users_modes,
3925 sizeof(**channel_users_modes) *
3927 (*channel_users_modes)[i] = NULL;
3928 *channel_modes = silc_realloc(*channel_modes,
3929 sizeof(**channel_modes) * (i + 1));
3930 (*channel_modes)[i] = NULL;
3931 *channel_ids = silc_realloc(*channel_ids,
3932 sizeof(**channel_ids) * (i + 1));
3933 (*channel_ids)[i] = NULL;
3934 silc_server_announce_get_channel_users(server, channel,
3935 &(*channel_modes)[i],
3937 &(*channel_users_modes)[i]);
3938 (*channel_ids)[i] = channel->id;
3940 /* Channel's topic */
3941 *channel_topics = silc_realloc(*channel_topics,
3942 sizeof(**channel_topics) * (i + 1));
3943 (*channel_topics)[i] = NULL;
3944 silc_server_announce_get_channel_topic(server, channel,
3945 &(*channel_topics)[i]);
3948 if (!silc_idcache_list_next(list, &id_cache))
3952 *channel_users_modes_c += i;
3955 silc_idcache_list_free(list);
3959 /* This function is used to announce our existing channels to our router
3960 when we've connected to it. This also announces the users on the
3961 channels to the router. If the `creation_time' is non-zero only the
3962 channels that was created after the `creation_time' are announced.
3963 Note that the channel users are still announced even if the `creation_time'
3966 void silc_server_announce_channels(SilcServer server,
3967 unsigned long creation_time,
3968 SilcSocketConnection remote)
3970 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
3971 SilcBuffer *channel_users_modes = NULL;
3972 SilcBuffer *channel_topics = NULL;
3973 SilcUInt32 channel_users_modes_c = 0;
3974 SilcChannelID **channel_ids = NULL;
3976 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3978 /* Get channels and channel users in local list */
3979 silc_server_announce_get_channels(server, server->local_list,
3980 &channels, &channel_modes,
3982 &channel_users_modes,
3983 &channel_users_modes_c,
3985 &channel_ids, creation_time);
3987 /* Get channels and channel users in global list */
3988 if (server->server_type != SILC_SERVER)
3989 silc_server_announce_get_channels(server, server->global_list,
3990 &channels, &channel_modes,
3992 &channel_users_modes,
3993 &channel_users_modes_c,
3995 &channel_ids, creation_time);
3998 silc_buffer_push(channels, channels->data - channels->head);
3999 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4001 /* Send the packet */
4002 silc_server_packet_send(server, remote,
4003 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4004 channels->data, channels->len,
4007 silc_buffer_free(channels);
4010 if (channel_modes) {
4013 for (i = 0; i < channel_users_modes_c; i++) {
4014 if (!channel_modes[i])
4016 silc_buffer_push(channel_modes[i],
4017 channel_modes[i]->data -
4018 channel_modes[i]->head);
4019 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4020 channel_modes[i]->len);
4021 silc_server_packet_send_dest(server, remote,
4022 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4023 channel_ids[i], SILC_ID_CHANNEL,
4024 channel_modes[i]->data,
4025 channel_modes[i]->len,
4027 silc_buffer_free(channel_modes[i]);
4029 silc_free(channel_modes);
4032 if (channel_users) {
4033 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4034 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4035 channel_users->len);
4037 /* Send the packet */
4038 silc_server_packet_send(server, remote,
4039 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4040 channel_users->data, channel_users->len,
4043 silc_buffer_free(channel_users);
4046 if (channel_users_modes) {
4049 for (i = 0; i < channel_users_modes_c; i++) {
4050 if (!channel_users_modes[i])
4052 silc_buffer_push(channel_users_modes[i],
4053 channel_users_modes[i]->data -
4054 channel_users_modes[i]->head);
4055 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4056 channel_users_modes[i]->len);
4057 silc_server_packet_send_dest(server, remote,
4058 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4059 channel_ids[i], SILC_ID_CHANNEL,
4060 channel_users_modes[i]->data,
4061 channel_users_modes[i]->len,
4063 silc_buffer_free(channel_users_modes[i]);
4065 silc_free(channel_users_modes);
4068 if (channel_topics) {
4071 for (i = 0; i < channel_users_modes_c; i++) {
4072 if (!channel_topics[i])
4075 silc_buffer_push(channel_topics[i],
4076 channel_topics[i]->data -
4077 channel_topics[i]->head);
4078 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4079 channel_topics[i]->len);
4080 silc_server_packet_send_dest(server, remote,
4081 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4082 channel_ids[i], SILC_ID_CHANNEL,
4083 channel_topics[i]->data,
4084 channel_topics[i]->len,
4086 silc_buffer_free(channel_topics[i]);
4088 silc_free(channel_topics);
4091 silc_free(channel_ids);
4094 /* Failure timeout callback. If this is called then we will immediately
4095 process the received failure. We always process the failure with timeout
4096 since we do not want to blindly trust to received failure packets.
4097 This won't be called (the timeout is cancelled) if the failure was
4098 bogus (it is bogus if remote does not close the connection after sending
4101 SILC_TASK_CALLBACK(silc_server_failure_callback)
4103 SilcServerFailureContext f = (SilcServerFailureContext)context;
4105 if (f->sock->protocol) {
4106 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4107 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4113 /* Assembles user list and users mode list from the `channel'. */
4115 bool silc_server_get_users_on_channel(SilcServer server,
4116 SilcChannelEntry channel,
4117 SilcBuffer *user_list,
4118 SilcBuffer *mode_list,
4119 SilcUInt32 *user_count)
4121 SilcChannelClientEntry chl;
4122 SilcHashTableList htl;
4123 SilcBuffer client_id_list;
4124 SilcBuffer client_mode_list;
4126 SilcUInt32 list_count = 0, len = 0;
4128 if (!silc_hash_table_count(channel->user_list))
4131 silc_hash_table_list(channel->user_list, &htl);
4132 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4133 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4134 silc_hash_table_list_reset(&htl);
4136 client_id_list = silc_buffer_alloc(len);
4138 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4139 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4140 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4142 silc_hash_table_list(channel->user_list, &htl);
4143 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4145 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4146 silc_buffer_put(client_id_list, idp->data, idp->len);
4147 silc_buffer_pull(client_id_list, idp->len);
4148 silc_buffer_free(idp);
4150 /* Client's mode on channel */
4151 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4152 silc_buffer_pull(client_mode_list, 4);
4156 silc_hash_table_list_reset(&htl);
4157 silc_buffer_push(client_id_list,
4158 client_id_list->data - client_id_list->head);
4159 silc_buffer_push(client_mode_list,
4160 client_mode_list->data - client_mode_list->head);
4162 *user_list = client_id_list;
4163 *mode_list = client_mode_list;
4164 *user_count = list_count;
4168 /* Saves users and their modes to the `channel'. */
4170 void silc_server_save_users_on_channel(SilcServer server,
4171 SilcSocketConnection sock,
4172 SilcChannelEntry channel,
4173 SilcClientID *noadd,
4174 SilcBuffer user_list,
4175 SilcBuffer mode_list,
4176 SilcUInt32 user_count)
4181 SilcClientID *client_id;
4182 SilcClientEntry client;
4183 SilcIDCacheEntry cache;
4184 SilcChannelClientEntry chl;
4187 SILC_LOG_DEBUG(("Start"));
4189 for (i = 0; i < user_count; i++) {
4191 SILC_GET16_MSB(idp_len, user_list->data + 2);
4193 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4194 silc_buffer_pull(user_list, idp_len);
4199 SILC_GET32_MSB(mode, mode_list->data);
4200 silc_buffer_pull(mode_list, 4);
4202 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4203 silc_free(client_id);
4209 /* Check if we have this client cached already. */
4210 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4211 server->server_type, &cache);
4213 client = silc_idlist_find_client_by_id(server->global_list,
4214 client_id, server->server_type,
4219 /* If router did not find such Client ID in its lists then this must
4220 be bogus client or some router in the net is buggy. */
4221 if (server->server_type == SILC_ROUTER) {
4222 silc_free(client_id);
4226 /* We don't have that client anywhere, add it. The client is added
4227 to global list since server didn't have it in the lists so it must be
4229 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4230 silc_id_dup(client_id, SILC_ID_CLIENT),
4231 sock->user_data, NULL, 0);
4233 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4234 silc_free(client_id);
4238 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4240 /* Found, if it is from global list we'll assure that we won't
4241 expire it now that the entry is on channel. */
4246 silc_free(client_id);
4248 if (!silc_server_client_on_channel(client, channel, &chl)) {
4249 /* Client was not on the channel, add it. */
4250 chl = silc_calloc(1, sizeof(*chl));
4251 chl->client = client;
4253 chl->channel = channel;
4254 silc_hash_table_add(channel->user_list, chl->client, chl);
4255 silc_hash_table_add(client->channels, chl->channel, chl);
4256 channel->user_count++;
4264 /* Saves channels and channels user modes to the `client'. Removes
4265 the client from those channels that are not sent in the list but
4268 void silc_server_save_user_channels(SilcServer server,
4269 SilcSocketConnection sock,
4270 SilcClientEntry client,
4271 SilcBuffer channels,
4272 SilcBuffer channels_user_modes)
4275 SilcUInt32 *chumodes;
4276 SilcChannelPayload entry;
4277 SilcChannelEntry channel;
4278 SilcChannelID *channel_id;
4279 SilcChannelClientEntry chl;
4280 SilcHashTable ht = NULL;
4281 SilcHashTableList htl;
4285 if (!channels ||!channels_user_modes)
4288 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4289 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4291 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4292 NULL, NULL, NULL, TRUE);
4293 silc_dlist_start(ch);
4294 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4295 /* Check if we have this channel, and add it if we don't have it.
4296 Also add the client on the channel unless it is there already. */
4297 channel_id = silc_channel_get_id_parse(entry);
4298 channel = silc_idlist_find_channel_by_id(server->local_list,
4301 channel = silc_idlist_find_channel_by_id(server->global_list,
4304 if (server->server_type != SILC_SERVER) {
4305 silc_free(channel_id);
4310 /* We don't have that channel anywhere, add it. */
4311 name = silc_channel_get_name(entry, NULL);
4312 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4313 channel_id, server->router,
4316 silc_free(channel_id);
4323 channel->mode = silc_channel_get_mode(entry);
4325 /* Add the client on the channel */
4326 if (!silc_server_client_on_channel(client, channel, &chl)) {
4327 chl = silc_calloc(1, sizeof(*chl));
4328 chl->client = client;
4329 chl->mode = chumodes[i++];
4330 chl->channel = channel;
4331 silc_hash_table_add(channel->user_list, chl->client, chl);
4332 silc_hash_table_add(client->channels, chl->channel, chl);
4333 channel->user_count++;
4336 chl->mode = chumodes[i++];
4339 silc_hash_table_add(ht, channel, channel);
4340 silc_free(channel_id);
4342 silc_channel_payload_list_free(ch);
4343 silc_free(chumodes);
4347 /* Go through the list again and remove client from channels that
4348 are no part of the list. */
4350 silc_hash_table_list(client->channels, &htl);
4351 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4352 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4353 silc_hash_table_del(chl->channel->user_list, chl->client);
4354 silc_hash_table_del(chl->client->channels, chl->channel);
4358 silc_hash_table_list_reset(&htl);
4359 silc_hash_table_free(ht);
4361 silc_hash_table_list(client->channels, &htl);
4362 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4363 silc_hash_table_del(chl->channel->user_list, chl->client);
4364 silc_hash_table_del(chl->client->channels, chl->channel);
4367 silc_hash_table_list_reset(&htl);
4371 /* Lookups route to the client indicated by the `id_data'. The connection
4372 object and internal data object is returned. Returns NULL if route
4373 could not be found to the client. If the `client_id' is specified then
4374 it is used and the `id_data' is ignored. */
4376 SilcSocketConnection
4377 silc_server_get_client_route(SilcServer server,
4378 unsigned char *id_data,
4380 SilcClientID *client_id,
4381 SilcIDListData *idata,
4382 SilcClientEntry *client_entry)
4385 SilcClientEntry client;
4387 SILC_LOG_DEBUG(("Start"));
4390 *client_entry = NULL;
4392 /* Decode destination Client ID */
4394 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4396 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4400 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4403 /* If the destination belongs to our server we don't have to route
4404 the packet anywhere but to send it to the local destination. */
4405 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4409 /* If we are router and the client has router then the client is in
4410 our cell but not directly connected to us. */
4411 if (server->server_type == SILC_ROUTER && client->router) {
4412 /* We are of course in this case the client's router thus the route
4413 to the client is the server who owns the client. So, we will send
4414 the packet to that server. */
4416 *idata = (SilcIDListData)client->router;
4417 return client->router->connection;
4420 /* Seems that client really is directly connected to us */
4422 *idata = (SilcIDListData)client;
4424 *client_entry = client;
4425 return client->connection;
4428 /* Destination belongs to someone not in this server. If we are normal
4429 server our action is to send the packet to our router. */
4430 if (server->server_type != SILC_ROUTER && !server->standalone) {
4433 *idata = (SilcIDListData)server->router;
4434 return server->router->connection;
4437 /* We are router and we will perform route lookup for the destination
4438 and send the packet to fastest route. */
4439 if (server->server_type == SILC_ROUTER && !server->standalone) {
4440 /* Check first that the ID is valid */
4441 client = silc_idlist_find_client_by_id(server->global_list, id,
4444 SilcSocketConnection dst_sock;
4446 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4450 *idata = (SilcIDListData)dst_sock->user_data;
4459 /* Encodes and returns channel list of channels the `client' has joined.
4460 Secret channels are not put to the list. */
4462 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4463 SilcClientEntry client,
4466 SilcBuffer *user_mode_list)
4468 SilcBuffer buffer = NULL;
4469 SilcChannelEntry channel;
4470 SilcChannelClientEntry chl;
4471 SilcHashTableList htl;
4474 SilcUInt16 name_len;
4478 *user_mode_list = NULL;
4480 silc_hash_table_list(client->channels, &htl);
4481 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4482 channel = chl->channel;
4484 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4486 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4489 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4490 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4491 name_len = strlen(channel->channel_name);
4493 len = 4 + name_len + id_len + 4;
4494 buffer = silc_buffer_realloc(buffer,
4495 (buffer ? buffer->truelen + len : len));
4496 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4497 silc_buffer_format(buffer,
4498 SILC_STR_UI_SHORT(name_len),
4499 SILC_STR_UI_XNSTRING(channel->channel_name,
4501 SILC_STR_UI_SHORT(id_len),
4502 SILC_STR_UI_XNSTRING(cid, id_len),
4503 SILC_STR_UI_INT(chl->channel->mode),
4505 silc_buffer_pull(buffer, len);
4508 if (user_mode_list) {
4509 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4511 (*user_mode_list)->truelen + 4 :
4513 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4514 (*user_mode_list)->data));
4515 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4516 silc_buffer_pull(*user_mode_list, 4);
4519 silc_hash_table_list_reset(&htl);
4522 silc_buffer_push(buffer, buffer->data - buffer->head);
4523 if (user_mode_list && *user_mode_list)
4524 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4525 (*user_mode_list)->head));
4530 /* Finds client entry by Client ID and if it is not found then resolves
4531 it using WHOIS command. */
4533 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4534 SilcClientID *client_id,
4535 bool always_resolve,
4538 SilcClientEntry client;
4543 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4546 client = silc_idlist_find_client_by_id(server->global_list,
4547 client_id, TRUE, NULL);
4548 if (!client && server->server_type == SILC_ROUTER)
4552 if (!client && server->standalone)
4555 if (!client || !client->nickname || !client->username ||
4557 SilcBuffer buffer, idp;
4560 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4561 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4562 client->resolve_cmd_ident = ++server->cmd_ident;
4565 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4566 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4567 server->cmd_ident, 1,
4568 4, idp->data, idp->len);
4569 silc_server_packet_send(server, client ? client->router->connection :
4570 server->router->connection,
4571 SILC_PACKET_COMMAND, 0,
4572 buffer->data, buffer->len, FALSE);
4573 silc_buffer_free(idp);
4574 silc_buffer_free(buffer);
4585 /* A timeout callback for the re-key. We will be the initiator of the
4588 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4590 SilcSocketConnection sock = (SilcSocketConnection)context;
4591 SilcIDListData idata = (SilcIDListData)sock->user_data;
4592 SilcServer server = (SilcServer)idata->rekey->context;
4593 SilcProtocol protocol;
4594 SilcServerRekeyInternalContext *proto_ctx;
4596 SILC_LOG_DEBUG(("Start"));
4598 /* Allocate internal protocol context. This is sent as context
4600 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4601 proto_ctx->server = (void *)server;
4602 proto_ctx->sock = sock;
4603 proto_ctx->responder = FALSE;
4604 proto_ctx->pfs = idata->rekey->pfs;
4606 /* Perform rekey protocol. Will call the final callback after the
4607 protocol is over. */
4608 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4609 &protocol, proto_ctx, silc_server_rekey_final);
4610 sock->protocol = protocol;
4612 /* Run the protocol */
4613 silc_protocol_execute(protocol, server->schedule, 0, 0);
4615 /* Re-register re-key timeout */
4616 silc_schedule_task_add(server->schedule, sock->sock,
4617 silc_server_rekey_callback,
4618 context, idata->rekey->timeout, 0,
4619 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4622 /* The final callback for the REKEY protocol. This will actually take the
4623 new key material into use. */
4625 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4627 SilcProtocol protocol = (SilcProtocol)context;
4628 SilcServerRekeyInternalContext *ctx =
4629 (SilcServerRekeyInternalContext *)protocol->context;
4630 SilcServer server = (SilcServer)ctx->server;
4631 SilcSocketConnection sock = ctx->sock;
4633 SILC_LOG_DEBUG(("Start"));
4635 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4636 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4637 /* Error occured during protocol */
4638 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4639 silc_protocol_cancel(protocol, server->schedule);
4640 silc_protocol_free(protocol);
4641 sock->protocol = NULL;
4643 silc_packet_context_free(ctx->packet);
4645 silc_ske_free(ctx->ske);
4650 /* Purge the outgoing data queue to assure that all rekey packets really
4651 go to the network before we quit the protocol. */
4652 silc_server_packet_queue_purge(server, sock);
4655 silc_protocol_free(protocol);
4656 sock->protocol = NULL;
4658 silc_packet_context_free(ctx->packet);
4660 silc_ske_free(ctx->ske);
4664 /* Task callback used to retrieve network statistical information from
4665 router server once in a while. */
4667 SILC_TASK_CALLBACK(silc_server_get_stats)
4669 SilcServer server = (SilcServer)context;
4670 SilcBuffer idp, packet;
4672 SILC_LOG_DEBUG(("Retrieving stats from router"));
4674 if (!server->standalone) {
4675 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4676 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4677 ++server->cmd_ident, 1,
4678 1, idp->data, idp->len);
4679 silc_server_packet_send(server, server->router->connection,
4680 SILC_PACKET_COMMAND, 0, packet->data,
4681 packet->len, FALSE);
4682 silc_buffer_free(packet);
4683 silc_buffer_free(idp);
4686 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4687 server, 120, 0, SILC_TASK_TIMEOUT,