5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
90 silc_server_config_unref(&server->config_ref);
92 silc_rng_free(server->rng);
94 silc_pkcs_free(server->pkcs);
95 if (server->public_key)
96 silc_pkcs_public_key_free(server->public_key);
97 if (server->private_key)
98 silc_pkcs_private_key_free(server->private_key);
99 if (server->pending_commands)
100 silc_dlist_uninit(server->pending_commands);
101 if (server->id_entry)
102 silc_idlist_del_server(server->local_list, server->id_entry);
104 silc_idcache_free(server->local_list->clients);
105 silc_idcache_free(server->local_list->servers);
106 silc_idcache_free(server->local_list->channels);
107 silc_idcache_free(server->global_list->clients);
108 silc_idcache_free(server->global_list->servers);
109 silc_idcache_free(server->global_list->channels);
111 silc_free(server->sockets);
116 /* Opens a listening port.
117 XXX This function will become more general and will support multiple
120 static bool silc_server_listen(SilcServer server, int *sock)
123 *sock = silc_net_create_server(server->config->server_info->port,
124 server->config->server_info->server_ip);
126 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
127 server->config->server_info->server_ip,
128 server->config->server_info->port));
134 /* Initializes the entire SILC server. This is called always before running
135 the server. This is called only once at the initialization of the program.
136 This binds the server to its listenning port. After this function returns
137 one should call silc_server_run to start the server. This returns TRUE
138 when everything is ok to run the server. Configuration file must be
139 read and parsed before calling this. */
141 bool silc_server_init(SilcServer server)
145 SilcServerEntry id_entry;
146 SilcIDListPurge purge;
147 SilcSocketConnection newsocket = NULL;
149 SILC_LOG_DEBUG(("Initializing server"));
151 /* Take config object for us */
152 silc_server_config_ref(&server->config_ref, server->config,
155 /* Steal public and private key from the config object */
156 server->public_key = server->config->server_info->public_key;
157 server->private_key = server->config->server_info->private_key;
158 server->config->server_info->public_key = NULL;
159 server->config->server_info->private_key = NULL;
161 /* Register all configured ciphers, PKCS and hash functions. */
162 if (!silc_server_config_register_ciphers(server))
163 silc_cipher_register_default();
164 if (!silc_server_config_register_pkcs(server))
165 silc_pkcs_register_default();
166 if (!silc_server_config_register_hashfuncs(server))
167 silc_hash_register_default();
168 if (!silc_server_config_register_hmacs(server))
169 silc_hmac_register_default();
171 /* Initialize random number generator for the server. */
172 server->rng = silc_rng_alloc();
173 silc_rng_init(server->rng);
174 silc_rng_global_init(server->rng);
176 /* Initialize hash functions for server to use */
177 silc_hash_alloc("md5", &server->md5hash);
178 silc_hash_alloc("sha1", &server->sha1hash);
180 /* Allocate PKCS context for local public and private keys */
181 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
183 silc_pkcs_public_key_set(server->pkcs, server->public_key);
184 silc_pkcs_private_key_set(server->pkcs, server->private_key);
186 /* Initialize the scheduler */
187 server->schedule = silc_schedule_init(server->config->param.connections_max);
188 if (!server->schedule)
191 /* First, register log files configuration for error output */
192 silc_server_config_setlogfiles(server);
194 /* Initialize ID caches */
195 server->local_list->clients =
196 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
197 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
198 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
200 /* These are allocated for normal server as well as these hold some
201 global information that the server has fetched from its router. For
202 router these are used as they are supposed to be used on router. */
203 server->global_list->clients =
204 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
205 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
206 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
208 /* Create a listening server */
209 if (!silc_server_listen(server, &sock))
212 /* Set socket to non-blocking mode */
213 silc_net_set_socket_nonblock(sock);
216 /* Allocate the entire socket list that is used in server. Eventually
217 all connections will have entry in this table (it is a table of
218 pointers to the actual object that is allocated individually
220 server->sockets = silc_calloc(server->config->param.connections_max,
221 sizeof(*server->sockets));
222 if (!server->sockets)
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
234 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
257 server->config->server_info->server_name = NULL;
259 /* Add ourselves to the server list. We don't have a router yet
260 beacuse we haven't established a route yet. It will be done later.
261 For now, NULL is sent as router. This allocates new entry to
264 silc_idlist_add_server(server->local_list, strdup(server->server_name),
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
278 /* Register protocols */
279 silc_server_protocols_register();
281 /* Add the first task to the scheduler. This is task that is executed by
282 timeout. It expires as soon as the caller calls silc_server_run. This
283 task performs authentication protocol and key exchange with our
285 silc_schedule_task_add(server->schedule, 0,
286 silc_server_connect_to_router,
287 (void *)server, 0, 1,
289 SILC_TASK_PRI_NORMAL);
291 /* Add listener task to the scheduler. This task receives new connections
292 to the server. This task remains on the queue until the end of the
294 silc_schedule_task_add(server->schedule, sock,
295 silc_server_accept_new_connection,
296 (void *)server, 0, 0,
298 SILC_TASK_PRI_NORMAL);
299 server->listenning = TRUE;
301 /* If server connections has been configured then we must be router as
302 normal server cannot have server connections, only router connections. */
303 if (server->config->servers) {
304 SilcServerConfigServer *ptr = server->config->servers;
306 server->server_type = SILC_ROUTER;
308 if (ptr->backup_router) {
309 server->server_type = SILC_BACKUP_ROUTER;
310 server->backup_router = TRUE;
311 server->id_entry->server_type = SILC_BACKUP_ROUTER;
318 /* Register the ID Cache purge task. This periodically purges the ID cache
319 and removes the expired cache entries. */
321 /* Clients local list */
322 purge = silc_calloc(1, sizeof(*purge));
323 purge->cache = server->local_list->clients;
324 purge->schedule = server->schedule;
325 purge->timeout = 600;
326 silc_schedule_task_add(purge->schedule, 0,
328 (void *)purge, purge->timeout, 0,
329 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
331 /* Clients global list */
332 purge = silc_calloc(1, sizeof(*purge));
333 purge->cache = server->global_list->clients;
334 purge->schedule = server->schedule;
335 purge->timeout = 300;
336 silc_schedule_task_add(purge->schedule, 0,
338 (void *)purge, purge->timeout, 0,
339 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
341 SILC_LOG_DEBUG(("Server initialized"));
343 /* We are done here, return succesfully */
347 silc_net_close_server(sock);
351 /* This function basically reads the config file again and switches the config
352 object pointed by the server object. After that, we have to fix various
353 things such as the server_name and the listening ports.
354 Keep in mind that we no longer have the root privileges at this point. */
356 bool silc_server_rehash(SilcServer server)
358 SilcServerConfig newconfig;
359 SilcUInt32 max_conns;
361 SILC_LOG_INFO(("Rehashing server"));
363 /* Reset the logging system */
364 silc_log_quick = TRUE;
365 silc_log_flush_all();
367 /* Start the main rehash phase (read again the config file) */
368 newconfig = silc_server_config_alloc(server->config_file);
370 SILC_LOG_ERROR(("Rehash FAILED."));
374 max_conns = server->config->param.connections_max;
376 /* Our old config is gone now. We'll unreference our reference made in
377 silc_server_init and then destroy it since we are destroying it
378 underneath the application (layer which called silc_server_init). */
379 silc_server_config_unref(&server->config_ref);
380 silc_server_config_destroy(server->config);
382 /* Take new config context */
383 server->config = newconfig;
384 silc_server_config_ref(&server->config_ref, server->config, server->config);
386 /* Reinit scheduler if necessary */
387 if (server->config->param.connections_max > max_conns)
388 silc_schedule_reinit(server->schedule,
389 server->config->param.connections_max);
391 /* Fix the server_name field */
392 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
393 silc_free(server->server_name);
394 server->server_name = newconfig->server_info->server_name;
395 newconfig->server_info->server_name = NULL;
397 /* Update the idcache list with a fresh pointer */
398 silc_free(server->id_entry->server_name);
399 server->id_entry->server_name = strdup(server->server_name);
400 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
401 silc_idcache_add(server->local_list->servers,
402 server->id_entry->server_name,
403 server->id_entry->id, server->id_entry, 0, NULL);
406 silc_server_config_setlogfiles(server);
408 /* Change new key pair if necessary */
409 if (newconfig->server_info->public_key &&
410 !silc_pkcs_public_key_compare(server->public_key,
411 newconfig->server_info->public_key)) {
412 silc_pkcs_public_key_free(server->public_key);
413 silc_pkcs_private_key_free(server->private_key);
414 server->public_key = server->config->server_info->public_key;
415 server->private_key = server->config->server_info->private_key;
416 server->config->server_info->public_key = NULL;
417 server->config->server_info->private_key = NULL;
419 /* Allocate PKCS context for local public and private keys */
420 silc_pkcs_free(server->pkcs);
421 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
423 silc_pkcs_public_key_set(server->pkcs, server->public_key);
424 silc_pkcs_private_key_set(server->pkcs, server->private_key);
427 /* Go through all configured routers after rehash */
428 silc_schedule_task_add(server->schedule, 0,
429 silc_server_connect_to_router,
430 (void *)server, 0, 1,
432 SILC_TASK_PRI_NORMAL);
434 /* Check whether our router status has changed */
435 if (server->config->servers) {
436 SilcServerConfigServer *ptr = server->config->servers;
438 server->server_type = SILC_ROUTER;
440 if (ptr->backup_router) {
441 server->server_type = SILC_BACKUP_ROUTER;
442 server->backup_router = TRUE;
443 server->id_entry->server_type = SILC_BACKUP_ROUTER;
450 SILC_LOG_DEBUG(("Server rehashed"));
455 /* The heart of the server. This runs the scheduler thus runs the server.
456 When this returns the server has been stopped and the program will
459 void silc_server_run(SilcServer server)
461 SILC_LOG_INFO(("SILC Server started"));
463 /* Start the scheduler, the heart of the SILC server. When this returns
464 the program will be terminated. */
465 silc_schedule(server->schedule);
468 /* Stops the SILC server. This function is used to shutdown the server.
469 This is usually called after the scheduler has returned. After stopping
470 the server one should call silc_server_free. */
472 void silc_server_stop(SilcServer server)
474 SILC_LOG_DEBUG(("Stopping server"));
476 if (server->schedule) {
477 silc_schedule_stop(server->schedule);
478 silc_schedule_uninit(server->schedule);
479 server->schedule = NULL;
482 silc_server_protocols_unregister();
484 SILC_LOG_DEBUG(("Server stopped"));
487 /* Function that is called when the network connection to a router has
488 been established. This will continue with the key exchange protocol
489 with the remote router. */
491 void silc_server_start_key_exchange(SilcServer server,
492 SilcServerConnection sconn,
495 SilcSocketConnection newsocket;
496 SilcProtocol protocol;
497 SilcServerKEInternalContext *proto_ctx;
498 SilcServerConfigRouter *conn =
499 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
502 /* Cancel any possible retry timeouts */
503 silc_schedule_task_del_by_callback(server->schedule,
504 silc_server_connect_router);
506 /* Set socket options */
507 silc_net_set_socket_nonblock(sock);
508 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
510 /* Create socket connection for the connection. Even though we
511 know that we are connecting to a router we will mark the socket
512 to be unknown connection until we have executed authentication
514 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
515 server->sockets[sock] = newsocket;
516 newsocket->hostname = strdup(sconn->remote_host);
517 newsocket->ip = strdup(sconn->remote_host);
518 newsocket->port = sconn->remote_port;
519 sconn->sock = newsocket;
521 /* Allocate internal protocol context. This is sent as context
523 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
524 proto_ctx->server = (void *)server;
525 proto_ctx->context = (void *)sconn;
526 proto_ctx->sock = newsocket;
527 proto_ctx->rng = server->rng;
528 proto_ctx->responder = FALSE;
530 /* Set Key Exchange flags from configuration, but fall back to global
532 SILC_GET_SKE_FLAGS(conn, proto_ctx);
533 if (server->config->param.key_exchange_pfs)
534 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
536 /* Perform key exchange protocol. silc_server_connect_to_router_second
537 will be called after the protocol is finished. */
538 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
539 &protocol, proto_ctx,
540 silc_server_connect_to_router_second);
541 newsocket->protocol = protocol;
543 /* Register a timeout task that will be executed if the protocol
544 is not executed within set limit. */
545 proto_ctx->timeout_task =
546 silc_schedule_task_add(server->schedule, sock,
547 silc_server_timeout_remote,
548 server, server->config->key_exchange_timeout, 0,
552 /* Register the connection for network input and output. This sets
553 that scheduler will listen for incoming packets for this connection
554 and sets that outgoing packets may be sent to this connection as
555 well. However, this doesn't set the scheduler for outgoing traffic,
556 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
557 later when outgoing data is available. */
558 context = (void *)server;
559 SILC_REGISTER_CONNECTION_FOR_IO(sock);
561 /* Run the protocol */
562 silc_protocol_execute(protocol, server->schedule, 0, 0);
565 /* Timeout callback that will be called to retry connecting to remote
566 router. This is used by both normal and router server. This will wait
567 before retrying the connecting. The timeout is generated by exponential
568 backoff algorithm. */
570 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
572 SilcServerConnection sconn = (SilcServerConnection)context;
573 SilcServer server = sconn->server;
574 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
575 SilcServerConfigConnParams *param =
576 (conn->param ? conn->param : &server->config->param);
578 SILC_LOG_INFO(("Retrying connecting to a router"));
580 /* Calculate next timeout */
581 if (sconn->retry_count >= 1) {
582 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
583 if (sconn->retry_timeout > param->reconnect_interval_max)
584 sconn->retry_timeout = param->reconnect_interval_max;
586 sconn->retry_timeout = param->reconnect_interval;
588 sconn->retry_count++;
589 sconn->retry_timeout = sconn->retry_timeout +
590 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
592 /* If we've reached max retry count, give up. */
593 if ((sconn->retry_count > param->reconnect_count) &&
594 !param->reconnect_keep_trying) {
595 SILC_LOG_ERROR(("Could not connect to router, giving up"));
596 silc_server_config_unref(&sconn->conn);
597 silc_free(sconn->remote_host);
598 silc_free(sconn->backup_replace_ip);
603 /* We will lookup a fresh pointer later */
604 silc_server_config_unref(&sconn->conn);
606 /* Wait one before retrying */
607 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
608 context, sconn->retry_timeout, 0,
609 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
612 /* Generic routine to use connect to a router. */
614 SILC_TASK_CALLBACK(silc_server_connect_router)
616 SilcServerConnection sconn = (SilcServerConnection)context;
617 SilcServer server = sconn->server;
618 SilcServerConfigRouter *rconn;
621 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
622 (sconn->backup ? "backup router" : "router"),
623 sconn->remote_host, sconn->remote_port));
625 server->router_connect = time(NULL);
626 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
629 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
630 (sconn->backup ? "backup router" : "router"),
631 sconn->remote_host, sconn->remote_port));
632 silc_free(sconn->remote_host);
633 silc_free(sconn->backup_replace_ip);
637 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
639 /* Connect to remote host */
640 sock = silc_net_create_connection(server->config->server_info->server_ip,
644 SILC_LOG_ERROR(("Could not connect to router %s:%d",
645 sconn->remote_host, sconn->remote_port));
646 if (!sconn->no_reconnect)
647 silc_schedule_task_add(server->schedule, 0,
648 silc_server_connect_to_router_retry,
649 context, 0, 1, SILC_TASK_TIMEOUT,
650 SILC_TASK_PRI_NORMAL);
652 silc_server_config_unref(&sconn->conn);
656 /* Continue with key exchange protocol */
657 silc_server_start_key_exchange(server, sconn, sock);
660 /* This function connects to our primary router or if we are a router this
661 establishes all our primary routes. This is called at the start of the
662 server to do authentication and key exchange with our router - called
665 SILC_TASK_CALLBACK(silc_server_connect_to_router)
667 SilcServer server = (SilcServer)context;
668 SilcServerConnection sconn;
669 SilcServerConfigRouter *ptr;
671 SILC_LOG_DEBUG(("Connecting to router(s)"));
673 if (server->server_type == SILC_SERVER) {
674 SILC_LOG_DEBUG(("We are normal server"));
675 } else if (server->server_type == SILC_ROUTER) {
676 SILC_LOG_DEBUG(("We are router"));
678 SILC_LOG_DEBUG(("We are backup router/normal server"));
681 if (!server->config->routers) {
682 /* There wasn't a configured router, we will continue but we don't
683 have a connection to outside world. We will be standalone server. */
684 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
685 server->standalone = TRUE;
689 /* Create the connections to all our routes */
690 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
692 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
693 ptr->backup_router ? "Backup router" : "Router",
694 ptr->initiator ? "Initiator" : "Responder",
695 ptr->host, ptr->port));
697 if (ptr->initiator) {
698 /* Check whether we are connected to this host already */
699 if (silc_server_num_sockets_by_remote(server,
700 silc_net_is_ip(ptr->host) ?
702 silc_net_is_ip(ptr->host) ?
703 NULL : ptr->host, ptr->port,
704 SILC_SOCKET_TYPE_ROUTER)) {
705 SILC_LOG_DEBUG(("We are already connected to this router"));
709 /* Allocate connection object for hold connection specific stuff. */
710 sconn = silc_calloc(1, sizeof(*sconn));
711 sconn->server = server;
712 sconn->remote_host = strdup(ptr->host);
713 sconn->remote_port = ptr->port;
714 sconn->backup = ptr->backup_router;
716 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
717 sconn->backup_replace_port = ptr->backup_replace_port;
720 if (!server->router_conn && !sconn->backup)
721 server->router_conn = sconn;
723 silc_schedule_task_add(server->schedule, 0,
724 silc_server_connect_router,
725 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
726 SILC_TASK_PRI_NORMAL);
731 /* Second part of connecting to router(s). Key exchange protocol has been
732 executed and now we will execute authentication protocol. */
734 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
736 SilcProtocol protocol = (SilcProtocol)context;
737 SilcServerKEInternalContext *ctx =
738 (SilcServerKEInternalContext *)protocol->context;
739 SilcServer server = (SilcServer)ctx->server;
740 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
741 SilcSocketConnection sock = ctx->sock;
742 SilcServerConnAuthInternalContext *proto_ctx;
743 SilcServerConfigRouter *conn = NULL;
745 SILC_LOG_DEBUG(("Start"));
747 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
748 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
749 /* Error occured during protocol */
750 silc_protocol_free(protocol);
751 sock->protocol = NULL;
752 silc_ske_free_key_material(ctx->keymat);
754 silc_packet_context_free(ctx->packet);
756 silc_ske_free(ctx->ske);
757 silc_free(ctx->dest_id);
759 silc_server_config_unref(&sconn->conn);
760 silc_free(sconn->remote_host);
761 silc_free(sconn->backup_replace_ip);
763 silc_schedule_task_del_by_callback(server->schedule,
764 silc_server_failure_callback);
765 silc_server_disconnect_remote(server, sock, "Server closed connection: "
766 "Key exchange failed");
770 /* We now have the key material as the result of the key exchange
771 protocol. Take the key material into use. Free the raw key material
772 as soon as we've set them into use. */
773 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
774 ctx->sock, ctx->keymat,
775 ctx->ske->prop->cipher,
776 ctx->ske->prop->pkcs,
777 ctx->ske->prop->hash,
778 ctx->ske->prop->hmac,
779 ctx->ske->prop->group,
781 silc_protocol_free(protocol);
782 sock->protocol = NULL;
783 silc_ske_free_key_material(ctx->keymat);
785 silc_packet_context_free(ctx->packet);
787 silc_ske_free(ctx->ske);
788 silc_free(ctx->dest_id);
790 silc_server_config_unref(&sconn->conn);
791 silc_free(sconn->remote_host);
792 silc_free(sconn->backup_replace_ip);
794 silc_schedule_task_del_by_callback(server->schedule,
795 silc_server_failure_callback);
796 silc_server_disconnect_remote(server, sock, "Server closed connection: "
797 "Key exchange failed");
800 silc_ske_free_key_material(ctx->keymat);
802 /* Allocate internal context for the authentication protocol. This
803 is sent as context for the protocol. */
804 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
805 proto_ctx->server = (void *)server;
806 proto_ctx->context = (void *)sconn;
807 proto_ctx->sock = sock;
808 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
809 proto_ctx->dest_id_type = ctx->dest_id_type;
810 proto_ctx->dest_id = ctx->dest_id;
812 /* Resolve the authentication method used in this connection. Check if
813 we find a match from user configured connections */
814 if (!sconn->conn.ref_ptr)
815 conn = silc_server_config_find_router_conn(server, sock->hostname,
818 conn = sconn->conn.ref_ptr;
821 /* Match found. Use the configured authentication method. Take only
822 the passphrase, since for public key auth we automatically use
823 our local key pair. */
824 if (conn->passphrase) {
825 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
826 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
828 proto_ctx->auth_data = strdup(conn->passphrase);
829 proto_ctx->auth_data_len = strlen(conn->passphrase);
830 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
832 } else if (conn->publickeys) {
833 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
835 proto_ctx->auth_meth = SILC_AUTH_NONE;
838 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
839 sock->hostname, sock->ip, sock->port));
840 silc_protocol_free(protocol);
841 sock->protocol = NULL;
843 silc_packet_context_free(ctx->packet);
845 silc_ske_free(ctx->ske);
846 silc_free(ctx->dest_id);
848 silc_server_config_unref(&sconn->conn);
849 silc_free(sconn->remote_host);
850 silc_free(sconn->backup_replace_ip);
852 silc_schedule_task_del_by_callback(server->schedule,
853 silc_server_failure_callback);
854 silc_server_disconnect_remote(server, sock, "Server closed connection: "
855 "Key exchange failed");
859 /* Free old protocol as it is finished now */
860 silc_protocol_free(protocol);
862 silc_packet_context_free(ctx->packet);
864 sock->protocol = NULL;
866 /* Allocate the authentication protocol. This is allocated here
867 but we won't start it yet. We will be receiving party of this
868 protocol thus we will wait that connecting party will make
870 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
871 &sock->protocol, proto_ctx,
872 silc_server_connect_to_router_final);
874 /* Register timeout task. If the protocol is not executed inside
875 this timelimit the connection will be terminated. */
876 proto_ctx->timeout_task =
877 silc_schedule_task_add(server->schedule, sock->sock,
878 silc_server_timeout_remote,
880 server->config->conn_auth_timeout, 0,
884 /* Run the protocol */
885 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
888 /* Finalizes the connection to router. Registers a server task to the
889 queue so that we can accept new connections. */
891 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
893 SilcProtocol protocol = (SilcProtocol)context;
894 SilcServerConnAuthInternalContext *ctx =
895 (SilcServerConnAuthInternalContext *)protocol->context;
896 SilcServer server = (SilcServer)ctx->server;
897 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
898 SilcSocketConnection sock = ctx->sock;
899 SilcServerEntry id_entry;
901 SilcServerHBContext hb_context;
902 unsigned char *id_string;
904 SilcIDListData idata;
905 SilcServerConfigRouter *conn = NULL;
906 SilcServerConfigConnParams *param = NULL;
908 SILC_LOG_DEBUG(("Start"));
910 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
911 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
912 /* Error occured during protocol */
913 silc_free(ctx->dest_id);
914 silc_server_disconnect_remote(server, sock, "Server closed connection: "
915 "Authentication failed");
919 /* Add a task to the queue. This task receives new connections to the
920 server. This task remains on the queue until the end of the program. */
921 if (!server->listenning && !sconn->backup) {
922 silc_schedule_task_add(server->schedule, server->sock,
923 silc_server_accept_new_connection,
924 (void *)server, 0, 0,
926 SILC_TASK_PRI_NORMAL);
927 server->listenning = TRUE;
930 /* Send NEW_SERVER packet to the router. We will become registered
931 to the SILC network after sending this packet. */
932 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
933 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
934 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
935 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
936 silc_buffer_format(packet,
937 SILC_STR_UI_SHORT(id_len),
938 SILC_STR_UI_XNSTRING(id_string, id_len),
939 SILC_STR_UI_SHORT(strlen(server->server_name)),
940 SILC_STR_UI_XNSTRING(server->server_name,
941 strlen(server->server_name)),
944 /* Send the packet */
945 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
946 packet->data, packet->len, TRUE);
947 silc_buffer_free(packet);
948 silc_free(id_string);
950 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
952 /* Check that we do not have this ID already */
953 id_entry = silc_idlist_find_server_by_id(server->local_list,
954 ctx->dest_id, TRUE, NULL);
956 silc_idcache_del_by_context(server->local_list->servers, id_entry);
958 id_entry = silc_idlist_find_server_by_id(server->global_list,
959 ctx->dest_id, TRUE, NULL);
961 silc_idcache_del_by_context(server->global_list->servers, id_entry);
964 SILC_LOG_DEBUG(("New server id(%s)",
965 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
967 /* Add the connected router to global server list */
968 id_entry = silc_idlist_add_server(server->global_list,
969 strdup(sock->hostname),
970 SILC_ROUTER, ctx->dest_id, NULL, sock);
972 silc_free(ctx->dest_id);
973 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
974 silc_server_disconnect_remote(server, sock, "Server closed connection: "
975 "Authentication failed");
979 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
980 silc_free(sock->user_data);
981 sock->user_data = (void *)id_entry;
982 sock->type = SILC_SOCKET_TYPE_ROUTER;
983 idata = (SilcIDListData)sock->user_data;
984 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
986 conn = sconn->conn.ref_ptr;
987 param = &server->config->param;
988 if (conn && conn->param)
991 /* Perform keepalive. The `hb_context' will be freed automatically
992 when finally calling the silc_socket_free function. */
993 hb_context = silc_calloc(1, sizeof(*hb_context));
994 hb_context->server = server;
995 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
996 silc_server_perform_heartbeat,
999 /* Register re-key timeout */
1000 idata->rekey->timeout = param->key_exchange_rekey;
1001 idata->rekey->context = (void *)server;
1002 silc_schedule_task_add(server->schedule, sock->sock,
1003 silc_server_rekey_callback,
1004 (void *)sock, idata->rekey->timeout, 0,
1005 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1007 if (!sconn->backup) {
1008 /* Mark this router our primary router if we're still standalone */
1009 if (server->standalone) {
1010 server->id_entry->router = id_entry;
1011 server->router = id_entry;
1012 server->standalone = FALSE;
1014 /* If we are router then announce our possible servers. */
1015 if (server->server_type == SILC_ROUTER)
1016 silc_server_announce_servers(server, FALSE, 0,
1017 server->router->connection);
1019 /* Announce our clients and channels to the router */
1020 silc_server_announce_clients(server, 0, server->router->connection);
1021 silc_server_announce_channels(server, 0, server->router->connection);
1024 /* Add this server to be our backup router */
1025 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1026 sconn->backup_replace_port, FALSE);
1029 sock->protocol = NULL;
1031 /* Call the completion callback to indicate that we've connected to
1033 if (sconn->callback)
1034 (*sconn->callback)(server, id_entry, sconn->callback_context);
1037 /* Free the temporary connection data context */
1039 silc_server_config_unref(&sconn->conn);
1040 silc_free(sconn->remote_host);
1041 silc_free(sconn->backup_replace_ip);
1044 if (sconn == server->router_conn)
1045 server->router_conn = NULL;
1047 /* Free the protocol object */
1048 if (sock->protocol == protocol)
1049 sock->protocol = NULL;
1050 silc_protocol_free(protocol);
1052 silc_packet_context_free(ctx->packet);
1054 silc_ske_free(ctx->ske);
1055 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1056 silc_free(ctx->auth_data);
1060 /* Host lookup callback that is called after the incoming connection's
1061 IP and FQDN lookup is performed. This will actually check the acceptance
1062 of the incoming connection and will register the key exchange protocol
1063 for this connection. */
1066 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1069 SilcServer server = (SilcServer)context;
1070 SilcServerKEInternalContext *proto_ctx;
1071 SilcServerConfigClient *cconfig = NULL;
1072 SilcServerConfigServer *sconfig = NULL;
1073 SilcServerConfigRouter *rconfig = NULL;
1074 SilcServerConfigDeny *deny;
1077 SILC_LOG_DEBUG(("Start"));
1079 /* Check whether we could resolve both IP and FQDN. */
1080 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1081 server->config->require_reverse_lookup)) {
1082 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1083 sock->hostname ? sock->hostname :
1084 sock->ip ? sock->ip : ""));
1085 server->stat.conn_failures++;
1086 silc_server_disconnect_remote(server, sock,
1087 "Server closed connection: Unknown host");
1091 /* Register the connection for network input and output. This sets
1092 that scheduler will listen for incoming packets for this connection
1093 and sets that outgoing packets may be sent to this connection as well.
1094 However, this doesn't set the scheduler for outgoing traffic, it
1095 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1096 later when outgoing data is available. */
1097 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1099 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1102 port = server->sockets[server->sock]->port; /* Listenning port */
1104 /* Check whether this connection is denied to connect to us. */
1105 deny = silc_server_config_find_denied(server, sock->ip);
1107 deny = silc_server_config_find_denied(server, sock->hostname);
1109 /* The connection is denied */
1110 SILC_LOG_INFO(("Connection %s (%s) is denied",
1111 sock->hostname, sock->ip));
1112 silc_server_disconnect_remote(server, sock, deny->reason ?
1114 "Server closed connection: "
1115 "Connection refused");
1116 server->stat.conn_failures++;
1120 /* Check whether we have configured this sort of connection at all. We
1121 have to check all configurations since we don't know what type of
1122 connection this is. */
1123 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1124 cconfig = silc_server_config_find_client(server, sock->hostname);
1125 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1126 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1127 if (server->server_type == SILC_ROUTER) {
1128 if (!(rconfig = silc_server_config_find_router_conn(server,
1130 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1133 if (!cconfig && !sconfig && !rconfig) {
1134 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1136 silc_server_disconnect_remote(server, sock,
1137 "Server closed connection: "
1138 "Connection refused");
1139 server->stat.conn_failures++;
1143 /* The connection is allowed */
1145 /* Allocate internal context for key exchange protocol. This is
1146 sent as context for the protocol. */
1147 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1148 proto_ctx->server = context;
1149 proto_ctx->sock = sock;
1150 proto_ctx->rng = server->rng;
1151 proto_ctx->responder = TRUE;
1152 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1153 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1154 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1156 /* Take flags for key exchange. Since we do not know what type of connection
1157 this is, we go through all found configurations and use the global ones
1158 as well. This will result always into strictest key exchange flags. */
1159 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1160 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1161 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1162 if (server->config->param.key_exchange_pfs)
1163 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1165 /* Prepare the connection for key exchange protocol. We allocate the
1166 protocol but will not start it yet. The connector will be the
1167 initiator of the protocol thus we will wait for initiation from
1168 there before we start the protocol. */
1169 server->stat.auth_attempts++;
1170 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1171 &sock->protocol, proto_ctx,
1172 silc_server_accept_new_connection_second);
1174 /* Register a timeout task that will be executed if the connector
1175 will not start the key exchange protocol within specified timeout
1176 and the connection will be closed. */
1177 proto_ctx->timeout_task =
1178 silc_schedule_task_add(server->schedule, sock->sock,
1179 silc_server_timeout_remote,
1180 context, server->config->key_exchange_timeout, 0,
1185 /* Accepts new connections to the server. Accepting new connections are
1186 done in three parts to make it async. */
1188 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1190 SilcServer server = (SilcServer)context;
1191 SilcSocketConnection newsocket;
1194 SILC_LOG_DEBUG(("Accepting new connection"));
1196 server->stat.conn_attempts++;
1198 sock = silc_net_accept_connection(server->sock);
1200 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1201 server->stat.conn_failures++;
1205 /* Check for maximum allowed connections */
1206 if (sock > server->config->param.connections_max) {
1207 SILC_LOG_ERROR(("Refusing connection, server is full"));
1208 server->stat.conn_failures++;
1209 silc_net_close_connection(sock);
1213 /* Set socket options */
1214 silc_net_set_socket_nonblock(sock);
1215 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1217 /* We don't create a ID yet, since we don't know what type of connection
1218 this is yet. But, we do add the connection to the socket table. */
1219 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1220 server->sockets[sock] = newsocket;
1222 /* Perform asynchronous host lookup. This will lookup the IP and the
1223 FQDN of the remote connection. After the lookup is done the connection
1224 is accepted further. */
1225 silc_socket_host_lookup(newsocket, TRUE,
1226 silc_server_accept_new_connection_lookup, context,
1230 /* Second part of accepting new connection. Key exchange protocol has been
1231 performed and now it is time to do little connection authentication
1232 protocol to figure out whether this connection is client or server
1233 and whether it has right to access this server (especially server
1234 connections needs to be authenticated). */
1236 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1238 SilcProtocol protocol = (SilcProtocol)context;
1239 SilcServerKEInternalContext *ctx =
1240 (SilcServerKEInternalContext *)protocol->context;
1241 SilcServer server = (SilcServer)ctx->server;
1242 SilcSocketConnection sock = ctx->sock;
1243 SilcServerConnAuthInternalContext *proto_ctx;
1245 SILC_LOG_DEBUG(("Start"));
1247 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1248 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1249 /* Error occured during protocol */
1250 silc_protocol_free(protocol);
1251 sock->protocol = NULL;
1252 silc_ske_free_key_material(ctx->keymat);
1254 silc_packet_context_free(ctx->packet);
1256 silc_ske_free(ctx->ske);
1257 silc_free(ctx->dest_id);
1258 silc_server_config_unref(&ctx->cconfig);
1259 silc_server_config_unref(&ctx->sconfig);
1260 silc_server_config_unref(&ctx->rconfig);
1262 silc_schedule_task_del_by_callback(server->schedule,
1263 silc_server_failure_callback);
1264 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1265 "Key exchange failed");
1266 server->stat.auth_failures++;
1270 /* We now have the key material as the result of the key exchange
1271 protocol. Take the key material into use. Free the raw key material
1272 as soon as we've set them into use. */
1273 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1274 ctx->sock, ctx->keymat,
1275 ctx->ske->prop->cipher,
1276 ctx->ske->prop->pkcs,
1277 ctx->ske->prop->hash,
1278 ctx->ske->prop->hmac,
1279 ctx->ske->prop->group,
1281 silc_protocol_free(protocol);
1282 sock->protocol = NULL;
1283 silc_ske_free_key_material(ctx->keymat);
1285 silc_packet_context_free(ctx->packet);
1287 silc_ske_free(ctx->ske);
1288 silc_free(ctx->dest_id);
1289 silc_server_config_unref(&ctx->cconfig);
1290 silc_server_config_unref(&ctx->sconfig);
1291 silc_server_config_unref(&ctx->rconfig);
1293 silc_schedule_task_del_by_callback(server->schedule,
1294 silc_server_failure_callback);
1295 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1296 "Key exchange failed");
1297 server->stat.auth_failures++;
1300 silc_ske_free_key_material(ctx->keymat);
1302 /* Allocate internal context for the authentication protocol. This
1303 is sent as context for the protocol. */
1304 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1305 proto_ctx->server = (void *)server;
1306 proto_ctx->sock = sock;
1307 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1308 proto_ctx->responder = TRUE;
1309 proto_ctx->dest_id_type = ctx->dest_id_type;
1310 proto_ctx->dest_id = ctx->dest_id;
1311 proto_ctx->cconfig = ctx->cconfig;
1312 proto_ctx->sconfig = ctx->sconfig;
1313 proto_ctx->rconfig = ctx->rconfig;
1315 /* Free old protocol as it is finished now */
1316 silc_protocol_free(protocol);
1318 silc_packet_context_free(ctx->packet);
1320 sock->protocol = NULL;
1322 /* Allocate the authentication protocol. This is allocated here
1323 but we won't start it yet. We will be receiving party of this
1324 protocol thus we will wait that connecting party will make
1325 their first move. */
1326 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1327 &sock->protocol, proto_ctx,
1328 silc_server_accept_new_connection_final);
1330 /* Register timeout task. If the protocol is not executed inside
1331 this timelimit the connection will be terminated. */
1332 proto_ctx->timeout_task =
1333 silc_schedule_task_add(server->schedule, sock->sock,
1334 silc_server_timeout_remote,
1336 server->config->conn_auth_timeout, 0,
1341 /* Final part of accepting new connection. The connection has now
1342 been authenticated and keys has been exchanged. We also know whether
1343 this is client or server connection. */
1345 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1347 SilcProtocol protocol = (SilcProtocol)context;
1348 SilcServerConnAuthInternalContext *ctx =
1349 (SilcServerConnAuthInternalContext *)protocol->context;
1350 SilcServer server = (SilcServer)ctx->server;
1351 SilcSocketConnection sock = ctx->sock;
1352 SilcServerHBContext hb_context;
1353 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1355 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1357 SILC_LOG_DEBUG(("Start"));
1359 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1360 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1361 /* Error occured during protocol */
1362 silc_protocol_free(protocol);
1363 sock->protocol = NULL;
1365 silc_packet_context_free(ctx->packet);
1367 silc_ske_free(ctx->ske);
1368 silc_free(ctx->dest_id);
1369 silc_server_config_unref(&ctx->cconfig);
1370 silc_server_config_unref(&ctx->sconfig);
1371 silc_server_config_unref(&ctx->rconfig);
1373 silc_schedule_task_del_by_callback(server->schedule,
1374 silc_server_failure_callback);
1375 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1376 "Authentication failed");
1377 server->stat.auth_failures++;
1381 entry->data.last_receive = time(NULL);
1383 switch (ctx->conn_type) {
1384 case SILC_SOCKET_TYPE_CLIENT:
1386 SilcClientEntry client;
1387 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1389 /* Verify whether this connection is after all allowed to connect */
1390 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1391 &server->config->param,
1392 conn->param, ctx->ske)) {
1393 server->stat.auth_failures++;
1397 SILC_LOG_DEBUG(("Remote host is client"));
1398 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1401 /* Add the client to the client ID cache. The nickname and Client ID
1402 and other information is created after we have received NEW_CLIENT
1403 packet from client. */
1404 client = silc_idlist_add_client(server->local_list,
1405 NULL, NULL, NULL, NULL, NULL, sock, 0);
1407 SILC_LOG_ERROR(("Could not add new client to cache"));
1408 silc_free(sock->user_data);
1409 silc_server_disconnect_remote(server, sock,
1410 "Server closed connection: "
1411 "Authentication failed");
1412 server->stat.auth_failures++;
1417 server->stat.my_clients++;
1418 server->stat.clients++;
1419 if (server->server_type == SILC_ROUTER)
1420 server->stat.cell_clients++;
1422 /* Get connection parameters */
1424 if (conn->param->keepalive_secs)
1425 hearbeat_timeout = conn->param->keepalive_secs;
1428 id_entry = (void *)client;
1431 case SILC_SOCKET_TYPE_SERVER:
1432 case SILC_SOCKET_TYPE_ROUTER:
1434 SilcServerEntry new_server;
1435 bool initiator = FALSE;
1436 bool backup_local = FALSE;
1437 bool backup_router = FALSE;
1438 char *backup_replace_ip = NULL;
1439 SilcUInt16 backup_replace_port = 0;
1440 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1441 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1443 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1444 /* Verify whether this connection is after all allowed to connect */
1445 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1446 &server->config->param,
1447 rconn ? rconn->param : NULL,
1449 server->stat.auth_failures++;
1455 if (rconn->param->keepalive_secs)
1456 hearbeat_timeout = rconn->param->keepalive_secs;
1459 initiator = rconn->initiator;
1460 backup_local = rconn->backup_local;
1461 backup_router = rconn->backup_router;
1462 backup_replace_ip = rconn->backup_replace_ip;
1463 backup_replace_port = rconn->backup_replace_port;
1467 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1468 /* Verify whether this connection is after all allowed to connect */
1469 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1470 &server->config->param,
1471 sconn ? sconn->param : NULL,
1473 server->stat.auth_failures++;
1478 if (sconn->param->keepalive_secs)
1479 hearbeat_timeout = sconn->param->keepalive_secs;
1482 backup_router = sconn->backup_router;
1486 SILC_LOG_DEBUG(("Remote host is %s",
1487 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1488 "server" : (backup_router ?
1489 "backup router" : "router")));
1490 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1491 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1492 "server" : (backup_router ?
1493 "backup router" : "router")));
1495 /* Add the server into server cache. The server name and Server ID
1496 is updated after we have received NEW_SERVER packet from the
1497 server. We mark ourselves as router for this server if we really
1500 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1501 server->local_list : (backup_router ?
1502 server->local_list :
1503 server->global_list)),
1505 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1506 SILC_SERVER : SILC_ROUTER),
1508 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1509 server->id_entry : (backup_router ?
1510 server->id_entry : NULL)),
1513 SILC_LOG_ERROR(("Could not add new server to cache"));
1514 silc_free(sock->user_data);
1515 silc_server_disconnect_remote(server, sock,
1516 "Server closed connection: "
1517 "Authentication failed");
1518 server->stat.auth_failures++;
1523 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1524 server->stat.my_servers++;
1526 server->stat.my_routers++;
1527 server->stat.servers++;
1529 id_entry = (void *)new_server;
1531 /* If the incoming connection is router and marked as backup router
1532 then add it to be one of our backups */
1533 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1534 silc_server_backup_add(server, new_server, backup_replace_ip,
1535 backup_replace_port, backup_local);
1537 /* Change it back to SERVER type since that's what it really is. */
1539 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1541 new_server->server_type = SILC_BACKUP_ROUTER;
1544 /* Check whether this connection is to be our primary router connection
1545 if we do not already have the primary route. */
1546 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1547 if (silc_server_config_is_primary_route(server) && !initiator)
1550 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1551 server->standalone = FALSE;
1552 if (!server->id_entry->router) {
1553 server->id_entry->router = id_entry;
1554 server->router = id_entry;
1565 sock->type = ctx->conn_type;
1567 /* Add the common data structure to the ID entry. */
1568 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1570 /* Add to sockets internal pointer for fast referencing */
1571 silc_free(sock->user_data);
1572 sock->user_data = id_entry;
1574 /* Connection has been fully established now. Everything is ok. */
1575 SILC_LOG_DEBUG(("New connection authenticated"));
1577 /* Perform keepalive. The `hb_context' will be freed automatically
1578 when finally calling the silc_socket_free function. */
1579 hb_context = silc_calloc(1, sizeof(*hb_context));
1580 hb_context->server = server;
1581 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1582 silc_server_perform_heartbeat,
1586 silc_schedule_task_del_by_callback(server->schedule,
1587 silc_server_failure_callback);
1588 silc_protocol_free(protocol);
1590 silc_packet_context_free(ctx->packet);
1592 silc_ske_free(ctx->ske);
1593 silc_free(ctx->dest_id);
1594 silc_server_config_unref(&ctx->cconfig);
1595 silc_server_config_unref(&ctx->sconfig);
1596 silc_server_config_unref(&ctx->rconfig);
1598 sock->protocol = NULL;
1601 /* This function is used to read packets from network and send packets to
1602 network. This is usually a generic task. */
1604 SILC_TASK_CALLBACK(silc_server_packet_process)
1606 SilcServer server = (SilcServer)context;
1607 SilcSocketConnection sock = server->sockets[fd];
1608 SilcIDListData idata;
1609 SilcCipher cipher = NULL;
1610 SilcHmac hmac = NULL;
1611 SilcUInt32 sequence = 0;
1617 SILC_LOG_DEBUG(("Processing packet"));
1619 /* Packet sending */
1621 if (type == SILC_TASK_WRITE) {
1622 /* Do not send data to disconnected connection */
1623 if (SILC_IS_DISCONNECTED(sock))
1626 server->stat.packets_sent++;
1628 /* Send the packet */
1629 ret = silc_packet_send(sock, TRUE);
1631 /* If returned -2 could not write to connection now, will do
1637 SILC_LOG_ERROR(("Error sending packet to connection "
1638 "%s:%d [%s]", sock->hostname, sock->port,
1639 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1640 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1641 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1646 /* The packet has been sent and now it is time to set the connection
1647 back to only for input. When there is again some outgoing data
1648 available for this connection it will be set for output as well.
1649 This call clears the output setting and sets it only for input. */
1650 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1651 SILC_UNSET_OUTBUF_PENDING(sock);
1653 silc_buffer_clear(sock->outbuf);
1657 /* Packet receiving */
1659 /* Read some data from connection */
1660 ret = silc_packet_receive(sock);
1664 SILC_LOG_ERROR(("Error receiving packet from connection "
1665 "%s:%d [%s] %s", sock->hostname, sock->port,
1666 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1667 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1668 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1669 "Router"), strerror(errno)));
1675 SILC_LOG_DEBUG(("Read EOF"));
1677 /* If connection is disconnecting already we will finally
1678 close the connection */
1679 if (SILC_IS_DISCONNECTING(sock)) {
1680 if (sock->user_data)
1681 silc_server_free_sock_user_data(server, sock, NULL);
1682 silc_server_close_connection(server, sock);
1686 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1687 SILC_SET_DISCONNECTING(sock);
1689 if (sock->user_data) {
1691 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1692 silc_server_free_sock_user_data(server, sock, tmp);
1694 silc_server_free_sock_user_data(server, sock, NULL);
1695 } else if (server->router_conn && server->router_conn->sock == sock &&
1696 !server->router && server->standalone)
1697 silc_schedule_task_add(server->schedule, 0,
1698 silc_server_connect_to_router,
1701 SILC_TASK_PRI_NORMAL);
1703 silc_server_close_connection(server, sock);
1707 /* If connection is disconnecting or disconnected we will ignore
1709 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1710 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1714 server->stat.packets_received++;
1716 /* Get keys and stuff from ID entry */
1717 idata = (SilcIDListData)sock->user_data;
1719 cipher = idata->receive_key;
1720 hmac = idata->hmac_receive;
1721 sequence = idata->psn_receive;
1724 /* Process the packet. This will call the parser that will then
1725 decrypt and parse the packet. */
1726 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1727 TRUE : FALSE, cipher, hmac, sequence,
1728 silc_server_packet_parse, server);
1730 /* If this socket connection is not authenticated yet and the packet
1731 processing failed we will drop the connection since it can be
1732 a malicious flooder. */
1733 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1734 (!sock->protocol || sock->protocol->protocol->type ==
1735 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1736 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1737 SILC_SET_DISCONNECTING(sock);
1739 if (sock->user_data)
1740 silc_server_free_sock_user_data(server, sock, NULL);
1741 silc_server_close_connection(server, sock);
1745 /* Parses whole packet, received earlier. */
1747 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1749 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1750 SilcServer server = (SilcServer)parse_ctx->context;
1751 SilcSocketConnection sock = parse_ctx->sock;
1752 SilcPacketContext *packet = parse_ctx->packet;
1753 SilcIDListData idata = (SilcIDListData)sock->user_data;
1756 SILC_LOG_DEBUG(("Start"));
1758 /* Parse the packet */
1759 if (parse_ctx->normal)
1760 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1762 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1764 /* If entry is disabled ignore what we got. */
1765 if (ret != SILC_PACKET_RESUME_ROUTER &&
1766 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1767 SILC_LOG_DEBUG(("Connection is disabled"));
1771 if (ret == SILC_PACKET_NONE)
1774 /* Check that the the current client ID is same as in the client's packet. */
1775 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1776 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1777 if (client && client->id) {
1778 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1779 packet->src_id_type);
1780 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1788 if (server->server_type == SILC_ROUTER) {
1789 /* Route the packet if it is not destined to us. Other ID types but
1790 server are handled separately after processing them. */
1791 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1792 packet->dst_id_type == SILC_ID_SERVER &&
1793 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1794 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1796 /* Route the packet to fastest route for the destination ID */
1797 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1798 packet->dst_id_type);
1801 silc_server_packet_route(server,
1802 silc_server_route_get(server, id,
1803 packet->dst_id_type),
1810 /* Parse the incoming packet type */
1811 silc_server_packet_parse_type(server, sock, packet);
1813 if (server->server_type == SILC_ROUTER) {
1814 /* Broadcast packet if it is marked as broadcast packet and it is
1815 originated from router and we are router. */
1816 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1817 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1818 !server->standalone) {
1819 /* Broadcast to our primary route */
1820 silc_server_packet_broadcast(server, server->router->connection, packet);
1822 /* If we have backup routers then we need to feed all broadcast
1823 data to those servers. */
1824 silc_server_backup_broadcast(server, sock, packet);
1829 silc_packet_context_free(packet);
1830 silc_free(parse_ctx);
1833 /* Parser callback called by silc_packet_receive_process. This merely
1834 registers timeout that will handle the actual parsing when appropriate. */
1836 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1839 SilcServer server = (SilcServer)context;
1840 SilcSocketConnection sock = parser_context->sock;
1841 SilcIDListData idata = (SilcIDListData)sock->user_data;
1844 idata->psn_receive = parser_context->packet->sequence + 1;
1846 /* If protocol for this connection is key exchange or rekey then we'll
1847 process all packets synchronously, since there might be packets in
1848 queue that we are not able to decrypt without first processing the
1849 packets before them. */
1850 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1851 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1852 (sock->protocol && sock->protocol->protocol &&
1853 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1854 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1855 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1858 /* Reprocess data since we'll return FALSE here. This is because
1859 the idata->receive_key might have become valid in the last packet
1860 and we want to call this processor with valid cipher. */
1862 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1863 TRUE : FALSE, idata->receive_key,
1864 idata->hmac_receive, idata->psn_receive,
1865 silc_server_packet_parse, server);
1867 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1868 TRUE : FALSE, NULL, NULL, 0,
1869 silc_server_packet_parse, server);
1873 switch (sock->type) {
1874 case SILC_SOCKET_TYPE_UNKNOWN:
1875 case SILC_SOCKET_TYPE_CLIENT:
1876 /* Parse the packet with timeout */
1877 silc_schedule_task_add(server->schedule, sock->sock,
1878 silc_server_packet_parse_real,
1879 (void *)parser_context, 0, 100000,
1881 SILC_TASK_PRI_NORMAL);
1883 case SILC_SOCKET_TYPE_SERVER:
1884 case SILC_SOCKET_TYPE_ROUTER:
1885 /* Packets from servers are parsed immediately */
1886 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1896 /* Parses the packet type and calls what ever routines the packet type
1897 requires. This is done for all incoming packets. */
1899 void silc_server_packet_parse_type(SilcServer server,
1900 SilcSocketConnection sock,
1901 SilcPacketContext *packet)
1903 SilcPacketType type = packet->type;
1904 SilcIDListData idata = (SilcIDListData)sock->user_data;
1906 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1908 /* Parse the packet type */
1910 case SILC_PACKET_DISCONNECT:
1911 SILC_LOG_DEBUG(("Disconnect packet"));
1912 if (packet->flags & SILC_PACKET_FLAG_LIST)
1914 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1915 /* Duplicate to null terminate the string. */
1916 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1917 SILC_LOG_ERROR(("%s", message));
1922 case SILC_PACKET_SUCCESS:
1924 * Success received for something. For now we can have only
1925 * one protocol for connection executing at once hence this
1926 * success message is for whatever protocol is executing currently.
1928 SILC_LOG_DEBUG(("Success packet"));
1929 if (packet->flags & SILC_PACKET_FLAG_LIST)
1932 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1935 case SILC_PACKET_FAILURE:
1937 * Failure received for something. For now we can have only
1938 * one protocol for connection executing at once hence this
1939 * failure message is for whatever protocol is executing currently.
1941 SILC_LOG_DEBUG(("Failure packet"));
1942 if (packet->flags & SILC_PACKET_FLAG_LIST)
1944 if (sock->protocol) {
1945 SilcServerFailureContext f;
1946 f = silc_calloc(1, sizeof(*f));
1950 /* We will wait 5 seconds to process this failure packet */
1951 silc_schedule_task_add(server->schedule, sock->sock,
1952 silc_server_failure_callback, (void *)f, 5, 0,
1953 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1957 case SILC_PACKET_REJECT:
1958 SILC_LOG_DEBUG(("Reject packet"));
1959 if (packet->flags & SILC_PACKET_FLAG_LIST)
1964 case SILC_PACKET_NOTIFY:
1966 * Received notify packet. Server can receive notify packets from
1967 * router. Server then relays the notify messages to clients if needed.
1969 SILC_LOG_DEBUG(("Notify packet"));
1970 if (packet->flags & SILC_PACKET_FLAG_LIST)
1971 silc_server_notify_list(server, sock, packet);
1973 silc_server_notify(server, sock, packet);
1979 case SILC_PACKET_CHANNEL_MESSAGE:
1981 * Received channel message. Channel messages are special packets
1982 * (although probably most common ones) thus they are handled
1985 SILC_LOG_DEBUG(("Channel Message packet"));
1986 if (packet->flags & SILC_PACKET_FLAG_LIST)
1988 idata->last_receive = time(NULL);
1989 silc_server_channel_message(server, sock, packet);
1992 case SILC_PACKET_CHANNEL_KEY:
1994 * Received key for channel. As channels are created by the router
1995 * the keys are as well. We will distribute the key to all of our
1996 * locally connected clients on the particular channel. Router
1997 * never receives this channel and thus is ignored.
1999 SILC_LOG_DEBUG(("Channel Key packet"));
2000 if (packet->flags & SILC_PACKET_FLAG_LIST)
2002 silc_server_channel_key(server, sock, packet);
2008 case SILC_PACKET_COMMAND:
2010 * Recived command. Processes the command request and allocates the
2011 * command context and calls the command.
2013 SILC_LOG_DEBUG(("Command packet"));
2014 if (packet->flags & SILC_PACKET_FLAG_LIST)
2016 silc_server_command_process(server, sock, packet);
2019 case SILC_PACKET_COMMAND_REPLY:
2021 * Received command reply packet. Received command reply to command. It
2022 * may be reply to command sent by us or reply to command sent by client
2023 * that we've routed further.
2025 SILC_LOG_DEBUG(("Command Reply packet"));
2026 if (packet->flags & SILC_PACKET_FLAG_LIST)
2028 silc_server_command_reply(server, sock, packet);
2032 * Private Message packets
2034 case SILC_PACKET_PRIVATE_MESSAGE:
2036 * Received private message packet. The packet is coming from either
2039 SILC_LOG_DEBUG(("Private Message packet"));
2040 if (packet->flags & SILC_PACKET_FLAG_LIST)
2042 idata->last_receive = time(NULL);
2043 silc_server_private_message(server, sock, packet);
2046 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2048 * Private message key packet.
2050 if (packet->flags & SILC_PACKET_FLAG_LIST)
2052 silc_server_private_message_key(server, sock, packet);
2056 * Key Exchange protocol packets
2058 case SILC_PACKET_KEY_EXCHANGE:
2059 SILC_LOG_DEBUG(("KE packet"));
2060 if (packet->flags & SILC_PACKET_FLAG_LIST)
2063 if (sock->protocol && sock->protocol->protocol &&
2064 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2065 SilcServerKEInternalContext *proto_ctx =
2066 (SilcServerKEInternalContext *)sock->protocol->context;
2068 proto_ctx->packet = silc_packet_context_dup(packet);
2070 /* Let the protocol handle the packet */
2071 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2073 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2074 "protocol active, packet dropped."));
2078 case SILC_PACKET_KEY_EXCHANGE_1:
2079 SILC_LOG_DEBUG(("KE 1 packet"));
2080 if (packet->flags & SILC_PACKET_FLAG_LIST)
2083 if (sock->protocol && sock->protocol->protocol &&
2084 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2085 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2087 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2088 SilcServerRekeyInternalContext *proto_ctx =
2089 (SilcServerRekeyInternalContext *)sock->protocol->context;
2091 if (proto_ctx->packet)
2092 silc_packet_context_free(proto_ctx->packet);
2094 proto_ctx->packet = silc_packet_context_dup(packet);
2096 /* Let the protocol handle the packet */
2097 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2099 SilcServerKEInternalContext *proto_ctx =
2100 (SilcServerKEInternalContext *)sock->protocol->context;
2102 if (proto_ctx->packet)
2103 silc_packet_context_free(proto_ctx->packet);
2105 proto_ctx->packet = silc_packet_context_dup(packet);
2106 proto_ctx->dest_id_type = packet->src_id_type;
2107 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2108 packet->src_id_type);
2109 if (!proto_ctx->dest_id)
2112 /* Let the protocol handle the packet */
2113 silc_protocol_execute(sock->protocol, server->schedule,
2117 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2118 "protocol active, packet dropped."));
2122 case SILC_PACKET_KEY_EXCHANGE_2:
2123 SILC_LOG_DEBUG(("KE 2 packet"));
2124 if (packet->flags & SILC_PACKET_FLAG_LIST)
2127 if (sock->protocol && sock->protocol->protocol &&
2128 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2129 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2131 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2132 SilcServerRekeyInternalContext *proto_ctx =
2133 (SilcServerRekeyInternalContext *)sock->protocol->context;
2135 if (proto_ctx->packet)
2136 silc_packet_context_free(proto_ctx->packet);
2138 proto_ctx->packet = silc_packet_context_dup(packet);
2140 /* Let the protocol handle the packet */
2141 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2143 SilcServerKEInternalContext *proto_ctx =
2144 (SilcServerKEInternalContext *)sock->protocol->context;
2146 if (proto_ctx->packet)
2147 silc_packet_context_free(proto_ctx->packet);
2149 proto_ctx->packet = silc_packet_context_dup(packet);
2150 proto_ctx->dest_id_type = packet->src_id_type;
2151 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2152 packet->src_id_type);
2153 if (!proto_ctx->dest_id)
2156 /* Let the protocol handle the packet */
2157 silc_protocol_execute(sock->protocol, server->schedule,
2161 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2162 "protocol active, packet dropped."));
2166 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2168 * Connection authentication request packet. When we receive this packet
2169 * we will send to the other end information about our mandatory
2170 * authentication method for the connection. This packet maybe received
2173 SILC_LOG_DEBUG(("Connection authentication request packet"));
2174 if (packet->flags & SILC_PACKET_FLAG_LIST)
2176 silc_server_connection_auth_request(server, sock, packet);
2180 * Connection Authentication protocol packets
2182 case SILC_PACKET_CONNECTION_AUTH:
2183 /* Start of the authentication protocol. We receive here the
2184 authentication data and will verify it. */
2185 SILC_LOG_DEBUG(("Connection auth packet"));
2186 if (packet->flags & SILC_PACKET_FLAG_LIST)
2189 if (sock->protocol && sock->protocol->protocol->type
2190 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2192 SilcServerConnAuthInternalContext *proto_ctx =
2193 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2195 proto_ctx->packet = silc_packet_context_dup(packet);
2197 /* Let the protocol handle the packet */
2198 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2200 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2201 "protocol active, packet dropped."));
2205 case SILC_PACKET_NEW_ID:
2207 * Received New ID packet. This includes some new ID that has been
2208 * created. It may be for client, server or channel. This is the way
2209 * to distribute information about new registered entities in the
2212 SILC_LOG_DEBUG(("New ID packet"));
2213 if (packet->flags & SILC_PACKET_FLAG_LIST)
2214 silc_server_new_id_list(server, sock, packet);
2216 silc_server_new_id(server, sock, packet);
2219 case SILC_PACKET_NEW_CLIENT:
2221 * Received new client packet. This includes client information that
2222 * we will use to create initial client ID. After creating new
2223 * ID we will send it to the client.
2225 SILC_LOG_DEBUG(("New Client packet"));
2226 if (packet->flags & SILC_PACKET_FLAG_LIST)
2228 silc_server_new_client(server, sock, packet);
2231 case SILC_PACKET_NEW_SERVER:
2233 * Received new server packet. This includes Server ID and some other
2234 * information that we may save. This is received after server has
2237 SILC_LOG_DEBUG(("New Server packet"));
2238 if (packet->flags & SILC_PACKET_FLAG_LIST)
2240 silc_server_new_server(server, sock, packet);
2243 case SILC_PACKET_NEW_CHANNEL:
2245 * Received new channel packet. Information about new channel in the
2246 * network are distributed using this packet.
2248 SILC_LOG_DEBUG(("New Channel packet"));
2249 if (packet->flags & SILC_PACKET_FLAG_LIST)
2250 silc_server_new_channel_list(server, sock, packet);
2252 silc_server_new_channel(server, sock, packet);
2255 case SILC_PACKET_HEARTBEAT:
2257 * Received heartbeat.
2259 SILC_LOG_DEBUG(("Heartbeat packet"));
2260 if (packet->flags & SILC_PACKET_FLAG_LIST)
2264 case SILC_PACKET_KEY_AGREEMENT:
2266 * Received heartbeat.
2268 SILC_LOG_DEBUG(("Key agreement packet"));
2269 if (packet->flags & SILC_PACKET_FLAG_LIST)
2271 silc_server_key_agreement(server, sock, packet);
2274 case SILC_PACKET_REKEY:
2276 * Received re-key packet. The sender wants to regenerate the session
2279 SILC_LOG_DEBUG(("Re-key packet"));
2280 if (packet->flags & SILC_PACKET_FLAG_LIST)
2282 silc_server_rekey(server, sock, packet);
2285 case SILC_PACKET_REKEY_DONE:
2287 * The re-key is done.
2289 SILC_LOG_DEBUG(("Re-key done packet"));
2290 if (packet->flags & SILC_PACKET_FLAG_LIST)
2293 if (sock->protocol && sock->protocol->protocol &&
2294 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2296 SilcServerRekeyInternalContext *proto_ctx =
2297 (SilcServerRekeyInternalContext *)sock->protocol->context;
2299 if (proto_ctx->packet)
2300 silc_packet_context_free(proto_ctx->packet);
2302 proto_ctx->packet = silc_packet_context_dup(packet);
2304 /* Let the protocol handle the packet */
2305 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2307 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2308 "protocol active, packet dropped."));
2312 case SILC_PACKET_FTP:
2314 SILC_LOG_DEBUG(("FTP packet"));
2315 if (packet->flags & SILC_PACKET_FLAG_LIST)
2317 silc_server_ftp(server, sock, packet);
2320 case SILC_PACKET_RESUME_ROUTER:
2321 /* Resume router packet received. This packet is received for backup
2322 router resuming protocol. */
2323 SILC_LOG_DEBUG(("Resume router packet"));
2324 if (packet->flags & SILC_PACKET_FLAG_LIST)
2326 silc_server_backup_resume_router(server, sock, packet);
2330 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2336 /* Creates connection to a remote router. */
2338 void silc_server_create_connection(SilcServer server,
2339 const char *remote_host, SilcUInt32 port)
2341 SilcServerConnection sconn;
2343 /* Allocate connection object for hold connection specific stuff. */
2344 sconn = silc_calloc(1, sizeof(*sconn));
2345 sconn->server = server;
2346 sconn->remote_host = strdup(remote_host);
2347 sconn->remote_port = port;
2348 sconn->no_reconnect = TRUE;
2350 silc_schedule_task_add(server->schedule, 0,
2351 silc_server_connect_router,
2352 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2353 SILC_TASK_PRI_NORMAL);
2356 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2358 silc_socket_free((SilcSocketConnection)context);
2361 /* Closes connection to socket connection */
2363 void silc_server_close_connection(SilcServer server,
2364 SilcSocketConnection sock)
2366 if (!server->sockets[sock->sock])
2369 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2371 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2372 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2373 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2376 /* We won't listen for this connection anymore */
2377 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2379 /* Unregister all tasks */
2380 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2382 /* Close the actual connection */
2383 silc_net_close_connection(sock->sock);
2384 server->sockets[sock->sock] = NULL;
2386 /* If sock->user_data is NULL then we'll check for active protocols
2387 here since the silc_server_free_sock_user_data has not been called
2388 for this connection. */
2389 if (!sock->user_data) {
2390 /* If any protocol is active cancel its execution. It will call
2391 the final callback which will finalize the disconnection. */
2392 if (sock->protocol) {
2393 silc_protocol_cancel(sock->protocol, server->schedule);
2394 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2395 silc_protocol_execute_final(sock->protocol, server->schedule);
2396 sock->protocol = NULL;
2401 silc_schedule_task_add(server->schedule, 0,
2402 silc_server_close_connection_final,
2403 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2404 SILC_TASK_PRI_NORMAL);
2407 /* Sends disconnect message to remote connection and disconnects the
2410 void silc_server_disconnect_remote(SilcServer server,
2411 SilcSocketConnection sock,
2412 const char *fmt, ...)
2415 unsigned char buf[4096];
2420 memset(buf, 0, sizeof(buf));
2422 vsprintf(buf, fmt, ap);
2425 SILC_LOG_DEBUG(("Disconnecting remote host"));
2427 /* Notify remote end that the conversation is over. The notify message
2428 is tried to be sent immediately. */
2429 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2430 buf, strlen(buf), TRUE);
2431 silc_server_packet_queue_purge(server, sock);
2433 /* Mark the connection to be disconnected */
2434 SILC_SET_DISCONNECTED(sock);
2435 silc_server_close_connection(server, sock);
2440 SilcClientEntry client;
2441 } *FreeClientInternal;
2443 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2445 FreeClientInternal i = (FreeClientInternal)context;
2447 silc_idlist_del_data(i->client);
2448 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2452 /* Frees client data and notifies about client's signoff. */
2454 void silc_server_free_client_data(SilcServer server,
2455 SilcSocketConnection sock,
2456 SilcClientEntry client,
2458 const char *signoff)
2460 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2462 /* If there is pending outgoing data for the client then purge it
2463 to the network before removing the client entry. */
2464 silc_server_packet_queue_purge(server, sock);
2469 /* Send SIGNOFF notify to routers. */
2470 if (notify && !server->standalone && server->router)
2471 silc_server_send_notify_signoff(server, server->router->connection,
2472 server->server_type == SILC_SERVER ?
2473 FALSE : TRUE, client->id, signoff);
2475 /* Remove client from all channels */
2477 silc_server_remove_from_channels(server, NULL, client,
2478 TRUE, (char *)signoff, TRUE);
2480 silc_server_remove_from_channels(server, NULL, client,
2481 FALSE, NULL, FALSE);
2483 /* Update statistics */
2484 server->stat.my_clients--;
2485 server->stat.clients--;
2486 if (server->server_type == SILC_ROUTER)
2487 server->stat.cell_clients--;
2488 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2489 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2491 /* We will not delete the client entry right away. We will take it
2492 into history (for WHOWAS command) for 5 minutes */
2495 silc_schedule_task_add(server->schedule, 0,
2496 silc_server_free_client_data_timeout,
2498 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2499 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2500 client->router = NULL;
2501 client->connection = NULL;
2505 /* Frees user_data pointer from socket connection object. This also sends
2506 appropriate notify packets to the network to inform about leaving
2509 void silc_server_free_sock_user_data(SilcServer server,
2510 SilcSocketConnection sock,
2511 const char *signoff_message)
2513 SILC_LOG_DEBUG(("Start"));
2515 switch (sock->type) {
2516 case SILC_SOCKET_TYPE_CLIENT:
2518 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2519 silc_server_free_client_data(server, sock, user_data, TRUE,
2523 case SILC_SOCKET_TYPE_SERVER:
2524 case SILC_SOCKET_TYPE_ROUTER:
2526 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2527 SilcServerEntry backup_router = NULL;
2530 backup_router = silc_server_backup_get(server, user_data->id);
2532 /* If this was our primary router connection then we're lost to
2533 the outside world. */
2534 if (server->router == user_data) {
2535 /* Check whether we have a backup router connection */
2536 if (!backup_router || backup_router == user_data) {
2537 silc_schedule_task_add(server->schedule, 0,
2538 silc_server_connect_to_router,
2541 SILC_TASK_PRI_NORMAL);
2543 server->id_entry->router = NULL;
2544 server->router = NULL;
2545 server->standalone = TRUE;
2546 backup_router = NULL;
2548 SILC_LOG_INFO(("New primary router is backup router %s",
2549 backup_router->server_name));
2550 SILC_LOG_DEBUG(("New primary router is backup router %s",
2551 backup_router->server_name));
2552 server->id_entry->router = backup_router;
2553 server->router = backup_router;
2554 server->router_connect = time(0);
2555 server->backup_primary = TRUE;
2556 if (server->server_type == SILC_BACKUP_ROUTER) {
2557 server->server_type = SILC_ROUTER;
2559 /* We'll need to constantly try to reconnect to the primary
2560 router so that we'll see when it comes back online. */
2561 silc_server_backup_reconnect(server, sock->ip, sock->port,
2562 silc_server_backup_connected,
2566 /* Mark this connection as replaced */
2567 silc_server_backup_replaced_add(server, user_data->id,
2570 } else if (backup_router) {
2571 SILC_LOG_INFO(("Enabling the use of backup router %s",
2572 backup_router->server_name));
2573 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2574 backup_router->server_name));
2576 /* Mark this connection as replaced */
2577 silc_server_backup_replaced_add(server, user_data->id,
2581 if (!backup_router) {
2582 /* Free all client entries that this server owns as they will
2583 become invalid now as well. */
2585 silc_server_remove_clients_by_server(server, user_data, TRUE);
2586 if (server->server_type == SILC_SERVER)
2587 silc_server_remove_channels_by_server(server, user_data);
2589 /* Update the client entries of this server to the new backup
2590 router. This also removes the clients that *really* was owned
2591 by the primary router and went down with the router. */
2592 silc_server_update_clients_by_server(server, user_data, backup_router,
2594 silc_server_update_servers_by_server(server, user_data, backup_router);
2595 if (server->server_type == SILC_SERVER)
2596 silc_server_update_channels_by_server(server, user_data,
2600 /* Free the server entry */
2601 silc_server_backup_del(server, user_data);
2602 silc_server_backup_replaced_del(server, user_data);
2603 silc_idlist_del_data(user_data);
2604 if (!silc_idlist_del_server(server->local_list, user_data))
2605 silc_idlist_del_server(server->global_list, user_data);
2606 server->stat.my_servers--;
2607 server->stat.servers--;
2608 if (server->server_type == SILC_ROUTER)
2609 server->stat.cell_servers--;
2611 if (backup_router) {
2612 /* Announce all of our stuff that was created about 5 minutes ago.
2613 The backup router knows all the other stuff already. */
2614 if (server->server_type == SILC_ROUTER)
2615 silc_server_announce_servers(server, FALSE, time(0) - 300,
2616 backup_router->connection);
2618 /* Announce our clients and channels to the router */
2619 silc_server_announce_clients(server, time(0) - 300,
2620 backup_router->connection);
2621 silc_server_announce_channels(server, time(0) - 300,
2622 backup_router->connection);
2628 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2630 silc_idlist_del_data(user_data);
2631 silc_free(user_data);
2636 /* If any protocol is active cancel its execution */
2637 if (sock->protocol) {
2638 silc_protocol_cancel(sock->protocol, server->schedule);
2639 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2640 silc_protocol_execute_final(sock->protocol, server->schedule);
2641 sock->protocol = NULL;
2644 sock->user_data = NULL;
2647 /* Removes client from all channels it has joined. This is used when client
2648 connection is disconnected. If the client on a channel is last, the
2649 channel is removed as well. This sends the SIGNOFF notify types. */
2651 void silc_server_remove_from_channels(SilcServer server,
2652 SilcSocketConnection sock,
2653 SilcClientEntry client,
2655 char *signoff_message,
2658 SilcChannelEntry channel;
2659 SilcChannelClientEntry chl;
2660 SilcHashTableList htl;
2663 SILC_LOG_DEBUG(("Start"));
2665 if (!client || !client->id)
2668 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2670 /* Remove the client from all channels. The client is removed from
2671 the channels' user list. */
2672 silc_hash_table_list(client->channels, &htl);
2673 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2674 channel = chl->channel;
2676 /* Remove channel from client's channel list */
2677 silc_hash_table_del(client->channels, channel);
2679 /* Remove channel if there is no users anymore */
2680 if (server->server_type == SILC_ROUTER &&
2681 silc_hash_table_count(channel->user_list) < 2) {
2683 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2684 if (silc_idlist_del_channel(server->local_list, channel))
2685 server->stat.my_channels--;
2687 silc_idlist_del_channel(server->global_list, channel);
2691 /* Remove client from channel's client list */
2692 silc_hash_table_del(channel->user_list, chl->client);
2693 channel->user_count--;
2695 /* If there is no global users on the channel anymore mark the channel
2696 as local channel. Do not check if the removed client is local client. */
2697 if (server->server_type != SILC_ROUTER && channel->global_users &&
2698 chl->client->router && !silc_server_channel_has_global(channel))
2699 channel->global_users = FALSE;
2702 server->stat.my_chanclients--;
2704 /* If there is not at least one local user on the channel then we don't
2705 need the channel entry anymore, we can remove it safely. */
2706 if (server->server_type != SILC_ROUTER &&
2707 !silc_server_channel_has_local(channel)) {
2708 /* Notify about leaving client if this channel has global users. */
2709 if (notify && channel->global_users)
2710 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2711 SILC_NOTIFY_TYPE_SIGNOFF,
2712 signoff_message ? 2 : 1,
2713 clidp->data, clidp->len,
2714 signoff_message, signoff_message ?
2715 strlen(signoff_message) : 0);
2718 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2720 if (channel->founder_key) {
2721 /* The founder auth data exists, do not remove the channel entry */
2722 SilcChannelClientEntry chl2;
2723 SilcHashTableList htl2;
2725 channel->disabled = TRUE;
2727 silc_hash_table_list(channel->user_list, &htl2);
2728 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2729 silc_hash_table_del(chl2->client->channels, channel);
2730 silc_hash_table_del(channel->user_list, chl2->client);
2731 channel->user_count--;
2734 silc_hash_table_list_reset(&htl2);
2738 /* Remove the channel entry */
2739 if (silc_idlist_del_channel(server->local_list, channel))
2740 server->stat.my_channels--;
2742 silc_idlist_del_channel(server->global_list, channel);
2746 /* Send notify to channel about client leaving SILC and thus
2747 the entire channel. */
2749 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2750 SILC_NOTIFY_TYPE_SIGNOFF,
2751 signoff_message ? 2 : 1,
2752 clidp->data, clidp->len,
2753 signoff_message, signoff_message ?
2754 strlen(signoff_message) : 0);
2756 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2757 /* Re-generate channel key */
2758 if (!silc_server_create_channel_key(server, channel, 0))
2761 /* Send the channel key to the channel. The key of course is not sent
2762 to the client who was removed from the channel. */
2763 silc_server_send_channel_key(server, client->connection, channel,
2764 server->server_type == SILC_ROUTER ?
2765 FALSE : !server->standalone);
2770 silc_hash_table_list_reset(&htl);
2771 silc_buffer_free(clidp);
2774 /* Removes client from one channel. This is used for example when client
2775 calls LEAVE command to remove itself from the channel. Returns TRUE
2776 if channel still exists and FALSE if the channel is removed when
2777 last client leaves the channel. If `notify' is FALSE notify messages
2780 int silc_server_remove_from_one_channel(SilcServer server,
2781 SilcSocketConnection sock,
2782 SilcChannelEntry channel,
2783 SilcClientEntry client,
2786 SilcChannelClientEntry chl;
2789 SILC_LOG_DEBUG(("Start"));
2791 /* Get the entry to the channel, if this client is not on the channel
2793 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2796 /* Remove the client from the channel. The client is removed from
2797 the channel's user list. */
2799 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2801 /* Remove channel from client's channel list */
2802 silc_hash_table_del(client->channels, chl->channel);
2804 /* Remove channel if there is no users anymore */
2805 if (server->server_type == SILC_ROUTER &&
2806 silc_hash_table_count(channel->user_list) < 2) {
2808 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2809 if (silc_idlist_del_channel(server->local_list, channel))
2810 server->stat.my_channels--;
2812 silc_idlist_del_channel(server->global_list, channel);
2813 silc_buffer_free(clidp);
2817 /* Remove client from channel's client list */
2818 silc_hash_table_del(channel->user_list, chl->client);
2819 channel->user_count--;
2821 /* If there is no global users on the channel anymore mark the channel
2822 as local channel. Do not check if the client is local client. */
2823 if (server->server_type != SILC_ROUTER && channel->global_users &&
2824 chl->client->router && !silc_server_channel_has_global(channel))
2825 channel->global_users = FALSE;
2828 server->stat.my_chanclients--;
2830 /* If there is not at least one local user on the channel then we don't
2831 need the channel entry anymore, we can remove it safely. */
2832 if (server->server_type != SILC_ROUTER &&
2833 !silc_server_channel_has_local(channel)) {
2834 /* Notify about leaving client if this channel has global users. */
2835 if (notify && channel->global_users)
2836 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2837 SILC_NOTIFY_TYPE_LEAVE, 1,
2838 clidp->data, clidp->len);
2840 silc_buffer_free(clidp);
2843 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2845 if (channel->founder_key) {
2846 /* The founder auth data exists, do not remove the channel entry */
2847 SilcChannelClientEntry chl2;
2848 SilcHashTableList htl2;
2850 channel->disabled = TRUE;
2852 silc_hash_table_list(channel->user_list, &htl2);
2853 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2854 silc_hash_table_del(chl2->client->channels, channel);
2855 silc_hash_table_del(channel->user_list, chl2->client);
2856 channel->user_count--;
2859 silc_hash_table_list_reset(&htl2);
2863 /* Remove the channel entry */
2864 if (silc_idlist_del_channel(server->local_list, channel))
2865 server->stat.my_channels--;
2867 silc_idlist_del_channel(server->global_list, channel);
2871 /* Send notify to channel about client leaving the channel */
2873 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2874 SILC_NOTIFY_TYPE_LEAVE, 1,
2875 clidp->data, clidp->len);
2877 silc_buffer_free(clidp);
2881 /* Timeout callback. This is called if connection is idle or for some
2882 other reason is not responding within some period of time. This
2883 disconnects the remote end. */
2885 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2887 SilcServer server = (SilcServer)context;
2888 SilcSocketConnection sock = server->sockets[fd];
2890 SILC_LOG_DEBUG(("Start"));
2895 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2896 sock->hostname, sock->ip));
2898 /* If we have protocol active we must assure that we call the protocol's
2899 final callback so that all the memory is freed. */
2900 if (sock->protocol) {
2901 silc_protocol_cancel(sock->protocol, server->schedule);
2902 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2903 silc_protocol_execute_final(sock->protocol, server->schedule);
2904 sock->protocol = NULL;
2908 if (sock->user_data)
2909 silc_server_free_sock_user_data(server, sock, NULL);
2911 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2912 "Connection timeout");
2915 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2916 function may be used only by router. In real SILC network all channels
2917 are created by routers thus this function is never used by normal
2920 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2921 SilcServerID *router_id,
2927 SilcChannelID *channel_id;
2928 SilcChannelEntry entry;
2932 SILC_LOG_DEBUG(("Creating new channel"));
2935 cipher = SILC_DEFAULT_CIPHER;
2937 hmac = SILC_DEFAULT_HMAC;
2939 /* Allocate cipher */
2940 if (!silc_cipher_alloc(cipher, &key))
2944 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2945 silc_cipher_free(key);
2949 channel_name = strdup(channel_name);
2951 /* Create the channel ID */
2952 if (!silc_id_create_channel_id(server, router_id, server->rng,
2954 silc_free(channel_name);
2955 silc_cipher_free(key);
2956 silc_hmac_free(newhmac);
2960 /* Create the channel */
2961 entry = silc_idlist_add_channel(server->local_list, channel_name,
2962 SILC_CHANNEL_MODE_NONE, channel_id,
2963 NULL, key, newhmac, 0);
2965 silc_free(channel_name);
2966 silc_cipher_free(key);
2967 silc_hmac_free(newhmac);
2968 silc_free(channel_id);
2972 entry->cipher = strdup(cipher);
2973 entry->hmac_name = strdup(hmac);
2975 /* Now create the actual key material */
2976 if (!silc_server_create_channel_key(server, entry,
2977 silc_cipher_get_key_len(key) / 8)) {
2978 silc_idlist_del_channel(server->local_list, entry);
2982 /* Notify other routers about the new channel. We send the packet
2983 to our primary route. */
2984 if (broadcast && server->standalone == FALSE)
2985 silc_server_send_new_channel(server, server->router->connection, TRUE,
2986 channel_name, entry->id,
2987 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2990 server->stat.my_channels++;
2995 /* Same as above but creates the channel with Channel ID `channel_id. */
2998 silc_server_create_new_channel_with_id(SilcServer server,
3002 SilcChannelID *channel_id,
3005 SilcChannelEntry entry;
3009 SILC_LOG_DEBUG(("Creating new channel"));
3012 cipher = SILC_DEFAULT_CIPHER;
3014 hmac = SILC_DEFAULT_HMAC;
3016 /* Allocate cipher */
3017 if (!silc_cipher_alloc(cipher, &key))
3021 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3022 silc_cipher_free(key);
3026 channel_name = strdup(channel_name);
3028 /* Create the channel */
3029 entry = silc_idlist_add_channel(server->local_list, channel_name,
3030 SILC_CHANNEL_MODE_NONE, channel_id,
3031 NULL, key, newhmac, 0);
3033 silc_cipher_free(key);
3034 silc_hmac_free(newhmac);
3035 silc_free(channel_name);
3039 /* Now create the actual key material */
3040 if (!silc_server_create_channel_key(server, entry,
3041 silc_cipher_get_key_len(key) / 8)) {
3042 silc_idlist_del_channel(server->local_list, entry);
3046 /* Notify other routers about the new channel. We send the packet
3047 to our primary route. */
3048 if (broadcast && server->standalone == FALSE)
3049 silc_server_send_new_channel(server, server->router->connection, TRUE,
3050 channel_name, entry->id,
3051 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3054 server->stat.my_channels++;
3059 /* Channel's key re-key timeout callback. */
3061 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3063 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3064 SilcServer server = (SilcServer)rekey->context;
3068 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3071 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3074 /* Generates new channel key. This is used to create the initial channel key
3075 but also to re-generate new key for channel. If `key_len' is provided
3076 it is the bytes of the key length. */
3078 bool silc_server_create_channel_key(SilcServer server,
3079 SilcChannelEntry channel,
3083 unsigned char channel_key[32], hash[32];
3086 SILC_LOG_DEBUG(("Generating channel key"));
3088 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3089 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3093 if (!channel->channel_key)
3094 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3095 channel->channel_key = NULL;
3101 else if (channel->key_len)
3102 len = channel->key_len / 8;
3104 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3106 /* Create channel key */
3107 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3110 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3112 /* Remove old key if exists */
3114 memset(channel->key, 0, channel->key_len / 8);
3115 silc_free(channel->key);
3119 channel->key_len = len * 8;
3120 channel->key = silc_memdup(channel_key, len);
3121 memset(channel_key, 0, sizeof(channel_key));
3123 /* Generate HMAC key from the channel key data and set it */
3125 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3126 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3127 silc_hmac_set_key(channel->hmac, hash,
3128 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3129 memset(hash, 0, sizeof(hash));
3131 if (server->server_type == SILC_ROUTER) {
3132 if (!channel->rekey)
3133 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3134 channel->rekey->context = (void *)server;
3135 channel->rekey->channel = channel;
3136 channel->rekey->key_len = key_len;
3137 if (channel->rekey->task)
3138 silc_schedule_task_del(server->schedule, channel->rekey->task);
3140 channel->rekey->task =
3141 silc_schedule_task_add(server->schedule, 0,
3142 silc_server_channel_key_rekey,
3143 (void *)channel->rekey,
3144 server->config->channel_rekey_secs, 0,
3146 SILC_TASK_PRI_NORMAL);
3152 /* Saves the channel key found in the encoded `key_payload' buffer. This
3153 function is used when we receive Channel Key Payload and also when we're
3154 processing JOIN command reply. Returns entry to the channel. */
3156 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3157 SilcBuffer key_payload,
3158 SilcChannelEntry channel)
3160 SilcChannelKeyPayload payload = NULL;
3161 SilcChannelID *id = NULL;
3162 unsigned char *tmp, hash[32];
3166 SILC_LOG_DEBUG(("Start"));
3168 /* Decode channel key payload */
3169 payload = silc_channel_key_payload_parse(key_payload->data,
3172 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3177 /* Get the channel entry */
3180 /* Get channel ID */
3181 tmp = silc_channel_key_get_id(payload, &tmp_len);
3182 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3188 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3190 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3192 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3193 silc_id_render(id, SILC_ID_CHANNEL)));
3199 tmp = silc_channel_key_get_key(payload, &tmp_len);
3205 cipher = silc_channel_key_get_cipher(payload, NULL);
3211 /* Remove old key if exists */
3213 memset(channel->key, 0, channel->key_len / 8);
3214 silc_free(channel->key);
3215 silc_cipher_free(channel->channel_key);
3218 /* Create new cipher */
3219 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3220 channel->channel_key = NULL;
3225 if (channel->cipher)
3226 silc_free(channel->cipher);
3227 channel->cipher = strdup(cipher);
3230 channel->key_len = tmp_len * 8;
3231 channel->key = silc_memdup(tmp, tmp_len);
3232 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3234 /* Generate HMAC key from the channel key data and set it */
3236 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3237 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3238 silc_hmac_set_key(channel->hmac, hash,
3239 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3241 memset(hash, 0, sizeof(hash));
3242 memset(tmp, 0, tmp_len);
3244 if (server->server_type == SILC_ROUTER) {
3245 if (!channel->rekey)
3246 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3247 channel->rekey->context = (void *)server;
3248 channel->rekey->channel = channel;
3249 if (channel->rekey->task)
3250 silc_schedule_task_del(server->schedule, channel->rekey->task);
3252 channel->rekey->task =
3253 silc_schedule_task_add(server->schedule, 0,
3254 silc_server_channel_key_rekey,
3255 (void *)channel->rekey,
3256 server->config->channel_rekey_secs, 0,
3258 SILC_TASK_PRI_NORMAL);
3264 silc_channel_key_payload_free(payload);
3269 /* Heartbeat callback. This function is set as argument for the
3270 silc_socket_set_heartbeat function. The library will call this function
3271 at the set time interval. */
3273 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3276 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3278 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3280 /* Send the heartbeat */
3281 silc_server_send_heartbeat(hb->server, sock);
3284 /* Returns assembled of all servers in the given ID list. The packet's
3285 form is dictated by the New ID payload. */
3287 static void silc_server_announce_get_servers(SilcServer server,
3288 SilcServerEntry remote,
3290 SilcBuffer *servers,
3291 unsigned long creation_time)
3293 SilcIDCacheList list;
3294 SilcIDCacheEntry id_cache;
3295 SilcServerEntry entry;
3298 /* Go through all clients in the list */
3299 if (silc_idcache_get_all(id_list->servers, &list)) {
3300 if (silc_idcache_list_first(list, &id_cache)) {
3302 entry = (SilcServerEntry)id_cache->context;
3304 /* Do not announce the one we've sending our announcements and
3305 do not announce ourself. Also check the creation time if it's
3307 if ((entry == remote) || (entry == server->id_entry) ||
3308 (creation_time && entry->data.created < creation_time)) {
3309 if (!silc_idcache_list_next(list, &id_cache))
3314 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3316 *servers = silc_buffer_realloc(*servers,
3318 (*servers)->truelen + idp->len :
3320 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3321 silc_buffer_put(*servers, idp->data, idp->len);
3322 silc_buffer_pull(*servers, idp->len);
3323 silc_buffer_free(idp);
3325 if (!silc_idcache_list_next(list, &id_cache))
3330 silc_idcache_list_free(list);
3335 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3341 p = silc_notify_payload_encode(notify, argc, ap);
3347 /* This function is used by router to announce existing servers to our
3348 primary router when we've connected to it. If `creation_time' is non-zero
3349 then only the servers that has been created after the `creation_time'
3350 will be announced. */
3352 void silc_server_announce_servers(SilcServer server, bool global,
3353 unsigned long creation_time,
3354 SilcSocketConnection remote)
3356 SilcBuffer servers = NULL;
3358 SILC_LOG_DEBUG(("Announcing servers"));
3360 /* Get servers in local list */
3361 silc_server_announce_get_servers(server, remote->user_data,
3362 server->local_list, &servers,
3366 /* Get servers in global list */
3367 silc_server_announce_get_servers(server, remote->user_data,
3368 server->global_list, &servers,
3372 silc_buffer_push(servers, servers->data - servers->head);
3373 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3375 /* Send the packet */
3376 silc_server_packet_send(server, remote,
3377 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3378 servers->data, servers->len, TRUE);
3380 silc_buffer_free(servers);
3384 /* Returns assembled packet of all clients in the given ID list. The
3385 packet's form is dictated by the New ID Payload. */
3387 static void silc_server_announce_get_clients(SilcServer server,
3389 SilcBuffer *clients,
3391 unsigned long creation_time)
3393 SilcIDCacheList list;
3394 SilcIDCacheEntry id_cache;
3395 SilcClientEntry client;
3398 unsigned char mode[4];
3400 /* Go through all clients in the list */
3401 if (silc_idcache_get_all(id_list->clients, &list)) {
3402 if (silc_idcache_list_first(list, &id_cache)) {
3404 client = (SilcClientEntry)id_cache->context;
3406 if (creation_time && client->data.created < creation_time) {
3407 if (!silc_idcache_list_next(list, &id_cache))
3412 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3414 *clients = silc_buffer_realloc(*clients,
3416 (*clients)->truelen + idp->len :
3418 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3419 silc_buffer_put(*clients, idp->data, idp->len);
3420 silc_buffer_pull(*clients, idp->len);
3422 SILC_PUT32_MSB(client->mode, mode);
3423 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3424 2, idp->data, idp->len,
3426 *umodes = silc_buffer_realloc(*umodes,
3428 (*umodes)->truelen + tmp->len :
3430 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3431 silc_buffer_put(*umodes, tmp->data, tmp->len);
3432 silc_buffer_pull(*umodes, tmp->len);
3433 silc_buffer_free(tmp);
3435 silc_buffer_free(idp);
3437 if (!silc_idcache_list_next(list, &id_cache))
3442 silc_idcache_list_free(list);
3446 /* This function is used to announce our existing clients to our router
3447 when we've connected to it. If `creation_time' is non-zero then only
3448 the clients that has been created after the `creation_time' will be
3451 void silc_server_announce_clients(SilcServer server,
3452 unsigned long creation_time,
3453 SilcSocketConnection remote)
3455 SilcBuffer clients = NULL;
3456 SilcBuffer umodes = NULL;
3458 SILC_LOG_DEBUG(("Announcing clients"));
3460 /* Get clients in local list */
3461 silc_server_announce_get_clients(server, server->local_list,
3462 &clients, &umodes, creation_time);
3464 /* As router we announce our global list as well */
3465 if (server->server_type == SILC_ROUTER)
3466 silc_server_announce_get_clients(server, server->global_list,
3467 &clients, &umodes, creation_time);
3470 silc_buffer_push(clients, clients->data - clients->head);
3471 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3473 /* Send the packet */
3474 silc_server_packet_send(server, remote,
3475 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3476 clients->data, clients->len, TRUE);
3478 silc_buffer_free(clients);
3482 silc_buffer_push(umodes, umodes->data - umodes->head);
3483 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3485 /* Send the packet */
3486 silc_server_packet_send(server, remote,
3487 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3488 umodes->data, umodes->len, TRUE);
3490 silc_buffer_free(umodes);
3494 /* Returns channel's topic for announcing it */
3496 void silc_server_announce_get_channel_topic(SilcServer server,
3497 SilcChannelEntry channel,
3502 if (channel->topic) {
3503 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3504 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3505 chidp->data, chidp->len,
3507 strlen(channel->topic));
3508 silc_buffer_free(chidp);
3512 /* Returns assembled packets for channel users of the `channel'. */
3514 void silc_server_announce_get_channel_users(SilcServer server,
3515 SilcChannelEntry channel,
3516 SilcBuffer *channel_users,
3517 SilcBuffer *channel_users_modes)
3519 SilcChannelClientEntry chl;
3520 SilcHashTableList htl;
3521 SilcBuffer chidp, clidp;
3524 unsigned char mode[4];
3526 SILC_LOG_DEBUG(("Start"));
3528 /* Now find all users on the channel */
3529 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3530 silc_hash_table_list(channel->user_list, &htl);
3531 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3532 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3535 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3536 clidp->data, clidp->len,
3537 chidp->data, chidp->len);
3540 silc_buffer_realloc(*channel_users,
3542 (*channel_users)->truelen + len : len));
3543 silc_buffer_pull_tail(*channel_users,
3544 ((*channel_users)->end -
3545 (*channel_users)->data));
3547 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3548 silc_buffer_pull(*channel_users, len);
3549 silc_buffer_free(tmp);
3551 /* CUMODE notify for mode change on the channel */
3552 SILC_PUT32_MSB(chl->mode, mode);
3553 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3554 3, clidp->data, clidp->len,
3556 clidp->data, clidp->len);
3558 *channel_users_modes =
3559 silc_buffer_realloc(*channel_users_modes,
3560 (*channel_users_modes ?
3561 (*channel_users_modes)->truelen + len : len));
3562 silc_buffer_pull_tail(*channel_users_modes,
3563 ((*channel_users_modes)->end -
3564 (*channel_users_modes)->data));
3566 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3567 silc_buffer_pull(*channel_users_modes, len);
3568 silc_buffer_free(tmp);
3570 silc_buffer_free(clidp);
3572 silc_hash_table_list_reset(&htl);
3573 silc_buffer_free(chidp);
3576 /* Returns assembled packets for all channels and users on those channels
3577 from the given ID List. The packets are in the form dictated by the
3578 New Channel and New Channel User payloads. */
3580 void silc_server_announce_get_channels(SilcServer server,
3582 SilcBuffer *channels,
3583 SilcBuffer *channel_users,
3584 SilcBuffer **channel_users_modes,
3585 SilcUInt32 *channel_users_modes_c,
3586 SilcBuffer **channel_topics,
3587 SilcChannelID ***channel_ids,
3588 unsigned long creation_time)
3590 SilcIDCacheList list;
3591 SilcIDCacheEntry id_cache;
3592 SilcChannelEntry channel;
3595 SilcUInt16 name_len;
3597 int i = *channel_users_modes_c;
3600 SILC_LOG_DEBUG(("Start"));
3602 /* Go through all channels in the list */
3603 if (silc_idcache_get_all(id_list->channels, &list)) {
3604 if (silc_idcache_list_first(list, &id_cache)) {
3606 channel = (SilcChannelEntry)id_cache->context;
3608 if (creation_time && channel->created < creation_time)
3613 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3614 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3615 name_len = strlen(channel->channel_name);
3618 len = 4 + name_len + id_len + 4;
3620 silc_buffer_realloc(*channels,
3621 (*channels ? (*channels)->truelen +
3623 silc_buffer_pull_tail(*channels,
3624 ((*channels)->end - (*channels)->data));
3625 silc_buffer_format(*channels,
3626 SILC_STR_UI_SHORT(name_len),
3627 SILC_STR_UI_XNSTRING(channel->channel_name,
3629 SILC_STR_UI_SHORT(id_len),
3630 SILC_STR_UI_XNSTRING(cid, id_len),
3631 SILC_STR_UI_INT(channel->mode),
3633 silc_buffer_pull(*channels, len);
3636 /* Channel user modes */
3637 *channel_users_modes = silc_realloc(*channel_users_modes,
3638 sizeof(**channel_users_modes) *
3640 (*channel_users_modes)[i] = NULL;
3641 *channel_ids = silc_realloc(*channel_ids,
3642 sizeof(**channel_ids) * (i + 1));
3643 (*channel_ids)[i] = NULL;
3644 silc_server_announce_get_channel_users(server, channel,
3646 &(*channel_users_modes)[i]);
3647 (*channel_ids)[i] = channel->id;
3649 /* Channel's topic */
3650 *channel_topics = silc_realloc(*channel_topics,
3651 sizeof(**channel_topics) * (i + 1));
3652 (*channel_topics)[i] = NULL;
3653 silc_server_announce_get_channel_topic(server, channel,
3654 &(*channel_topics)[i]);
3657 if (!silc_idcache_list_next(list, &id_cache))
3661 *channel_users_modes_c += i;
3664 silc_idcache_list_free(list);
3668 /* This function is used to announce our existing channels to our router
3669 when we've connected to it. This also announces the users on the
3670 channels to the router. If the `creation_time' is non-zero only the
3671 channels that was created after the `creation_time' are announced.
3672 Note that the channel users are still announced even if the `creation_time'
3675 void silc_server_announce_channels(SilcServer server,
3676 unsigned long creation_time,
3677 SilcSocketConnection remote)
3679 SilcBuffer channels = NULL, channel_users = NULL;
3680 SilcBuffer *channel_users_modes = NULL;
3681 SilcBuffer *channel_topics = NULL;
3682 SilcUInt32 channel_users_modes_c = 0;
3683 SilcChannelID **channel_ids = NULL;
3685 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3687 /* Get channels and channel users in local list */
3688 silc_server_announce_get_channels(server, server->local_list,
3689 &channels, &channel_users,
3690 &channel_users_modes,
3691 &channel_users_modes_c,
3693 &channel_ids, creation_time);
3695 /* Get channels and channel users in global list */
3696 if (server->server_type != SILC_SERVER)
3697 silc_server_announce_get_channels(server, server->global_list,
3698 &channels, &channel_users,
3699 &channel_users_modes,
3700 &channel_users_modes_c,
3702 &channel_ids, creation_time);
3705 silc_buffer_push(channels, channels->data - channels->head);
3706 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3708 /* Send the packet */
3709 silc_server_packet_send(server, remote,
3710 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3711 channels->data, channels->len,
3714 silc_buffer_free(channels);
3717 if (channel_users) {
3718 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3719 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3720 channel_users->len);
3722 /* Send the packet */
3723 silc_server_packet_send(server, remote,
3724 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3725 channel_users->data, channel_users->len,
3728 silc_buffer_free(channel_users);
3731 if (channel_users_modes) {
3734 for (i = 0; i < channel_users_modes_c; i++) {
3735 if (!channel_users_modes[i])
3737 silc_buffer_push(channel_users_modes[i],
3738 channel_users_modes[i]->data -
3739 channel_users_modes[i]->head);
3740 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3741 channel_users_modes[i]->len);
3742 silc_server_packet_send_dest(server, remote,
3743 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3744 channel_ids[i], SILC_ID_CHANNEL,
3745 channel_users_modes[i]->data,
3746 channel_users_modes[i]->len,
3748 silc_buffer_free(channel_users_modes[i]);
3750 silc_free(channel_users_modes);
3753 if (channel_topics) {
3756 for (i = 0; i < channel_users_modes_c; i++) {
3757 if (!channel_topics[i])
3760 silc_buffer_push(channel_topics[i],
3761 channel_topics[i]->data -
3762 channel_topics[i]->head);
3763 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3764 channel_topics[i]->len);
3765 silc_server_packet_send_dest(server, remote,
3766 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3767 channel_ids[i], SILC_ID_CHANNEL,
3768 channel_topics[i]->data,
3769 channel_topics[i]->len,
3771 silc_buffer_free(channel_topics[i]);
3773 silc_free(channel_topics);
3776 silc_free(channel_ids);
3779 /* Failure timeout callback. If this is called then we will immediately
3780 process the received failure. We always process the failure with timeout
3781 since we do not want to blindly trust to received failure packets.
3782 This won't be called (the timeout is cancelled) if the failure was
3783 bogus (it is bogus if remote does not close the connection after sending
3786 SILC_TASK_CALLBACK(silc_server_failure_callback)
3788 SilcServerFailureContext f = (SilcServerFailureContext)context;
3790 if (f->sock->protocol) {
3791 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3792 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3798 /* Assembles user list and users mode list from the `channel'. */
3800 void silc_server_get_users_on_channel(SilcServer server,
3801 SilcChannelEntry channel,
3802 SilcBuffer *user_list,
3803 SilcBuffer *mode_list,
3804 SilcUInt32 *user_count)
3806 SilcChannelClientEntry chl;
3807 SilcHashTableList htl;
3808 SilcBuffer client_id_list;
3809 SilcBuffer client_mode_list;
3811 SilcUInt32 list_count = 0, len = 0;
3813 silc_hash_table_list(channel->user_list, &htl);
3814 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3815 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3816 silc_hash_table_list_reset(&htl);
3818 client_id_list = silc_buffer_alloc(len);
3820 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3821 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3822 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3824 silc_hash_table_list(channel->user_list, &htl);
3825 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3827 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3828 silc_buffer_put(client_id_list, idp->data, idp->len);
3829 silc_buffer_pull(client_id_list, idp->len);
3830 silc_buffer_free(idp);
3832 /* Client's mode on channel */
3833 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3834 silc_buffer_pull(client_mode_list, 4);
3838 silc_hash_table_list_reset(&htl);
3839 silc_buffer_push(client_id_list,
3840 client_id_list->data - client_id_list->head);
3841 silc_buffer_push(client_mode_list,
3842 client_mode_list->data - client_mode_list->head);
3844 *user_list = client_id_list;
3845 *mode_list = client_mode_list;
3846 *user_count = list_count;
3849 /* Saves users and their modes to the `channel'. */
3851 void silc_server_save_users_on_channel(SilcServer server,
3852 SilcSocketConnection sock,
3853 SilcChannelEntry channel,
3854 SilcClientID *noadd,
3855 SilcBuffer user_list,
3856 SilcBuffer mode_list,
3857 SilcUInt32 user_count)
3862 SilcClientID *client_id;
3863 SilcClientEntry client;
3864 SilcIDCacheEntry cache;
3867 SILC_LOG_DEBUG(("Start"));
3869 for (i = 0; i < user_count; i++) {
3871 SILC_GET16_MSB(idp_len, user_list->data + 2);
3873 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3874 silc_buffer_pull(user_list, idp_len);
3879 SILC_GET32_MSB(mode, mode_list->data);
3880 silc_buffer_pull(mode_list, 4);
3882 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3883 silc_free(client_id);
3889 /* Check if we have this client cached already. */
3890 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3891 server->server_type, &cache);
3893 client = silc_idlist_find_client_by_id(server->global_list,
3894 client_id, server->server_type,
3899 /* If router did not find such Client ID in its lists then this must
3900 be bogus client or some router in the net is buggy. */
3901 if (server->server_type == SILC_ROUTER) {
3902 silc_free(client_id);
3906 /* We don't have that client anywhere, add it. The client is added
3907 to global list since server didn't have it in the lists so it must be
3909 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3910 silc_id_dup(client_id, SILC_ID_CLIENT),
3911 sock->user_data, NULL, 0);
3913 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3914 silc_free(client_id);
3918 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3920 /* Found, if it is from global list we'll assure that we won't
3921 expire it now that the entry is on channel. */
3926 silc_free(client_id);
3928 if (!silc_server_client_on_channel(client, channel, NULL)) {
3929 /* Client was not on the channel, add it. */
3930 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3931 chl->client = client;
3933 chl->channel = channel;
3934 silc_hash_table_add(channel->user_list, chl->client, chl);
3935 silc_hash_table_add(client->channels, chl->channel, chl);
3936 channel->user_count++;
3941 /* Lookups route to the client indicated by the `id_data'. The connection
3942 object and internal data object is returned. Returns NULL if route
3943 could not be found to the client. If the `client_id' is specified then
3944 it is used and the `id_data' is ignored. */
3946 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3947 unsigned char *id_data,
3949 SilcClientID *client_id,
3950 SilcIDListData *idata)
3953 SilcClientEntry client;
3955 SILC_LOG_DEBUG(("Start"));
3957 /* Decode destination Client ID */
3959 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3961 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3965 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3968 /* If the destination belongs to our server we don't have to route
3969 the packet anywhere but to send it to the local destination. */
3970 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3974 /* If we are router and the client has router then the client is in
3975 our cell but not directly connected to us. */
3976 if (server->server_type == SILC_ROUTER && client->router) {
3977 /* We are of course in this case the client's router thus the route
3978 to the client is the server who owns the client. So, we will send
3979 the packet to that server. */
3981 *idata = (SilcIDListData)client->router;
3982 return client->router->connection;
3985 /* Seems that client really is directly connected to us */
3987 *idata = (SilcIDListData)client;
3988 return client->connection;
3991 /* Destination belongs to someone not in this server. If we are normal
3992 server our action is to send the packet to our router. */
3993 if (server->server_type != SILC_ROUTER && !server->standalone) {
3996 *idata = (SilcIDListData)server->router;
3997 return server->router->connection;
4000 /* We are router and we will perform route lookup for the destination
4001 and send the packet to fastest route. */
4002 if (server->server_type == SILC_ROUTER && !server->standalone) {
4003 /* Check first that the ID is valid */
4004 client = silc_idlist_find_client_by_id(server->global_list, id,
4007 SilcSocketConnection dst_sock;
4009 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4013 *idata = (SilcIDListData)dst_sock->user_data;
4022 /* Encodes and returns channel list of channels the `client' has joined.
4023 Secret channels are not put to the list. */
4025 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4026 SilcClientEntry client)
4028 SilcBuffer buffer = NULL;
4029 SilcChannelEntry channel;
4030 SilcChannelClientEntry chl;
4031 SilcHashTableList htl;
4034 SilcUInt16 name_len;
4037 silc_hash_table_list(client->channels, &htl);
4038 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4039 channel = chl->channel;
4041 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
4042 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
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);
4049 len = 4 + name_len + id_len + 4;
4050 buffer = silc_buffer_realloc(buffer,
4051 (buffer ? (buffer)->truelen + len : len));
4052 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4053 silc_buffer_format(buffer,
4054 SILC_STR_UI_SHORT(name_len),
4055 SILC_STR_UI_XNSTRING(channel->channel_name,
4057 SILC_STR_UI_SHORT(id_len),
4058 SILC_STR_UI_XNSTRING(cid, id_len),
4059 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4061 silc_buffer_pull(buffer, len);
4064 silc_hash_table_list_reset(&htl);
4067 silc_buffer_push(buffer, buffer->data - buffer->head);
4072 /* Finds client entry by Client ID and if it is not found then resolves
4073 it using WHOIS command. */
4075 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4076 SilcClientID *client_id,
4079 SilcClientEntry client;
4084 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4087 client = silc_idlist_find_client_by_id(server->global_list,
4088 client_id, TRUE, NULL);
4089 if (!client && server->server_type == SILC_ROUTER)
4093 if (!client && server->standalone)
4096 if (!client || !client->nickname || !client->username) {
4097 SilcBuffer buffer, idp;
4099 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4100 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4101 client->resolve_cmd_ident = ++server->cmd_ident;
4103 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4104 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4105 server->cmd_ident, 1,
4106 3, idp->data, idp->len);
4107 silc_server_packet_send(server, client ? client->router->connection :
4108 server->router->connection,
4109 SILC_PACKET_COMMAND, 0,
4110 buffer->data, buffer->len, FALSE);
4111 silc_buffer_free(idp);
4112 silc_buffer_free(buffer);
4123 /* A timeout callback for the re-key. We will be the initiator of the
4126 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4128 SilcSocketConnection sock = (SilcSocketConnection)context;
4129 SilcIDListData idata = (SilcIDListData)sock->user_data;
4130 SilcServer server = (SilcServer)idata->rekey->context;
4131 SilcProtocol protocol;
4132 SilcServerRekeyInternalContext *proto_ctx;
4134 SILC_LOG_DEBUG(("Start"));
4136 /* Allocate internal protocol context. This is sent as context
4138 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4139 proto_ctx->server = (void *)server;
4140 proto_ctx->sock = sock;
4141 proto_ctx->responder = FALSE;
4142 proto_ctx->pfs = idata->rekey->pfs;
4144 /* Perform rekey protocol. Will call the final callback after the
4145 protocol is over. */
4146 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4147 &protocol, proto_ctx, silc_server_rekey_final);
4148 sock->protocol = protocol;
4150 /* Run the protocol */
4151 silc_protocol_execute(protocol, server->schedule, 0, 0);
4153 /* Re-register re-key timeout */
4154 silc_schedule_task_add(server->schedule, sock->sock,
4155 silc_server_rekey_callback,
4156 context, idata->rekey->timeout, 0,
4157 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4160 /* The final callback for the REKEY protocol. This will actually take the
4161 new key material into use. */
4163 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4165 SilcProtocol protocol = (SilcProtocol)context;
4166 SilcServerRekeyInternalContext *ctx =
4167 (SilcServerRekeyInternalContext *)protocol->context;
4168 SilcServer server = (SilcServer)ctx->server;
4169 SilcSocketConnection sock = ctx->sock;
4171 SILC_LOG_DEBUG(("Start"));
4173 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4174 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4175 /* Error occured during protocol */
4176 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4177 silc_protocol_cancel(protocol, server->schedule);
4178 silc_protocol_free(protocol);
4179 sock->protocol = NULL;
4181 silc_packet_context_free(ctx->packet);
4183 silc_ske_free(ctx->ske);
4188 /* Purge the outgoing data queue to assure that all rekey packets really
4189 go to the network before we quit the protocol. */
4190 silc_server_packet_queue_purge(server, sock);
4193 silc_protocol_free(protocol);
4194 sock->protocol = NULL;
4196 silc_packet_context_free(ctx->packet);
4198 silc_ske_free(ctx->ske);