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 SilcIDListData idata = server->sockets[i]->user_data;
681 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
683 silc_schedule_task_del_by_context(server->schedule,
685 silc_server_disconnect_remote(server, server->sockets[i],
687 "Server is shutting down");
689 silc_socket_free(server->sockets[i]);
690 server->sockets[i] = NULL;
694 /* We are not connected to network anymore */
695 server->standalone = TRUE;
697 silc_schedule_stop(server->schedule);
698 silc_schedule_uninit(server->schedule);
699 server->schedule = NULL;
701 silc_free(server->sockets);
702 server->sockets = NULL;
705 silc_server_protocols_unregister();
707 SILC_LOG_DEBUG(("Server stopped"));
710 /* Function that is called when the network connection to a router has
711 been established. This will continue with the key exchange protocol
712 with the remote router. */
714 void silc_server_start_key_exchange(SilcServer server,
715 SilcServerConnection sconn,
718 SilcSocketConnection newsocket;
719 SilcProtocol protocol;
720 SilcServerKEInternalContext *proto_ctx;
721 SilcServerConfigRouter *conn =
722 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
725 /* Cancel any possible retry timeouts */
726 silc_schedule_task_del_by_callback(server->schedule,
727 silc_server_connect_to_router_retry);
729 /* Set socket options */
730 silc_net_set_socket_nonblock(sock);
731 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
733 /* Create socket connection for the connection. Even though we
734 know that we are connecting to a router we will mark the socket
735 to be unknown connection until we have executed authentication
737 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
738 server->sockets[sock] = newsocket;
739 newsocket->hostname = strdup(sconn->remote_host);
740 newsocket->ip = strdup(sconn->remote_host);
741 newsocket->port = sconn->remote_port;
742 sconn->sock = newsocket;
744 /* Allocate internal protocol context. This is sent as context
746 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
747 proto_ctx->server = (void *)server;
748 proto_ctx->context = (void *)sconn;
749 proto_ctx->sock = newsocket;
750 proto_ctx->rng = server->rng;
751 proto_ctx->responder = FALSE;
753 /* Set Key Exchange flags from configuration, but fall back to global
755 SILC_GET_SKE_FLAGS(conn, proto_ctx);
756 if (server->config->param.key_exchange_pfs)
757 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
759 /* Perform key exchange protocol. silc_server_connect_to_router_second
760 will be called after the protocol is finished. */
761 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
762 &protocol, proto_ctx,
763 silc_server_connect_to_router_second);
764 newsocket->protocol = protocol;
766 /* Register a timeout task that will be executed if the protocol
767 is not executed within set limit. */
768 proto_ctx->timeout_task =
769 silc_schedule_task_add(server->schedule, sock,
770 silc_server_timeout_remote,
771 server, server->config->key_exchange_timeout, 0,
775 /* Register the connection for network input and output. This sets
776 that scheduler will listen for incoming packets for this connection
777 and sets that outgoing packets may be sent to this connection as
778 well. However, this doesn't set the scheduler for outgoing traffic,
779 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
780 later when outgoing data is available. */
781 context = (void *)server;
782 SILC_REGISTER_CONNECTION_FOR_IO(sock);
784 /* Run the protocol */
785 silc_protocol_execute(protocol, server->schedule, 0, 0);
788 /* Timeout callback that will be called to retry connecting to remote
789 router. This is used by both normal and router server. This will wait
790 before retrying the connecting. The timeout is generated by exponential
791 backoff algorithm. */
793 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
795 SilcServerConnection sconn = (SilcServerConnection)context;
796 SilcServer server = sconn->server;
797 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
798 SilcServerConfigConnParams *param =
799 (conn->param ? conn->param : &server->config->param);
801 SILC_LOG_INFO(("Retrying connecting to a router"));
803 /* Calculate next timeout */
804 if (sconn->retry_count >= 1) {
805 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
806 if (sconn->retry_timeout > param->reconnect_interval_max)
807 sconn->retry_timeout = param->reconnect_interval_max;
809 sconn->retry_timeout = param->reconnect_interval;
811 sconn->retry_count++;
812 sconn->retry_timeout = sconn->retry_timeout +
813 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
815 /* If we've reached max retry count, give up. */
816 if ((sconn->retry_count > param->reconnect_count) &&
817 !param->reconnect_keep_trying) {
818 SILC_LOG_ERROR(("Could not connect to router, giving up"));
819 silc_server_config_unref(&sconn->conn);
820 silc_free(sconn->remote_host);
821 silc_free(sconn->backup_replace_ip);
826 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
827 sconn->retry_timeout));
829 /* We will lookup a fresh pointer later */
830 silc_server_config_unref(&sconn->conn);
832 /* Wait one before retrying */
833 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
834 context, sconn->retry_timeout, 0,
835 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
838 /* Generic routine to use connect to a router. */
840 SILC_TASK_CALLBACK(silc_server_connect_router)
842 SilcServerConnection sconn = (SilcServerConnection)context;
843 SilcServer server = sconn->server;
844 SilcServerConfigRouter *rconn;
847 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
848 (sconn->backup ? "backup router" : "router"),
849 sconn->remote_host, sconn->remote_port));
851 server->router_connect = time(NULL);
852 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
855 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
856 (sconn->backup ? "backup router" : "router"),
857 sconn->remote_host, sconn->remote_port));
858 silc_free(sconn->remote_host);
859 silc_free(sconn->backup_replace_ip);
863 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
865 /* Connect to remote host */
866 sock = silc_net_create_connection(
867 (!server->config->server_info->primary ? NULL :
868 server->config->server_info->primary->server_ip),
869 sconn->remote_port, sconn->remote_host);
871 SILC_LOG_ERROR(("Could not connect to router %s:%d",
872 sconn->remote_host, sconn->remote_port));
873 if (!sconn->no_reconnect)
874 silc_schedule_task_add(server->schedule, 0,
875 silc_server_connect_to_router_retry,
876 context, 0, 1, SILC_TASK_TIMEOUT,
877 SILC_TASK_PRI_NORMAL);
879 silc_server_config_unref(&sconn->conn);
883 /* Continue with key exchange protocol */
884 silc_server_start_key_exchange(server, sconn, sock);
887 /* This function connects to our primary router or if we are a router this
888 establishes all our primary routes. This is called at the start of the
889 server to do authentication and key exchange with our router - called
892 SILC_TASK_CALLBACK(silc_server_connect_to_router)
894 SilcServer server = (SilcServer)context;
895 SilcServerConnection sconn;
896 SilcServerConfigRouter *ptr;
898 SILC_LOG_DEBUG(("We are %s",
899 (server->server_type == SILC_SERVER ?
900 "normal server" : server->server_type == SILC_ROUTER ?
901 "router" : "backup router/normal server")));
903 if (!server->config->routers) {
904 /* There wasn't a configured router, we will continue but we don't
905 have a connection to outside world. We will be standalone server. */
906 SILC_LOG_DEBUG(("No router(s), we are standalone"));
907 server->standalone = TRUE;
911 /* Cancel any possible retry timeouts */
912 silc_schedule_task_del_by_callback(server->schedule,
913 silc_server_connect_router);
914 silc_schedule_task_del_by_callback(server->schedule,
915 silc_server_connect_to_router_retry);
917 /* Create the connections to all our routes */
918 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
920 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
921 ptr->backup_router ? "Backup router" : "Router",
922 ptr->initiator ? "Initiator" : "Responder",
923 ptr->host, ptr->port));
925 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
926 ptr->initiator == FALSE && !server->backup_router)
927 server->wait_backup = TRUE;
929 if (ptr->initiator) {
930 /* Check whether we are connected to this host already */
931 if (silc_server_num_sockets_by_remote(server,
932 silc_net_is_ip(ptr->host) ?
934 silc_net_is_ip(ptr->host) ?
935 NULL : ptr->host, ptr->port,
936 SILC_SOCKET_TYPE_ROUTER)) {
937 SILC_LOG_DEBUG(("We are already connected to this router"));
941 /* Allocate connection object for hold connection specific stuff. */
942 sconn = silc_calloc(1, sizeof(*sconn));
943 sconn->server = server;
944 sconn->remote_host = strdup(ptr->host);
945 sconn->remote_port = ptr->port;
946 sconn->backup = ptr->backup_router;
948 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
949 sconn->backup_replace_port = ptr->backup_replace_port;
952 if (!server->router_conn && !sconn->backup)
953 server->router_conn = sconn;
955 silc_schedule_task_add(server->schedule, 0,
956 silc_server_connect_router,
957 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
958 SILC_TASK_PRI_NORMAL);
963 /* Second part of connecting to router(s). Key exchange protocol has been
964 executed and now we will execute authentication protocol. */
966 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
968 SilcProtocol protocol = (SilcProtocol)context;
969 SilcServerKEInternalContext *ctx =
970 (SilcServerKEInternalContext *)protocol->context;
971 SilcServer server = (SilcServer)ctx->server;
972 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
973 SilcSocketConnection sock = ctx->sock;
974 SilcServerConnAuthInternalContext *proto_ctx;
975 SilcServerConfigRouter *conn = NULL;
977 SILC_LOG_DEBUG(("Start"));
979 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
980 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
981 /* Error occured during protocol */
982 silc_protocol_free(protocol);
983 sock->protocol = NULL;
984 silc_ske_free_key_material(ctx->keymat);
986 silc_packet_context_free(ctx->packet);
988 silc_ske_free(ctx->ske);
989 silc_free(ctx->dest_id);
991 silc_schedule_task_del_by_callback(server->schedule,
992 silc_server_failure_callback);
993 silc_server_disconnect_remote(server, sock,
994 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
996 /* Try reconnecting if configuration wants it */
997 if (!sconn->no_reconnect) {
998 silc_schedule_task_add(server->schedule, 0,
999 silc_server_connect_to_router_retry,
1000 sconn, 0, 1, SILC_TASK_TIMEOUT,
1001 SILC_TASK_PRI_NORMAL);
1005 /* Call completion to indicate error */
1006 if (sconn->callback)
1007 (*sconn->callback)(server, NULL, sconn->callback_context);
1009 silc_server_config_unref(&sconn->conn);
1010 silc_free(sconn->remote_host);
1011 silc_free(sconn->backup_replace_ip);
1016 /* We now have the key material as the result of the key exchange
1017 protocol. Take the key material into use. Free the raw key material
1018 as soon as we've set them into use. */
1019 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1020 ctx->sock, ctx->keymat,
1021 ctx->ske->prop->cipher,
1022 ctx->ske->prop->pkcs,
1023 ctx->ske->prop->hash,
1024 ctx->ske->prop->hmac,
1025 ctx->ske->prop->group,
1027 silc_protocol_free(protocol);
1028 sock->protocol = NULL;
1029 silc_ske_free_key_material(ctx->keymat);
1031 silc_packet_context_free(ctx->packet);
1033 silc_ske_free(ctx->ske);
1034 silc_free(ctx->dest_id);
1036 silc_schedule_task_del_by_callback(server->schedule,
1037 silc_server_failure_callback);
1038 silc_server_disconnect_remote(server, sock,
1039 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1041 /* Try reconnecting if configuration wants it */
1042 if (!sconn->no_reconnect) {
1043 silc_schedule_task_add(server->schedule, 0,
1044 silc_server_connect_to_router_retry,
1045 sconn, 0, 1, SILC_TASK_TIMEOUT,
1046 SILC_TASK_PRI_NORMAL);
1050 /* Call completion to indicate error */
1051 if (sconn->callback)
1052 (*sconn->callback)(server, NULL, sconn->callback_context);
1054 silc_server_config_unref(&sconn->conn);
1055 silc_free(sconn->remote_host);
1056 silc_free(sconn->backup_replace_ip);
1060 silc_ske_free_key_material(ctx->keymat);
1062 /* Allocate internal context for the authentication protocol. This
1063 is sent as context for the protocol. */
1064 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1065 proto_ctx->server = (void *)server;
1066 proto_ctx->context = (void *)sconn;
1067 proto_ctx->sock = sock;
1068 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1069 proto_ctx->dest_id_type = ctx->dest_id_type;
1070 proto_ctx->dest_id = ctx->dest_id;
1072 /* Resolve the authentication method used in this connection. Check if
1073 we find a match from user configured connections */
1074 if (!sconn->conn.ref_ptr)
1075 conn = silc_server_config_find_router_conn(server, sock->hostname,
1078 conn = sconn->conn.ref_ptr;
1081 /* Match found. Use the configured authentication method. Take only
1082 the passphrase, since for public key auth we automatically use
1083 our local key pair. */
1084 if (conn->passphrase) {
1085 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1086 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1088 proto_ctx->auth_data = strdup(conn->passphrase);
1089 proto_ctx->auth_data_len = strlen(conn->passphrase);
1090 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1092 } else if (conn->publickeys) {
1093 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1095 proto_ctx->auth_meth = SILC_AUTH_NONE;
1098 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1099 sock->hostname, sock->ip, sock->port));
1100 silc_protocol_free(protocol);
1101 sock->protocol = NULL;
1103 silc_packet_context_free(ctx->packet);
1105 silc_ske_free(ctx->ske);
1106 silc_free(ctx->dest_id);
1108 silc_server_config_unref(&sconn->conn);
1109 silc_free(sconn->remote_host);
1110 silc_free(sconn->backup_replace_ip);
1112 silc_schedule_task_del_by_callback(server->schedule,
1113 silc_server_failure_callback);
1114 silc_server_disconnect_remote(server, sock,
1115 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1119 /* Free old protocol as it is finished now */
1120 silc_protocol_free(protocol);
1122 silc_packet_context_free(ctx->packet);
1124 sock->protocol = NULL;
1126 /* Allocate the authentication protocol. This is allocated here
1127 but we won't start it yet. We will be receiving party of this
1128 protocol thus we will wait that connecting party will make
1129 their first move. */
1130 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1131 &sock->protocol, proto_ctx,
1132 silc_server_connect_to_router_final);
1134 /* Register timeout task. If the protocol is not executed inside
1135 this timelimit the connection will be terminated. */
1136 proto_ctx->timeout_task =
1137 silc_schedule_task_add(server->schedule, sock->sock,
1138 silc_server_timeout_remote,
1140 server->config->conn_auth_timeout, 0,
1144 /* Run the protocol */
1145 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1148 /* Finalizes the connection to router. Registers a server task to the
1149 queue so that we can accept new connections. */
1151 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1153 SilcProtocol protocol = (SilcProtocol)context;
1154 SilcServerConnAuthInternalContext *ctx =
1155 (SilcServerConnAuthInternalContext *)protocol->context;
1156 SilcServer server = (SilcServer)ctx->server;
1157 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1158 SilcSocketConnection sock = ctx->sock;
1159 SilcServerEntry id_entry = NULL;
1161 SilcServerHBContext hb_context;
1162 unsigned char *id_string;
1164 SilcIDListData idata;
1165 SilcServerConfigRouter *conn = NULL;
1166 SilcServerConfigConnParams *param = NULL;
1168 SILC_LOG_DEBUG(("Start"));
1170 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1171 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1172 /* Error occured during protocol */
1173 silc_free(ctx->dest_id);
1174 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1177 /* Try reconnecting if configuration wants it */
1178 if (!sconn->no_reconnect) {
1179 silc_schedule_task_add(server->schedule, 0,
1180 silc_server_connect_to_router_retry,
1181 sconn, 0, 1, SILC_TASK_TIMEOUT,
1182 SILC_TASK_PRI_NORMAL);
1189 /* Add a task to the queue. This task receives new connections to the
1190 server. This task remains on the queue until the end of the program. */
1191 if (!server->listenning && !sconn->backup) {
1192 silc_schedule_task_add(server->schedule, server->sock,
1193 silc_server_accept_new_connection,
1194 (void *)server, 0, 0,
1196 SILC_TASK_PRI_NORMAL);
1197 server->listenning = TRUE;
1200 /* Send NEW_SERVER packet to the router. We will become registered
1201 to the SILC network after sending this packet. */
1202 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1203 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1204 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1205 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1206 silc_buffer_format(packet,
1207 SILC_STR_UI_SHORT(id_len),
1208 SILC_STR_UI_XNSTRING(id_string, id_len),
1209 SILC_STR_UI_SHORT(strlen(server->server_name)),
1210 SILC_STR_UI_XNSTRING(server->server_name,
1211 strlen(server->server_name)),
1214 /* Send the packet */
1215 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1216 packet->data, packet->len, TRUE);
1217 silc_buffer_free(packet);
1218 silc_free(id_string);
1220 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1222 /* Check that we do not have this ID already */
1223 id_entry = silc_idlist_find_server_by_id(server->local_list,
1224 ctx->dest_id, TRUE, NULL);
1226 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1228 id_entry = silc_idlist_find_server_by_id(server->global_list,
1229 ctx->dest_id, TRUE, NULL);
1231 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1234 SILC_LOG_DEBUG(("New server id(%s)",
1235 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1237 /* Add the connected router to global server list. Router is sent
1238 as NULL since it's local to us. */
1239 id_entry = silc_idlist_add_server(server->global_list,
1240 strdup(sock->hostname),
1241 SILC_ROUTER, ctx->dest_id, NULL, sock);
1243 silc_free(ctx->dest_id);
1244 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1245 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1250 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1251 silc_free(sock->user_data);
1252 sock->user_data = (void *)id_entry;
1253 sock->type = SILC_SOCKET_TYPE_ROUTER;
1254 idata = (SilcIDListData)sock->user_data;
1255 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1256 SILC_IDLIST_STATUS_LOCAL);
1258 conn = sconn->conn.ref_ptr;
1259 param = &server->config->param;
1260 if (conn && conn->param)
1261 param = conn->param;
1263 /* Perform keepalive. The `hb_context' will be freed automatically
1264 when finally calling the silc_socket_free function. */
1265 hb_context = silc_calloc(1, sizeof(*hb_context));
1266 hb_context->server = server;
1267 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1268 silc_server_perform_heartbeat,
1271 /* Register re-key timeout */
1272 idata->rekey->timeout = param->key_exchange_rekey;
1273 idata->rekey->context = (void *)server;
1274 silc_schedule_task_add(server->schedule, sock->sock,
1275 silc_server_rekey_callback,
1276 (void *)sock, idata->rekey->timeout, 0,
1277 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1279 if (!sconn->backup) {
1280 /* Mark this router our primary router if we're still standalone */
1281 if (server->standalone) {
1282 server->id_entry->router = id_entry;
1283 server->router = id_entry;
1284 server->standalone = FALSE;
1286 /* If we are router then announce our possible servers. Backup
1287 router announces also global servers. */
1288 if (server->server_type == SILC_ROUTER)
1289 silc_server_announce_servers(server,
1290 server->backup_router ? TRUE : FALSE,
1291 0, SILC_PRIMARY_ROUTE(server));
1293 /* Announce our clients and channels to the router */
1294 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1295 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1297 /* If we are backup router then this primary router is whom we are
1299 if (server->server_type == SILC_BACKUP_ROUTER)
1300 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1303 /* Add this server to be our backup router */
1304 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1305 sconn->backup_replace_port, FALSE);
1308 sock->protocol = NULL;
1311 /* Call the completion callback to indicate that we've connected to
1313 if (sconn->callback)
1314 (*sconn->callback)(server, id_entry, sconn->callback_context);
1316 /* Free the temporary connection data context */
1318 silc_server_config_unref(&sconn->conn);
1319 silc_free(sconn->remote_host);
1320 silc_free(sconn->backup_replace_ip);
1323 if (sconn == server->router_conn)
1324 server->router_conn = NULL;
1327 /* Free the protocol object */
1328 if (sock->protocol == protocol)
1329 sock->protocol = NULL;
1330 silc_protocol_free(protocol);
1332 silc_packet_context_free(ctx->packet);
1334 silc_ske_free(ctx->ske);
1335 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1336 silc_free(ctx->auth_data);
1340 /* Host lookup callback that is called after the incoming connection's
1341 IP and FQDN lookup is performed. This will actually check the acceptance
1342 of the incoming connection and will register the key exchange protocol
1343 for this connection. */
1346 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1349 SilcServerKEInternalContext *proto_ctx =
1350 (SilcServerKEInternalContext *)context;
1351 SilcServer server = (SilcServer)proto_ctx->server;
1352 SilcServerConfigClient *cconfig = NULL;
1353 SilcServerConfigServer *sconfig = NULL;
1354 SilcServerConfigRouter *rconfig = NULL;
1355 SilcServerConfigDeny *deny;
1358 context = (void *)server;
1360 /* Check whether we could resolve both IP and FQDN. */
1361 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1362 server->config->require_reverse_lookup)) {
1363 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1364 sock->hostname ? sock->hostname :
1365 sock->ip ? sock->ip : ""));
1366 server->stat.conn_failures++;
1367 silc_server_disconnect_remote(server, sock,
1368 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1369 "Unknown host or IP");
1370 silc_free(proto_ctx);
1374 /* Register the connection for network input and output. This sets
1375 that scheduler will listen for incoming packets for this connection
1376 and sets that outgoing packets may be sent to this connection as well.
1377 However, this doesn't set the scheduler for outgoing traffic, it
1378 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1379 later when outgoing data is available. */
1380 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1382 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1385 /* Listenning port */
1386 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1387 silc_server_disconnect_remote(server, sock,
1388 SILC_STATUS_ERR_RESOURCE_LIMIT,
1389 "Connection refused");
1390 server->stat.conn_failures++;
1391 silc_free(proto_ctx);
1394 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1396 /* Check whether this connection is denied to connect to us. */
1397 deny = silc_server_config_find_denied(server, sock->ip);
1399 deny = silc_server_config_find_denied(server, sock->hostname);
1401 /* The connection is denied */
1402 SILC_LOG_INFO(("Connection %s (%s) is denied",
1403 sock->hostname, sock->ip));
1404 silc_server_disconnect_remote(server, sock,
1405 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1407 server->stat.conn_failures++;
1408 silc_free(proto_ctx);
1412 /* Check whether we have configured this sort of connection at all. We
1413 have to check all configurations since we don't know what type of
1414 connection this is. */
1415 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1416 cconfig = silc_server_config_find_client(server, sock->hostname);
1417 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1418 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1419 if (server->server_type == SILC_ROUTER) {
1420 if (!(rconfig = silc_server_config_find_router_conn(server,
1421 sock->ip, sock->port)))
1422 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1425 if (!cconfig && !sconfig && !rconfig) {
1426 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1428 silc_server_disconnect_remote(server, sock,
1429 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1430 server->stat.conn_failures++;
1431 silc_free(proto_ctx);
1435 /* The connection is allowed */
1437 /* Set internal context for key exchange protocol. This is
1438 sent as context for the protocol. */
1439 proto_ctx->sock = sock;
1440 proto_ctx->rng = server->rng;
1441 proto_ctx->responder = TRUE;
1442 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1443 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1444 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1446 /* Take flags for key exchange. Since we do not know what type of connection
1447 this is, we go through all found configurations and use the global ones
1448 as well. This will result always into strictest key exchange flags. */
1449 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1450 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1451 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1452 if (server->config->param.key_exchange_pfs)
1453 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1455 /* Prepare the connection for key exchange protocol. We allocate the
1456 protocol but will not start it yet. The connector will be the
1457 initiator of the protocol thus we will wait for initiation from
1458 there before we start the protocol. */
1459 server->stat.auth_attempts++;
1460 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1461 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1462 &sock->protocol, proto_ctx,
1463 silc_server_accept_new_connection_second);
1465 /* Register a timeout task that will be executed if the connector
1466 will not start the key exchange protocol within specified timeout
1467 and the connection will be closed. */
1468 proto_ctx->timeout_task =
1469 silc_schedule_task_add(server->schedule, sock->sock,
1470 silc_server_timeout_remote,
1472 server->config->key_exchange_timeout, 0,
1477 /* Accepts new connections to the server. Accepting new connections are
1478 done in three parts to make it async. */
1480 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1482 SilcServer server = (SilcServer)context;
1483 SilcSocketConnection newsocket;
1484 SilcServerKEInternalContext *proto_ctx;
1487 SILC_LOG_DEBUG(("Accepting new connection"));
1489 server->stat.conn_attempts++;
1491 sock = silc_net_accept_connection(fd);
1493 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1494 server->stat.conn_failures++;
1498 /* Check for maximum allowed connections */
1499 if (sock > server->config->param.connections_max) {
1500 SILC_LOG_ERROR(("Refusing connection, server is full"));
1501 server->stat.conn_failures++;
1502 silc_net_close_connection(sock);
1506 /* Set socket options */
1507 silc_net_set_socket_nonblock(sock);
1508 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1510 /* We don't create a ID yet, since we don't know what type of connection
1511 this is yet. But, we do add the connection to the socket table. */
1512 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1513 server->sockets[sock] = newsocket;
1515 /* Perform asynchronous host lookup. This will lookup the IP and the
1516 FQDN of the remote connection. After the lookup is done the connection
1517 is accepted further. */
1518 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1519 proto_ctx->server = server;
1520 proto_ctx->context = (void *)fd;
1521 silc_socket_host_lookup(newsocket, TRUE,
1522 silc_server_accept_new_connection_lookup,
1523 (void *)proto_ctx, server->schedule);
1526 /* Second part of accepting new connection. Key exchange protocol has been
1527 performed and now it is time to do little connection authentication
1528 protocol to figure out whether this connection is client or server
1529 and whether it has right to access this server (especially server
1530 connections needs to be authenticated). */
1532 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1534 SilcProtocol protocol = (SilcProtocol)context;
1535 SilcServerKEInternalContext *ctx =
1536 (SilcServerKEInternalContext *)protocol->context;
1537 SilcServer server = (SilcServer)ctx->server;
1538 SilcSocketConnection sock = ctx->sock;
1539 SilcServerConnAuthInternalContext *proto_ctx;
1541 SILC_LOG_DEBUG(("Start"));
1543 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1544 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1545 /* Error occured during protocol */
1546 SILC_LOG_DEBUG(("Error key exchange protocol"));
1547 silc_protocol_free(protocol);
1548 sock->protocol = NULL;
1549 silc_ske_free_key_material(ctx->keymat);
1551 silc_packet_context_free(ctx->packet);
1553 silc_ske_free(ctx->ske);
1554 silc_free(ctx->dest_id);
1555 silc_server_config_unref(&ctx->cconfig);
1556 silc_server_config_unref(&ctx->sconfig);
1557 silc_server_config_unref(&ctx->rconfig);
1559 silc_schedule_task_del_by_callback(server->schedule,
1560 silc_server_failure_callback);
1561 silc_server_disconnect_remote(server, sock,
1562 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1564 server->stat.auth_failures++;
1568 /* We now have the key material as the result of the key exchange
1569 protocol. Take the key material into use. Free the raw key material
1570 as soon as we've set them into use. */
1571 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1572 ctx->sock, ctx->keymat,
1573 ctx->ske->prop->cipher,
1574 ctx->ske->prop->pkcs,
1575 ctx->ske->prop->hash,
1576 ctx->ske->prop->hmac,
1577 ctx->ske->prop->group,
1579 SILC_LOG_ERROR(("Error setting key material in use"));
1580 silc_protocol_free(protocol);
1581 sock->protocol = NULL;
1582 silc_ske_free_key_material(ctx->keymat);
1584 silc_packet_context_free(ctx->packet);
1586 silc_ske_free(ctx->ske);
1587 silc_free(ctx->dest_id);
1588 silc_server_config_unref(&ctx->cconfig);
1589 silc_server_config_unref(&ctx->sconfig);
1590 silc_server_config_unref(&ctx->rconfig);
1592 silc_schedule_task_del_by_callback(server->schedule,
1593 silc_server_failure_callback);
1594 silc_server_disconnect_remote(server, sock,
1595 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1596 server->stat.auth_failures++;
1599 silc_ske_free_key_material(ctx->keymat);
1601 /* Allocate internal context for the authentication protocol. This
1602 is sent as context for the protocol. */
1603 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1604 proto_ctx->server = (void *)server;
1605 proto_ctx->sock = sock;
1606 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1607 proto_ctx->responder = TRUE;
1608 proto_ctx->dest_id_type = ctx->dest_id_type;
1609 proto_ctx->dest_id = ctx->dest_id;
1610 proto_ctx->cconfig = ctx->cconfig;
1611 proto_ctx->sconfig = ctx->sconfig;
1612 proto_ctx->rconfig = ctx->rconfig;
1614 /* Free old protocol as it is finished now */
1615 silc_protocol_free(protocol);
1617 silc_packet_context_free(ctx->packet);
1619 sock->protocol = NULL;
1621 /* Allocate the authentication protocol. This is allocated here
1622 but we won't start it yet. We will be receiving party of this
1623 protocol thus we will wait that connecting party will make
1624 their first move. */
1625 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1626 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1627 &sock->protocol, proto_ctx,
1628 silc_server_accept_new_connection_final);
1630 /* Register timeout task. If the protocol is not executed inside
1631 this timelimit the connection will be terminated. */
1632 proto_ctx->timeout_task =
1633 silc_schedule_task_add(server->schedule, sock->sock,
1634 silc_server_timeout_remote,
1636 server->config->conn_auth_timeout, 0,
1641 /* After this is called, server don't wait for backup router anymore.
1642 This gets called automatically even after we have backup router
1643 connection established. */
1645 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1647 SilcServer server = context;
1648 server->wait_backup = FALSE;
1651 /* Final part of accepting new connection. The connection has now
1652 been authenticated and keys has been exchanged. We also know whether
1653 this is client or server connection. */
1655 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1657 SilcProtocol protocol = (SilcProtocol)context;
1658 SilcServerConnAuthInternalContext *ctx =
1659 (SilcServerConnAuthInternalContext *)protocol->context;
1660 SilcServer server = (SilcServer)ctx->server;
1661 SilcSocketConnection sock = ctx->sock;
1662 SilcServerHBContext hb_context;
1663 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1665 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1667 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1668 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1669 /* Error occured during protocol */
1670 SILC_LOG_DEBUG(("Error during authentication protocol"));
1671 silc_protocol_free(protocol);
1672 sock->protocol = NULL;
1674 silc_packet_context_free(ctx->packet);
1676 silc_ske_free(ctx->ske);
1677 silc_free(ctx->dest_id);
1678 silc_server_config_unref(&ctx->cconfig);
1679 silc_server_config_unref(&ctx->sconfig);
1680 silc_server_config_unref(&ctx->rconfig);
1682 silc_schedule_task_del_by_callback(server->schedule,
1683 silc_server_failure_callback);
1684 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1686 server->stat.auth_failures++;
1690 entry->data.last_receive = time(NULL);
1692 switch (ctx->conn_type) {
1693 case SILC_SOCKET_TYPE_CLIENT:
1695 SilcClientEntry client;
1696 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1698 /* Verify whether this connection is after all allowed to connect */
1699 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1700 &server->config->param,
1701 conn->param, ctx->ske)) {
1702 server->stat.auth_failures++;
1706 /* If we are primary router and we have backup router configured
1707 but it has not connected to use yet, do not accept any other
1709 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1710 !server->backup_router) {
1711 SilcServerConfigRouter *router;
1712 router = silc_server_config_get_backup_router(server);
1713 if (router && strcmp(server->config->server_info->primary->server_ip,
1715 silc_server_find_socket_by_host(server,
1716 SILC_SOCKET_TYPE_SERVER,
1717 router->backup_replace_ip, 0)) {
1718 SILC_LOG_INFO(("Will not accept connections because we do "
1719 "not have backup router connection established"));
1720 silc_server_disconnect_remote(server, sock,
1721 SILC_STATUS_ERR_PERM_DENIED,
1722 "We do not have connection to backup "
1723 "router established, try later");
1724 silc_free(sock->user_data);
1725 server->stat.auth_failures++;
1727 /* From here on, wait 10 seconds for the backup router to appear. */
1728 silc_schedule_task_add(server->schedule, 0,
1729 silc_server_backup_router_wait,
1730 (void *)server, 10, 0,
1731 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1736 SILC_LOG_DEBUG(("Remote host is client"));
1737 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1740 /* Add the client to the client ID cache. The nickname and Client ID
1741 and other information is created after we have received NEW_CLIENT
1742 packet from client. */
1743 client = silc_idlist_add_client(server->local_list,
1744 NULL, NULL, NULL, NULL, NULL, sock, 0);
1746 SILC_LOG_ERROR(("Could not add new client to cache"));
1747 silc_free(sock->user_data);
1748 silc_server_disconnect_remote(server, sock,
1749 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1750 server->stat.auth_failures++;
1753 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1756 server->stat.my_clients++;
1757 server->stat.clients++;
1758 server->stat.cell_clients++;
1760 /* Get connection parameters */
1762 if (conn->param->keepalive_secs)
1763 hearbeat_timeout = conn->param->keepalive_secs;
1766 id_entry = (void *)client;
1769 case SILC_SOCKET_TYPE_SERVER:
1770 case SILC_SOCKET_TYPE_ROUTER:
1772 SilcServerEntry new_server;
1773 bool initiator = FALSE;
1774 bool backup_local = FALSE;
1775 bool backup_router = FALSE;
1776 char *backup_replace_ip = NULL;
1777 SilcUInt16 backup_replace_port = 0;
1778 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1779 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1781 /* If we are backup router and this is incoming server connection
1782 and we do not have connection to primary router, do not allow
1784 if (server->server_type == SILC_BACKUP_ROUTER &&
1785 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1786 !SILC_PRIMARY_ROUTE(server)) {
1787 SILC_LOG_INFO(("Will not accept server connection because we do "
1788 "not have primary router connection established"));
1789 silc_server_disconnect_remote(server, sock,
1790 SILC_STATUS_ERR_PERM_DENIED,
1791 "We do not have connection to primary "
1792 "router established, try later");
1793 silc_free(sock->user_data);
1794 server->stat.auth_failures++;
1798 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1799 /* Verify whether this connection is after all allowed to connect */
1800 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1801 &server->config->param,
1802 rconn ? rconn->param : NULL,
1804 silc_free(sock->user_data);
1805 server->stat.auth_failures++;
1811 if (rconn->param->keepalive_secs)
1812 hearbeat_timeout = rconn->param->keepalive_secs;
1815 initiator = rconn->initiator;
1816 backup_local = rconn->backup_local;
1817 backup_router = rconn->backup_router;
1818 backup_replace_ip = rconn->backup_replace_ip;
1819 backup_replace_port = rconn->backup_replace_port;
1823 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1824 /* Verify whether this connection is after all allowed to connect */
1825 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1826 &server->config->param,
1827 sconn ? sconn->param : NULL,
1829 silc_free(sock->user_data);
1830 server->stat.auth_failures++;
1835 if (sconn->param->keepalive_secs)
1836 hearbeat_timeout = sconn->param->keepalive_secs;
1839 backup_router = sconn->backup_router;
1843 /* If we are primary router and we have backup router configured
1844 but it has not connected to use yet, do not accept any other
1846 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1847 !server->backup_router && !backup_router) {
1848 SilcServerConfigRouter *router;
1849 router = silc_server_config_get_backup_router(server);
1850 if (router && strcmp(server->config->server_info->primary->server_ip,
1852 silc_server_find_socket_by_host(server,
1853 SILC_SOCKET_TYPE_SERVER,
1854 router->backup_replace_ip, 0)) {
1855 SILC_LOG_INFO(("Will not accept connections because we do "
1856 "not have backup router connection established"));
1857 silc_server_disconnect_remote(server, sock,
1858 SILC_STATUS_ERR_PERM_DENIED,
1859 "We do not have connection to backup "
1860 "router established, try later");
1861 silc_free(sock->user_data);
1862 server->stat.auth_failures++;
1864 /* From here on, wait 10 seconds for the backup router to appear. */
1865 silc_schedule_task_add(server->schedule, 0,
1866 silc_server_backup_router_wait,
1867 (void *)server, 10, 0,
1868 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1873 SILC_LOG_DEBUG(("Remote host is %s",
1874 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1875 "server" : (backup_router ?
1876 "backup router" : "router")));
1877 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1878 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1879 "server" : (backup_router ?
1880 "backup router" : "router")));
1882 /* Add the server into server cache. The server name and Server ID
1883 is updated after we have received NEW_SERVER packet from the
1884 server. We mark ourselves as router for this server if we really
1887 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1888 server->local_list : (backup_router ?
1889 server->local_list :
1890 server->global_list)),
1892 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1893 SILC_SERVER : SILC_ROUTER),
1895 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1896 server->id_entry : (backup_router ?
1897 server->id_entry : NULL)),
1900 SILC_LOG_ERROR(("Could not add new server to cache"));
1901 silc_free(sock->user_data);
1902 silc_server_disconnect_remote(server, sock,
1903 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1904 server->stat.auth_failures++;
1907 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1909 id_entry = (void *)new_server;
1911 /* If the incoming connection is router and marked as backup router
1912 then add it to be one of our backups */
1913 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1914 /* Change it back to SERVER type since that's what it really is. */
1916 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1917 new_server->server_type = SILC_BACKUP_ROUTER;
1919 /* Remove the backup waiting with timeout */
1920 silc_schedule_task_add(server->schedule, 0,
1921 silc_server_backup_router_wait,
1922 (void *)server, 5, 0,
1923 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1927 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1928 server->stat.my_servers++;
1930 server->stat.my_routers++;
1931 server->stat.routers++;
1933 server->stat.servers++;
1935 /* Check whether this connection is to be our primary router connection
1936 if we do not already have the primary route. */
1937 if (!backup_router &&
1938 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1939 if (silc_server_config_is_primary_route(server) && !initiator)
1942 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1943 server->standalone = FALSE;
1944 if (!server->id_entry->router) {
1945 server->id_entry->router = id_entry;
1946 server->router = id_entry;
1957 sock->type = ctx->conn_type;
1959 /* Add the common data structure to the ID entry. */
1960 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1962 /* Add to sockets internal pointer for fast referencing */
1963 silc_free(sock->user_data);
1964 sock->user_data = id_entry;
1966 /* Connection has been fully established now. Everything is ok. */
1967 SILC_LOG_DEBUG(("New connection authenticated"));
1969 /* Perform keepalive. The `hb_context' will be freed automatically
1970 when finally calling the silc_socket_free function. */
1971 hb_context = silc_calloc(1, sizeof(*hb_context));
1972 hb_context->server = server;
1973 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1974 silc_server_perform_heartbeat,
1978 silc_schedule_task_del_by_callback(server->schedule,
1979 silc_server_failure_callback);
1980 silc_protocol_free(protocol);
1982 silc_packet_context_free(ctx->packet);
1984 silc_ske_free(ctx->ske);
1985 silc_free(ctx->dest_id);
1986 silc_server_config_unref(&ctx->cconfig);
1987 silc_server_config_unref(&ctx->sconfig);
1988 silc_server_config_unref(&ctx->rconfig);
1990 sock->protocol = NULL;
1993 /* This function is used to read packets from network and send packets to
1994 network. This is usually a generic task. */
1996 SILC_TASK_CALLBACK(silc_server_packet_process)
1998 SilcServer server = (SilcServer)context;
1999 SilcSocketConnection sock = server->sockets[fd];
2000 SilcIDListData idata;
2001 SilcCipher cipher = NULL;
2002 SilcHmac hmac = NULL;
2003 SilcUInt32 sequence = 0;
2007 SILC_LOG_DEBUG(("Unknown socket connection"));
2011 /* Packet sending */
2013 if (type == SILC_TASK_WRITE) {
2014 /* Do not send data to disconnected connection */
2015 if (SILC_IS_DISCONNECTED(sock)) {
2016 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2020 server->stat.packets_sent++;
2022 /* Send the packet */
2023 ret = silc_packet_send(sock, TRUE);
2025 /* If returned -2 could not write to connection now, will do
2031 SILC_LOG_ERROR(("Error sending packet to connection "
2032 "%s:%d [%s]", sock->hostname, sock->port,
2033 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2034 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2035 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2040 /* The packet has been sent and now it is time to set the connection
2041 back to only for input. When there is again some outgoing data
2042 available for this connection it will be set for output as well.
2043 This call clears the output setting and sets it only for input. */
2044 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2045 SILC_UNSET_OUTBUF_PENDING(sock);
2047 silc_buffer_clear(sock->outbuf);
2051 /* Packet receiving */
2053 /* Read some data from connection */
2054 ret = silc_packet_receive(sock);
2058 SILC_LOG_ERROR(("Error receiving packet from connection "
2059 "%s:%d [%s] %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" :
2063 "Router"), strerror(errno)));
2069 SILC_LOG_DEBUG(("Read EOF"));
2071 /* If connection is disconnecting already we will finally
2072 close the connection */
2073 if (SILC_IS_DISCONNECTING(sock)) {
2074 if (sock->user_data)
2075 silc_server_free_sock_user_data(server, sock, NULL);
2076 silc_server_close_connection(server, sock);
2080 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2081 SILC_SET_DISCONNECTING(sock);
2083 if (sock->user_data) {
2085 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2086 silc_server_free_sock_user_data(server, sock, tmp);
2088 silc_server_free_sock_user_data(server, sock, NULL);
2089 } else if (server->router_conn && server->router_conn->sock == sock &&
2090 !server->router && server->standalone)
2091 silc_schedule_task_add(server->schedule, 0,
2092 silc_server_connect_to_router,
2095 SILC_TASK_PRI_NORMAL);
2097 silc_server_close_connection(server, sock);
2101 /* If connection is disconnecting or disconnected we will ignore
2103 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2104 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2108 /* Get keys and stuff from ID entry */
2109 idata = (SilcIDListData)sock->user_data;
2111 cipher = idata->receive_key;
2112 hmac = idata->hmac_receive;
2113 sequence = idata->psn_receive;
2116 /* Process the packet. This will call the parser that will then
2117 decrypt and parse the packet. */
2118 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2119 TRUE : FALSE, cipher, hmac, sequence,
2120 silc_server_packet_parse, server);
2122 /* If this socket connection is not authenticated yet and the packet
2123 processing failed we will drop the connection since it can be
2124 a malicious flooder. */
2125 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
2126 (!sock->protocol || sock->protocol->protocol->type ==
2127 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
2128 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
2129 SILC_SET_DISCONNECTING(sock);
2131 if (sock->user_data)
2132 silc_server_free_sock_user_data(server, sock, NULL);
2133 silc_server_close_connection(server, sock);
2137 /* Parses whole packet, received earlier. */
2139 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2141 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2142 SilcServer server = (SilcServer)parse_ctx->context;
2143 SilcSocketConnection sock = parse_ctx->sock;
2144 SilcPacketContext *packet = parse_ctx->packet;
2145 SilcIDListData idata = (SilcIDListData)sock->user_data;
2148 server->stat.packets_received++;
2150 /* Parse the packet */
2151 if (parse_ctx->normal)
2152 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2154 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2156 /* If entry is disabled ignore what we got. */
2157 if (ret != SILC_PACKET_RESUME_ROUTER &&
2158 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2159 SILC_LOG_DEBUG(("Connection is disabled"));
2162 if (ret != SILC_PACKET_HEARTBEAT &&
2163 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2164 SILC_LOG_DEBUG(("Connection is disabled"));
2168 if (ret == SILC_PACKET_NONE) {
2169 SILC_LOG_DEBUG(("Error parsing packet"));
2173 /* Check that the the current client ID is same as in the client's packet. */
2174 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2175 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2176 if (client && client->id && packet->src_id) {
2177 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2178 packet->src_id_type);
2179 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2181 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2188 if (server->server_type == SILC_ROUTER) {
2189 /* Route the packet if it is not destined to us. Other ID types but
2190 server are handled separately after processing them. */
2191 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2192 packet->dst_id_type == SILC_ID_SERVER &&
2193 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2194 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2196 /* Route the packet to fastest route for the destination ID */
2197 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2198 packet->dst_id_type);
2201 silc_server_packet_route(server,
2202 silc_server_route_get(server, id,
2203 packet->dst_id_type),
2210 /* Parse the incoming packet type */
2211 silc_server_packet_parse_type(server, sock, packet);
2213 /* Broadcast packet if it is marked as broadcast packet and it is
2214 originated from router and we are router. */
2215 if (server->server_type == SILC_ROUTER &&
2216 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2217 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2218 /* Broadcast to our primary route */
2219 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2221 /* If we have backup routers then we need to feed all broadcast
2222 data to those servers. */
2223 silc_server_backup_broadcast(server, sock, packet);
2227 silc_packet_context_free(packet);
2228 silc_free(parse_ctx);
2231 /* Parser callback called by silc_packet_receive_process. This merely
2232 registers timeout that will handle the actual parsing when appropriate. */
2234 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2237 SilcServer server = (SilcServer)context;
2238 SilcSocketConnection sock = parser_context->sock;
2239 SilcIDListData idata = (SilcIDListData)sock->user_data;
2242 idata->psn_receive = parser_context->packet->sequence + 1;
2244 /* If protocol for this connection is key exchange or rekey then we'll
2245 process all packets synchronously, since there might be packets in
2246 queue that we are not able to decrypt without first processing the
2247 packets before them. */
2248 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2249 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2250 (sock->protocol && sock->protocol->protocol &&
2251 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2252 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2253 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2256 /* Reprocess data since we'll return FALSE here. This is because
2257 the idata->receive_key might have become valid in the last packet
2258 and we want to call this processor with valid cipher. */
2260 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2261 TRUE : FALSE, idata->receive_key,
2262 idata->hmac_receive, idata->psn_receive,
2263 silc_server_packet_parse, server);
2265 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2266 TRUE : FALSE, NULL, NULL, 0,
2267 silc_server_packet_parse, server);
2271 switch (sock->type) {
2272 case SILC_SOCKET_TYPE_UNKNOWN:
2273 case SILC_SOCKET_TYPE_CLIENT:
2274 /* Parse the packet with timeout */
2275 silc_schedule_task_add(server->schedule, sock->sock,
2276 silc_server_packet_parse_real,
2277 (void *)parser_context, 0, 100000,
2279 SILC_TASK_PRI_NORMAL);
2281 case SILC_SOCKET_TYPE_SERVER:
2282 case SILC_SOCKET_TYPE_ROUTER:
2283 /* Packets from servers are parsed immediately */
2284 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2294 /* Parses the packet type and calls what ever routines the packet type
2295 requires. This is done for all incoming packets. */
2297 void silc_server_packet_parse_type(SilcServer server,
2298 SilcSocketConnection sock,
2299 SilcPacketContext *packet)
2301 SilcPacketType type = packet->type;
2302 SilcIDListData idata = (SilcIDListData)sock->user_data;
2304 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2305 silc_get_packet_name(type), packet->flags));
2307 /* Parse the packet type */
2309 case SILC_PACKET_DISCONNECT:
2312 char *message = NULL;
2314 if (packet->flags & SILC_PACKET_FLAG_LIST)
2316 if (packet->buffer->len < 1)
2319 status = (SilcStatus)packet->buffer->data[0];
2320 if (packet->buffer->len > 1 &&
2321 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2322 message = silc_memdup(packet->buffer->data + 1,
2323 packet->buffer->len - 1);
2325 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2326 sock->ip, sock->hostname,
2327 silc_get_status_message(status), status,
2328 message ? message : ""));
2331 /* Handle the disconnection from our end too */
2332 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2333 silc_server_free_sock_user_data(server, sock, NULL);
2334 silc_server_close_connection(server, sock);
2338 case SILC_PACKET_SUCCESS:
2340 * Success received for something. For now we can have only
2341 * one protocol for connection executing at once hence this
2342 * success message is for whatever protocol is executing currently.
2344 if (packet->flags & SILC_PACKET_FLAG_LIST)
2347 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2350 case SILC_PACKET_FAILURE:
2352 * Failure received for something. For now we can have only
2353 * one protocol for connection executing at once hence this
2354 * failure message is for whatever protocol is executing currently.
2356 if (packet->flags & SILC_PACKET_FLAG_LIST)
2358 if (sock->protocol) {
2359 SilcServerFailureContext f;
2360 f = silc_calloc(1, sizeof(*f));
2364 /* We will wait 5 seconds to process this failure packet */
2365 silc_schedule_task_add(server->schedule, sock->sock,
2366 silc_server_failure_callback, (void *)f, 5, 0,
2367 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2371 case SILC_PACKET_REJECT:
2372 if (packet->flags & SILC_PACKET_FLAG_LIST)
2377 case SILC_PACKET_NOTIFY:
2379 * Received notify packet. Server can receive notify packets from
2380 * router. Server then relays the notify messages to clients if needed.
2382 if (packet->flags & SILC_PACKET_FLAG_LIST)
2383 silc_server_notify_list(server, sock, packet);
2385 silc_server_notify(server, sock, packet);
2391 case SILC_PACKET_CHANNEL_MESSAGE:
2393 * Received channel message. Channel messages are special packets
2394 * (although probably most common ones) thus they are handled
2397 if (packet->flags & SILC_PACKET_FLAG_LIST)
2399 idata->last_receive = time(NULL);
2400 silc_server_channel_message(server, sock, packet);
2403 case SILC_PACKET_CHANNEL_KEY:
2405 * Received key for channel. As channels are created by the router
2406 * the keys are as well. We will distribute the key to all of our
2407 * locally connected clients on the particular channel. Router
2408 * never receives this channel and thus is ignored.
2410 if (packet->flags & SILC_PACKET_FLAG_LIST)
2412 silc_server_channel_key(server, sock, packet);
2418 case SILC_PACKET_COMMAND:
2420 * Recived command. Processes the command request and allocates the
2421 * command context and calls the command.
2423 if (packet->flags & SILC_PACKET_FLAG_LIST)
2425 silc_server_command_process(server, sock, packet);
2428 case SILC_PACKET_COMMAND_REPLY:
2430 * Received command reply packet. Received command reply to command. It
2431 * may be reply to command sent by us or reply to command sent by client
2432 * that we've routed further.
2434 if (packet->flags & SILC_PACKET_FLAG_LIST)
2436 silc_server_command_reply(server, sock, packet);
2440 * Private Message packets
2442 case SILC_PACKET_PRIVATE_MESSAGE:
2444 * Received private message packet. The packet is coming from either
2447 if (packet->flags & SILC_PACKET_FLAG_LIST)
2449 idata->last_receive = time(NULL);
2450 silc_server_private_message(server, sock, packet);
2453 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2455 * Private message key packet.
2457 if (packet->flags & SILC_PACKET_FLAG_LIST)
2459 silc_server_private_message_key(server, sock, packet);
2463 * Key Exchange protocol packets
2465 case SILC_PACKET_KEY_EXCHANGE:
2466 if (packet->flags & SILC_PACKET_FLAG_LIST)
2469 if (sock->protocol && sock->protocol->protocol &&
2470 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2471 SilcServerKEInternalContext *proto_ctx =
2472 (SilcServerKEInternalContext *)sock->protocol->context;
2474 proto_ctx->packet = silc_packet_context_dup(packet);
2476 /* Let the protocol handle the packet */
2477 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2479 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2480 "protocol active, packet dropped."));
2484 case SILC_PACKET_KEY_EXCHANGE_1:
2485 if (packet->flags & SILC_PACKET_FLAG_LIST)
2488 if (sock->protocol && sock->protocol->protocol &&
2489 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2490 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2492 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2493 SilcServerRekeyInternalContext *proto_ctx =
2494 (SilcServerRekeyInternalContext *)sock->protocol->context;
2496 if (proto_ctx->packet)
2497 silc_packet_context_free(proto_ctx->packet);
2499 proto_ctx->packet = silc_packet_context_dup(packet);
2501 /* Let the protocol handle the packet */
2502 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2504 SilcServerKEInternalContext *proto_ctx =
2505 (SilcServerKEInternalContext *)sock->protocol->context;
2507 if (proto_ctx->packet)
2508 silc_packet_context_free(proto_ctx->packet);
2510 proto_ctx->packet = silc_packet_context_dup(packet);
2511 proto_ctx->dest_id_type = packet->src_id_type;
2512 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2513 packet->src_id_type);
2514 if (!proto_ctx->dest_id)
2517 /* Let the protocol handle the packet */
2518 silc_protocol_execute(sock->protocol, server->schedule,
2522 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2523 "protocol active, packet dropped."));
2527 case SILC_PACKET_KEY_EXCHANGE_2:
2528 if (packet->flags & SILC_PACKET_FLAG_LIST)
2531 if (sock->protocol && sock->protocol->protocol &&
2532 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2533 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2535 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2536 SilcServerRekeyInternalContext *proto_ctx =
2537 (SilcServerRekeyInternalContext *)sock->protocol->context;
2539 if (proto_ctx->packet)
2540 silc_packet_context_free(proto_ctx->packet);
2542 proto_ctx->packet = silc_packet_context_dup(packet);
2544 /* Let the protocol handle the packet */
2545 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2547 SilcServerKEInternalContext *proto_ctx =
2548 (SilcServerKEInternalContext *)sock->protocol->context;
2550 if (proto_ctx->packet)
2551 silc_packet_context_free(proto_ctx->packet);
2553 proto_ctx->packet = silc_packet_context_dup(packet);
2554 proto_ctx->dest_id_type = packet->src_id_type;
2555 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2556 packet->src_id_type);
2557 if (!proto_ctx->dest_id)
2560 /* Let the protocol handle the packet */
2561 silc_protocol_execute(sock->protocol, server->schedule,
2565 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2566 "protocol active, packet dropped."));
2570 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2572 * Connection authentication request packet. When we receive this packet
2573 * we will send to the other end information about our mandatory
2574 * authentication method for the connection. This packet maybe received
2577 if (packet->flags & SILC_PACKET_FLAG_LIST)
2579 silc_server_connection_auth_request(server, sock, packet);
2583 * Connection Authentication protocol packets
2585 case SILC_PACKET_CONNECTION_AUTH:
2586 /* Start of the authentication protocol. We receive here the
2587 authentication data and will verify it. */
2588 if (packet->flags & SILC_PACKET_FLAG_LIST)
2591 if (sock->protocol && sock->protocol->protocol->type
2592 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2594 SilcServerConnAuthInternalContext *proto_ctx =
2595 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2597 proto_ctx->packet = silc_packet_context_dup(packet);
2599 /* Let the protocol handle the packet */
2600 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2602 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2603 "protocol active, packet dropped."));
2607 case SILC_PACKET_NEW_ID:
2609 * Received New ID packet. This includes some new ID that has been
2610 * created. It may be for client, server or channel. This is the way
2611 * to distribute information about new registered entities in the
2614 if (packet->flags & SILC_PACKET_FLAG_LIST)
2615 silc_server_new_id_list(server, sock, packet);
2617 silc_server_new_id(server, sock, packet);
2620 case SILC_PACKET_NEW_CLIENT:
2622 * Received new client packet. This includes client information that
2623 * we will use to create initial client ID. After creating new
2624 * ID we will send it to the client.
2626 if (packet->flags & SILC_PACKET_FLAG_LIST)
2628 silc_server_new_client(server, sock, packet);
2631 case SILC_PACKET_NEW_SERVER:
2633 * Received new server packet. This includes Server ID and some other
2634 * information that we may save. This is received after server has
2637 if (packet->flags & SILC_PACKET_FLAG_LIST)
2639 silc_server_new_server(server, sock, packet);
2642 case SILC_PACKET_NEW_CHANNEL:
2644 * Received new channel packet. Information about new channel in the
2645 * network are distributed using this packet.
2647 if (packet->flags & SILC_PACKET_FLAG_LIST)
2648 silc_server_new_channel_list(server, sock, packet);
2650 silc_server_new_channel(server, sock, packet);
2653 case SILC_PACKET_HEARTBEAT:
2655 * Received heartbeat.
2657 if (packet->flags & SILC_PACKET_FLAG_LIST)
2661 case SILC_PACKET_KEY_AGREEMENT:
2663 * Received heartbeat.
2665 if (packet->flags & SILC_PACKET_FLAG_LIST)
2667 silc_server_key_agreement(server, sock, packet);
2670 case SILC_PACKET_REKEY:
2672 * Received re-key packet. The sender wants to regenerate the session
2675 if (packet->flags & SILC_PACKET_FLAG_LIST)
2677 silc_server_rekey(server, sock, packet);
2680 case SILC_PACKET_REKEY_DONE:
2682 * The re-key is done.
2684 if (packet->flags & SILC_PACKET_FLAG_LIST)
2687 if (sock->protocol && sock->protocol->protocol &&
2688 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2690 SilcServerRekeyInternalContext *proto_ctx =
2691 (SilcServerRekeyInternalContext *)sock->protocol->context;
2693 if (proto_ctx->packet)
2694 silc_packet_context_free(proto_ctx->packet);
2696 proto_ctx->packet = silc_packet_context_dup(packet);
2698 /* Let the protocol handle the packet */
2699 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2701 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2702 "protocol active, packet dropped."));
2706 case SILC_PACKET_FTP:
2708 if (packet->flags & SILC_PACKET_FLAG_LIST)
2710 silc_server_ftp(server, sock, packet);
2713 case SILC_PACKET_RESUME_CLIENT:
2715 if (packet->flags & SILC_PACKET_FLAG_LIST)
2717 silc_server_resume_client(server, sock, packet);
2720 case SILC_PACKET_RESUME_ROUTER:
2721 /* Resume router packet received. This packet is received for backup
2722 router resuming protocol. */
2723 if (packet->flags & SILC_PACKET_FLAG_LIST)
2725 silc_server_backup_resume_router(server, sock, packet);
2729 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2734 /* Creates connection to a remote router. */
2736 void silc_server_create_connection(SilcServer server,
2737 const char *remote_host, SilcUInt32 port)
2739 SilcServerConnection sconn;
2741 /* Allocate connection object for hold connection specific stuff. */
2742 sconn = silc_calloc(1, sizeof(*sconn));
2743 sconn->server = server;
2744 sconn->remote_host = strdup(remote_host);
2745 sconn->remote_port = port;
2746 sconn->no_reconnect = TRUE;
2748 silc_schedule_task_add(server->schedule, 0,
2749 silc_server_connect_router,
2750 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2751 SILC_TASK_PRI_NORMAL);
2754 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2756 silc_socket_free(context);
2759 /* Closes connection to socket connection */
2761 void silc_server_close_connection(SilcServer server,
2762 SilcSocketConnection sock)
2764 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2765 silc_schedule_task_add(server->schedule, 0,
2766 silc_server_close_connection_final,
2767 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2768 SILC_TASK_PRI_NORMAL);
2772 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2774 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2775 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2776 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2779 /* We won't listen for this connection anymore */
2780 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2782 /* Unregister all tasks */
2783 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2785 /* Close the actual connection */
2786 silc_net_close_connection(sock->sock);
2787 server->sockets[sock->sock] = NULL;
2789 /* If sock->user_data is NULL then we'll check for active protocols
2790 here since the silc_server_free_sock_user_data has not been called
2791 for this connection. */
2792 if (!sock->user_data) {
2793 /* If any protocol is active cancel its execution. It will call
2794 the final callback which will finalize the disconnection. */
2795 if (sock->protocol) {
2796 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2797 silc_protocol_cancel(sock->protocol, server->schedule);
2798 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2799 silc_protocol_execute_final(sock->protocol, server->schedule);
2800 sock->protocol = NULL;
2805 silc_schedule_task_add(server->schedule, 0,
2806 silc_server_close_connection_final,
2807 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2808 SILC_TASK_PRI_NORMAL);
2811 /* Sends disconnect message to remote connection and disconnects the
2814 void silc_server_disconnect_remote(SilcServer server,
2815 SilcSocketConnection sock,
2816 SilcStatus status, ...)
2819 unsigned char buf[512];
2827 memset(buf, 0, sizeof(buf));
2828 va_start(ap, status);
2829 cp = va_arg(ap, char *);
2831 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2836 SILC_LOG_DEBUG(("Disconnecting remote host"));
2838 /* Notify remote end that the conversation is over. The notify message
2839 is tried to be sent immediately. */
2843 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2845 buffer = silc_buffer_alloc_size(len);
2849 buffer->data[0] = status;
2851 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2853 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2854 buffer->data, buffer->len, TRUE);
2855 silc_buffer_free(buffer);
2858 silc_server_packet_queue_purge(server, sock);
2860 /* Mark the connection to be disconnected */
2861 SILC_SET_DISCONNECTED(sock);
2862 silc_server_close_connection(server, sock);
2867 SilcClientEntry client;
2868 } *FreeClientInternal;
2870 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2872 FreeClientInternal i = (FreeClientInternal)context;
2874 silc_idlist_del_data(i->client);
2875 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2879 /* Frees client data and notifies about client's signoff. */
2881 void silc_server_free_client_data(SilcServer server,
2882 SilcSocketConnection sock,
2883 SilcClientEntry client,
2885 const char *signoff)
2887 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2889 SILC_LOG_DEBUG(("Freeing client data"));
2892 if (!client->router && !client->connection &&
2893 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2894 SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2895 SILC_LOG_ERROR(("****** Contact Pekka"));
2896 SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2901 /* If there is pending outgoing data for the client then purge it
2902 to the network before removing the client entry. */
2903 silc_server_packet_queue_purge(server, sock);
2906 /* Check if anyone is watching this nickname */
2907 if (server->server_type == SILC_ROUTER)
2908 silc_server_check_watcher_list(server, client, NULL,
2909 SILC_NOTIFY_TYPE_SIGNOFF);
2911 /* Send SIGNOFF notify to routers. */
2913 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2914 SILC_BROADCAST(server), client->id,
2918 /* Remove client from all channels */
2920 silc_server_remove_from_channels(server, NULL, client,
2921 TRUE, (char *)signoff, TRUE);
2923 silc_server_remove_from_channels(server, NULL, client,
2924 FALSE, NULL, FALSE);
2926 /* Remove this client from watcher list if it is */
2927 silc_server_del_from_watcher_list(server, client);
2929 /* Update statistics */
2930 server->stat.my_clients--;
2931 server->stat.clients--;
2932 if (server->stat.cell_clients)
2933 server->stat.cell_clients--;
2934 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2935 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2936 silc_schedule_task_del_by_context(server->schedule, client);
2938 /* We will not delete the client entry right away. We will take it
2939 into history (for WHOWAS command) for 5 minutes */
2942 silc_schedule_task_add(server->schedule, 0,
2943 silc_server_free_client_data_timeout,
2945 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2946 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2948 client->router = NULL;
2949 client->connection = NULL;
2952 /* Frees user_data pointer from socket connection object. This also sends
2953 appropriate notify packets to the network to inform about leaving
2956 void silc_server_free_sock_user_data(SilcServer server,
2957 SilcSocketConnection sock,
2958 const char *signoff_message)
2960 switch (sock->type) {
2961 case SILC_SOCKET_TYPE_CLIENT:
2963 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2964 silc_server_free_client_data(server, sock, user_data, TRUE,
2968 case SILC_SOCKET_TYPE_SERVER:
2969 case SILC_SOCKET_TYPE_ROUTER:
2971 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2972 SilcServerEntry backup_router = NULL;
2974 SILC_LOG_DEBUG(("Freeing server data"));
2977 backup_router = silc_server_backup_get(server, user_data->id);
2979 if (!server->backup_router && server->server_type == SILC_ROUTER &&
2980 backup_router == server->id_entry &&
2981 sock->type != SILC_SOCKET_TYPE_ROUTER)
2982 backup_router = NULL;
2984 /* If this was our primary router connection then we're lost to
2985 the outside world. */
2986 if (server->router == user_data) {
2987 /* Check whether we have a backup router connection */
2988 if (!backup_router || backup_router == user_data) {
2989 silc_schedule_task_add(server->schedule, 0,
2990 silc_server_connect_to_router,
2993 SILC_TASK_PRI_NORMAL);
2995 server->id_entry->router = NULL;
2996 server->router = NULL;
2997 server->standalone = TRUE;
2998 backup_router = NULL;
3000 if (server->id_entry != backup_router) {
3001 SILC_LOG_INFO(("New primary router is backup router %s",
3002 backup_router->server_name));
3003 server->id_entry->router = backup_router;
3004 server->router = backup_router;
3005 server->router_connect = time(0);
3006 server->backup_primary = TRUE;
3008 SILC_LOG_INFO(("We are now new primary router in this cell"));
3009 server->id_entry->router = NULL;
3010 server->router = NULL;
3011 server->standalone = TRUE;
3013 /* We stop here to take a breath */
3017 if (server->server_type == SILC_BACKUP_ROUTER) {
3018 server->server_type = SILC_ROUTER;
3020 /* We'll need to constantly try to reconnect to the primary
3021 router so that we'll see when it comes back online. */
3022 silc_server_backup_reconnect(server, sock->ip, sock->port,
3023 silc_server_backup_connected,
3027 /* Mark this connection as replaced */
3028 silc_server_backup_replaced_add(server, user_data->id,
3031 } else if (backup_router) {
3032 SILC_LOG_INFO(("Enabling the use of backup router %s",
3033 backup_router->server_name));
3034 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3035 backup_router->server_name));
3037 /* Mark this connection as replaced */
3038 silc_server_backup_replaced_add(server, user_data->id,
3042 if (!backup_router) {
3043 /* Remove all servers that are originated from this server, and
3044 remove the clients of those servers too. */
3045 silc_server_remove_servers_by_server(server, user_data, TRUE);
3047 /* Remove the clients that this server owns as they will become
3049 silc_server_remove_clients_by_server(server, user_data,
3052 /* Remove channels owned by this server */
3053 if (server->server_type == SILC_SERVER)
3054 silc_server_remove_channels_by_server(server, user_data);
3056 /* Enable local server connections that may be disabled */
3057 silc_server_local_servers_toggle_enabled(server, TRUE);
3059 /* Update the client entries of this server to the new backup
3060 router. If we are the backup router we also resolve the real
3061 servers for the clients. After updating is over this also
3062 removes the clients that this server explicitly owns. */
3063 silc_server_update_clients_by_server(server, user_data,
3064 backup_router, TRUE);
3066 /* If we are router and just lost our primary router (now standlaone)
3067 we remove everything that was behind it, since we don't know
3069 if (server->server_type == SILC_ROUTER && server->standalone)
3070 /* Remove all servers that are originated from this server, and
3071 remove the clients of those servers too. */
3072 silc_server_remove_servers_by_server(server, user_data, TRUE);
3074 /* Finally remove the clients that are explicitly owned by this
3075 server. They go down with the server. */
3076 silc_server_remove_clients_by_server(server, user_data,
3079 /* Update our server cache to use the new backup router too. */
3080 silc_server_update_servers_by_server(server, user_data, backup_router);
3081 if (server->server_type == SILC_SERVER)
3082 silc_server_update_channels_by_server(server, user_data,
3085 /* Send notify about primary router going down to local operators */
3086 if (server->backup_router)
3087 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3088 SILC_NOTIFY_TYPE_NONE,
3089 ("%s switched to backup router %s "
3090 "(we are primary router now)",
3091 server->server_name, server->server_name));
3092 else if (server->router)
3093 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3094 SILC_NOTIFY_TYPE_NONE,
3095 ("%s switched to backup router %s",
3096 server->server_name,
3097 server->router->server_name));
3100 /* Free the server entry */
3101 silc_server_backup_del(server, user_data);
3102 silc_server_backup_replaced_del(server, user_data);
3103 silc_idlist_del_data(user_data);
3104 if (!silc_idlist_del_server(server->local_list, user_data))
3105 silc_idlist_del_server(server->global_list, user_data);
3106 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3107 server->stat.my_servers--;
3109 server->stat.my_routers--;
3110 server->stat.routers--;
3112 server->stat.servers--;
3113 if (server->server_type == SILC_ROUTER)
3114 server->stat.cell_servers--;
3116 if (backup_router && backup_router != server->id_entry) {
3117 /* Announce all of our stuff that was created about 5 minutes ago.
3118 The backup router knows all the other stuff already. */
3119 if (server->server_type == SILC_ROUTER)
3120 silc_server_announce_servers(server, FALSE, time(0) - 300,
3121 backup_router->connection);
3123 /* Announce our clients and channels to the router */
3124 silc_server_announce_clients(server, time(0) - 300,
3125 backup_router->connection);
3126 silc_server_announce_channels(server, time(0) - 300,
3127 backup_router->connection);
3133 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3135 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3137 silc_idlist_del_data(user_data);
3138 silc_free(user_data);
3143 /* If any protocol is active cancel its execution */
3144 if (sock->protocol) {
3145 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3146 silc_protocol_cancel(sock->protocol, server->schedule);
3147 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3148 silc_protocol_execute_final(sock->protocol, server->schedule);
3149 sock->protocol = NULL;
3152 sock->user_data = NULL;
3155 /* Removes client from all channels it has joined. This is used when client
3156 connection is disconnected. If the client on a channel is last, the
3157 channel is removed as well. This sends the SIGNOFF notify types. */
3159 void silc_server_remove_from_channels(SilcServer server,
3160 SilcSocketConnection sock,
3161 SilcClientEntry client,
3163 const char *signoff_message,
3166 SilcChannelEntry channel;
3167 SilcChannelClientEntry chl;
3168 SilcHashTableList htl;
3169 SilcBuffer clidp = NULL;
3174 SILC_LOG_DEBUG(("Removing client from joined channels"));
3176 if (notify && !client->id)
3180 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3185 /* Remove the client from all channels. The client is removed from
3186 the channels' user list. */
3187 silc_hash_table_list(client->channels, &htl);
3188 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3189 channel = chl->channel;
3191 /* Remove channel if this is last client leaving the channel, unless
3192 the channel is permanent. */
3193 if (server->server_type != SILC_SERVER &&
3194 silc_hash_table_count(channel->user_list) < 2) {
3195 silc_server_channel_delete(server, channel);
3199 silc_hash_table_del(client->channels, channel);
3200 silc_hash_table_del(channel->user_list, chl->client);
3201 channel->user_count--;
3203 /* If there is no global users on the channel anymore mark the channel
3204 as local channel. Do not check if the removed client is local client. */
3205 if (server->server_type == SILC_SERVER && channel->global_users &&
3206 chl->client->router && !silc_server_channel_has_global(channel))
3207 channel->global_users = FALSE;
3211 /* Update statistics */
3212 if (SILC_IS_LOCAL(client))
3213 server->stat.my_chanclients--;
3214 if (server->server_type == SILC_ROUTER) {
3215 server->stat.cell_chanclients--;
3216 server->stat.chanclients--;
3219 /* If there is not at least one local user on the channel then we don't
3220 need the channel entry anymore, we can remove it safely, unless the
3221 channel is permanent channel */
3222 if (server->server_type == SILC_SERVER &&
3223 !silc_server_channel_has_local(channel)) {
3224 /* Notify about leaving client if this channel has global users. */
3225 if (notify && channel->global_users)
3226 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3227 SILC_NOTIFY_TYPE_SIGNOFF,
3228 signoff_message ? 2 : 1,
3229 clidp->data, clidp->len,
3230 signoff_message, signoff_message ?
3231 strlen(signoff_message) : 0);
3233 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3234 silc_server_channel_delete(server, channel);
3238 /* Send notify to channel about client leaving SILC and channel too */
3240 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3241 SILC_NOTIFY_TYPE_SIGNOFF,
3242 signoff_message ? 2 : 1,
3243 clidp->data, clidp->len,
3244 signoff_message, signoff_message ?
3245 strlen(signoff_message) : 0);
3247 /* Don't create keys if we are shutting down */
3248 if (server->server_shutdown)
3251 /* Re-generate channel key if needed */
3252 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3253 if (!silc_server_create_channel_key(server, channel, 0))
3256 /* Send the channel key to the channel. The key of course is not sent
3257 to the client who was removed from the channel. */
3258 silc_server_send_channel_key(server, client->connection, channel,
3259 server->server_type == SILC_ROUTER ?
3260 FALSE : !server->standalone);
3264 silc_hash_table_list_reset(&htl);
3266 silc_buffer_free(clidp);
3269 /* Removes client from one channel. This is used for example when client
3270 calls LEAVE command to remove itself from the channel. Returns TRUE
3271 if channel still exists and FALSE if the channel is removed when
3272 last client leaves the channel. If `notify' is FALSE notify messages
3275 bool silc_server_remove_from_one_channel(SilcServer server,
3276 SilcSocketConnection sock,
3277 SilcChannelEntry channel,
3278 SilcClientEntry client,
3281 SilcChannelClientEntry chl;
3284 SILC_LOG_DEBUG(("Removing %s from channel %s",
3285 silc_id_render(client->id, SILC_ID_CLIENT),
3286 channel->channel_name));
3288 /* Get the entry to the channel, if this client is not on the channel
3290 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3293 /* Remove channel if this is last client leaving the channel, unless
3294 the channel is permanent. */
3295 if (server->server_type != SILC_SERVER &&
3296 silc_hash_table_count(channel->user_list) < 2) {
3297 silc_server_channel_delete(server, channel);
3301 silc_hash_table_del(client->channels, chl->channel);
3302 silc_hash_table_del(channel->user_list, chl->client);
3303 channel->user_count--;
3305 /* If there is no global users on the channel anymore mark the channel
3306 as local channel. Do not check if the client is local client. */
3307 if (server->server_type == SILC_SERVER && channel->global_users &&
3308 chl->client->router && !silc_server_channel_has_global(channel))
3309 channel->global_users = FALSE;
3313 /* Update statistics */
3314 if (SILC_IS_LOCAL(client))
3315 server->stat.my_chanclients--;
3316 if (server->server_type == SILC_ROUTER) {
3317 server->stat.cell_chanclients--;
3318 server->stat.chanclients--;
3321 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3325 /* If there is not at least one local user on the channel then we don't
3326 need the channel entry anymore, we can remove it safely, unless the
3327 channel is permanent channel */
3328 if (server->server_type == SILC_SERVER &&
3329 !silc_server_channel_has_local(channel)) {
3330 /* Notify about leaving client if this channel has global users. */
3331 if (notify && channel->global_users)
3332 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3333 SILC_NOTIFY_TYPE_LEAVE, 1,
3334 clidp->data, clidp->len);
3336 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3337 silc_server_channel_delete(server, channel);
3338 silc_buffer_free(clidp);
3342 /* Send notify to channel about client leaving the channel */
3344 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3345 SILC_NOTIFY_TYPE_LEAVE, 1,
3346 clidp->data, clidp->len);
3348 silc_buffer_free(clidp);
3352 /* Timeout callback. This is called if connection is idle or for some
3353 other reason is not responding within some period of time. This
3354 disconnects the remote end. */
3356 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3358 SilcServer server = (SilcServer)context;
3359 SilcSocketConnection sock = server->sockets[fd];
3360 SilcProtocolType protocol = 0;
3362 SILC_LOG_DEBUG(("Start"));
3367 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3368 sock->hostname, sock->ip));
3370 /* If we have protocol active we must assure that we call the protocol's
3371 final callback so that all the memory is freed. */
3372 if (sock->protocol) {
3373 protocol = sock->protocol->protocol->type;
3374 silc_protocol_cancel(sock->protocol, server->schedule);
3375 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3376 silc_protocol_execute_final(sock->protocol, server->schedule);
3377 sock->protocol = NULL;
3381 if (sock->user_data)
3382 silc_server_free_sock_user_data(server, sock, NULL);
3384 silc_server_disconnect_remote(server, sock,
3386 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3387 SILC_STATUS_ERR_AUTH_FAILED :
3388 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3389 "Connection timeout");
3392 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3393 function may be used only by router. In real SILC network all channels
3394 are created by routers thus this function is never used by normal
3397 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3398 SilcServerID *router_id,
3404 SilcChannelID *channel_id;
3405 SilcChannelEntry entry;
3409 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3412 cipher = SILC_DEFAULT_CIPHER;
3414 hmac = SILC_DEFAULT_HMAC;
3416 /* Allocate cipher */
3417 if (!silc_cipher_alloc(cipher, &key))
3421 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3422 silc_cipher_free(key);
3426 channel_name = strdup(channel_name);
3428 /* Create the channel ID */
3429 if (!silc_id_create_channel_id(server, router_id, server->rng,
3431 silc_free(channel_name);
3432 silc_cipher_free(key);
3433 silc_hmac_free(newhmac);
3437 /* Create the channel */
3438 entry = silc_idlist_add_channel(server->local_list, channel_name,
3439 SILC_CHANNEL_MODE_NONE, channel_id,
3440 NULL, key, newhmac, 0);
3442 silc_free(channel_name);
3443 silc_cipher_free(key);
3444 silc_hmac_free(newhmac);
3445 silc_free(channel_id);
3449 entry->cipher = strdup(cipher);
3450 entry->hmac_name = strdup(hmac);
3452 /* Now create the actual key material */
3453 if (!silc_server_create_channel_key(server, entry,
3454 silc_cipher_get_key_len(key) / 8)) {
3455 silc_idlist_del_channel(server->local_list, entry);
3459 /* Notify other routers about the new channel. We send the packet
3460 to our primary route. */
3462 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3463 channel_name, entry->id,
3464 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3467 /* Distribute to backup routers */
3468 if (broadcast && server->server_type == SILC_ROUTER) {
3471 SilcUInt32 name_len = strlen(channel_name);
3472 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3473 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3475 packet = silc_channel_payload_encode(channel_name, name_len,
3476 cid, channel_id_len, entry->mode);
3477 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3478 packet->data, packet->len, FALSE, TRUE);
3480 silc_buffer_free(packet);
3483 server->stat.my_channels++;
3484 if (server->server_type == SILC_ROUTER) {
3485 server->stat.channels++;
3486 server->stat.cell_channels++;
3487 entry->users_resolved = TRUE;
3493 /* Same as above but creates the channel with Channel ID `channel_id. */
3496 silc_server_create_new_channel_with_id(SilcServer server,
3500 SilcChannelID *channel_id,
3503 SilcChannelEntry entry;
3507 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3510 cipher = SILC_DEFAULT_CIPHER;
3512 hmac = SILC_DEFAULT_HMAC;
3514 /* Allocate cipher */
3515 if (!silc_cipher_alloc(cipher, &key))
3519 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3520 silc_cipher_free(key);
3524 channel_name = strdup(channel_name);
3526 /* Create the channel */
3527 entry = silc_idlist_add_channel(server->local_list, channel_name,
3528 SILC_CHANNEL_MODE_NONE, channel_id,
3529 NULL, key, newhmac, 0);
3531 silc_cipher_free(key);
3532 silc_hmac_free(newhmac);
3533 silc_free(channel_name);
3537 /* Now create the actual key material */
3538 if (!silc_server_create_channel_key(server, entry,
3539 silc_cipher_get_key_len(key) / 8)) {
3540 silc_idlist_del_channel(server->local_list, entry);
3544 /* Notify other routers about the new channel. We send the packet
3545 to our primary route. */
3547 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3548 channel_name, entry->id,
3549 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3552 /* Distribute to backup routers */
3553 if (broadcast && server->server_type == SILC_ROUTER) {
3556 SilcUInt32 name_len = strlen(channel_name);
3557 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3558 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3560 packet = silc_channel_payload_encode(channel_name, name_len,
3561 cid, channel_id_len, entry->mode);
3562 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3563 packet->data, packet->len, FALSE, TRUE);
3565 silc_buffer_free(packet);
3568 server->stat.my_channels++;
3569 if (server->server_type == SILC_ROUTER) {
3570 server->stat.channels++;
3571 server->stat.cell_channels++;
3572 entry->users_resolved = TRUE;
3578 /* Channel's key re-key timeout callback. */
3580 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3582 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3583 SilcServer server = (SilcServer)rekey->context;
3587 /* Return now if we are shutting down */
3588 if (server->server_shutdown)
3591 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3594 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3597 /* Generates new channel key. This is used to create the initial channel key
3598 but also to re-generate new key for channel. If `key_len' is provided
3599 it is the bytes of the key length. */
3601 bool silc_server_create_channel_key(SilcServer server,
3602 SilcChannelEntry channel,
3606 unsigned char channel_key[32], hash[32];
3609 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3610 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3614 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3616 if (!channel->channel_key)
3617 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3618 channel->channel_key = NULL;
3624 else if (channel->key_len)
3625 len = channel->key_len / 8;
3627 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3629 /* Create channel key */
3630 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3633 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3635 /* Remove old key if exists */
3637 memset(channel->key, 0, channel->key_len / 8);
3638 silc_free(channel->key);
3642 channel->key_len = len * 8;
3643 channel->key = silc_memdup(channel_key, len);
3644 memset(channel_key, 0, sizeof(channel_key));
3646 /* Generate HMAC key from the channel key data and set it */
3648 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3649 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3650 silc_hmac_set_key(channel->hmac, hash,
3651 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3652 memset(hash, 0, sizeof(hash));
3654 if (server->server_type == SILC_ROUTER) {
3655 if (!channel->rekey)
3656 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3657 channel->rekey->context = (void *)server;
3658 channel->rekey->channel = channel;
3659 channel->rekey->key_len = key_len;
3660 if (channel->rekey->task)
3661 silc_schedule_task_del(server->schedule, channel->rekey->task);
3663 channel->rekey->task =
3664 silc_schedule_task_add(server->schedule, 0,
3665 silc_server_channel_key_rekey,
3666 (void *)channel->rekey,
3667 server->config->channel_rekey_secs, 0,
3669 SILC_TASK_PRI_NORMAL);
3675 /* Saves the channel key found in the encoded `key_payload' buffer. This
3676 function is used when we receive Channel Key Payload and also when we're
3677 processing JOIN command reply. Returns entry to the channel. */
3679 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3680 SilcBuffer key_payload,
3681 SilcChannelEntry channel)
3683 SilcChannelKeyPayload payload = NULL;
3684 SilcChannelID *id = NULL;
3685 unsigned char *tmp, hash[32];
3689 /* Decode channel key payload */
3690 payload = silc_channel_key_payload_parse(key_payload->data,
3693 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3698 /* Get the channel entry */
3701 /* Get channel ID */
3702 tmp = silc_channel_key_get_id(payload, &tmp_len);
3703 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3709 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3711 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3713 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3714 silc_id_render(id, SILC_ID_CHANNEL)));
3720 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3722 tmp = silc_channel_key_get_key(payload, &tmp_len);
3728 cipher = silc_channel_key_get_cipher(payload, NULL);
3734 /* Remove old key if exists */
3736 memset(channel->key, 0, channel->key_len / 8);
3737 silc_free(channel->key);
3738 silc_cipher_free(channel->channel_key);
3741 /* Create new cipher */
3742 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3743 channel->channel_key = NULL;
3748 if (channel->cipher)
3749 silc_free(channel->cipher);
3750 channel->cipher = strdup(cipher);
3753 channel->key_len = tmp_len * 8;
3754 channel->key = silc_memdup(tmp, tmp_len);
3755 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3757 /* Generate HMAC key from the channel key data and set it */
3759 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3760 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3761 silc_hmac_set_key(channel->hmac, hash,
3762 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3764 memset(hash, 0, sizeof(hash));
3765 memset(tmp, 0, tmp_len);
3767 if (server->server_type == SILC_ROUTER) {
3768 if (!channel->rekey)
3769 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3770 channel->rekey->context = (void *)server;
3771 channel->rekey->channel = channel;
3772 if (channel->rekey->task)
3773 silc_schedule_task_del(server->schedule, channel->rekey->task);
3775 channel->rekey->task =
3776 silc_schedule_task_add(server->schedule, 0,
3777 silc_server_channel_key_rekey,
3778 (void *)channel->rekey,
3779 server->config->channel_rekey_secs, 0,
3781 SILC_TASK_PRI_NORMAL);
3787 silc_channel_key_payload_free(payload);
3792 /* Heartbeat callback. This function is set as argument for the
3793 silc_socket_set_heartbeat function. The library will call this function
3794 at the set time interval. */
3796 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3799 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3801 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3803 /* Send the heartbeat */
3804 silc_server_send_heartbeat(hb->server, sock);
3807 /* Returns assembled of all servers in the given ID list. The packet's
3808 form is dictated by the New ID payload. */
3810 static void silc_server_announce_get_servers(SilcServer server,
3811 SilcServerEntry remote,
3813 SilcBuffer *servers,
3814 unsigned long creation_time)
3816 SilcIDCacheList list;
3817 SilcIDCacheEntry id_cache;
3818 SilcServerEntry entry;
3821 /* Go through all clients in the list */
3822 if (silc_idcache_get_all(id_list->servers, &list)) {
3823 if (silc_idcache_list_first(list, &id_cache)) {
3825 entry = (SilcServerEntry)id_cache->context;
3827 /* Do not announce the one we've sending our announcements and
3828 do not announce ourself. Also check the creation time if it's
3830 if ((entry == remote) || (entry == server->id_entry) ||
3831 (creation_time && entry->data.created < creation_time)) {
3832 if (!silc_idcache_list_next(list, &id_cache))
3837 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3839 *servers = silc_buffer_realloc(*servers,
3841 (*servers)->truelen + idp->len :
3843 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3844 silc_buffer_put(*servers, idp->data, idp->len);
3845 silc_buffer_pull(*servers, idp->len);
3846 silc_buffer_free(idp);
3848 if (!silc_idcache_list_next(list, &id_cache))
3853 silc_idcache_list_free(list);
3858 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3864 p = silc_notify_payload_encode(notify, argc, ap);
3870 /* This function is used by router to announce existing servers to our
3871 primary router when we've connected to it. If `creation_time' is non-zero
3872 then only the servers that has been created after the `creation_time'
3873 will be announced. */
3875 void silc_server_announce_servers(SilcServer server, bool global,
3876 unsigned long creation_time,
3877 SilcSocketConnection remote)
3879 SilcBuffer servers = NULL;
3881 SILC_LOG_DEBUG(("Announcing servers"));
3883 /* Get servers in local list */
3884 silc_server_announce_get_servers(server, remote->user_data,
3885 server->local_list, &servers,
3889 /* Get servers in global list */
3890 silc_server_announce_get_servers(server, remote->user_data,
3891 server->global_list, &servers,
3895 silc_buffer_push(servers, servers->data - servers->head);
3896 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3898 /* Send the packet */
3899 silc_server_packet_send(server, remote,
3900 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3901 servers->data, servers->len, TRUE);
3903 silc_buffer_free(servers);
3907 /* Returns assembled packet of all clients in the given ID list. The
3908 packet's form is dictated by the New ID Payload. */
3910 static void silc_server_announce_get_clients(SilcServer server,
3912 SilcBuffer *clients,
3914 unsigned long creation_time)
3916 SilcIDCacheList list;
3917 SilcIDCacheEntry id_cache;
3918 SilcClientEntry client;
3921 unsigned char mode[4];
3923 /* Go through all clients in the list */
3924 if (silc_idcache_get_all(id_list->clients, &list)) {
3925 if (silc_idcache_list_first(list, &id_cache)) {
3927 client = (SilcClientEntry)id_cache->context;
3929 if (creation_time && client->data.created < creation_time) {
3930 if (!silc_idcache_list_next(list, &id_cache))
3935 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3937 *clients = silc_buffer_realloc(*clients,
3939 (*clients)->truelen + idp->len :
3941 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3942 silc_buffer_put(*clients, idp->data, idp->len);
3943 silc_buffer_pull(*clients, idp->len);
3945 SILC_PUT32_MSB(client->mode, mode);
3947 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3948 2, idp->data, idp->len,
3950 *umodes = silc_buffer_realloc(*umodes,
3952 (*umodes)->truelen + tmp->len :
3954 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3955 silc_buffer_put(*umodes, tmp->data, tmp->len);
3956 silc_buffer_pull(*umodes, tmp->len);
3957 silc_buffer_free(tmp);
3959 silc_buffer_free(idp);
3961 if (!silc_idcache_list_next(list, &id_cache))
3966 silc_idcache_list_free(list);
3970 /* This function is used to announce our existing clients to our router
3971 when we've connected to it. If `creation_time' is non-zero then only
3972 the clients that has been created after the `creation_time' will be
3975 void silc_server_announce_clients(SilcServer server,
3976 unsigned long creation_time,
3977 SilcSocketConnection remote)
3979 SilcBuffer clients = NULL;
3980 SilcBuffer umodes = NULL;
3982 SILC_LOG_DEBUG(("Announcing clients"));
3984 /* Get clients in local list */
3985 silc_server_announce_get_clients(server, server->local_list,
3986 &clients, &umodes, creation_time);
3988 /* As router we announce our global list as well */
3989 if (server->server_type == SILC_ROUTER)
3990 silc_server_announce_get_clients(server, server->global_list,
3991 &clients, &umodes, creation_time);
3994 silc_buffer_push(clients, clients->data - clients->head);
3995 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3997 /* Send the packet */
3998 silc_server_packet_send(server, remote,
3999 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4000 clients->data, clients->len, TRUE);
4002 silc_buffer_free(clients);
4006 silc_buffer_push(umodes, umodes->data - umodes->head);
4007 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
4009 /* Send the packet */
4010 silc_server_packet_send(server, remote,
4011 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4012 umodes->data, umodes->len, TRUE);
4014 silc_buffer_free(umodes);
4018 /* Returns channel's topic for announcing it */
4020 void silc_server_announce_get_channel_topic(SilcServer server,
4021 SilcChannelEntry channel,
4026 if (channel->topic) {
4027 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4028 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4029 chidp->data, chidp->len,
4031 strlen(channel->topic));
4032 silc_buffer_free(chidp);
4036 /* Returns assembled packets for channel users of the `channel'. */
4038 void silc_server_announce_get_channel_users(SilcServer server,
4039 SilcChannelEntry channel,
4040 SilcBuffer *channel_modes,
4041 SilcBuffer *channel_users,
4042 SilcBuffer *channel_users_modes)
4044 SilcChannelClientEntry chl;
4045 SilcHashTableList htl;
4046 SilcBuffer chidp, clidp, csidp;
4049 unsigned char mode[4], *fkey = NULL;
4050 SilcUInt32 fkey_len = 0;
4053 SILC_LOG_DEBUG(("Start"));
4055 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4056 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4059 SILC_PUT32_MSB(channel->mode, mode);
4060 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4061 if (channel->founder_key)
4062 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4064 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4065 6, csidp->data, csidp->len,
4068 hmac, hmac ? strlen(hmac) : 0,
4069 channel->passphrase,
4070 channel->passphrase ?
4071 strlen(channel->passphrase) : 0,
4075 silc_buffer_realloc(*channel_modes,
4077 (*channel_modes)->truelen + len : len));
4078 silc_buffer_pull_tail(*channel_modes,
4079 ((*channel_modes)->end -
4080 (*channel_modes)->data));
4081 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4082 silc_buffer_pull(*channel_modes, len);
4083 silc_buffer_free(tmp);
4088 /* Now find all users on the channel */
4089 silc_hash_table_list(channel->user_list, &htl);
4090 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4091 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4094 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4095 clidp->data, clidp->len,
4096 chidp->data, chidp->len);
4099 silc_buffer_realloc(*channel_users,
4101 (*channel_users)->truelen + len : len));
4102 silc_buffer_pull_tail(*channel_users,
4103 ((*channel_users)->end -
4104 (*channel_users)->data));
4106 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4107 silc_buffer_pull(*channel_users, len);
4108 silc_buffer_free(tmp);
4110 /* CUMODE notify for mode change on the channel */
4111 SILC_PUT32_MSB(chl->mode, mode);
4112 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4113 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4114 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4115 4, csidp->data, csidp->len,
4117 clidp->data, clidp->len,
4120 *channel_users_modes =
4121 silc_buffer_realloc(*channel_users_modes,
4122 (*channel_users_modes ?
4123 (*channel_users_modes)->truelen + len : len));
4124 silc_buffer_pull_tail(*channel_users_modes,
4125 ((*channel_users_modes)->end -
4126 (*channel_users_modes)->data));
4128 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4129 silc_buffer_pull(*channel_users_modes, len);
4130 silc_buffer_free(tmp);
4134 silc_buffer_free(clidp);
4136 silc_hash_table_list_reset(&htl);
4137 silc_buffer_free(chidp);
4138 silc_buffer_free(csidp);
4141 /* Returns assembled packets for all channels and users on those channels
4142 from the given ID List. The packets are in the form dictated by the
4143 New Channel and New Channel User payloads. */
4145 void silc_server_announce_get_channels(SilcServer server,
4147 SilcBuffer *channels,
4148 SilcBuffer **channel_modes,
4149 SilcBuffer *channel_users,
4150 SilcBuffer **channel_users_modes,
4151 SilcUInt32 *channel_users_modes_c,
4152 SilcBuffer **channel_topics,
4153 SilcChannelID ***channel_ids,
4154 unsigned long creation_time)
4156 SilcIDCacheList list;
4157 SilcIDCacheEntry id_cache;
4158 SilcChannelEntry channel;
4161 SilcUInt16 name_len;
4163 int i = *channel_users_modes_c;
4166 SILC_LOG_DEBUG(("Start"));
4168 /* Go through all channels in the list */
4169 if (silc_idcache_get_all(id_list->channels, &list)) {
4170 if (silc_idcache_list_first(list, &id_cache)) {
4172 channel = (SilcChannelEntry)id_cache->context;
4174 if (creation_time && channel->created < creation_time)
4179 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4180 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4181 name_len = strlen(channel->channel_name);
4184 len = 4 + name_len + id_len + 4;
4186 silc_buffer_realloc(*channels,
4187 (*channels ? (*channels)->truelen +
4189 silc_buffer_pull_tail(*channels,
4190 ((*channels)->end - (*channels)->data));
4191 silc_buffer_format(*channels,
4192 SILC_STR_UI_SHORT(name_len),
4193 SILC_STR_UI_XNSTRING(channel->channel_name,
4195 SILC_STR_UI_SHORT(id_len),
4196 SILC_STR_UI_XNSTRING(cid, id_len),
4197 SILC_STR_UI_INT(channel->mode),
4199 silc_buffer_pull(*channels, len);
4202 if (creation_time && channel->updated < creation_time)
4208 /* Channel user modes */
4209 *channel_users_modes = silc_realloc(*channel_users_modes,
4210 sizeof(**channel_users_modes) *
4212 (*channel_users_modes)[i] = NULL;
4213 *channel_modes = silc_realloc(*channel_modes,
4214 sizeof(**channel_modes) * (i + 1));
4215 (*channel_modes)[i] = NULL;
4216 *channel_ids = silc_realloc(*channel_ids,
4217 sizeof(**channel_ids) * (i + 1));
4218 (*channel_ids)[i] = NULL;
4219 silc_server_announce_get_channel_users(server, channel,
4220 &(*channel_modes)[i],
4222 &(*channel_users_modes)[i]);
4223 (*channel_ids)[i] = channel->id;
4225 /* Channel's topic */
4226 *channel_topics = silc_realloc(*channel_topics,
4227 sizeof(**channel_topics) * (i + 1));
4228 (*channel_topics)[i] = NULL;
4229 silc_server_announce_get_channel_topic(server, channel,
4230 &(*channel_topics)[i]);
4231 (*channel_users_modes_c)++;
4235 if (!silc_idcache_list_next(list, &id_cache))
4240 silc_idcache_list_free(list);
4244 /* This function is used to announce our existing channels to our router
4245 when we've connected to it. This also announces the users on the
4246 channels to the router. If the `creation_time' is non-zero only the
4247 channels that was created after the `creation_time' are announced.
4248 Note that the channel users are still announced even if the `creation_time'
4251 void silc_server_announce_channels(SilcServer server,
4252 unsigned long creation_time,
4253 SilcSocketConnection remote)
4255 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4256 SilcBuffer *channel_users_modes = NULL;
4257 SilcBuffer *channel_topics = NULL;
4258 SilcUInt32 channel_users_modes_c = 0;
4259 SilcChannelID **channel_ids = NULL;
4261 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4263 /* Get channels and channel users in local list */
4264 silc_server_announce_get_channels(server, server->local_list,
4265 &channels, &channel_modes,
4267 &channel_users_modes,
4268 &channel_users_modes_c,
4270 &channel_ids, creation_time);
4272 /* Get channels and channel users in global list */
4273 if (server->server_type != SILC_SERVER)
4274 silc_server_announce_get_channels(server, server->global_list,
4275 &channels, &channel_modes,
4277 &channel_users_modes,
4278 &channel_users_modes_c,
4280 &channel_ids, creation_time);
4283 silc_buffer_push(channels, channels->data - channels->head);
4284 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4286 /* Send the packet */
4287 silc_server_packet_send(server, remote,
4288 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4289 channels->data, channels->len,
4292 silc_buffer_free(channels);
4295 if (channel_users) {
4296 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4297 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4298 channel_users->len);
4300 /* Send the packet */
4301 silc_server_packet_send(server, remote,
4302 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4303 channel_users->data, channel_users->len,
4306 silc_buffer_free(channel_users);
4309 if (channel_modes) {
4312 for (i = 0; i < channel_users_modes_c; i++) {
4313 if (!channel_modes[i])
4315 silc_buffer_push(channel_modes[i],
4316 channel_modes[i]->data -
4317 channel_modes[i]->head);
4318 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4319 channel_modes[i]->len);
4320 silc_server_packet_send_dest(server, remote,
4321 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4322 channel_ids[i], SILC_ID_CHANNEL,
4323 channel_modes[i]->data,
4324 channel_modes[i]->len,
4326 silc_buffer_free(channel_modes[i]);
4328 silc_free(channel_modes);
4331 if (channel_users_modes) {
4334 for (i = 0; i < channel_users_modes_c; i++) {
4335 if (!channel_users_modes[i])
4337 silc_buffer_push(channel_users_modes[i],
4338 channel_users_modes[i]->data -
4339 channel_users_modes[i]->head);
4340 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4341 channel_users_modes[i]->len);
4342 silc_server_packet_send_dest(server, remote,
4343 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4344 channel_ids[i], SILC_ID_CHANNEL,
4345 channel_users_modes[i]->data,
4346 channel_users_modes[i]->len,
4348 silc_buffer_free(channel_users_modes[i]);
4350 silc_free(channel_users_modes);
4353 if (channel_topics) {
4356 for (i = 0; i < channel_users_modes_c; i++) {
4357 if (!channel_topics[i])
4360 silc_buffer_push(channel_topics[i],
4361 channel_topics[i]->data -
4362 channel_topics[i]->head);
4363 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4364 channel_topics[i]->len);
4365 silc_server_packet_send_dest(server, remote,
4366 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4367 channel_ids[i], SILC_ID_CHANNEL,
4368 channel_topics[i]->data,
4369 channel_topics[i]->len,
4371 silc_buffer_free(channel_topics[i]);
4373 silc_free(channel_topics);
4376 silc_free(channel_ids);
4379 /* Failure timeout callback. If this is called then we will immediately
4380 process the received failure. We always process the failure with timeout
4381 since we do not want to blindly trust to received failure packets.
4382 This won't be called (the timeout is cancelled) if the failure was
4383 bogus (it is bogus if remote does not close the connection after sending
4386 SILC_TASK_CALLBACK(silc_server_failure_callback)
4388 SilcServerFailureContext f = (SilcServerFailureContext)context;
4390 if (f->sock->protocol) {
4391 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4392 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4398 /* Assembles user list and users mode list from the `channel'. */
4400 bool silc_server_get_users_on_channel(SilcServer server,
4401 SilcChannelEntry channel,
4402 SilcBuffer *user_list,
4403 SilcBuffer *mode_list,
4404 SilcUInt32 *user_count)
4406 SilcChannelClientEntry chl;
4407 SilcHashTableList htl;
4408 SilcBuffer client_id_list;
4409 SilcBuffer client_mode_list;
4411 SilcUInt32 list_count = 0, len = 0;
4413 if (!silc_hash_table_count(channel->user_list))
4416 silc_hash_table_list(channel->user_list, &htl);
4417 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4418 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4419 silc_hash_table_list_reset(&htl);
4421 client_id_list = silc_buffer_alloc(len);
4423 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4424 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4425 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4427 silc_hash_table_list(channel->user_list, &htl);
4428 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4430 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4431 silc_buffer_put(client_id_list, idp->data, idp->len);
4432 silc_buffer_pull(client_id_list, idp->len);
4433 silc_buffer_free(idp);
4435 /* Client's mode on channel */
4436 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4437 silc_buffer_pull(client_mode_list, 4);
4441 silc_hash_table_list_reset(&htl);
4442 silc_buffer_push(client_id_list,
4443 client_id_list->data - client_id_list->head);
4444 silc_buffer_push(client_mode_list,
4445 client_mode_list->data - client_mode_list->head);
4447 *user_list = client_id_list;
4448 *mode_list = client_mode_list;
4449 *user_count = list_count;
4453 /* Saves users and their modes to the `channel'. */
4455 void silc_server_save_users_on_channel(SilcServer server,
4456 SilcSocketConnection sock,
4457 SilcChannelEntry channel,
4458 SilcClientID *noadd,
4459 SilcBuffer user_list,
4460 SilcBuffer mode_list,
4461 SilcUInt32 user_count)
4466 SilcClientID *client_id;
4467 SilcClientEntry client;
4468 SilcIDCacheEntry cache;
4469 SilcChannelClientEntry chl;
4472 SILC_LOG_DEBUG(("Start"));
4474 for (i = 0; i < user_count; i++) {
4476 SILC_GET16_MSB(idp_len, user_list->data + 2);
4478 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4479 silc_buffer_pull(user_list, idp_len);
4484 SILC_GET32_MSB(mode, mode_list->data);
4485 silc_buffer_pull(mode_list, 4);
4487 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4488 silc_free(client_id);
4494 /* Check if we have this client cached already. */
4495 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4496 server->server_type, &cache);
4498 client = silc_idlist_find_client_by_id(server->global_list,
4499 client_id, server->server_type,
4504 /* If router did not find such Client ID in its lists then this must
4505 be bogus client or some router in the net is buggy. */
4506 if (server->server_type == SILC_ROUTER) {
4507 silc_free(client_id);
4511 /* We don't have that client anywhere, add it. The client is added
4512 to global list since server didn't have it in the lists so it must be
4514 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4515 silc_id_dup(client_id, SILC_ID_CLIENT),
4516 sock->user_data, NULL, 0);
4518 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4519 silc_free(client_id);
4523 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4525 /* Found, if it is from global list we'll assure that we won't
4526 expire it now that the entry is on channel. */
4531 silc_free(client_id);
4533 if (!silc_server_client_on_channel(client, channel, &chl)) {
4534 /* Client was not on the channel, add it. */
4535 chl = silc_calloc(1, sizeof(*chl));
4536 chl->client = client;
4538 chl->channel = channel;
4539 silc_hash_table_add(channel->user_list, chl->client, chl);
4540 silc_hash_table_add(client->channels, chl->channel, chl);
4541 channel->user_count++;
4549 /* Saves channels and channels user modes to the `client'. Removes
4550 the client from those channels that are not sent in the list but
4553 void silc_server_save_user_channels(SilcServer server,
4554 SilcSocketConnection sock,
4555 SilcClientEntry client,
4556 SilcBuffer channels,
4557 SilcBuffer channels_user_modes)
4560 SilcUInt32 *chumodes;
4561 SilcChannelPayload entry;
4562 SilcChannelEntry channel;
4563 SilcChannelID *channel_id;
4564 SilcChannelClientEntry chl;
4565 SilcHashTable ht = NULL;
4566 SilcHashTableList htl;
4570 if (!channels ||!channels_user_modes)
4573 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4574 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4576 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4577 NULL, NULL, NULL, TRUE);
4578 silc_dlist_start(ch);
4579 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4580 /* Check if we have this channel, and add it if we don't have it.
4581 Also add the client on the channel unless it is there already. */
4582 channel_id = silc_channel_get_id_parse(entry);
4583 channel = silc_idlist_find_channel_by_id(server->local_list,
4586 channel = silc_idlist_find_channel_by_id(server->global_list,
4589 if (server->server_type != SILC_SERVER) {
4590 silc_free(channel_id);
4595 /* We don't have that channel anywhere, add it. */
4596 name = silc_channel_get_name(entry, NULL);
4597 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4598 channel_id, server->router,
4601 silc_free(channel_id);
4608 channel->mode = silc_channel_get_mode(entry);
4610 /* Add the client on the channel */
4611 if (!silc_server_client_on_channel(client, channel, &chl)) {
4612 chl = silc_calloc(1, sizeof(*chl));
4613 chl->client = client;
4614 chl->mode = chumodes[i++];
4615 chl->channel = channel;
4616 silc_hash_table_add(channel->user_list, chl->client, chl);
4617 silc_hash_table_add(client->channels, chl->channel, chl);
4618 channel->user_count++;
4621 chl->mode = chumodes[i++];
4624 silc_hash_table_add(ht, channel, channel);
4625 silc_free(channel_id);
4627 silc_channel_payload_list_free(ch);
4628 silc_free(chumodes);
4632 /* Go through the list again and remove client from channels that
4633 are no part of the list. */
4635 silc_hash_table_list(client->channels, &htl);
4636 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4637 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4638 silc_hash_table_del(chl->channel->user_list, chl->client);
4639 silc_hash_table_del(chl->client->channels, chl->channel);
4643 silc_hash_table_list_reset(&htl);
4644 silc_hash_table_free(ht);
4646 silc_hash_table_list(client->channels, &htl);
4647 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4648 silc_hash_table_del(chl->channel->user_list, chl->client);
4649 silc_hash_table_del(chl->client->channels, chl->channel);
4652 silc_hash_table_list_reset(&htl);
4656 /* Lookups route to the client indicated by the `id_data'. The connection
4657 object and internal data object is returned. Returns NULL if route
4658 could not be found to the client. If the `client_id' is specified then
4659 it is used and the `id_data' is ignored. */
4661 SilcSocketConnection
4662 silc_server_get_client_route(SilcServer server,
4663 unsigned char *id_data,
4665 SilcClientID *client_id,
4666 SilcIDListData *idata,
4667 SilcClientEntry *client_entry)
4670 SilcClientEntry client;
4672 SILC_LOG_DEBUG(("Start"));
4675 *client_entry = NULL;
4677 /* Decode destination Client ID */
4679 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4681 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4685 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4688 /* If the destination belongs to our server we don't have to route
4689 the packet anywhere but to send it to the local destination. */
4690 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4694 /* If we are router and the client has router then the client is in
4695 our cell but not directly connected to us. */
4696 if (server->server_type == SILC_ROUTER && client->router) {
4697 /* We are of course in this case the client's router thus the route
4698 to the client is the server who owns the client. So, we will send
4699 the packet to that server. */
4701 *idata = (SilcIDListData)client->router;
4702 return client->router->connection;
4705 /* Seems that client really is directly connected to us */
4707 *idata = (SilcIDListData)client;
4709 *client_entry = client;
4710 return client->connection;
4713 /* Destination belongs to someone not in this server. If we are normal
4714 server our action is to send the packet to our router. */
4715 if (server->server_type != SILC_ROUTER && !server->standalone) {
4718 *idata = (SilcIDListData)server->router;
4719 return SILC_PRIMARY_ROUTE(server);
4722 /* We are router and we will perform route lookup for the destination
4723 and send the packet to fastest route. */
4724 if (server->server_type == SILC_ROUTER && !server->standalone) {
4725 /* Check first that the ID is valid */
4726 client = silc_idlist_find_client_by_id(server->global_list, id,
4729 SilcSocketConnection dst_sock;
4731 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4735 *idata = (SilcIDListData)dst_sock->user_data;
4744 /* Encodes and returns channel list of channels the `client' has joined.
4745 Secret channels are not put to the list. */
4747 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4748 SilcClientEntry client,
4751 SilcBuffer *user_mode_list)
4753 SilcBuffer buffer = NULL;
4754 SilcChannelEntry channel;
4755 SilcChannelClientEntry chl;
4756 SilcHashTableList htl;
4759 SilcUInt16 name_len;
4763 *user_mode_list = NULL;
4765 silc_hash_table_list(client->channels, &htl);
4766 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4767 channel = chl->channel;
4769 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4771 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4774 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4775 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4776 name_len = strlen(channel->channel_name);
4778 len = 4 + name_len + id_len + 4;
4779 buffer = silc_buffer_realloc(buffer,
4780 (buffer ? buffer->truelen + len : len));
4781 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4782 silc_buffer_format(buffer,
4783 SILC_STR_UI_SHORT(name_len),
4784 SILC_STR_UI_XNSTRING(channel->channel_name,
4786 SILC_STR_UI_SHORT(id_len),
4787 SILC_STR_UI_XNSTRING(cid, id_len),
4788 SILC_STR_UI_INT(chl->channel->mode),
4790 silc_buffer_pull(buffer, len);
4793 if (user_mode_list) {
4794 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4796 (*user_mode_list)->truelen + 4 :
4798 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4799 (*user_mode_list)->data));
4800 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4801 silc_buffer_pull(*user_mode_list, 4);
4804 silc_hash_table_list_reset(&htl);
4807 silc_buffer_push(buffer, buffer->data - buffer->head);
4808 if (user_mode_list && *user_mode_list)
4809 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4810 (*user_mode_list)->head));
4815 /* Finds client entry by Client ID and if it is not found then resolves
4816 it using WHOIS command. */
4818 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4819 SilcClientID *client_id,
4820 bool always_resolve,
4823 SilcClientEntry client;
4828 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4831 client = silc_idlist_find_client_by_id(server->global_list,
4832 client_id, TRUE, NULL);
4833 if (!client && server->server_type == SILC_ROUTER)
4837 if (!client && server->standalone)
4840 if (!client || !client->nickname || !client->username ||
4842 SilcBuffer buffer, idp;
4845 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4846 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4847 client->resolve_cmd_ident = ++server->cmd_ident;
4850 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4851 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4852 server->cmd_ident, 1,
4853 4, idp->data, idp->len);
4854 silc_server_packet_send(server, client ? client->router->connection :
4855 SILC_PRIMARY_ROUTE(server),
4856 SILC_PACKET_COMMAND, 0,
4857 buffer->data, buffer->len, FALSE);
4858 silc_buffer_free(idp);
4859 silc_buffer_free(buffer);
4870 /* A timeout callback for the re-key. We will be the initiator of the
4873 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4875 SilcSocketConnection sock = (SilcSocketConnection)context;
4876 SilcIDListData idata = (SilcIDListData)sock->user_data;
4877 SilcServer server = (SilcServer)idata->rekey->context;
4878 SilcProtocol protocol;
4879 SilcServerRekeyInternalContext *proto_ctx;
4881 /* Allocate internal protocol context. This is sent as context
4883 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4884 proto_ctx->server = (void *)server;
4885 proto_ctx->sock = sock;
4886 proto_ctx->responder = FALSE;
4887 proto_ctx->pfs = idata->rekey->pfs;
4889 /* Perform rekey protocol. Will call the final callback after the
4890 protocol is over. */
4891 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4892 &protocol, proto_ctx, silc_server_rekey_final);
4893 sock->protocol = protocol;
4895 /* Run the protocol */
4896 silc_protocol_execute(protocol, server->schedule, 0, 0);
4898 SILC_LOG_DEBUG(("Rekey protocol completed"));
4900 /* Re-register re-key timeout */
4901 silc_schedule_task_add(server->schedule, sock->sock,
4902 silc_server_rekey_callback,
4903 context, idata->rekey->timeout, 0,
4904 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4907 /* The final callback for the REKEY protocol. This will actually take the
4908 new key material into use. */
4910 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4912 SilcProtocol protocol = (SilcProtocol)context;
4913 SilcServerRekeyInternalContext *ctx =
4914 (SilcServerRekeyInternalContext *)protocol->context;
4915 SilcServer server = (SilcServer)ctx->server;
4916 SilcSocketConnection sock = ctx->sock;
4918 SILC_LOG_DEBUG(("Start"));
4920 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4921 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4922 /* Error occured during protocol */
4923 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4924 silc_protocol_cancel(protocol, server->schedule);
4925 silc_protocol_free(protocol);
4926 sock->protocol = NULL;
4928 silc_packet_context_free(ctx->packet);
4930 silc_ske_free(ctx->ske);
4935 /* Purge the outgoing data queue to assure that all rekey packets really
4936 go to the network before we quit the protocol. */
4937 silc_server_packet_queue_purge(server, sock);
4940 silc_protocol_free(protocol);
4941 sock->protocol = NULL;
4943 silc_packet_context_free(ctx->packet);
4945 silc_ske_free(ctx->ske);
4949 /* Task callback used to retrieve network statistical information from
4950 router server once in a while. */
4952 SILC_TASK_CALLBACK(silc_server_get_stats)
4954 SilcServer server = (SilcServer)context;
4955 SilcBuffer idp, packet;
4957 SILC_LOG_DEBUG(("Retrieving stats from router"));
4959 if (!server->standalone) {
4960 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4961 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4962 ++server->cmd_ident, 1,
4963 1, idp->data, idp->len);
4964 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4965 SILC_PACKET_COMMAND, 0, packet->data,
4966 packet->len, FALSE);
4967 silc_buffer_free(packet);
4968 silc_buffer_free(idp);
4971 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4972 server, 120, 0, SILC_TASK_TIMEOUT,