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_rehash_close_connection);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
33 SILC_TASK_CALLBACK(silc_server_connect_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
36 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
39 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
40 SILC_TASK_CALLBACK(silc_server_packet_process);
41 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
42 SILC_TASK_CALLBACK(silc_server_close_connection_final);
43 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
44 SILC_TASK_CALLBACK(silc_server_timeout_remote);
45 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
46 SILC_TASK_CALLBACK(silc_server_failure_callback);
47 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 SILC_TASK_CALLBACK(silc_server_get_stats);
50 /* Allocates a new SILC server object. This has to be done before the server
51 can be used. After allocation one must call silc_server_init to initialize
52 the server. The new allocated server object is returned to the new_server
55 int silc_server_alloc(SilcServer *new_server)
59 SILC_LOG_DEBUG(("Allocating new server object"));
61 server = silc_calloc(1, sizeof(*server));
62 server->server_type = SILC_SERVER;
63 server->standalone = TRUE;
64 server->local_list = silc_calloc(1, sizeof(*server->local_list));
65 server->global_list = silc_calloc(1, sizeof(*server->global_list));
66 server->pending_commands = silc_dlist_init();
68 server->sim = silc_dlist_init();
76 /* Free's the SILC server object. This is called at the very end before
79 void silc_server_free(SilcServer server)
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_config_unref(&server->config_ref);
98 silc_rng_free(server->rng);
100 silc_pkcs_free(server->pkcs);
101 if (server->public_key)
102 silc_pkcs_public_key_free(server->public_key);
103 if (server->private_key)
104 silc_pkcs_private_key_free(server->private_key);
105 if (server->pending_commands)
106 silc_dlist_uninit(server->pending_commands);
107 if (server->id_entry)
108 silc_idlist_del_server(server->local_list, server->id_entry);
110 silc_idcache_free(server->local_list->clients);
111 silc_idcache_free(server->local_list->servers);
112 silc_idcache_free(server->local_list->channels);
113 silc_idcache_free(server->global_list->clients);
114 silc_idcache_free(server->global_list->servers);
115 silc_idcache_free(server->global_list->channels);
116 silc_hash_table_free(server->watcher_list);
118 silc_hash_free(server->md5hash);
119 silc_hash_free(server->sha1hash);
120 silc_hmac_unregister_all();
121 silc_hash_unregister_all();
122 silc_cipher_unregister_all();
123 silc_pkcs_unregister_all();
125 silc_free(server->local_list);
126 silc_free(server->global_list);
127 silc_free(server->server_name);
128 silc_free(server->id_string);
129 silc_free(server->purge_i);
130 silc_free(server->purge_g);
134 /* Creates a new server listener. */
136 static bool silc_server_listen(SilcServer server, const char *server_ip,
137 SilcUInt16 port, int *sock)
139 *sock = silc_net_create_server(port, server_ip);
141 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
148 /* Adds a secondary listener. */
150 bool silc_server_init_secondary(SilcServer server)
152 int sock = 0, sock_list[server->config->param.connections_max];
153 SilcSocketConnection newsocket = NULL;
154 SilcServerConfigServerInfoInterface *interface;
156 for (interface = server->config->server_info->secondary; interface;
157 interface = interface->next, sock++) {
159 if (!silc_server_listen(server,
160 interface->server_ip, interface->port, &sock_list[sock]))
163 /* Set socket to non-blocking mode */
164 silc_net_set_socket_nonblock(sock_list[sock]);
166 /* Add ourselves also to the socket table. The entry allocated above
167 is sent as argument for fast referencing in the future. */
168 silc_socket_alloc(sock_list[sock],
169 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
170 server->sockets[sock_list[sock]] = newsocket;
171 SILC_SET_LISTENER(newsocket);
173 /* Perform name and address lookups to resolve the listenning address
175 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
177 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
179 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
180 newsocket->hostname ? newsocket->hostname :
181 newsocket->ip ? newsocket->ip : ""));
182 server->stat.conn_failures++;
185 if (!newsocket->hostname)
186 newsocket->hostname = strdup(newsocket->ip);
188 newsocket->port = silc_net_get_local_port(sock);
190 newsocket->user_data = (void *)server->id_entry;
191 silc_schedule_task_add(server->schedule, sock_list[sock],
192 silc_server_accept_new_connection,
193 (void *)server, 0, 0,
195 SILC_TASK_PRI_NORMAL);
201 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
205 /* Initializes the entire SILC server. This is called always before running
206 the server. This is called only once at the initialization of the program.
207 This binds the server to its listenning port. After this function returns
208 one should call silc_server_run to start the server. This returns TRUE
209 when everything is ok to run the server. Configuration file must be
210 read and parsed before calling this. */
212 bool silc_server_init(SilcServer server)
216 SilcServerEntry id_entry;
217 SilcIDListPurge purge;
218 SilcSocketConnection newsocket = NULL;
220 SILC_LOG_DEBUG(("Initializing server"));
222 server->starttime = time(NULL);
224 /* Take config object for us */
225 silc_server_config_ref(&server->config_ref, server->config,
228 /* Steal public and private key from the config object */
229 server->public_key = server->config->server_info->public_key;
230 server->private_key = server->config->server_info->private_key;
231 server->config->server_info->public_key = NULL;
232 server->config->server_info->private_key = NULL;
234 /* Register all configured ciphers, PKCS and hash functions. */
235 if (!silc_server_config_register_ciphers(server))
236 silc_cipher_register_default();
237 if (!silc_server_config_register_pkcs(server))
238 silc_pkcs_register_default();
239 if (!silc_server_config_register_hashfuncs(server))
240 silc_hash_register_default();
241 if (!silc_server_config_register_hmacs(server))
242 silc_hmac_register_default();
244 /* Initialize random number generator for the server. */
245 server->rng = silc_rng_alloc();
246 silc_rng_init(server->rng);
247 silc_rng_global_init(server->rng);
249 /* Initialize hash functions for server to use */
250 silc_hash_alloc("md5", &server->md5hash);
251 silc_hash_alloc("sha1", &server->sha1hash);
253 /* Allocate PKCS context for local public and private keys */
254 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
256 silc_pkcs_public_key_set(server->pkcs, server->public_key);
257 silc_pkcs_private_key_set(server->pkcs, server->private_key);
259 /* Initialize the scheduler */
260 server->schedule = silc_schedule_init(server->config->param.connections_max);
261 if (!server->schedule)
264 /* First, register log files configuration for error output */
265 silc_server_config_setlogfiles(server);
267 /* Initialize ID caches */
268 server->local_list->clients =
269 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
270 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
271 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
273 /* These are allocated for normal server as well as these hold some
274 global information that the server has fetched from its router. For
275 router these are used as they are supposed to be used on router. */
276 server->global_list->clients =
277 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
278 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
279 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
281 /* Init watcher list */
282 server->watcher_list =
283 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
284 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
286 if (!server->watcher_list)
289 /* Create a listening server */
290 if (!silc_server_listen(server,
291 server->config->server_info->primary == NULL ? NULL :
292 server->config->server_info->primary->server_ip,
293 server->config->server_info->primary == NULL ? 0 :
294 server->config->server_info->primary->port,
298 /* Set socket to non-blocking mode */
299 silc_net_set_socket_nonblock(sock);
302 /* Allocate the entire socket list that is used in server. Eventually
303 all connections will have entry in this table (it is a table of
304 pointers to the actual object that is allocated individually
306 server->sockets = silc_calloc(server->config->param.connections_max,
307 sizeof(*server->sockets));
308 if (!server->sockets)
311 /* Add ourselves also to the socket table. The entry allocated above
312 is sent as argument for fast referencing in the future. */
313 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
314 server->sockets[sock] = newsocket;
315 SILC_SET_LISTENER(newsocket);
317 /* Perform name and address lookups to resolve the listenning address
319 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
321 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
323 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
324 newsocket->hostname ? newsocket->hostname :
325 newsocket->ip ? newsocket->ip : ""));
326 server->stat.conn_failures++;
329 if (!newsocket->hostname)
330 newsocket->hostname = strdup(newsocket->ip);
332 newsocket->port = silc_net_get_local_port(sock);
334 /* Create a Server ID for the server. */
335 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
340 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
341 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
342 server->server_name = server->config->server_info->server_name;
343 server->config->server_info->server_name = NULL;
345 /* Add ourselves to the server list. We don't have a router yet
346 beacuse we haven't established a route yet. It will be done later.
347 For now, NULL is sent as router. This allocates new entry to
350 silc_idlist_add_server(server->local_list, strdup(server->server_name),
351 server->server_type, server->id, NULL, NULL);
353 SILC_LOG_ERROR(("Could not add ourselves to cache"));
356 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
358 /* Put the allocated socket pointer also to the entry allocated above
359 for fast back-referencing to the socket list. */
360 newsocket->user_data = (void *)id_entry;
361 id_entry->connection = (void *)newsocket;
362 server->id_entry = id_entry;
364 /* Register protocols */
365 silc_server_protocols_register();
367 /* Add the first task to the scheduler. This is task that is executed by
368 timeout. It expires as soon as the caller calls silc_server_run. This
369 task performs authentication protocol and key exchange with our
371 silc_schedule_task_add(server->schedule, 0,
372 silc_server_connect_to_router,
373 (void *)server, 0, 1,
375 SILC_TASK_PRI_NORMAL);
377 /* Add listener task to the scheduler. This task receives new connections
378 to the server. This task remains on the queue until the end of the
380 silc_schedule_task_add(server->schedule, sock,
381 silc_server_accept_new_connection,
382 (void *)server, 0, 0,
384 SILC_TASK_PRI_NORMAL);
386 if (silc_server_init_secondary(server) == FALSE)
389 server->listenning = TRUE;
391 /* If server connections has been configured then we must be router as
392 normal server cannot have server connections, only router connections. */
393 if (server->config->servers) {
394 SilcServerConfigServer *ptr = server->config->servers;
396 server->server_type = SILC_ROUTER;
398 if (ptr->backup_router) {
399 server->server_type = SILC_BACKUP_ROUTER;
400 server->backup_router = TRUE;
401 server->id_entry->server_type = SILC_BACKUP_ROUTER;
408 /* Register the ID Cache purge task. This periodically purges the ID cache
409 and removes the expired cache entries. */
411 /* Clients local list */
412 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
413 purge->cache = server->local_list->clients;
414 purge->schedule = server->schedule;
415 purge->timeout = 600;
416 silc_schedule_task_add(purge->schedule, 0,
418 (void *)purge, purge->timeout, 0,
419 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
421 /* Clients global list */
422 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
423 purge->cache = server->global_list->clients;
424 purge->schedule = server->schedule;
425 purge->timeout = 300;
426 silc_schedule_task_add(purge->schedule, 0,
428 (void *)purge, purge->timeout, 0,
429 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
431 /* If we are normal server we'll retrieve network statisticial information
432 once in a while from the router. */
433 if (server->server_type == SILC_SERVER)
434 silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
435 server, 10, 0, SILC_TASK_TIMEOUT,
438 if (server->server_type == SILC_ROUTER)
439 server->stat.routers++;
441 SILC_LOG_DEBUG(("Server initialized"));
443 /* We are done here, return succesfully */
447 silc_server_config_unref(&server->config_ref);
448 silc_net_close_server(sock);
452 /* Task callback to close a socket connection after rehash */
454 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
456 SilcServer server = context;
457 SilcSocketConnection sock = server->sockets[fd];
462 SILC_LOG_INFO(("Closing connection %s:%d [%s]: connection is unconfigured",
463 sock->hostname, sock->port,
464 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
465 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
466 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
468 silc_schedule_task_del_by_context(server->schedule, sock);
469 silc_server_disconnect_remote(server, sock,
470 SILC_STATUS_ERR_BANNED_FROM_SERVER,
471 "This connection is removed from "
474 silc_server_free_sock_user_data(server, sock, NULL);
477 /* This function basically reads the config file again and switches the config
478 object pointed by the server object. After that, we have to fix various
479 things such as the server_name and the listening ports.
480 Keep in mind that we no longer have the root privileges at this point. */
482 bool silc_server_rehash(SilcServer server)
484 SilcServerConfig newconfig;
486 SILC_LOG_INFO(("Rehashing server"));
488 /* Reset the logging system */
489 silc_log_quick = TRUE;
490 silc_log_flush_all();
492 /* Start the main rehash phase (read again the config file) */
493 newconfig = silc_server_config_alloc(server->config_file);
495 SILC_LOG_ERROR(("Rehash FAILED."));
499 /* Reinit scheduler if necessary */
500 if (newconfig->param.connections_max > server->config->param.connections_max)
501 if (!silc_schedule_reinit(server->schedule,
502 newconfig->param.connections_max))
505 /* Fix the server_name field */
506 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
507 silc_free(server->server_name);
508 server->server_name = newconfig->server_info->server_name;
509 newconfig->server_info->server_name = NULL;
511 /* Update the idcache list with a fresh pointer */
512 silc_free(server->id_entry->server_name);
513 server->id_entry->server_name = strdup(server->server_name);
514 if (!silc_idcache_del_by_context(server->local_list->servers,
517 if (!silc_idcache_add(server->local_list->servers,
518 server->id_entry->server_name,
519 server->id_entry->id, server->id_entry, 0, NULL))
524 silc_server_config_setlogfiles(server);
526 /* Change new key pair if necessary */
527 if (newconfig->server_info->public_key &&
528 !silc_pkcs_public_key_compare(server->public_key,
529 newconfig->server_info->public_key)) {
530 silc_pkcs_public_key_free(server->public_key);
531 silc_pkcs_private_key_free(server->private_key);
532 server->public_key = newconfig->server_info->public_key;
533 server->private_key = newconfig->server_info->private_key;
534 newconfig->server_info->public_key = NULL;
535 newconfig->server_info->private_key = NULL;
537 /* Allocate PKCS context for local public and private keys */
538 silc_pkcs_free(server->pkcs);
539 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
541 silc_pkcs_public_key_set(server->pkcs, server->public_key);
542 silc_pkcs_private_key_set(server->pkcs, server->private_key);
545 /* Check for unconfigured server and router connections and close
546 connections that were unconfigured. */
548 if (server->config->routers) {
549 SilcServerConfigRouter *ptr;
550 SilcServerConfigRouter *newptr;
553 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
556 /* Check whether new config has this one too */
557 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
558 if (!strcmp(newptr->host, ptr->host) && newptr->port == ptr->port &&
559 newptr->initiator == ptr->initiator) {
566 /* Remove this connection */
567 SilcSocketConnection sock;
568 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
569 ptr->host, ptr->port);
570 if (sock && !SILC_IS_LISTENER(sock))
571 silc_schedule_task_add(server->schedule, sock->sock,
572 silc_server_rehash_close_connection,
573 server, 0, 1, SILC_TASK_TIMEOUT,
574 SILC_TASK_PRI_NORMAL);
579 if (server->config->servers) {
580 SilcServerConfigServer *ptr;
581 SilcServerConfigServer *newptr;
584 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
587 /* Check whether new config has this one too */
588 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
589 if (!strcmp(newptr->host, ptr->host)) {
596 /* Remove this connection */
597 SilcSocketConnection sock;
598 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
600 if (sock && !SILC_IS_LISTENER(sock))
601 silc_schedule_task_add(server->schedule, sock->sock,
602 silc_server_rehash_close_connection,
603 server, 0, 1, SILC_TASK_TIMEOUT,
604 SILC_TASK_PRI_NORMAL);
609 /* Go through all configured routers after rehash */
610 silc_schedule_task_add(server->schedule, 0,
611 silc_server_connect_to_router,
612 (void *)server, 0, 1,
614 SILC_TASK_PRI_NORMAL);
616 /* Check whether our router status has changed */
617 if (newconfig->servers) {
618 SilcServerConfigServer *ptr = newconfig->servers;
620 server->server_type = SILC_ROUTER;
622 if (ptr->backup_router) {
623 server->server_type = SILC_BACKUP_ROUTER;
624 server->backup_router = TRUE;
625 server->id_entry->server_type = SILC_BACKUP_ROUTER;
632 /* Our old config is gone now. We'll unreference our reference made in
633 silc_server_init and then destroy it since we are destroying it
634 underneath the application (layer which called silc_server_init). */
635 silc_server_config_unref(&server->config_ref);
636 silc_server_config_destroy(server->config);
638 /* Take new config context */
639 server->config = newconfig;
640 silc_server_config_ref(&server->config_ref, server->config, server->config);
642 SILC_LOG_DEBUG(("Server rehashed"));
647 /* The heart of the server. This runs the scheduler thus runs the server.
648 When this returns the server has been stopped and the program will
651 void silc_server_run(SilcServer server)
653 SILC_LOG_INFO(("SILC Server started"));
655 /* Start the scheduler, the heart of the SILC server. When this returns
656 the program will be terminated. */
657 silc_schedule(server->schedule);
660 /* Stops the SILC server. This function is used to shutdown the server.
661 This is usually called after the scheduler has returned. After stopping
662 the server one should call silc_server_free. */
664 void silc_server_stop(SilcServer server)
666 SILC_LOG_DEBUG(("Stopping server"));
668 if (server->schedule) {
671 server->server_shutdown = TRUE;
673 /* Close all connections */
674 for (i = 0; i < server->config->param.connections_max; i++) {
675 if (!server->sockets[i])
677 if (!SILC_IS_LISTENER(server->sockets[i])) {
678 SilcSocketConnection sock = server->sockets[i];
679 SilcIDListData idata = sock->user_data;
682 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
684 silc_schedule_task_del_by_context(server->schedule,
686 silc_server_disconnect_remote(server, server->sockets[i],
688 "Server is shutting down");
690 silc_server_free_sock_user_data(server, sock,
691 "Server is shutting down");
692 silc_socket_free(sock);
694 silc_socket_free(server->sockets[i]);
695 server->sockets[i] = NULL;
699 /* We are not connected to network anymore */
700 server->standalone = TRUE;
702 silc_schedule_stop(server->schedule);
703 silc_schedule_uninit(server->schedule);
704 server->schedule = NULL;
706 silc_free(server->sockets);
707 server->sockets = NULL;
710 silc_server_protocols_unregister();
712 SILC_LOG_DEBUG(("Server stopped"));
715 /* Function that is called when the network connection to a router has
716 been established. This will continue with the key exchange protocol
717 with the remote router. */
719 void silc_server_start_key_exchange(SilcServer server,
720 SilcServerConnection sconn,
723 SilcSocketConnection newsocket;
724 SilcProtocol protocol;
725 SilcServerKEInternalContext *proto_ctx;
726 SilcServerConfigRouter *conn =
727 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
730 /* Cancel any possible retry timeouts */
731 silc_schedule_task_del_by_callback(server->schedule,
732 silc_server_connect_to_router_retry);
734 /* Set socket options */
735 silc_net_set_socket_nonblock(sock);
736 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
738 /* Create socket connection for the connection. Even though we
739 know that we are connecting to a router we will mark the socket
740 to be unknown connection until we have executed authentication
742 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
743 server->sockets[sock] = newsocket;
744 newsocket->hostname = strdup(sconn->remote_host);
745 newsocket->ip = strdup(sconn->remote_host);
746 newsocket->port = sconn->remote_port;
747 sconn->sock = newsocket;
749 /* Allocate internal protocol context. This is sent as context
751 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
752 proto_ctx->server = (void *)server;
753 proto_ctx->context = (void *)sconn;
754 proto_ctx->sock = newsocket;
755 proto_ctx->rng = server->rng;
756 proto_ctx->responder = FALSE;
758 /* Set Key Exchange flags from configuration, but fall back to global
760 SILC_GET_SKE_FLAGS(conn, proto_ctx);
761 if (server->config->param.key_exchange_pfs)
762 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
764 /* Perform key exchange protocol. silc_server_connect_to_router_second
765 will be called after the protocol is finished. */
766 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
767 &protocol, proto_ctx,
768 silc_server_connect_to_router_second);
769 newsocket->protocol = protocol;
771 /* Register a timeout task that will be executed if the protocol
772 is not executed within set limit. */
773 proto_ctx->timeout_task =
774 silc_schedule_task_add(server->schedule, sock,
775 silc_server_timeout_remote,
776 server, server->config->key_exchange_timeout, 0,
780 /* Register the connection for network input and output. This sets
781 that scheduler will listen for incoming packets for this connection
782 and sets that outgoing packets may be sent to this connection as
783 well. However, this doesn't set the scheduler for outgoing traffic,
784 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
785 later when outgoing data is available. */
786 context = (void *)server;
787 SILC_REGISTER_CONNECTION_FOR_IO(sock);
789 /* Run the protocol */
790 silc_protocol_execute(protocol, server->schedule, 0, 0);
793 /* Timeout callback that will be called to retry connecting to remote
794 router. This is used by both normal and router server. This will wait
795 before retrying the connecting. The timeout is generated by exponential
796 backoff algorithm. */
798 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
800 SilcServerConnection sconn = (SilcServerConnection)context;
801 SilcServer server = sconn->server;
802 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
803 SilcServerConfigConnParams *param =
804 (conn->param ? conn->param : &server->config->param);
806 /* Don't retry if we are shutting down. */
807 if (server->server_shutdown) {
808 silc_server_config_unref(&sconn->conn);
809 silc_free(sconn->remote_host);
810 silc_free(sconn->backup_replace_ip);
815 SILC_LOG_INFO(("Retrying connecting to a router"));
817 /* Calculate next timeout */
818 if (sconn->retry_count >= 1) {
819 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
820 if (sconn->retry_timeout > param->reconnect_interval_max)
821 sconn->retry_timeout = param->reconnect_interval_max;
823 sconn->retry_timeout = param->reconnect_interval;
825 sconn->retry_count++;
826 sconn->retry_timeout = sconn->retry_timeout +
827 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
829 /* If we've reached max retry count, give up. */
830 if ((sconn->retry_count > param->reconnect_count) &&
831 !param->reconnect_keep_trying) {
832 SILC_LOG_ERROR(("Could not connect to router, giving up"));
833 silc_server_config_unref(&sconn->conn);
834 silc_free(sconn->remote_host);
835 silc_free(sconn->backup_replace_ip);
840 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
841 sconn->retry_timeout));
843 /* We will lookup a fresh pointer later */
844 silc_server_config_unref(&sconn->conn);
846 /* Wait one before retrying */
847 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
848 context, sconn->retry_timeout, 0,
849 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
852 /* Generic routine to use connect to a router. */
854 SILC_TASK_CALLBACK(silc_server_connect_router)
856 SilcServerConnection sconn = (SilcServerConnection)context;
857 SilcServer server = sconn->server;
858 SilcServerConfigRouter *rconn;
861 /* Don't connect if we are shutting down. */
862 if (server->server_shutdown) {
863 silc_free(sconn->remote_host);
864 silc_free(sconn->backup_replace_ip);
869 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
870 (sconn->backup ? "backup router" : "router"),
871 sconn->remote_host, sconn->remote_port));
873 server->router_connect = time(NULL);
874 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
877 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
878 (sconn->backup ? "backup router" : "router"),
879 sconn->remote_host, sconn->remote_port));
880 silc_free(sconn->remote_host);
881 silc_free(sconn->backup_replace_ip);
885 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
887 /* Connect to remote host */
888 sock = silc_net_create_connection(
889 (!server->config->server_info->primary ? NULL :
890 server->config->server_info->primary->server_ip),
891 sconn->remote_port, sconn->remote_host);
893 SILC_LOG_ERROR(("Could not connect to router %s:%d",
894 sconn->remote_host, sconn->remote_port));
895 if (!sconn->no_reconnect)
896 silc_schedule_task_add(server->schedule, 0,
897 silc_server_connect_to_router_retry,
898 context, 0, 1, SILC_TASK_TIMEOUT,
899 SILC_TASK_PRI_NORMAL);
901 silc_server_config_unref(&sconn->conn);
905 /* Continue with key exchange protocol */
906 silc_server_start_key_exchange(server, sconn, sock);
909 /* This function connects to our primary router or if we are a router this
910 establishes all our primary routes. This is called at the start of the
911 server to do authentication and key exchange with our router - called
914 SILC_TASK_CALLBACK(silc_server_connect_to_router)
916 SilcServer server = (SilcServer)context;
917 SilcServerConnection sconn;
918 SilcServerConfigRouter *ptr;
920 /* Don't connect if we are shutting down. */
921 if (server->server_shutdown)
924 SILC_LOG_DEBUG(("We are %s",
925 (server->server_type == SILC_SERVER ?
926 "normal server" : server->server_type == SILC_ROUTER ?
927 "router" : "backup router/normal server")));
929 if (!server->config->routers) {
930 /* There wasn't a configured router, we will continue but we don't
931 have a connection to outside world. We will be standalone server. */
932 SILC_LOG_DEBUG(("No router(s), we are standalone"));
933 server->standalone = TRUE;
937 /* Cancel any possible retry timeouts */
938 silc_schedule_task_del_by_callback(server->schedule,
939 silc_server_connect_router);
940 silc_schedule_task_del_by_callback(server->schedule,
941 silc_server_connect_to_router_retry);
943 /* Create the connections to all our routes */
944 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
946 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
947 ptr->backup_router ? "Backup router" : "Router",
948 ptr->initiator ? "Initiator" : "Responder",
949 ptr->host, ptr->port));
951 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
952 ptr->initiator == FALSE && !server->backup_router &&
953 !silc_server_config_get_backup_router(server))
954 server->wait_backup = TRUE;
956 if (ptr->initiator) {
957 /* Check whether we are connected to this host already */
958 if (silc_server_num_sockets_by_remote(server,
959 silc_net_is_ip(ptr->host) ?
961 silc_net_is_ip(ptr->host) ?
962 NULL : ptr->host, ptr->port,
963 SILC_SOCKET_TYPE_ROUTER)) {
964 SILC_LOG_DEBUG(("We are already connected to this router"));
968 /* Allocate connection object for hold connection specific stuff. */
969 sconn = silc_calloc(1, sizeof(*sconn));
970 sconn->server = server;
971 sconn->remote_host = strdup(ptr->host);
972 sconn->remote_port = ptr->port;
973 sconn->backup = ptr->backup_router;
975 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
976 sconn->backup_replace_port = ptr->backup_replace_port;
979 if (!server->router_conn && !sconn->backup)
980 server->router_conn = sconn;
982 silc_schedule_task_add(server->schedule, 0,
983 silc_server_connect_router,
984 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
985 SILC_TASK_PRI_NORMAL);
990 /* Second part of connecting to router(s). Key exchange protocol has been
991 executed and now we will execute authentication protocol. */
993 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
995 SilcProtocol protocol = (SilcProtocol)context;
996 SilcServerKEInternalContext *ctx =
997 (SilcServerKEInternalContext *)protocol->context;
998 SilcServer server = (SilcServer)ctx->server;
999 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1000 SilcSocketConnection sock = ctx->sock;
1001 SilcServerConnAuthInternalContext *proto_ctx;
1002 SilcServerConfigRouter *conn = NULL;
1004 SILC_LOG_DEBUG(("Start"));
1006 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1007 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1008 /* Error occured during protocol */
1009 silc_protocol_free(protocol);
1010 sock->protocol = NULL;
1011 silc_ske_free_key_material(ctx->keymat);
1013 silc_packet_context_free(ctx->packet);
1015 silc_ske_free(ctx->ske);
1016 silc_free(ctx->dest_id);
1018 silc_schedule_task_del_by_callback(server->schedule,
1019 silc_server_failure_callback);
1020 silc_server_disconnect_remote(server, sock,
1021 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1023 /* Try reconnecting if configuration wants it */
1024 if (!sconn->no_reconnect) {
1025 silc_schedule_task_add(server->schedule, 0,
1026 silc_server_connect_to_router_retry,
1027 sconn, 0, 1, SILC_TASK_TIMEOUT,
1028 SILC_TASK_PRI_NORMAL);
1032 /* Call completion to indicate error */
1033 if (sconn->callback)
1034 (*sconn->callback)(server, NULL, sconn->callback_context);
1036 silc_server_config_unref(&sconn->conn);
1037 silc_free(sconn->remote_host);
1038 silc_free(sconn->backup_replace_ip);
1043 /* We now have the key material as the result of the key exchange
1044 protocol. Take the key material into use. Free the raw key material
1045 as soon as we've set them into use. */
1046 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1047 ctx->sock, ctx->keymat,
1048 ctx->ske->prop->cipher,
1049 ctx->ske->prop->pkcs,
1050 ctx->ske->prop->hash,
1051 ctx->ske->prop->hmac,
1052 ctx->ske->prop->group,
1054 silc_protocol_free(protocol);
1055 sock->protocol = NULL;
1056 silc_ske_free_key_material(ctx->keymat);
1058 silc_packet_context_free(ctx->packet);
1060 silc_ske_free(ctx->ske);
1061 silc_free(ctx->dest_id);
1063 silc_schedule_task_del_by_callback(server->schedule,
1064 silc_server_failure_callback);
1065 silc_server_disconnect_remote(server, sock,
1066 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1068 /* Try reconnecting if configuration wants it */
1069 if (!sconn->no_reconnect) {
1070 silc_schedule_task_add(server->schedule, 0,
1071 silc_server_connect_to_router_retry,
1072 sconn, 0, 1, SILC_TASK_TIMEOUT,
1073 SILC_TASK_PRI_NORMAL);
1077 /* Call completion to indicate error */
1078 if (sconn->callback)
1079 (*sconn->callback)(server, NULL, sconn->callback_context);
1081 silc_server_config_unref(&sconn->conn);
1082 silc_free(sconn->remote_host);
1083 silc_free(sconn->backup_replace_ip);
1087 silc_ske_free_key_material(ctx->keymat);
1089 /* Allocate internal context for the authentication protocol. This
1090 is sent as context for the protocol. */
1091 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1092 proto_ctx->server = (void *)server;
1093 proto_ctx->context = (void *)sconn;
1094 proto_ctx->sock = sock;
1095 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1096 proto_ctx->dest_id_type = ctx->dest_id_type;
1097 proto_ctx->dest_id = ctx->dest_id;
1099 /* Resolve the authentication method used in this connection. Check if
1100 we find a match from user configured connections */
1101 if (!sconn->conn.ref_ptr)
1102 conn = silc_server_config_find_router_conn(server, sock->hostname,
1105 conn = sconn->conn.ref_ptr;
1108 /* Match found. Use the configured authentication method. Take only
1109 the passphrase, since for public key auth we automatically use
1110 our local key pair. */
1111 if (conn->passphrase) {
1112 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1113 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1115 proto_ctx->auth_data = strdup(conn->passphrase);
1116 proto_ctx->auth_data_len = strlen(conn->passphrase);
1117 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1119 } else if (conn->publickeys) {
1120 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1122 proto_ctx->auth_meth = SILC_AUTH_NONE;
1125 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1126 sock->hostname, sock->ip, sock->port));
1127 silc_protocol_free(protocol);
1128 sock->protocol = NULL;
1130 silc_packet_context_free(ctx->packet);
1132 silc_ske_free(ctx->ske);
1133 silc_free(ctx->dest_id);
1135 silc_server_config_unref(&sconn->conn);
1136 silc_free(sconn->remote_host);
1137 silc_free(sconn->backup_replace_ip);
1139 silc_schedule_task_del_by_callback(server->schedule,
1140 silc_server_failure_callback);
1141 silc_server_disconnect_remote(server, sock,
1142 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1146 /* Free old protocol as it is finished now */
1147 silc_protocol_free(protocol);
1149 silc_packet_context_free(ctx->packet);
1151 sock->protocol = NULL;
1153 /* Allocate the authentication protocol. This is allocated here
1154 but we won't start it yet. We will be receiving party of this
1155 protocol thus we will wait that connecting party will make
1156 their first move. */
1157 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1158 &sock->protocol, proto_ctx,
1159 silc_server_connect_to_router_final);
1161 /* Register timeout task. If the protocol is not executed inside
1162 this timelimit the connection will be terminated. */
1163 proto_ctx->timeout_task =
1164 silc_schedule_task_add(server->schedule, sock->sock,
1165 silc_server_timeout_remote,
1167 server->config->conn_auth_timeout, 0,
1171 /* Run the protocol */
1172 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1175 /* Finalizes the connection to router. Registers a server task to the
1176 queue so that we can accept new connections. */
1178 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1180 SilcProtocol protocol = (SilcProtocol)context;
1181 SilcServerConnAuthInternalContext *ctx =
1182 (SilcServerConnAuthInternalContext *)protocol->context;
1183 SilcServer server = (SilcServer)ctx->server;
1184 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1185 SilcSocketConnection sock = ctx->sock;
1186 SilcServerEntry id_entry = NULL;
1188 SilcServerHBContext hb_context;
1189 unsigned char *id_string;
1191 SilcIDListData idata;
1192 SilcServerConfigRouter *conn = NULL;
1193 SilcServerConfigConnParams *param = NULL;
1195 SILC_LOG_DEBUG(("Start"));
1197 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1198 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1199 /* Error occured during protocol */
1200 silc_free(ctx->dest_id);
1201 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1204 /* Try reconnecting if configuration wants it */
1205 if (!sconn->no_reconnect) {
1206 silc_schedule_task_add(server->schedule, 0,
1207 silc_server_connect_to_router_retry,
1208 sconn, 0, 1, SILC_TASK_TIMEOUT,
1209 SILC_TASK_PRI_NORMAL);
1216 /* Add a task to the queue. This task receives new connections to the
1217 server. This task remains on the queue until the end of the program. */
1218 if (!server->listenning && !sconn->backup) {
1219 silc_schedule_task_add(server->schedule, server->sock,
1220 silc_server_accept_new_connection,
1221 (void *)server, 0, 0,
1223 SILC_TASK_PRI_NORMAL);
1224 server->listenning = TRUE;
1227 /* Send NEW_SERVER packet to the router. We will become registered
1228 to the SILC network after sending this packet. */
1229 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1230 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1231 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1232 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1233 silc_buffer_format(packet,
1234 SILC_STR_UI_SHORT(id_len),
1235 SILC_STR_UI_XNSTRING(id_string, id_len),
1236 SILC_STR_UI_SHORT(strlen(server->server_name)),
1237 SILC_STR_UI_XNSTRING(server->server_name,
1238 strlen(server->server_name)),
1241 /* Send the packet */
1242 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1243 packet->data, packet->len, TRUE);
1244 silc_buffer_free(packet);
1245 silc_free(id_string);
1247 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1249 /* Check that we do not have this ID already */
1250 id_entry = silc_idlist_find_server_by_id(server->local_list,
1251 ctx->dest_id, TRUE, NULL);
1253 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1255 id_entry = silc_idlist_find_server_by_id(server->global_list,
1256 ctx->dest_id, TRUE, NULL);
1258 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1261 SILC_LOG_DEBUG(("New server id(%s)",
1262 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1264 /* Add the connected router to global server list. Router is sent
1265 as NULL since it's local to us. */
1266 id_entry = silc_idlist_add_server(server->global_list,
1267 strdup(sock->hostname),
1268 SILC_ROUTER, ctx->dest_id, NULL, sock);
1270 silc_free(ctx->dest_id);
1271 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1272 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1277 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1278 silc_free(sock->user_data);
1279 sock->user_data = (void *)id_entry;
1280 sock->type = SILC_SOCKET_TYPE_ROUTER;
1281 idata = (SilcIDListData)sock->user_data;
1282 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1283 SILC_IDLIST_STATUS_LOCAL);
1285 conn = sconn->conn.ref_ptr;
1286 param = &server->config->param;
1287 if (conn && conn->param)
1288 param = conn->param;
1290 /* Perform keepalive. The `hb_context' will be freed automatically
1291 when finally calling the silc_socket_free function. */
1292 hb_context = silc_calloc(1, sizeof(*hb_context));
1293 hb_context->server = server;
1294 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1295 silc_server_perform_heartbeat,
1298 /* Register re-key timeout */
1299 idata->rekey->timeout = param->key_exchange_rekey;
1300 idata->rekey->context = (void *)server;
1301 silc_schedule_task_add(server->schedule, sock->sock,
1302 silc_server_rekey_callback,
1303 (void *)sock, idata->rekey->timeout, 0,
1304 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1306 if (!sconn->backup) {
1307 /* Mark this router our primary router if we're still standalone */
1308 if (server->standalone) {
1309 server->id_entry->router = id_entry;
1310 server->router = id_entry;
1311 server->standalone = FALSE;
1313 /* If we are router then announce our possible servers. Backup
1314 router announces also global servers. */
1315 if (server->server_type == SILC_ROUTER)
1316 silc_server_announce_servers(server,
1317 server->backup_router ? TRUE : FALSE,
1318 0, SILC_PRIMARY_ROUTE(server));
1320 /* Announce our clients and channels to the router */
1321 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1322 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1324 /* If we are backup router then this primary router is whom we are
1326 if (server->server_type == SILC_BACKUP_ROUTER)
1327 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1330 /* Add this server to be our backup router */
1331 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1332 sconn->backup_replace_port, FALSE);
1335 sock->protocol = NULL;
1338 /* Call the completion callback to indicate that we've connected to
1340 if (sconn && sconn->callback)
1341 (*sconn->callback)(server, id_entry, sconn->callback_context);
1343 /* Free the temporary connection data context */
1345 silc_server_config_unref(&sconn->conn);
1346 silc_free(sconn->remote_host);
1347 silc_free(sconn->backup_replace_ip);
1350 if (sconn == server->router_conn)
1351 server->router_conn = NULL;
1354 /* Free the protocol object */
1355 if (sock->protocol == protocol)
1356 sock->protocol = NULL;
1357 silc_protocol_free(protocol);
1359 silc_packet_context_free(ctx->packet);
1361 silc_ske_free(ctx->ske);
1362 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1363 silc_free(ctx->auth_data);
1367 /* Host lookup callback that is called after the incoming connection's
1368 IP and FQDN lookup is performed. This will actually check the acceptance
1369 of the incoming connection and will register the key exchange protocol
1370 for this connection. */
1373 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1376 SilcServerKEInternalContext *proto_ctx =
1377 (SilcServerKEInternalContext *)context;
1378 SilcServer server = (SilcServer)proto_ctx->server;
1379 SilcServerConfigClient *cconfig = NULL;
1380 SilcServerConfigServer *sconfig = NULL;
1381 SilcServerConfigRouter *rconfig = NULL;
1382 SilcServerConfigDeny *deny;
1385 context = (void *)server;
1387 /* Check whether we could resolve both IP and FQDN. */
1388 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1389 server->config->require_reverse_lookup)) {
1390 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1391 sock->hostname ? sock->hostname :
1392 sock->ip ? sock->ip : ""));
1393 server->stat.conn_failures++;
1394 silc_server_disconnect_remote(server, sock,
1395 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1396 "Unknown host or IP");
1397 silc_free(proto_ctx);
1401 /* Register the connection for network input and output. This sets
1402 that scheduler will listen for incoming packets for this connection
1403 and sets that outgoing packets may be sent to this connection as well.
1404 However, this doesn't set the scheduler for outgoing traffic, it
1405 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1406 later when outgoing data is available. */
1407 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1409 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1412 /* Listenning port */
1413 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1414 silc_server_disconnect_remote(server, sock,
1415 SILC_STATUS_ERR_RESOURCE_LIMIT,
1416 "Connection refused");
1417 server->stat.conn_failures++;
1418 silc_free(proto_ctx);
1421 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1423 /* Check whether this connection is denied to connect to us. */
1424 deny = silc_server_config_find_denied(server, sock->ip);
1426 deny = silc_server_config_find_denied(server, sock->hostname);
1428 /* The connection is denied */
1429 SILC_LOG_INFO(("Connection %s (%s) is denied",
1430 sock->hostname, sock->ip));
1431 silc_server_disconnect_remote(server, sock,
1432 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1434 server->stat.conn_failures++;
1435 silc_free(proto_ctx);
1439 /* Check whether we have configured this sort of connection at all. We
1440 have to check all configurations since we don't know what type of
1441 connection this is. */
1442 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1443 cconfig = silc_server_config_find_client(server, sock->hostname);
1444 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1445 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1446 if (server->server_type == SILC_ROUTER) {
1447 if (!(rconfig = silc_server_config_find_router_conn(server,
1448 sock->ip, sock->port)))
1449 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1452 if (!cconfig && !sconfig && !rconfig) {
1453 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1455 silc_server_disconnect_remote(server, sock,
1456 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1457 server->stat.conn_failures++;
1458 silc_free(proto_ctx);
1462 /* The connection is allowed */
1464 /* Set internal context for key exchange protocol. This is
1465 sent as context for the protocol. */
1466 proto_ctx->sock = sock;
1467 proto_ctx->rng = server->rng;
1468 proto_ctx->responder = TRUE;
1469 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1470 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1471 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1473 /* Take flags for key exchange. Since we do not know what type of connection
1474 this is, we go through all found configurations and use the global ones
1475 as well. This will result always into strictest key exchange flags. */
1476 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1477 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1478 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1479 if (server->config->param.key_exchange_pfs)
1480 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1482 /* Prepare the connection for key exchange protocol. We allocate the
1483 protocol but will not start it yet. The connector will be the
1484 initiator of the protocol thus we will wait for initiation from
1485 there before we start the protocol. */
1486 server->stat.auth_attempts++;
1487 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1488 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1489 &sock->protocol, proto_ctx,
1490 silc_server_accept_new_connection_second);
1492 /* Register a timeout task that will be executed if the connector
1493 will not start the key exchange protocol within specified timeout
1494 and the connection will be closed. */
1495 proto_ctx->timeout_task =
1496 silc_schedule_task_add(server->schedule, sock->sock,
1497 silc_server_timeout_remote,
1499 server->config->key_exchange_timeout, 0,
1504 /* Accepts new connections to the server. Accepting new connections are
1505 done in three parts to make it async. */
1507 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1509 SilcServer server = (SilcServer)context;
1510 SilcSocketConnection newsocket;
1511 SilcServerKEInternalContext *proto_ctx;
1514 SILC_LOG_DEBUG(("Accepting new connection"));
1516 server->stat.conn_attempts++;
1518 sock = silc_net_accept_connection(fd);
1520 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1521 server->stat.conn_failures++;
1525 /* Check for maximum allowed connections */
1526 if (sock > server->config->param.connections_max) {
1527 SILC_LOG_ERROR(("Refusing connection, server is full"));
1528 server->stat.conn_failures++;
1529 silc_net_close_connection(sock);
1533 /* Set socket options */
1534 silc_net_set_socket_nonblock(sock);
1535 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1537 /* We don't create a ID yet, since we don't know what type of connection
1538 this is yet. But, we do add the connection to the socket table. */
1539 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1540 server->sockets[sock] = newsocket;
1542 /* Perform asynchronous host lookup. This will lookup the IP and the
1543 FQDN of the remote connection. After the lookup is done the connection
1544 is accepted further. */
1545 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1546 proto_ctx->server = server;
1547 proto_ctx->context = (void *)fd;
1548 silc_socket_host_lookup(newsocket, TRUE,
1549 silc_server_accept_new_connection_lookup,
1550 (void *)proto_ctx, server->schedule);
1553 /* Second part of accepting new connection. Key exchange protocol has been
1554 performed and now it is time to do little connection authentication
1555 protocol to figure out whether this connection is client or server
1556 and whether it has right to access this server (especially server
1557 connections needs to be authenticated). */
1559 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1561 SilcProtocol protocol = (SilcProtocol)context;
1562 SilcServerKEInternalContext *ctx =
1563 (SilcServerKEInternalContext *)protocol->context;
1564 SilcServer server = (SilcServer)ctx->server;
1565 SilcSocketConnection sock = ctx->sock;
1566 SilcServerConnAuthInternalContext *proto_ctx;
1568 SILC_LOG_DEBUG(("Start"));
1570 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1571 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1572 /* Error occured during protocol */
1573 SILC_LOG_DEBUG(("Error key exchange protocol"));
1574 silc_protocol_free(protocol);
1575 sock->protocol = NULL;
1576 silc_ske_free_key_material(ctx->keymat);
1578 silc_packet_context_free(ctx->packet);
1580 silc_ske_free(ctx->ske);
1581 silc_free(ctx->dest_id);
1582 silc_server_config_unref(&ctx->cconfig);
1583 silc_server_config_unref(&ctx->sconfig);
1584 silc_server_config_unref(&ctx->rconfig);
1586 silc_schedule_task_del_by_callback(server->schedule,
1587 silc_server_failure_callback);
1588 silc_server_disconnect_remote(server, sock,
1589 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1591 server->stat.auth_failures++;
1595 /* We now have the key material as the result of the key exchange
1596 protocol. Take the key material into use. Free the raw key material
1597 as soon as we've set them into use. */
1598 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1599 ctx->sock, ctx->keymat,
1600 ctx->ske->prop->cipher,
1601 ctx->ske->prop->pkcs,
1602 ctx->ske->prop->hash,
1603 ctx->ske->prop->hmac,
1604 ctx->ske->prop->group,
1606 SILC_LOG_ERROR(("Error setting key material in use"));
1607 silc_protocol_free(protocol);
1608 sock->protocol = NULL;
1609 silc_ske_free_key_material(ctx->keymat);
1611 silc_packet_context_free(ctx->packet);
1613 silc_ske_free(ctx->ske);
1614 silc_free(ctx->dest_id);
1615 silc_server_config_unref(&ctx->cconfig);
1616 silc_server_config_unref(&ctx->sconfig);
1617 silc_server_config_unref(&ctx->rconfig);
1619 silc_schedule_task_del_by_callback(server->schedule,
1620 silc_server_failure_callback);
1621 silc_server_disconnect_remote(server, sock,
1622 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1623 server->stat.auth_failures++;
1626 silc_ske_free_key_material(ctx->keymat);
1628 /* Allocate internal context for the authentication protocol. This
1629 is sent as context for the protocol. */
1630 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1631 proto_ctx->server = (void *)server;
1632 proto_ctx->sock = sock;
1633 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1634 proto_ctx->responder = TRUE;
1635 proto_ctx->dest_id_type = ctx->dest_id_type;
1636 proto_ctx->dest_id = ctx->dest_id;
1637 proto_ctx->cconfig = ctx->cconfig;
1638 proto_ctx->sconfig = ctx->sconfig;
1639 proto_ctx->rconfig = ctx->rconfig;
1641 /* Free old protocol as it is finished now */
1642 silc_protocol_free(protocol);
1644 silc_packet_context_free(ctx->packet);
1646 sock->protocol = NULL;
1648 /* Allocate the authentication protocol. This is allocated here
1649 but we won't start it yet. We will be receiving party of this
1650 protocol thus we will wait that connecting party will make
1651 their first move. */
1652 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1653 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1654 &sock->protocol, proto_ctx,
1655 silc_server_accept_new_connection_final);
1657 /* Register timeout task. If the protocol is not executed inside
1658 this timelimit the connection will be terminated. */
1659 proto_ctx->timeout_task =
1660 silc_schedule_task_add(server->schedule, sock->sock,
1661 silc_server_timeout_remote,
1663 server->config->conn_auth_timeout, 0,
1668 /* After this is called, server don't wait for backup router anymore.
1669 This gets called automatically even after we have backup router
1670 connection established. */
1672 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1674 SilcServer server = context;
1675 server->wait_backup = FALSE;
1678 /* Final part of accepting new connection. The connection has now
1679 been authenticated and keys has been exchanged. We also know whether
1680 this is client or server connection. */
1682 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1684 SilcProtocol protocol = (SilcProtocol)context;
1685 SilcServerConnAuthInternalContext *ctx =
1686 (SilcServerConnAuthInternalContext *)protocol->context;
1687 SilcServer server = (SilcServer)ctx->server;
1688 SilcSocketConnection sock = ctx->sock;
1689 SilcServerHBContext hb_context;
1690 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1692 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1694 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1695 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1696 /* Error occured during protocol */
1697 SILC_LOG_DEBUG(("Error during authentication protocol"));
1698 silc_protocol_free(protocol);
1699 sock->protocol = NULL;
1701 silc_packet_context_free(ctx->packet);
1703 silc_ske_free(ctx->ske);
1704 silc_free(ctx->dest_id);
1705 silc_server_config_unref(&ctx->cconfig);
1706 silc_server_config_unref(&ctx->sconfig);
1707 silc_server_config_unref(&ctx->rconfig);
1709 silc_schedule_task_del_by_callback(server->schedule,
1710 silc_server_failure_callback);
1711 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1713 server->stat.auth_failures++;
1717 entry->data.last_receive = time(NULL);
1719 switch (ctx->conn_type) {
1720 case SILC_SOCKET_TYPE_CLIENT:
1722 SilcClientEntry client;
1723 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1725 /* Verify whether this connection is after all allowed to connect */
1726 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1727 &server->config->param,
1728 conn->param, ctx->ske)) {
1729 server->stat.auth_failures++;
1733 /* If we are primary router and we have backup router configured
1734 but it has not connected to use yet, do not accept any other
1736 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1737 !server->backup_router) {
1738 SilcServerConfigRouter *router;
1739 router = silc_server_config_get_backup_router(server);
1740 if (router && strcmp(server->config->server_info->primary->server_ip,
1742 silc_server_find_socket_by_host(server,
1743 SILC_SOCKET_TYPE_SERVER,
1744 router->backup_replace_ip, 0)) {
1745 SILC_LOG_INFO(("Will not accept connections because we do "
1746 "not have backup router connection established"));
1747 silc_server_disconnect_remote(server, sock,
1748 SILC_STATUS_ERR_PERM_DENIED,
1749 "We do not have connection to backup "
1750 "router established, try later");
1751 silc_free(sock->user_data);
1752 server->stat.auth_failures++;
1754 /* From here on, wait 10 seconds for the backup router to appear. */
1755 silc_schedule_task_add(server->schedule, 0,
1756 silc_server_backup_router_wait,
1757 (void *)server, 10, 0,
1758 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1763 SILC_LOG_DEBUG(("Remote host is client"));
1764 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1767 /* Add the client to the client ID cache. The nickname and Client ID
1768 and other information is created after we have received NEW_CLIENT
1769 packet from client. */
1770 client = silc_idlist_add_client(server->local_list,
1771 NULL, NULL, NULL, NULL, NULL, sock, 0);
1773 SILC_LOG_ERROR(("Could not add new client to cache"));
1774 silc_free(sock->user_data);
1775 silc_server_disconnect_remote(server, sock,
1776 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1777 server->stat.auth_failures++;
1780 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1783 server->stat.my_clients++;
1784 server->stat.clients++;
1785 server->stat.cell_clients++;
1787 /* Get connection parameters */
1789 if (conn->param->keepalive_secs)
1790 hearbeat_timeout = conn->param->keepalive_secs;
1793 id_entry = (void *)client;
1796 case SILC_SOCKET_TYPE_SERVER:
1797 case SILC_SOCKET_TYPE_ROUTER:
1799 SilcServerEntry new_server;
1800 bool initiator = FALSE;
1801 bool backup_local = FALSE;
1802 bool backup_router = FALSE;
1803 char *backup_replace_ip = NULL;
1804 SilcUInt16 backup_replace_port = 0;
1805 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1806 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1808 /* If we are backup router and this is incoming server connection
1809 and we do not have connection to primary router, do not allow
1811 if (server->server_type == SILC_BACKUP_ROUTER &&
1812 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1813 !SILC_PRIMARY_ROUTE(server)) {
1814 SILC_LOG_INFO(("Will not accept server connection because we do "
1815 "not have primary router connection established"));
1816 silc_server_disconnect_remote(server, sock,
1817 SILC_STATUS_ERR_PERM_DENIED,
1818 "We do not have connection to primary "
1819 "router established, try later");
1820 silc_free(sock->user_data);
1821 server->stat.auth_failures++;
1825 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1826 /* Verify whether this connection is after all allowed to connect */
1827 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1828 &server->config->param,
1829 rconn ? rconn->param : NULL,
1831 silc_free(sock->user_data);
1832 server->stat.auth_failures++;
1838 if (rconn->param->keepalive_secs)
1839 hearbeat_timeout = rconn->param->keepalive_secs;
1842 initiator = rconn->initiator;
1843 backup_local = rconn->backup_local;
1844 backup_router = rconn->backup_router;
1845 backup_replace_ip = rconn->backup_replace_ip;
1846 backup_replace_port = rconn->backup_replace_port;
1850 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1851 /* Verify whether this connection is after all allowed to connect */
1852 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1853 &server->config->param,
1854 sconn ? sconn->param : NULL,
1856 silc_free(sock->user_data);
1857 server->stat.auth_failures++;
1862 if (sconn->param->keepalive_secs)
1863 hearbeat_timeout = sconn->param->keepalive_secs;
1866 backup_router = sconn->backup_router;
1870 /* If we are primary router and we have backup router configured
1871 but it has not connected to use yet, do not accept any other
1873 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1874 !server->backup_router && !backup_router) {
1875 SilcServerConfigRouter *router;
1876 router = silc_server_config_get_backup_router(server);
1877 if (router && strcmp(server->config->server_info->primary->server_ip,
1879 silc_server_find_socket_by_host(server,
1880 SILC_SOCKET_TYPE_SERVER,
1881 router->backup_replace_ip, 0)) {
1882 SILC_LOG_INFO(("Will not accept connections because we do "
1883 "not have backup router connection established"));
1884 silc_server_disconnect_remote(server, sock,
1885 SILC_STATUS_ERR_PERM_DENIED,
1886 "We do not have connection to backup "
1887 "router established, try later");
1888 silc_free(sock->user_data);
1889 server->stat.auth_failures++;
1891 /* From here on, wait 10 seconds for the backup router to appear. */
1892 silc_schedule_task_add(server->schedule, 0,
1893 silc_server_backup_router_wait,
1894 (void *)server, 10, 0,
1895 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1900 SILC_LOG_DEBUG(("Remote host is %s",
1901 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1902 "server" : (backup_router ?
1903 "backup router" : "router")));
1904 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1905 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1906 "server" : (backup_router ?
1907 "backup router" : "router")));
1909 /* Add the server into server cache. The server name and Server ID
1910 is updated after we have received NEW_SERVER packet from the
1911 server. We mark ourselves as router for this server if we really
1914 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1915 server->local_list : (backup_router ?
1916 server->local_list :
1917 server->global_list)),
1919 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1920 SILC_SERVER : SILC_ROUTER),
1922 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1923 server->id_entry : (backup_router ?
1924 server->id_entry : NULL)),
1927 SILC_LOG_ERROR(("Could not add new server to cache"));
1928 silc_free(sock->user_data);
1929 silc_server_disconnect_remote(server, sock,
1930 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1931 server->stat.auth_failures++;
1934 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1936 id_entry = (void *)new_server;
1938 /* If the incoming connection is router and marked as backup router
1939 then add it to be one of our backups */
1940 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1941 /* Change it back to SERVER type since that's what it really is. */
1943 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1944 new_server->server_type = SILC_BACKUP_ROUTER;
1946 /* Remove the backup waiting with timeout */
1947 silc_schedule_task_add(server->schedule, 0,
1948 silc_server_backup_router_wait,
1949 (void *)server, 5, 0,
1950 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1954 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1955 server->stat.my_servers++;
1957 server->stat.my_routers++;
1958 server->stat.routers++;
1960 server->stat.servers++;
1962 /* Check whether this connection is to be our primary router connection
1963 if we do not already have the primary route. */
1964 if (!backup_router &&
1965 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1966 if (silc_server_config_is_primary_route(server) && !initiator)
1969 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1970 server->standalone = FALSE;
1971 if (!server->id_entry->router) {
1972 server->id_entry->router = id_entry;
1973 server->router = id_entry;
1984 sock->type = ctx->conn_type;
1986 /* Add the common data structure to the ID entry. */
1987 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1989 /* Add to sockets internal pointer for fast referencing */
1990 silc_free(sock->user_data);
1991 sock->user_data = id_entry;
1993 /* Connection has been fully established now. Everything is ok. */
1994 SILC_LOG_DEBUG(("New connection authenticated"));
1996 /* Perform keepalive. The `hb_context' will be freed automatically
1997 when finally calling the silc_socket_free function. */
1998 hb_context = silc_calloc(1, sizeof(*hb_context));
1999 hb_context->server = server;
2000 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
2001 silc_server_perform_heartbeat,
2005 silc_schedule_task_del_by_callback(server->schedule,
2006 silc_server_failure_callback);
2007 silc_protocol_free(protocol);
2009 silc_packet_context_free(ctx->packet);
2011 silc_ske_free(ctx->ske);
2012 silc_free(ctx->dest_id);
2013 silc_server_config_unref(&ctx->cconfig);
2014 silc_server_config_unref(&ctx->sconfig);
2015 silc_server_config_unref(&ctx->rconfig);
2017 sock->protocol = NULL;
2020 /* This function is used to read packets from network and send packets to
2021 network. This is usually a generic task. */
2023 SILC_TASK_CALLBACK(silc_server_packet_process)
2025 SilcServer server = (SilcServer)context;
2026 SilcSocketConnection sock = server->sockets[fd];
2027 SilcIDListData idata;
2028 SilcCipher cipher = NULL;
2029 SilcHmac hmac = NULL;
2030 SilcUInt32 sequence = 0;
2034 SILC_LOG_DEBUG(("Unknown socket connection"));
2038 /* Packet sending */
2040 if (type == SILC_TASK_WRITE) {
2041 /* Do not send data to disconnected connection */
2042 if (SILC_IS_DISCONNECTED(sock)) {
2043 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2047 server->stat.packets_sent++;
2049 /* Send the packet */
2050 ret = silc_packet_send(sock, TRUE);
2052 /* If returned -2 could not write to connection now, will do
2058 SILC_LOG_ERROR(("Error sending packet to connection "
2059 "%s:%d [%s]", sock->hostname, sock->port,
2060 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2061 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2062 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2067 /* The packet has been sent and now it is time to set the connection
2068 back to only for input. When there is again some outgoing data
2069 available for this connection it will be set for output as well.
2070 This call clears the output setting and sets it only for input. */
2071 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2072 SILC_UNSET_OUTBUF_PENDING(sock);
2074 silc_buffer_clear(sock->outbuf);
2078 /* Packet receiving */
2080 /* Read some data from connection */
2081 ret = silc_packet_receive(sock);
2085 SILC_LOG_ERROR(("Error receiving packet from connection "
2086 "%s:%d [%s] %s", sock->hostname, sock->port,
2087 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2088 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2089 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2090 "Router"), strerror(errno)));
2096 SILC_LOG_DEBUG(("Read EOF"));
2098 /* If connection is disconnecting already we will finally
2099 close the connection */
2100 if (SILC_IS_DISCONNECTING(sock)) {
2101 if (sock->user_data)
2102 silc_server_free_sock_user_data(server, sock, NULL);
2103 silc_server_close_connection(server, sock);
2107 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2108 SILC_SET_DISCONNECTING(sock);
2110 if (sock->user_data) {
2112 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2113 silc_server_free_sock_user_data(server, sock, tmp);
2115 silc_server_free_sock_user_data(server, sock, NULL);
2116 } else if (server->router_conn && server->router_conn->sock == sock &&
2117 !server->router && server->standalone)
2118 silc_schedule_task_add(server->schedule, 0,
2119 silc_server_connect_to_router,
2122 SILC_TASK_PRI_NORMAL);
2124 silc_server_close_connection(server, sock);
2128 /* If connection is disconnecting or disconnected we will ignore
2130 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2131 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2135 /* Get keys and stuff from ID entry */
2136 idata = (SilcIDListData)sock->user_data;
2138 cipher = idata->receive_key;
2139 hmac = idata->hmac_receive;
2140 sequence = idata->psn_receive;
2143 /* Process the packet. This will call the parser that will then
2144 decrypt and parse the packet. */
2145 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2146 TRUE : FALSE, cipher, hmac, sequence,
2147 silc_server_packet_parse, server);
2149 /* If this socket connection is not authenticated yet and the packet
2150 processing failed we will drop the connection since it can be
2151 a malicious flooder. */
2152 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
2153 (!sock->protocol || sock->protocol->protocol->type ==
2154 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
2155 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
2156 SILC_SET_DISCONNECTING(sock);
2158 if (sock->user_data)
2159 silc_server_free_sock_user_data(server, sock, NULL);
2160 silc_server_close_connection(server, sock);
2164 /* Parses whole packet, received earlier. */
2166 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2168 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2169 SilcServer server = (SilcServer)parse_ctx->context;
2170 SilcSocketConnection sock = parse_ctx->sock;
2171 SilcPacketContext *packet = parse_ctx->packet;
2172 SilcIDListData idata = (SilcIDListData)sock->user_data;
2175 server->stat.packets_received++;
2177 /* Parse the packet */
2178 if (parse_ctx->normal)
2179 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2181 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2183 /* If entry is disabled ignore what we got. */
2184 if (ret != SILC_PACKET_RESUME_ROUTER &&
2185 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2186 SILC_LOG_DEBUG(("Connection is disabled"));
2189 if (ret != SILC_PACKET_HEARTBEAT &&
2190 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2191 SILC_LOG_DEBUG(("Connection is disabled"));
2195 if (ret == SILC_PACKET_NONE) {
2196 SILC_LOG_DEBUG(("Error parsing packet"));
2200 /* Check that the the current client ID is same as in the client's packet. */
2201 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2202 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2203 if (client && client->id && packet->src_id) {
2204 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2205 packet->src_id_type);
2206 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2208 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2215 if (server->server_type == SILC_ROUTER) {
2216 /* Route the packet if it is not destined to us. Other ID types but
2217 server are handled separately after processing them. */
2218 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2219 packet->dst_id_type == SILC_ID_SERVER &&
2220 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2221 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2223 /* Route the packet to fastest route for the destination ID */
2224 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2225 packet->dst_id_type);
2228 silc_server_packet_route(server,
2229 silc_server_route_get(server, id,
2230 packet->dst_id_type),
2237 /* Parse the incoming packet type */
2238 silc_server_packet_parse_type(server, sock, packet);
2240 /* Broadcast packet if it is marked as broadcast packet and it is
2241 originated from router and we are router. */
2242 if (server->server_type == SILC_ROUTER &&
2243 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2244 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2245 /* Broadcast to our primary route */
2246 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2248 /* If we have backup routers then we need to feed all broadcast
2249 data to those servers. */
2250 silc_server_backup_broadcast(server, sock, packet);
2254 silc_packet_context_free(packet);
2255 silc_free(parse_ctx);
2258 /* Parser callback called by silc_packet_receive_process. This merely
2259 registers timeout that will handle the actual parsing when appropriate. */
2261 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2264 SilcServer server = (SilcServer)context;
2265 SilcSocketConnection sock = parser_context->sock;
2266 SilcIDListData idata = (SilcIDListData)sock->user_data;
2269 idata->psn_receive = parser_context->packet->sequence + 1;
2271 /* If protocol for this connection is key exchange or rekey then we'll
2272 process all packets synchronously, since there might be packets in
2273 queue that we are not able to decrypt without first processing the
2274 packets before them. */
2275 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2276 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2277 (sock->protocol && sock->protocol->protocol &&
2278 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2279 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2280 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2283 /* Reprocess data since we'll return FALSE here. This is because
2284 the idata->receive_key might have become valid in the last packet
2285 and we want to call this processor with valid cipher. */
2287 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2288 TRUE : FALSE, idata->receive_key,
2289 idata->hmac_receive, idata->psn_receive,
2290 silc_server_packet_parse, server);
2292 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2293 TRUE : FALSE, NULL, NULL, 0,
2294 silc_server_packet_parse, server);
2298 switch (sock->type) {
2299 case SILC_SOCKET_TYPE_UNKNOWN:
2300 case SILC_SOCKET_TYPE_CLIENT:
2301 /* Parse the packet with timeout */
2302 silc_schedule_task_add(server->schedule, sock->sock,
2303 silc_server_packet_parse_real,
2304 (void *)parser_context, 0, 100000,
2306 SILC_TASK_PRI_NORMAL);
2308 case SILC_SOCKET_TYPE_SERVER:
2309 case SILC_SOCKET_TYPE_ROUTER:
2310 /* Packets from servers are parsed immediately */
2311 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2321 /* Parses the packet type and calls what ever routines the packet type
2322 requires. This is done for all incoming packets. */
2324 void silc_server_packet_parse_type(SilcServer server,
2325 SilcSocketConnection sock,
2326 SilcPacketContext *packet)
2328 SilcPacketType type = packet->type;
2329 SilcIDListData idata = (SilcIDListData)sock->user_data;
2331 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2332 silc_get_packet_name(type), packet->flags));
2334 /* Parse the packet type */
2336 case SILC_PACKET_DISCONNECT:
2339 char *message = NULL;
2341 if (packet->flags & SILC_PACKET_FLAG_LIST)
2343 if (packet->buffer->len < 1)
2346 status = (SilcStatus)packet->buffer->data[0];
2347 if (packet->buffer->len > 1 &&
2348 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2349 message = silc_memdup(packet->buffer->data + 1,
2350 packet->buffer->len - 1);
2352 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2353 sock->ip, sock->hostname,
2354 silc_get_status_message(status), status,
2355 message ? message : ""));
2358 /* Handle the disconnection from our end too */
2359 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2360 silc_server_free_sock_user_data(server, sock, NULL);
2361 silc_server_close_connection(server, sock);
2365 case SILC_PACKET_SUCCESS:
2367 * Success received for something. For now we can have only
2368 * one protocol for connection executing at once hence this
2369 * success message is for whatever protocol is executing currently.
2371 if (packet->flags & SILC_PACKET_FLAG_LIST)
2374 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2377 case SILC_PACKET_FAILURE:
2379 * Failure received for something. For now we can have only
2380 * one protocol for connection executing at once hence this
2381 * failure message is for whatever protocol is executing currently.
2383 if (packet->flags & SILC_PACKET_FLAG_LIST)
2385 if (sock->protocol) {
2386 SilcServerFailureContext f;
2387 f = silc_calloc(1, sizeof(*f));
2391 /* We will wait 5 seconds to process this failure packet */
2392 silc_schedule_task_add(server->schedule, sock->sock,
2393 silc_server_failure_callback, (void *)f, 5, 0,
2394 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2398 case SILC_PACKET_REJECT:
2399 if (packet->flags & SILC_PACKET_FLAG_LIST)
2404 case SILC_PACKET_NOTIFY:
2406 * Received notify packet. Server can receive notify packets from
2407 * router. Server then relays the notify messages to clients if needed.
2409 if (packet->flags & SILC_PACKET_FLAG_LIST)
2410 silc_server_notify_list(server, sock, packet);
2412 silc_server_notify(server, sock, packet);
2418 case SILC_PACKET_CHANNEL_MESSAGE:
2420 * Received channel message. Channel messages are special packets
2421 * (although probably most common ones) thus they are handled
2424 if (packet->flags & SILC_PACKET_FLAG_LIST)
2426 idata->last_receive = time(NULL);
2427 silc_server_channel_message(server, sock, packet);
2430 case SILC_PACKET_CHANNEL_KEY:
2432 * Received key for channel. As channels are created by the router
2433 * the keys are as well. We will distribute the key to all of our
2434 * locally connected clients on the particular channel. Router
2435 * never receives this channel and thus is ignored.
2437 if (packet->flags & SILC_PACKET_FLAG_LIST)
2439 silc_server_channel_key(server, sock, packet);
2445 case SILC_PACKET_COMMAND:
2447 * Recived command. Processes the command request and allocates the
2448 * command context and calls the command.
2450 if (packet->flags & SILC_PACKET_FLAG_LIST)
2452 silc_server_command_process(server, sock, packet);
2455 case SILC_PACKET_COMMAND_REPLY:
2457 * Received command reply packet. Received command reply to command. It
2458 * may be reply to command sent by us or reply to command sent by client
2459 * that we've routed further.
2461 if (packet->flags & SILC_PACKET_FLAG_LIST)
2463 silc_server_command_reply(server, sock, packet);
2467 * Private Message packets
2469 case SILC_PACKET_PRIVATE_MESSAGE:
2471 * Received private message packet. The packet is coming from either
2474 if (packet->flags & SILC_PACKET_FLAG_LIST)
2476 idata->last_receive = time(NULL);
2477 silc_server_private_message(server, sock, packet);
2480 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2482 * Private message key packet.
2484 if (packet->flags & SILC_PACKET_FLAG_LIST)
2486 silc_server_private_message_key(server, sock, packet);
2490 * Key Exchange protocol packets
2492 case SILC_PACKET_KEY_EXCHANGE:
2493 if (packet->flags & SILC_PACKET_FLAG_LIST)
2496 if (sock->protocol && sock->protocol->protocol &&
2497 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2498 SilcServerKEInternalContext *proto_ctx =
2499 (SilcServerKEInternalContext *)sock->protocol->context;
2501 proto_ctx->packet = silc_packet_context_dup(packet);
2503 /* Let the protocol handle the packet */
2504 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2506 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2507 "protocol active, packet dropped."));
2511 case SILC_PACKET_KEY_EXCHANGE_1:
2512 if (packet->flags & SILC_PACKET_FLAG_LIST)
2515 if (sock->protocol && sock->protocol->protocol &&
2516 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2517 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2519 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2520 SilcServerRekeyInternalContext *proto_ctx =
2521 (SilcServerRekeyInternalContext *)sock->protocol->context;
2523 if (proto_ctx->packet)
2524 silc_packet_context_free(proto_ctx->packet);
2526 proto_ctx->packet = silc_packet_context_dup(packet);
2528 /* Let the protocol handle the packet */
2529 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2531 SilcServerKEInternalContext *proto_ctx =
2532 (SilcServerKEInternalContext *)sock->protocol->context;
2534 if (proto_ctx->packet)
2535 silc_packet_context_free(proto_ctx->packet);
2537 proto_ctx->packet = silc_packet_context_dup(packet);
2538 proto_ctx->dest_id_type = packet->src_id_type;
2539 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2540 packet->src_id_type);
2541 if (!proto_ctx->dest_id)
2544 /* Let the protocol handle the packet */
2545 silc_protocol_execute(sock->protocol, server->schedule,
2549 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2550 "protocol active, packet dropped."));
2554 case SILC_PACKET_KEY_EXCHANGE_2:
2555 if (packet->flags & SILC_PACKET_FLAG_LIST)
2558 if (sock->protocol && sock->protocol->protocol &&
2559 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2560 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2562 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2563 SilcServerRekeyInternalContext *proto_ctx =
2564 (SilcServerRekeyInternalContext *)sock->protocol->context;
2566 if (proto_ctx->packet)
2567 silc_packet_context_free(proto_ctx->packet);
2569 proto_ctx->packet = silc_packet_context_dup(packet);
2571 /* Let the protocol handle the packet */
2572 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2574 SilcServerKEInternalContext *proto_ctx =
2575 (SilcServerKEInternalContext *)sock->protocol->context;
2577 if (proto_ctx->packet)
2578 silc_packet_context_free(proto_ctx->packet);
2580 proto_ctx->packet = silc_packet_context_dup(packet);
2581 proto_ctx->dest_id_type = packet->src_id_type;
2582 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2583 packet->src_id_type);
2584 if (!proto_ctx->dest_id)
2587 /* Let the protocol handle the packet */
2588 silc_protocol_execute(sock->protocol, server->schedule,
2592 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2593 "protocol active, packet dropped."));
2597 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2599 * Connection authentication request packet. When we receive this packet
2600 * we will send to the other end information about our mandatory
2601 * authentication method for the connection. This packet maybe received
2604 if (packet->flags & SILC_PACKET_FLAG_LIST)
2606 silc_server_connection_auth_request(server, sock, packet);
2610 * Connection Authentication protocol packets
2612 case SILC_PACKET_CONNECTION_AUTH:
2613 /* Start of the authentication protocol. We receive here the
2614 authentication data and will verify it. */
2615 if (packet->flags & SILC_PACKET_FLAG_LIST)
2618 if (sock->protocol && sock->protocol->protocol->type
2619 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2621 SilcServerConnAuthInternalContext *proto_ctx =
2622 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2624 proto_ctx->packet = silc_packet_context_dup(packet);
2626 /* Let the protocol handle the packet */
2627 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2629 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2630 "protocol active, packet dropped."));
2634 case SILC_PACKET_NEW_ID:
2636 * Received New ID packet. This includes some new ID that has been
2637 * created. It may be for client, server or channel. This is the way
2638 * to distribute information about new registered entities in the
2641 if (packet->flags & SILC_PACKET_FLAG_LIST)
2642 silc_server_new_id_list(server, sock, packet);
2644 silc_server_new_id(server, sock, packet);
2647 case SILC_PACKET_NEW_CLIENT:
2649 * Received new client packet. This includes client information that
2650 * we will use to create initial client ID. After creating new
2651 * ID we will send it to the client.
2653 if (packet->flags & SILC_PACKET_FLAG_LIST)
2655 silc_server_new_client(server, sock, packet);
2658 case SILC_PACKET_NEW_SERVER:
2660 * Received new server packet. This includes Server ID and some other
2661 * information that we may save. This is received after server has
2664 if (packet->flags & SILC_PACKET_FLAG_LIST)
2666 silc_server_new_server(server, sock, packet);
2669 case SILC_PACKET_NEW_CHANNEL:
2671 * Received new channel packet. Information about new channel in the
2672 * network are distributed using this packet.
2674 if (packet->flags & SILC_PACKET_FLAG_LIST)
2675 silc_server_new_channel_list(server, sock, packet);
2677 silc_server_new_channel(server, sock, packet);
2680 case SILC_PACKET_HEARTBEAT:
2682 * Received heartbeat.
2684 if (packet->flags & SILC_PACKET_FLAG_LIST)
2688 case SILC_PACKET_KEY_AGREEMENT:
2690 * Received heartbeat.
2692 if (packet->flags & SILC_PACKET_FLAG_LIST)
2694 silc_server_key_agreement(server, sock, packet);
2697 case SILC_PACKET_REKEY:
2699 * Received re-key packet. The sender wants to regenerate the session
2702 if (packet->flags & SILC_PACKET_FLAG_LIST)
2704 silc_server_rekey(server, sock, packet);
2707 case SILC_PACKET_REKEY_DONE:
2709 * The re-key is done.
2711 if (packet->flags & SILC_PACKET_FLAG_LIST)
2714 if (sock->protocol && sock->protocol->protocol &&
2715 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2717 SilcServerRekeyInternalContext *proto_ctx =
2718 (SilcServerRekeyInternalContext *)sock->protocol->context;
2720 if (proto_ctx->packet)
2721 silc_packet_context_free(proto_ctx->packet);
2723 proto_ctx->packet = silc_packet_context_dup(packet);
2725 /* Let the protocol handle the packet */
2726 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2728 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2729 "protocol active, packet dropped."));
2733 case SILC_PACKET_FTP:
2735 if (packet->flags & SILC_PACKET_FLAG_LIST)
2737 silc_server_ftp(server, sock, packet);
2740 case SILC_PACKET_RESUME_CLIENT:
2742 if (packet->flags & SILC_PACKET_FLAG_LIST)
2744 silc_server_resume_client(server, sock, packet);
2747 case SILC_PACKET_RESUME_ROUTER:
2748 /* Resume router packet received. This packet is received for backup
2749 router resuming protocol. */
2750 if (packet->flags & SILC_PACKET_FLAG_LIST)
2752 silc_server_backup_resume_router(server, sock, packet);
2756 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2761 /* Creates connection to a remote router. */
2763 void silc_server_create_connection(SilcServer server,
2764 const char *remote_host, SilcUInt32 port)
2766 SilcServerConnection sconn;
2768 /* Allocate connection object for hold connection specific stuff. */
2769 sconn = silc_calloc(1, sizeof(*sconn));
2770 sconn->server = server;
2771 sconn->remote_host = strdup(remote_host);
2772 sconn->remote_port = port;
2773 sconn->no_reconnect = TRUE;
2775 silc_schedule_task_add(server->schedule, 0,
2776 silc_server_connect_router,
2777 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2778 SILC_TASK_PRI_NORMAL);
2781 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2783 silc_socket_free(context);
2786 /* Closes connection to socket connection */
2788 void silc_server_close_connection(SilcServer server,
2789 SilcSocketConnection sock)
2793 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2794 silc_schedule_task_add(server->schedule, 0,
2795 silc_server_close_connection_final,
2796 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2797 SILC_TASK_PRI_NORMAL);
2801 memset(tmp, 0, sizeof(tmp));
2802 silc_socket_get_error(sock, tmp, sizeof(tmp));
2803 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", sock->hostname,
2805 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2806 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2807 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2808 "Router"), tmp[0] ? tmp : ""));
2810 /* We won't listen for this connection anymore */
2811 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2813 /* Unregister all tasks */
2814 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2816 /* Close the actual connection */
2817 silc_net_close_connection(sock->sock);
2818 server->sockets[sock->sock] = NULL;
2820 /* If sock->user_data is NULL then we'll check for active protocols
2821 here since the silc_server_free_sock_user_data has not been called
2822 for this connection. */
2823 if (!sock->user_data) {
2824 /* If any protocol is active cancel its execution. It will call
2825 the final callback which will finalize the disconnection. */
2826 if (sock->protocol) {
2827 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2828 silc_protocol_cancel(sock->protocol, server->schedule);
2829 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2830 silc_protocol_execute_final(sock->protocol, server->schedule);
2831 sock->protocol = NULL;
2836 silc_schedule_task_add(server->schedule, 0,
2837 silc_server_close_connection_final,
2838 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2839 SILC_TASK_PRI_NORMAL);
2842 /* Sends disconnect message to remote connection and disconnects the
2845 void silc_server_disconnect_remote(SilcServer server,
2846 SilcSocketConnection sock,
2847 SilcStatus status, ...)
2850 unsigned char buf[512];
2858 memset(buf, 0, sizeof(buf));
2859 va_start(ap, status);
2860 cp = va_arg(ap, char *);
2862 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2867 SILC_LOG_DEBUG(("Disconnecting remote host"));
2869 /* Notify remote end that the conversation is over. The notify message
2870 is tried to be sent immediately. */
2874 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2876 buffer = silc_buffer_alloc_size(len);
2880 buffer->data[0] = status;
2882 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2884 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2885 buffer->data, buffer->len, TRUE);
2886 silc_buffer_free(buffer);
2889 silc_server_packet_queue_purge(server, sock);
2891 /* Mark the connection to be disconnected */
2892 SILC_SET_DISCONNECTED(sock);
2893 silc_server_close_connection(server, sock);
2898 SilcClientEntry client;
2899 } *FreeClientInternal;
2901 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2903 FreeClientInternal i = (FreeClientInternal)context;
2905 assert(!silc_hash_table_count(i->client->channels));
2907 silc_idlist_del_data(i->client);
2908 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2912 /* Frees client data and notifies about client's signoff. */
2914 void silc_server_free_client_data(SilcServer server,
2915 SilcSocketConnection sock,
2916 SilcClientEntry client,
2918 const char *signoff)
2920 SILC_LOG_DEBUG(("Freeing client data"));
2923 if (!client->router && !client->connection &&
2924 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2925 SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2926 SILC_LOG_ERROR(("****** Contact Pekka"));
2927 SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2932 /* If there is pending outgoing data for the client then purge it
2933 to the network before removing the client entry. */
2934 silc_server_packet_queue_purge(server, sock);
2937 /* Check if anyone is watching this nickname */
2938 if (server->server_type == SILC_ROUTER)
2939 silc_server_check_watcher_list(server, client, NULL,
2940 SILC_NOTIFY_TYPE_SIGNOFF);
2942 /* Send SIGNOFF notify to routers. */
2944 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2945 SILC_BROADCAST(server), client->id,
2949 /* Remove client from all channels */
2951 silc_server_remove_from_channels(server, NULL, client,
2952 TRUE, (char *)signoff, TRUE);
2954 silc_server_remove_from_channels(server, NULL, client,
2955 FALSE, NULL, FALSE);
2957 /* Remove this client from watcher list if it is */
2958 silc_server_del_from_watcher_list(server, client);
2960 /* Update statistics */
2961 server->stat.my_clients--;
2962 server->stat.clients--;
2963 if (server->stat.cell_clients)
2964 server->stat.cell_clients--;
2965 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2966 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2967 silc_schedule_task_del_by_context(server->schedule, client);
2969 /* We will not delete the client entry right away. We will take it
2970 into history (for WHOWAS command) for 5 minutes, unless we're
2971 shutting down server. */
2972 if (!server->server_shutdown) {
2973 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2976 silc_schedule_task_add(server->schedule, 0,
2977 silc_server_free_client_data_timeout,
2979 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2980 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2981 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
2983 client->router = NULL;
2984 client->connection = NULL;
2986 /* Delete directly since we're shutting down server */
2987 silc_idlist_del_data(client);
2988 silc_idlist_del_client(server->local_list, client);
2992 /* Frees user_data pointer from socket connection object. This also sends
2993 appropriate notify packets to the network to inform about leaving
2996 void silc_server_free_sock_user_data(SilcServer server,
2997 SilcSocketConnection sock,
2998 const char *signoff_message)
3000 switch (sock->type) {
3001 case SILC_SOCKET_TYPE_CLIENT:
3003 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
3004 silc_server_free_client_data(server, sock, user_data, TRUE,
3008 case SILC_SOCKET_TYPE_SERVER:
3009 case SILC_SOCKET_TYPE_ROUTER:
3011 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
3012 SilcServerEntry backup_router = NULL;
3014 SILC_LOG_DEBUG(("Freeing server data"));
3017 backup_router = silc_server_backup_get(server, user_data->id);
3019 if (!server->backup_router && server->server_type == SILC_ROUTER &&
3020 backup_router == server->id_entry &&
3021 sock->type != SILC_SOCKET_TYPE_ROUTER)
3022 backup_router = NULL;
3024 /* If this was our primary router connection then we're lost to
3025 the outside world. */
3026 if (server->router == user_data) {
3027 /* Check whether we have a backup router connection */
3028 if (!backup_router || backup_router == user_data) {
3029 silc_schedule_task_add(server->schedule, 0,
3030 silc_server_connect_to_router,
3033 SILC_TASK_PRI_NORMAL);
3035 server->id_entry->router = NULL;
3036 server->router = NULL;
3037 server->standalone = TRUE;
3038 backup_router = NULL;
3040 if (server->id_entry != backup_router) {
3041 SILC_LOG_INFO(("New primary router is backup router %s",
3042 backup_router->server_name));
3043 server->id_entry->router = backup_router;
3044 server->router = backup_router;
3045 server->router_connect = time(0);
3046 server->backup_primary = TRUE;
3048 SILC_LOG_INFO(("We are now new primary router in this cell"));
3049 server->id_entry->router = NULL;
3050 server->router = NULL;
3051 server->standalone = TRUE;
3053 /* We stop here to take a breath */
3057 if (server->server_type == SILC_BACKUP_ROUTER) {
3058 server->server_type = SILC_ROUTER;
3060 /* We'll need to constantly try to reconnect to the primary
3061 router so that we'll see when it comes back online. */
3062 silc_server_backup_reconnect(server, sock->ip, sock->port,
3063 silc_server_backup_connected,
3067 /* Mark this connection as replaced */
3068 silc_server_backup_replaced_add(server, user_data->id,
3071 } else if (backup_router) {
3072 SILC_LOG_INFO(("Enabling the use of backup router %s",
3073 backup_router->server_name));
3074 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3075 backup_router->server_name));
3077 /* Mark this connection as replaced */
3078 silc_server_backup_replaced_add(server, user_data->id,
3082 if (!backup_router) {
3083 /* Remove all servers that are originated from this server, and
3084 remove the clients of those servers too. */
3085 silc_server_remove_servers_by_server(server, user_data, TRUE);
3087 /* Remove the clients that this server owns as they will become
3089 silc_server_remove_clients_by_server(server, user_data,
3092 /* Remove channels owned by this server */
3093 if (server->server_type == SILC_SERVER)
3094 silc_server_remove_channels_by_server(server, user_data);
3096 /* Enable local server connections that may be disabled */
3097 silc_server_local_servers_toggle_enabled(server, TRUE);
3099 /* Update the client entries of this server to the new backup
3100 router. If we are the backup router we also resolve the real
3101 servers for the clients. After updating is over this also
3102 removes the clients that this server explicitly owns. */
3103 silc_server_update_clients_by_server(server, user_data,
3104 backup_router, TRUE);
3106 /* If we are router and just lost our primary router (now standlaone)
3107 we remove everything that was behind it, since we don't know
3109 if (server->server_type == SILC_ROUTER && server->standalone)
3110 /* Remove all servers that are originated from this server, and
3111 remove the clients of those servers too. */
3112 silc_server_remove_servers_by_server(server, user_data, TRUE);
3114 /* Finally remove the clients that are explicitly owned by this
3115 server. They go down with the server. */
3116 silc_server_remove_clients_by_server(server, user_data,
3119 /* Update our server cache to use the new backup router too. */
3120 silc_server_update_servers_by_server(server, user_data, backup_router);
3121 if (server->server_type == SILC_SERVER)
3122 silc_server_update_channels_by_server(server, user_data,
3125 /* Send notify about primary router going down to local operators */
3126 if (server->backup_router)
3127 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3128 SILC_NOTIFY_TYPE_NONE,
3129 ("%s switched to backup router %s "
3130 "(we are primary router now)",
3131 server->server_name, server->server_name));
3132 else if (server->router)
3133 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3134 SILC_NOTIFY_TYPE_NONE,
3135 ("%s switched to backup router %s",
3136 server->server_name,
3137 server->router->server_name));
3140 /* Free the server entry */
3141 silc_server_backup_del(server, user_data);
3142 silc_server_backup_replaced_del(server, user_data);
3143 silc_idlist_del_data(user_data);
3144 if (!silc_idlist_del_server(server->local_list, user_data))
3145 silc_idlist_del_server(server->global_list, user_data);
3146 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3147 server->stat.my_servers--;
3149 server->stat.my_routers--;
3150 server->stat.routers--;
3152 server->stat.servers--;
3153 if (server->server_type == SILC_ROUTER)
3154 server->stat.cell_servers--;
3156 if (backup_router && backup_router != server->id_entry) {
3157 /* Announce all of our stuff that was created about 5 minutes ago.
3158 The backup router knows all the other stuff already. */
3159 if (server->server_type == SILC_ROUTER)
3160 silc_server_announce_servers(server, FALSE, time(0) - 300,
3161 backup_router->connection);
3163 /* Announce our clients and channels to the router */
3164 silc_server_announce_clients(server, time(0) - 300,
3165 backup_router->connection);
3166 silc_server_announce_channels(server, time(0) - 300,
3167 backup_router->connection);
3173 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3175 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3177 silc_idlist_del_data(user_data);
3178 silc_free(user_data);
3183 /* If any protocol is active cancel its execution */
3184 if (sock->protocol) {
3185 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3186 silc_protocol_cancel(sock->protocol, server->schedule);
3187 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3188 silc_protocol_execute_final(sock->protocol, server->schedule);
3189 sock->protocol = NULL;
3192 sock->user_data = NULL;
3195 /* Removes client from all channels it has joined. This is used when client
3196 connection is disconnected. If the client on a channel is last, the
3197 channel is removed as well. This sends the SIGNOFF notify types. */
3199 void silc_server_remove_from_channels(SilcServer server,
3200 SilcSocketConnection sock,
3201 SilcClientEntry client,
3203 const char *signoff_message,
3206 SilcChannelEntry channel;
3207 SilcChannelClientEntry chl;
3208 SilcHashTableList htl;
3209 SilcBuffer clidp = NULL;
3214 SILC_LOG_DEBUG(("Removing client from joined channels"));
3216 if (notify && !client->id)
3220 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3225 /* Remove the client from all channels. The client is removed from
3226 the channels' user list. */
3227 silc_hash_table_list(client->channels, &htl);
3228 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3229 channel = chl->channel;
3231 /* Remove channel if this is last client leaving the channel, unless
3232 the channel is permanent. */
3233 if (server->server_type != SILC_SERVER &&
3234 silc_hash_table_count(channel->user_list) < 2) {
3235 silc_server_channel_delete(server, channel);
3239 silc_hash_table_del(client->channels, channel);
3240 silc_hash_table_del(channel->user_list, chl->client);
3241 channel->user_count--;
3243 /* If there is no global users on the channel anymore mark the channel
3244 as local channel. Do not check if the removed client is local client. */
3245 if (server->server_type == SILC_SERVER && channel->global_users &&
3246 chl->client->router && !silc_server_channel_has_global(channel))
3247 channel->global_users = FALSE;
3251 /* Update statistics */
3252 if (SILC_IS_LOCAL(client))
3253 server->stat.my_chanclients--;
3254 if (server->server_type == SILC_ROUTER) {
3255 server->stat.cell_chanclients--;
3256 server->stat.chanclients--;
3259 /* If there is not at least one local user on the channel then we don't
3260 need the channel entry anymore, we can remove it safely, unless the
3261 channel is permanent channel */
3262 if (server->server_type == SILC_SERVER &&
3263 !silc_server_channel_has_local(channel)) {
3264 /* Notify about leaving client if this channel has global users. */
3265 if (notify && channel->global_users)
3266 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3267 SILC_NOTIFY_TYPE_SIGNOFF,
3268 signoff_message ? 2 : 1,
3269 clidp->data, clidp->len,
3270 signoff_message, signoff_message ?
3271 strlen(signoff_message) : 0);
3273 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3274 silc_server_channel_delete(server, channel);
3278 /* Send notify to channel about client leaving SILC and channel too */
3280 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3281 SILC_NOTIFY_TYPE_SIGNOFF,
3282 signoff_message ? 2 : 1,
3283 clidp->data, clidp->len,
3284 signoff_message, signoff_message ?
3285 strlen(signoff_message) : 0);
3287 /* Don't create keys if we are shutting down */
3288 if (server->server_shutdown)
3291 /* Re-generate channel key if needed */
3292 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3293 if (!silc_server_create_channel_key(server, channel, 0))
3296 /* Send the channel key to the channel. The key of course is not sent
3297 to the client who was removed from the channel. */
3298 silc_server_send_channel_key(server, client->connection, channel,
3299 server->server_type == SILC_ROUTER ?
3300 FALSE : !server->standalone);
3304 silc_hash_table_list_reset(&htl);
3306 silc_buffer_free(clidp);
3309 /* Removes client from one channel. This is used for example when client
3310 calls LEAVE command to remove itself from the channel. Returns TRUE
3311 if channel still exists and FALSE if the channel is removed when
3312 last client leaves the channel. If `notify' is FALSE notify messages
3315 bool silc_server_remove_from_one_channel(SilcServer server,
3316 SilcSocketConnection sock,
3317 SilcChannelEntry channel,
3318 SilcClientEntry client,
3321 SilcChannelClientEntry chl;
3324 SILC_LOG_DEBUG(("Removing %s from channel %s",
3325 silc_id_render(client->id, SILC_ID_CLIENT),
3326 channel->channel_name));
3328 /* Get the entry to the channel, if this client is not on the channel
3330 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3333 /* Remove channel if this is last client leaving the channel, unless
3334 the channel is permanent. */
3335 if (server->server_type != SILC_SERVER &&
3336 silc_hash_table_count(channel->user_list) < 2) {
3337 silc_server_channel_delete(server, channel);
3341 silc_hash_table_del(client->channels, chl->channel);
3342 silc_hash_table_del(channel->user_list, chl->client);
3343 channel->user_count--;
3345 /* If there is no global users on the channel anymore mark the channel
3346 as local channel. Do not check if the client is local client. */
3347 if (server->server_type == SILC_SERVER && channel->global_users &&
3348 chl->client->router && !silc_server_channel_has_global(channel))
3349 channel->global_users = FALSE;
3353 /* Update statistics */
3354 if (SILC_IS_LOCAL(client))
3355 server->stat.my_chanclients--;
3356 if (server->server_type == SILC_ROUTER) {
3357 server->stat.cell_chanclients--;
3358 server->stat.chanclients--;
3361 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3365 /* If there is not at least one local user on the channel then we don't
3366 need the channel entry anymore, we can remove it safely, unless the
3367 channel is permanent channel */
3368 if (server->server_type == SILC_SERVER &&
3369 !silc_server_channel_has_local(channel)) {
3370 /* Notify about leaving client if this channel has global users. */
3371 if (notify && channel->global_users)
3372 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3373 SILC_NOTIFY_TYPE_LEAVE, 1,
3374 clidp->data, clidp->len);
3376 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3377 silc_server_channel_delete(server, channel);
3378 silc_buffer_free(clidp);
3382 /* Send notify to channel about client leaving the channel */
3384 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3385 SILC_NOTIFY_TYPE_LEAVE, 1,
3386 clidp->data, clidp->len);
3388 silc_buffer_free(clidp);
3392 /* Timeout callback. This is called if connection is idle or for some
3393 other reason is not responding within some period of time. This
3394 disconnects the remote end. */
3396 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3398 SilcServer server = (SilcServer)context;
3399 SilcSocketConnection sock = server->sockets[fd];
3400 SilcProtocolType protocol = 0;
3402 SILC_LOG_DEBUG(("Start"));
3407 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3408 sock->hostname, sock->ip));
3410 /* If we have protocol active we must assure that we call the protocol's
3411 final callback so that all the memory is freed. */
3412 if (sock->protocol) {
3413 protocol = sock->protocol->protocol->type;
3414 silc_protocol_cancel(sock->protocol, server->schedule);
3415 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3416 silc_protocol_execute_final(sock->protocol, server->schedule);
3417 sock->protocol = NULL;
3421 if (sock->user_data)
3422 silc_server_free_sock_user_data(server, sock, NULL);
3424 silc_server_disconnect_remote(server, sock,
3426 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3427 SILC_STATUS_ERR_AUTH_FAILED :
3428 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3429 "Connection timeout");
3432 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3433 function may be used only by router. In real SILC network all channels
3434 are created by routers thus this function is never used by normal
3437 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3438 SilcServerID *router_id,
3444 SilcChannelID *channel_id;
3445 SilcChannelEntry entry;
3449 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3452 cipher = SILC_DEFAULT_CIPHER;
3454 hmac = SILC_DEFAULT_HMAC;
3456 /* Allocate cipher */
3457 if (!silc_cipher_alloc(cipher, &key))
3461 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3462 silc_cipher_free(key);
3466 channel_name = strdup(channel_name);
3468 /* Create the channel ID */
3469 if (!silc_id_create_channel_id(server, router_id, server->rng,
3471 silc_free(channel_name);
3472 silc_cipher_free(key);
3473 silc_hmac_free(newhmac);
3477 /* Create the channel */
3478 entry = silc_idlist_add_channel(server->local_list, channel_name,
3479 SILC_CHANNEL_MODE_NONE, channel_id,
3480 NULL, key, newhmac, 0);
3482 silc_free(channel_name);
3483 silc_cipher_free(key);
3484 silc_hmac_free(newhmac);
3485 silc_free(channel_id);
3489 entry->cipher = strdup(cipher);
3490 entry->hmac_name = strdup(hmac);
3492 /* Now create the actual key material */
3493 if (!silc_server_create_channel_key(server, entry,
3494 silc_cipher_get_key_len(key) / 8)) {
3495 silc_idlist_del_channel(server->local_list, entry);
3499 /* Notify other routers about the new channel. We send the packet
3500 to our primary route. */
3502 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3503 channel_name, entry->id,
3504 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3507 /* Distribute to backup routers */
3508 if (broadcast && server->server_type == SILC_ROUTER) {
3511 SilcUInt32 name_len = strlen(channel_name);
3512 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3513 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3515 packet = silc_channel_payload_encode(channel_name, name_len,
3516 cid, channel_id_len, entry->mode);
3517 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3518 packet->data, packet->len, FALSE, TRUE);
3520 silc_buffer_free(packet);
3523 server->stat.my_channels++;
3524 if (server->server_type == SILC_ROUTER) {
3525 server->stat.channels++;
3526 server->stat.cell_channels++;
3527 entry->users_resolved = TRUE;
3533 /* Same as above but creates the channel with Channel ID `channel_id. */
3536 silc_server_create_new_channel_with_id(SilcServer server,
3540 SilcChannelID *channel_id,
3543 SilcChannelEntry entry;
3547 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3550 cipher = SILC_DEFAULT_CIPHER;
3552 hmac = SILC_DEFAULT_HMAC;
3554 /* Allocate cipher */
3555 if (!silc_cipher_alloc(cipher, &key))
3559 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3560 silc_cipher_free(key);
3564 channel_name = strdup(channel_name);
3566 /* Create the channel */
3567 entry = silc_idlist_add_channel(server->local_list, channel_name,
3568 SILC_CHANNEL_MODE_NONE, channel_id,
3569 NULL, key, newhmac, 0);
3571 silc_cipher_free(key);
3572 silc_hmac_free(newhmac);
3573 silc_free(channel_name);
3577 /* Now create the actual key material */
3578 if (!silc_server_create_channel_key(server, entry,
3579 silc_cipher_get_key_len(key) / 8)) {
3580 silc_idlist_del_channel(server->local_list, entry);
3584 /* Notify other routers about the new channel. We send the packet
3585 to our primary route. */
3587 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3588 channel_name, entry->id,
3589 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3592 /* Distribute to backup routers */
3593 if (broadcast && server->server_type == SILC_ROUTER) {
3596 SilcUInt32 name_len = strlen(channel_name);
3597 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3598 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3600 packet = silc_channel_payload_encode(channel_name, name_len,
3601 cid, channel_id_len, entry->mode);
3602 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3603 packet->data, packet->len, FALSE, TRUE);
3605 silc_buffer_free(packet);
3608 server->stat.my_channels++;
3609 if (server->server_type == SILC_ROUTER) {
3610 server->stat.channels++;
3611 server->stat.cell_channels++;
3612 entry->users_resolved = TRUE;
3618 /* Channel's key re-key timeout callback. */
3620 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3622 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3623 SilcServer server = (SilcServer)rekey->context;
3627 /* Return now if we are shutting down */
3628 if (server->server_shutdown)
3631 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3634 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3637 /* Generates new channel key. This is used to create the initial channel key
3638 but also to re-generate new key for channel. If `key_len' is provided
3639 it is the bytes of the key length. */
3641 bool silc_server_create_channel_key(SilcServer server,
3642 SilcChannelEntry channel,
3646 unsigned char channel_key[32], hash[32];
3649 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3650 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3654 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3656 if (!channel->channel_key)
3657 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3658 channel->channel_key = NULL;
3664 else if (channel->key_len)
3665 len = channel->key_len / 8;
3667 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3669 /* Create channel key */
3670 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3673 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3675 /* Remove old key if exists */
3677 memset(channel->key, 0, channel->key_len / 8);
3678 silc_free(channel->key);
3682 channel->key_len = len * 8;
3683 channel->key = silc_memdup(channel_key, len);
3684 memset(channel_key, 0, sizeof(channel_key));
3686 /* Generate HMAC key from the channel key data and set it */
3688 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3689 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3690 silc_hmac_set_key(channel->hmac, hash,
3691 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3692 memset(hash, 0, sizeof(hash));
3694 if (server->server_type == SILC_ROUTER) {
3695 if (!channel->rekey)
3696 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3697 channel->rekey->context = (void *)server;
3698 channel->rekey->channel = channel;
3699 channel->rekey->key_len = key_len;
3700 if (channel->rekey->task)
3701 silc_schedule_task_del(server->schedule, channel->rekey->task);
3703 channel->rekey->task =
3704 silc_schedule_task_add(server->schedule, 0,
3705 silc_server_channel_key_rekey,
3706 (void *)channel->rekey,
3707 server->config->channel_rekey_secs, 0,
3709 SILC_TASK_PRI_NORMAL);
3715 /* Saves the channel key found in the encoded `key_payload' buffer. This
3716 function is used when we receive Channel Key Payload and also when we're
3717 processing JOIN command reply. Returns entry to the channel. */
3719 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3720 SilcBuffer key_payload,
3721 SilcChannelEntry channel)
3723 SilcChannelKeyPayload payload = NULL;
3724 SilcChannelID *id = NULL;
3725 unsigned char *tmp, hash[32];
3729 /* Decode channel key payload */
3730 payload = silc_channel_key_payload_parse(key_payload->data,
3733 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3738 /* Get the channel entry */
3741 /* Get channel ID */
3742 tmp = silc_channel_key_get_id(payload, &tmp_len);
3743 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3749 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3751 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3753 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3754 silc_id_render(id, SILC_ID_CHANNEL)));
3760 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3762 tmp = silc_channel_key_get_key(payload, &tmp_len);
3768 cipher = silc_channel_key_get_cipher(payload, NULL);
3774 /* Remove old key if exists */
3776 memset(channel->key, 0, channel->key_len / 8);
3777 silc_free(channel->key);
3778 silc_cipher_free(channel->channel_key);
3781 /* Create new cipher */
3782 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3783 channel->channel_key = NULL;
3788 if (channel->cipher)
3789 silc_free(channel->cipher);
3790 channel->cipher = strdup(cipher);
3793 channel->key_len = tmp_len * 8;
3794 channel->key = silc_memdup(tmp, tmp_len);
3795 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3797 /* Generate HMAC key from the channel key data and set it */
3799 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3800 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3801 silc_hmac_set_key(channel->hmac, hash,
3802 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3804 memset(hash, 0, sizeof(hash));
3805 memset(tmp, 0, tmp_len);
3807 if (server->server_type == SILC_ROUTER) {
3808 if (!channel->rekey)
3809 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3810 channel->rekey->context = (void *)server;
3811 channel->rekey->channel = channel;
3812 if (channel->rekey->task)
3813 silc_schedule_task_del(server->schedule, channel->rekey->task);
3815 channel->rekey->task =
3816 silc_schedule_task_add(server->schedule, 0,
3817 silc_server_channel_key_rekey,
3818 (void *)channel->rekey,
3819 server->config->channel_rekey_secs, 0,
3821 SILC_TASK_PRI_NORMAL);
3827 silc_channel_key_payload_free(payload);
3832 /* Heartbeat callback. This function is set as argument for the
3833 silc_socket_set_heartbeat function. The library will call this function
3834 at the set time interval. */
3836 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3839 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3841 SILC_LOG_DEBUG(("Sending heartbeat to %s:%d (%s)", sock->hostname,
3842 sock->port, sock->ip));
3844 /* Send the heartbeat */
3845 silc_server_send_heartbeat(hb->server, sock);
3848 /* Returns assembled of all servers in the given ID list. The packet's
3849 form is dictated by the New ID payload. */
3851 static void silc_server_announce_get_servers(SilcServer server,
3852 SilcServerEntry remote,
3854 SilcBuffer *servers,
3855 unsigned long creation_time)
3857 SilcIDCacheList list;
3858 SilcIDCacheEntry id_cache;
3859 SilcServerEntry entry;
3862 /* Go through all clients in the list */
3863 if (silc_idcache_get_all(id_list->servers, &list)) {
3864 if (silc_idcache_list_first(list, &id_cache)) {
3866 entry = (SilcServerEntry)id_cache->context;
3868 /* Do not announce the one we've sending our announcements and
3869 do not announce ourself. Also check the creation time if it's
3871 if ((entry == remote) || (entry == server->id_entry) ||
3872 (creation_time && entry->data.created < creation_time)) {
3873 if (!silc_idcache_list_next(list, &id_cache))
3878 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3880 *servers = silc_buffer_realloc(*servers,
3882 (*servers)->truelen + idp->len :
3884 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3885 silc_buffer_put(*servers, idp->data, idp->len);
3886 silc_buffer_pull(*servers, idp->len);
3887 silc_buffer_free(idp);
3889 if (!silc_idcache_list_next(list, &id_cache))
3894 silc_idcache_list_free(list);
3899 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3905 p = silc_notify_payload_encode(notify, argc, ap);
3911 /* This function is used by router to announce existing servers to our
3912 primary router when we've connected to it. If `creation_time' is non-zero
3913 then only the servers that has been created after the `creation_time'
3914 will be announced. */
3916 void silc_server_announce_servers(SilcServer server, bool global,
3917 unsigned long creation_time,
3918 SilcSocketConnection remote)
3920 SilcBuffer servers = NULL;
3922 SILC_LOG_DEBUG(("Announcing servers"));
3924 /* Get servers in local list */
3925 silc_server_announce_get_servers(server, remote->user_data,
3926 server->local_list, &servers,
3930 /* Get servers in global list */
3931 silc_server_announce_get_servers(server, remote->user_data,
3932 server->global_list, &servers,
3936 silc_buffer_push(servers, servers->data - servers->head);
3937 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3939 /* Send the packet */
3940 silc_server_packet_send(server, remote,
3941 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3942 servers->data, servers->len, TRUE);
3944 silc_buffer_free(servers);
3948 /* Returns assembled packet of all clients in the given ID list. The
3949 packet's form is dictated by the New ID Payload. */
3951 static void silc_server_announce_get_clients(SilcServer server,
3953 SilcBuffer *clients,
3955 unsigned long creation_time)
3957 SilcIDCacheList list;
3958 SilcIDCacheEntry id_cache;
3959 SilcClientEntry client;
3962 unsigned char mode[4];
3964 /* Go through all clients in the list */
3965 if (silc_idcache_get_all(id_list->clients, &list)) {
3966 if (silc_idcache_list_first(list, &id_cache)) {
3968 client = (SilcClientEntry)id_cache->context;
3970 if (creation_time && client->data.created < creation_time) {
3971 if (!silc_idcache_list_next(list, &id_cache))
3975 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED) &&
3976 !client->connection && !client->router && !SILC_IS_LOCAL(client)) {
3977 if (!silc_idcache_list_next(list, &id_cache))
3982 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3984 *clients = silc_buffer_realloc(*clients,
3986 (*clients)->truelen + idp->len :
3988 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3989 silc_buffer_put(*clients, idp->data, idp->len);
3990 silc_buffer_pull(*clients, idp->len);
3992 SILC_PUT32_MSB(client->mode, mode);
3994 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3995 2, idp->data, idp->len,
3997 *umodes = silc_buffer_realloc(*umodes,
3999 (*umodes)->truelen + tmp->len :
4001 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4002 silc_buffer_put(*umodes, tmp->data, tmp->len);
4003 silc_buffer_pull(*umodes, tmp->len);
4004 silc_buffer_free(tmp);
4006 silc_buffer_free(idp);
4008 if (!silc_idcache_list_next(list, &id_cache))
4013 silc_idcache_list_free(list);
4017 /* This function is used to announce our existing clients to our router
4018 when we've connected to it. If `creation_time' is non-zero then only
4019 the clients that has been created after the `creation_time' will be
4022 void silc_server_announce_clients(SilcServer server,
4023 unsigned long creation_time,
4024 SilcSocketConnection remote)
4026 SilcBuffer clients = NULL;
4027 SilcBuffer umodes = NULL;
4029 SILC_LOG_DEBUG(("Announcing clients"));
4031 /* Get clients in local list */
4032 silc_server_announce_get_clients(server, server->local_list,
4033 &clients, &umodes, creation_time);
4035 /* As router we announce our global list as well */
4036 if (server->server_type == SILC_ROUTER)
4037 silc_server_announce_get_clients(server, server->global_list,
4038 &clients, &umodes, creation_time);
4041 silc_buffer_push(clients, clients->data - clients->head);
4042 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
4044 /* Send the packet */
4045 silc_server_packet_send(server, remote,
4046 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4047 clients->data, clients->len, TRUE);
4049 silc_buffer_free(clients);
4053 silc_buffer_push(umodes, umodes->data - umodes->head);
4054 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4056 /* Send the packet */
4057 silc_server_packet_send(server, remote,
4058 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4059 umodes->data, umodes->len, TRUE);
4061 silc_buffer_free(umodes);
4065 /* Returns channel's topic for announcing it */
4067 void silc_server_announce_get_channel_topic(SilcServer server,
4068 SilcChannelEntry channel,
4073 if (channel->topic) {
4074 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4075 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4076 chidp->data, chidp->len,
4078 strlen(channel->topic));
4079 silc_buffer_free(chidp);
4083 /* Returns assembled packets for channel users of the `channel'. */
4085 void silc_server_announce_get_channel_users(SilcServer server,
4086 SilcChannelEntry channel,
4087 SilcBuffer *channel_modes,
4088 SilcBuffer *channel_users,
4089 SilcBuffer *channel_users_modes)
4091 SilcChannelClientEntry chl;
4092 SilcHashTableList htl;
4093 SilcBuffer chidp, clidp, csidp;
4096 unsigned char mode[4], *fkey = NULL;
4097 SilcUInt32 fkey_len = 0;
4100 SILC_LOG_DEBUG(("Start"));
4102 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4103 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4106 SILC_PUT32_MSB(channel->mode, mode);
4107 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4108 if (channel->founder_key)
4109 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4111 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4112 6, csidp->data, csidp->len,
4115 hmac, hmac ? strlen(hmac) : 0,
4116 channel->passphrase,
4117 channel->passphrase ?
4118 strlen(channel->passphrase) : 0,
4122 silc_buffer_realloc(*channel_modes,
4124 (*channel_modes)->truelen + len : len));
4125 silc_buffer_pull_tail(*channel_modes,
4126 ((*channel_modes)->end -
4127 (*channel_modes)->data));
4128 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4129 silc_buffer_pull(*channel_modes, len);
4130 silc_buffer_free(tmp);
4135 /* Now find all users on the channel */
4136 silc_hash_table_list(channel->user_list, &htl);
4137 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4138 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4141 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4142 clidp->data, clidp->len,
4143 chidp->data, chidp->len);
4146 silc_buffer_realloc(*channel_users,
4148 (*channel_users)->truelen + len : len));
4149 silc_buffer_pull_tail(*channel_users,
4150 ((*channel_users)->end -
4151 (*channel_users)->data));
4153 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4154 silc_buffer_pull(*channel_users, len);
4155 silc_buffer_free(tmp);
4157 /* CUMODE notify for mode change on the channel */
4158 SILC_PUT32_MSB(chl->mode, mode);
4159 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4160 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4161 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4162 4, csidp->data, csidp->len,
4164 clidp->data, clidp->len,
4167 *channel_users_modes =
4168 silc_buffer_realloc(*channel_users_modes,
4169 (*channel_users_modes ?
4170 (*channel_users_modes)->truelen + len : len));
4171 silc_buffer_pull_tail(*channel_users_modes,
4172 ((*channel_users_modes)->end -
4173 (*channel_users_modes)->data));
4175 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4176 silc_buffer_pull(*channel_users_modes, len);
4177 silc_buffer_free(tmp);
4181 silc_buffer_free(clidp);
4183 silc_hash_table_list_reset(&htl);
4184 silc_buffer_free(chidp);
4185 silc_buffer_free(csidp);
4188 /* Returns assembled packets for all channels and users on those channels
4189 from the given ID List. The packets are in the form dictated by the
4190 New Channel and New Channel User payloads. */
4192 void silc_server_announce_get_channels(SilcServer server,
4194 SilcBuffer *channels,
4195 SilcBuffer **channel_modes,
4196 SilcBuffer *channel_users,
4197 SilcBuffer **channel_users_modes,
4198 SilcUInt32 *channel_users_modes_c,
4199 SilcBuffer **channel_topics,
4200 SilcChannelID ***channel_ids,
4201 unsigned long creation_time)
4203 SilcIDCacheList list;
4204 SilcIDCacheEntry id_cache;
4205 SilcChannelEntry channel;
4208 SilcUInt16 name_len;
4210 int i = *channel_users_modes_c;
4213 SILC_LOG_DEBUG(("Start"));
4215 /* Go through all channels in the list */
4216 if (silc_idcache_get_all(id_list->channels, &list)) {
4217 if (silc_idcache_list_first(list, &id_cache)) {
4219 channel = (SilcChannelEntry)id_cache->context;
4221 if (creation_time && channel->created < creation_time)
4226 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4227 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4228 name_len = strlen(channel->channel_name);
4231 len = 4 + name_len + id_len + 4;
4233 silc_buffer_realloc(*channels,
4234 (*channels ? (*channels)->truelen +
4236 silc_buffer_pull_tail(*channels,
4237 ((*channels)->end - (*channels)->data));
4238 silc_buffer_format(*channels,
4239 SILC_STR_UI_SHORT(name_len),
4240 SILC_STR_UI_XNSTRING(channel->channel_name,
4242 SILC_STR_UI_SHORT(id_len),
4243 SILC_STR_UI_XNSTRING(cid, id_len),
4244 SILC_STR_UI_INT(channel->mode),
4246 silc_buffer_pull(*channels, len);
4249 if (creation_time && channel->updated < creation_time)
4255 /* Channel user modes */
4256 *channel_users_modes = silc_realloc(*channel_users_modes,
4257 sizeof(**channel_users_modes) *
4259 (*channel_users_modes)[i] = NULL;
4260 *channel_modes = silc_realloc(*channel_modes,
4261 sizeof(**channel_modes) * (i + 1));
4262 (*channel_modes)[i] = NULL;
4263 *channel_ids = silc_realloc(*channel_ids,
4264 sizeof(**channel_ids) * (i + 1));
4265 (*channel_ids)[i] = NULL;
4266 silc_server_announce_get_channel_users(server, channel,
4267 &(*channel_modes)[i],
4269 &(*channel_users_modes)[i]);
4270 (*channel_ids)[i] = channel->id;
4272 /* Channel's topic */
4273 *channel_topics = silc_realloc(*channel_topics,
4274 sizeof(**channel_topics) * (i + 1));
4275 (*channel_topics)[i] = NULL;
4276 silc_server_announce_get_channel_topic(server, channel,
4277 &(*channel_topics)[i]);
4278 (*channel_users_modes_c)++;
4282 if (!silc_idcache_list_next(list, &id_cache))
4287 silc_idcache_list_free(list);
4291 /* This function is used to announce our existing channels to our router
4292 when we've connected to it. This also announces the users on the
4293 channels to the router. If the `creation_time' is non-zero only the
4294 channels that was created after the `creation_time' are announced.
4295 Note that the channel users are still announced even if the `creation_time'
4298 void silc_server_announce_channels(SilcServer server,
4299 unsigned long creation_time,
4300 SilcSocketConnection remote)
4302 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4303 SilcBuffer *channel_users_modes = NULL;
4304 SilcBuffer *channel_topics = NULL;
4305 SilcUInt32 channel_users_modes_c = 0;
4306 SilcChannelID **channel_ids = NULL;
4308 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4310 /* Get channels and channel users in local list */
4311 silc_server_announce_get_channels(server, server->local_list,
4312 &channels, &channel_modes,
4314 &channel_users_modes,
4315 &channel_users_modes_c,
4317 &channel_ids, creation_time);
4319 /* Get channels and channel users in global list */
4320 if (server->server_type != SILC_SERVER)
4321 silc_server_announce_get_channels(server, server->global_list,
4322 &channels, &channel_modes,
4324 &channel_users_modes,
4325 &channel_users_modes_c,
4327 &channel_ids, creation_time);
4330 silc_buffer_push(channels, channels->data - channels->head);
4331 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4333 /* Send the packet */
4334 silc_server_packet_send(server, remote,
4335 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4336 channels->data, channels->len,
4339 silc_buffer_free(channels);
4342 if (channel_users) {
4343 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4344 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4345 channel_users->len);
4347 /* Send the packet */
4348 silc_server_packet_send(server, remote,
4349 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4350 channel_users->data, channel_users->len,
4353 silc_buffer_free(channel_users);
4356 if (channel_modes) {
4359 for (i = 0; i < channel_users_modes_c; i++) {
4360 if (!channel_modes[i])
4362 silc_buffer_push(channel_modes[i],
4363 channel_modes[i]->data -
4364 channel_modes[i]->head);
4365 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4366 channel_modes[i]->len);
4367 silc_server_packet_send_dest(server, remote,
4368 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4369 channel_ids[i], SILC_ID_CHANNEL,
4370 channel_modes[i]->data,
4371 channel_modes[i]->len,
4373 silc_buffer_free(channel_modes[i]);
4375 silc_free(channel_modes);
4378 if (channel_users_modes) {
4381 for (i = 0; i < channel_users_modes_c; i++) {
4382 if (!channel_users_modes[i])
4384 silc_buffer_push(channel_users_modes[i],
4385 channel_users_modes[i]->data -
4386 channel_users_modes[i]->head);
4387 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4388 channel_users_modes[i]->len);
4389 silc_server_packet_send_dest(server, remote,
4390 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4391 channel_ids[i], SILC_ID_CHANNEL,
4392 channel_users_modes[i]->data,
4393 channel_users_modes[i]->len,
4395 silc_buffer_free(channel_users_modes[i]);
4397 silc_free(channel_users_modes);
4400 if (channel_topics) {
4403 for (i = 0; i < channel_users_modes_c; i++) {
4404 if (!channel_topics[i])
4407 silc_buffer_push(channel_topics[i],
4408 channel_topics[i]->data -
4409 channel_topics[i]->head);
4410 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4411 channel_topics[i]->len);
4412 silc_server_packet_send_dest(server, remote,
4413 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4414 channel_ids[i], SILC_ID_CHANNEL,
4415 channel_topics[i]->data,
4416 channel_topics[i]->len,
4418 silc_buffer_free(channel_topics[i]);
4420 silc_free(channel_topics);
4423 silc_free(channel_ids);
4426 /* Failure timeout callback. If this is called then we will immediately
4427 process the received failure. We always process the failure with timeout
4428 since we do not want to blindly trust to received failure packets.
4429 This won't be called (the timeout is cancelled) if the failure was
4430 bogus (it is bogus if remote does not close the connection after sending
4433 SILC_TASK_CALLBACK(silc_server_failure_callback)
4435 SilcServerFailureContext f = (SilcServerFailureContext)context;
4437 if (f->sock->protocol) {
4438 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4439 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4445 /* Assembles user list and users mode list from the `channel'. */
4447 bool silc_server_get_users_on_channel(SilcServer server,
4448 SilcChannelEntry channel,
4449 SilcBuffer *user_list,
4450 SilcBuffer *mode_list,
4451 SilcUInt32 *user_count)
4453 SilcChannelClientEntry chl;
4454 SilcHashTableList htl;
4455 SilcBuffer client_id_list;
4456 SilcBuffer client_mode_list;
4458 SilcUInt32 list_count = 0, len = 0;
4460 if (!silc_hash_table_count(channel->user_list))
4463 silc_hash_table_list(channel->user_list, &htl);
4464 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4465 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4466 silc_hash_table_list_reset(&htl);
4468 client_id_list = silc_buffer_alloc(len);
4470 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4471 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4472 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4474 silc_hash_table_list(channel->user_list, &htl);
4475 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4477 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4478 silc_buffer_put(client_id_list, idp->data, idp->len);
4479 silc_buffer_pull(client_id_list, idp->len);
4480 silc_buffer_free(idp);
4482 /* Client's mode on channel */
4483 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4484 silc_buffer_pull(client_mode_list, 4);
4488 silc_hash_table_list_reset(&htl);
4489 silc_buffer_push(client_id_list,
4490 client_id_list->data - client_id_list->head);
4491 silc_buffer_push(client_mode_list,
4492 client_mode_list->data - client_mode_list->head);
4494 *user_list = client_id_list;
4495 *mode_list = client_mode_list;
4496 *user_count = list_count;
4500 /* Saves users and their modes to the `channel'. */
4502 void silc_server_save_users_on_channel(SilcServer server,
4503 SilcSocketConnection sock,
4504 SilcChannelEntry channel,
4505 SilcClientID *noadd,
4506 SilcBuffer user_list,
4507 SilcBuffer mode_list,
4508 SilcUInt32 user_count)
4513 SilcClientID *client_id;
4514 SilcClientEntry client;
4515 SilcIDCacheEntry cache;
4516 SilcChannelClientEntry chl;
4518 SILC_LOG_DEBUG(("Start"));
4520 for (i = 0; i < user_count; i++) {
4522 SILC_GET16_MSB(idp_len, user_list->data + 2);
4524 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4525 silc_buffer_pull(user_list, idp_len);
4530 SILC_GET32_MSB(mode, mode_list->data);
4531 silc_buffer_pull(mode_list, 4);
4533 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4534 silc_free(client_id);
4540 /* Check if we have this client cached already. */
4541 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4542 server->server_type, &cache);
4544 client = silc_idlist_find_client_by_id(server->global_list,
4545 client_id, server->server_type,
4548 /* If router did not find such Client ID in its lists then this must
4549 be bogus client or some router in the net is buggy. */
4550 if (server->server_type == SILC_ROUTER) {
4551 silc_free(client_id);
4555 /* We don't have that client anywhere, add it. The client is added
4556 to global list since server didn't have it in the lists so it must be
4558 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4559 silc_id_dup(client_id, SILC_ID_CLIENT),
4560 sock->user_data, NULL, 0);
4562 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4563 silc_free(client_id);
4567 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4572 silc_free(client_id);
4574 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4575 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4576 "%s", channel->channel_name));
4580 if (!silc_server_client_on_channel(client, channel, &chl)) {
4581 /* Client was not on the channel, add it. */
4582 chl = silc_calloc(1, sizeof(*chl));
4583 chl->client = client;
4585 chl->channel = channel;
4586 silc_hash_table_add(channel->user_list, chl->client, chl);
4587 silc_hash_table_add(client->channels, chl->channel, chl);
4588 channel->user_count++;
4596 /* Saves channels and channels user modes to the `client'. Removes
4597 the client from those channels that are not sent in the list but
4600 void silc_server_save_user_channels(SilcServer server,
4601 SilcSocketConnection sock,
4602 SilcClientEntry client,
4603 SilcBuffer channels,
4604 SilcBuffer channels_user_modes)
4607 SilcUInt32 *chumodes;
4608 SilcChannelPayload entry;
4609 SilcChannelEntry channel;
4610 SilcChannelID *channel_id;
4611 SilcChannelClientEntry chl;
4612 SilcHashTable ht = NULL;
4613 SilcHashTableList htl;
4617 if (!channels || !channels_user_modes ||
4618 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4621 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4622 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4624 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4625 NULL, NULL, NULL, TRUE);
4626 silc_dlist_start(ch);
4627 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4628 /* Check if we have this channel, and add it if we don't have it.
4629 Also add the client on the channel unless it is there already. */
4630 channel_id = silc_channel_get_id_parse(entry);
4631 channel = silc_idlist_find_channel_by_id(server->local_list,
4634 channel = silc_idlist_find_channel_by_id(server->global_list,
4637 if (server->server_type != SILC_SERVER) {
4638 silc_free(channel_id);
4643 /* We don't have that channel anywhere, add it. */
4644 name = silc_channel_get_name(entry, NULL);
4645 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4646 channel_id, server->router,
4649 silc_free(channel_id);
4656 channel->mode = silc_channel_get_mode(entry);
4658 /* Add the client on the channel */
4659 if (!silc_server_client_on_channel(client, channel, &chl)) {
4660 chl = silc_calloc(1, sizeof(*chl));
4661 chl->client = client;
4662 chl->mode = chumodes[i++];
4663 chl->channel = channel;
4664 silc_hash_table_add(channel->user_list, chl->client, chl);
4665 silc_hash_table_add(client->channels, chl->channel, chl);
4666 channel->user_count++;
4669 chl->mode = chumodes[i++];
4672 silc_hash_table_add(ht, channel, channel);
4673 silc_free(channel_id);
4675 silc_channel_payload_list_free(ch);
4676 silc_free(chumodes);
4680 /* Go through the list again and remove client from channels that
4681 are no part of the list. */
4683 silc_hash_table_list(client->channels, &htl);
4684 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4685 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4686 silc_hash_table_del(chl->channel->user_list, chl->client);
4687 silc_hash_table_del(chl->client->channels, chl->channel);
4691 silc_hash_table_list_reset(&htl);
4692 silc_hash_table_free(ht);
4694 silc_hash_table_list(client->channels, &htl);
4695 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4696 silc_hash_table_del(chl->channel->user_list, chl->client);
4697 silc_hash_table_del(chl->client->channels, chl->channel);
4700 silc_hash_table_list_reset(&htl);
4704 /* Lookups route to the client indicated by the `id_data'. The connection
4705 object and internal data object is returned. Returns NULL if route
4706 could not be found to the client. If the `client_id' is specified then
4707 it is used and the `id_data' is ignored. */
4709 SilcSocketConnection
4710 silc_server_get_client_route(SilcServer server,
4711 unsigned char *id_data,
4713 SilcClientID *client_id,
4714 SilcIDListData *idata,
4715 SilcClientEntry *client_entry)
4718 SilcClientEntry client;
4720 SILC_LOG_DEBUG(("Start"));
4723 *client_entry = NULL;
4725 /* Decode destination Client ID */
4727 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4729 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4733 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4736 /* If the destination belongs to our server we don't have to route
4737 the packet anywhere but to send it to the local destination. */
4738 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4742 /* If we are router and the client has router then the client is in
4743 our cell but not directly connected to us. */
4744 if (server->server_type == SILC_ROUTER && client->router) {
4745 /* We are of course in this case the client's router thus the route
4746 to the client is the server who owns the client. So, we will send
4747 the packet to that server. */
4749 *idata = (SilcIDListData)client->router;
4750 return client->router->connection;
4753 /* Seems that client really is directly connected to us */
4755 *idata = (SilcIDListData)client;
4757 *client_entry = client;
4758 return client->connection;
4761 /* Destination belongs to someone not in this server. If we are normal
4762 server our action is to send the packet to our router. */
4763 if (server->server_type != SILC_ROUTER && !server->standalone) {
4766 *idata = (SilcIDListData)server->router;
4767 return SILC_PRIMARY_ROUTE(server);
4770 /* We are router and we will perform route lookup for the destination
4771 and send the packet to fastest route. */
4772 if (server->server_type == SILC_ROUTER && !server->standalone) {
4773 /* Check first that the ID is valid */
4774 client = silc_idlist_find_client_by_id(server->global_list, id,
4777 SilcSocketConnection dst_sock;
4779 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4783 *idata = (SilcIDListData)dst_sock->user_data;
4792 /* Encodes and returns channel list of channels the `client' has joined.
4793 Secret channels are not put to the list. */
4795 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4796 SilcClientEntry client,
4799 SilcBuffer *user_mode_list)
4801 SilcBuffer buffer = NULL;
4802 SilcChannelEntry channel;
4803 SilcChannelClientEntry chl;
4804 SilcHashTableList htl;
4807 SilcUInt16 name_len;
4811 *user_mode_list = NULL;
4813 silc_hash_table_list(client->channels, &htl);
4814 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4815 channel = chl->channel;
4817 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4819 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4822 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4823 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4824 name_len = strlen(channel->channel_name);
4826 len = 4 + name_len + id_len + 4;
4827 buffer = silc_buffer_realloc(buffer,
4828 (buffer ? buffer->truelen + len : len));
4829 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4830 silc_buffer_format(buffer,
4831 SILC_STR_UI_SHORT(name_len),
4832 SILC_STR_UI_XNSTRING(channel->channel_name,
4834 SILC_STR_UI_SHORT(id_len),
4835 SILC_STR_UI_XNSTRING(cid, id_len),
4836 SILC_STR_UI_INT(chl->channel->mode),
4838 silc_buffer_pull(buffer, len);
4841 if (user_mode_list) {
4842 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4844 (*user_mode_list)->truelen + 4 :
4846 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4847 (*user_mode_list)->data));
4848 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4849 silc_buffer_pull(*user_mode_list, 4);
4852 silc_hash_table_list_reset(&htl);
4855 silc_buffer_push(buffer, buffer->data - buffer->head);
4856 if (user_mode_list && *user_mode_list)
4857 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4858 (*user_mode_list)->head));
4863 /* Finds client entry by Client ID and if it is not found then resolves
4864 it using WHOIS command. */
4866 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4867 SilcClientID *client_id,
4868 bool always_resolve,
4871 SilcClientEntry client;
4876 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4879 client = silc_idlist_find_client_by_id(server->global_list,
4880 client_id, TRUE, NULL);
4881 if (!client && server->server_type == SILC_ROUTER)
4885 if (!client && server->standalone)
4888 if (!client || !client->nickname || !client->username ||
4890 SilcBuffer buffer, idp;
4893 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4894 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4895 client->resolve_cmd_ident = ++server->cmd_ident;
4898 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4899 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4900 server->cmd_ident, 1,
4901 4, idp->data, idp->len);
4902 silc_server_packet_send(server, client ? client->router->connection :
4903 SILC_PRIMARY_ROUTE(server),
4904 SILC_PACKET_COMMAND, 0,
4905 buffer->data, buffer->len, FALSE);
4906 silc_buffer_free(idp);
4907 silc_buffer_free(buffer);
4918 /* A timeout callback for the re-key. We will be the initiator of the
4921 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4923 SilcSocketConnection sock = (SilcSocketConnection)context;
4924 SilcIDListData idata = (SilcIDListData)sock->user_data;
4925 SilcServer server = (SilcServer)idata->rekey->context;
4926 SilcProtocol protocol;
4927 SilcServerRekeyInternalContext *proto_ctx;
4929 /* Allocate internal protocol context. This is sent as context
4931 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4932 proto_ctx->server = (void *)server;
4933 proto_ctx->sock = sock;
4934 proto_ctx->responder = FALSE;
4935 proto_ctx->pfs = idata->rekey->pfs;
4937 /* Perform rekey protocol. Will call the final callback after the
4938 protocol is over. */
4939 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4940 &protocol, proto_ctx, silc_server_rekey_final);
4941 sock->protocol = protocol;
4943 /* Run the protocol */
4944 silc_protocol_execute(protocol, server->schedule, 0, 0);
4946 SILC_LOG_DEBUG(("Rekey protocol completed"));
4948 /* Re-register re-key timeout */
4949 silc_schedule_task_add(server->schedule, sock->sock,
4950 silc_server_rekey_callback,
4951 context, idata->rekey->timeout, 0,
4952 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4955 /* The final callback for the REKEY protocol. This will actually take the
4956 new key material into use. */
4958 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4960 SilcProtocol protocol = (SilcProtocol)context;
4961 SilcServerRekeyInternalContext *ctx =
4962 (SilcServerRekeyInternalContext *)protocol->context;
4963 SilcServer server = (SilcServer)ctx->server;
4964 SilcSocketConnection sock = ctx->sock;
4966 SILC_LOG_DEBUG(("Start"));
4968 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4969 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4970 /* Error occured during protocol */
4971 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4972 silc_protocol_cancel(protocol, server->schedule);
4973 silc_protocol_free(protocol);
4974 sock->protocol = NULL;
4976 silc_packet_context_free(ctx->packet);
4978 silc_ske_free(ctx->ske);
4983 /* Purge the outgoing data queue to assure that all rekey packets really
4984 go to the network before we quit the protocol. */
4985 silc_server_packet_queue_purge(server, sock);
4988 silc_protocol_free(protocol);
4989 sock->protocol = NULL;
4991 silc_packet_context_free(ctx->packet);
4993 silc_ske_free(ctx->ske);
4997 /* Task callback used to retrieve network statistical information from
4998 router server once in a while. */
5000 SILC_TASK_CALLBACK(silc_server_get_stats)
5002 SilcServer server = (SilcServer)context;
5003 SilcBuffer idp, packet;
5005 SILC_LOG_DEBUG(("Retrieving stats from router"));
5007 if (!server->standalone) {
5008 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5009 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5010 ++server->cmd_ident, 1,
5011 1, idp->data, idp->len);
5012 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5013 SILC_PACKET_COMMAND, 0, packet->data,
5014 packet->len, FALSE);
5015 silc_buffer_free(packet);
5016 silc_buffer_free(idp);
5019 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
5020 server, 120, 0, SILC_TASK_TIMEOUT,