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 /* Close all connections */
672 for (i = 0; i < server->config->param.connections_max; i++) {
673 if (!server->sockets[i])
675 if (!SILC_IS_LISTENER(server->sockets[i])) {
676 silc_schedule_task_del_by_context(server->schedule,
678 silc_server_disconnect_remote(server, server->sockets[i],
680 "Server is shutting down");
682 silc_socket_free(server->sockets[i]);
683 server->sockets[i] = NULL;
687 /* We are not connected to network anymore */
688 server->standalone = TRUE;
690 silc_schedule_stop(server->schedule);
691 silc_schedule_uninit(server->schedule);
692 server->schedule = NULL;
694 silc_free(server->sockets);
695 server->sockets = NULL;
698 silc_server_protocols_unregister();
700 SILC_LOG_DEBUG(("Server stopped"));
703 /* Function that is called when the network connection to a router has
704 been established. This will continue with the key exchange protocol
705 with the remote router. */
707 void silc_server_start_key_exchange(SilcServer server,
708 SilcServerConnection sconn,
711 SilcSocketConnection newsocket;
712 SilcProtocol protocol;
713 SilcServerKEInternalContext *proto_ctx;
714 SilcServerConfigRouter *conn =
715 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
718 /* Cancel any possible retry timeouts */
719 silc_schedule_task_del_by_callback(server->schedule,
720 silc_server_connect_to_router_retry);
722 /* Set socket options */
723 silc_net_set_socket_nonblock(sock);
724 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
726 /* Create socket connection for the connection. Even though we
727 know that we are connecting to a router we will mark the socket
728 to be unknown connection until we have executed authentication
730 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
731 server->sockets[sock] = newsocket;
732 newsocket->hostname = strdup(sconn->remote_host);
733 newsocket->ip = strdup(sconn->remote_host);
734 newsocket->port = sconn->remote_port;
735 sconn->sock = newsocket;
737 /* Allocate internal protocol context. This is sent as context
739 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
740 proto_ctx->server = (void *)server;
741 proto_ctx->context = (void *)sconn;
742 proto_ctx->sock = newsocket;
743 proto_ctx->rng = server->rng;
744 proto_ctx->responder = FALSE;
746 /* Set Key Exchange flags from configuration, but fall back to global
748 SILC_GET_SKE_FLAGS(conn, proto_ctx);
749 if (server->config->param.key_exchange_pfs)
750 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
752 /* Perform key exchange protocol. silc_server_connect_to_router_second
753 will be called after the protocol is finished. */
754 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
755 &protocol, proto_ctx,
756 silc_server_connect_to_router_second);
757 newsocket->protocol = protocol;
759 /* Register a timeout task that will be executed if the protocol
760 is not executed within set limit. */
761 proto_ctx->timeout_task =
762 silc_schedule_task_add(server->schedule, sock,
763 silc_server_timeout_remote,
764 server, server->config->key_exchange_timeout, 0,
768 /* Register the connection for network input and output. This sets
769 that scheduler will listen for incoming packets for this connection
770 and sets that outgoing packets may be sent to this connection as
771 well. However, this doesn't set the scheduler for outgoing traffic,
772 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
773 later when outgoing data is available. */
774 context = (void *)server;
775 SILC_REGISTER_CONNECTION_FOR_IO(sock);
777 /* Run the protocol */
778 silc_protocol_execute(protocol, server->schedule, 0, 0);
781 /* Timeout callback that will be called to retry connecting to remote
782 router. This is used by both normal and router server. This will wait
783 before retrying the connecting. The timeout is generated by exponential
784 backoff algorithm. */
786 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
788 SilcServerConnection sconn = (SilcServerConnection)context;
789 SilcServer server = sconn->server;
790 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
791 SilcServerConfigConnParams *param =
792 (conn->param ? conn->param : &server->config->param);
794 SILC_LOG_INFO(("Retrying connecting to a router"));
796 /* Calculate next timeout */
797 if (sconn->retry_count >= 1) {
798 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
799 if (sconn->retry_timeout > param->reconnect_interval_max)
800 sconn->retry_timeout = param->reconnect_interval_max;
802 sconn->retry_timeout = param->reconnect_interval;
804 sconn->retry_count++;
805 sconn->retry_timeout = sconn->retry_timeout +
806 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
808 /* If we've reached max retry count, give up. */
809 if ((sconn->retry_count > param->reconnect_count) &&
810 !param->reconnect_keep_trying) {
811 SILC_LOG_ERROR(("Could not connect to router, giving up"));
812 silc_server_config_unref(&sconn->conn);
813 silc_free(sconn->remote_host);
814 silc_free(sconn->backup_replace_ip);
819 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
820 sconn->retry_timeout));
822 /* We will lookup a fresh pointer later */
823 silc_server_config_unref(&sconn->conn);
825 /* Wait one before retrying */
826 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
827 context, sconn->retry_timeout, 0,
828 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
831 /* Generic routine to use connect to a router. */
833 SILC_TASK_CALLBACK(silc_server_connect_router)
835 SilcServerConnection sconn = (SilcServerConnection)context;
836 SilcServer server = sconn->server;
837 SilcServerConfigRouter *rconn;
840 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
841 (sconn->backup ? "backup router" : "router"),
842 sconn->remote_host, sconn->remote_port));
844 server->router_connect = time(NULL);
845 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
848 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
849 (sconn->backup ? "backup router" : "router"),
850 sconn->remote_host, sconn->remote_port));
851 silc_free(sconn->remote_host);
852 silc_free(sconn->backup_replace_ip);
856 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
858 /* Connect to remote host */
859 sock = silc_net_create_connection(
860 (!server->config->server_info->primary ? NULL :
861 server->config->server_info->primary->server_ip),
862 sconn->remote_port, sconn->remote_host);
864 SILC_LOG_ERROR(("Could not connect to router %s:%d",
865 sconn->remote_host, sconn->remote_port));
866 if (!sconn->no_reconnect)
867 silc_schedule_task_add(server->schedule, 0,
868 silc_server_connect_to_router_retry,
869 context, 0, 1, SILC_TASK_TIMEOUT,
870 SILC_TASK_PRI_NORMAL);
872 silc_server_config_unref(&sconn->conn);
876 /* Continue with key exchange protocol */
877 silc_server_start_key_exchange(server, sconn, sock);
880 /* This function connects to our primary router or if we are a router this
881 establishes all our primary routes. This is called at the start of the
882 server to do authentication and key exchange with our router - called
885 SILC_TASK_CALLBACK(silc_server_connect_to_router)
887 SilcServer server = (SilcServer)context;
888 SilcServerConnection sconn;
889 SilcServerConfigRouter *ptr;
891 SILC_LOG_DEBUG(("Connecting to router(s)"));
893 if (server->server_type == SILC_SERVER) {
894 SILC_LOG_DEBUG(("We are normal server"));
895 } else if (server->server_type == SILC_ROUTER) {
896 SILC_LOG_DEBUG(("We are router"));
898 SILC_LOG_DEBUG(("We are backup router/normal server"));
901 if (!server->config->routers) {
902 /* There wasn't a configured router, we will continue but we don't
903 have a connection to outside world. We will be standalone server. */
904 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
905 server->standalone = TRUE;
909 /* Cancel any possible retry timeouts */
910 silc_schedule_task_del_by_callback(server->schedule,
911 silc_server_connect_router);
912 silc_schedule_task_del_by_callback(server->schedule,
913 silc_server_connect_to_router_retry);
915 /* Create the connections to all our routes */
916 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
918 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
919 ptr->backup_router ? "Backup router" : "Router",
920 ptr->initiator ? "Initiator" : "Responder",
921 ptr->host, ptr->port));
923 if (ptr->initiator) {
924 /* Check whether we are connected to this host already */
925 if (silc_server_num_sockets_by_remote(server,
926 silc_net_is_ip(ptr->host) ?
928 silc_net_is_ip(ptr->host) ?
929 NULL : ptr->host, ptr->port,
930 SILC_SOCKET_TYPE_ROUTER)) {
931 SILC_LOG_DEBUG(("We are already connected to this router"));
935 /* Allocate connection object for hold connection specific stuff. */
936 sconn = silc_calloc(1, sizeof(*sconn));
937 sconn->server = server;
938 sconn->remote_host = strdup(ptr->host);
939 sconn->remote_port = ptr->port;
940 sconn->backup = ptr->backup_router;
942 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
943 sconn->backup_replace_port = ptr->backup_replace_port;
946 if (!server->router_conn && !sconn->backup)
947 server->router_conn = sconn;
949 silc_schedule_task_add(server->schedule, 0,
950 silc_server_connect_router,
951 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
952 SILC_TASK_PRI_NORMAL);
957 /* Second part of connecting to router(s). Key exchange protocol has been
958 executed and now we will execute authentication protocol. */
960 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
962 SilcProtocol protocol = (SilcProtocol)context;
963 SilcServerKEInternalContext *ctx =
964 (SilcServerKEInternalContext *)protocol->context;
965 SilcServer server = (SilcServer)ctx->server;
966 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
967 SilcSocketConnection sock = ctx->sock;
968 SilcServerConnAuthInternalContext *proto_ctx;
969 SilcServerConfigRouter *conn = NULL;
971 SILC_LOG_DEBUG(("Start"));
973 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
974 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
975 /* Error occured during protocol */
976 silc_protocol_free(protocol);
977 sock->protocol = NULL;
978 silc_ske_free_key_material(ctx->keymat);
980 silc_packet_context_free(ctx->packet);
982 silc_ske_free(ctx->ske);
983 silc_free(ctx->dest_id);
985 silc_schedule_task_del_by_callback(server->schedule,
986 silc_server_failure_callback);
987 silc_server_disconnect_remote(server, sock,
988 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
990 /* Try reconnecting if configuration wants it */
991 if (!sconn->no_reconnect) {
992 silc_schedule_task_add(server->schedule, 0,
993 silc_server_connect_to_router_retry,
994 sconn, 0, 1, SILC_TASK_TIMEOUT,
995 SILC_TASK_PRI_NORMAL);
998 silc_server_config_unref(&sconn->conn);
999 silc_free(sconn->remote_host);
1000 silc_free(sconn->backup_replace_ip);
1005 /* We now have the key material as the result of the key exchange
1006 protocol. Take the key material into use. Free the raw key material
1007 as soon as we've set them into use. */
1008 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1009 ctx->sock, ctx->keymat,
1010 ctx->ske->prop->cipher,
1011 ctx->ske->prop->pkcs,
1012 ctx->ske->prop->hash,
1013 ctx->ske->prop->hmac,
1014 ctx->ske->prop->group,
1016 silc_protocol_free(protocol);
1017 sock->protocol = NULL;
1018 silc_ske_free_key_material(ctx->keymat);
1020 silc_packet_context_free(ctx->packet);
1022 silc_ske_free(ctx->ske);
1023 silc_free(ctx->dest_id);
1025 silc_schedule_task_del_by_callback(server->schedule,
1026 silc_server_failure_callback);
1027 silc_server_disconnect_remote(server, sock,
1028 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1030 /* Try reconnecting if configuration wants it */
1031 if (!sconn->no_reconnect) {
1032 silc_schedule_task_add(server->schedule, 0,
1033 silc_server_connect_to_router_retry,
1034 sconn, 0, 1, SILC_TASK_TIMEOUT,
1035 SILC_TASK_PRI_NORMAL);
1038 silc_server_config_unref(&sconn->conn);
1039 silc_free(sconn->remote_host);
1040 silc_free(sconn->backup_replace_ip);
1044 silc_ske_free_key_material(ctx->keymat);
1046 /* Allocate internal context for the authentication protocol. This
1047 is sent as context for the protocol. */
1048 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1049 proto_ctx->server = (void *)server;
1050 proto_ctx->context = (void *)sconn;
1051 proto_ctx->sock = sock;
1052 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1053 proto_ctx->dest_id_type = ctx->dest_id_type;
1054 proto_ctx->dest_id = ctx->dest_id;
1056 /* Resolve the authentication method used in this connection. Check if
1057 we find a match from user configured connections */
1058 if (!sconn->conn.ref_ptr)
1059 conn = silc_server_config_find_router_conn(server, sock->hostname,
1062 conn = sconn->conn.ref_ptr;
1065 /* Match found. Use the configured authentication method. Take only
1066 the passphrase, since for public key auth we automatically use
1067 our local key pair. */
1068 if (conn->passphrase) {
1069 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1070 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1072 proto_ctx->auth_data = strdup(conn->passphrase);
1073 proto_ctx->auth_data_len = strlen(conn->passphrase);
1074 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1076 } else if (conn->publickeys) {
1077 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1079 proto_ctx->auth_meth = SILC_AUTH_NONE;
1082 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1083 sock->hostname, sock->ip, sock->port));
1084 silc_protocol_free(protocol);
1085 sock->protocol = NULL;
1087 silc_packet_context_free(ctx->packet);
1089 silc_ske_free(ctx->ske);
1090 silc_free(ctx->dest_id);
1092 silc_server_config_unref(&sconn->conn);
1093 silc_free(sconn->remote_host);
1094 silc_free(sconn->backup_replace_ip);
1096 silc_schedule_task_del_by_callback(server->schedule,
1097 silc_server_failure_callback);
1098 silc_server_disconnect_remote(server, sock,
1099 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1103 /* Free old protocol as it is finished now */
1104 silc_protocol_free(protocol);
1106 silc_packet_context_free(ctx->packet);
1108 sock->protocol = NULL;
1110 /* Allocate the authentication protocol. This is allocated here
1111 but we won't start it yet. We will be receiving party of this
1112 protocol thus we will wait that connecting party will make
1113 their first move. */
1114 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1115 &sock->protocol, proto_ctx,
1116 silc_server_connect_to_router_final);
1118 /* Register timeout task. If the protocol is not executed inside
1119 this timelimit the connection will be terminated. */
1120 proto_ctx->timeout_task =
1121 silc_schedule_task_add(server->schedule, sock->sock,
1122 silc_server_timeout_remote,
1124 server->config->conn_auth_timeout, 0,
1128 /* Run the protocol */
1129 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1132 /* Finalizes the connection to router. Registers a server task to the
1133 queue so that we can accept new connections. */
1135 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1137 SilcProtocol protocol = (SilcProtocol)context;
1138 SilcServerConnAuthInternalContext *ctx =
1139 (SilcServerConnAuthInternalContext *)protocol->context;
1140 SilcServer server = (SilcServer)ctx->server;
1141 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1142 SilcSocketConnection sock = ctx->sock;
1143 SilcServerEntry id_entry;
1145 SilcServerHBContext hb_context;
1146 unsigned char *id_string;
1148 SilcIDListData idata;
1149 SilcServerConfigRouter *conn = NULL;
1150 SilcServerConfigConnParams *param = NULL;
1152 SILC_LOG_DEBUG(("Start"));
1154 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1155 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1156 /* Error occured during protocol */
1157 silc_free(ctx->dest_id);
1158 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1161 /* Try reconnecting if configuration wants it */
1162 if (!sconn->no_reconnect) {
1163 silc_schedule_task_add(server->schedule, 0,
1164 silc_server_connect_to_router_retry,
1165 sconn, 0, 1, SILC_TASK_TIMEOUT,
1166 SILC_TASK_PRI_NORMAL);
1173 /* Add a task to the queue. This task receives new connections to the
1174 server. This task remains on the queue until the end of the program. */
1175 if (!server->listenning && !sconn->backup) {
1176 silc_schedule_task_add(server->schedule, server->sock,
1177 silc_server_accept_new_connection,
1178 (void *)server, 0, 0,
1180 SILC_TASK_PRI_NORMAL);
1181 server->listenning = TRUE;
1184 /* Send NEW_SERVER packet to the router. We will become registered
1185 to the SILC network after sending this packet. */
1186 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1187 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1188 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1189 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1190 silc_buffer_format(packet,
1191 SILC_STR_UI_SHORT(id_len),
1192 SILC_STR_UI_XNSTRING(id_string, id_len),
1193 SILC_STR_UI_SHORT(strlen(server->server_name)),
1194 SILC_STR_UI_XNSTRING(server->server_name,
1195 strlen(server->server_name)),
1198 /* Send the packet */
1199 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1200 packet->data, packet->len, TRUE);
1201 silc_buffer_free(packet);
1202 silc_free(id_string);
1204 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1206 /* Check that we do not have this ID already */
1207 id_entry = silc_idlist_find_server_by_id(server->local_list,
1208 ctx->dest_id, TRUE, NULL);
1210 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1212 id_entry = silc_idlist_find_server_by_id(server->global_list,
1213 ctx->dest_id, TRUE, NULL);
1215 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1218 SILC_LOG_DEBUG(("New server id(%s)",
1219 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1221 /* Add the connected router to global server list */
1222 id_entry = silc_idlist_add_server(server->global_list,
1223 strdup(sock->hostname),
1224 SILC_ROUTER, ctx->dest_id, NULL, sock);
1226 silc_free(ctx->dest_id);
1227 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1228 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1233 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1234 silc_free(sock->user_data);
1235 sock->user_data = (void *)id_entry;
1236 sock->type = SILC_SOCKET_TYPE_ROUTER;
1237 idata = (SilcIDListData)sock->user_data;
1238 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1240 conn = sconn->conn.ref_ptr;
1241 param = &server->config->param;
1242 if (conn && conn->param)
1243 param = conn->param;
1245 /* Perform keepalive. The `hb_context' will be freed automatically
1246 when finally calling the silc_socket_free function. */
1247 hb_context = silc_calloc(1, sizeof(*hb_context));
1248 hb_context->server = server;
1249 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1250 silc_server_perform_heartbeat,
1253 /* Register re-key timeout */
1254 idata->rekey->timeout = param->key_exchange_rekey;
1255 idata->rekey->context = (void *)server;
1256 silc_schedule_task_add(server->schedule, sock->sock,
1257 silc_server_rekey_callback,
1258 (void *)sock, idata->rekey->timeout, 0,
1259 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1261 if (!sconn->backup) {
1262 /* Mark this router our primary router if we're still standalone */
1263 if (server->standalone) {
1264 server->id_entry->router = id_entry;
1265 server->router = id_entry;
1266 server->standalone = FALSE;
1268 /* If we are router then announce our possible servers. */
1269 if (server->server_type == SILC_ROUTER)
1270 silc_server_announce_servers(server, FALSE, 0,
1271 SILC_PRIMARY_ROUTE(server));
1273 /* Announce our clients and channels to the router */
1274 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1275 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1277 /* If we are backup router then this primary router is whom we are
1279 if (server->server_type == SILC_BACKUP_ROUTER)
1280 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1283 /* Add this server to be our backup router */
1284 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1285 sconn->backup_replace_port, FALSE);
1288 sock->protocol = NULL;
1290 /* Call the completion callback to indicate that we've connected to
1292 if (sconn->callback)
1293 (*sconn->callback)(server, id_entry, sconn->callback_context);
1296 /* Free the temporary connection data context */
1298 silc_server_config_unref(&sconn->conn);
1299 silc_free(sconn->remote_host);
1300 silc_free(sconn->backup_replace_ip);
1303 if (sconn == server->router_conn)
1304 server->router_conn = NULL;
1307 /* Free the protocol object */
1308 if (sock->protocol == protocol)
1309 sock->protocol = NULL;
1310 silc_protocol_free(protocol);
1312 silc_packet_context_free(ctx->packet);
1314 silc_ske_free(ctx->ske);
1315 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1316 silc_free(ctx->auth_data);
1320 /* Host lookup callback that is called after the incoming connection's
1321 IP and FQDN lookup is performed. This will actually check the acceptance
1322 of the incoming connection and will register the key exchange protocol
1323 for this connection. */
1326 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1329 SilcServerKEInternalContext *proto_ctx =
1330 (SilcServerKEInternalContext *)context;
1331 SilcServer server = (SilcServer)proto_ctx->server;
1332 SilcServerConfigClient *cconfig = NULL;
1333 SilcServerConfigServer *sconfig = NULL;
1334 SilcServerConfigRouter *rconfig = NULL;
1335 SilcServerConfigDeny *deny;
1338 context = (void *)server;
1340 /* Check whether we could resolve both IP and FQDN. */
1341 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1342 server->config->require_reverse_lookup)) {
1343 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1344 sock->hostname ? sock->hostname :
1345 sock->ip ? sock->ip : ""));
1346 server->stat.conn_failures++;
1347 silc_server_disconnect_remote(server, sock,
1348 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1349 "Unknown host or IP");
1350 silc_free(proto_ctx);
1354 /* Register the connection for network input and output. This sets
1355 that scheduler will listen for incoming packets for this connection
1356 and sets that outgoing packets may be sent to this connection as well.
1357 However, this doesn't set the scheduler for outgoing traffic, it
1358 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1359 later when outgoing data is available. */
1360 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1362 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1365 /* Listenning port */
1366 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1367 silc_server_disconnect_remote(server, sock,
1368 SILC_STATUS_ERR_RESOURCE_LIMIT,
1369 "Connection refused");
1370 server->stat.conn_failures++;
1371 silc_free(proto_ctx);
1374 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1376 /* Check whether this connection is denied to connect to us. */
1377 deny = silc_server_config_find_denied(server, sock->ip);
1379 deny = silc_server_config_find_denied(server, sock->hostname);
1381 /* The connection is denied */
1382 SILC_LOG_INFO(("Connection %s (%s) is denied",
1383 sock->hostname, sock->ip));
1384 silc_server_disconnect_remote(server, sock,
1385 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1387 server->stat.conn_failures++;
1388 silc_free(proto_ctx);
1392 /* Check whether we have configured this sort of connection at all. We
1393 have to check all configurations since we don't know what type of
1394 connection this is. */
1395 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1396 cconfig = silc_server_config_find_client(server, sock->hostname);
1397 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1398 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1399 if (server->server_type == SILC_ROUTER) {
1400 if (!(rconfig = silc_server_config_find_router_conn(server,
1401 sock->ip, sock->port)))
1402 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1405 if (!cconfig && !sconfig && !rconfig) {
1406 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1408 silc_server_disconnect_remote(server, sock,
1409 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1410 server->stat.conn_failures++;
1411 silc_free(proto_ctx);
1415 /* The connection is allowed */
1417 /* Set internal context for key exchange protocol. This is
1418 sent as context for the protocol. */
1419 proto_ctx->sock = sock;
1420 proto_ctx->rng = server->rng;
1421 proto_ctx->responder = TRUE;
1422 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1423 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1424 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1426 /* Take flags for key exchange. Since we do not know what type of connection
1427 this is, we go through all found configurations and use the global ones
1428 as well. This will result always into strictest key exchange flags. */
1429 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1430 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1431 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1432 if (server->config->param.key_exchange_pfs)
1433 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1435 /* Prepare the connection for key exchange protocol. We allocate the
1436 protocol but will not start it yet. The connector will be the
1437 initiator of the protocol thus we will wait for initiation from
1438 there before we start the protocol. */
1439 server->stat.auth_attempts++;
1440 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1441 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1442 &sock->protocol, proto_ctx,
1443 silc_server_accept_new_connection_second);
1445 /* Register a timeout task that will be executed if the connector
1446 will not start the key exchange protocol within specified timeout
1447 and the connection will be closed. */
1448 proto_ctx->timeout_task =
1449 silc_schedule_task_add(server->schedule, sock->sock,
1450 silc_server_timeout_remote,
1452 server->config->key_exchange_timeout, 0,
1457 /* Accepts new connections to the server. Accepting new connections are
1458 done in three parts to make it async. */
1460 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1462 SilcServer server = (SilcServer)context;
1463 SilcSocketConnection newsocket;
1464 SilcServerKEInternalContext *proto_ctx;
1467 SILC_LOG_DEBUG(("Accepting new connection"));
1469 server->stat.conn_attempts++;
1471 sock = silc_net_accept_connection(fd);
1473 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1474 server->stat.conn_failures++;
1478 /* Check for maximum allowed connections */
1479 if (sock > server->config->param.connections_max) {
1480 SILC_LOG_ERROR(("Refusing connection, server is full"));
1481 server->stat.conn_failures++;
1482 silc_net_close_connection(sock);
1486 /* Set socket options */
1487 silc_net_set_socket_nonblock(sock);
1488 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1490 /* We don't create a ID yet, since we don't know what type of connection
1491 this is yet. But, we do add the connection to the socket table. */
1492 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1493 server->sockets[sock] = newsocket;
1495 /* Perform asynchronous host lookup. This will lookup the IP and the
1496 FQDN of the remote connection. After the lookup is done the connection
1497 is accepted further. */
1498 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1499 proto_ctx->server = server;
1500 proto_ctx->context = (void *)fd;
1501 silc_socket_host_lookup(newsocket, TRUE,
1502 silc_server_accept_new_connection_lookup,
1503 (void *)proto_ctx, server->schedule);
1506 /* Second part of accepting new connection. Key exchange protocol has been
1507 performed and now it is time to do little connection authentication
1508 protocol to figure out whether this connection is client or server
1509 and whether it has right to access this server (especially server
1510 connections needs to be authenticated). */
1512 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1514 SilcProtocol protocol = (SilcProtocol)context;
1515 SilcServerKEInternalContext *ctx =
1516 (SilcServerKEInternalContext *)protocol->context;
1517 SilcServer server = (SilcServer)ctx->server;
1518 SilcSocketConnection sock = ctx->sock;
1519 SilcServerConnAuthInternalContext *proto_ctx;
1521 SILC_LOG_DEBUG(("Start"));
1523 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1524 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1525 /* Error occured during protocol */
1526 SILC_LOG_DEBUG(("Error key exchange protocol"));
1527 silc_protocol_free(protocol);
1528 sock->protocol = NULL;
1529 silc_ske_free_key_material(ctx->keymat);
1531 silc_packet_context_free(ctx->packet);
1533 silc_ske_free(ctx->ske);
1534 silc_free(ctx->dest_id);
1535 silc_server_config_unref(&ctx->cconfig);
1536 silc_server_config_unref(&ctx->sconfig);
1537 silc_server_config_unref(&ctx->rconfig);
1539 silc_schedule_task_del_by_callback(server->schedule,
1540 silc_server_failure_callback);
1541 silc_server_disconnect_remote(server, sock,
1542 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1544 server->stat.auth_failures++;
1548 /* We now have the key material as the result of the key exchange
1549 protocol. Take the key material into use. Free the raw key material
1550 as soon as we've set them into use. */
1551 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1552 ctx->sock, ctx->keymat,
1553 ctx->ske->prop->cipher,
1554 ctx->ske->prop->pkcs,
1555 ctx->ske->prop->hash,
1556 ctx->ske->prop->hmac,
1557 ctx->ske->prop->group,
1559 SILC_LOG_ERROR(("Error setting key material in use"));
1560 silc_protocol_free(protocol);
1561 sock->protocol = NULL;
1562 silc_ske_free_key_material(ctx->keymat);
1564 silc_packet_context_free(ctx->packet);
1566 silc_ske_free(ctx->ske);
1567 silc_free(ctx->dest_id);
1568 silc_server_config_unref(&ctx->cconfig);
1569 silc_server_config_unref(&ctx->sconfig);
1570 silc_server_config_unref(&ctx->rconfig);
1572 silc_schedule_task_del_by_callback(server->schedule,
1573 silc_server_failure_callback);
1574 silc_server_disconnect_remote(server, sock,
1575 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1576 server->stat.auth_failures++;
1579 silc_ske_free_key_material(ctx->keymat);
1581 /* Allocate internal context for the authentication protocol. This
1582 is sent as context for the protocol. */
1583 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1584 proto_ctx->server = (void *)server;
1585 proto_ctx->sock = sock;
1586 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1587 proto_ctx->responder = TRUE;
1588 proto_ctx->dest_id_type = ctx->dest_id_type;
1589 proto_ctx->dest_id = ctx->dest_id;
1590 proto_ctx->cconfig = ctx->cconfig;
1591 proto_ctx->sconfig = ctx->sconfig;
1592 proto_ctx->rconfig = ctx->rconfig;
1594 /* Free old protocol as it is finished now */
1595 silc_protocol_free(protocol);
1597 silc_packet_context_free(ctx->packet);
1599 sock->protocol = NULL;
1601 /* Allocate the authentication protocol. This is allocated here
1602 but we won't start it yet. We will be receiving party of this
1603 protocol thus we will wait that connecting party will make
1604 their first move. */
1605 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1606 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1607 &sock->protocol, proto_ctx,
1608 silc_server_accept_new_connection_final);
1610 /* Register timeout task. If the protocol is not executed inside
1611 this timelimit the connection will be terminated. */
1612 proto_ctx->timeout_task =
1613 silc_schedule_task_add(server->schedule, sock->sock,
1614 silc_server_timeout_remote,
1616 server->config->conn_auth_timeout, 0,
1621 /* Final part of accepting new connection. The connection has now
1622 been authenticated and keys has been exchanged. We also know whether
1623 this is client or server connection. */
1625 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1627 SilcProtocol protocol = (SilcProtocol)context;
1628 SilcServerConnAuthInternalContext *ctx =
1629 (SilcServerConnAuthInternalContext *)protocol->context;
1630 SilcServer server = (SilcServer)ctx->server;
1631 SilcSocketConnection sock = ctx->sock;
1632 SilcServerHBContext hb_context;
1633 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1635 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1637 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1638 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1639 /* Error occured during protocol */
1640 SILC_LOG_DEBUG(("Error during authentication protocol"));
1641 silc_protocol_free(protocol);
1642 sock->protocol = NULL;
1644 silc_packet_context_free(ctx->packet);
1646 silc_ske_free(ctx->ske);
1647 silc_free(ctx->dest_id);
1648 silc_server_config_unref(&ctx->cconfig);
1649 silc_server_config_unref(&ctx->sconfig);
1650 silc_server_config_unref(&ctx->rconfig);
1652 silc_schedule_task_del_by_callback(server->schedule,
1653 silc_server_failure_callback);
1654 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1656 server->stat.auth_failures++;
1660 entry->data.last_receive = time(NULL);
1662 switch (ctx->conn_type) {
1663 case SILC_SOCKET_TYPE_CLIENT:
1665 SilcClientEntry client;
1666 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1668 /* Verify whether this connection is after all allowed to connect */
1669 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1670 &server->config->param,
1671 conn->param, ctx->ske)) {
1672 server->stat.auth_failures++;
1676 SILC_LOG_DEBUG(("Remote host is client"));
1677 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1680 /* Add the client to the client ID cache. The nickname and Client ID
1681 and other information is created after we have received NEW_CLIENT
1682 packet from client. */
1683 client = silc_idlist_add_client(server->local_list,
1684 NULL, NULL, NULL, NULL, NULL, sock, 0);
1686 SILC_LOG_ERROR(("Could not add new client to cache"));
1687 silc_free(sock->user_data);
1688 silc_server_disconnect_remote(server, sock,
1689 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1690 server->stat.auth_failures++;
1693 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1696 server->stat.my_clients++;
1697 server->stat.clients++;
1698 server->stat.cell_clients++;
1700 /* Get connection parameters */
1702 if (conn->param->keepalive_secs)
1703 hearbeat_timeout = conn->param->keepalive_secs;
1706 id_entry = (void *)client;
1709 case SILC_SOCKET_TYPE_SERVER:
1710 case SILC_SOCKET_TYPE_ROUTER:
1712 SilcServerEntry new_server;
1713 bool initiator = FALSE;
1714 bool backup_local = FALSE;
1715 bool backup_router = FALSE;
1716 char *backup_replace_ip = NULL;
1717 SilcUInt16 backup_replace_port = 0;
1718 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1719 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1721 /* If we are backup router and this is incoming server connection
1722 and we do not have connection to primary router, do not allow
1724 if (server->server_type == SILC_BACKUP_ROUTER &&
1725 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1726 !SILC_PRIMARY_ROUTE(server)) {
1727 SILC_LOG_INFO(("Will not accept server connection because we do "
1728 "not have primary router connection established"));
1729 silc_server_disconnect_remote(server, sock,
1730 SILC_STATUS_ERR_PERM_DENIED,
1731 "We do not have connection to primary "
1732 "router established, try later");
1733 silc_free(sock->user_data);
1734 server->stat.auth_failures++;
1738 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1739 /* Verify whether this connection is after all allowed to connect */
1740 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1741 &server->config->param,
1742 rconn ? rconn->param : NULL,
1744 silc_free(sock->user_data);
1745 server->stat.auth_failures++;
1751 if (rconn->param->keepalive_secs)
1752 hearbeat_timeout = rconn->param->keepalive_secs;
1755 initiator = rconn->initiator;
1756 backup_local = rconn->backup_local;
1757 backup_router = rconn->backup_router;
1758 backup_replace_ip = rconn->backup_replace_ip;
1759 backup_replace_port = rconn->backup_replace_port;
1763 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1764 /* Verify whether this connection is after all allowed to connect */
1765 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1766 &server->config->param,
1767 sconn ? sconn->param : NULL,
1769 silc_free(sock->user_data);
1770 server->stat.auth_failures++;
1775 if (sconn->param->keepalive_secs)
1776 hearbeat_timeout = sconn->param->keepalive_secs;
1779 backup_router = sconn->backup_router;
1783 SILC_LOG_DEBUG(("Remote host is %s",
1784 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1785 "server" : (backup_router ?
1786 "backup router" : "router")));
1787 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1788 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1789 "server" : (backup_router ?
1790 "backup router" : "router")));
1792 /* Add the server into server cache. The server name and Server ID
1793 is updated after we have received NEW_SERVER packet from the
1794 server. We mark ourselves as router for this server if we really
1797 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1798 server->local_list : (backup_router ?
1799 server->local_list :
1800 server->global_list)),
1802 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1803 SILC_SERVER : SILC_ROUTER),
1805 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1806 server->id_entry : (backup_router ?
1807 server->id_entry : NULL)),
1810 SILC_LOG_ERROR(("Could not add new server to cache"));
1811 silc_free(sock->user_data);
1812 silc_server_disconnect_remote(server, sock,
1813 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1814 server->stat.auth_failures++;
1817 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1819 id_entry = (void *)new_server;
1821 /* If the incoming connection is router and marked as backup router
1822 then add it to be one of our backups */
1823 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1824 silc_server_backup_add(server, new_server, backup_replace_ip,
1825 backup_replace_port, backup_local);
1827 /* Change it back to SERVER type since that's what it really is. */
1829 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1831 new_server->server_type = SILC_BACKUP_ROUTER;
1835 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1836 server->stat.my_servers++;
1838 server->stat.my_routers++;
1839 server->stat.routers++;
1841 server->stat.servers++;
1843 /* Check whether this connection is to be our primary router connection
1844 if we do not already have the primary route. */
1845 if (!backup_router &&
1846 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1847 if (silc_server_config_is_primary_route(server) && !initiator)
1850 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1851 server->standalone = FALSE;
1852 if (!server->id_entry->router) {
1853 server->id_entry->router = id_entry;
1854 server->router = id_entry;
1865 sock->type = ctx->conn_type;
1867 /* Add the common data structure to the ID entry. */
1868 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1870 /* Add to sockets internal pointer for fast referencing */
1871 silc_free(sock->user_data);
1872 sock->user_data = id_entry;
1874 /* Connection has been fully established now. Everything is ok. */
1875 SILC_LOG_DEBUG(("New connection authenticated"));
1877 /* Perform keepalive. The `hb_context' will be freed automatically
1878 when finally calling the silc_socket_free function. */
1879 hb_context = silc_calloc(1, sizeof(*hb_context));
1880 hb_context->server = server;
1881 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1882 silc_server_perform_heartbeat,
1886 silc_schedule_task_del_by_callback(server->schedule,
1887 silc_server_failure_callback);
1888 silc_protocol_free(protocol);
1890 silc_packet_context_free(ctx->packet);
1892 silc_ske_free(ctx->ske);
1893 silc_free(ctx->dest_id);
1894 silc_server_config_unref(&ctx->cconfig);
1895 silc_server_config_unref(&ctx->sconfig);
1896 silc_server_config_unref(&ctx->rconfig);
1898 sock->protocol = NULL;
1901 /* This function is used to read packets from network and send packets to
1902 network. This is usually a generic task. */
1904 SILC_TASK_CALLBACK(silc_server_packet_process)
1906 SilcServer server = (SilcServer)context;
1907 SilcSocketConnection sock = server->sockets[fd];
1908 SilcIDListData idata;
1909 SilcCipher cipher = NULL;
1910 SilcHmac hmac = NULL;
1911 SilcUInt32 sequence = 0;
1915 SILC_LOG_DEBUG(("Unknown socket connection"));
1919 /* Packet sending */
1921 if (type == SILC_TASK_WRITE) {
1922 /* Do not send data to disconnected connection */
1923 if (SILC_IS_DISCONNECTED(sock)) {
1924 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
1928 server->stat.packets_sent++;
1930 /* Send the packet */
1931 ret = silc_packet_send(sock, TRUE);
1933 /* If returned -2 could not write to connection now, will do
1939 SILC_LOG_ERROR(("Error sending packet to connection "
1940 "%s:%d [%s]", sock->hostname, sock->port,
1941 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1942 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1943 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1948 /* The packet has been sent and now it is time to set the connection
1949 back to only for input. When there is again some outgoing data
1950 available for this connection it will be set for output as well.
1951 This call clears the output setting and sets it only for input. */
1952 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1953 SILC_UNSET_OUTBUF_PENDING(sock);
1955 silc_buffer_clear(sock->outbuf);
1959 /* Packet receiving */
1961 /* Read some data from connection */
1962 ret = silc_packet_receive(sock);
1966 SILC_LOG_ERROR(("Error receiving packet from connection "
1967 "%s:%d [%s] %s", sock->hostname, sock->port,
1968 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1969 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1970 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1971 "Router"), strerror(errno)));
1977 SILC_LOG_DEBUG(("Read EOF"));
1979 /* If connection is disconnecting already we will finally
1980 close the connection */
1981 if (SILC_IS_DISCONNECTING(sock)) {
1982 if (sock->user_data)
1983 silc_server_free_sock_user_data(server, sock, NULL);
1984 silc_server_close_connection(server, sock);
1988 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1989 SILC_SET_DISCONNECTING(sock);
1991 if (sock->user_data) {
1993 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1994 silc_server_free_sock_user_data(server, sock, tmp);
1996 silc_server_free_sock_user_data(server, sock, NULL);
1997 } else if (server->router_conn && server->router_conn->sock == sock &&
1998 !server->router && server->standalone)
1999 silc_schedule_task_add(server->schedule, 0,
2000 silc_server_connect_to_router,
2003 SILC_TASK_PRI_NORMAL);
2005 silc_server_close_connection(server, sock);
2009 /* If connection is disconnecting or disconnected we will ignore
2011 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2012 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2016 /* Get keys and stuff from ID entry */
2017 idata = (SilcIDListData)sock->user_data;
2019 cipher = idata->receive_key;
2020 hmac = idata->hmac_receive;
2021 sequence = idata->psn_receive;
2024 /* Process the packet. This will call the parser that will then
2025 decrypt and parse the packet. */
2026 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2027 TRUE : FALSE, cipher, hmac, sequence,
2028 silc_server_packet_parse, server);
2030 /* If this socket connection is not authenticated yet and the packet
2031 processing failed we will drop the connection since it can be
2032 a malicious flooder. */
2033 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
2034 (!sock->protocol || sock->protocol->protocol->type ==
2035 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
2036 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
2037 SILC_SET_DISCONNECTING(sock);
2039 if (sock->user_data)
2040 silc_server_free_sock_user_data(server, sock, NULL);
2041 silc_server_close_connection(server, sock);
2045 /* Parses whole packet, received earlier. */
2047 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2049 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2050 SilcServer server = (SilcServer)parse_ctx->context;
2051 SilcSocketConnection sock = parse_ctx->sock;
2052 SilcPacketContext *packet = parse_ctx->packet;
2053 SilcIDListData idata = (SilcIDListData)sock->user_data;
2056 server->stat.packets_received++;
2058 /* Parse the packet */
2059 if (parse_ctx->normal)
2060 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2062 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2064 /* If entry is disabled ignore what we got. */
2065 if (ret != SILC_PACKET_RESUME_ROUTER &&
2066 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2067 SILC_LOG_DEBUG(("Connection is disabled"));
2071 if (ret == SILC_PACKET_NONE) {
2072 SILC_LOG_DEBUG(("Error parsing packet"));
2076 /* Check that the the current client ID is same as in the client's packet. */
2077 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2078 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2079 if (client && client->id) {
2080 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2081 packet->src_id_type);
2082 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2084 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2091 if (server->server_type == SILC_ROUTER) {
2092 /* Route the packet if it is not destined to us. Other ID types but
2093 server are handled separately after processing them. */
2094 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2095 packet->dst_id_type == SILC_ID_SERVER &&
2096 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2097 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2099 /* Route the packet to fastest route for the destination ID */
2100 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2101 packet->dst_id_type);
2104 silc_server_packet_route(server,
2105 silc_server_route_get(server, id,
2106 packet->dst_id_type),
2113 /* Parse the incoming packet type */
2114 silc_server_packet_parse_type(server, sock, packet);
2116 /* Broadcast packet if it is marked as broadcast packet and it is
2117 originated from router and we are router. */
2118 if (server->server_type == SILC_ROUTER &&
2119 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2120 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2121 /* Broadcast to our primary route */
2122 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2124 /* If we have backup routers then we need to feed all broadcast
2125 data to those servers. */
2126 silc_server_backup_broadcast(server, sock, packet);
2130 silc_packet_context_free(packet);
2131 silc_free(parse_ctx);
2134 /* Parser callback called by silc_packet_receive_process. This merely
2135 registers timeout that will handle the actual parsing when appropriate. */
2137 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2140 SilcServer server = (SilcServer)context;
2141 SilcSocketConnection sock = parser_context->sock;
2142 SilcIDListData idata = (SilcIDListData)sock->user_data;
2145 idata->psn_receive = parser_context->packet->sequence + 1;
2147 /* If protocol for this connection is key exchange or rekey then we'll
2148 process all packets synchronously, since there might be packets in
2149 queue that we are not able to decrypt without first processing the
2150 packets before them. */
2151 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2152 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2153 (sock->protocol && sock->protocol->protocol &&
2154 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2155 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2156 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2159 /* Reprocess data since we'll return FALSE here. This is because
2160 the idata->receive_key might have become valid in the last packet
2161 and we want to call this processor with valid cipher. */
2163 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2164 TRUE : FALSE, idata->receive_key,
2165 idata->hmac_receive, idata->psn_receive,
2166 silc_server_packet_parse, server);
2168 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2169 TRUE : FALSE, NULL, NULL, 0,
2170 silc_server_packet_parse, server);
2174 switch (sock->type) {
2175 case SILC_SOCKET_TYPE_UNKNOWN:
2176 case SILC_SOCKET_TYPE_CLIENT:
2177 /* Parse the packet with timeout */
2178 silc_schedule_task_add(server->schedule, sock->sock,
2179 silc_server_packet_parse_real,
2180 (void *)parser_context, 0, 100000,
2182 SILC_TASK_PRI_NORMAL);
2184 case SILC_SOCKET_TYPE_SERVER:
2185 case SILC_SOCKET_TYPE_ROUTER:
2186 /* Packets from servers are parsed immediately */
2187 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2197 /* Parses the packet type and calls what ever routines the packet type
2198 requires. This is done for all incoming packets. */
2200 void silc_server_packet_parse_type(SilcServer server,
2201 SilcSocketConnection sock,
2202 SilcPacketContext *packet)
2204 SilcPacketType type = packet->type;
2205 SilcIDListData idata = (SilcIDListData)sock->user_data;
2207 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2208 silc_get_packet_name(type), packet->flags));
2210 /* Parse the packet type */
2212 case SILC_PACKET_DISCONNECT:
2215 char *message = NULL;
2217 if (packet->flags & SILC_PACKET_FLAG_LIST)
2219 if (packet->buffer->len < 1)
2222 status = (SilcStatus)packet->buffer->data[0];
2223 if (packet->buffer->len > 1 &&
2224 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2225 message = silc_memdup(packet->buffer->data + 1,
2226 packet->buffer->len - 1);
2228 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2229 sock->ip, sock->hostname,
2230 silc_get_status_message(status), status,
2231 message ? message : ""));
2236 case SILC_PACKET_SUCCESS:
2238 * Success received for something. For now we can have only
2239 * one protocol for connection executing at once hence this
2240 * success message is for whatever protocol is executing currently.
2242 if (packet->flags & SILC_PACKET_FLAG_LIST)
2245 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2248 case SILC_PACKET_FAILURE:
2250 * Failure received for something. For now we can have only
2251 * one protocol for connection executing at once hence this
2252 * failure message is for whatever protocol is executing currently.
2254 if (packet->flags & SILC_PACKET_FLAG_LIST)
2256 if (sock->protocol) {
2257 SilcServerFailureContext f;
2258 f = silc_calloc(1, sizeof(*f));
2262 /* We will wait 5 seconds to process this failure packet */
2263 silc_schedule_task_add(server->schedule, sock->sock,
2264 silc_server_failure_callback, (void *)f, 5, 0,
2265 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2269 case SILC_PACKET_REJECT:
2270 if (packet->flags & SILC_PACKET_FLAG_LIST)
2275 case SILC_PACKET_NOTIFY:
2277 * Received notify packet. Server can receive notify packets from
2278 * router. Server then relays the notify messages to clients if needed.
2280 if (packet->flags & SILC_PACKET_FLAG_LIST)
2281 silc_server_notify_list(server, sock, packet);
2283 silc_server_notify(server, sock, packet);
2289 case SILC_PACKET_CHANNEL_MESSAGE:
2291 * Received channel message. Channel messages are special packets
2292 * (although probably most common ones) thus they are handled
2295 if (packet->flags & SILC_PACKET_FLAG_LIST)
2297 idata->last_receive = time(NULL);
2298 silc_server_channel_message(server, sock, packet);
2301 case SILC_PACKET_CHANNEL_KEY:
2303 * Received key for channel. As channels are created by the router
2304 * the keys are as well. We will distribute the key to all of our
2305 * locally connected clients on the particular channel. Router
2306 * never receives this channel and thus is ignored.
2308 if (packet->flags & SILC_PACKET_FLAG_LIST)
2310 silc_server_channel_key(server, sock, packet);
2316 case SILC_PACKET_COMMAND:
2318 * Recived command. Processes the command request and allocates the
2319 * command context and calls the command.
2321 if (packet->flags & SILC_PACKET_FLAG_LIST)
2323 silc_server_command_process(server, sock, packet);
2326 case SILC_PACKET_COMMAND_REPLY:
2328 * Received command reply packet. Received command reply to command. It
2329 * may be reply to command sent by us or reply to command sent by client
2330 * that we've routed further.
2332 if (packet->flags & SILC_PACKET_FLAG_LIST)
2334 silc_server_command_reply(server, sock, packet);
2338 * Private Message packets
2340 case SILC_PACKET_PRIVATE_MESSAGE:
2342 * Received private message packet. The packet is coming from either
2345 if (packet->flags & SILC_PACKET_FLAG_LIST)
2347 idata->last_receive = time(NULL);
2348 silc_server_private_message(server, sock, packet);
2351 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2353 * Private message key packet.
2355 if (packet->flags & SILC_PACKET_FLAG_LIST)
2357 silc_server_private_message_key(server, sock, packet);
2361 * Key Exchange protocol packets
2363 case SILC_PACKET_KEY_EXCHANGE:
2364 if (packet->flags & SILC_PACKET_FLAG_LIST)
2367 if (sock->protocol && sock->protocol->protocol &&
2368 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2369 SilcServerKEInternalContext *proto_ctx =
2370 (SilcServerKEInternalContext *)sock->protocol->context;
2372 proto_ctx->packet = silc_packet_context_dup(packet);
2374 /* Let the protocol handle the packet */
2375 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2377 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2378 "protocol active, packet dropped."));
2382 case SILC_PACKET_KEY_EXCHANGE_1:
2383 if (packet->flags & SILC_PACKET_FLAG_LIST)
2386 if (sock->protocol && sock->protocol->protocol &&
2387 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2388 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2390 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2391 SilcServerRekeyInternalContext *proto_ctx =
2392 (SilcServerRekeyInternalContext *)sock->protocol->context;
2394 if (proto_ctx->packet)
2395 silc_packet_context_free(proto_ctx->packet);
2397 proto_ctx->packet = silc_packet_context_dup(packet);
2399 /* Let the protocol handle the packet */
2400 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2402 SilcServerKEInternalContext *proto_ctx =
2403 (SilcServerKEInternalContext *)sock->protocol->context;
2405 if (proto_ctx->packet)
2406 silc_packet_context_free(proto_ctx->packet);
2408 proto_ctx->packet = silc_packet_context_dup(packet);
2409 proto_ctx->dest_id_type = packet->src_id_type;
2410 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2411 packet->src_id_type);
2412 if (!proto_ctx->dest_id)
2415 /* Let the protocol handle the packet */
2416 silc_protocol_execute(sock->protocol, server->schedule,
2420 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2421 "protocol active, packet dropped."));
2425 case SILC_PACKET_KEY_EXCHANGE_2:
2426 if (packet->flags & SILC_PACKET_FLAG_LIST)
2429 if (sock->protocol && sock->protocol->protocol &&
2430 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2431 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2433 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2434 SilcServerRekeyInternalContext *proto_ctx =
2435 (SilcServerRekeyInternalContext *)sock->protocol->context;
2437 if (proto_ctx->packet)
2438 silc_packet_context_free(proto_ctx->packet);
2440 proto_ctx->packet = silc_packet_context_dup(packet);
2442 /* Let the protocol handle the packet */
2443 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2445 SilcServerKEInternalContext *proto_ctx =
2446 (SilcServerKEInternalContext *)sock->protocol->context;
2448 if (proto_ctx->packet)
2449 silc_packet_context_free(proto_ctx->packet);
2451 proto_ctx->packet = silc_packet_context_dup(packet);
2452 proto_ctx->dest_id_type = packet->src_id_type;
2453 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2454 packet->src_id_type);
2455 if (!proto_ctx->dest_id)
2458 /* Let the protocol handle the packet */
2459 silc_protocol_execute(sock->protocol, server->schedule,
2463 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2464 "protocol active, packet dropped."));
2468 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2470 * Connection authentication request packet. When we receive this packet
2471 * we will send to the other end information about our mandatory
2472 * authentication method for the connection. This packet maybe received
2475 if (packet->flags & SILC_PACKET_FLAG_LIST)
2477 silc_server_connection_auth_request(server, sock, packet);
2481 * Connection Authentication protocol packets
2483 case SILC_PACKET_CONNECTION_AUTH:
2484 /* Start of the authentication protocol. We receive here the
2485 authentication data and will verify it. */
2486 if (packet->flags & SILC_PACKET_FLAG_LIST)
2489 if (sock->protocol && sock->protocol->protocol->type
2490 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2492 SilcServerConnAuthInternalContext *proto_ctx =
2493 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2495 proto_ctx->packet = silc_packet_context_dup(packet);
2497 /* Let the protocol handle the packet */
2498 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2500 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2501 "protocol active, packet dropped."));
2505 case SILC_PACKET_NEW_ID:
2507 * Received New ID packet. This includes some new ID that has been
2508 * created. It may be for client, server or channel. This is the way
2509 * to distribute information about new registered entities in the
2512 if (packet->flags & SILC_PACKET_FLAG_LIST)
2513 silc_server_new_id_list(server, sock, packet);
2515 silc_server_new_id(server, sock, packet);
2518 case SILC_PACKET_NEW_CLIENT:
2520 * Received new client packet. This includes client information that
2521 * we will use to create initial client ID. After creating new
2522 * ID we will send it to the client.
2524 if (packet->flags & SILC_PACKET_FLAG_LIST)
2526 silc_server_new_client(server, sock, packet);
2529 case SILC_PACKET_NEW_SERVER:
2531 * Received new server packet. This includes Server ID and some other
2532 * information that we may save. This is received after server has
2535 if (packet->flags & SILC_PACKET_FLAG_LIST)
2537 silc_server_new_server(server, sock, packet);
2540 case SILC_PACKET_NEW_CHANNEL:
2542 * Received new channel packet. Information about new channel in the
2543 * network are distributed using this packet.
2545 if (packet->flags & SILC_PACKET_FLAG_LIST)
2546 silc_server_new_channel_list(server, sock, packet);
2548 silc_server_new_channel(server, sock, packet);
2551 case SILC_PACKET_HEARTBEAT:
2553 * Received heartbeat.
2555 if (packet->flags & SILC_PACKET_FLAG_LIST)
2559 case SILC_PACKET_KEY_AGREEMENT:
2561 * Received heartbeat.
2563 if (packet->flags & SILC_PACKET_FLAG_LIST)
2565 silc_server_key_agreement(server, sock, packet);
2568 case SILC_PACKET_REKEY:
2570 * Received re-key packet. The sender wants to regenerate the session
2573 if (packet->flags & SILC_PACKET_FLAG_LIST)
2575 silc_server_rekey(server, sock, packet);
2578 case SILC_PACKET_REKEY_DONE:
2580 * The re-key is done.
2582 if (packet->flags & SILC_PACKET_FLAG_LIST)
2585 if (sock->protocol && sock->protocol->protocol &&
2586 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2588 SilcServerRekeyInternalContext *proto_ctx =
2589 (SilcServerRekeyInternalContext *)sock->protocol->context;
2591 if (proto_ctx->packet)
2592 silc_packet_context_free(proto_ctx->packet);
2594 proto_ctx->packet = silc_packet_context_dup(packet);
2596 /* Let the protocol handle the packet */
2597 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2599 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2600 "protocol active, packet dropped."));
2604 case SILC_PACKET_FTP:
2606 if (packet->flags & SILC_PACKET_FLAG_LIST)
2608 silc_server_ftp(server, sock, packet);
2611 case SILC_PACKET_RESUME_CLIENT:
2613 if (packet->flags & SILC_PACKET_FLAG_LIST)
2615 silc_server_resume_client(server, sock, packet);
2618 case SILC_PACKET_RESUME_ROUTER:
2619 /* Resume router packet received. This packet is received for backup
2620 router resuming protocol. */
2621 if (packet->flags & SILC_PACKET_FLAG_LIST)
2623 silc_server_backup_resume_router(server, sock, packet);
2627 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2632 /* Creates connection to a remote router. */
2634 void silc_server_create_connection(SilcServer server,
2635 const char *remote_host, SilcUInt32 port)
2637 SilcServerConnection sconn;
2639 /* Allocate connection object for hold connection specific stuff. */
2640 sconn = silc_calloc(1, sizeof(*sconn));
2641 sconn->server = server;
2642 sconn->remote_host = strdup(remote_host);
2643 sconn->remote_port = port;
2644 sconn->no_reconnect = TRUE;
2646 silc_schedule_task_add(server->schedule, 0,
2647 silc_server_connect_router,
2648 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2649 SILC_TASK_PRI_NORMAL);
2652 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2654 silc_socket_free(context);
2657 /* Closes connection to socket connection */
2659 void silc_server_close_connection(SilcServer server,
2660 SilcSocketConnection sock)
2662 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2663 silc_socket_free(sock);
2667 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2669 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2670 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2671 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2674 /* We won't listen for this connection anymore */
2675 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2677 /* Unregister all tasks */
2678 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2680 /* Close the actual connection */
2681 silc_net_close_connection(sock->sock);
2682 server->sockets[sock->sock] = NULL;
2684 /* If sock->user_data is NULL then we'll check for active protocols
2685 here since the silc_server_free_sock_user_data has not been called
2686 for this connection. */
2687 if (!sock->user_data) {
2688 /* If any protocol is active cancel its execution. It will call
2689 the final callback which will finalize the disconnection. */
2690 if (sock->protocol) {
2691 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2692 silc_protocol_cancel(sock->protocol, server->schedule);
2693 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2694 silc_protocol_execute_final(sock->protocol, server->schedule);
2695 sock->protocol = NULL;
2700 silc_schedule_task_add(server->schedule, 0,
2701 silc_server_close_connection_final,
2702 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2703 SILC_TASK_PRI_NORMAL);
2706 /* Sends disconnect message to remote connection and disconnects the
2709 void silc_server_disconnect_remote(SilcServer server,
2710 SilcSocketConnection sock,
2711 SilcStatus status, ...)
2714 unsigned char buf[512];
2722 memset(buf, 0, sizeof(buf));
2723 va_start(ap, status);
2724 cp = va_arg(ap, char *);
2726 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2731 SILC_LOG_DEBUG(("Disconnecting remote host"));
2733 /* Notify remote end that the conversation is over. The notify message
2734 is tried to be sent immediately. */
2738 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2740 buffer = silc_buffer_alloc_size(len);
2744 buffer->data[0] = status;
2746 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2748 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2749 buffer->data, buffer->len, TRUE);
2750 silc_buffer_free(buffer);
2753 silc_server_packet_queue_purge(server, sock);
2755 /* Mark the connection to be disconnected */
2756 SILC_SET_DISCONNECTED(sock);
2757 silc_server_close_connection(server, sock);
2762 SilcClientEntry client;
2763 } *FreeClientInternal;
2765 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2767 FreeClientInternal i = (FreeClientInternal)context;
2769 silc_idlist_del_data(i->client);
2770 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2774 /* Frees client data and notifies about client's signoff. */
2776 void silc_server_free_client_data(SilcServer server,
2777 SilcSocketConnection sock,
2778 SilcClientEntry client,
2780 const char *signoff)
2782 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2784 SILC_LOG_DEBUG(("Freeing client data"));
2787 if (!client->router && !client->connection &&
2788 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2789 SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2790 SILC_LOG_ERROR(("****** Contact Pekka"));
2791 SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2796 /* If there is pending outgoing data for the client then purge it
2797 to the network before removing the client entry. */
2798 silc_server_packet_queue_purge(server, sock);
2801 /* Check if anyone is watching this nickname */
2802 if (server->server_type == SILC_ROUTER)
2803 silc_server_check_watcher_list(server, client, NULL,
2804 SILC_NOTIFY_TYPE_SIGNOFF);
2806 /* Send SIGNOFF notify to routers. */
2808 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2809 SILC_BROADCAST(server), client->id,
2813 /* Remove client from all channels */
2815 silc_server_remove_from_channels(server, NULL, client,
2816 TRUE, (char *)signoff, TRUE);
2818 silc_server_remove_from_channels(server, NULL, client,
2819 FALSE, NULL, FALSE);
2821 /* Remove this client from watcher list if it is */
2822 silc_server_del_from_watcher_list(server, client);
2824 /* Update statistics */
2825 server->stat.my_clients--;
2826 server->stat.clients--;
2827 if (server->stat.cell_clients)
2828 server->stat.cell_clients--;
2829 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2830 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2831 silc_schedule_task_del_by_context(server->schedule, client);
2833 /* We will not delete the client entry right away. We will take it
2834 into history (for WHOWAS command) for 5 minutes */
2837 silc_schedule_task_add(server->schedule, 0,
2838 silc_server_free_client_data_timeout,
2840 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2841 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2843 client->router = NULL;
2844 client->connection = NULL;
2847 /* Frees user_data pointer from socket connection object. This also sends
2848 appropriate notify packets to the network to inform about leaving
2851 void silc_server_free_sock_user_data(SilcServer server,
2852 SilcSocketConnection sock,
2853 const char *signoff_message)
2855 switch (sock->type) {
2856 case SILC_SOCKET_TYPE_CLIENT:
2858 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2859 silc_server_free_client_data(server, sock, user_data, TRUE,
2863 case SILC_SOCKET_TYPE_SERVER:
2864 case SILC_SOCKET_TYPE_ROUTER:
2866 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2867 SilcServerEntry backup_router = NULL;
2869 SILC_LOG_DEBUG(("Freeing server data"));
2872 backup_router = silc_server_backup_get(server, user_data->id);
2874 /* If this was our primary router connection then we're lost to
2875 the outside world. */
2876 if (server->router == user_data) {
2877 /* Check whether we have a backup router connection */
2878 if (!backup_router || backup_router == user_data) {
2879 silc_schedule_task_add(server->schedule, 0,
2880 silc_server_connect_to_router,
2883 SILC_TASK_PRI_NORMAL);
2885 server->id_entry->router = NULL;
2886 server->router = NULL;
2887 server->standalone = TRUE;
2888 backup_router = NULL;
2890 if (server->id_entry == backup_router) {
2891 SILC_LOG_INFO(("We are now new router in this cell"));
2892 SILC_LOG_DEBUG(("We are now new router in this cell"));
2894 SILC_LOG_INFO(("New primary router is backup router %s",
2895 backup_router->server_name));
2896 SILC_LOG_DEBUG(("New primary router is backup router %s",
2897 backup_router->server_name));
2899 if (server->id_entry != backup_router) {
2900 server->id_entry->router = backup_router;
2901 server->router = backup_router;
2902 server->router_connect = time(0);
2903 server->backup_primary = TRUE;
2905 server->id_entry->router = NULL;
2906 server->router = NULL;
2907 server->standalone = TRUE;
2910 if (server->server_type == SILC_BACKUP_ROUTER) {
2911 server->server_type = SILC_ROUTER;
2913 /* We'll need to constantly try to reconnect to the primary
2914 router so that we'll see when it comes back online. */
2915 silc_server_backup_reconnect(server, sock->ip, sock->port,
2916 silc_server_backup_connected,
2920 /* Mark this connection as replaced */
2921 silc_server_backup_replaced_add(server, user_data->id,
2924 } else if (backup_router) {
2925 SILC_LOG_INFO(("Enabling the use of backup router %s",
2926 backup_router->server_name));
2927 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2928 backup_router->server_name));
2930 /* Mark this connection as replaced */
2931 silc_server_backup_replaced_add(server, user_data->id,
2935 if (!backup_router) {
2936 /* As router, remove clients and channels always. As normal server
2937 remove only if it is our primary router. Other connections
2938 may be backup routers and these normal server don't handle here. */
2939 if (server->server_type != SILC_SERVER ||
2940 server->standalone || sock == SILC_PRIMARY_ROUTE(server)) {
2941 /* Free all client entries that this server owns as they will
2942 become invalid now as well. */
2943 silc_server_remove_clients_by_server(server, user_data, TRUE);
2944 if (server->server_type == SILC_SERVER)
2945 silc_server_remove_channels_by_server(server, user_data);
2948 /* Update the client entries of this server to the new backup
2949 router. This also removes the clients that *really* was owned
2950 by the primary router and went down with the router. */
2951 silc_server_update_clients_by_server(server, user_data, backup_router,
2953 silc_server_update_servers_by_server(server, user_data, backup_router,
2955 if (server->server_type == SILC_SERVER)
2956 silc_server_update_channels_by_server(server, user_data,
2959 /* Send notify about primary router going down to local operators */
2960 if (server->backup_router)
2961 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
2962 SILC_NOTIFY_TYPE_NONE,
2963 ("%s switched to backup router %s "
2964 "(we are primary router now)",
2965 server->server_name, server->server_name));
2967 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
2968 SILC_NOTIFY_TYPE_NONE,
2969 ("%s switched to backup router %s",
2970 server->server_name,
2971 server->router->server_name));
2974 /* Free the server entry */
2975 silc_server_backup_del(server, user_data);
2976 silc_server_backup_replaced_del(server, user_data);
2977 silc_idlist_del_data(user_data);
2978 if (!silc_idlist_del_server(server->local_list, user_data))
2979 silc_idlist_del_server(server->global_list, user_data);
2980 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2981 server->stat.my_servers--;
2983 server->stat.my_routers--;
2984 server->stat.routers--;
2986 server->stat.servers--;
2987 if (server->server_type == SILC_ROUTER)
2988 server->stat.cell_servers--;
2990 if (backup_router && backup_router != server->id_entry) {
2991 /* Announce all of our stuff that was created about 5 minutes ago.
2992 The backup router knows all the other stuff already. */
2993 if (server->server_type == SILC_ROUTER)
2994 silc_server_announce_servers(server, FALSE, time(0) - 300,
2995 backup_router->connection);
2997 /* Announce our clients and channels to the router */
2998 silc_server_announce_clients(server, time(0) - 300,
2999 backup_router->connection);
3000 silc_server_announce_channels(server, time(0) - 300,
3001 backup_router->connection);
3007 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3009 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3011 silc_idlist_del_data(user_data);
3012 silc_free(user_data);
3017 /* If any protocol is active cancel its execution */
3018 if (sock->protocol) {
3019 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3020 silc_protocol_cancel(sock->protocol, server->schedule);
3021 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3022 silc_protocol_execute_final(sock->protocol, server->schedule);
3023 sock->protocol = NULL;
3026 sock->user_data = NULL;
3029 /* Removes client from all channels it has joined. This is used when client
3030 connection is disconnected. If the client on a channel is last, the
3031 channel is removed as well. This sends the SIGNOFF notify types. */
3033 void silc_server_remove_from_channels(SilcServer server,
3034 SilcSocketConnection sock,
3035 SilcClientEntry client,
3037 const char *signoff_message,
3040 SilcChannelEntry channel;
3041 SilcChannelClientEntry chl;
3042 SilcHashTableList htl;
3043 SilcBuffer clidp = NULL;
3048 SILC_LOG_DEBUG(("Removing client from joined channels"));
3050 if (notify && !client->id)
3054 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3059 /* Remove the client from all channels. The client is removed from
3060 the channels' user list. */
3061 silc_hash_table_list(client->channels, &htl);
3062 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3063 channel = chl->channel;
3065 /* Remove channel if this is last client leaving the channel, unless
3066 the channel is permanent. */
3067 if (server->server_type == SILC_ROUTER &&
3068 silc_hash_table_count(channel->user_list) < 2) {
3069 silc_server_channel_delete(server, channel);
3073 silc_hash_table_del(client->channels, channel);
3074 silc_hash_table_del(channel->user_list, chl->client);
3075 channel->user_count--;
3077 /* If there is no global users on the channel anymore mark the channel
3078 as local channel. Do not check if the removed client is local client. */
3079 if (server->server_type != SILC_ROUTER && channel->global_users &&
3080 chl->client->router && !silc_server_channel_has_global(channel))
3081 channel->global_users = FALSE;
3085 /* Update statistics */
3086 if (SILC_IS_LOCAL(client))
3087 server->stat.my_chanclients--;
3088 if (server->server_type == SILC_ROUTER) {
3089 server->stat.cell_chanclients--;
3090 server->stat.chanclients--;
3093 /* If there is not at least one local user on the channel then we don't
3094 need the channel entry anymore, we can remove it safely, unless the
3095 channel is permanent channel */
3096 if (server->server_type != SILC_ROUTER &&
3097 !silc_server_channel_has_local(channel)) {
3098 /* Notify about leaving client if this channel has global users. */
3099 if (notify && channel->global_users)
3100 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3101 SILC_NOTIFY_TYPE_SIGNOFF,
3102 signoff_message ? 2 : 1,
3103 clidp->data, clidp->len,
3104 signoff_message, signoff_message ?
3105 strlen(signoff_message) : 0);
3107 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3108 silc_server_channel_delete(server, channel);
3112 /* Send notify to channel about client leaving SILC and channel too */
3114 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3115 SILC_NOTIFY_TYPE_SIGNOFF,
3116 signoff_message ? 2 : 1,
3117 clidp->data, clidp->len,
3118 signoff_message, signoff_message ?
3119 strlen(signoff_message) : 0);
3121 /* Re-generate channel key if needed */
3122 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3123 if (!silc_server_create_channel_key(server, channel, 0))
3126 /* Send the channel key to the channel. The key of course is not sent
3127 to the client who was removed from the channel. */
3128 silc_server_send_channel_key(server, client->connection, channel,
3129 server->server_type == SILC_ROUTER ?
3130 FALSE : !server->standalone);
3134 silc_hash_table_list_reset(&htl);
3136 silc_buffer_free(clidp);
3139 /* Removes client from one channel. This is used for example when client
3140 calls LEAVE command to remove itself from the channel. Returns TRUE
3141 if channel still exists and FALSE if the channel is removed when
3142 last client leaves the channel. If `notify' is FALSE notify messages
3145 bool silc_server_remove_from_one_channel(SilcServer server,
3146 SilcSocketConnection sock,
3147 SilcChannelEntry channel,
3148 SilcClientEntry client,
3151 SilcChannelClientEntry chl;
3154 SILC_LOG_DEBUG(("Removing %s from channel %s",
3155 silc_id_render(client->id, SILC_ID_CLIENT),
3156 channel->channel_name));
3158 /* Get the entry to the channel, if this client is not on the channel
3160 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3163 /* Remove channel if this is last client leaving the channel, unless
3164 the channel is permanent. */
3165 if (server->server_type == SILC_ROUTER &&
3166 silc_hash_table_count(channel->user_list) < 2) {
3167 silc_server_channel_delete(server, channel);
3171 silc_hash_table_del(client->channels, chl->channel);
3172 silc_hash_table_del(channel->user_list, chl->client);
3173 channel->user_count--;
3175 /* If there is no global users on the channel anymore mark the channel
3176 as local channel. Do not check if the client is local client. */
3177 if (server->server_type != SILC_ROUTER && channel->global_users &&
3178 chl->client->router && !silc_server_channel_has_global(channel))
3179 channel->global_users = FALSE;
3183 /* Update statistics */
3184 if (SILC_IS_LOCAL(client))
3185 server->stat.my_chanclients--;
3186 if (server->server_type == SILC_ROUTER) {
3187 server->stat.cell_chanclients--;
3188 server->stat.chanclients--;
3191 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3195 /* If there is not at least one local user on the channel then we don't
3196 need the channel entry anymore, we can remove it safely, unless the
3197 channel is permanent channel */
3198 if (server->server_type != SILC_ROUTER &&
3199 !silc_server_channel_has_local(channel)) {
3200 /* Notify about leaving client if this channel has global users. */
3201 if (notify && channel->global_users)
3202 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3203 SILC_NOTIFY_TYPE_LEAVE, 1,
3204 clidp->data, clidp->len);
3206 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3207 silc_server_channel_delete(server, channel);
3208 silc_buffer_free(clidp);
3212 /* Send notify to channel about client leaving the channel */
3214 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3215 SILC_NOTIFY_TYPE_LEAVE, 1,
3216 clidp->data, clidp->len);
3218 silc_buffer_free(clidp);
3222 /* Timeout callback. This is called if connection is idle or for some
3223 other reason is not responding within some period of time. This
3224 disconnects the remote end. */
3226 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3228 SilcServer server = (SilcServer)context;
3229 SilcSocketConnection sock = server->sockets[fd];
3230 SilcProtocolType protocol = 0;
3232 SILC_LOG_DEBUG(("Start"));
3237 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3238 sock->hostname, sock->ip));
3240 /* If we have protocol active we must assure that we call the protocol's
3241 final callback so that all the memory is freed. */
3242 if (sock->protocol) {
3243 protocol = sock->protocol->protocol->type;
3244 silc_protocol_cancel(sock->protocol, server->schedule);
3245 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3246 silc_protocol_execute_final(sock->protocol, server->schedule);
3247 sock->protocol = NULL;
3251 if (sock->user_data)
3252 silc_server_free_sock_user_data(server, sock, NULL);
3254 silc_server_disconnect_remote(server, sock,
3256 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3257 SILC_STATUS_ERR_AUTH_FAILED :
3258 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3259 "Connection timeout");
3262 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3263 function may be used only by router. In real SILC network all channels
3264 are created by routers thus this function is never used by normal
3267 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3268 SilcServerID *router_id,
3274 SilcChannelID *channel_id;
3275 SilcChannelEntry entry;
3279 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3282 cipher = SILC_DEFAULT_CIPHER;
3284 hmac = SILC_DEFAULT_HMAC;
3286 /* Allocate cipher */
3287 if (!silc_cipher_alloc(cipher, &key))
3291 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3292 silc_cipher_free(key);
3296 channel_name = strdup(channel_name);
3298 /* Create the channel ID */
3299 if (!silc_id_create_channel_id(server, router_id, server->rng,
3301 silc_free(channel_name);
3302 silc_cipher_free(key);
3303 silc_hmac_free(newhmac);
3307 /* Create the channel */
3308 entry = silc_idlist_add_channel(server->local_list, channel_name,
3309 SILC_CHANNEL_MODE_NONE, channel_id,
3310 NULL, key, newhmac, 0);
3312 silc_free(channel_name);
3313 silc_cipher_free(key);
3314 silc_hmac_free(newhmac);
3315 silc_free(channel_id);
3319 entry->cipher = strdup(cipher);
3320 entry->hmac_name = strdup(hmac);
3322 /* Now create the actual key material */
3323 if (!silc_server_create_channel_key(server, entry,
3324 silc_cipher_get_key_len(key) / 8)) {
3325 silc_idlist_del_channel(server->local_list, entry);
3329 /* Notify other routers about the new channel. We send the packet
3330 to our primary route. */
3332 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3333 channel_name, entry->id,
3334 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3337 /* Distribute to backup routers */
3338 if (broadcast && server->server_type == SILC_ROUTER) {
3341 SilcUInt32 name_len = strlen(channel_name);
3342 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3343 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3345 packet = silc_channel_payload_encode(channel_name, name_len,
3346 cid, channel_id_len, entry->mode);
3347 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3348 packet->data, packet->len, FALSE, TRUE);
3350 silc_buffer_free(packet);
3353 server->stat.my_channels++;
3354 if (server->server_type == SILC_ROUTER) {
3355 server->stat.channels++;
3356 server->stat.cell_channels++;
3357 entry->users_resolved = TRUE;
3363 /* Same as above but creates the channel with Channel ID `channel_id. */
3366 silc_server_create_new_channel_with_id(SilcServer server,
3370 SilcChannelID *channel_id,
3373 SilcChannelEntry entry;
3377 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3380 cipher = SILC_DEFAULT_CIPHER;
3382 hmac = SILC_DEFAULT_HMAC;
3384 /* Allocate cipher */
3385 if (!silc_cipher_alloc(cipher, &key))
3389 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3390 silc_cipher_free(key);
3394 channel_name = strdup(channel_name);
3396 /* Create the channel */
3397 entry = silc_idlist_add_channel(server->local_list, channel_name,
3398 SILC_CHANNEL_MODE_NONE, channel_id,
3399 NULL, key, newhmac, 0);
3401 silc_cipher_free(key);
3402 silc_hmac_free(newhmac);
3403 silc_free(channel_name);
3407 /* Now create the actual key material */
3408 if (!silc_server_create_channel_key(server, entry,
3409 silc_cipher_get_key_len(key) / 8)) {
3410 silc_idlist_del_channel(server->local_list, entry);
3414 /* Notify other routers about the new channel. We send the packet
3415 to our primary route. */
3417 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3418 channel_name, entry->id,
3419 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3422 /* Distribute to backup routers */
3423 if (broadcast && server->server_type == SILC_ROUTER) {
3426 SilcUInt32 name_len = strlen(channel_name);
3427 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3428 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3430 packet = silc_channel_payload_encode(channel_name, name_len,
3431 cid, channel_id_len, entry->mode);
3432 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3433 packet->data, packet->len, FALSE, TRUE);
3435 silc_buffer_free(packet);
3438 server->stat.my_channels++;
3439 if (server->server_type == SILC_ROUTER) {
3440 server->stat.channels++;
3441 server->stat.cell_channels++;
3442 entry->users_resolved = TRUE;
3448 /* Channel's key re-key timeout callback. */
3450 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3452 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3453 SilcServer server = (SilcServer)rekey->context;
3457 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3460 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3463 /* Generates new channel key. This is used to create the initial channel key
3464 but also to re-generate new key for channel. If `key_len' is provided
3465 it is the bytes of the key length. */
3467 bool silc_server_create_channel_key(SilcServer server,
3468 SilcChannelEntry channel,
3472 unsigned char channel_key[32], hash[32];
3475 SILC_LOG_DEBUG(("Generating channel key"));
3477 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3478 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3482 if (!channel->channel_key)
3483 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3484 channel->channel_key = NULL;
3490 else if (channel->key_len)
3491 len = channel->key_len / 8;
3493 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3495 /* Create channel key */
3496 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3499 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3501 /* Remove old key if exists */
3503 memset(channel->key, 0, channel->key_len / 8);
3504 silc_free(channel->key);
3508 channel->key_len = len * 8;
3509 channel->key = silc_memdup(channel_key, len);
3510 memset(channel_key, 0, sizeof(channel_key));
3512 /* Generate HMAC key from the channel key data and set it */
3514 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3515 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3516 silc_hmac_set_key(channel->hmac, hash,
3517 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3518 memset(hash, 0, sizeof(hash));
3520 if (server->server_type == SILC_ROUTER) {
3521 if (!channel->rekey)
3522 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3523 channel->rekey->context = (void *)server;
3524 channel->rekey->channel = channel;
3525 channel->rekey->key_len = key_len;
3526 if (channel->rekey->task)
3527 silc_schedule_task_del(server->schedule, channel->rekey->task);
3529 channel->rekey->task =
3530 silc_schedule_task_add(server->schedule, 0,
3531 silc_server_channel_key_rekey,
3532 (void *)channel->rekey,
3533 server->config->channel_rekey_secs, 0,
3535 SILC_TASK_PRI_NORMAL);
3541 /* Saves the channel key found in the encoded `key_payload' buffer. This
3542 function is used when we receive Channel Key Payload and also when we're
3543 processing JOIN command reply. Returns entry to the channel. */
3545 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3546 SilcBuffer key_payload,
3547 SilcChannelEntry channel)
3549 SilcChannelKeyPayload payload = NULL;
3550 SilcChannelID *id = NULL;
3551 unsigned char *tmp, hash[32];
3555 SILC_LOG_DEBUG(("Saving new channel key"));
3557 /* Decode channel key payload */
3558 payload = silc_channel_key_payload_parse(key_payload->data,
3561 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3566 /* Get the channel entry */
3569 /* Get channel ID */
3570 tmp = silc_channel_key_get_id(payload, &tmp_len);
3571 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3577 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3579 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3581 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3582 silc_id_render(id, SILC_ID_CHANNEL)));
3588 tmp = silc_channel_key_get_key(payload, &tmp_len);
3594 cipher = silc_channel_key_get_cipher(payload, NULL);
3600 /* Remove old key if exists */
3602 memset(channel->key, 0, channel->key_len / 8);
3603 silc_free(channel->key);
3604 silc_cipher_free(channel->channel_key);
3607 /* Create new cipher */
3608 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3609 channel->channel_key = NULL;
3614 if (channel->cipher)
3615 silc_free(channel->cipher);
3616 channel->cipher = strdup(cipher);
3619 channel->key_len = tmp_len * 8;
3620 channel->key = silc_memdup(tmp, tmp_len);
3621 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3623 /* Generate HMAC key from the channel key data and set it */
3625 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3626 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3627 silc_hmac_set_key(channel->hmac, hash,
3628 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3630 memset(hash, 0, sizeof(hash));
3631 memset(tmp, 0, tmp_len);
3633 if (server->server_type == SILC_ROUTER) {
3634 if (!channel->rekey)
3635 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3636 channel->rekey->context = (void *)server;
3637 channel->rekey->channel = channel;
3638 if (channel->rekey->task)
3639 silc_schedule_task_del(server->schedule, channel->rekey->task);
3641 channel->rekey->task =
3642 silc_schedule_task_add(server->schedule, 0,
3643 silc_server_channel_key_rekey,
3644 (void *)channel->rekey,
3645 server->config->channel_rekey_secs, 0,
3647 SILC_TASK_PRI_NORMAL);
3653 silc_channel_key_payload_free(payload);
3658 /* Heartbeat callback. This function is set as argument for the
3659 silc_socket_set_heartbeat function. The library will call this function
3660 at the set time interval. */
3662 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3665 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3667 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3669 /* Send the heartbeat */
3670 silc_server_send_heartbeat(hb->server, sock);
3673 /* Returns assembled of all servers in the given ID list. The packet's
3674 form is dictated by the New ID payload. */
3676 static void silc_server_announce_get_servers(SilcServer server,
3677 SilcServerEntry remote,
3679 SilcBuffer *servers,
3680 unsigned long creation_time)
3682 SilcIDCacheList list;
3683 SilcIDCacheEntry id_cache;
3684 SilcServerEntry entry;
3687 /* Go through all clients in the list */
3688 if (silc_idcache_get_all(id_list->servers, &list)) {
3689 if (silc_idcache_list_first(list, &id_cache)) {
3691 entry = (SilcServerEntry)id_cache->context;
3693 /* Do not announce the one we've sending our announcements and
3694 do not announce ourself. Also check the creation time if it's
3696 if ((entry == remote) || (entry == server->id_entry) ||
3697 (creation_time && entry->data.created < creation_time)) {
3698 if (!silc_idcache_list_next(list, &id_cache))
3703 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3705 *servers = silc_buffer_realloc(*servers,
3707 (*servers)->truelen + idp->len :
3709 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3710 silc_buffer_put(*servers, idp->data, idp->len);
3711 silc_buffer_pull(*servers, idp->len);
3712 silc_buffer_free(idp);
3714 if (!silc_idcache_list_next(list, &id_cache))
3719 silc_idcache_list_free(list);
3724 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3730 p = silc_notify_payload_encode(notify, argc, ap);
3736 /* This function is used by router to announce existing servers to our
3737 primary router when we've connected to it. If `creation_time' is non-zero
3738 then only the servers that has been created after the `creation_time'
3739 will be announced. */
3741 void silc_server_announce_servers(SilcServer server, bool global,
3742 unsigned long creation_time,
3743 SilcSocketConnection remote)
3745 SilcBuffer servers = NULL;
3747 SILC_LOG_DEBUG(("Announcing servers"));
3749 /* Get servers in local list */
3750 silc_server_announce_get_servers(server, remote->user_data,
3751 server->local_list, &servers,
3755 /* Get servers in global list */
3756 silc_server_announce_get_servers(server, remote->user_data,
3757 server->global_list, &servers,
3761 silc_buffer_push(servers, servers->data - servers->head);
3762 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3764 /* Send the packet */
3765 silc_server_packet_send(server, remote,
3766 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3767 servers->data, servers->len, TRUE);
3769 silc_buffer_free(servers);
3773 /* Returns assembled packet of all clients in the given ID list. The
3774 packet's form is dictated by the New ID Payload. */
3776 static void silc_server_announce_get_clients(SilcServer server,
3778 SilcBuffer *clients,
3780 unsigned long creation_time)
3782 SilcIDCacheList list;
3783 SilcIDCacheEntry id_cache;
3784 SilcClientEntry client;
3787 unsigned char mode[4];
3789 /* Go through all clients in the list */
3790 if (silc_idcache_get_all(id_list->clients, &list)) {
3791 if (silc_idcache_list_first(list, &id_cache)) {
3793 client = (SilcClientEntry)id_cache->context;
3795 if (creation_time && client->data.created < creation_time) {
3796 if (!silc_idcache_list_next(list, &id_cache))
3801 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3803 *clients = silc_buffer_realloc(*clients,
3805 (*clients)->truelen + idp->len :
3807 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3808 silc_buffer_put(*clients, idp->data, idp->len);
3809 silc_buffer_pull(*clients, idp->len);
3811 SILC_PUT32_MSB(client->mode, mode);
3813 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3814 2, idp->data, idp->len,
3816 *umodes = silc_buffer_realloc(*umodes,
3818 (*umodes)->truelen + tmp->len :
3820 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3821 silc_buffer_put(*umodes, tmp->data, tmp->len);
3822 silc_buffer_pull(*umodes, tmp->len);
3823 silc_buffer_free(tmp);
3825 silc_buffer_free(idp);
3827 if (!silc_idcache_list_next(list, &id_cache))
3832 silc_idcache_list_free(list);
3836 /* This function is used to announce our existing clients to our router
3837 when we've connected to it. If `creation_time' is non-zero then only
3838 the clients that has been created after the `creation_time' will be
3841 void silc_server_announce_clients(SilcServer server,
3842 unsigned long creation_time,
3843 SilcSocketConnection remote)
3845 SilcBuffer clients = NULL;
3846 SilcBuffer umodes = NULL;
3848 SILC_LOG_DEBUG(("Announcing clients"));
3850 /* Get clients in local list */
3851 silc_server_announce_get_clients(server, server->local_list,
3852 &clients, &umodes, creation_time);
3854 /* As router we announce our global list as well */
3855 if (server->server_type == SILC_ROUTER)
3856 silc_server_announce_get_clients(server, server->global_list,
3857 &clients, &umodes, creation_time);
3860 silc_buffer_push(clients, clients->data - clients->head);
3861 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3863 /* Send the packet */
3864 silc_server_packet_send(server, remote,
3865 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3866 clients->data, clients->len, TRUE);
3868 silc_buffer_free(clients);
3872 silc_buffer_push(umodes, umodes->data - umodes->head);
3873 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3875 /* Send the packet */
3876 silc_server_packet_send(server, remote,
3877 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3878 umodes->data, umodes->len, TRUE);
3880 silc_buffer_free(umodes);
3884 /* Returns channel's topic for announcing it */
3886 void silc_server_announce_get_channel_topic(SilcServer server,
3887 SilcChannelEntry channel,
3892 if (channel->topic) {
3893 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3894 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3895 chidp->data, chidp->len,
3897 strlen(channel->topic));
3898 silc_buffer_free(chidp);
3902 /* Returns assembled packets for channel users of the `channel'. */
3904 void silc_server_announce_get_channel_users(SilcServer server,
3905 SilcChannelEntry channel,
3906 SilcBuffer *channel_modes,
3907 SilcBuffer *channel_users,
3908 SilcBuffer *channel_users_modes)
3910 SilcChannelClientEntry chl;
3911 SilcHashTableList htl;
3912 SilcBuffer chidp, clidp, csidp;
3915 unsigned char mode[4], *fkey = NULL;
3916 SilcUInt32 fkey_len = 0;
3919 SILC_LOG_DEBUG(("Start"));
3921 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3922 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3925 SILC_PUT32_MSB(channel->mode, mode);
3926 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3927 if (channel->founder_key)
3928 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3930 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3931 6, csidp->data, csidp->len,
3934 hmac, hmac ? strlen(hmac) : 0,
3935 channel->passphrase,
3936 channel->passphrase ?
3937 strlen(channel->passphrase) : 0,
3941 silc_buffer_realloc(*channel_modes,
3943 (*channel_modes)->truelen + len : len));
3944 silc_buffer_pull_tail(*channel_modes,
3945 ((*channel_modes)->end -
3946 (*channel_modes)->data));
3947 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3948 silc_buffer_pull(*channel_modes, len);
3949 silc_buffer_free(tmp);
3954 /* Now find all users on the channel */
3955 silc_hash_table_list(channel->user_list, &htl);
3956 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3957 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3960 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3961 clidp->data, clidp->len,
3962 chidp->data, chidp->len);
3965 silc_buffer_realloc(*channel_users,
3967 (*channel_users)->truelen + len : len));
3968 silc_buffer_pull_tail(*channel_users,
3969 ((*channel_users)->end -
3970 (*channel_users)->data));
3972 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3973 silc_buffer_pull(*channel_users, len);
3974 silc_buffer_free(tmp);
3976 /* CUMODE notify for mode change on the channel */
3977 SILC_PUT32_MSB(chl->mode, mode);
3978 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3979 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3980 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3981 4, csidp->data, csidp->len,
3983 clidp->data, clidp->len,
3986 *channel_users_modes =
3987 silc_buffer_realloc(*channel_users_modes,
3988 (*channel_users_modes ?
3989 (*channel_users_modes)->truelen + len : len));
3990 silc_buffer_pull_tail(*channel_users_modes,
3991 ((*channel_users_modes)->end -
3992 (*channel_users_modes)->data));
3994 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3995 silc_buffer_pull(*channel_users_modes, len);
3996 silc_buffer_free(tmp);
4000 silc_buffer_free(clidp);
4002 silc_hash_table_list_reset(&htl);
4003 silc_buffer_free(chidp);
4004 silc_buffer_free(csidp);
4007 /* Returns assembled packets for all channels and users on those channels
4008 from the given ID List. The packets are in the form dictated by the
4009 New Channel and New Channel User payloads. */
4011 void silc_server_announce_get_channels(SilcServer server,
4013 SilcBuffer *channels,
4014 SilcBuffer **channel_modes,
4015 SilcBuffer *channel_users,
4016 SilcBuffer **channel_users_modes,
4017 SilcUInt32 *channel_users_modes_c,
4018 SilcBuffer **channel_topics,
4019 SilcChannelID ***channel_ids,
4020 unsigned long creation_time)
4022 SilcIDCacheList list;
4023 SilcIDCacheEntry id_cache;
4024 SilcChannelEntry channel;
4027 SilcUInt16 name_len;
4029 int i = *channel_users_modes_c;
4032 SILC_LOG_DEBUG(("Start"));
4034 /* Go through all channels in the list */
4035 if (silc_idcache_get_all(id_list->channels, &list)) {
4036 if (silc_idcache_list_first(list, &id_cache)) {
4038 channel = (SilcChannelEntry)id_cache->context;
4040 if (creation_time && channel->created < creation_time)
4045 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4046 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4047 name_len = strlen(channel->channel_name);
4050 len = 4 + name_len + id_len + 4;
4052 silc_buffer_realloc(*channels,
4053 (*channels ? (*channels)->truelen +
4055 silc_buffer_pull_tail(*channels,
4056 ((*channels)->end - (*channels)->data));
4057 silc_buffer_format(*channels,
4058 SILC_STR_UI_SHORT(name_len),
4059 SILC_STR_UI_XNSTRING(channel->channel_name,
4061 SILC_STR_UI_SHORT(id_len),
4062 SILC_STR_UI_XNSTRING(cid, id_len),
4063 SILC_STR_UI_INT(channel->mode),
4065 silc_buffer_pull(*channels, len);
4068 /* Channel user modes */
4069 *channel_users_modes = silc_realloc(*channel_users_modes,
4070 sizeof(**channel_users_modes) *
4072 (*channel_users_modes)[i] = NULL;
4073 *channel_modes = silc_realloc(*channel_modes,
4074 sizeof(**channel_modes) * (i + 1));
4075 (*channel_modes)[i] = NULL;
4076 *channel_ids = silc_realloc(*channel_ids,
4077 sizeof(**channel_ids) * (i + 1));
4078 (*channel_ids)[i] = NULL;
4079 silc_server_announce_get_channel_users(server, channel,
4080 &(*channel_modes)[i],
4082 &(*channel_users_modes)[i]);
4083 (*channel_ids)[i] = channel->id;
4085 /* Channel's topic */
4086 *channel_topics = silc_realloc(*channel_topics,
4087 sizeof(**channel_topics) * (i + 1));
4088 (*channel_topics)[i] = NULL;
4089 silc_server_announce_get_channel_topic(server, channel,
4090 &(*channel_topics)[i]);
4093 if (!silc_idcache_list_next(list, &id_cache))
4097 *channel_users_modes_c += i;
4100 silc_idcache_list_free(list);
4104 /* This function is used to announce our existing channels to our router
4105 when we've connected to it. This also announces the users on the
4106 channels to the router. If the `creation_time' is non-zero only the
4107 channels that was created after the `creation_time' are announced.
4108 Note that the channel users are still announced even if the `creation_time'
4111 void silc_server_announce_channels(SilcServer server,
4112 unsigned long creation_time,
4113 SilcSocketConnection remote)
4115 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4116 SilcBuffer *channel_users_modes = NULL;
4117 SilcBuffer *channel_topics = NULL;
4118 SilcUInt32 channel_users_modes_c = 0;
4119 SilcChannelID **channel_ids = NULL;
4121 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4123 /* Get channels and channel users in local list */
4124 silc_server_announce_get_channels(server, server->local_list,
4125 &channels, &channel_modes,
4127 &channel_users_modes,
4128 &channel_users_modes_c,
4130 &channel_ids, creation_time);
4132 /* Get channels and channel users in global list */
4133 if (server->server_type != SILC_SERVER)
4134 silc_server_announce_get_channels(server, server->global_list,
4135 &channels, &channel_modes,
4137 &channel_users_modes,
4138 &channel_users_modes_c,
4140 &channel_ids, creation_time);
4143 silc_buffer_push(channels, channels->data - channels->head);
4144 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4146 /* Send the packet */
4147 silc_server_packet_send(server, remote,
4148 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4149 channels->data, channels->len,
4152 silc_buffer_free(channels);
4155 if (channel_users) {
4156 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4157 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4158 channel_users->len);
4160 /* Send the packet */
4161 silc_server_packet_send(server, remote,
4162 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4163 channel_users->data, channel_users->len,
4166 silc_buffer_free(channel_users);
4169 if (channel_modes) {
4172 for (i = 0; i < channel_users_modes_c; i++) {
4173 if (!channel_modes[i])
4175 silc_buffer_push(channel_modes[i],
4176 channel_modes[i]->data -
4177 channel_modes[i]->head);
4178 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4179 channel_modes[i]->len);
4180 silc_server_packet_send_dest(server, remote,
4181 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4182 channel_ids[i], SILC_ID_CHANNEL,
4183 channel_modes[i]->data,
4184 channel_modes[i]->len,
4186 silc_buffer_free(channel_modes[i]);
4188 silc_free(channel_modes);
4191 if (channel_users_modes) {
4194 for (i = 0; i < channel_users_modes_c; i++) {
4195 if (!channel_users_modes[i])
4197 silc_buffer_push(channel_users_modes[i],
4198 channel_users_modes[i]->data -
4199 channel_users_modes[i]->head);
4200 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4201 channel_users_modes[i]->len);
4202 silc_server_packet_send_dest(server, remote,
4203 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4204 channel_ids[i], SILC_ID_CHANNEL,
4205 channel_users_modes[i]->data,
4206 channel_users_modes[i]->len,
4208 silc_buffer_free(channel_users_modes[i]);
4210 silc_free(channel_users_modes);
4213 if (channel_topics) {
4216 for (i = 0; i < channel_users_modes_c; i++) {
4217 if (!channel_topics[i])
4220 silc_buffer_push(channel_topics[i],
4221 channel_topics[i]->data -
4222 channel_topics[i]->head);
4223 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4224 channel_topics[i]->len);
4225 silc_server_packet_send_dest(server, remote,
4226 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4227 channel_ids[i], SILC_ID_CHANNEL,
4228 channel_topics[i]->data,
4229 channel_topics[i]->len,
4231 silc_buffer_free(channel_topics[i]);
4233 silc_free(channel_topics);
4236 silc_free(channel_ids);
4239 /* Failure timeout callback. If this is called then we will immediately
4240 process the received failure. We always process the failure with timeout
4241 since we do not want to blindly trust to received failure packets.
4242 This won't be called (the timeout is cancelled) if the failure was
4243 bogus (it is bogus if remote does not close the connection after sending
4246 SILC_TASK_CALLBACK(silc_server_failure_callback)
4248 SilcServerFailureContext f = (SilcServerFailureContext)context;
4250 if (f->sock->protocol) {
4251 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4252 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4258 /* Assembles user list and users mode list from the `channel'. */
4260 bool silc_server_get_users_on_channel(SilcServer server,
4261 SilcChannelEntry channel,
4262 SilcBuffer *user_list,
4263 SilcBuffer *mode_list,
4264 SilcUInt32 *user_count)
4266 SilcChannelClientEntry chl;
4267 SilcHashTableList htl;
4268 SilcBuffer client_id_list;
4269 SilcBuffer client_mode_list;
4271 SilcUInt32 list_count = 0, len = 0;
4273 if (!silc_hash_table_count(channel->user_list))
4276 silc_hash_table_list(channel->user_list, &htl);
4277 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4278 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4279 silc_hash_table_list_reset(&htl);
4281 client_id_list = silc_buffer_alloc(len);
4283 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4284 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4285 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4287 silc_hash_table_list(channel->user_list, &htl);
4288 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4290 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4291 silc_buffer_put(client_id_list, idp->data, idp->len);
4292 silc_buffer_pull(client_id_list, idp->len);
4293 silc_buffer_free(idp);
4295 /* Client's mode on channel */
4296 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4297 silc_buffer_pull(client_mode_list, 4);
4301 silc_hash_table_list_reset(&htl);
4302 silc_buffer_push(client_id_list,
4303 client_id_list->data - client_id_list->head);
4304 silc_buffer_push(client_mode_list,
4305 client_mode_list->data - client_mode_list->head);
4307 *user_list = client_id_list;
4308 *mode_list = client_mode_list;
4309 *user_count = list_count;
4313 /* Saves users and their modes to the `channel'. */
4315 void silc_server_save_users_on_channel(SilcServer server,
4316 SilcSocketConnection sock,
4317 SilcChannelEntry channel,
4318 SilcClientID *noadd,
4319 SilcBuffer user_list,
4320 SilcBuffer mode_list,
4321 SilcUInt32 user_count)
4326 SilcClientID *client_id;
4327 SilcClientEntry client;
4328 SilcIDCacheEntry cache;
4329 SilcChannelClientEntry chl;
4332 SILC_LOG_DEBUG(("Start"));
4334 for (i = 0; i < user_count; i++) {
4336 SILC_GET16_MSB(idp_len, user_list->data + 2);
4338 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4339 silc_buffer_pull(user_list, idp_len);
4344 SILC_GET32_MSB(mode, mode_list->data);
4345 silc_buffer_pull(mode_list, 4);
4347 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4348 silc_free(client_id);
4354 /* Check if we have this client cached already. */
4355 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4356 server->server_type, &cache);
4358 client = silc_idlist_find_client_by_id(server->global_list,
4359 client_id, server->server_type,
4364 /* If router did not find such Client ID in its lists then this must
4365 be bogus client or some router in the net is buggy. */
4366 if (server->server_type == SILC_ROUTER) {
4367 silc_free(client_id);
4371 /* We don't have that client anywhere, add it. The client is added
4372 to global list since server didn't have it in the lists so it must be
4374 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4375 silc_id_dup(client_id, SILC_ID_CLIENT),
4376 sock->user_data, NULL, 0);
4378 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4379 silc_free(client_id);
4383 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4385 /* Found, if it is from global list we'll assure that we won't
4386 expire it now that the entry is on channel. */
4391 silc_free(client_id);
4393 if (!silc_server_client_on_channel(client, channel, &chl)) {
4394 /* Client was not on the channel, add it. */
4395 chl = silc_calloc(1, sizeof(*chl));
4396 chl->client = client;
4398 chl->channel = channel;
4399 silc_hash_table_add(channel->user_list, chl->client, chl);
4400 silc_hash_table_add(client->channels, chl->channel, chl);
4401 channel->user_count++;
4409 /* Saves channels and channels user modes to the `client'. Removes
4410 the client from those channels that are not sent in the list but
4413 void silc_server_save_user_channels(SilcServer server,
4414 SilcSocketConnection sock,
4415 SilcClientEntry client,
4416 SilcBuffer channels,
4417 SilcBuffer channels_user_modes)
4420 SilcUInt32 *chumodes;
4421 SilcChannelPayload entry;
4422 SilcChannelEntry channel;
4423 SilcChannelID *channel_id;
4424 SilcChannelClientEntry chl;
4425 SilcHashTable ht = NULL;
4426 SilcHashTableList htl;
4430 if (!channels ||!channels_user_modes)
4433 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4434 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4436 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4437 NULL, NULL, NULL, TRUE);
4438 silc_dlist_start(ch);
4439 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4440 /* Check if we have this channel, and add it if we don't have it.
4441 Also add the client on the channel unless it is there already. */
4442 channel_id = silc_channel_get_id_parse(entry);
4443 channel = silc_idlist_find_channel_by_id(server->local_list,
4446 channel = silc_idlist_find_channel_by_id(server->global_list,
4449 if (server->server_type != SILC_SERVER) {
4450 silc_free(channel_id);
4455 /* We don't have that channel anywhere, add it. */
4456 name = silc_channel_get_name(entry, NULL);
4457 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4458 channel_id, server->router,
4461 silc_free(channel_id);
4468 channel->mode = silc_channel_get_mode(entry);
4470 /* Add the client on the channel */
4471 if (!silc_server_client_on_channel(client, channel, &chl)) {
4472 chl = silc_calloc(1, sizeof(*chl));
4473 chl->client = client;
4474 chl->mode = chumodes[i++];
4475 chl->channel = channel;
4476 silc_hash_table_add(channel->user_list, chl->client, chl);
4477 silc_hash_table_add(client->channels, chl->channel, chl);
4478 channel->user_count++;
4481 chl->mode = chumodes[i++];
4484 silc_hash_table_add(ht, channel, channel);
4485 silc_free(channel_id);
4487 silc_channel_payload_list_free(ch);
4488 silc_free(chumodes);
4492 /* Go through the list again and remove client from channels that
4493 are no part of the list. */
4495 silc_hash_table_list(client->channels, &htl);
4496 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4497 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4498 silc_hash_table_del(chl->channel->user_list, chl->client);
4499 silc_hash_table_del(chl->client->channels, chl->channel);
4503 silc_hash_table_list_reset(&htl);
4504 silc_hash_table_free(ht);
4506 silc_hash_table_list(client->channels, &htl);
4507 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4508 silc_hash_table_del(chl->channel->user_list, chl->client);
4509 silc_hash_table_del(chl->client->channels, chl->channel);
4512 silc_hash_table_list_reset(&htl);
4516 /* Lookups route to the client indicated by the `id_data'. The connection
4517 object and internal data object is returned. Returns NULL if route
4518 could not be found to the client. If the `client_id' is specified then
4519 it is used and the `id_data' is ignored. */
4521 SilcSocketConnection
4522 silc_server_get_client_route(SilcServer server,
4523 unsigned char *id_data,
4525 SilcClientID *client_id,
4526 SilcIDListData *idata,
4527 SilcClientEntry *client_entry)
4530 SilcClientEntry client;
4532 SILC_LOG_DEBUG(("Start"));
4535 *client_entry = NULL;
4537 /* Decode destination Client ID */
4539 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4541 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4545 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4548 /* If the destination belongs to our server we don't have to route
4549 the packet anywhere but to send it to the local destination. */
4550 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4554 /* If we are router and the client has router then the client is in
4555 our cell but not directly connected to us. */
4556 if (server->server_type == SILC_ROUTER && client->router) {
4557 /* We are of course in this case the client's router thus the route
4558 to the client is the server who owns the client. So, we will send
4559 the packet to that server. */
4561 *idata = (SilcIDListData)client->router;
4562 return client->router->connection;
4565 /* Seems that client really is directly connected to us */
4567 *idata = (SilcIDListData)client;
4569 *client_entry = client;
4570 return client->connection;
4573 /* Destination belongs to someone not in this server. If we are normal
4574 server our action is to send the packet to our router. */
4575 if (server->server_type != SILC_ROUTER && !server->standalone) {
4578 *idata = (SilcIDListData)server->router;
4579 return SILC_PRIMARY_ROUTE(server);
4582 /* We are router and we will perform route lookup for the destination
4583 and send the packet to fastest route. */
4584 if (server->server_type == SILC_ROUTER && !server->standalone) {
4585 /* Check first that the ID is valid */
4586 client = silc_idlist_find_client_by_id(server->global_list, id,
4589 SilcSocketConnection dst_sock;
4591 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4595 *idata = (SilcIDListData)dst_sock->user_data;
4604 /* Encodes and returns channel list of channels the `client' has joined.
4605 Secret channels are not put to the list. */
4607 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4608 SilcClientEntry client,
4611 SilcBuffer *user_mode_list)
4613 SilcBuffer buffer = NULL;
4614 SilcChannelEntry channel;
4615 SilcChannelClientEntry chl;
4616 SilcHashTableList htl;
4619 SilcUInt16 name_len;
4623 *user_mode_list = NULL;
4625 silc_hash_table_list(client->channels, &htl);
4626 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4627 channel = chl->channel;
4629 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4631 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4634 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4635 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4636 name_len = strlen(channel->channel_name);
4638 len = 4 + name_len + id_len + 4;
4639 buffer = silc_buffer_realloc(buffer,
4640 (buffer ? buffer->truelen + len : len));
4641 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4642 silc_buffer_format(buffer,
4643 SILC_STR_UI_SHORT(name_len),
4644 SILC_STR_UI_XNSTRING(channel->channel_name,
4646 SILC_STR_UI_SHORT(id_len),
4647 SILC_STR_UI_XNSTRING(cid, id_len),
4648 SILC_STR_UI_INT(chl->channel->mode),
4650 silc_buffer_pull(buffer, len);
4653 if (user_mode_list) {
4654 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4656 (*user_mode_list)->truelen + 4 :
4658 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4659 (*user_mode_list)->data));
4660 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4661 silc_buffer_pull(*user_mode_list, 4);
4664 silc_hash_table_list_reset(&htl);
4667 silc_buffer_push(buffer, buffer->data - buffer->head);
4668 if (user_mode_list && *user_mode_list)
4669 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4670 (*user_mode_list)->head));
4675 /* Finds client entry by Client ID and if it is not found then resolves
4676 it using WHOIS command. */
4678 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4679 SilcClientID *client_id,
4680 bool always_resolve,
4683 SilcClientEntry client;
4688 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4691 client = silc_idlist_find_client_by_id(server->global_list,
4692 client_id, TRUE, NULL);
4693 if (!client && server->server_type == SILC_ROUTER)
4697 if (!client && server->standalone)
4700 if (!client || !client->nickname || !client->username ||
4702 SilcBuffer buffer, idp;
4705 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4706 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4707 client->resolve_cmd_ident = ++server->cmd_ident;
4710 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4711 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4712 server->cmd_ident, 1,
4713 4, idp->data, idp->len);
4714 silc_server_packet_send(server, client ? client->router->connection :
4715 SILC_PRIMARY_ROUTE(server),
4716 SILC_PACKET_COMMAND, 0,
4717 buffer->data, buffer->len, FALSE);
4718 silc_buffer_free(idp);
4719 silc_buffer_free(buffer);
4730 /* A timeout callback for the re-key. We will be the initiator of the
4733 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4735 SilcSocketConnection sock = (SilcSocketConnection)context;
4736 SilcIDListData idata = (SilcIDListData)sock->user_data;
4737 SilcServer server = (SilcServer)idata->rekey->context;
4738 SilcProtocol protocol;
4739 SilcServerRekeyInternalContext *proto_ctx;
4741 SILC_LOG_DEBUG(("Start"));
4743 /* Allocate internal protocol context. This is sent as context
4745 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4746 proto_ctx->server = (void *)server;
4747 proto_ctx->sock = sock;
4748 proto_ctx->responder = FALSE;
4749 proto_ctx->pfs = idata->rekey->pfs;
4751 /* Perform rekey protocol. Will call the final callback after the
4752 protocol is over. */
4753 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4754 &protocol, proto_ctx, silc_server_rekey_final);
4755 sock->protocol = protocol;
4757 /* Run the protocol */
4758 silc_protocol_execute(protocol, server->schedule, 0, 0);
4760 /* Re-register re-key timeout */
4761 silc_schedule_task_add(server->schedule, sock->sock,
4762 silc_server_rekey_callback,
4763 context, idata->rekey->timeout, 0,
4764 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4767 /* The final callback for the REKEY protocol. This will actually take the
4768 new key material into use. */
4770 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4772 SilcProtocol protocol = (SilcProtocol)context;
4773 SilcServerRekeyInternalContext *ctx =
4774 (SilcServerRekeyInternalContext *)protocol->context;
4775 SilcServer server = (SilcServer)ctx->server;
4776 SilcSocketConnection sock = ctx->sock;
4778 SILC_LOG_DEBUG(("Start"));
4780 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4781 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4782 /* Error occured during protocol */
4783 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4784 silc_protocol_cancel(protocol, server->schedule);
4785 silc_protocol_free(protocol);
4786 sock->protocol = NULL;
4788 silc_packet_context_free(ctx->packet);
4790 silc_ske_free(ctx->ske);
4795 /* Purge the outgoing data queue to assure that all rekey packets really
4796 go to the network before we quit the protocol. */
4797 silc_server_packet_queue_purge(server, sock);
4800 silc_protocol_free(protocol);
4801 sock->protocol = NULL;
4803 silc_packet_context_free(ctx->packet);
4805 silc_ske_free(ctx->ske);
4809 /* Task callback used to retrieve network statistical information from
4810 router server once in a while. */
4812 SILC_TASK_CALLBACK(silc_server_get_stats)
4814 SilcServer server = (SilcServer)context;
4815 SilcBuffer idp, packet;
4817 SILC_LOG_DEBUG(("Retrieving stats from router"));
4819 if (!server->standalone) {
4820 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4821 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4822 ++server->cmd_ident, 1,
4823 1, idp->data, idp->len);
4824 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4825 SILC_PACKET_COMMAND, 0, packet->data,
4826 packet->len, FALSE);
4827 silc_buffer_free(packet);
4828 silc_buffer_free(idp);
4831 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4832 server, 120, 0, SILC_TASK_TIMEOUT,