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 /* Steal public and private key from the config object */
152 server->public_key = server->config->server_info->public_key;
153 server->private_key = server->config->server_info->private_key;
154 server->config->server_info->public_key = NULL;
155 server->config->server_info->private_key = NULL;
157 /* Register all configured ciphers, PKCS and hash functions. */
158 if (!silc_server_config_register_ciphers(server))
159 silc_cipher_register_default();
160 if (!silc_server_config_register_pkcs(server))
161 silc_pkcs_register_default();
162 if (!silc_server_config_register_hashfuncs(server))
163 silc_hash_register_default();
164 if (!silc_server_config_register_hmacs(server))
165 silc_hmac_register_default();
167 /* Initialize random number generator for the server. */
168 server->rng = silc_rng_alloc();
169 silc_rng_init(server->rng);
170 silc_rng_global_init(server->rng);
172 /* Initialize hash functions for server to use */
173 silc_hash_alloc("md5", &server->md5hash);
174 silc_hash_alloc("sha1", &server->sha1hash);
176 /* Allocate PKCS context for local public and private keys */
177 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
179 silc_pkcs_public_key_set(server->pkcs, server->public_key);
180 silc_pkcs_private_key_set(server->pkcs, server->private_key);
182 /* Initialize the scheduler */
183 server->schedule = silc_schedule_init(server->config->param.connections_max);
184 if (!server->schedule)
187 /* First, register log files configuration for error output */
188 silc_server_config_setlogfiles(server);
190 /* Initialize ID caches */
191 server->local_list->clients =
192 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
193 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
194 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
196 /* These are allocated for normal server as well as these hold some
197 global information that the server has fetched from its router. For
198 router these are used as they are supposed to be used on router. */
199 server->global_list->clients =
200 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
201 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
202 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
204 /* Create a listening server */
205 if (!silc_server_listen(server, &sock))
208 /* Set socket to non-blocking mode */
209 silc_net_set_socket_nonblock(sock);
212 /* Allocate the entire socket list that is used in server. Eventually
213 all connections will have entry in this table (it is a table of
214 pointers to the actual object that is allocated individually
216 server->sockets = silc_calloc(server->config->param.connections_max,
217 sizeof(*server->sockets));
218 if (!server->sockets)
221 /* Add ourselves also to the socket table. The entry allocated above
222 is sent as argument for fast referencing in the future. */
223 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
224 server->sockets[sock] = newsocket;
226 /* Perform name and address lookups to resolve the listenning address
228 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
230 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
232 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
233 newsocket->hostname ? newsocket->hostname :
234 newsocket->ip ? newsocket->ip : ""));
235 server->stat.conn_failures++;
238 if (!newsocket->hostname)
239 newsocket->hostname = strdup(newsocket->ip);
241 newsocket->port = silc_net_get_local_port(sock);
243 /* Create a Server ID for the server. */
244 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
249 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
250 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
251 server->id_type = SILC_ID_SERVER;
252 server->server_name = server->config->server_info->server_name;
253 server->config->server_info->server_name = NULL;
255 /* Add ourselves to the server list. We don't have a router yet
256 beacuse we haven't established a route yet. It will be done later.
257 For now, NULL is sent as router. This allocates new entry to
260 silc_idlist_add_server(server->local_list, strdup(server->server_name),
261 server->server_type, server->id, NULL, NULL);
263 SILC_LOG_ERROR(("Could not add ourselves to cache"));
266 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
268 /* Put the allocated socket pointer also to the entry allocated above
269 for fast back-referencing to the socket list. */
270 newsocket->user_data = (void *)id_entry;
271 id_entry->connection = (void *)newsocket;
272 server->id_entry = id_entry;
274 /* Register protocols */
275 silc_server_protocols_register();
277 /* Add the first task to the scheduler. This is task that is executed by
278 timeout. It expires as soon as the caller calls silc_server_run. This
279 task performs authentication protocol and key exchange with our
281 silc_schedule_task_add(server->schedule, sock,
282 silc_server_connect_to_router,
283 (void *)server, 0, 1,
285 SILC_TASK_PRI_NORMAL);
287 /* Add listener task to the scheduler. This task receives new connections
288 to the server. This task remains on the queue until the end of the
290 silc_schedule_task_add(server->schedule, sock,
291 silc_server_accept_new_connection,
292 (void *)server, 0, 0,
294 SILC_TASK_PRI_NORMAL);
295 server->listenning = TRUE;
297 /* If server connections has been configured then we must be router as
298 normal server cannot have server connections, only router connections. */
299 if (server->config->servers) {
300 SilcServerConfigServer *ptr = server->config->servers;
302 server->server_type = SILC_ROUTER;
304 if (ptr->backup_router) {
305 server->server_type = SILC_BACKUP_ROUTER;
306 server->backup_router = TRUE;
307 server->id_entry->server_type = SILC_BACKUP_ROUTER;
314 /* Register the ID Cache purge task. This periodically purges the ID cache
315 and removes the expired cache entries. */
317 /* Clients local list */
318 purge = silc_calloc(1, sizeof(*purge));
319 purge->cache = server->local_list->clients;
320 purge->schedule = server->schedule;
321 purge->timeout = 600;
322 silc_schedule_task_add(purge->schedule, 0,
324 (void *)purge, purge->timeout, 0,
325 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
327 /* Clients global list */
328 purge = silc_calloc(1, sizeof(*purge));
329 purge->cache = server->global_list->clients;
330 purge->schedule = server->schedule;
331 purge->timeout = 300;
332 silc_schedule_task_add(purge->schedule, 0,
334 (void *)purge, purge->timeout, 0,
335 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
337 SILC_LOG_DEBUG(("Server initialized"));
339 /* We are done here, return succesfully */
343 silc_net_close_server(sock);
347 /* This function basically reads the config file again and switches the config
348 object pointed by the server object. After that, we have to fix various
349 things such as the server_name and the listening ports.
350 Keep in mind that we no longer have the root privileges at this point. */
352 bool silc_server_rehash(SilcServer server)
354 SilcServerConfig newconfig;
356 SILC_LOG_INFO(("Rehashing server"));
358 /* Reset the logging system */
359 silc_log_quick = TRUE;
360 silc_log_flush_all();
362 /* Start the main rehash phase (read again the config file) */
363 newconfig = silc_server_config_alloc(server->config_file);
365 SILC_LOG_ERROR(("Rehash FAILED."));
369 /* Config file parsing went fine, so our old config is gone now. We
370 unreference the basic pointer and it should be destroyed as soon
371 as all other references are released. */
372 silc_server_config_unref(&server->config_ref);
373 server->config = newconfig;
374 silc_server_config_ref(&server->config_ref, server->config, server->config);
376 /* Fix the server_name field */
377 if (!strcmp(server->server_name, newconfig->server_info->server_name)) {
378 /* We don't need any update */
379 silc_free(newconfig->server_info->server_name);
380 newconfig->server_info->server_name = NULL;
382 silc_free(server->server_name);
383 server->server_name = newconfig->server_info->server_name;
384 newconfig->server_info->server_name = NULL;
386 /* Update the idcache list with a fresh pointer */
387 silc_free(server->id_entry->server_name);
388 server->id_entry->server_name = strdup(server->server_name);
389 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
390 silc_idcache_add(server->local_list->servers,
391 server->id_entry->server_name,
392 server->id_entry->id, server->id_entry, 0, NULL);
395 silc_server_config_setlogfiles(server);
397 /* Change new key pair if necessary */
398 if (newconfig->server_info->public_key &&
399 !silc_pkcs_public_key_compare(server->public_key,
400 newconfig->server_info->public_key)) {
401 silc_pkcs_public_key_free(server->public_key);
402 silc_pkcs_private_key_free(server->private_key);
403 server->public_key = server->config->server_info->public_key;
404 server->private_key = server->config->server_info->private_key;
405 server->config->server_info->public_key = NULL;
406 server->config->server_info->private_key = NULL;
408 /* Allocate PKCS context for local public and private keys */
409 silc_pkcs_free(server->pkcs);
410 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
412 silc_pkcs_public_key_set(server->pkcs, server->public_key);
413 silc_pkcs_private_key_set(server->pkcs, server->private_key);
419 /* The heart of the server. This runs the scheduler thus runs the server.
420 When this returns the server has been stopped and the program will
423 void silc_server_run(SilcServer server)
425 SILC_LOG_INFO(("SILC Server started"));
427 /* Start the scheduler, the heart of the SILC server. When this returns
428 the program will be terminated. */
429 silc_schedule(server->schedule);
432 /* Stops the SILC server. This function is used to shutdown the server.
433 This is usually called after the scheduler has returned. After stopping
434 the server one should call silc_server_free. */
436 void silc_server_stop(SilcServer server)
438 SILC_LOG_DEBUG(("Stopping server"));
440 if (server->schedule) {
441 silc_schedule_stop(server->schedule);
442 silc_schedule_uninit(server->schedule);
443 server->schedule = NULL;
446 silc_server_protocols_unregister();
448 SILC_LOG_DEBUG(("Server stopped"));
451 /* Function that is called when the network connection to a router has
452 been established. This will continue with the key exchange protocol
453 with the remote router. */
455 void silc_server_start_key_exchange(SilcServer server,
456 SilcServerConnection sconn,
459 SilcSocketConnection newsocket;
460 SilcProtocol protocol;
461 SilcServerKEInternalContext *proto_ctx;
462 SilcServerConfigRouter *conn =
463 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
466 /* Cancel any possible retry timeouts */
467 silc_schedule_task_del_by_callback(server->schedule,
468 silc_server_connect_router);
470 /* Set socket options */
471 silc_net_set_socket_nonblock(sock);
472 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
474 /* Create socket connection for the connection. Even though we
475 know that we are connecting to a router we will mark the socket
476 to be unknown connection until we have executed authentication
478 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
479 server->sockets[sock] = newsocket;
480 newsocket->hostname = strdup(sconn->remote_host);
481 newsocket->ip = strdup(sconn->remote_host);
482 newsocket->port = sconn->remote_port;
483 sconn->sock = newsocket;
485 /* Allocate internal protocol context. This is sent as context
487 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
488 proto_ctx->server = (void *)server;
489 proto_ctx->context = (void *)sconn;
490 proto_ctx->sock = newsocket;
491 proto_ctx->rng = server->rng;
492 proto_ctx->responder = FALSE;
494 /* Set Key Exchange flags from configuration, but fall back to global
496 SILC_GET_SKE_FLAGS(conn, proto_ctx);
497 if (server->config->param.key_exchange_pfs)
498 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
500 /* Perform key exchange protocol. silc_server_connect_to_router_second
501 will be called after the protocol is finished. */
502 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
503 &protocol, proto_ctx,
504 silc_server_connect_to_router_second);
505 newsocket->protocol = protocol;
507 /* Register a timeout task that will be executed if the protocol
508 is not executed within set limit. */
509 proto_ctx->timeout_task =
510 silc_schedule_task_add(server->schedule, sock,
511 silc_server_timeout_remote,
512 server, server->config->key_exchange_timeout, 0,
516 /* Register the connection for network input and output. This sets
517 that scheduler will listen for incoming packets for this connection
518 and sets that outgoing packets may be sent to this connection as
519 well. However, this doesn't set the scheduler for outgoing traffic,
520 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
521 later when outgoing data is available. */
522 context = (void *)server;
523 SILC_REGISTER_CONNECTION_FOR_IO(sock);
525 /* Run the protocol */
526 silc_protocol_execute(protocol, server->schedule, 0, 0);
529 /* Timeout callback that will be called to retry connecting to remote
530 router. This is used by both normal and router server. This will wait
531 before retrying the connecting. The timeout is generated by exponential
532 backoff algorithm. */
534 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
536 SilcServerConnection sconn = (SilcServerConnection)context;
537 SilcServer server = sconn->server;
538 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
539 SilcServerConfigConnParams *param =
540 (conn->param ? conn->param : &server->config->param);
542 SILC_LOG_INFO(("Retrying connecting to a router"));
544 /* Calculate next timeout */
545 if (sconn->retry_count >= 1) {
546 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
547 if (sconn->retry_timeout > param->reconnect_interval_max)
548 sconn->retry_timeout = param->reconnect_interval_max;
550 sconn->retry_timeout = param->reconnect_interval;
552 sconn->retry_count++;
553 sconn->retry_timeout = sconn->retry_timeout +
554 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
556 /* If we've reached max retry count, give up. */
557 if ((sconn->retry_count > param->reconnect_count) &&
558 !param->reconnect_keep_trying) {
559 SILC_LOG_ERROR(("Could not connect to router, giving up"));
560 silc_server_config_unref(&sconn->conn);
561 silc_free(sconn->remote_host);
562 silc_free(sconn->backup_replace_ip);
567 /* We will lookup a fresh pointer later */
568 silc_server_config_unref(&sconn->conn);
570 /* Wait one before retrying */
571 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
572 context, sconn->retry_timeout, 0,
573 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
576 /* Generic routine to use connect to a router. */
578 SILC_TASK_CALLBACK(silc_server_connect_router)
580 SilcServerConnection sconn = (SilcServerConnection)context;
581 SilcServer server = sconn->server;
582 SilcServerConfigRouter *rconn;
585 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
586 (sconn->backup ? "backup router" : "router"),
587 sconn->remote_host, sconn->remote_port));
589 server->router_connect = time(NULL);
590 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
593 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
594 (sconn->backup ? "backup router" : "router"),
595 sconn->remote_host, sconn->remote_port));
596 silc_free(sconn->remote_host);
597 silc_free(sconn->backup_replace_ip);
601 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
603 /* Connect to remote host */
604 sock = silc_net_create_connection(server->config->server_info->server_ip,
608 SILC_LOG_ERROR(("Could not connect to router %s:%d",
609 sconn->remote_host, sconn->remote_port));
610 if (!sconn->no_reconnect)
611 silc_schedule_task_add(server->schedule, 0,
612 silc_server_connect_to_router_retry,
613 context, 0, 1, SILC_TASK_TIMEOUT,
614 SILC_TASK_PRI_NORMAL);
616 silc_server_config_unref(&sconn->conn);
620 /* Continue with key exchange protocol */
621 silc_server_start_key_exchange(server, sconn, sock);
624 /* This function connects to our primary router or if we are a router this
625 establishes all our primary routes. This is called at the start of the
626 server to do authentication and key exchange with our router - called
629 SILC_TASK_CALLBACK(silc_server_connect_to_router)
631 SilcServer server = (SilcServer)context;
632 SilcServerConnection sconn;
633 SilcServerConfigRouter *ptr;
635 SILC_LOG_DEBUG(("Connecting to router(s)"));
637 if (server->server_type == SILC_SERVER) {
638 SILC_LOG_DEBUG(("We are normal server"));
639 } else if (server->server_type == SILC_ROUTER) {
640 SILC_LOG_DEBUG(("We are router"));
642 SILC_LOG_DEBUG(("We are backup router/normal server"));
645 if (!server->config->routers) {
646 /* There wasn't a configured router, we will continue but we don't
647 have a connection to outside world. We will be standalone server. */
648 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
649 server->standalone = TRUE;
653 /* Create the connections to all our routes */
654 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
656 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
657 ptr->backup_router ? "Backup router" : "Router",
658 ptr->initiator ? "Initiator" : "Responder",
659 ptr->host, ptr->port));
661 if (ptr->initiator) {
662 /* Allocate connection object for hold connection specific stuff. */
663 sconn = silc_calloc(1, sizeof(*sconn));
664 sconn->server = server;
665 sconn->remote_host = strdup(ptr->host);
666 sconn->remote_port = ptr->port;
667 sconn->backup = ptr->backup_router;
669 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
670 sconn->backup_replace_port = ptr->backup_replace_port;
673 if (!server->router_conn && !sconn->backup)
674 server->router_conn = sconn;
676 silc_schedule_task_add(server->schedule, fd,
677 silc_server_connect_router,
678 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
679 SILC_TASK_PRI_NORMAL);
684 /* Second part of connecting to router(s). Key exchange protocol has been
685 executed and now we will execute authentication protocol. */
687 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
689 SilcProtocol protocol = (SilcProtocol)context;
690 SilcServerKEInternalContext *ctx =
691 (SilcServerKEInternalContext *)protocol->context;
692 SilcServer server = (SilcServer)ctx->server;
693 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
694 SilcSocketConnection sock = ctx->sock;
695 SilcServerConnAuthInternalContext *proto_ctx;
696 SilcServerConfigRouter *conn = NULL;
698 SILC_LOG_DEBUG(("Start"));
700 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
701 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
702 /* Error occured during protocol */
703 silc_protocol_free(protocol);
704 sock->protocol = NULL;
705 silc_ske_free_key_material(ctx->keymat);
707 silc_packet_context_free(ctx->packet);
709 silc_ske_free(ctx->ske);
710 silc_free(ctx->dest_id);
712 silc_server_config_unref(&sconn->conn);
713 silc_free(sconn->remote_host);
714 silc_free(sconn->backup_replace_ip);
716 silc_schedule_task_del_by_callback(server->schedule,
717 silc_server_failure_callback);
718 silc_server_disconnect_remote(server, sock, "Server closed connection: "
719 "Key exchange failed");
723 /* We now have the key material as the result of the key exchange
724 protocol. Take the key material into use. Free the raw key material
725 as soon as we've set them into use. */
726 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
727 ctx->sock, ctx->keymat,
728 ctx->ske->prop->cipher,
729 ctx->ske->prop->pkcs,
730 ctx->ske->prop->hash,
731 ctx->ske->prop->hmac,
732 ctx->ske->prop->group,
734 silc_protocol_free(protocol);
735 sock->protocol = NULL;
736 silc_ske_free_key_material(ctx->keymat);
738 silc_packet_context_free(ctx->packet);
740 silc_ske_free(ctx->ske);
741 silc_free(ctx->dest_id);
743 silc_server_config_unref(&sconn->conn);
744 silc_free(sconn->remote_host);
745 silc_free(sconn->backup_replace_ip);
747 silc_schedule_task_del_by_callback(server->schedule,
748 silc_server_failure_callback);
749 silc_server_disconnect_remote(server, sock, "Server closed connection: "
750 "Key exchange failed");
753 silc_ske_free_key_material(ctx->keymat);
755 /* Allocate internal context for the authentication protocol. This
756 is sent as context for the protocol. */
757 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
758 proto_ctx->server = (void *)server;
759 proto_ctx->context = (void *)sconn;
760 proto_ctx->sock = sock;
761 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
762 proto_ctx->dest_id_type = ctx->dest_id_type;
763 proto_ctx->dest_id = ctx->dest_id;
765 /* Resolve the authentication method used in this connection. Check if
766 we find a match from user configured connections */
767 if (!sconn->conn.ref_ptr)
768 conn = silc_server_config_find_router_conn(server, sock->hostname,
771 conn = sconn->conn.ref_ptr;
774 /* Match found. Use the configured authentication method. Take only
775 the passphrase, since for public key auth we automatically use
776 our local key pair. */
777 if (conn->passphrase) {
778 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
779 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
781 proto_ctx->auth_data = strdup(conn->passphrase);
782 proto_ctx->auth_data_len = strlen(conn->passphrase);
783 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
785 } else if (conn->publickeys) {
786 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
788 proto_ctx->auth_meth = SILC_AUTH_NONE;
791 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
792 sock->hostname, sock->ip, sock->port));
793 silc_protocol_free(protocol);
794 sock->protocol = NULL;
796 silc_packet_context_free(ctx->packet);
798 silc_ske_free(ctx->ske);
799 silc_free(ctx->dest_id);
801 silc_server_config_unref(&sconn->conn);
802 silc_free(sconn->remote_host);
803 silc_free(sconn->backup_replace_ip);
805 silc_schedule_task_del_by_callback(server->schedule,
806 silc_server_failure_callback);
807 silc_server_disconnect_remote(server, sock, "Server closed connection: "
808 "Key exchange failed");
812 /* Free old protocol as it is finished now */
813 silc_protocol_free(protocol);
815 silc_packet_context_free(ctx->packet);
817 sock->protocol = NULL;
819 /* Allocate the authentication protocol. This is allocated here
820 but we won't start it yet. We will be receiving party of this
821 protocol thus we will wait that connecting party will make
823 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
824 &sock->protocol, proto_ctx,
825 silc_server_connect_to_router_final);
827 /* Register timeout task. If the protocol is not executed inside
828 this timelimit the connection will be terminated. */
829 proto_ctx->timeout_task =
830 silc_schedule_task_add(server->schedule, sock->sock,
831 silc_server_timeout_remote,
833 server->config->conn_auth_timeout, 0,
837 /* Run the protocol */
838 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
841 /* Finalizes the connection to router. Registers a server task to the
842 queue so that we can accept new connections. */
844 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
846 SilcProtocol protocol = (SilcProtocol)context;
847 SilcServerConnAuthInternalContext *ctx =
848 (SilcServerConnAuthInternalContext *)protocol->context;
849 SilcServer server = (SilcServer)ctx->server;
850 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
851 SilcSocketConnection sock = ctx->sock;
852 SilcServerEntry id_entry;
854 SilcServerHBContext hb_context;
855 unsigned char *id_string;
857 SilcIDListData idata;
858 SilcServerConfigRouter *conn = NULL;
859 SilcServerConfigConnParams *param = NULL;
861 SILC_LOG_DEBUG(("Start"));
863 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
864 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
865 /* Error occured during protocol */
866 silc_free(ctx->dest_id);
867 silc_server_disconnect_remote(server, sock, "Server closed connection: "
868 "Authentication failed");
872 /* Add a task to the queue. This task receives new connections to the
873 server. This task remains on the queue until the end of the program. */
874 if (!server->listenning && !sconn->backup) {
875 silc_schedule_task_add(server->schedule, server->sock,
876 silc_server_accept_new_connection,
877 (void *)server, 0, 0,
879 SILC_TASK_PRI_NORMAL);
880 server->listenning = TRUE;
883 /* Send NEW_SERVER packet to the router. We will become registered
884 to the SILC network after sending this packet. */
885 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
886 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
887 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
888 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
889 silc_buffer_format(packet,
890 SILC_STR_UI_SHORT(id_len),
891 SILC_STR_UI_XNSTRING(id_string, id_len),
892 SILC_STR_UI_SHORT(strlen(server->server_name)),
893 SILC_STR_UI_XNSTRING(server->server_name,
894 strlen(server->server_name)),
897 /* Send the packet */
898 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
899 packet->data, packet->len, TRUE);
900 silc_buffer_free(packet);
901 silc_free(id_string);
903 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
905 /* Check that we do not have this ID already */
906 id_entry = silc_idlist_find_server_by_id(server->local_list,
907 ctx->dest_id, TRUE, NULL);
909 silc_idcache_del_by_context(server->local_list->servers, id_entry);
911 id_entry = silc_idlist_find_server_by_id(server->global_list,
912 ctx->dest_id, TRUE, NULL);
914 silc_idcache_del_by_context(server->global_list->servers, id_entry);
917 SILC_LOG_DEBUG(("New server id(%s)",
918 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
920 /* Add the connected router to global server list */
921 id_entry = silc_idlist_add_server(server->global_list,
922 strdup(sock->hostname),
923 SILC_ROUTER, ctx->dest_id, NULL, sock);
925 silc_free(ctx->dest_id);
926 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
927 silc_server_disconnect_remote(server, sock, "Server closed connection: "
928 "Authentication failed");
932 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
933 silc_free(sock->user_data);
934 sock->user_data = (void *)id_entry;
935 sock->type = SILC_SOCKET_TYPE_ROUTER;
936 idata = (SilcIDListData)sock->user_data;
937 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
939 conn = sconn->conn.ref_ptr;
940 param = &server->config->param;
941 if (conn && conn->param)
944 /* Perform keepalive. The `hb_context' will be freed automatically
945 when finally calling the silc_socket_free function. */
946 hb_context = silc_calloc(1, sizeof(*hb_context));
947 hb_context->server = server;
948 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
949 silc_server_perform_heartbeat,
952 /* Register re-key timeout */
953 idata->rekey->timeout = param->key_exchange_rekey;
954 idata->rekey->context = (void *)server;
955 silc_schedule_task_add(server->schedule, sock->sock,
956 silc_server_rekey_callback,
957 (void *)sock, idata->rekey->timeout, 0,
958 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
960 if (!sconn->backup) {
961 /* Mark this router our primary router if we're still standalone */
962 if (server->standalone) {
963 server->id_entry->router = id_entry;
964 server->router = id_entry;
965 server->standalone = FALSE;
967 /* If we are router then announce our possible servers. */
968 if (server->server_type == SILC_ROUTER)
969 silc_server_announce_servers(server, FALSE, 0,
970 server->router->connection);
972 /* Announce our clients and channels to the router */
973 silc_server_announce_clients(server, 0, server->router->connection);
974 silc_server_announce_channels(server, 0, server->router->connection);
977 /* Add this server to be our backup router */
978 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
979 sconn->backup_replace_port, FALSE);
982 sock->protocol = NULL;
984 /* Call the completion callback to indicate that we've connected to
987 (*sconn->callback)(server, id_entry, sconn->callback_context);
990 /* Free the temporary connection data context */
992 silc_server_config_unref(&sconn->conn);
993 silc_free(sconn->remote_host);
994 silc_free(sconn->backup_replace_ip);
997 if (sconn == server->router_conn)
998 server->router_conn = NULL;
1000 /* Free the protocol object */
1001 if (sock->protocol == protocol)
1002 sock->protocol = NULL;
1003 silc_protocol_free(protocol);
1005 silc_packet_context_free(ctx->packet);
1007 silc_ske_free(ctx->ske);
1008 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1009 silc_free(ctx->auth_data);
1013 /* Host lookup callback that is called after the incoming connection's
1014 IP and FQDN lookup is performed. This will actually check the acceptance
1015 of the incoming connection and will register the key exchange protocol
1016 for this connection. */
1019 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1022 SilcServer server = (SilcServer)context;
1023 SilcServerKEInternalContext *proto_ctx;
1024 SilcServerConfigClient *cconfig = NULL;
1025 SilcServerConfigServer *sconfig = NULL;
1026 SilcServerConfigRouter *rconfig = NULL;
1027 SilcServerConfigDeny *deny;
1030 SILC_LOG_DEBUG(("Start"));
1032 /* Check whether we could resolve both IP and FQDN. */
1033 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1034 server->config->require_reverse_lookup)) {
1035 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1036 sock->hostname ? sock->hostname :
1037 sock->ip ? sock->ip : ""));
1038 server->stat.conn_failures++;
1039 silc_server_disconnect_remote(server, sock,
1040 "Server closed connection: Unknown host");
1044 /* Register the connection for network input and output. This sets
1045 that scheduler will listen for incoming packets for this connection
1046 and sets that outgoing packets may be sent to this connection as well.
1047 However, this doesn't set the scheduler for outgoing traffic, it
1048 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1049 later when outgoing data is available. */
1050 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1052 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1055 port = server->sockets[server->sock]->port; /* Listenning port */
1057 /* Check whether this connection is denied to connect to us. */
1058 deny = silc_server_config_find_denied(server, sock->ip);
1060 deny = silc_server_config_find_denied(server, sock->hostname);
1062 /* The connection is denied */
1063 SILC_LOG_INFO(("Connection %s (%s) is denied",
1064 sock->hostname, sock->ip));
1065 silc_server_disconnect_remote(server, sock, deny->reason ?
1067 "Server closed connection: "
1068 "Connection refused");
1069 server->stat.conn_failures++;
1073 /* Check whether we have configured this sort of connection at all. We
1074 have to check all configurations since we don't know what type of
1075 connection this is. */
1076 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1077 cconfig = silc_server_config_find_client(server, sock->hostname);
1078 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1079 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1080 if (server->server_type == SILC_ROUTER) {
1081 if (!(rconfig = silc_server_config_find_router_conn(server,
1083 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1086 if (!cconfig && !sconfig && !rconfig) {
1087 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1089 silc_server_disconnect_remote(server, sock,
1090 "Server closed connection: "
1091 "Connection refused");
1092 server->stat.conn_failures++;
1096 /* The connection is allowed */
1098 /* Allocate internal context for key exchange protocol. This is
1099 sent as context for the protocol. */
1100 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1101 proto_ctx->server = context;
1102 proto_ctx->sock = sock;
1103 proto_ctx->rng = server->rng;
1104 proto_ctx->responder = TRUE;
1105 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1106 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1107 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1109 /* Take flags for key exchange. Since we do not know what type of connection
1110 this is, we go through all found configurations and use the global ones
1111 as well. This will result always into strictest key exchange flags. */
1112 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1113 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1114 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1115 if (server->config->param.key_exchange_pfs)
1116 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1118 /* Prepare the connection for key exchange protocol. We allocate the
1119 protocol but will not start it yet. The connector will be the
1120 initiator of the protocol thus we will wait for initiation from
1121 there before we start the protocol. */
1122 server->stat.auth_attempts++;
1123 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1124 &sock->protocol, proto_ctx,
1125 silc_server_accept_new_connection_second);
1127 /* Register a timeout task that will be executed if the connector
1128 will not start the key exchange protocol within specified timeout
1129 and the connection will be closed. */
1130 proto_ctx->timeout_task =
1131 silc_schedule_task_add(server->schedule, sock->sock,
1132 silc_server_timeout_remote,
1133 context, server->config->key_exchange_timeout, 0,
1138 /* Accepts new connections to the server. Accepting new connections are
1139 done in three parts to make it async. */
1141 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1143 SilcServer server = (SilcServer)context;
1144 SilcSocketConnection newsocket;
1147 SILC_LOG_DEBUG(("Accepting new connection"));
1149 server->stat.conn_attempts++;
1151 sock = silc_net_accept_connection(server->sock);
1153 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1154 server->stat.conn_failures++;
1158 /* Check for maximum allowed connections */
1159 if (sock > server->config->param.connections_max) {
1160 SILC_LOG_ERROR(("Refusing connection, server is full"));
1161 server->stat.conn_failures++;
1162 silc_net_close_connection(sock);
1166 /* Set socket options */
1167 silc_net_set_socket_nonblock(sock);
1168 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1170 /* We don't create a ID yet, since we don't know what type of connection
1171 this is yet. But, we do add the connection to the socket table. */
1172 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1173 server->sockets[sock] = newsocket;
1175 /* Perform asynchronous host lookup. This will lookup the IP and the
1176 FQDN of the remote connection. After the lookup is done the connection
1177 is accepted further. */
1178 silc_socket_host_lookup(newsocket, TRUE,
1179 silc_server_accept_new_connection_lookup, context,
1183 /* Second part of accepting new connection. Key exchange protocol has been
1184 performed and now it is time to do little connection authentication
1185 protocol to figure out whether this connection is client or server
1186 and whether it has right to access this server (especially server
1187 connections needs to be authenticated). */
1189 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1191 SilcProtocol protocol = (SilcProtocol)context;
1192 SilcServerKEInternalContext *ctx =
1193 (SilcServerKEInternalContext *)protocol->context;
1194 SilcServer server = (SilcServer)ctx->server;
1195 SilcSocketConnection sock = ctx->sock;
1196 SilcServerConnAuthInternalContext *proto_ctx;
1198 SILC_LOG_DEBUG(("Start"));
1200 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1201 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1202 /* Error occured during protocol */
1203 silc_protocol_free(protocol);
1204 sock->protocol = NULL;
1205 silc_ske_free_key_material(ctx->keymat);
1207 silc_packet_context_free(ctx->packet);
1209 silc_ske_free(ctx->ske);
1210 silc_free(ctx->dest_id);
1211 silc_server_config_unref(&ctx->cconfig);
1212 silc_server_config_unref(&ctx->sconfig);
1213 silc_server_config_unref(&ctx->rconfig);
1215 silc_schedule_task_del_by_callback(server->schedule,
1216 silc_server_failure_callback);
1217 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1218 "Key exchange failed");
1219 server->stat.auth_failures++;
1223 /* We now have the key material as the result of the key exchange
1224 protocol. Take the key material into use. Free the raw key material
1225 as soon as we've set them into use. */
1226 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1227 ctx->sock, ctx->keymat,
1228 ctx->ske->prop->cipher,
1229 ctx->ske->prop->pkcs,
1230 ctx->ske->prop->hash,
1231 ctx->ske->prop->hmac,
1232 ctx->ske->prop->group,
1234 silc_protocol_free(protocol);
1235 sock->protocol = NULL;
1236 silc_ske_free_key_material(ctx->keymat);
1238 silc_packet_context_free(ctx->packet);
1240 silc_ske_free(ctx->ske);
1241 silc_free(ctx->dest_id);
1242 silc_server_config_unref(&ctx->cconfig);
1243 silc_server_config_unref(&ctx->sconfig);
1244 silc_server_config_unref(&ctx->rconfig);
1246 silc_schedule_task_del_by_callback(server->schedule,
1247 silc_server_failure_callback);
1248 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1249 "Key exchange failed");
1250 server->stat.auth_failures++;
1253 silc_ske_free_key_material(ctx->keymat);
1255 /* Allocate internal context for the authentication protocol. This
1256 is sent as context for the protocol. */
1257 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1258 proto_ctx->server = (void *)server;
1259 proto_ctx->sock = sock;
1260 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1261 proto_ctx->responder = TRUE;
1262 proto_ctx->dest_id_type = ctx->dest_id_type;
1263 proto_ctx->dest_id = ctx->dest_id;
1264 proto_ctx->cconfig = ctx->cconfig;
1265 proto_ctx->sconfig = ctx->sconfig;
1266 proto_ctx->rconfig = ctx->rconfig;
1268 /* Free old protocol as it is finished now */
1269 silc_protocol_free(protocol);
1271 silc_packet_context_free(ctx->packet);
1273 sock->protocol = NULL;
1275 /* Allocate the authentication protocol. This is allocated here
1276 but we won't start it yet. We will be receiving party of this
1277 protocol thus we will wait that connecting party will make
1278 their first move. */
1279 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1280 &sock->protocol, proto_ctx,
1281 silc_server_accept_new_connection_final);
1283 /* Register timeout task. If the protocol is not executed inside
1284 this timelimit the connection will be terminated. */
1285 proto_ctx->timeout_task =
1286 silc_schedule_task_add(server->schedule, sock->sock,
1287 silc_server_timeout_remote,
1289 server->config->conn_auth_timeout, 0,
1294 /* Final part of accepting new connection. The connection has now
1295 been authenticated and keys has been exchanged. We also know whether
1296 this is client or server connection. */
1298 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1300 SilcProtocol protocol = (SilcProtocol)context;
1301 SilcServerConnAuthInternalContext *ctx =
1302 (SilcServerConnAuthInternalContext *)protocol->context;
1303 SilcServer server = (SilcServer)ctx->server;
1304 SilcSocketConnection sock = ctx->sock;
1305 SilcServerHBContext hb_context;
1306 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1308 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1310 SILC_LOG_DEBUG(("Start"));
1312 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1313 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1314 /* Error occured during protocol */
1315 silc_protocol_free(protocol);
1316 sock->protocol = NULL;
1318 silc_packet_context_free(ctx->packet);
1320 silc_ske_free(ctx->ske);
1321 silc_free(ctx->dest_id);
1322 silc_server_config_unref(&ctx->cconfig);
1323 silc_server_config_unref(&ctx->sconfig);
1324 silc_server_config_unref(&ctx->rconfig);
1326 silc_schedule_task_del_by_callback(server->schedule,
1327 silc_server_failure_callback);
1328 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1329 "Authentication failed");
1330 server->stat.auth_failures++;
1334 entry->data.last_receive = time(NULL);
1336 switch (ctx->conn_type) {
1337 case SILC_SOCKET_TYPE_CLIENT:
1339 SilcClientEntry client;
1340 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1342 /* Verify whether this connection is after all allowed to connect */
1343 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1344 &server->config->param,
1345 conn->param, ctx->ske)) {
1346 server->stat.auth_failures++;
1350 SILC_LOG_DEBUG(("Remote host is client"));
1351 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1354 /* Add the client to the client ID cache. The nickname and Client ID
1355 and other information is created after we have received NEW_CLIENT
1356 packet from client. */
1357 client = silc_idlist_add_client(server->local_list,
1358 NULL, NULL, NULL, NULL, NULL, sock, 0);
1360 SILC_LOG_ERROR(("Could not add new client to cache"));
1361 silc_free(sock->user_data);
1362 silc_server_disconnect_remote(server, sock,
1363 "Server closed connection: "
1364 "Authentication failed");
1365 server->stat.auth_failures++;
1370 server->stat.my_clients++;
1371 server->stat.clients++;
1372 if (server->server_type == SILC_ROUTER)
1373 server->stat.cell_clients++;
1375 /* Get connection parameters */
1377 if (conn->param->keepalive_secs)
1378 hearbeat_timeout = conn->param->keepalive_secs;
1381 id_entry = (void *)client;
1384 case SILC_SOCKET_TYPE_SERVER:
1385 case SILC_SOCKET_TYPE_ROUTER:
1387 SilcServerEntry new_server;
1388 bool initiator = FALSE;
1389 bool backup_local = FALSE;
1390 bool backup_router = FALSE;
1391 char *backup_replace_ip = NULL;
1392 SilcUInt16 backup_replace_port = 0;
1393 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1394 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1396 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1397 /* Verify whether this connection is after all allowed to connect */
1398 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1399 &server->config->param,
1400 rconn ? rconn->param : NULL,
1402 server->stat.auth_failures++;
1408 if (rconn->param->keepalive_secs)
1409 hearbeat_timeout = rconn->param->keepalive_secs;
1412 initiator = rconn->initiator;
1413 backup_local = rconn->backup_local;
1414 backup_router = rconn->backup_router;
1415 backup_replace_ip = rconn->backup_replace_ip;
1416 backup_replace_port = rconn->backup_replace_port;
1420 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1421 /* Verify whether this connection is after all allowed to connect */
1422 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1423 &server->config->param,
1424 sconn ? sconn->param : NULL,
1426 server->stat.auth_failures++;
1431 if (sconn->param->keepalive_secs)
1432 hearbeat_timeout = sconn->param->keepalive_secs;
1435 backup_router = sconn->backup_router;
1439 SILC_LOG_DEBUG(("Remote host is %s",
1440 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1441 "server" : (backup_router ?
1442 "backup router" : "router")));
1443 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1444 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1445 "server" : (backup_router ?
1446 "backup router" : "router")));
1448 /* Add the server into server cache. The server name and Server ID
1449 is updated after we have received NEW_SERVER packet from the
1450 server. We mark ourselves as router for this server if we really
1453 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1454 server->local_list : (backup_router ?
1455 server->local_list :
1456 server->global_list)),
1458 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1459 SILC_SERVER : SILC_ROUTER),
1461 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1462 server->id_entry : (backup_router ?
1463 server->id_entry : NULL)),
1466 SILC_LOG_ERROR(("Could not add new server to cache"));
1467 silc_free(sock->user_data);
1468 silc_server_disconnect_remote(server, sock,
1469 "Server closed connection: "
1470 "Authentication failed");
1471 server->stat.auth_failures++;
1476 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1477 server->stat.my_servers++;
1479 server->stat.my_routers++;
1480 server->stat.servers++;
1482 id_entry = (void *)new_server;
1484 /* If the incoming connection is router and marked as backup router
1485 then add it to be one of our backups */
1486 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1487 silc_server_backup_add(server, new_server, backup_replace_ip,
1488 backup_replace_port, backup_local);
1490 /* Change it back to SERVER type since that's what it really is. */
1492 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1494 new_server->server_type = SILC_BACKUP_ROUTER;
1497 /* Check whether this connection is to be our primary router connection
1498 if we do not already have the primary route. */
1499 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1500 if (silc_server_config_is_primary_route(server) && !initiator)
1503 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1504 server->standalone = FALSE;
1505 if (!server->id_entry->router) {
1506 server->id_entry->router = id_entry;
1507 server->router = id_entry;
1518 sock->type = ctx->conn_type;
1520 /* Add the common data structure to the ID entry. */
1521 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1523 /* Add to sockets internal pointer for fast referencing */
1524 silc_free(sock->user_data);
1525 sock->user_data = id_entry;
1527 /* Connection has been fully established now. Everything is ok. */
1528 SILC_LOG_DEBUG(("New connection authenticated"));
1530 /* Perform keepalive. The `hb_context' will be freed automatically
1531 when finally calling the silc_socket_free function. */
1532 hb_context = silc_calloc(1, sizeof(*hb_context));
1533 hb_context->server = server;
1534 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1535 silc_server_perform_heartbeat,
1539 silc_schedule_task_del_by_callback(server->schedule,
1540 silc_server_failure_callback);
1541 silc_protocol_free(protocol);
1543 silc_packet_context_free(ctx->packet);
1545 silc_ske_free(ctx->ske);
1546 silc_free(ctx->dest_id);
1547 silc_server_config_unref(&ctx->cconfig);
1548 silc_server_config_unref(&ctx->sconfig);
1549 silc_server_config_unref(&ctx->rconfig);
1551 sock->protocol = NULL;
1554 /* This function is used to read packets from network and send packets to
1555 network. This is usually a generic task. */
1557 SILC_TASK_CALLBACK(silc_server_packet_process)
1559 SilcServer server = (SilcServer)context;
1560 SilcSocketConnection sock = server->sockets[fd];
1561 SilcIDListData idata;
1562 SilcCipher cipher = NULL;
1563 SilcHmac hmac = NULL;
1564 SilcUInt32 sequence = 0;
1570 SILC_LOG_DEBUG(("Processing packet"));
1572 /* Packet sending */
1574 if (type == SILC_TASK_WRITE) {
1575 /* Do not send data to disconnected connection */
1576 if (SILC_IS_DISCONNECTED(sock))
1579 server->stat.packets_sent++;
1581 /* Send the packet */
1582 ret = silc_packet_send(sock, TRUE);
1584 /* If returned -2 could not write to connection now, will do
1590 SILC_LOG_ERROR(("Error sending packet to connection "
1591 "%s:%d [%s]", sock->hostname, sock->port,
1592 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1593 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1594 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1599 /* The packet has been sent and now it is time to set the connection
1600 back to only for input. When there is again some outgoing data
1601 available for this connection it will be set for output as well.
1602 This call clears the output setting and sets it only for input. */
1603 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1604 SILC_UNSET_OUTBUF_PENDING(sock);
1606 silc_buffer_clear(sock->outbuf);
1610 /* Packet receiving */
1612 /* Read some data from connection */
1613 ret = silc_packet_receive(sock);
1617 SILC_LOG_ERROR(("Error receiving packet from connection "
1618 "%s:%d [%s] %s", sock->hostname, sock->port,
1619 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1620 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1621 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1622 "Router"), strerror(errno)));
1628 SILC_LOG_DEBUG(("Read EOF"));
1630 /* If connection is disconnecting already we will finally
1631 close the connection */
1632 if (SILC_IS_DISCONNECTING(sock)) {
1633 if (sock->user_data)
1634 silc_server_free_sock_user_data(server, sock, NULL);
1635 silc_server_close_connection(server, sock);
1639 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1640 SILC_SET_DISCONNECTING(sock);
1642 if (sock->user_data) {
1644 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1645 silc_server_free_sock_user_data(server, sock, tmp);
1647 silc_server_free_sock_user_data(server, sock, NULL);
1648 } else if (server->router_conn && server->router_conn->sock == sock &&
1649 !server->router && server->standalone)
1650 silc_schedule_task_add(server->schedule, 0,
1651 silc_server_connect_to_router,
1654 SILC_TASK_PRI_NORMAL);
1656 silc_server_close_connection(server, sock);
1660 /* If connection is disconnecting or disconnected we will ignore
1662 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1663 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1667 server->stat.packets_received++;
1669 /* Get keys and stuff from ID entry */
1670 idata = (SilcIDListData)sock->user_data;
1672 cipher = idata->receive_key;
1673 hmac = idata->hmac_receive;
1674 sequence = idata->psn_receive;
1677 /* Process the packet. This will call the parser that will then
1678 decrypt and parse the packet. */
1679 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1680 TRUE : FALSE, cipher, hmac, sequence,
1681 silc_server_packet_parse, server);
1683 /* If this socket connection is not authenticated yet and the packet
1684 processing failed we will drop the connection since it can be
1685 a malicious flooder. */
1686 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1687 (!sock->protocol || sock->protocol->protocol->type ==
1688 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1689 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1690 SILC_SET_DISCONNECTING(sock);
1692 if (sock->user_data)
1693 silc_server_free_sock_user_data(server, sock, NULL);
1694 silc_server_close_connection(server, sock);
1698 /* Parses whole packet, received earlier. */
1700 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1702 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1703 SilcServer server = (SilcServer)parse_ctx->context;
1704 SilcSocketConnection sock = parse_ctx->sock;
1705 SilcPacketContext *packet = parse_ctx->packet;
1706 SilcIDListData idata = (SilcIDListData)sock->user_data;
1709 SILC_LOG_DEBUG(("Start"));
1711 /* Parse the packet */
1712 if (parse_ctx->normal)
1713 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1715 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1717 /* If entry is disabled ignore what we got. */
1718 if (ret != SILC_PACKET_RESUME_ROUTER &&
1719 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1720 SILC_LOG_DEBUG(("Connection is disabled"));
1724 if (ret == SILC_PACKET_NONE)
1727 /* Check that the the current client ID is same as in the client's packet. */
1728 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1729 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1730 if (client && client->id) {
1731 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1732 packet->src_id_type);
1733 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1741 if (server->server_type == SILC_ROUTER) {
1742 /* Route the packet if it is not destined to us. Other ID types but
1743 server are handled separately after processing them. */
1744 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1745 packet->dst_id_type == SILC_ID_SERVER &&
1746 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1747 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1749 /* Route the packet to fastest route for the destination ID */
1750 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1751 packet->dst_id_type);
1754 silc_server_packet_route(server,
1755 silc_server_route_get(server, id,
1756 packet->dst_id_type),
1763 /* Parse the incoming packet type */
1764 silc_server_packet_parse_type(server, sock, packet);
1766 if (server->server_type == SILC_ROUTER) {
1767 /* Broadcast packet if it is marked as broadcast packet and it is
1768 originated from router and we are router. */
1769 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1770 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1771 !server->standalone) {
1772 /* Broadcast to our primary route */
1773 silc_server_packet_broadcast(server, server->router->connection, packet);
1775 /* If we have backup routers then we need to feed all broadcast
1776 data to those servers. */
1777 silc_server_backup_broadcast(server, sock, packet);
1782 silc_packet_context_free(packet);
1783 silc_free(parse_ctx);
1786 /* Parser callback called by silc_packet_receive_process. This merely
1787 registers timeout that will handle the actual parsing when appropriate. */
1789 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1792 SilcServer server = (SilcServer)context;
1793 SilcSocketConnection sock = parser_context->sock;
1794 SilcIDListData idata = (SilcIDListData)sock->user_data;
1797 idata->psn_receive = parser_context->packet->sequence + 1;
1799 /* If protocol for this connection is key exchange or rekey then we'll
1800 process all packets synchronously, since there might be packets in
1801 queue that we are not able to decrypt without first processing the
1802 packets before them. */
1803 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1804 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1805 (sock->protocol && sock->protocol->protocol &&
1806 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1807 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1808 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1811 /* Reprocess data since we'll return FALSE here. This is because
1812 the idata->receive_key might have become valid in the last packet
1813 and we want to call this processor with valid cipher. */
1815 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1816 TRUE : FALSE, idata->receive_key,
1817 idata->hmac_receive, idata->psn_receive,
1818 silc_server_packet_parse, server);
1820 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1821 TRUE : FALSE, NULL, NULL, 0,
1822 silc_server_packet_parse, server);
1826 switch (sock->type) {
1827 case SILC_SOCKET_TYPE_UNKNOWN:
1828 case SILC_SOCKET_TYPE_CLIENT:
1829 /* Parse the packet with timeout */
1830 silc_schedule_task_add(server->schedule, sock->sock,
1831 silc_server_packet_parse_real,
1832 (void *)parser_context, 0, 100000,
1834 SILC_TASK_PRI_NORMAL);
1836 case SILC_SOCKET_TYPE_SERVER:
1837 case SILC_SOCKET_TYPE_ROUTER:
1838 /* Packets from servers are parsed immediately */
1839 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1849 /* Parses the packet type and calls what ever routines the packet type
1850 requires. This is done for all incoming packets. */
1852 void silc_server_packet_parse_type(SilcServer server,
1853 SilcSocketConnection sock,
1854 SilcPacketContext *packet)
1856 SilcPacketType type = packet->type;
1857 SilcIDListData idata = (SilcIDListData)sock->user_data;
1859 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1861 /* Parse the packet type */
1863 case SILC_PACKET_DISCONNECT:
1864 SILC_LOG_DEBUG(("Disconnect packet"));
1865 if (packet->flags & SILC_PACKET_FLAG_LIST)
1867 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1868 /* Duplicate to null terminate the string. */
1869 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1870 SILC_LOG_ERROR(("%s", message));
1875 case SILC_PACKET_SUCCESS:
1877 * Success received for something. For now we can have only
1878 * one protocol for connection executing at once hence this
1879 * success message is for whatever protocol is executing currently.
1881 SILC_LOG_DEBUG(("Success packet"));
1882 if (packet->flags & SILC_PACKET_FLAG_LIST)
1885 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1888 case SILC_PACKET_FAILURE:
1890 * Failure received for something. For now we can have only
1891 * one protocol for connection executing at once hence this
1892 * failure message is for whatever protocol is executing currently.
1894 SILC_LOG_DEBUG(("Failure packet"));
1895 if (packet->flags & SILC_PACKET_FLAG_LIST)
1897 if (sock->protocol) {
1898 SilcServerFailureContext f;
1899 f = silc_calloc(1, sizeof(*f));
1903 /* We will wait 5 seconds to process this failure packet */
1904 silc_schedule_task_add(server->schedule, sock->sock,
1905 silc_server_failure_callback, (void *)f, 5, 0,
1906 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1910 case SILC_PACKET_REJECT:
1911 SILC_LOG_DEBUG(("Reject packet"));
1912 if (packet->flags & SILC_PACKET_FLAG_LIST)
1917 case SILC_PACKET_NOTIFY:
1919 * Received notify packet. Server can receive notify packets from
1920 * router. Server then relays the notify messages to clients if needed.
1922 SILC_LOG_DEBUG(("Notify packet"));
1923 if (packet->flags & SILC_PACKET_FLAG_LIST)
1924 silc_server_notify_list(server, sock, packet);
1926 silc_server_notify(server, sock, packet);
1932 case SILC_PACKET_CHANNEL_MESSAGE:
1934 * Received channel message. Channel messages are special packets
1935 * (although probably most common ones) thus they are handled
1938 SILC_LOG_DEBUG(("Channel Message packet"));
1939 if (packet->flags & SILC_PACKET_FLAG_LIST)
1941 idata->last_receive = time(NULL);
1942 silc_server_channel_message(server, sock, packet);
1945 case SILC_PACKET_CHANNEL_KEY:
1947 * Received key for channel. As channels are created by the router
1948 * the keys are as well. We will distribute the key to all of our
1949 * locally connected clients on the particular channel. Router
1950 * never receives this channel and thus is ignored.
1952 SILC_LOG_DEBUG(("Channel Key packet"));
1953 if (packet->flags & SILC_PACKET_FLAG_LIST)
1955 silc_server_channel_key(server, sock, packet);
1961 case SILC_PACKET_COMMAND:
1963 * Recived command. Processes the command request and allocates the
1964 * command context and calls the command.
1966 SILC_LOG_DEBUG(("Command packet"));
1967 if (packet->flags & SILC_PACKET_FLAG_LIST)
1969 silc_server_command_process(server, sock, packet);
1972 case SILC_PACKET_COMMAND_REPLY:
1974 * Received command reply packet. Received command reply to command. It
1975 * may be reply to command sent by us or reply to command sent by client
1976 * that we've routed further.
1978 SILC_LOG_DEBUG(("Command Reply packet"));
1979 if (packet->flags & SILC_PACKET_FLAG_LIST)
1981 silc_server_command_reply(server, sock, packet);
1985 * Private Message packets
1987 case SILC_PACKET_PRIVATE_MESSAGE:
1989 * Received private message packet. The packet is coming from either
1992 SILC_LOG_DEBUG(("Private Message packet"));
1993 if (packet->flags & SILC_PACKET_FLAG_LIST)
1995 idata->last_receive = time(NULL);
1996 silc_server_private_message(server, sock, packet);
1999 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2001 * Private message key packet.
2003 if (packet->flags & SILC_PACKET_FLAG_LIST)
2005 silc_server_private_message_key(server, sock, packet);
2009 * Key Exchange protocol packets
2011 case SILC_PACKET_KEY_EXCHANGE:
2012 SILC_LOG_DEBUG(("KE packet"));
2013 if (packet->flags & SILC_PACKET_FLAG_LIST)
2016 if (sock->protocol && sock->protocol->protocol &&
2017 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2018 SilcServerKEInternalContext *proto_ctx =
2019 (SilcServerKEInternalContext *)sock->protocol->context;
2021 proto_ctx->packet = silc_packet_context_dup(packet);
2023 /* Let the protocol handle the packet */
2024 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2026 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2027 "protocol active, packet dropped."));
2031 case SILC_PACKET_KEY_EXCHANGE_1:
2032 SILC_LOG_DEBUG(("KE 1 packet"));
2033 if (packet->flags & SILC_PACKET_FLAG_LIST)
2036 if (sock->protocol && sock->protocol->protocol &&
2037 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2038 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2040 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2041 SilcServerRekeyInternalContext *proto_ctx =
2042 (SilcServerRekeyInternalContext *)sock->protocol->context;
2044 if (proto_ctx->packet)
2045 silc_packet_context_free(proto_ctx->packet);
2047 proto_ctx->packet = silc_packet_context_dup(packet);
2049 /* Let the protocol handle the packet */
2050 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2052 SilcServerKEInternalContext *proto_ctx =
2053 (SilcServerKEInternalContext *)sock->protocol->context;
2055 if (proto_ctx->packet)
2056 silc_packet_context_free(proto_ctx->packet);
2058 proto_ctx->packet = silc_packet_context_dup(packet);
2059 proto_ctx->dest_id_type = packet->src_id_type;
2060 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2061 packet->src_id_type);
2062 if (!proto_ctx->dest_id)
2065 /* Let the protocol handle the packet */
2066 silc_protocol_execute(sock->protocol, server->schedule,
2070 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2071 "protocol active, packet dropped."));
2075 case SILC_PACKET_KEY_EXCHANGE_2:
2076 SILC_LOG_DEBUG(("KE 2 packet"));
2077 if (packet->flags & SILC_PACKET_FLAG_LIST)
2080 if (sock->protocol && sock->protocol->protocol &&
2081 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2082 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2084 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2085 SilcServerRekeyInternalContext *proto_ctx =
2086 (SilcServerRekeyInternalContext *)sock->protocol->context;
2088 if (proto_ctx->packet)
2089 silc_packet_context_free(proto_ctx->packet);
2091 proto_ctx->packet = silc_packet_context_dup(packet);
2093 /* Let the protocol handle the packet */
2094 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2096 SilcServerKEInternalContext *proto_ctx =
2097 (SilcServerKEInternalContext *)sock->protocol->context;
2099 if (proto_ctx->packet)
2100 silc_packet_context_free(proto_ctx->packet);
2102 proto_ctx->packet = silc_packet_context_dup(packet);
2103 proto_ctx->dest_id_type = packet->src_id_type;
2104 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2105 packet->src_id_type);
2106 if (!proto_ctx->dest_id)
2109 /* Let the protocol handle the packet */
2110 silc_protocol_execute(sock->protocol, server->schedule,
2114 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2115 "protocol active, packet dropped."));
2119 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2121 * Connection authentication request packet. When we receive this packet
2122 * we will send to the other end information about our mandatory
2123 * authentication method for the connection. This packet maybe received
2126 SILC_LOG_DEBUG(("Connection authentication request packet"));
2127 if (packet->flags & SILC_PACKET_FLAG_LIST)
2129 silc_server_connection_auth_request(server, sock, packet);
2133 * Connection Authentication protocol packets
2135 case SILC_PACKET_CONNECTION_AUTH:
2136 /* Start of the authentication protocol. We receive here the
2137 authentication data and will verify it. */
2138 SILC_LOG_DEBUG(("Connection auth packet"));
2139 if (packet->flags & SILC_PACKET_FLAG_LIST)
2142 if (sock->protocol && sock->protocol->protocol->type
2143 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2145 SilcServerConnAuthInternalContext *proto_ctx =
2146 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2148 proto_ctx->packet = silc_packet_context_dup(packet);
2150 /* Let the protocol handle the packet */
2151 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2153 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2154 "protocol active, packet dropped."));
2158 case SILC_PACKET_NEW_ID:
2160 * Received New ID packet. This includes some new ID that has been
2161 * created. It may be for client, server or channel. This is the way
2162 * to distribute information about new registered entities in the
2165 SILC_LOG_DEBUG(("New ID packet"));
2166 if (packet->flags & SILC_PACKET_FLAG_LIST)
2167 silc_server_new_id_list(server, sock, packet);
2169 silc_server_new_id(server, sock, packet);
2172 case SILC_PACKET_NEW_CLIENT:
2174 * Received new client packet. This includes client information that
2175 * we will use to create initial client ID. After creating new
2176 * ID we will send it to the client.
2178 SILC_LOG_DEBUG(("New Client packet"));
2179 if (packet->flags & SILC_PACKET_FLAG_LIST)
2181 silc_server_new_client(server, sock, packet);
2184 case SILC_PACKET_NEW_SERVER:
2186 * Received new server packet. This includes Server ID and some other
2187 * information that we may save. This is received after server has
2190 SILC_LOG_DEBUG(("New Server packet"));
2191 if (packet->flags & SILC_PACKET_FLAG_LIST)
2193 silc_server_new_server(server, sock, packet);
2196 case SILC_PACKET_NEW_CHANNEL:
2198 * Received new channel packet. Information about new channel in the
2199 * network are distributed using this packet.
2201 SILC_LOG_DEBUG(("New Channel packet"));
2202 if (packet->flags & SILC_PACKET_FLAG_LIST)
2203 silc_server_new_channel_list(server, sock, packet);
2205 silc_server_new_channel(server, sock, packet);
2208 case SILC_PACKET_HEARTBEAT:
2210 * Received heartbeat.
2212 SILC_LOG_DEBUG(("Heartbeat packet"));
2213 if (packet->flags & SILC_PACKET_FLAG_LIST)
2217 case SILC_PACKET_KEY_AGREEMENT:
2219 * Received heartbeat.
2221 SILC_LOG_DEBUG(("Key agreement packet"));
2222 if (packet->flags & SILC_PACKET_FLAG_LIST)
2224 silc_server_key_agreement(server, sock, packet);
2227 case SILC_PACKET_REKEY:
2229 * Received re-key packet. The sender wants to regenerate the session
2232 SILC_LOG_DEBUG(("Re-key packet"));
2233 if (packet->flags & SILC_PACKET_FLAG_LIST)
2235 silc_server_rekey(server, sock, packet);
2238 case SILC_PACKET_REKEY_DONE:
2240 * The re-key is done.
2242 SILC_LOG_DEBUG(("Re-key done packet"));
2243 if (packet->flags & SILC_PACKET_FLAG_LIST)
2246 if (sock->protocol && sock->protocol->protocol &&
2247 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2249 SilcServerRekeyInternalContext *proto_ctx =
2250 (SilcServerRekeyInternalContext *)sock->protocol->context;
2252 if (proto_ctx->packet)
2253 silc_packet_context_free(proto_ctx->packet);
2255 proto_ctx->packet = silc_packet_context_dup(packet);
2257 /* Let the protocol handle the packet */
2258 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2260 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2261 "protocol active, packet dropped."));
2265 case SILC_PACKET_FTP:
2267 SILC_LOG_DEBUG(("FTP packet"));
2268 if (packet->flags & SILC_PACKET_FLAG_LIST)
2270 silc_server_ftp(server, sock, packet);
2273 case SILC_PACKET_RESUME_ROUTER:
2274 /* Resume router packet received. This packet is received for backup
2275 router resuming protocol. */
2276 SILC_LOG_DEBUG(("Resume router packet"));
2277 if (packet->flags & SILC_PACKET_FLAG_LIST)
2279 silc_server_backup_resume_router(server, sock, packet);
2283 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2289 /* Creates connection to a remote router. */
2291 void silc_server_create_connection(SilcServer server,
2292 const char *remote_host, SilcUInt32 port)
2294 SilcServerConnection sconn;
2296 /* Allocate connection object for hold connection specific stuff. */
2297 sconn = silc_calloc(1, sizeof(*sconn));
2298 sconn->server = server;
2299 sconn->remote_host = strdup(remote_host);
2300 sconn->remote_port = port;
2301 sconn->no_reconnect = TRUE;
2303 silc_schedule_task_add(server->schedule, 0,
2304 silc_server_connect_router,
2305 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2306 SILC_TASK_PRI_NORMAL);
2309 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2311 silc_socket_free((SilcSocketConnection)context);
2314 /* Closes connection to socket connection */
2316 void silc_server_close_connection(SilcServer server,
2317 SilcSocketConnection sock)
2319 if (!server->sockets[sock->sock])
2322 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2324 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2325 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2326 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2329 /* We won't listen for this connection anymore */
2330 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2332 /* Unregister all tasks */
2333 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2335 /* Close the actual connection */
2336 silc_net_close_connection(sock->sock);
2337 server->sockets[sock->sock] = NULL;
2339 /* If sock->user_data is NULL then we'll check for active protocols
2340 here since the silc_server_free_sock_user_data has not been called
2341 for this connection. */
2342 if (!sock->user_data) {
2343 /* If any protocol is active cancel its execution. It will call
2344 the final callback which will finalize the disconnection. */
2345 if (sock->protocol) {
2346 silc_protocol_cancel(sock->protocol, server->schedule);
2347 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2348 silc_protocol_execute_final(sock->protocol, server->schedule);
2349 sock->protocol = NULL;
2354 silc_schedule_task_add(server->schedule, 0,
2355 silc_server_close_connection_final,
2356 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2357 SILC_TASK_PRI_NORMAL);
2360 /* Sends disconnect message to remote connection and disconnects the
2363 void silc_server_disconnect_remote(SilcServer server,
2364 SilcSocketConnection sock,
2365 const char *fmt, ...)
2368 unsigned char buf[4096];
2373 memset(buf, 0, sizeof(buf));
2375 vsprintf(buf, fmt, ap);
2378 SILC_LOG_DEBUG(("Disconnecting remote host"));
2380 /* Notify remote end that the conversation is over. The notify message
2381 is tried to be sent immediately. */
2382 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2383 buf, strlen(buf), TRUE);
2384 silc_server_packet_queue_purge(server, sock);
2386 /* Mark the connection to be disconnected */
2387 SILC_SET_DISCONNECTED(sock);
2388 silc_server_close_connection(server, sock);
2393 SilcClientEntry client;
2394 } *FreeClientInternal;
2396 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2398 FreeClientInternal i = (FreeClientInternal)context;
2400 silc_idlist_del_data(i->client);
2401 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2405 /* Frees client data and notifies about client's signoff. */
2407 void silc_server_free_client_data(SilcServer server,
2408 SilcSocketConnection sock,
2409 SilcClientEntry client,
2411 const char *signoff)
2413 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2415 /* If there is pending outgoing data for the client then purge it
2416 to the network before removing the client entry. */
2417 silc_server_packet_queue_purge(server, sock);
2422 /* Send SIGNOFF notify to routers. */
2423 if (notify && !server->standalone && server->router)
2424 silc_server_send_notify_signoff(server, server->router->connection,
2425 server->server_type == SILC_SERVER ?
2426 FALSE : TRUE, client->id, signoff);
2428 /* Remove client from all channels */
2430 silc_server_remove_from_channels(server, NULL, client,
2431 TRUE, (char *)signoff, TRUE);
2433 silc_server_remove_from_channels(server, NULL, client,
2434 FALSE, NULL, FALSE);
2436 /* Update statistics */
2437 server->stat.my_clients--;
2438 server->stat.clients--;
2439 if (server->server_type == SILC_ROUTER)
2440 server->stat.cell_clients--;
2441 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2442 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2444 /* We will not delete the client entry right away. We will take it
2445 into history (for WHOWAS command) for 5 minutes */
2448 silc_schedule_task_add(server->schedule, 0,
2449 silc_server_free_client_data_timeout,
2451 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2452 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2453 client->router = NULL;
2454 client->connection = NULL;
2458 /* Frees user_data pointer from socket connection object. This also sends
2459 appropriate notify packets to the network to inform about leaving
2462 void silc_server_free_sock_user_data(SilcServer server,
2463 SilcSocketConnection sock,
2464 const char *signoff_message)
2466 SILC_LOG_DEBUG(("Start"));
2468 switch (sock->type) {
2469 case SILC_SOCKET_TYPE_CLIENT:
2471 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2472 silc_server_free_client_data(server, sock, user_data, TRUE,
2476 case SILC_SOCKET_TYPE_SERVER:
2477 case SILC_SOCKET_TYPE_ROUTER:
2479 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2480 SilcServerEntry backup_router = NULL;
2483 backup_router = silc_server_backup_get(server, user_data->id);
2485 /* If this was our primary router connection then we're lost to
2486 the outside world. */
2487 if (server->router == user_data) {
2488 /* Check whether we have a backup router connection */
2489 if (!backup_router || backup_router == user_data) {
2490 silc_schedule_task_add(server->schedule, 0,
2491 silc_server_connect_to_router,
2494 SILC_TASK_PRI_NORMAL);
2496 server->id_entry->router = NULL;
2497 server->router = NULL;
2498 server->standalone = TRUE;
2499 backup_router = NULL;
2501 SILC_LOG_INFO(("New primary router is backup router %s",
2502 backup_router->server_name));
2503 SILC_LOG_DEBUG(("New primary router is backup router %s",
2504 backup_router->server_name));
2505 server->id_entry->router = backup_router;
2506 server->router = backup_router;
2507 server->router_connect = time(0);
2508 server->backup_primary = TRUE;
2509 if (server->server_type == SILC_BACKUP_ROUTER) {
2510 server->server_type = SILC_ROUTER;
2512 /* We'll need to constantly try to reconnect to the primary
2513 router so that we'll see when it comes back online. */
2514 silc_server_backup_reconnect(server, sock->ip, sock->port,
2515 silc_server_backup_connected,
2519 /* Mark this connection as replaced */
2520 silc_server_backup_replaced_add(server, user_data->id,
2523 } else if (backup_router) {
2524 SILC_LOG_INFO(("Enabling the use of backup router %s",
2525 backup_router->server_name));
2526 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2527 backup_router->server_name));
2529 /* Mark this connection as replaced */
2530 silc_server_backup_replaced_add(server, user_data->id,
2534 if (!backup_router) {
2535 /* Free all client entries that this server owns as they will
2536 become invalid now as well. */
2538 silc_server_remove_clients_by_server(server, user_data, TRUE);
2539 if (server->server_type == SILC_SERVER)
2540 silc_server_remove_channels_by_server(server, user_data);
2542 /* Update the client entries of this server to the new backup
2543 router. This also removes the clients that *really* was owned
2544 by the primary router and went down with the router. */
2545 silc_server_update_clients_by_server(server, user_data, backup_router,
2547 silc_server_update_servers_by_server(server, user_data, backup_router);
2548 if (server->server_type == SILC_SERVER)
2549 silc_server_update_channels_by_server(server, user_data,
2553 /* Free the server entry */
2554 silc_server_backup_del(server, user_data);
2555 silc_server_backup_replaced_del(server, user_data);
2556 silc_idlist_del_data(user_data);
2557 if (!silc_idlist_del_server(server->local_list, user_data))
2558 silc_idlist_del_server(server->global_list, user_data);
2559 server->stat.my_servers--;
2560 server->stat.servers--;
2561 if (server->server_type == SILC_ROUTER)
2562 server->stat.cell_servers--;
2564 if (backup_router) {
2565 /* Announce all of our stuff that was created about 5 minutes ago.
2566 The backup router knows all the other stuff already. */
2567 if (server->server_type == SILC_ROUTER)
2568 silc_server_announce_servers(server, FALSE, time(0) - 300,
2569 backup_router->connection);
2571 /* Announce our clients and channels to the router */
2572 silc_server_announce_clients(server, time(0) - 300,
2573 backup_router->connection);
2574 silc_server_announce_channels(server, time(0) - 300,
2575 backup_router->connection);
2581 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2583 silc_idlist_del_data(user_data);
2584 silc_free(user_data);
2589 /* If any protocol is active cancel its execution */
2590 if (sock->protocol) {
2591 silc_protocol_cancel(sock->protocol, server->schedule);
2592 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2593 silc_protocol_execute_final(sock->protocol, server->schedule);
2594 sock->protocol = NULL;
2597 sock->user_data = NULL;
2600 /* Removes client from all channels it has joined. This is used when client
2601 connection is disconnected. If the client on a channel is last, the
2602 channel is removed as well. This sends the SIGNOFF notify types. */
2604 void silc_server_remove_from_channels(SilcServer server,
2605 SilcSocketConnection sock,
2606 SilcClientEntry client,
2608 char *signoff_message,
2611 SilcChannelEntry channel;
2612 SilcChannelClientEntry chl;
2613 SilcHashTableList htl;
2616 SILC_LOG_DEBUG(("Start"));
2618 if (!client || !client->id)
2621 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2623 /* Remove the client from all channels. The client is removed from
2624 the channels' user list. */
2625 silc_hash_table_list(client->channels, &htl);
2626 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2627 channel = chl->channel;
2629 /* Remove channel from client's channel list */
2630 silc_hash_table_del(client->channels, channel);
2632 /* Remove channel if there is no users anymore */
2633 if (server->server_type == SILC_ROUTER &&
2634 silc_hash_table_count(channel->user_list) < 2) {
2636 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2637 if (silc_idlist_del_channel(server->local_list, channel))
2638 server->stat.my_channels--;
2640 silc_idlist_del_channel(server->global_list, channel);
2644 /* Remove client from channel's client list */
2645 silc_hash_table_del(channel->user_list, chl->client);
2646 channel->user_count--;
2648 /* If there is no global users on the channel anymore mark the channel
2649 as local channel. Do not check if the removed client is local client. */
2650 if (server->server_type != SILC_ROUTER && channel->global_users &&
2651 chl->client->router && !silc_server_channel_has_global(channel))
2652 channel->global_users = FALSE;
2655 server->stat.my_chanclients--;
2657 /* If there is not at least one local user on the channel then we don't
2658 need the channel entry anymore, we can remove it safely. */
2659 if (server->server_type != SILC_ROUTER &&
2660 !silc_server_channel_has_local(channel)) {
2661 /* Notify about leaving client if this channel has global users. */
2662 if (notify && channel->global_users)
2663 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2664 SILC_NOTIFY_TYPE_SIGNOFF,
2665 signoff_message ? 2 : 1,
2666 clidp->data, clidp->len,
2667 signoff_message, signoff_message ?
2668 strlen(signoff_message) : 0);
2671 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2673 if (channel->founder_key) {
2674 /* The founder auth data exists, do not remove the channel entry */
2675 SilcChannelClientEntry chl2;
2676 SilcHashTableList htl2;
2678 channel->disabled = TRUE;
2680 silc_hash_table_list(channel->user_list, &htl2);
2681 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2682 silc_hash_table_del(chl2->client->channels, channel);
2683 silc_hash_table_del(channel->user_list, chl2->client);
2684 channel->user_count--;
2687 silc_hash_table_list_reset(&htl2);
2691 /* Remove the channel entry */
2692 if (silc_idlist_del_channel(server->local_list, channel))
2693 server->stat.my_channels--;
2695 silc_idlist_del_channel(server->global_list, channel);
2699 /* Send notify to channel about client leaving SILC and thus
2700 the entire channel. */
2702 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2703 SILC_NOTIFY_TYPE_SIGNOFF,
2704 signoff_message ? 2 : 1,
2705 clidp->data, clidp->len,
2706 signoff_message, signoff_message ?
2707 strlen(signoff_message) : 0);
2709 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2710 /* Re-generate channel key */
2711 if (!silc_server_create_channel_key(server, channel, 0))
2714 /* Send the channel key to the channel. The key of course is not sent
2715 to the client who was removed from the channel. */
2716 silc_server_send_channel_key(server, client->connection, channel,
2717 server->server_type == SILC_ROUTER ?
2718 FALSE : !server->standalone);
2723 silc_hash_table_list_reset(&htl);
2724 silc_buffer_free(clidp);
2727 /* Removes client from one channel. This is used for example when client
2728 calls LEAVE command to remove itself from the channel. Returns TRUE
2729 if channel still exists and FALSE if the channel is removed when
2730 last client leaves the channel. If `notify' is FALSE notify messages
2733 int silc_server_remove_from_one_channel(SilcServer server,
2734 SilcSocketConnection sock,
2735 SilcChannelEntry channel,
2736 SilcClientEntry client,
2739 SilcChannelClientEntry chl;
2742 SILC_LOG_DEBUG(("Start"));
2744 /* Get the entry to the channel, if this client is not on the channel
2746 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2749 /* Remove the client from the channel. The client is removed from
2750 the channel's user list. */
2752 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2754 /* Remove channel from client's channel list */
2755 silc_hash_table_del(client->channels, chl->channel);
2757 /* Remove channel if there is no users anymore */
2758 if (server->server_type == SILC_ROUTER &&
2759 silc_hash_table_count(channel->user_list) < 2) {
2761 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2762 if (silc_idlist_del_channel(server->local_list, channel))
2763 server->stat.my_channels--;
2765 silc_idlist_del_channel(server->global_list, channel);
2766 silc_buffer_free(clidp);
2770 /* Remove client from channel's client list */
2771 silc_hash_table_del(channel->user_list, chl->client);
2772 channel->user_count--;
2774 /* If there is no global users on the channel anymore mark the channel
2775 as local channel. Do not check if the client is local client. */
2776 if (server->server_type != SILC_ROUTER && channel->global_users &&
2777 chl->client->router && !silc_server_channel_has_global(channel))
2778 channel->global_users = FALSE;
2781 server->stat.my_chanclients--;
2783 /* If there is not at least one local user on the channel then we don't
2784 need the channel entry anymore, we can remove it safely. */
2785 if (server->server_type != SILC_ROUTER &&
2786 !silc_server_channel_has_local(channel)) {
2787 /* Notify about leaving client if this channel has global users. */
2788 if (notify && channel->global_users)
2789 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2790 SILC_NOTIFY_TYPE_LEAVE, 1,
2791 clidp->data, clidp->len);
2793 silc_buffer_free(clidp);
2796 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2798 if (channel->founder_key) {
2799 /* The founder auth data exists, do not remove the channel entry */
2800 SilcChannelClientEntry chl2;
2801 SilcHashTableList htl2;
2803 channel->disabled = TRUE;
2805 silc_hash_table_list(channel->user_list, &htl2);
2806 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2807 silc_hash_table_del(chl2->client->channels, channel);
2808 silc_hash_table_del(channel->user_list, chl2->client);
2809 channel->user_count--;
2812 silc_hash_table_list_reset(&htl2);
2816 /* Remove the channel entry */
2817 if (silc_idlist_del_channel(server->local_list, channel))
2818 server->stat.my_channels--;
2820 silc_idlist_del_channel(server->global_list, channel);
2824 /* Send notify to channel about client leaving the channel */
2826 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2827 SILC_NOTIFY_TYPE_LEAVE, 1,
2828 clidp->data, clidp->len);
2830 silc_buffer_free(clidp);
2834 /* Timeout callback. This is called if connection is idle or for some
2835 other reason is not responding within some period of time. This
2836 disconnects the remote end. */
2838 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2840 SilcServer server = (SilcServer)context;
2841 SilcSocketConnection sock = server->sockets[fd];
2843 SILC_LOG_DEBUG(("Start"));
2848 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2849 sock->hostname, sock->ip));
2851 /* If we have protocol active we must assure that we call the protocol's
2852 final callback so that all the memory is freed. */
2853 if (sock->protocol) {
2854 silc_protocol_cancel(sock->protocol, server->schedule);
2855 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2856 silc_protocol_execute_final(sock->protocol, server->schedule);
2857 sock->protocol = NULL;
2861 if (sock->user_data)
2862 silc_server_free_sock_user_data(server, sock, NULL);
2864 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2865 "Connection timeout");
2868 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2869 function may be used only by router. In real SILC network all channels
2870 are created by routers thus this function is never used by normal
2873 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2874 SilcServerID *router_id,
2880 SilcChannelID *channel_id;
2881 SilcChannelEntry entry;
2885 SILC_LOG_DEBUG(("Creating new channel"));
2888 cipher = SILC_DEFAULT_CIPHER;
2890 hmac = SILC_DEFAULT_HMAC;
2892 /* Allocate cipher */
2893 if (!silc_cipher_alloc(cipher, &key))
2897 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2898 silc_cipher_free(key);
2902 channel_name = strdup(channel_name);
2904 /* Create the channel ID */
2905 if (!silc_id_create_channel_id(server, router_id, server->rng,
2907 silc_free(channel_name);
2908 silc_cipher_free(key);
2909 silc_hmac_free(newhmac);
2913 /* Create the channel */
2914 entry = silc_idlist_add_channel(server->local_list, channel_name,
2915 SILC_CHANNEL_MODE_NONE, channel_id,
2916 NULL, key, newhmac, 0);
2918 silc_free(channel_name);
2919 silc_cipher_free(key);
2920 silc_hmac_free(newhmac);
2921 silc_free(channel_id);
2925 entry->cipher = strdup(cipher);
2926 entry->hmac_name = strdup(hmac);
2928 /* Now create the actual key material */
2929 if (!silc_server_create_channel_key(server, entry,
2930 silc_cipher_get_key_len(key) / 8)) {
2931 silc_idlist_del_channel(server->local_list, entry);
2935 /* Notify other routers about the new channel. We send the packet
2936 to our primary route. */
2937 if (broadcast && server->standalone == FALSE)
2938 silc_server_send_new_channel(server, server->router->connection, TRUE,
2939 channel_name, entry->id,
2940 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2943 server->stat.my_channels++;
2948 /* Same as above but creates the channel with Channel ID `channel_id. */
2951 silc_server_create_new_channel_with_id(SilcServer server,
2955 SilcChannelID *channel_id,
2958 SilcChannelEntry entry;
2962 SILC_LOG_DEBUG(("Creating new channel"));
2965 cipher = SILC_DEFAULT_CIPHER;
2967 hmac = SILC_DEFAULT_HMAC;
2969 /* Allocate cipher */
2970 if (!silc_cipher_alloc(cipher, &key))
2974 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2975 silc_cipher_free(key);
2979 channel_name = strdup(channel_name);
2981 /* Create the channel */
2982 entry = silc_idlist_add_channel(server->local_list, channel_name,
2983 SILC_CHANNEL_MODE_NONE, channel_id,
2984 NULL, key, newhmac, 0);
2986 silc_cipher_free(key);
2987 silc_hmac_free(newhmac);
2988 silc_free(channel_name);
2992 /* Now create the actual key material */
2993 if (!silc_server_create_channel_key(server, entry,
2994 silc_cipher_get_key_len(key) / 8)) {
2995 silc_idlist_del_channel(server->local_list, entry);
2999 /* Notify other routers about the new channel. We send the packet
3000 to our primary route. */
3001 if (broadcast && server->standalone == FALSE)
3002 silc_server_send_new_channel(server, server->router->connection, TRUE,
3003 channel_name, entry->id,
3004 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3007 server->stat.my_channels++;
3012 /* Channel's key re-key timeout callback. */
3014 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3016 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3017 SilcServer server = (SilcServer)rekey->context;
3021 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3024 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3027 /* Generates new channel key. This is used to create the initial channel key
3028 but also to re-generate new key for channel. If `key_len' is provided
3029 it is the bytes of the key length. */
3031 bool silc_server_create_channel_key(SilcServer server,
3032 SilcChannelEntry channel,
3036 unsigned char channel_key[32], hash[32];
3039 SILC_LOG_DEBUG(("Generating channel key"));
3041 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3042 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3046 if (!channel->channel_key)
3047 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3048 channel->channel_key = NULL;
3054 else if (channel->key_len)
3055 len = channel->key_len / 8;
3057 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3059 /* Create channel key */
3060 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3063 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3065 /* Remove old key if exists */
3067 memset(channel->key, 0, channel->key_len / 8);
3068 silc_free(channel->key);
3072 channel->key_len = len * 8;
3073 channel->key = silc_memdup(channel_key, len);
3074 memset(channel_key, 0, sizeof(channel_key));
3076 /* Generate HMAC key from the channel key data and set it */
3078 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3079 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3080 silc_hmac_set_key(channel->hmac, hash,
3081 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3082 memset(hash, 0, sizeof(hash));
3084 if (server->server_type == SILC_ROUTER) {
3085 if (!channel->rekey)
3086 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3087 channel->rekey->context = (void *)server;
3088 channel->rekey->channel = channel;
3089 channel->rekey->key_len = key_len;
3090 if (channel->rekey->task)
3091 silc_schedule_task_del(server->schedule, channel->rekey->task);
3093 channel->rekey->task =
3094 silc_schedule_task_add(server->schedule, 0,
3095 silc_server_channel_key_rekey,
3096 (void *)channel->rekey,
3097 server->config->channel_rekey_secs, 0,
3099 SILC_TASK_PRI_NORMAL);
3105 /* Saves the channel key found in the encoded `key_payload' buffer. This
3106 function is used when we receive Channel Key Payload and also when we're
3107 processing JOIN command reply. Returns entry to the channel. */
3109 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3110 SilcBuffer key_payload,
3111 SilcChannelEntry channel)
3113 SilcChannelKeyPayload payload = NULL;
3114 SilcChannelID *id = NULL;
3115 unsigned char *tmp, hash[32];
3119 SILC_LOG_DEBUG(("Start"));
3121 /* Decode channel key payload */
3122 payload = silc_channel_key_payload_parse(key_payload->data,
3125 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3130 /* Get the channel entry */
3133 /* Get channel ID */
3134 tmp = silc_channel_key_get_id(payload, &tmp_len);
3135 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3141 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3143 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3145 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3146 silc_id_render(id, SILC_ID_CHANNEL)));
3152 tmp = silc_channel_key_get_key(payload, &tmp_len);
3158 cipher = silc_channel_key_get_cipher(payload, NULL);
3164 /* Remove old key if exists */
3166 memset(channel->key, 0, channel->key_len / 8);
3167 silc_free(channel->key);
3168 silc_cipher_free(channel->channel_key);
3171 /* Create new cipher */
3172 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3173 channel->channel_key = NULL;
3178 if (channel->cipher)
3179 silc_free(channel->cipher);
3180 channel->cipher = strdup(cipher);
3183 channel->key_len = tmp_len * 8;
3184 channel->key = silc_memdup(tmp, tmp_len);
3185 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3187 /* Generate HMAC key from the channel key data and set it */
3189 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3190 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3191 silc_hmac_set_key(channel->hmac, hash,
3192 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3194 memset(hash, 0, sizeof(hash));
3195 memset(tmp, 0, tmp_len);
3197 if (server->server_type == SILC_ROUTER) {
3198 if (!channel->rekey)
3199 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3200 channel->rekey->context = (void *)server;
3201 channel->rekey->channel = channel;
3202 if (channel->rekey->task)
3203 silc_schedule_task_del(server->schedule, channel->rekey->task);
3205 channel->rekey->task =
3206 silc_schedule_task_add(server->schedule, 0,
3207 silc_server_channel_key_rekey,
3208 (void *)channel->rekey,
3209 server->config->channel_rekey_secs, 0,
3211 SILC_TASK_PRI_NORMAL);
3217 silc_channel_key_payload_free(payload);
3222 /* Heartbeat callback. This function is set as argument for the
3223 silc_socket_set_heartbeat function. The library will call this function
3224 at the set time interval. */
3226 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3229 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3231 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3233 /* Send the heartbeat */
3234 silc_server_send_heartbeat(hb->server, sock);
3237 /* Returns assembled of all servers in the given ID list. The packet's
3238 form is dictated by the New ID payload. */
3240 static void silc_server_announce_get_servers(SilcServer server,
3241 SilcServerEntry remote,
3243 SilcBuffer *servers,
3244 unsigned long creation_time)
3246 SilcIDCacheList list;
3247 SilcIDCacheEntry id_cache;
3248 SilcServerEntry entry;
3251 /* Go through all clients in the list */
3252 if (silc_idcache_get_all(id_list->servers, &list)) {
3253 if (silc_idcache_list_first(list, &id_cache)) {
3255 entry = (SilcServerEntry)id_cache->context;
3257 /* Do not announce the one we've sending our announcements and
3258 do not announce ourself. Also check the creation time if it's
3260 if ((entry == remote) || (entry == server->id_entry) ||
3261 (creation_time && entry->data.created < creation_time)) {
3262 if (!silc_idcache_list_next(list, &id_cache))
3267 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3269 *servers = silc_buffer_realloc(*servers,
3271 (*servers)->truelen + idp->len :
3273 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3274 silc_buffer_put(*servers, idp->data, idp->len);
3275 silc_buffer_pull(*servers, idp->len);
3276 silc_buffer_free(idp);
3278 if (!silc_idcache_list_next(list, &id_cache))
3283 silc_idcache_list_free(list);
3288 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3294 p = silc_notify_payload_encode(notify, argc, ap);
3300 /* This function is used by router to announce existing servers to our
3301 primary router when we've connected to it. If `creation_time' is non-zero
3302 then only the servers that has been created after the `creation_time'
3303 will be announced. */
3305 void silc_server_announce_servers(SilcServer server, bool global,
3306 unsigned long creation_time,
3307 SilcSocketConnection remote)
3309 SilcBuffer servers = NULL;
3311 SILC_LOG_DEBUG(("Announcing servers"));
3313 /* Get servers in local list */
3314 silc_server_announce_get_servers(server, remote->user_data,
3315 server->local_list, &servers,
3319 /* Get servers in global list */
3320 silc_server_announce_get_servers(server, remote->user_data,
3321 server->global_list, &servers,
3325 silc_buffer_push(servers, servers->data - servers->head);
3326 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3328 /* Send the packet */
3329 silc_server_packet_send(server, remote,
3330 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3331 servers->data, servers->len, TRUE);
3333 silc_buffer_free(servers);
3337 /* Returns assembled packet of all clients in the given ID list. The
3338 packet's form is dictated by the New ID Payload. */
3340 static void silc_server_announce_get_clients(SilcServer server,
3342 SilcBuffer *clients,
3344 unsigned long creation_time)
3346 SilcIDCacheList list;
3347 SilcIDCacheEntry id_cache;
3348 SilcClientEntry client;
3351 unsigned char mode[4];
3353 /* Go through all clients in the list */
3354 if (silc_idcache_get_all(id_list->clients, &list)) {
3355 if (silc_idcache_list_first(list, &id_cache)) {
3357 client = (SilcClientEntry)id_cache->context;
3359 if (creation_time && client->data.created < creation_time) {
3360 if (!silc_idcache_list_next(list, &id_cache))
3365 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3367 *clients = silc_buffer_realloc(*clients,
3369 (*clients)->truelen + idp->len :
3371 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3372 silc_buffer_put(*clients, idp->data, idp->len);
3373 silc_buffer_pull(*clients, idp->len);
3375 SILC_PUT32_MSB(client->mode, mode);
3376 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3377 2, idp->data, idp->len,
3379 *umodes = silc_buffer_realloc(*umodes,
3381 (*umodes)->truelen + tmp->len :
3383 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3384 silc_buffer_put(*umodes, tmp->data, tmp->len);
3385 silc_buffer_pull(*umodes, tmp->len);
3386 silc_buffer_free(tmp);
3388 silc_buffer_free(idp);
3390 if (!silc_idcache_list_next(list, &id_cache))
3395 silc_idcache_list_free(list);
3399 /* This function is used to announce our existing clients to our router
3400 when we've connected to it. If `creation_time' is non-zero then only
3401 the clients that has been created after the `creation_time' will be
3404 void silc_server_announce_clients(SilcServer server,
3405 unsigned long creation_time,
3406 SilcSocketConnection remote)
3408 SilcBuffer clients = NULL;
3409 SilcBuffer umodes = NULL;
3411 SILC_LOG_DEBUG(("Announcing clients"));
3413 /* Get clients in local list */
3414 silc_server_announce_get_clients(server, server->local_list,
3415 &clients, &umodes, creation_time);
3417 /* As router we announce our global list as well */
3418 if (server->server_type == SILC_ROUTER)
3419 silc_server_announce_get_clients(server, server->global_list,
3420 &clients, &umodes, creation_time);
3423 silc_buffer_push(clients, clients->data - clients->head);
3424 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3426 /* Send the packet */
3427 silc_server_packet_send(server, remote,
3428 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3429 clients->data, clients->len, TRUE);
3431 silc_buffer_free(clients);
3435 silc_buffer_push(umodes, umodes->data - umodes->head);
3436 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3438 /* Send the packet */
3439 silc_server_packet_send(server, remote,
3440 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3441 umodes->data, umodes->len, TRUE);
3443 silc_buffer_free(umodes);
3447 /* Returns channel's topic for announcing it */
3449 void silc_server_announce_get_channel_topic(SilcServer server,
3450 SilcChannelEntry channel,
3455 if (channel->topic) {
3456 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3457 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3458 chidp->data, chidp->len,
3460 strlen(channel->topic));
3461 silc_buffer_free(chidp);
3465 /* Returns assembled packets for channel users of the `channel'. */
3467 void silc_server_announce_get_channel_users(SilcServer server,
3468 SilcChannelEntry channel,
3469 SilcBuffer *channel_users,
3470 SilcBuffer *channel_users_modes)
3472 SilcChannelClientEntry chl;
3473 SilcHashTableList htl;
3474 SilcBuffer chidp, clidp;
3477 unsigned char mode[4];
3479 SILC_LOG_DEBUG(("Start"));
3481 /* Now find all users on the channel */
3482 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3483 silc_hash_table_list(channel->user_list, &htl);
3484 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3485 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3488 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3489 clidp->data, clidp->len,
3490 chidp->data, chidp->len);
3493 silc_buffer_realloc(*channel_users,
3495 (*channel_users)->truelen + len : len));
3496 silc_buffer_pull_tail(*channel_users,
3497 ((*channel_users)->end -
3498 (*channel_users)->data));
3500 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3501 silc_buffer_pull(*channel_users, len);
3502 silc_buffer_free(tmp);
3504 /* CUMODE notify for mode change on the channel */
3505 SILC_PUT32_MSB(chl->mode, mode);
3506 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3507 3, clidp->data, clidp->len,
3509 clidp->data, clidp->len);
3511 *channel_users_modes =
3512 silc_buffer_realloc(*channel_users_modes,
3513 (*channel_users_modes ?
3514 (*channel_users_modes)->truelen + len : len));
3515 silc_buffer_pull_tail(*channel_users_modes,
3516 ((*channel_users_modes)->end -
3517 (*channel_users_modes)->data));
3519 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3520 silc_buffer_pull(*channel_users_modes, len);
3521 silc_buffer_free(tmp);
3523 silc_buffer_free(clidp);
3525 silc_hash_table_list_reset(&htl);
3526 silc_buffer_free(chidp);
3529 /* Returns assembled packets for all channels and users on those channels
3530 from the given ID List. The packets are in the form dictated by the
3531 New Channel and New Channel User payloads. */
3533 void silc_server_announce_get_channels(SilcServer server,
3535 SilcBuffer *channels,
3536 SilcBuffer *channel_users,
3537 SilcBuffer **channel_users_modes,
3538 SilcUInt32 *channel_users_modes_c,
3539 SilcBuffer **channel_topics,
3540 SilcChannelID ***channel_ids,
3541 unsigned long creation_time)
3543 SilcIDCacheList list;
3544 SilcIDCacheEntry id_cache;
3545 SilcChannelEntry channel;
3548 SilcUInt16 name_len;
3550 int i = *channel_users_modes_c;
3553 SILC_LOG_DEBUG(("Start"));
3555 /* Go through all channels in the list */
3556 if (silc_idcache_get_all(id_list->channels, &list)) {
3557 if (silc_idcache_list_first(list, &id_cache)) {
3559 channel = (SilcChannelEntry)id_cache->context;
3561 if (creation_time && channel->created < creation_time)
3566 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3567 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3568 name_len = strlen(channel->channel_name);
3571 len = 4 + name_len + id_len + 4;
3573 silc_buffer_realloc(*channels,
3574 (*channels ? (*channels)->truelen +
3576 silc_buffer_pull_tail(*channels,
3577 ((*channels)->end - (*channels)->data));
3578 silc_buffer_format(*channels,
3579 SILC_STR_UI_SHORT(name_len),
3580 SILC_STR_UI_XNSTRING(channel->channel_name,
3582 SILC_STR_UI_SHORT(id_len),
3583 SILC_STR_UI_XNSTRING(cid, id_len),
3584 SILC_STR_UI_INT(channel->mode),
3586 silc_buffer_pull(*channels, len);
3589 /* Channel user modes */
3590 *channel_users_modes = silc_realloc(*channel_users_modes,
3591 sizeof(**channel_users_modes) *
3593 (*channel_users_modes)[i] = NULL;
3594 *channel_ids = silc_realloc(*channel_ids,
3595 sizeof(**channel_ids) * (i + 1));
3596 (*channel_ids)[i] = NULL;
3597 silc_server_announce_get_channel_users(server, channel,
3599 &(*channel_users_modes)[i]);
3600 (*channel_ids)[i] = channel->id;
3602 /* Channel's topic */
3603 *channel_topics = silc_realloc(*channel_topics,
3604 sizeof(**channel_topics) * (i + 1));
3605 (*channel_topics)[i] = NULL;
3606 silc_server_announce_get_channel_topic(server, channel,
3607 &(*channel_topics)[i]);
3610 if (!silc_idcache_list_next(list, &id_cache))
3614 *channel_users_modes_c += i;
3617 silc_idcache_list_free(list);
3621 /* This function is used to announce our existing channels to our router
3622 when we've connected to it. This also announces the users on the
3623 channels to the router. If the `creation_time' is non-zero only the
3624 channels that was created after the `creation_time' are announced.
3625 Note that the channel users are still announced even if the `creation_time'
3628 void silc_server_announce_channels(SilcServer server,
3629 unsigned long creation_time,
3630 SilcSocketConnection remote)
3632 SilcBuffer channels = NULL, channel_users = NULL;
3633 SilcBuffer *channel_users_modes = NULL;
3634 SilcBuffer *channel_topics = NULL;
3635 SilcUInt32 channel_users_modes_c = 0;
3636 SilcChannelID **channel_ids = NULL;
3638 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3640 /* Get channels and channel users in local list */
3641 silc_server_announce_get_channels(server, server->local_list,
3642 &channels, &channel_users,
3643 &channel_users_modes,
3644 &channel_users_modes_c,
3646 &channel_ids, creation_time);
3648 /* Get channels and channel users in global list */
3649 if (server->server_type != SILC_SERVER)
3650 silc_server_announce_get_channels(server, server->global_list,
3651 &channels, &channel_users,
3652 &channel_users_modes,
3653 &channel_users_modes_c,
3655 &channel_ids, creation_time);
3658 silc_buffer_push(channels, channels->data - channels->head);
3659 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3661 /* Send the packet */
3662 silc_server_packet_send(server, remote,
3663 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3664 channels->data, channels->len,
3667 silc_buffer_free(channels);
3670 if (channel_users) {
3671 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3672 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3673 channel_users->len);
3675 /* Send the packet */
3676 silc_server_packet_send(server, remote,
3677 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3678 channel_users->data, channel_users->len,
3681 silc_buffer_free(channel_users);
3684 if (channel_users_modes) {
3687 for (i = 0; i < channel_users_modes_c; i++) {
3688 if (!channel_users_modes[i])
3690 silc_buffer_push(channel_users_modes[i],
3691 channel_users_modes[i]->data -
3692 channel_users_modes[i]->head);
3693 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3694 channel_users_modes[i]->len);
3695 silc_server_packet_send_dest(server, remote,
3696 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3697 channel_ids[i], SILC_ID_CHANNEL,
3698 channel_users_modes[i]->data,
3699 channel_users_modes[i]->len,
3701 silc_buffer_free(channel_users_modes[i]);
3703 silc_free(channel_users_modes);
3706 if (channel_topics) {
3709 for (i = 0; i < channel_users_modes_c; i++) {
3710 if (!channel_topics[i])
3713 silc_buffer_push(channel_topics[i],
3714 channel_topics[i]->data -
3715 channel_topics[i]->head);
3716 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3717 channel_topics[i]->len);
3718 silc_server_packet_send_dest(server, remote,
3719 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3720 channel_ids[i], SILC_ID_CHANNEL,
3721 channel_topics[i]->data,
3722 channel_topics[i]->len,
3724 silc_buffer_free(channel_topics[i]);
3726 silc_free(channel_topics);
3729 silc_free(channel_ids);
3732 /* Failure timeout callback. If this is called then we will immediately
3733 process the received failure. We always process the failure with timeout
3734 since we do not want to blindly trust to received failure packets.
3735 This won't be called (the timeout is cancelled) if the failure was
3736 bogus (it is bogus if remote does not close the connection after sending
3739 SILC_TASK_CALLBACK(silc_server_failure_callback)
3741 SilcServerFailureContext f = (SilcServerFailureContext)context;
3743 if (f->sock->protocol) {
3744 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3745 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3751 /* Assembles user list and users mode list from the `channel'. */
3753 void silc_server_get_users_on_channel(SilcServer server,
3754 SilcChannelEntry channel,
3755 SilcBuffer *user_list,
3756 SilcBuffer *mode_list,
3757 SilcUInt32 *user_count)
3759 SilcChannelClientEntry chl;
3760 SilcHashTableList htl;
3761 SilcBuffer client_id_list;
3762 SilcBuffer client_mode_list;
3764 SilcUInt32 list_count = 0, len = 0;
3766 silc_hash_table_list(channel->user_list, &htl);
3767 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3768 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3769 silc_hash_table_list_reset(&htl);
3771 client_id_list = silc_buffer_alloc(len);
3773 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3774 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3775 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3777 silc_hash_table_list(channel->user_list, &htl);
3778 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3780 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3781 silc_buffer_put(client_id_list, idp->data, idp->len);
3782 silc_buffer_pull(client_id_list, idp->len);
3783 silc_buffer_free(idp);
3785 /* Client's mode on channel */
3786 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3787 silc_buffer_pull(client_mode_list, 4);
3791 silc_hash_table_list_reset(&htl);
3792 silc_buffer_push(client_id_list,
3793 client_id_list->data - client_id_list->head);
3794 silc_buffer_push(client_mode_list,
3795 client_mode_list->data - client_mode_list->head);
3797 *user_list = client_id_list;
3798 *mode_list = client_mode_list;
3799 *user_count = list_count;
3802 /* Saves users and their modes to the `channel'. */
3804 void silc_server_save_users_on_channel(SilcServer server,
3805 SilcSocketConnection sock,
3806 SilcChannelEntry channel,
3807 SilcClientID *noadd,
3808 SilcBuffer user_list,
3809 SilcBuffer mode_list,
3810 SilcUInt32 user_count)
3815 SilcClientID *client_id;
3816 SilcClientEntry client;
3817 SilcIDCacheEntry cache;
3820 SILC_LOG_DEBUG(("Start"));
3822 for (i = 0; i < user_count; i++) {
3824 SILC_GET16_MSB(idp_len, user_list->data + 2);
3826 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3827 silc_buffer_pull(user_list, idp_len);
3832 SILC_GET32_MSB(mode, mode_list->data);
3833 silc_buffer_pull(mode_list, 4);
3835 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3836 silc_free(client_id);
3842 /* Check if we have this client cached already. */
3843 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3844 server->server_type, &cache);
3846 client = silc_idlist_find_client_by_id(server->global_list,
3847 client_id, server->server_type,
3852 /* If router did not find such Client ID in its lists then this must
3853 be bogus client or some router in the net is buggy. */
3854 if (server->server_type == SILC_ROUTER) {
3855 silc_free(client_id);
3859 /* We don't have that client anywhere, add it. The client is added
3860 to global list since server didn't have it in the lists so it must be
3862 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3863 silc_id_dup(client_id, SILC_ID_CLIENT),
3864 sock->user_data, NULL, 0);
3866 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3867 silc_free(client_id);
3871 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3873 /* Found, if it is from global list we'll assure that we won't
3874 expire it now that the entry is on channel. */
3879 silc_free(client_id);
3881 if (!silc_server_client_on_channel(client, channel, NULL)) {
3882 /* Client was not on the channel, add it. */
3883 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3884 chl->client = client;
3886 chl->channel = channel;
3887 silc_hash_table_add(channel->user_list, chl->client, chl);
3888 silc_hash_table_add(client->channels, chl->channel, chl);
3889 channel->user_count++;
3894 /* Lookups route to the client indicated by the `id_data'. The connection
3895 object and internal data object is returned. Returns NULL if route
3896 could not be found to the client. If the `client_id' is specified then
3897 it is used and the `id_data' is ignored. */
3899 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3900 unsigned char *id_data,
3902 SilcClientID *client_id,
3903 SilcIDListData *idata)
3906 SilcClientEntry client;
3908 SILC_LOG_DEBUG(("Start"));
3910 /* Decode destination Client ID */
3912 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3914 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3918 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3921 /* If the destination belongs to our server we don't have to route
3922 the packet anywhere but to send it to the local destination. */
3923 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3927 /* If we are router and the client has router then the client is in
3928 our cell but not directly connected to us. */
3929 if (server->server_type == SILC_ROUTER && client->router) {
3930 /* We are of course in this case the client's router thus the route
3931 to the client is the server who owns the client. So, we will send
3932 the packet to that server. */
3934 *idata = (SilcIDListData)client->router;
3935 return client->router->connection;
3938 /* Seems that client really is directly connected to us */
3940 *idata = (SilcIDListData)client;
3941 return client->connection;
3944 /* Destination belongs to someone not in this server. If we are normal
3945 server our action is to send the packet to our router. */
3946 if (server->server_type != SILC_ROUTER && !server->standalone) {
3949 *idata = (SilcIDListData)server->router;
3950 return server->router->connection;
3953 /* We are router and we will perform route lookup for the destination
3954 and send the packet to fastest route. */
3955 if (server->server_type == SILC_ROUTER && !server->standalone) {
3956 /* Check first that the ID is valid */
3957 client = silc_idlist_find_client_by_id(server->global_list, id,
3960 SilcSocketConnection dst_sock;
3962 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3966 *idata = (SilcIDListData)dst_sock->user_data;
3975 /* Encodes and returns channel list of channels the `client' has joined.
3976 Secret channels are not put to the list. */
3978 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3979 SilcClientEntry client)
3981 SilcBuffer buffer = NULL;
3982 SilcChannelEntry channel;
3983 SilcChannelClientEntry chl;
3984 SilcHashTableList htl;
3987 SilcUInt16 name_len;
3990 silc_hash_table_list(client->channels, &htl);
3991 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3992 channel = chl->channel;
3994 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3995 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
3998 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3999 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4000 name_len = strlen(channel->channel_name);
4002 len = 4 + name_len + id_len + 4;
4003 buffer = silc_buffer_realloc(buffer,
4004 (buffer ? (buffer)->truelen + len : len));
4005 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4006 silc_buffer_format(buffer,
4007 SILC_STR_UI_SHORT(name_len),
4008 SILC_STR_UI_XNSTRING(channel->channel_name,
4010 SILC_STR_UI_SHORT(id_len),
4011 SILC_STR_UI_XNSTRING(cid, id_len),
4012 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4014 silc_buffer_pull(buffer, len);
4017 silc_hash_table_list_reset(&htl);
4020 silc_buffer_push(buffer, buffer->data - buffer->head);
4025 /* Finds client entry by Client ID and if it is not found then resolves
4026 it using WHOIS command. */
4028 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4029 SilcClientID *client_id,
4032 SilcClientEntry client;
4037 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4040 client = silc_idlist_find_client_by_id(server->global_list,
4041 client_id, TRUE, NULL);
4042 if (!client && server->server_type == SILC_ROUTER)
4046 if (!client && server->standalone)
4049 if (!client || !client->nickname || !client->username) {
4050 SilcBuffer buffer, idp;
4052 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4053 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4054 client->resolve_cmd_ident = ++server->cmd_ident;
4056 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4057 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4058 server->cmd_ident, 1,
4059 3, idp->data, idp->len);
4060 silc_server_packet_send(server, client ? client->router->connection :
4061 server->router->connection,
4062 SILC_PACKET_COMMAND, 0,
4063 buffer->data, buffer->len, FALSE);
4064 silc_buffer_free(idp);
4065 silc_buffer_free(buffer);
4076 /* A timeout callback for the re-key. We will be the initiator of the
4079 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4081 SilcSocketConnection sock = (SilcSocketConnection)context;
4082 SilcIDListData idata = (SilcIDListData)sock->user_data;
4083 SilcServer server = (SilcServer)idata->rekey->context;
4084 SilcProtocol protocol;
4085 SilcServerRekeyInternalContext *proto_ctx;
4087 SILC_LOG_DEBUG(("Start"));
4089 /* Allocate internal protocol context. This is sent as context
4091 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4092 proto_ctx->server = (void *)server;
4093 proto_ctx->sock = sock;
4094 proto_ctx->responder = FALSE;
4095 proto_ctx->pfs = idata->rekey->pfs;
4097 /* Perform rekey protocol. Will call the final callback after the
4098 protocol is over. */
4099 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4100 &protocol, proto_ctx, silc_server_rekey_final);
4101 sock->protocol = protocol;
4103 /* Run the protocol */
4104 silc_protocol_execute(protocol, server->schedule, 0, 0);
4106 /* Re-register re-key timeout */
4107 silc_schedule_task_add(server->schedule, sock->sock,
4108 silc_server_rekey_callback,
4109 context, idata->rekey->timeout, 0,
4110 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4113 /* The final callback for the REKEY protocol. This will actually take the
4114 new key material into use. */
4116 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4118 SilcProtocol protocol = (SilcProtocol)context;
4119 SilcServerRekeyInternalContext *ctx =
4120 (SilcServerRekeyInternalContext *)protocol->context;
4121 SilcServer server = (SilcServer)ctx->server;
4122 SilcSocketConnection sock = ctx->sock;
4124 SILC_LOG_DEBUG(("Start"));
4126 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4127 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4128 /* Error occured during protocol */
4129 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4130 silc_protocol_cancel(protocol, server->schedule);
4131 silc_protocol_free(protocol);
4132 sock->protocol = NULL;
4134 silc_packet_context_free(ctx->packet);
4136 silc_ske_free(ctx->ske);
4141 /* Purge the outgoing data queue to assure that all rekey packets really
4142 go to the network before we quit the protocol. */
4143 silc_server_packet_queue_purge(server, sock);
4146 silc_protocol_free(protocol);
4147 sock->protocol = NULL;
4149 silc_packet_context_free(ctx->packet);
4151 silc_ske_free(ctx->ske);