5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
32 SILC_TASK_CALLBACK(silc_server_connect_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
39 SILC_TASK_CALLBACK(silc_server_packet_process);
40 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
41 SILC_TASK_CALLBACK(silc_server_close_connection_final);
42 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
43 SILC_TASK_CALLBACK(silc_server_timeout_remote);
44 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
45 SILC_TASK_CALLBACK(silc_server_failure_callback);
46 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 /* Allocates a new SILC server object. This has to be done before the server
49 can be used. After allocation one must call silc_server_init to initialize
50 the server. The new allocated server object is returned to the new_server
53 int silc_server_alloc(SilcServer *new_server)
57 SILC_LOG_DEBUG(("Allocating new server object"));
59 server = silc_calloc(1, sizeof(*server));
60 server->server_type = SILC_SERVER;
61 server->standalone = TRUE;
62 server->local_list = silc_calloc(1, sizeof(*server->local_list));
63 server->global_list = silc_calloc(1, sizeof(*server->global_list));
64 server->pending_commands = silc_dlist_init();
66 server->sim = silc_dlist_init();
74 /* Free's the SILC server object. This is called at the very end before
77 void silc_server_free(SilcServer server)
83 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
84 silc_dlist_del(server->sim, sim);
87 silc_dlist_uninit(server->sim);
90 silc_server_config_unref(&server->config_ref);
92 silc_rng_free(server->rng);
94 silc_pkcs_free(server->pkcs);
95 if (server->public_key)
96 silc_pkcs_public_key_free(server->public_key);
97 if (server->private_key)
98 silc_pkcs_private_key_free(server->private_key);
99 if (server->pending_commands)
100 silc_dlist_uninit(server->pending_commands);
101 if (server->id_entry)
102 silc_idlist_del_server(server->local_list, server->id_entry);
104 silc_idcache_free(server->local_list->clients);
105 silc_idcache_free(server->local_list->servers);
106 silc_idcache_free(server->local_list->channels);
107 silc_idcache_free(server->global_list->clients);
108 silc_idcache_free(server->global_list->servers);
109 silc_idcache_free(server->global_list->channels);
111 silc_free(server->sockets);
116 /* Opens a listening port.
117 XXX This function will become more general and will support multiple
120 static bool silc_server_listen(SilcServer server, int *sock)
123 *sock = silc_net_create_server(server->config->server_info->port,
124 server->config->server_info->server_ip);
126 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
127 server->config->server_info->server_ip,
128 server->config->server_info->port));
134 /* Initializes the entire SILC server. This is called always before running
135 the server. This is called only once at the initialization of the program.
136 This binds the server to its listenning port. After this function returns
137 one should call silc_server_run to start the server. This returns TRUE
138 when everything is ok to run the server. Configuration file must be
139 read and parsed before calling this. */
141 bool silc_server_init(SilcServer server)
145 SilcServerEntry id_entry;
146 SilcIDListPurge purge;
147 SilcSocketConnection newsocket = NULL;
149 SILC_LOG_DEBUG(("Initializing server"));
151 /* Take config object for us */
152 silc_server_config_ref(&server->config_ref, server->config,
155 /* Steal public and private key from the config object */
156 server->public_key = server->config->server_info->public_key;
157 server->private_key = server->config->server_info->private_key;
158 server->config->server_info->public_key = NULL;
159 server->config->server_info->private_key = NULL;
161 /* Register all configured ciphers, PKCS and hash functions. */
162 if (!silc_server_config_register_ciphers(server))
163 silc_cipher_register_default();
164 if (!silc_server_config_register_pkcs(server))
165 silc_pkcs_register_default();
166 if (!silc_server_config_register_hashfuncs(server))
167 silc_hash_register_default();
168 if (!silc_server_config_register_hmacs(server))
169 silc_hmac_register_default();
171 /* Initialize random number generator for the server. */
172 server->rng = silc_rng_alloc();
173 silc_rng_init(server->rng);
174 silc_rng_global_init(server->rng);
176 /* Initialize hash functions for server to use */
177 silc_hash_alloc("md5", &server->md5hash);
178 silc_hash_alloc("sha1", &server->sha1hash);
180 /* Allocate PKCS context for local public and private keys */
181 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
183 silc_pkcs_public_key_set(server->pkcs, server->public_key);
184 silc_pkcs_private_key_set(server->pkcs, server->private_key);
186 /* Initialize the scheduler */
187 server->schedule = silc_schedule_init(server->config->param.connections_max);
188 if (!server->schedule)
191 /* First, register log files configuration for error output */
192 silc_server_config_setlogfiles(server);
194 /* Initialize ID caches */
195 server->local_list->clients =
196 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
197 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
198 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
200 /* These are allocated for normal server as well as these hold some
201 global information that the server has fetched from its router. For
202 router these are used as they are supposed to be used on router. */
203 server->global_list->clients =
204 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
205 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
206 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
208 /* Create a listening server */
209 if (!silc_server_listen(server, &sock))
212 /* Set socket to non-blocking mode */
213 silc_net_set_socket_nonblock(sock);
216 /* Allocate the entire socket list that is used in server. Eventually
217 all connections will have entry in this table (it is a table of
218 pointers to the actual object that is allocated individually
220 server->sockets = silc_calloc(server->config->param.connections_max,
221 sizeof(*server->sockets));
222 if (!server->sockets)
225 /* Add ourselves also to the socket table. The entry allocated above
226 is sent as argument for fast referencing in the future. */
227 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
228 server->sockets[sock] = newsocket;
230 /* Perform name and address lookups to resolve the listenning address
232 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
234 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
236 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
237 newsocket->hostname ? newsocket->hostname :
238 newsocket->ip ? newsocket->ip : ""));
239 server->stat.conn_failures++;
242 if (!newsocket->hostname)
243 newsocket->hostname = strdup(newsocket->ip);
245 newsocket->port = silc_net_get_local_port(sock);
247 /* Create a Server ID for the server. */
248 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
253 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
254 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
255 server->id_type = SILC_ID_SERVER;
256 server->server_name = server->config->server_info->server_name;
257 server->config->server_info->server_name = NULL;
259 /* Add ourselves to the server list. We don't have a router yet
260 beacuse we haven't established a route yet. It will be done later.
261 For now, NULL is sent as router. This allocates new entry to
264 silc_idlist_add_server(server->local_list, strdup(server->server_name),
265 server->server_type, server->id, NULL, NULL);
267 SILC_LOG_ERROR(("Could not add ourselves to cache"));
270 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
272 /* Put the allocated socket pointer also to the entry allocated above
273 for fast back-referencing to the socket list. */
274 newsocket->user_data = (void *)id_entry;
275 id_entry->connection = (void *)newsocket;
276 server->id_entry = id_entry;
278 /* Register protocols */
279 silc_server_protocols_register();
281 /* Add the first task to the scheduler. This is task that is executed by
282 timeout. It expires as soon as the caller calls silc_server_run. This
283 task performs authentication protocol and key exchange with our
285 silc_schedule_task_add(server->schedule, sock,
286 silc_server_connect_to_router,
287 (void *)server, 0, 1,
289 SILC_TASK_PRI_NORMAL);
291 /* Add listener task to the scheduler. This task receives new connections
292 to the server. This task remains on the queue until the end of the
294 silc_schedule_task_add(server->schedule, sock,
295 silc_server_accept_new_connection,
296 (void *)server, 0, 0,
298 SILC_TASK_PRI_NORMAL);
299 server->listenning = TRUE;
301 /* If server connections has been configured then we must be router as
302 normal server cannot have server connections, only router connections. */
303 if (server->config->servers) {
304 SilcServerConfigServer *ptr = server->config->servers;
306 server->server_type = SILC_ROUTER;
308 if (ptr->backup_router) {
309 server->server_type = SILC_BACKUP_ROUTER;
310 server->backup_router = TRUE;
311 server->id_entry->server_type = SILC_BACKUP_ROUTER;
318 /* Register the ID Cache purge task. This periodically purges the ID cache
319 and removes the expired cache entries. */
321 /* Clients local list */
322 purge = silc_calloc(1, sizeof(*purge));
323 purge->cache = server->local_list->clients;
324 purge->schedule = server->schedule;
325 purge->timeout = 600;
326 silc_schedule_task_add(purge->schedule, 0,
328 (void *)purge, purge->timeout, 0,
329 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
331 /* Clients global list */
332 purge = silc_calloc(1, sizeof(*purge));
333 purge->cache = server->global_list->clients;
334 purge->schedule = server->schedule;
335 purge->timeout = 300;
336 silc_schedule_task_add(purge->schedule, 0,
338 (void *)purge, purge->timeout, 0,
339 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
341 SILC_LOG_DEBUG(("Server initialized"));
343 /* We are done here, return succesfully */
347 silc_net_close_server(sock);
351 /* This function basically reads the config file again and switches the config
352 object pointed by the server object. After that, we have to fix various
353 things such as the server_name and the listening ports.
354 Keep in mind that we no longer have the root privileges at this point. */
356 bool silc_server_rehash(SilcServer server)
358 SilcServerConfig newconfig;
360 SILC_LOG_INFO(("Rehashing server"));
362 /* Our old config is gone now. We'll unreference our reference made in
363 silc_server_init and then destroy it since we are destroying it
364 underneath the application (layer which called silc_server_init). */
365 silc_server_config_unref(&server->config_ref);
366 silc_server_config_destroy(server->config);
368 /* Reset the logging system */
369 silc_log_quick = TRUE;
370 silc_log_flush_all();
372 /* Start the main rehash phase (read again the config file) */
373 newconfig = silc_server_config_alloc(server->config_file);
375 SILC_LOG_ERROR(("Rehash FAILED."));
379 /* Take new config context */
380 server->config = newconfig;
381 silc_server_config_ref(&server->config_ref, server->config, server->config);
383 /* Fix the server_name field */
384 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
385 silc_free(server->server_name);
386 server->server_name = newconfig->server_info->server_name;
387 newconfig->server_info->server_name = NULL;
389 /* Update the idcache list with a fresh pointer */
390 silc_free(server->id_entry->server_name);
391 server->id_entry->server_name = strdup(server->server_name);
392 silc_idcache_del_by_context(server->local_list->servers, server->id_entry);
393 silc_idcache_add(server->local_list->servers,
394 server->id_entry->server_name,
395 server->id_entry->id, server->id_entry, 0, NULL);
398 silc_server_config_setlogfiles(server);
400 /* Change new key pair if necessary */
401 if (newconfig->server_info->public_key &&
402 !silc_pkcs_public_key_compare(server->public_key,
403 newconfig->server_info->public_key)) {
404 silc_pkcs_public_key_free(server->public_key);
405 silc_pkcs_private_key_free(server->private_key);
406 server->public_key = server->config->server_info->public_key;
407 server->private_key = server->config->server_info->private_key;
408 server->config->server_info->public_key = NULL;
409 server->config->server_info->private_key = NULL;
411 /* Allocate PKCS context for local public and private keys */
412 silc_pkcs_free(server->pkcs);
413 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
415 silc_pkcs_public_key_set(server->pkcs, server->public_key);
416 silc_pkcs_private_key_set(server->pkcs, server->private_key);
422 /* The heart of the server. This runs the scheduler thus runs the server.
423 When this returns the server has been stopped and the program will
426 void silc_server_run(SilcServer server)
428 SILC_LOG_INFO(("SILC Server started"));
430 /* Start the scheduler, the heart of the SILC server. When this returns
431 the program will be terminated. */
432 silc_schedule(server->schedule);
435 /* Stops the SILC server. This function is used to shutdown the server.
436 This is usually called after the scheduler has returned. After stopping
437 the server one should call silc_server_free. */
439 void silc_server_stop(SilcServer server)
441 SILC_LOG_DEBUG(("Stopping server"));
443 if (server->schedule) {
444 silc_schedule_stop(server->schedule);
445 silc_schedule_uninit(server->schedule);
446 server->schedule = NULL;
449 silc_server_protocols_unregister();
451 SILC_LOG_DEBUG(("Server stopped"));
454 /* Function that is called when the network connection to a router has
455 been established. This will continue with the key exchange protocol
456 with the remote router. */
458 void silc_server_start_key_exchange(SilcServer server,
459 SilcServerConnection sconn,
462 SilcSocketConnection newsocket;
463 SilcProtocol protocol;
464 SilcServerKEInternalContext *proto_ctx;
465 SilcServerConfigRouter *conn =
466 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
469 /* Cancel any possible retry timeouts */
470 silc_schedule_task_del_by_callback(server->schedule,
471 silc_server_connect_router);
473 /* Set socket options */
474 silc_net_set_socket_nonblock(sock);
475 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
477 /* Create socket connection for the connection. Even though we
478 know that we are connecting to a router we will mark the socket
479 to be unknown connection until we have executed authentication
481 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
482 server->sockets[sock] = newsocket;
483 newsocket->hostname = strdup(sconn->remote_host);
484 newsocket->ip = strdup(sconn->remote_host);
485 newsocket->port = sconn->remote_port;
486 sconn->sock = newsocket;
488 /* Allocate internal protocol context. This is sent as context
490 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
491 proto_ctx->server = (void *)server;
492 proto_ctx->context = (void *)sconn;
493 proto_ctx->sock = newsocket;
494 proto_ctx->rng = server->rng;
495 proto_ctx->responder = FALSE;
497 /* Set Key Exchange flags from configuration, but fall back to global
499 SILC_GET_SKE_FLAGS(conn, proto_ctx);
500 if (server->config->param.key_exchange_pfs)
501 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
503 /* Perform key exchange protocol. silc_server_connect_to_router_second
504 will be called after the protocol is finished. */
505 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
506 &protocol, proto_ctx,
507 silc_server_connect_to_router_second);
508 newsocket->protocol = protocol;
510 /* Register a timeout task that will be executed if the protocol
511 is not executed within set limit. */
512 proto_ctx->timeout_task =
513 silc_schedule_task_add(server->schedule, sock,
514 silc_server_timeout_remote,
515 server, server->config->key_exchange_timeout, 0,
519 /* Register the connection for network input and output. This sets
520 that scheduler will listen for incoming packets for this connection
521 and sets that outgoing packets may be sent to this connection as
522 well. However, this doesn't set the scheduler for outgoing traffic,
523 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
524 later when outgoing data is available. */
525 context = (void *)server;
526 SILC_REGISTER_CONNECTION_FOR_IO(sock);
528 /* Run the protocol */
529 silc_protocol_execute(protocol, server->schedule, 0, 0);
532 /* Timeout callback that will be called to retry connecting to remote
533 router. This is used by both normal and router server. This will wait
534 before retrying the connecting. The timeout is generated by exponential
535 backoff algorithm. */
537 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
539 SilcServerConnection sconn = (SilcServerConnection)context;
540 SilcServer server = sconn->server;
541 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
542 SilcServerConfigConnParams *param =
543 (conn->param ? conn->param : &server->config->param);
545 SILC_LOG_INFO(("Retrying connecting to a router"));
547 /* Calculate next timeout */
548 if (sconn->retry_count >= 1) {
549 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
550 if (sconn->retry_timeout > param->reconnect_interval_max)
551 sconn->retry_timeout = param->reconnect_interval_max;
553 sconn->retry_timeout = param->reconnect_interval;
555 sconn->retry_count++;
556 sconn->retry_timeout = sconn->retry_timeout +
557 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
559 /* If we've reached max retry count, give up. */
560 if ((sconn->retry_count > param->reconnect_count) &&
561 !param->reconnect_keep_trying) {
562 SILC_LOG_ERROR(("Could not connect to router, giving up"));
563 silc_server_config_unref(&sconn->conn);
564 silc_free(sconn->remote_host);
565 silc_free(sconn->backup_replace_ip);
570 /* We will lookup a fresh pointer later */
571 silc_server_config_unref(&sconn->conn);
573 /* Wait one before retrying */
574 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
575 context, sconn->retry_timeout, 0,
576 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
579 /* Generic routine to use connect to a router. */
581 SILC_TASK_CALLBACK(silc_server_connect_router)
583 SilcServerConnection sconn = (SilcServerConnection)context;
584 SilcServer server = sconn->server;
585 SilcServerConfigRouter *rconn;
588 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
589 (sconn->backup ? "backup router" : "router"),
590 sconn->remote_host, sconn->remote_port));
592 server->router_connect = time(NULL);
593 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
596 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
597 (sconn->backup ? "backup router" : "router"),
598 sconn->remote_host, sconn->remote_port));
599 silc_free(sconn->remote_host);
600 silc_free(sconn->backup_replace_ip);
604 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
606 /* Connect to remote host */
607 sock = silc_net_create_connection(server->config->server_info->server_ip,
611 SILC_LOG_ERROR(("Could not connect to router %s:%d",
612 sconn->remote_host, sconn->remote_port));
613 if (!sconn->no_reconnect)
614 silc_schedule_task_add(server->schedule, 0,
615 silc_server_connect_to_router_retry,
616 context, 0, 1, SILC_TASK_TIMEOUT,
617 SILC_TASK_PRI_NORMAL);
619 silc_server_config_unref(&sconn->conn);
623 /* Continue with key exchange protocol */
624 silc_server_start_key_exchange(server, sconn, sock);
627 /* This function connects to our primary router or if we are a router this
628 establishes all our primary routes. This is called at the start of the
629 server to do authentication and key exchange with our router - called
632 SILC_TASK_CALLBACK(silc_server_connect_to_router)
634 SilcServer server = (SilcServer)context;
635 SilcServerConnection sconn;
636 SilcServerConfigRouter *ptr;
638 SILC_LOG_DEBUG(("Connecting to router(s)"));
640 if (server->server_type == SILC_SERVER) {
641 SILC_LOG_DEBUG(("We are normal server"));
642 } else if (server->server_type == SILC_ROUTER) {
643 SILC_LOG_DEBUG(("We are router"));
645 SILC_LOG_DEBUG(("We are backup router/normal server"));
648 if (!server->config->routers) {
649 /* There wasn't a configured router, we will continue but we don't
650 have a connection to outside world. We will be standalone server. */
651 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
652 server->standalone = TRUE;
656 /* Create the connections to all our routes */
657 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
659 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
660 ptr->backup_router ? "Backup router" : "Router",
661 ptr->initiator ? "Initiator" : "Responder",
662 ptr->host, ptr->port));
664 if (ptr->initiator) {
665 /* Allocate connection object for hold connection specific stuff. */
666 sconn = silc_calloc(1, sizeof(*sconn));
667 sconn->server = server;
668 sconn->remote_host = strdup(ptr->host);
669 sconn->remote_port = ptr->port;
670 sconn->backup = ptr->backup_router;
672 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
673 sconn->backup_replace_port = ptr->backup_replace_port;
676 if (!server->router_conn && !sconn->backup)
677 server->router_conn = sconn;
679 silc_schedule_task_add(server->schedule, fd,
680 silc_server_connect_router,
681 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
682 SILC_TASK_PRI_NORMAL);
687 /* Second part of connecting to router(s). Key exchange protocol has been
688 executed and now we will execute authentication protocol. */
690 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
692 SilcProtocol protocol = (SilcProtocol)context;
693 SilcServerKEInternalContext *ctx =
694 (SilcServerKEInternalContext *)protocol->context;
695 SilcServer server = (SilcServer)ctx->server;
696 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
697 SilcSocketConnection sock = ctx->sock;
698 SilcServerConnAuthInternalContext *proto_ctx;
699 SilcServerConfigRouter *conn = NULL;
701 SILC_LOG_DEBUG(("Start"));
703 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
704 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
705 /* Error occured during protocol */
706 silc_protocol_free(protocol);
707 sock->protocol = NULL;
708 silc_ske_free_key_material(ctx->keymat);
710 silc_packet_context_free(ctx->packet);
712 silc_ske_free(ctx->ske);
713 silc_free(ctx->dest_id);
715 silc_server_config_unref(&sconn->conn);
716 silc_free(sconn->remote_host);
717 silc_free(sconn->backup_replace_ip);
719 silc_schedule_task_del_by_callback(server->schedule,
720 silc_server_failure_callback);
721 silc_server_disconnect_remote(server, sock, "Server closed connection: "
722 "Key exchange failed");
726 /* We now have the key material as the result of the key exchange
727 protocol. Take the key material into use. Free the raw key material
728 as soon as we've set them into use. */
729 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
730 ctx->sock, ctx->keymat,
731 ctx->ske->prop->cipher,
732 ctx->ske->prop->pkcs,
733 ctx->ske->prop->hash,
734 ctx->ske->prop->hmac,
735 ctx->ske->prop->group,
737 silc_protocol_free(protocol);
738 sock->protocol = NULL;
739 silc_ske_free_key_material(ctx->keymat);
741 silc_packet_context_free(ctx->packet);
743 silc_ske_free(ctx->ske);
744 silc_free(ctx->dest_id);
746 silc_server_config_unref(&sconn->conn);
747 silc_free(sconn->remote_host);
748 silc_free(sconn->backup_replace_ip);
750 silc_schedule_task_del_by_callback(server->schedule,
751 silc_server_failure_callback);
752 silc_server_disconnect_remote(server, sock, "Server closed connection: "
753 "Key exchange failed");
756 silc_ske_free_key_material(ctx->keymat);
758 /* Allocate internal context for the authentication protocol. This
759 is sent as context for the protocol. */
760 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
761 proto_ctx->server = (void *)server;
762 proto_ctx->context = (void *)sconn;
763 proto_ctx->sock = sock;
764 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
765 proto_ctx->dest_id_type = ctx->dest_id_type;
766 proto_ctx->dest_id = ctx->dest_id;
768 /* Resolve the authentication method used in this connection. Check if
769 we find a match from user configured connections */
770 if (!sconn->conn.ref_ptr)
771 conn = silc_server_config_find_router_conn(server, sock->hostname,
774 conn = sconn->conn.ref_ptr;
777 /* Match found. Use the configured authentication method. Take only
778 the passphrase, since for public key auth we automatically use
779 our local key pair. */
780 if (conn->passphrase) {
781 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
782 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
784 proto_ctx->auth_data = strdup(conn->passphrase);
785 proto_ctx->auth_data_len = strlen(conn->passphrase);
786 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
788 } else if (conn->publickeys) {
789 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
791 proto_ctx->auth_meth = SILC_AUTH_NONE;
794 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
795 sock->hostname, sock->ip, sock->port));
796 silc_protocol_free(protocol);
797 sock->protocol = NULL;
799 silc_packet_context_free(ctx->packet);
801 silc_ske_free(ctx->ske);
802 silc_free(ctx->dest_id);
804 silc_server_config_unref(&sconn->conn);
805 silc_free(sconn->remote_host);
806 silc_free(sconn->backup_replace_ip);
808 silc_schedule_task_del_by_callback(server->schedule,
809 silc_server_failure_callback);
810 silc_server_disconnect_remote(server, sock, "Server closed connection: "
811 "Key exchange failed");
815 /* Free old protocol as it is finished now */
816 silc_protocol_free(protocol);
818 silc_packet_context_free(ctx->packet);
820 sock->protocol = NULL;
822 /* Allocate the authentication protocol. This is allocated here
823 but we won't start it yet. We will be receiving party of this
824 protocol thus we will wait that connecting party will make
826 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
827 &sock->protocol, proto_ctx,
828 silc_server_connect_to_router_final);
830 /* Register timeout task. If the protocol is not executed inside
831 this timelimit the connection will be terminated. */
832 proto_ctx->timeout_task =
833 silc_schedule_task_add(server->schedule, sock->sock,
834 silc_server_timeout_remote,
836 server->config->conn_auth_timeout, 0,
840 /* Run the protocol */
841 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
844 /* Finalizes the connection to router. Registers a server task to the
845 queue so that we can accept new connections. */
847 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
849 SilcProtocol protocol = (SilcProtocol)context;
850 SilcServerConnAuthInternalContext *ctx =
851 (SilcServerConnAuthInternalContext *)protocol->context;
852 SilcServer server = (SilcServer)ctx->server;
853 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
854 SilcSocketConnection sock = ctx->sock;
855 SilcServerEntry id_entry;
857 SilcServerHBContext hb_context;
858 unsigned char *id_string;
860 SilcIDListData idata;
861 SilcServerConfigRouter *conn = NULL;
862 SilcServerConfigConnParams *param = NULL;
864 SILC_LOG_DEBUG(("Start"));
866 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
867 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
868 /* Error occured during protocol */
869 silc_free(ctx->dest_id);
870 silc_server_disconnect_remote(server, sock, "Server closed connection: "
871 "Authentication failed");
875 /* Add a task to the queue. This task receives new connections to the
876 server. This task remains on the queue until the end of the program. */
877 if (!server->listenning && !sconn->backup) {
878 silc_schedule_task_add(server->schedule, server->sock,
879 silc_server_accept_new_connection,
880 (void *)server, 0, 0,
882 SILC_TASK_PRI_NORMAL);
883 server->listenning = TRUE;
886 /* Send NEW_SERVER packet to the router. We will become registered
887 to the SILC network after sending this packet. */
888 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
889 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
890 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
891 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
892 silc_buffer_format(packet,
893 SILC_STR_UI_SHORT(id_len),
894 SILC_STR_UI_XNSTRING(id_string, id_len),
895 SILC_STR_UI_SHORT(strlen(server->server_name)),
896 SILC_STR_UI_XNSTRING(server->server_name,
897 strlen(server->server_name)),
900 /* Send the packet */
901 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
902 packet->data, packet->len, TRUE);
903 silc_buffer_free(packet);
904 silc_free(id_string);
906 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
908 /* Check that we do not have this ID already */
909 id_entry = silc_idlist_find_server_by_id(server->local_list,
910 ctx->dest_id, TRUE, NULL);
912 silc_idcache_del_by_context(server->local_list->servers, id_entry);
914 id_entry = silc_idlist_find_server_by_id(server->global_list,
915 ctx->dest_id, TRUE, NULL);
917 silc_idcache_del_by_context(server->global_list->servers, id_entry);
920 SILC_LOG_DEBUG(("New server id(%s)",
921 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
923 /* Add the connected router to global server list */
924 id_entry = silc_idlist_add_server(server->global_list,
925 strdup(sock->hostname),
926 SILC_ROUTER, ctx->dest_id, NULL, sock);
928 silc_free(ctx->dest_id);
929 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
930 silc_server_disconnect_remote(server, sock, "Server closed connection: "
931 "Authentication failed");
935 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
936 silc_free(sock->user_data);
937 sock->user_data = (void *)id_entry;
938 sock->type = SILC_SOCKET_TYPE_ROUTER;
939 idata = (SilcIDListData)sock->user_data;
940 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
942 conn = sconn->conn.ref_ptr;
943 param = &server->config->param;
944 if (conn && conn->param)
947 /* Perform keepalive. The `hb_context' will be freed automatically
948 when finally calling the silc_socket_free function. */
949 hb_context = silc_calloc(1, sizeof(*hb_context));
950 hb_context->server = server;
951 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
952 silc_server_perform_heartbeat,
955 /* Register re-key timeout */
956 idata->rekey->timeout = param->key_exchange_rekey;
957 idata->rekey->context = (void *)server;
958 silc_schedule_task_add(server->schedule, sock->sock,
959 silc_server_rekey_callback,
960 (void *)sock, idata->rekey->timeout, 0,
961 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
963 if (!sconn->backup) {
964 /* Mark this router our primary router if we're still standalone */
965 if (server->standalone) {
966 server->id_entry->router = id_entry;
967 server->router = id_entry;
968 server->standalone = FALSE;
970 /* If we are router then announce our possible servers. */
971 if (server->server_type == SILC_ROUTER)
972 silc_server_announce_servers(server, FALSE, 0,
973 server->router->connection);
975 /* Announce our clients and channels to the router */
976 silc_server_announce_clients(server, 0, server->router->connection);
977 silc_server_announce_channels(server, 0, server->router->connection);
980 /* Add this server to be our backup router */
981 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
982 sconn->backup_replace_port, FALSE);
985 sock->protocol = NULL;
987 /* Call the completion callback to indicate that we've connected to
990 (*sconn->callback)(server, id_entry, sconn->callback_context);
993 /* Free the temporary connection data context */
995 silc_server_config_unref(&sconn->conn);
996 silc_free(sconn->remote_host);
997 silc_free(sconn->backup_replace_ip);
1000 if (sconn == server->router_conn)
1001 server->router_conn = NULL;
1003 /* Free the protocol object */
1004 if (sock->protocol == protocol)
1005 sock->protocol = NULL;
1006 silc_protocol_free(protocol);
1008 silc_packet_context_free(ctx->packet);
1010 silc_ske_free(ctx->ske);
1011 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1012 silc_free(ctx->auth_data);
1016 /* Host lookup callback that is called after the incoming connection's
1017 IP and FQDN lookup is performed. This will actually check the acceptance
1018 of the incoming connection and will register the key exchange protocol
1019 for this connection. */
1022 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1025 SilcServer server = (SilcServer)context;
1026 SilcServerKEInternalContext *proto_ctx;
1027 SilcServerConfigClient *cconfig = NULL;
1028 SilcServerConfigServer *sconfig = NULL;
1029 SilcServerConfigRouter *rconfig = NULL;
1030 SilcServerConfigDeny *deny;
1033 SILC_LOG_DEBUG(("Start"));
1035 /* Check whether we could resolve both IP and FQDN. */
1036 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1037 server->config->require_reverse_lookup)) {
1038 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1039 sock->hostname ? sock->hostname :
1040 sock->ip ? sock->ip : ""));
1041 server->stat.conn_failures++;
1042 silc_server_disconnect_remote(server, sock,
1043 "Server closed connection: Unknown host");
1047 /* Register the connection for network input and output. This sets
1048 that scheduler will listen for incoming packets for this connection
1049 and sets that outgoing packets may be sent to this connection as well.
1050 However, this doesn't set the scheduler for outgoing traffic, it
1051 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1052 later when outgoing data is available. */
1053 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1055 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1058 port = server->sockets[server->sock]->port; /* Listenning port */
1060 /* Check whether this connection is denied to connect to us. */
1061 deny = silc_server_config_find_denied(server, sock->ip);
1063 deny = silc_server_config_find_denied(server, sock->hostname);
1065 /* The connection is denied */
1066 SILC_LOG_INFO(("Connection %s (%s) is denied",
1067 sock->hostname, sock->ip));
1068 silc_server_disconnect_remote(server, sock, deny->reason ?
1070 "Server closed connection: "
1071 "Connection refused");
1072 server->stat.conn_failures++;
1076 /* Check whether we have configured this sort of connection at all. We
1077 have to check all configurations since we don't know what type of
1078 connection this is. */
1079 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1080 cconfig = silc_server_config_find_client(server, sock->hostname);
1081 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1082 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1083 if (server->server_type == SILC_ROUTER) {
1084 if (!(rconfig = silc_server_config_find_router_conn(server,
1086 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1089 if (!cconfig && !sconfig && !rconfig) {
1090 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1092 silc_server_disconnect_remote(server, sock,
1093 "Server closed connection: "
1094 "Connection refused");
1095 server->stat.conn_failures++;
1099 /* The connection is allowed */
1101 /* Allocate internal context for key exchange protocol. This is
1102 sent as context for the protocol. */
1103 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1104 proto_ctx->server = context;
1105 proto_ctx->sock = sock;
1106 proto_ctx->rng = server->rng;
1107 proto_ctx->responder = TRUE;
1108 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1109 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1110 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1112 /* Take flags for key exchange. Since we do not know what type of connection
1113 this is, we go through all found configurations and use the global ones
1114 as well. This will result always into strictest key exchange flags. */
1115 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1116 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1117 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1118 if (server->config->param.key_exchange_pfs)
1119 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1121 /* Prepare the connection for key exchange protocol. We allocate the
1122 protocol but will not start it yet. The connector will be the
1123 initiator of the protocol thus we will wait for initiation from
1124 there before we start the protocol. */
1125 server->stat.auth_attempts++;
1126 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1127 &sock->protocol, proto_ctx,
1128 silc_server_accept_new_connection_second);
1130 /* Register a timeout task that will be executed if the connector
1131 will not start the key exchange protocol within specified timeout
1132 and the connection will be closed. */
1133 proto_ctx->timeout_task =
1134 silc_schedule_task_add(server->schedule, sock->sock,
1135 silc_server_timeout_remote,
1136 context, server->config->key_exchange_timeout, 0,
1141 /* Accepts new connections to the server. Accepting new connections are
1142 done in three parts to make it async. */
1144 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1146 SilcServer server = (SilcServer)context;
1147 SilcSocketConnection newsocket;
1150 SILC_LOG_DEBUG(("Accepting new connection"));
1152 server->stat.conn_attempts++;
1154 sock = silc_net_accept_connection(server->sock);
1156 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1157 server->stat.conn_failures++;
1161 /* Check for maximum allowed connections */
1162 if (sock > server->config->param.connections_max) {
1163 SILC_LOG_ERROR(("Refusing connection, server is full"));
1164 server->stat.conn_failures++;
1165 silc_net_close_connection(sock);
1169 /* Set socket options */
1170 silc_net_set_socket_nonblock(sock);
1171 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1173 /* We don't create a ID yet, since we don't know what type of connection
1174 this is yet. But, we do add the connection to the socket table. */
1175 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1176 server->sockets[sock] = newsocket;
1178 /* Perform asynchronous host lookup. This will lookup the IP and the
1179 FQDN of the remote connection. After the lookup is done the connection
1180 is accepted further. */
1181 silc_socket_host_lookup(newsocket, TRUE,
1182 silc_server_accept_new_connection_lookup, context,
1186 /* Second part of accepting new connection. Key exchange protocol has been
1187 performed and now it is time to do little connection authentication
1188 protocol to figure out whether this connection is client or server
1189 and whether it has right to access this server (especially server
1190 connections needs to be authenticated). */
1192 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1194 SilcProtocol protocol = (SilcProtocol)context;
1195 SilcServerKEInternalContext *ctx =
1196 (SilcServerKEInternalContext *)protocol->context;
1197 SilcServer server = (SilcServer)ctx->server;
1198 SilcSocketConnection sock = ctx->sock;
1199 SilcServerConnAuthInternalContext *proto_ctx;
1201 SILC_LOG_DEBUG(("Start"));
1203 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1204 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1205 /* Error occured during protocol */
1206 silc_protocol_free(protocol);
1207 sock->protocol = NULL;
1208 silc_ske_free_key_material(ctx->keymat);
1210 silc_packet_context_free(ctx->packet);
1212 silc_ske_free(ctx->ske);
1213 silc_free(ctx->dest_id);
1214 silc_server_config_unref(&ctx->cconfig);
1215 silc_server_config_unref(&ctx->sconfig);
1216 silc_server_config_unref(&ctx->rconfig);
1218 silc_schedule_task_del_by_callback(server->schedule,
1219 silc_server_failure_callback);
1220 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1221 "Key exchange failed");
1222 server->stat.auth_failures++;
1226 /* We now have the key material as the result of the key exchange
1227 protocol. Take the key material into use. Free the raw key material
1228 as soon as we've set them into use. */
1229 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1230 ctx->sock, ctx->keymat,
1231 ctx->ske->prop->cipher,
1232 ctx->ske->prop->pkcs,
1233 ctx->ske->prop->hash,
1234 ctx->ske->prop->hmac,
1235 ctx->ske->prop->group,
1237 silc_protocol_free(protocol);
1238 sock->protocol = NULL;
1239 silc_ske_free_key_material(ctx->keymat);
1241 silc_packet_context_free(ctx->packet);
1243 silc_ske_free(ctx->ske);
1244 silc_free(ctx->dest_id);
1245 silc_server_config_unref(&ctx->cconfig);
1246 silc_server_config_unref(&ctx->sconfig);
1247 silc_server_config_unref(&ctx->rconfig);
1249 silc_schedule_task_del_by_callback(server->schedule,
1250 silc_server_failure_callback);
1251 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1252 "Key exchange failed");
1253 server->stat.auth_failures++;
1256 silc_ske_free_key_material(ctx->keymat);
1258 /* Allocate internal context for the authentication protocol. This
1259 is sent as context for the protocol. */
1260 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1261 proto_ctx->server = (void *)server;
1262 proto_ctx->sock = sock;
1263 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1264 proto_ctx->responder = TRUE;
1265 proto_ctx->dest_id_type = ctx->dest_id_type;
1266 proto_ctx->dest_id = ctx->dest_id;
1267 proto_ctx->cconfig = ctx->cconfig;
1268 proto_ctx->sconfig = ctx->sconfig;
1269 proto_ctx->rconfig = ctx->rconfig;
1271 /* Free old protocol as it is finished now */
1272 silc_protocol_free(protocol);
1274 silc_packet_context_free(ctx->packet);
1276 sock->protocol = NULL;
1278 /* Allocate the authentication protocol. This is allocated here
1279 but we won't start it yet. We will be receiving party of this
1280 protocol thus we will wait that connecting party will make
1281 their first move. */
1282 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1283 &sock->protocol, proto_ctx,
1284 silc_server_accept_new_connection_final);
1286 /* Register timeout task. If the protocol is not executed inside
1287 this timelimit the connection will be terminated. */
1288 proto_ctx->timeout_task =
1289 silc_schedule_task_add(server->schedule, sock->sock,
1290 silc_server_timeout_remote,
1292 server->config->conn_auth_timeout, 0,
1297 /* Final part of accepting new connection. The connection has now
1298 been authenticated and keys has been exchanged. We also know whether
1299 this is client or server connection. */
1301 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1303 SilcProtocol protocol = (SilcProtocol)context;
1304 SilcServerConnAuthInternalContext *ctx =
1305 (SilcServerConnAuthInternalContext *)protocol->context;
1306 SilcServer server = (SilcServer)ctx->server;
1307 SilcSocketConnection sock = ctx->sock;
1308 SilcServerHBContext hb_context;
1309 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1311 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1313 SILC_LOG_DEBUG(("Start"));
1315 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1316 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1317 /* Error occured during protocol */
1318 silc_protocol_free(protocol);
1319 sock->protocol = NULL;
1321 silc_packet_context_free(ctx->packet);
1323 silc_ske_free(ctx->ske);
1324 silc_free(ctx->dest_id);
1325 silc_server_config_unref(&ctx->cconfig);
1326 silc_server_config_unref(&ctx->sconfig);
1327 silc_server_config_unref(&ctx->rconfig);
1329 silc_schedule_task_del_by_callback(server->schedule,
1330 silc_server_failure_callback);
1331 silc_server_disconnect_remote(server, sock, "Server closed connection: "
1332 "Authentication failed");
1333 server->stat.auth_failures++;
1337 entry->data.last_receive = time(NULL);
1339 switch (ctx->conn_type) {
1340 case SILC_SOCKET_TYPE_CLIENT:
1342 SilcClientEntry client;
1343 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1345 /* Verify whether this connection is after all allowed to connect */
1346 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1347 &server->config->param,
1348 conn->param, ctx->ske)) {
1349 server->stat.auth_failures++;
1353 SILC_LOG_DEBUG(("Remote host is client"));
1354 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1357 /* Add the client to the client ID cache. The nickname and Client ID
1358 and other information is created after we have received NEW_CLIENT
1359 packet from client. */
1360 client = silc_idlist_add_client(server->local_list,
1361 NULL, NULL, NULL, NULL, NULL, sock, 0);
1363 SILC_LOG_ERROR(("Could not add new client to cache"));
1364 silc_free(sock->user_data);
1365 silc_server_disconnect_remote(server, sock,
1366 "Server closed connection: "
1367 "Authentication failed");
1368 server->stat.auth_failures++;
1373 server->stat.my_clients++;
1374 server->stat.clients++;
1375 if (server->server_type == SILC_ROUTER)
1376 server->stat.cell_clients++;
1378 /* Get connection parameters */
1380 if (conn->param->keepalive_secs)
1381 hearbeat_timeout = conn->param->keepalive_secs;
1384 id_entry = (void *)client;
1387 case SILC_SOCKET_TYPE_SERVER:
1388 case SILC_SOCKET_TYPE_ROUTER:
1390 SilcServerEntry new_server;
1391 bool initiator = FALSE;
1392 bool backup_local = FALSE;
1393 bool backup_router = FALSE;
1394 char *backup_replace_ip = NULL;
1395 SilcUInt16 backup_replace_port = 0;
1396 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1397 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1399 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1400 /* Verify whether this connection is after all allowed to connect */
1401 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1402 &server->config->param,
1403 rconn ? rconn->param : NULL,
1405 server->stat.auth_failures++;
1411 if (rconn->param->keepalive_secs)
1412 hearbeat_timeout = rconn->param->keepalive_secs;
1415 initiator = rconn->initiator;
1416 backup_local = rconn->backup_local;
1417 backup_router = rconn->backup_router;
1418 backup_replace_ip = rconn->backup_replace_ip;
1419 backup_replace_port = rconn->backup_replace_port;
1423 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1424 /* Verify whether this connection is after all allowed to connect */
1425 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1426 &server->config->param,
1427 sconn ? sconn->param : NULL,
1429 server->stat.auth_failures++;
1434 if (sconn->param->keepalive_secs)
1435 hearbeat_timeout = sconn->param->keepalive_secs;
1438 backup_router = sconn->backup_router;
1442 SILC_LOG_DEBUG(("Remote host is %s",
1443 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1444 "server" : (backup_router ?
1445 "backup router" : "router")));
1446 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1447 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1448 "server" : (backup_router ?
1449 "backup router" : "router")));
1451 /* Add the server into server cache. The server name and Server ID
1452 is updated after we have received NEW_SERVER packet from the
1453 server. We mark ourselves as router for this server if we really
1456 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1457 server->local_list : (backup_router ?
1458 server->local_list :
1459 server->global_list)),
1461 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1462 SILC_SERVER : SILC_ROUTER),
1464 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1465 server->id_entry : (backup_router ?
1466 server->id_entry : NULL)),
1469 SILC_LOG_ERROR(("Could not add new server to cache"));
1470 silc_free(sock->user_data);
1471 silc_server_disconnect_remote(server, sock,
1472 "Server closed connection: "
1473 "Authentication failed");
1474 server->stat.auth_failures++;
1479 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1480 server->stat.my_servers++;
1482 server->stat.my_routers++;
1483 server->stat.servers++;
1485 id_entry = (void *)new_server;
1487 /* If the incoming connection is router and marked as backup router
1488 then add it to be one of our backups */
1489 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1490 silc_server_backup_add(server, new_server, backup_replace_ip,
1491 backup_replace_port, backup_local);
1493 /* Change it back to SERVER type since that's what it really is. */
1495 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1497 new_server->server_type = SILC_BACKUP_ROUTER;
1500 /* Check whether this connection is to be our primary router connection
1501 if we do not already have the primary route. */
1502 if (server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1503 if (silc_server_config_is_primary_route(server) && !initiator)
1506 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1507 server->standalone = FALSE;
1508 if (!server->id_entry->router) {
1509 server->id_entry->router = id_entry;
1510 server->router = id_entry;
1521 sock->type = ctx->conn_type;
1523 /* Add the common data structure to the ID entry. */
1524 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1526 /* Add to sockets internal pointer for fast referencing */
1527 silc_free(sock->user_data);
1528 sock->user_data = id_entry;
1530 /* Connection has been fully established now. Everything is ok. */
1531 SILC_LOG_DEBUG(("New connection authenticated"));
1533 /* Perform keepalive. The `hb_context' will be freed automatically
1534 when finally calling the silc_socket_free function. */
1535 hb_context = silc_calloc(1, sizeof(*hb_context));
1536 hb_context->server = server;
1537 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1538 silc_server_perform_heartbeat,
1542 silc_schedule_task_del_by_callback(server->schedule,
1543 silc_server_failure_callback);
1544 silc_protocol_free(protocol);
1546 silc_packet_context_free(ctx->packet);
1548 silc_ske_free(ctx->ske);
1549 silc_free(ctx->dest_id);
1550 silc_server_config_unref(&ctx->cconfig);
1551 silc_server_config_unref(&ctx->sconfig);
1552 silc_server_config_unref(&ctx->rconfig);
1554 sock->protocol = NULL;
1557 /* This function is used to read packets from network and send packets to
1558 network. This is usually a generic task. */
1560 SILC_TASK_CALLBACK(silc_server_packet_process)
1562 SilcServer server = (SilcServer)context;
1563 SilcSocketConnection sock = server->sockets[fd];
1564 SilcIDListData idata;
1565 SilcCipher cipher = NULL;
1566 SilcHmac hmac = NULL;
1567 SilcUInt32 sequence = 0;
1573 SILC_LOG_DEBUG(("Processing packet"));
1575 /* Packet sending */
1577 if (type == SILC_TASK_WRITE) {
1578 /* Do not send data to disconnected connection */
1579 if (SILC_IS_DISCONNECTED(sock))
1582 server->stat.packets_sent++;
1584 /* Send the packet */
1585 ret = silc_packet_send(sock, TRUE);
1587 /* If returned -2 could not write to connection now, will do
1593 SILC_LOG_ERROR(("Error sending packet to connection "
1594 "%s:%d [%s]", sock->hostname, sock->port,
1595 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1596 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1597 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1602 /* The packet has been sent and now it is time to set the connection
1603 back to only for input. When there is again some outgoing data
1604 available for this connection it will be set for output as well.
1605 This call clears the output setting and sets it only for input. */
1606 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1607 SILC_UNSET_OUTBUF_PENDING(sock);
1609 silc_buffer_clear(sock->outbuf);
1613 /* Packet receiving */
1615 /* Read some data from connection */
1616 ret = silc_packet_receive(sock);
1620 SILC_LOG_ERROR(("Error receiving packet from connection "
1621 "%s:%d [%s] %s", sock->hostname, sock->port,
1622 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1623 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1624 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1625 "Router"), strerror(errno)));
1631 SILC_LOG_DEBUG(("Read EOF"));
1633 /* If connection is disconnecting already we will finally
1634 close the connection */
1635 if (SILC_IS_DISCONNECTING(sock)) {
1636 if (sock->user_data)
1637 silc_server_free_sock_user_data(server, sock, NULL);
1638 silc_server_close_connection(server, sock);
1642 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1643 SILC_SET_DISCONNECTING(sock);
1645 if (sock->user_data) {
1647 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1648 silc_server_free_sock_user_data(server, sock, tmp);
1650 silc_server_free_sock_user_data(server, sock, NULL);
1651 } else if (server->router_conn && server->router_conn->sock == sock &&
1652 !server->router && server->standalone)
1653 silc_schedule_task_add(server->schedule, 0,
1654 silc_server_connect_to_router,
1657 SILC_TASK_PRI_NORMAL);
1659 silc_server_close_connection(server, sock);
1663 /* If connection is disconnecting or disconnected we will ignore
1665 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1666 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1670 server->stat.packets_received++;
1672 /* Get keys and stuff from ID entry */
1673 idata = (SilcIDListData)sock->user_data;
1675 cipher = idata->receive_key;
1676 hmac = idata->hmac_receive;
1677 sequence = idata->psn_receive;
1680 /* Process the packet. This will call the parser that will then
1681 decrypt and parse the packet. */
1682 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1683 TRUE : FALSE, cipher, hmac, sequence,
1684 silc_server_packet_parse, server);
1686 /* If this socket connection is not authenticated yet and the packet
1687 processing failed we will drop the connection since it can be
1688 a malicious flooder. */
1689 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1690 (!sock->protocol || sock->protocol->protocol->type ==
1691 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1692 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1693 SILC_SET_DISCONNECTING(sock);
1695 if (sock->user_data)
1696 silc_server_free_sock_user_data(server, sock, NULL);
1697 silc_server_close_connection(server, sock);
1701 /* Parses whole packet, received earlier. */
1703 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1705 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1706 SilcServer server = (SilcServer)parse_ctx->context;
1707 SilcSocketConnection sock = parse_ctx->sock;
1708 SilcPacketContext *packet = parse_ctx->packet;
1709 SilcIDListData idata = (SilcIDListData)sock->user_data;
1712 SILC_LOG_DEBUG(("Start"));
1714 /* Parse the packet */
1715 if (parse_ctx->normal)
1716 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1718 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1720 /* If entry is disabled ignore what we got. */
1721 if (ret != SILC_PACKET_RESUME_ROUTER &&
1722 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1723 SILC_LOG_DEBUG(("Connection is disabled"));
1727 if (ret == SILC_PACKET_NONE)
1730 /* Check that the the current client ID is same as in the client's packet. */
1731 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1732 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1733 if (client && client->id) {
1734 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1735 packet->src_id_type);
1736 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1744 if (server->server_type == SILC_ROUTER) {
1745 /* Route the packet if it is not destined to us. Other ID types but
1746 server are handled separately after processing them. */
1747 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1748 packet->dst_id_type == SILC_ID_SERVER &&
1749 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1750 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1752 /* Route the packet to fastest route for the destination ID */
1753 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1754 packet->dst_id_type);
1757 silc_server_packet_route(server,
1758 silc_server_route_get(server, id,
1759 packet->dst_id_type),
1766 /* Parse the incoming packet type */
1767 silc_server_packet_parse_type(server, sock, packet);
1769 if (server->server_type == SILC_ROUTER) {
1770 /* Broadcast packet if it is marked as broadcast packet and it is
1771 originated from router and we are router. */
1772 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1773 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1774 !server->standalone) {
1775 /* Broadcast to our primary route */
1776 silc_server_packet_broadcast(server, server->router->connection, packet);
1778 /* If we have backup routers then we need to feed all broadcast
1779 data to those servers. */
1780 silc_server_backup_broadcast(server, sock, packet);
1785 silc_packet_context_free(packet);
1786 silc_free(parse_ctx);
1789 /* Parser callback called by silc_packet_receive_process. This merely
1790 registers timeout that will handle the actual parsing when appropriate. */
1792 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1795 SilcServer server = (SilcServer)context;
1796 SilcSocketConnection sock = parser_context->sock;
1797 SilcIDListData idata = (SilcIDListData)sock->user_data;
1800 idata->psn_receive = parser_context->packet->sequence + 1;
1802 /* If protocol for this connection is key exchange or rekey then we'll
1803 process all packets synchronously, since there might be packets in
1804 queue that we are not able to decrypt without first processing the
1805 packets before them. */
1806 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1807 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1808 (sock->protocol && sock->protocol->protocol &&
1809 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1810 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1811 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1814 /* Reprocess data since we'll return FALSE here. This is because
1815 the idata->receive_key might have become valid in the last packet
1816 and we want to call this processor with valid cipher. */
1818 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1819 TRUE : FALSE, idata->receive_key,
1820 idata->hmac_receive, idata->psn_receive,
1821 silc_server_packet_parse, server);
1823 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1824 TRUE : FALSE, NULL, NULL, 0,
1825 silc_server_packet_parse, server);
1829 switch (sock->type) {
1830 case SILC_SOCKET_TYPE_UNKNOWN:
1831 case SILC_SOCKET_TYPE_CLIENT:
1832 /* Parse the packet with timeout */
1833 silc_schedule_task_add(server->schedule, sock->sock,
1834 silc_server_packet_parse_real,
1835 (void *)parser_context, 0, 100000,
1837 SILC_TASK_PRI_NORMAL);
1839 case SILC_SOCKET_TYPE_SERVER:
1840 case SILC_SOCKET_TYPE_ROUTER:
1841 /* Packets from servers are parsed immediately */
1842 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1852 /* Parses the packet type and calls what ever routines the packet type
1853 requires. This is done for all incoming packets. */
1855 void silc_server_packet_parse_type(SilcServer server,
1856 SilcSocketConnection sock,
1857 SilcPacketContext *packet)
1859 SilcPacketType type = packet->type;
1860 SilcIDListData idata = (SilcIDListData)sock->user_data;
1862 SILC_LOG_DEBUG(("Parsing packet type %d", type));
1864 /* Parse the packet type */
1866 case SILC_PACKET_DISCONNECT:
1867 SILC_LOG_DEBUG(("Disconnect packet"));
1868 if (packet->flags & SILC_PACKET_FLAG_LIST)
1870 if (silc_string_is_ascii(packet->buffer->data, packet->buffer->len)) {
1871 /* Duplicate to null terminate the string. */
1872 char *message = silc_memdup(packet->buffer->data, packet->buffer->len);
1873 SILC_LOG_ERROR(("%s", message));
1878 case SILC_PACKET_SUCCESS:
1880 * Success received for something. For now we can have only
1881 * one protocol for connection executing at once hence this
1882 * success message is for whatever protocol is executing currently.
1884 SILC_LOG_DEBUG(("Success packet"));
1885 if (packet->flags & SILC_PACKET_FLAG_LIST)
1888 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1891 case SILC_PACKET_FAILURE:
1893 * Failure received for something. For now we can have only
1894 * one protocol for connection executing at once hence this
1895 * failure message is for whatever protocol is executing currently.
1897 SILC_LOG_DEBUG(("Failure packet"));
1898 if (packet->flags & SILC_PACKET_FLAG_LIST)
1900 if (sock->protocol) {
1901 SilcServerFailureContext f;
1902 f = silc_calloc(1, sizeof(*f));
1906 /* We will wait 5 seconds to process this failure packet */
1907 silc_schedule_task_add(server->schedule, sock->sock,
1908 silc_server_failure_callback, (void *)f, 5, 0,
1909 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1913 case SILC_PACKET_REJECT:
1914 SILC_LOG_DEBUG(("Reject packet"));
1915 if (packet->flags & SILC_PACKET_FLAG_LIST)
1920 case SILC_PACKET_NOTIFY:
1922 * Received notify packet. Server can receive notify packets from
1923 * router. Server then relays the notify messages to clients if needed.
1925 SILC_LOG_DEBUG(("Notify packet"));
1926 if (packet->flags & SILC_PACKET_FLAG_LIST)
1927 silc_server_notify_list(server, sock, packet);
1929 silc_server_notify(server, sock, packet);
1935 case SILC_PACKET_CHANNEL_MESSAGE:
1937 * Received channel message. Channel messages are special packets
1938 * (although probably most common ones) thus they are handled
1941 SILC_LOG_DEBUG(("Channel Message packet"));
1942 if (packet->flags & SILC_PACKET_FLAG_LIST)
1944 idata->last_receive = time(NULL);
1945 silc_server_channel_message(server, sock, packet);
1948 case SILC_PACKET_CHANNEL_KEY:
1950 * Received key for channel. As channels are created by the router
1951 * the keys are as well. We will distribute the key to all of our
1952 * locally connected clients on the particular channel. Router
1953 * never receives this channel and thus is ignored.
1955 SILC_LOG_DEBUG(("Channel Key packet"));
1956 if (packet->flags & SILC_PACKET_FLAG_LIST)
1958 silc_server_channel_key(server, sock, packet);
1964 case SILC_PACKET_COMMAND:
1966 * Recived command. Processes the command request and allocates the
1967 * command context and calls the command.
1969 SILC_LOG_DEBUG(("Command packet"));
1970 if (packet->flags & SILC_PACKET_FLAG_LIST)
1972 silc_server_command_process(server, sock, packet);
1975 case SILC_PACKET_COMMAND_REPLY:
1977 * Received command reply packet. Received command reply to command. It
1978 * may be reply to command sent by us or reply to command sent by client
1979 * that we've routed further.
1981 SILC_LOG_DEBUG(("Command Reply packet"));
1982 if (packet->flags & SILC_PACKET_FLAG_LIST)
1984 silc_server_command_reply(server, sock, packet);
1988 * Private Message packets
1990 case SILC_PACKET_PRIVATE_MESSAGE:
1992 * Received private message packet. The packet is coming from either
1995 SILC_LOG_DEBUG(("Private Message packet"));
1996 if (packet->flags & SILC_PACKET_FLAG_LIST)
1998 idata->last_receive = time(NULL);
1999 silc_server_private_message(server, sock, packet);
2002 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2004 * Private message key packet.
2006 if (packet->flags & SILC_PACKET_FLAG_LIST)
2008 silc_server_private_message_key(server, sock, packet);
2012 * Key Exchange protocol packets
2014 case SILC_PACKET_KEY_EXCHANGE:
2015 SILC_LOG_DEBUG(("KE packet"));
2016 if (packet->flags & SILC_PACKET_FLAG_LIST)
2019 if (sock->protocol && sock->protocol->protocol &&
2020 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2021 SilcServerKEInternalContext *proto_ctx =
2022 (SilcServerKEInternalContext *)sock->protocol->context;
2024 proto_ctx->packet = silc_packet_context_dup(packet);
2026 /* Let the protocol handle the packet */
2027 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2029 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2030 "protocol active, packet dropped."));
2034 case SILC_PACKET_KEY_EXCHANGE_1:
2035 SILC_LOG_DEBUG(("KE 1 packet"));
2036 if (packet->flags & SILC_PACKET_FLAG_LIST)
2039 if (sock->protocol && sock->protocol->protocol &&
2040 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2041 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2043 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2044 SilcServerRekeyInternalContext *proto_ctx =
2045 (SilcServerRekeyInternalContext *)sock->protocol->context;
2047 if (proto_ctx->packet)
2048 silc_packet_context_free(proto_ctx->packet);
2050 proto_ctx->packet = silc_packet_context_dup(packet);
2052 /* Let the protocol handle the packet */
2053 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2055 SilcServerKEInternalContext *proto_ctx =
2056 (SilcServerKEInternalContext *)sock->protocol->context;
2058 if (proto_ctx->packet)
2059 silc_packet_context_free(proto_ctx->packet);
2061 proto_ctx->packet = silc_packet_context_dup(packet);
2062 proto_ctx->dest_id_type = packet->src_id_type;
2063 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2064 packet->src_id_type);
2065 if (!proto_ctx->dest_id)
2068 /* Let the protocol handle the packet */
2069 silc_protocol_execute(sock->protocol, server->schedule,
2073 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2074 "protocol active, packet dropped."));
2078 case SILC_PACKET_KEY_EXCHANGE_2:
2079 SILC_LOG_DEBUG(("KE 2 packet"));
2080 if (packet->flags & SILC_PACKET_FLAG_LIST)
2083 if (sock->protocol && sock->protocol->protocol &&
2084 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2085 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2087 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2088 SilcServerRekeyInternalContext *proto_ctx =
2089 (SilcServerRekeyInternalContext *)sock->protocol->context;
2091 if (proto_ctx->packet)
2092 silc_packet_context_free(proto_ctx->packet);
2094 proto_ctx->packet = silc_packet_context_dup(packet);
2096 /* Let the protocol handle the packet */
2097 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2099 SilcServerKEInternalContext *proto_ctx =
2100 (SilcServerKEInternalContext *)sock->protocol->context;
2102 if (proto_ctx->packet)
2103 silc_packet_context_free(proto_ctx->packet);
2105 proto_ctx->packet = silc_packet_context_dup(packet);
2106 proto_ctx->dest_id_type = packet->src_id_type;
2107 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2108 packet->src_id_type);
2109 if (!proto_ctx->dest_id)
2112 /* Let the protocol handle the packet */
2113 silc_protocol_execute(sock->protocol, server->schedule,
2117 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2118 "protocol active, packet dropped."));
2122 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2124 * Connection authentication request packet. When we receive this packet
2125 * we will send to the other end information about our mandatory
2126 * authentication method for the connection. This packet maybe received
2129 SILC_LOG_DEBUG(("Connection authentication request packet"));
2130 if (packet->flags & SILC_PACKET_FLAG_LIST)
2132 silc_server_connection_auth_request(server, sock, packet);
2136 * Connection Authentication protocol packets
2138 case SILC_PACKET_CONNECTION_AUTH:
2139 /* Start of the authentication protocol. We receive here the
2140 authentication data and will verify it. */
2141 SILC_LOG_DEBUG(("Connection auth packet"));
2142 if (packet->flags & SILC_PACKET_FLAG_LIST)
2145 if (sock->protocol && sock->protocol->protocol->type
2146 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2148 SilcServerConnAuthInternalContext *proto_ctx =
2149 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2151 proto_ctx->packet = silc_packet_context_dup(packet);
2153 /* Let the protocol handle the packet */
2154 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2156 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2157 "protocol active, packet dropped."));
2161 case SILC_PACKET_NEW_ID:
2163 * Received New ID packet. This includes some new ID that has been
2164 * created. It may be for client, server or channel. This is the way
2165 * to distribute information about new registered entities in the
2168 SILC_LOG_DEBUG(("New ID packet"));
2169 if (packet->flags & SILC_PACKET_FLAG_LIST)
2170 silc_server_new_id_list(server, sock, packet);
2172 silc_server_new_id(server, sock, packet);
2175 case SILC_PACKET_NEW_CLIENT:
2177 * Received new client packet. This includes client information that
2178 * we will use to create initial client ID. After creating new
2179 * ID we will send it to the client.
2181 SILC_LOG_DEBUG(("New Client packet"));
2182 if (packet->flags & SILC_PACKET_FLAG_LIST)
2184 silc_server_new_client(server, sock, packet);
2187 case SILC_PACKET_NEW_SERVER:
2189 * Received new server packet. This includes Server ID and some other
2190 * information that we may save. This is received after server has
2193 SILC_LOG_DEBUG(("New Server packet"));
2194 if (packet->flags & SILC_PACKET_FLAG_LIST)
2196 silc_server_new_server(server, sock, packet);
2199 case SILC_PACKET_NEW_CHANNEL:
2201 * Received new channel packet. Information about new channel in the
2202 * network are distributed using this packet.
2204 SILC_LOG_DEBUG(("New Channel packet"));
2205 if (packet->flags & SILC_PACKET_FLAG_LIST)
2206 silc_server_new_channel_list(server, sock, packet);
2208 silc_server_new_channel(server, sock, packet);
2211 case SILC_PACKET_HEARTBEAT:
2213 * Received heartbeat.
2215 SILC_LOG_DEBUG(("Heartbeat packet"));
2216 if (packet->flags & SILC_PACKET_FLAG_LIST)
2220 case SILC_PACKET_KEY_AGREEMENT:
2222 * Received heartbeat.
2224 SILC_LOG_DEBUG(("Key agreement packet"));
2225 if (packet->flags & SILC_PACKET_FLAG_LIST)
2227 silc_server_key_agreement(server, sock, packet);
2230 case SILC_PACKET_REKEY:
2232 * Received re-key packet. The sender wants to regenerate the session
2235 SILC_LOG_DEBUG(("Re-key packet"));
2236 if (packet->flags & SILC_PACKET_FLAG_LIST)
2238 silc_server_rekey(server, sock, packet);
2241 case SILC_PACKET_REKEY_DONE:
2243 * The re-key is done.
2245 SILC_LOG_DEBUG(("Re-key done packet"));
2246 if (packet->flags & SILC_PACKET_FLAG_LIST)
2249 if (sock->protocol && sock->protocol->protocol &&
2250 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2252 SilcServerRekeyInternalContext *proto_ctx =
2253 (SilcServerRekeyInternalContext *)sock->protocol->context;
2255 if (proto_ctx->packet)
2256 silc_packet_context_free(proto_ctx->packet);
2258 proto_ctx->packet = silc_packet_context_dup(packet);
2260 /* Let the protocol handle the packet */
2261 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2263 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2264 "protocol active, packet dropped."));
2268 case SILC_PACKET_FTP:
2270 SILC_LOG_DEBUG(("FTP packet"));
2271 if (packet->flags & SILC_PACKET_FLAG_LIST)
2273 silc_server_ftp(server, sock, packet);
2276 case SILC_PACKET_RESUME_ROUTER:
2277 /* Resume router packet received. This packet is received for backup
2278 router resuming protocol. */
2279 SILC_LOG_DEBUG(("Resume router packet"));
2280 if (packet->flags & SILC_PACKET_FLAG_LIST)
2282 silc_server_backup_resume_router(server, sock, packet);
2286 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2292 /* Creates connection to a remote router. */
2294 void silc_server_create_connection(SilcServer server,
2295 const char *remote_host, SilcUInt32 port)
2297 SilcServerConnection sconn;
2299 /* Allocate connection object for hold connection specific stuff. */
2300 sconn = silc_calloc(1, sizeof(*sconn));
2301 sconn->server = server;
2302 sconn->remote_host = strdup(remote_host);
2303 sconn->remote_port = port;
2304 sconn->no_reconnect = TRUE;
2306 silc_schedule_task_add(server->schedule, 0,
2307 silc_server_connect_router,
2308 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2309 SILC_TASK_PRI_NORMAL);
2312 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2314 silc_socket_free((SilcSocketConnection)context);
2317 /* Closes connection to socket connection */
2319 void silc_server_close_connection(SilcServer server,
2320 SilcSocketConnection sock)
2322 if (!server->sockets[sock->sock])
2325 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2327 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2328 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2329 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2332 /* We won't listen for this connection anymore */
2333 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2335 /* Unregister all tasks */
2336 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2338 /* Close the actual connection */
2339 silc_net_close_connection(sock->sock);
2340 server->sockets[sock->sock] = NULL;
2342 /* If sock->user_data is NULL then we'll check for active protocols
2343 here since the silc_server_free_sock_user_data has not been called
2344 for this connection. */
2345 if (!sock->user_data) {
2346 /* If any protocol is active cancel its execution. It will call
2347 the final callback which will finalize the disconnection. */
2348 if (sock->protocol) {
2349 silc_protocol_cancel(sock->protocol, server->schedule);
2350 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2351 silc_protocol_execute_final(sock->protocol, server->schedule);
2352 sock->protocol = NULL;
2357 silc_schedule_task_add(server->schedule, 0,
2358 silc_server_close_connection_final,
2359 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2360 SILC_TASK_PRI_NORMAL);
2363 /* Sends disconnect message to remote connection and disconnects the
2366 void silc_server_disconnect_remote(SilcServer server,
2367 SilcSocketConnection sock,
2368 const char *fmt, ...)
2371 unsigned char buf[4096];
2376 memset(buf, 0, sizeof(buf));
2378 vsprintf(buf, fmt, ap);
2381 SILC_LOG_DEBUG(("Disconnecting remote host"));
2383 /* Notify remote end that the conversation is over. The notify message
2384 is tried to be sent immediately. */
2385 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2386 buf, strlen(buf), TRUE);
2387 silc_server_packet_queue_purge(server, sock);
2389 /* Mark the connection to be disconnected */
2390 SILC_SET_DISCONNECTED(sock);
2391 silc_server_close_connection(server, sock);
2396 SilcClientEntry client;
2397 } *FreeClientInternal;
2399 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2401 FreeClientInternal i = (FreeClientInternal)context;
2403 silc_idlist_del_data(i->client);
2404 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2408 /* Frees client data and notifies about client's signoff. */
2410 void silc_server_free_client_data(SilcServer server,
2411 SilcSocketConnection sock,
2412 SilcClientEntry client,
2414 const char *signoff)
2416 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2418 /* If there is pending outgoing data for the client then purge it
2419 to the network before removing the client entry. */
2420 silc_server_packet_queue_purge(server, sock);
2425 /* Send SIGNOFF notify to routers. */
2426 if (notify && !server->standalone && server->router)
2427 silc_server_send_notify_signoff(server, server->router->connection,
2428 server->server_type == SILC_SERVER ?
2429 FALSE : TRUE, client->id, signoff);
2431 /* Remove client from all channels */
2433 silc_server_remove_from_channels(server, NULL, client,
2434 TRUE, (char *)signoff, TRUE);
2436 silc_server_remove_from_channels(server, NULL, client,
2437 FALSE, NULL, FALSE);
2439 /* Update statistics */
2440 server->stat.my_clients--;
2441 server->stat.clients--;
2442 if (server->server_type == SILC_ROUTER)
2443 server->stat.cell_clients--;
2444 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2445 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2447 /* We will not delete the client entry right away. We will take it
2448 into history (for WHOWAS command) for 5 minutes */
2451 silc_schedule_task_add(server->schedule, 0,
2452 silc_server_free_client_data_timeout,
2454 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2455 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2456 client->router = NULL;
2457 client->connection = NULL;
2461 /* Frees user_data pointer from socket connection object. This also sends
2462 appropriate notify packets to the network to inform about leaving
2465 void silc_server_free_sock_user_data(SilcServer server,
2466 SilcSocketConnection sock,
2467 const char *signoff_message)
2469 SILC_LOG_DEBUG(("Start"));
2471 switch (sock->type) {
2472 case SILC_SOCKET_TYPE_CLIENT:
2474 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2475 silc_server_free_client_data(server, sock, user_data, TRUE,
2479 case SILC_SOCKET_TYPE_SERVER:
2480 case SILC_SOCKET_TYPE_ROUTER:
2482 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2483 SilcServerEntry backup_router = NULL;
2486 backup_router = silc_server_backup_get(server, user_data->id);
2488 /* If this was our primary router connection then we're lost to
2489 the outside world. */
2490 if (server->router == user_data) {
2491 /* Check whether we have a backup router connection */
2492 if (!backup_router || backup_router == user_data) {
2493 silc_schedule_task_add(server->schedule, 0,
2494 silc_server_connect_to_router,
2497 SILC_TASK_PRI_NORMAL);
2499 server->id_entry->router = NULL;
2500 server->router = NULL;
2501 server->standalone = TRUE;
2502 backup_router = NULL;
2504 SILC_LOG_INFO(("New primary router is backup router %s",
2505 backup_router->server_name));
2506 SILC_LOG_DEBUG(("New primary router is backup router %s",
2507 backup_router->server_name));
2508 server->id_entry->router = backup_router;
2509 server->router = backup_router;
2510 server->router_connect = time(0);
2511 server->backup_primary = TRUE;
2512 if (server->server_type == SILC_BACKUP_ROUTER) {
2513 server->server_type = SILC_ROUTER;
2515 /* We'll need to constantly try to reconnect to the primary
2516 router so that we'll see when it comes back online. */
2517 silc_server_backup_reconnect(server, sock->ip, sock->port,
2518 silc_server_backup_connected,
2522 /* Mark this connection as replaced */
2523 silc_server_backup_replaced_add(server, user_data->id,
2526 } else if (backup_router) {
2527 SILC_LOG_INFO(("Enabling the use of backup router %s",
2528 backup_router->server_name));
2529 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2530 backup_router->server_name));
2532 /* Mark this connection as replaced */
2533 silc_server_backup_replaced_add(server, user_data->id,
2537 if (!backup_router) {
2538 /* Free all client entries that this server owns as they will
2539 become invalid now as well. */
2541 silc_server_remove_clients_by_server(server, user_data, TRUE);
2542 if (server->server_type == SILC_SERVER)
2543 silc_server_remove_channels_by_server(server, user_data);
2545 /* Update the client entries of this server to the new backup
2546 router. This also removes the clients that *really* was owned
2547 by the primary router and went down with the router. */
2548 silc_server_update_clients_by_server(server, user_data, backup_router,
2550 silc_server_update_servers_by_server(server, user_data, backup_router);
2551 if (server->server_type == SILC_SERVER)
2552 silc_server_update_channels_by_server(server, user_data,
2556 /* Free the server entry */
2557 silc_server_backup_del(server, user_data);
2558 silc_server_backup_replaced_del(server, user_data);
2559 silc_idlist_del_data(user_data);
2560 if (!silc_idlist_del_server(server->local_list, user_data))
2561 silc_idlist_del_server(server->global_list, user_data);
2562 server->stat.my_servers--;
2563 server->stat.servers--;
2564 if (server->server_type == SILC_ROUTER)
2565 server->stat.cell_servers--;
2567 if (backup_router) {
2568 /* Announce all of our stuff that was created about 5 minutes ago.
2569 The backup router knows all the other stuff already. */
2570 if (server->server_type == SILC_ROUTER)
2571 silc_server_announce_servers(server, FALSE, time(0) - 300,
2572 backup_router->connection);
2574 /* Announce our clients and channels to the router */
2575 silc_server_announce_clients(server, time(0) - 300,
2576 backup_router->connection);
2577 silc_server_announce_channels(server, time(0) - 300,
2578 backup_router->connection);
2584 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2586 silc_idlist_del_data(user_data);
2587 silc_free(user_data);
2592 /* If any protocol is active cancel its execution */
2593 if (sock->protocol) {
2594 silc_protocol_cancel(sock->protocol, server->schedule);
2595 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2596 silc_protocol_execute_final(sock->protocol, server->schedule);
2597 sock->protocol = NULL;
2600 sock->user_data = NULL;
2603 /* Removes client from all channels it has joined. This is used when client
2604 connection is disconnected. If the client on a channel is last, the
2605 channel is removed as well. This sends the SIGNOFF notify types. */
2607 void silc_server_remove_from_channels(SilcServer server,
2608 SilcSocketConnection sock,
2609 SilcClientEntry client,
2611 char *signoff_message,
2614 SilcChannelEntry channel;
2615 SilcChannelClientEntry chl;
2616 SilcHashTableList htl;
2619 SILC_LOG_DEBUG(("Start"));
2621 if (!client || !client->id)
2624 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2626 /* Remove the client from all channels. The client is removed from
2627 the channels' user list. */
2628 silc_hash_table_list(client->channels, &htl);
2629 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2630 channel = chl->channel;
2632 /* Remove channel from client's channel list */
2633 silc_hash_table_del(client->channels, channel);
2635 /* Remove channel if there is no users anymore */
2636 if (server->server_type == SILC_ROUTER &&
2637 silc_hash_table_count(channel->user_list) < 2) {
2639 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2640 if (silc_idlist_del_channel(server->local_list, channel))
2641 server->stat.my_channels--;
2643 silc_idlist_del_channel(server->global_list, channel);
2647 /* Remove client from channel's client list */
2648 silc_hash_table_del(channel->user_list, chl->client);
2649 channel->user_count--;
2651 /* If there is no global users on the channel anymore mark the channel
2652 as local channel. Do not check if the removed client is local client. */
2653 if (server->server_type != SILC_ROUTER && channel->global_users &&
2654 chl->client->router && !silc_server_channel_has_global(channel))
2655 channel->global_users = FALSE;
2658 server->stat.my_chanclients--;
2660 /* If there is not at least one local user on the channel then we don't
2661 need the channel entry anymore, we can remove it safely. */
2662 if (server->server_type != SILC_ROUTER &&
2663 !silc_server_channel_has_local(channel)) {
2664 /* Notify about leaving client if this channel has global users. */
2665 if (notify && channel->global_users)
2666 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2667 SILC_NOTIFY_TYPE_SIGNOFF,
2668 signoff_message ? 2 : 1,
2669 clidp->data, clidp->len,
2670 signoff_message, signoff_message ?
2671 strlen(signoff_message) : 0);
2674 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2676 if (channel->founder_key) {
2677 /* The founder auth data exists, do not remove the channel entry */
2678 SilcChannelClientEntry chl2;
2679 SilcHashTableList htl2;
2681 channel->disabled = TRUE;
2683 silc_hash_table_list(channel->user_list, &htl2);
2684 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2685 silc_hash_table_del(chl2->client->channels, channel);
2686 silc_hash_table_del(channel->user_list, chl2->client);
2687 channel->user_count--;
2690 silc_hash_table_list_reset(&htl2);
2694 /* Remove the channel entry */
2695 if (silc_idlist_del_channel(server->local_list, channel))
2696 server->stat.my_channels--;
2698 silc_idlist_del_channel(server->global_list, channel);
2702 /* Send notify to channel about client leaving SILC and thus
2703 the entire channel. */
2705 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2706 SILC_NOTIFY_TYPE_SIGNOFF,
2707 signoff_message ? 2 : 1,
2708 clidp->data, clidp->len,
2709 signoff_message, signoff_message ?
2710 strlen(signoff_message) : 0);
2712 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2713 /* Re-generate channel key */
2714 if (!silc_server_create_channel_key(server, channel, 0))
2717 /* Send the channel key to the channel. The key of course is not sent
2718 to the client who was removed from the channel. */
2719 silc_server_send_channel_key(server, client->connection, channel,
2720 server->server_type == SILC_ROUTER ?
2721 FALSE : !server->standalone);
2726 silc_hash_table_list_reset(&htl);
2727 silc_buffer_free(clidp);
2730 /* Removes client from one channel. This is used for example when client
2731 calls LEAVE command to remove itself from the channel. Returns TRUE
2732 if channel still exists and FALSE if the channel is removed when
2733 last client leaves the channel. If `notify' is FALSE notify messages
2736 int silc_server_remove_from_one_channel(SilcServer server,
2737 SilcSocketConnection sock,
2738 SilcChannelEntry channel,
2739 SilcClientEntry client,
2742 SilcChannelClientEntry chl;
2745 SILC_LOG_DEBUG(("Start"));
2747 /* Get the entry to the channel, if this client is not on the channel
2749 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2752 /* Remove the client from the channel. The client is removed from
2753 the channel's user list. */
2755 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2757 /* Remove channel from client's channel list */
2758 silc_hash_table_del(client->channels, chl->channel);
2760 /* Remove channel if there is no users anymore */
2761 if (server->server_type == SILC_ROUTER &&
2762 silc_hash_table_count(channel->user_list) < 2) {
2764 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2765 if (silc_idlist_del_channel(server->local_list, channel))
2766 server->stat.my_channels--;
2768 silc_idlist_del_channel(server->global_list, channel);
2769 silc_buffer_free(clidp);
2773 /* Remove client from channel's client list */
2774 silc_hash_table_del(channel->user_list, chl->client);
2775 channel->user_count--;
2777 /* If there is no global users on the channel anymore mark the channel
2778 as local channel. Do not check if the client is local client. */
2779 if (server->server_type != SILC_ROUTER && channel->global_users &&
2780 chl->client->router && !silc_server_channel_has_global(channel))
2781 channel->global_users = FALSE;
2784 server->stat.my_chanclients--;
2786 /* If there is not at least one local user on the channel then we don't
2787 need the channel entry anymore, we can remove it safely. */
2788 if (server->server_type != SILC_ROUTER &&
2789 !silc_server_channel_has_local(channel)) {
2790 /* Notify about leaving client if this channel has global users. */
2791 if (notify && channel->global_users)
2792 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2793 SILC_NOTIFY_TYPE_LEAVE, 1,
2794 clidp->data, clidp->len);
2796 silc_buffer_free(clidp);
2799 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2801 if (channel->founder_key) {
2802 /* The founder auth data exists, do not remove the channel entry */
2803 SilcChannelClientEntry chl2;
2804 SilcHashTableList htl2;
2806 channel->disabled = TRUE;
2808 silc_hash_table_list(channel->user_list, &htl2);
2809 while (silc_hash_table_get(&htl2, NULL, (void *)&chl2)) {
2810 silc_hash_table_del(chl2->client->channels, channel);
2811 silc_hash_table_del(channel->user_list, chl2->client);
2812 channel->user_count--;
2815 silc_hash_table_list_reset(&htl2);
2819 /* Remove the channel entry */
2820 if (silc_idlist_del_channel(server->local_list, channel))
2821 server->stat.my_channels--;
2823 silc_idlist_del_channel(server->global_list, channel);
2827 /* Send notify to channel about client leaving the channel */
2829 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2830 SILC_NOTIFY_TYPE_LEAVE, 1,
2831 clidp->data, clidp->len);
2833 silc_buffer_free(clidp);
2837 /* Timeout callback. This is called if connection is idle or for some
2838 other reason is not responding within some period of time. This
2839 disconnects the remote end. */
2841 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2843 SilcServer server = (SilcServer)context;
2844 SilcSocketConnection sock = server->sockets[fd];
2846 SILC_LOG_DEBUG(("Start"));
2851 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
2852 sock->hostname, sock->ip));
2854 /* If we have protocol active we must assure that we call the protocol's
2855 final callback so that all the memory is freed. */
2856 if (sock->protocol) {
2857 silc_protocol_cancel(sock->protocol, server->schedule);
2858 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2859 silc_protocol_execute_final(sock->protocol, server->schedule);
2860 sock->protocol = NULL;
2864 if (sock->user_data)
2865 silc_server_free_sock_user_data(server, sock, NULL);
2867 silc_server_disconnect_remote(server, sock, "Server closed connection: "
2868 "Connection timeout");
2871 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2872 function may be used only by router. In real SILC network all channels
2873 are created by routers thus this function is never used by normal
2876 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
2877 SilcServerID *router_id,
2883 SilcChannelID *channel_id;
2884 SilcChannelEntry entry;
2888 SILC_LOG_DEBUG(("Creating new channel"));
2891 cipher = SILC_DEFAULT_CIPHER;
2893 hmac = SILC_DEFAULT_HMAC;
2895 /* Allocate cipher */
2896 if (!silc_cipher_alloc(cipher, &key))
2900 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2901 silc_cipher_free(key);
2905 channel_name = strdup(channel_name);
2907 /* Create the channel ID */
2908 if (!silc_id_create_channel_id(server, router_id, server->rng,
2910 silc_free(channel_name);
2911 silc_cipher_free(key);
2912 silc_hmac_free(newhmac);
2916 /* Create the channel */
2917 entry = silc_idlist_add_channel(server->local_list, channel_name,
2918 SILC_CHANNEL_MODE_NONE, channel_id,
2919 NULL, key, newhmac, 0);
2921 silc_free(channel_name);
2922 silc_cipher_free(key);
2923 silc_hmac_free(newhmac);
2924 silc_free(channel_id);
2928 entry->cipher = strdup(cipher);
2929 entry->hmac_name = strdup(hmac);
2931 /* Now create the actual key material */
2932 if (!silc_server_create_channel_key(server, entry,
2933 silc_cipher_get_key_len(key) / 8)) {
2934 silc_idlist_del_channel(server->local_list, entry);
2938 /* Notify other routers about the new channel. We send the packet
2939 to our primary route. */
2940 if (broadcast && server->standalone == FALSE)
2941 silc_server_send_new_channel(server, server->router->connection, TRUE,
2942 channel_name, entry->id,
2943 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
2946 server->stat.my_channels++;
2951 /* Same as above but creates the channel with Channel ID `channel_id. */
2954 silc_server_create_new_channel_with_id(SilcServer server,
2958 SilcChannelID *channel_id,
2961 SilcChannelEntry entry;
2965 SILC_LOG_DEBUG(("Creating new channel"));
2968 cipher = SILC_DEFAULT_CIPHER;
2970 hmac = SILC_DEFAULT_HMAC;
2972 /* Allocate cipher */
2973 if (!silc_cipher_alloc(cipher, &key))
2977 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2978 silc_cipher_free(key);
2982 channel_name = strdup(channel_name);
2984 /* Create the channel */
2985 entry = silc_idlist_add_channel(server->local_list, channel_name,
2986 SILC_CHANNEL_MODE_NONE, channel_id,
2987 NULL, key, newhmac, 0);
2989 silc_cipher_free(key);
2990 silc_hmac_free(newhmac);
2991 silc_free(channel_name);
2995 /* Now create the actual key material */
2996 if (!silc_server_create_channel_key(server, entry,
2997 silc_cipher_get_key_len(key) / 8)) {
2998 silc_idlist_del_channel(server->local_list, entry);
3002 /* Notify other routers about the new channel. We send the packet
3003 to our primary route. */
3004 if (broadcast && server->standalone == FALSE)
3005 silc_server_send_new_channel(server, server->router->connection, TRUE,
3006 channel_name, entry->id,
3007 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3010 server->stat.my_channels++;
3015 /* Channel's key re-key timeout callback. */
3017 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3019 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3020 SilcServer server = (SilcServer)rekey->context;
3024 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3027 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3030 /* Generates new channel key. This is used to create the initial channel key
3031 but also to re-generate new key for channel. If `key_len' is provided
3032 it is the bytes of the key length. */
3034 bool silc_server_create_channel_key(SilcServer server,
3035 SilcChannelEntry channel,
3039 unsigned char channel_key[32], hash[32];
3042 SILC_LOG_DEBUG(("Generating channel key"));
3044 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3045 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3049 if (!channel->channel_key)
3050 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3051 channel->channel_key = NULL;
3057 else if (channel->key_len)
3058 len = channel->key_len / 8;
3060 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3062 /* Create channel key */
3063 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3066 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3068 /* Remove old key if exists */
3070 memset(channel->key, 0, channel->key_len / 8);
3071 silc_free(channel->key);
3075 channel->key_len = len * 8;
3076 channel->key = silc_memdup(channel_key, len);
3077 memset(channel_key, 0, sizeof(channel_key));
3079 /* Generate HMAC key from the channel key data and set it */
3081 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3082 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3083 silc_hmac_set_key(channel->hmac, hash,
3084 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3085 memset(hash, 0, sizeof(hash));
3087 if (server->server_type == SILC_ROUTER) {
3088 if (!channel->rekey)
3089 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3090 channel->rekey->context = (void *)server;
3091 channel->rekey->channel = channel;
3092 channel->rekey->key_len = key_len;
3093 if (channel->rekey->task)
3094 silc_schedule_task_del(server->schedule, channel->rekey->task);
3096 channel->rekey->task =
3097 silc_schedule_task_add(server->schedule, 0,
3098 silc_server_channel_key_rekey,
3099 (void *)channel->rekey,
3100 server->config->channel_rekey_secs, 0,
3102 SILC_TASK_PRI_NORMAL);
3108 /* Saves the channel key found in the encoded `key_payload' buffer. This
3109 function is used when we receive Channel Key Payload and also when we're
3110 processing JOIN command reply. Returns entry to the channel. */
3112 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3113 SilcBuffer key_payload,
3114 SilcChannelEntry channel)
3116 SilcChannelKeyPayload payload = NULL;
3117 SilcChannelID *id = NULL;
3118 unsigned char *tmp, hash[32];
3122 SILC_LOG_DEBUG(("Start"));
3124 /* Decode channel key payload */
3125 payload = silc_channel_key_payload_parse(key_payload->data,
3128 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3133 /* Get the channel entry */
3136 /* Get channel ID */
3137 tmp = silc_channel_key_get_id(payload, &tmp_len);
3138 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3144 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3146 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3148 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3149 silc_id_render(id, SILC_ID_CHANNEL)));
3155 tmp = silc_channel_key_get_key(payload, &tmp_len);
3161 cipher = silc_channel_key_get_cipher(payload, NULL);
3167 /* Remove old key if exists */
3169 memset(channel->key, 0, channel->key_len / 8);
3170 silc_free(channel->key);
3171 silc_cipher_free(channel->channel_key);
3174 /* Create new cipher */
3175 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3176 channel->channel_key = NULL;
3181 if (channel->cipher)
3182 silc_free(channel->cipher);
3183 channel->cipher = strdup(cipher);
3186 channel->key_len = tmp_len * 8;
3187 channel->key = silc_memdup(tmp, tmp_len);
3188 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3190 /* Generate HMAC key from the channel key data and set it */
3192 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3193 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3194 silc_hmac_set_key(channel->hmac, hash,
3195 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3197 memset(hash, 0, sizeof(hash));
3198 memset(tmp, 0, tmp_len);
3200 if (server->server_type == SILC_ROUTER) {
3201 if (!channel->rekey)
3202 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3203 channel->rekey->context = (void *)server;
3204 channel->rekey->channel = channel;
3205 if (channel->rekey->task)
3206 silc_schedule_task_del(server->schedule, channel->rekey->task);
3208 channel->rekey->task =
3209 silc_schedule_task_add(server->schedule, 0,
3210 silc_server_channel_key_rekey,
3211 (void *)channel->rekey,
3212 server->config->channel_rekey_secs, 0,
3214 SILC_TASK_PRI_NORMAL);
3220 silc_channel_key_payload_free(payload);
3225 /* Heartbeat callback. This function is set as argument for the
3226 silc_socket_set_heartbeat function. The library will call this function
3227 at the set time interval. */
3229 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3232 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3234 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3236 /* Send the heartbeat */
3237 silc_server_send_heartbeat(hb->server, sock);
3240 /* Returns assembled of all servers in the given ID list. The packet's
3241 form is dictated by the New ID payload. */
3243 static void silc_server_announce_get_servers(SilcServer server,
3244 SilcServerEntry remote,
3246 SilcBuffer *servers,
3247 unsigned long creation_time)
3249 SilcIDCacheList list;
3250 SilcIDCacheEntry id_cache;
3251 SilcServerEntry entry;
3254 /* Go through all clients in the list */
3255 if (silc_idcache_get_all(id_list->servers, &list)) {
3256 if (silc_idcache_list_first(list, &id_cache)) {
3258 entry = (SilcServerEntry)id_cache->context;
3260 /* Do not announce the one we've sending our announcements and
3261 do not announce ourself. Also check the creation time if it's
3263 if ((entry == remote) || (entry == server->id_entry) ||
3264 (creation_time && entry->data.created < creation_time)) {
3265 if (!silc_idcache_list_next(list, &id_cache))
3270 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3272 *servers = silc_buffer_realloc(*servers,
3274 (*servers)->truelen + idp->len :
3276 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3277 silc_buffer_put(*servers, idp->data, idp->len);
3278 silc_buffer_pull(*servers, idp->len);
3279 silc_buffer_free(idp);
3281 if (!silc_idcache_list_next(list, &id_cache))
3286 silc_idcache_list_free(list);
3291 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3297 p = silc_notify_payload_encode(notify, argc, ap);
3303 /* This function is used by router to announce existing servers to our
3304 primary router when we've connected to it. If `creation_time' is non-zero
3305 then only the servers that has been created after the `creation_time'
3306 will be announced. */
3308 void silc_server_announce_servers(SilcServer server, bool global,
3309 unsigned long creation_time,
3310 SilcSocketConnection remote)
3312 SilcBuffer servers = NULL;
3314 SILC_LOG_DEBUG(("Announcing servers"));
3316 /* Get servers in local list */
3317 silc_server_announce_get_servers(server, remote->user_data,
3318 server->local_list, &servers,
3322 /* Get servers in global list */
3323 silc_server_announce_get_servers(server, remote->user_data,
3324 server->global_list, &servers,
3328 silc_buffer_push(servers, servers->data - servers->head);
3329 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3331 /* Send the packet */
3332 silc_server_packet_send(server, remote,
3333 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3334 servers->data, servers->len, TRUE);
3336 silc_buffer_free(servers);
3340 /* Returns assembled packet of all clients in the given ID list. The
3341 packet's form is dictated by the New ID Payload. */
3343 static void silc_server_announce_get_clients(SilcServer server,
3345 SilcBuffer *clients,
3347 unsigned long creation_time)
3349 SilcIDCacheList list;
3350 SilcIDCacheEntry id_cache;
3351 SilcClientEntry client;
3354 unsigned char mode[4];
3356 /* Go through all clients in the list */
3357 if (silc_idcache_get_all(id_list->clients, &list)) {
3358 if (silc_idcache_list_first(list, &id_cache)) {
3360 client = (SilcClientEntry)id_cache->context;
3362 if (creation_time && client->data.created < creation_time) {
3363 if (!silc_idcache_list_next(list, &id_cache))
3368 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3370 *clients = silc_buffer_realloc(*clients,
3372 (*clients)->truelen + idp->len :
3374 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3375 silc_buffer_put(*clients, idp->data, idp->len);
3376 silc_buffer_pull(*clients, idp->len);
3378 SILC_PUT32_MSB(client->mode, mode);
3379 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3380 2, idp->data, idp->len,
3382 *umodes = silc_buffer_realloc(*umodes,
3384 (*umodes)->truelen + tmp->len :
3386 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3387 silc_buffer_put(*umodes, tmp->data, tmp->len);
3388 silc_buffer_pull(*umodes, tmp->len);
3389 silc_buffer_free(tmp);
3391 silc_buffer_free(idp);
3393 if (!silc_idcache_list_next(list, &id_cache))
3398 silc_idcache_list_free(list);
3402 /* This function is used to announce our existing clients to our router
3403 when we've connected to it. If `creation_time' is non-zero then only
3404 the clients that has been created after the `creation_time' will be
3407 void silc_server_announce_clients(SilcServer server,
3408 unsigned long creation_time,
3409 SilcSocketConnection remote)
3411 SilcBuffer clients = NULL;
3412 SilcBuffer umodes = NULL;
3414 SILC_LOG_DEBUG(("Announcing clients"));
3416 /* Get clients in local list */
3417 silc_server_announce_get_clients(server, server->local_list,
3418 &clients, &umodes, creation_time);
3420 /* As router we announce our global list as well */
3421 if (server->server_type == SILC_ROUTER)
3422 silc_server_announce_get_clients(server, server->global_list,
3423 &clients, &umodes, creation_time);
3426 silc_buffer_push(clients, clients->data - clients->head);
3427 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3429 /* Send the packet */
3430 silc_server_packet_send(server, remote,
3431 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3432 clients->data, clients->len, TRUE);
3434 silc_buffer_free(clients);
3438 silc_buffer_push(umodes, umodes->data - umodes->head);
3439 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3441 /* Send the packet */
3442 silc_server_packet_send(server, remote,
3443 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3444 umodes->data, umodes->len, TRUE);
3446 silc_buffer_free(umodes);
3450 /* Returns channel's topic for announcing it */
3452 void silc_server_announce_get_channel_topic(SilcServer server,
3453 SilcChannelEntry channel,
3458 if (channel->topic) {
3459 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3460 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3461 chidp->data, chidp->len,
3463 strlen(channel->topic));
3464 silc_buffer_free(chidp);
3468 /* Returns assembled packets for channel users of the `channel'. */
3470 void silc_server_announce_get_channel_users(SilcServer server,
3471 SilcChannelEntry channel,
3472 SilcBuffer *channel_users,
3473 SilcBuffer *channel_users_modes)
3475 SilcChannelClientEntry chl;
3476 SilcHashTableList htl;
3477 SilcBuffer chidp, clidp;
3480 unsigned char mode[4];
3482 SILC_LOG_DEBUG(("Start"));
3484 /* Now find all users on the channel */
3485 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3486 silc_hash_table_list(channel->user_list, &htl);
3487 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3488 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3491 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3492 clidp->data, clidp->len,
3493 chidp->data, chidp->len);
3496 silc_buffer_realloc(*channel_users,
3498 (*channel_users)->truelen + len : len));
3499 silc_buffer_pull_tail(*channel_users,
3500 ((*channel_users)->end -
3501 (*channel_users)->data));
3503 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3504 silc_buffer_pull(*channel_users, len);
3505 silc_buffer_free(tmp);
3507 /* CUMODE notify for mode change on the channel */
3508 SILC_PUT32_MSB(chl->mode, mode);
3509 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3510 3, clidp->data, clidp->len,
3512 clidp->data, clidp->len);
3514 *channel_users_modes =
3515 silc_buffer_realloc(*channel_users_modes,
3516 (*channel_users_modes ?
3517 (*channel_users_modes)->truelen + len : len));
3518 silc_buffer_pull_tail(*channel_users_modes,
3519 ((*channel_users_modes)->end -
3520 (*channel_users_modes)->data));
3522 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3523 silc_buffer_pull(*channel_users_modes, len);
3524 silc_buffer_free(tmp);
3526 silc_buffer_free(clidp);
3528 silc_hash_table_list_reset(&htl);
3529 silc_buffer_free(chidp);
3532 /* Returns assembled packets for all channels and users on those channels
3533 from the given ID List. The packets are in the form dictated by the
3534 New Channel and New Channel User payloads. */
3536 void silc_server_announce_get_channels(SilcServer server,
3538 SilcBuffer *channels,
3539 SilcBuffer *channel_users,
3540 SilcBuffer **channel_users_modes,
3541 SilcUInt32 *channel_users_modes_c,
3542 SilcBuffer **channel_topics,
3543 SilcChannelID ***channel_ids,
3544 unsigned long creation_time)
3546 SilcIDCacheList list;
3547 SilcIDCacheEntry id_cache;
3548 SilcChannelEntry channel;
3551 SilcUInt16 name_len;
3553 int i = *channel_users_modes_c;
3556 SILC_LOG_DEBUG(("Start"));
3558 /* Go through all channels in the list */
3559 if (silc_idcache_get_all(id_list->channels, &list)) {
3560 if (silc_idcache_list_first(list, &id_cache)) {
3562 channel = (SilcChannelEntry)id_cache->context;
3564 if (creation_time && channel->created < creation_time)
3569 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3570 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3571 name_len = strlen(channel->channel_name);
3574 len = 4 + name_len + id_len + 4;
3576 silc_buffer_realloc(*channels,
3577 (*channels ? (*channels)->truelen +
3579 silc_buffer_pull_tail(*channels,
3580 ((*channels)->end - (*channels)->data));
3581 silc_buffer_format(*channels,
3582 SILC_STR_UI_SHORT(name_len),
3583 SILC_STR_UI_XNSTRING(channel->channel_name,
3585 SILC_STR_UI_SHORT(id_len),
3586 SILC_STR_UI_XNSTRING(cid, id_len),
3587 SILC_STR_UI_INT(channel->mode),
3589 silc_buffer_pull(*channels, len);
3592 /* Channel user modes */
3593 *channel_users_modes = silc_realloc(*channel_users_modes,
3594 sizeof(**channel_users_modes) *
3596 (*channel_users_modes)[i] = NULL;
3597 *channel_ids = silc_realloc(*channel_ids,
3598 sizeof(**channel_ids) * (i + 1));
3599 (*channel_ids)[i] = NULL;
3600 silc_server_announce_get_channel_users(server, channel,
3602 &(*channel_users_modes)[i]);
3603 (*channel_ids)[i] = channel->id;
3605 /* Channel's topic */
3606 *channel_topics = silc_realloc(*channel_topics,
3607 sizeof(**channel_topics) * (i + 1));
3608 (*channel_topics)[i] = NULL;
3609 silc_server_announce_get_channel_topic(server, channel,
3610 &(*channel_topics)[i]);
3613 if (!silc_idcache_list_next(list, &id_cache))
3617 *channel_users_modes_c += i;
3620 silc_idcache_list_free(list);
3624 /* This function is used to announce our existing channels to our router
3625 when we've connected to it. This also announces the users on the
3626 channels to the router. If the `creation_time' is non-zero only the
3627 channels that was created after the `creation_time' are announced.
3628 Note that the channel users are still announced even if the `creation_time'
3631 void silc_server_announce_channels(SilcServer server,
3632 unsigned long creation_time,
3633 SilcSocketConnection remote)
3635 SilcBuffer channels = NULL, channel_users = NULL;
3636 SilcBuffer *channel_users_modes = NULL;
3637 SilcBuffer *channel_topics = NULL;
3638 SilcUInt32 channel_users_modes_c = 0;
3639 SilcChannelID **channel_ids = NULL;
3641 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3643 /* Get channels and channel users in local list */
3644 silc_server_announce_get_channels(server, server->local_list,
3645 &channels, &channel_users,
3646 &channel_users_modes,
3647 &channel_users_modes_c,
3649 &channel_ids, creation_time);
3651 /* Get channels and channel users in global list */
3652 if (server->server_type != SILC_SERVER)
3653 silc_server_announce_get_channels(server, server->global_list,
3654 &channels, &channel_users,
3655 &channel_users_modes,
3656 &channel_users_modes_c,
3658 &channel_ids, creation_time);
3661 silc_buffer_push(channels, channels->data - channels->head);
3662 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3664 /* Send the packet */
3665 silc_server_packet_send(server, remote,
3666 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3667 channels->data, channels->len,
3670 silc_buffer_free(channels);
3673 if (channel_users) {
3674 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3675 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3676 channel_users->len);
3678 /* Send the packet */
3679 silc_server_packet_send(server, remote,
3680 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3681 channel_users->data, channel_users->len,
3684 silc_buffer_free(channel_users);
3687 if (channel_users_modes) {
3690 for (i = 0; i < channel_users_modes_c; i++) {
3691 if (!channel_users_modes[i])
3693 silc_buffer_push(channel_users_modes[i],
3694 channel_users_modes[i]->data -
3695 channel_users_modes[i]->head);
3696 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3697 channel_users_modes[i]->len);
3698 silc_server_packet_send_dest(server, remote,
3699 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3700 channel_ids[i], SILC_ID_CHANNEL,
3701 channel_users_modes[i]->data,
3702 channel_users_modes[i]->len,
3704 silc_buffer_free(channel_users_modes[i]);
3706 silc_free(channel_users_modes);
3709 if (channel_topics) {
3712 for (i = 0; i < channel_users_modes_c; i++) {
3713 if (!channel_topics[i])
3716 silc_buffer_push(channel_topics[i],
3717 channel_topics[i]->data -
3718 channel_topics[i]->head);
3719 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3720 channel_topics[i]->len);
3721 silc_server_packet_send_dest(server, remote,
3722 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3723 channel_ids[i], SILC_ID_CHANNEL,
3724 channel_topics[i]->data,
3725 channel_topics[i]->len,
3727 silc_buffer_free(channel_topics[i]);
3729 silc_free(channel_topics);
3732 silc_free(channel_ids);
3735 /* Failure timeout callback. If this is called then we will immediately
3736 process the received failure. We always process the failure with timeout
3737 since we do not want to blindly trust to received failure packets.
3738 This won't be called (the timeout is cancelled) if the failure was
3739 bogus (it is bogus if remote does not close the connection after sending
3742 SILC_TASK_CALLBACK(silc_server_failure_callback)
3744 SilcServerFailureContext f = (SilcServerFailureContext)context;
3746 if (f->sock->protocol) {
3747 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3748 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
3754 /* Assembles user list and users mode list from the `channel'. */
3756 void silc_server_get_users_on_channel(SilcServer server,
3757 SilcChannelEntry channel,
3758 SilcBuffer *user_list,
3759 SilcBuffer *mode_list,
3760 SilcUInt32 *user_count)
3762 SilcChannelClientEntry chl;
3763 SilcHashTableList htl;
3764 SilcBuffer client_id_list;
3765 SilcBuffer client_mode_list;
3767 SilcUInt32 list_count = 0, len = 0;
3769 silc_hash_table_list(channel->user_list, &htl);
3770 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3771 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
3772 silc_hash_table_list_reset(&htl);
3774 client_id_list = silc_buffer_alloc(len);
3776 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
3777 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3778 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3780 silc_hash_table_list(channel->user_list, &htl);
3781 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3783 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3784 silc_buffer_put(client_id_list, idp->data, idp->len);
3785 silc_buffer_pull(client_id_list, idp->len);
3786 silc_buffer_free(idp);
3788 /* Client's mode on channel */
3789 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3790 silc_buffer_pull(client_mode_list, 4);
3794 silc_hash_table_list_reset(&htl);
3795 silc_buffer_push(client_id_list,
3796 client_id_list->data - client_id_list->head);
3797 silc_buffer_push(client_mode_list,
3798 client_mode_list->data - client_mode_list->head);
3800 *user_list = client_id_list;
3801 *mode_list = client_mode_list;
3802 *user_count = list_count;
3805 /* Saves users and their modes to the `channel'. */
3807 void silc_server_save_users_on_channel(SilcServer server,
3808 SilcSocketConnection sock,
3809 SilcChannelEntry channel,
3810 SilcClientID *noadd,
3811 SilcBuffer user_list,
3812 SilcBuffer mode_list,
3813 SilcUInt32 user_count)
3818 SilcClientID *client_id;
3819 SilcClientEntry client;
3820 SilcIDCacheEntry cache;
3823 SILC_LOG_DEBUG(("Start"));
3825 for (i = 0; i < user_count; i++) {
3827 SILC_GET16_MSB(idp_len, user_list->data + 2);
3829 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
3830 silc_buffer_pull(user_list, idp_len);
3835 SILC_GET32_MSB(mode, mode_list->data);
3836 silc_buffer_pull(mode_list, 4);
3838 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3839 silc_free(client_id);
3845 /* Check if we have this client cached already. */
3846 client = silc_idlist_find_client_by_id(server->local_list, client_id,
3847 server->server_type, &cache);
3849 client = silc_idlist_find_client_by_id(server->global_list,
3850 client_id, server->server_type,
3855 /* If router did not find such Client ID in its lists then this must
3856 be bogus client or some router in the net is buggy. */
3857 if (server->server_type == SILC_ROUTER) {
3858 silc_free(client_id);
3862 /* We don't have that client anywhere, add it. The client is added
3863 to global list since server didn't have it in the lists so it must be
3865 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
3866 silc_id_dup(client_id, SILC_ID_CLIENT),
3867 sock->user_data, NULL, 0);
3869 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
3870 silc_free(client_id);
3874 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3876 /* Found, if it is from global list we'll assure that we won't
3877 expire it now that the entry is on channel. */
3882 silc_free(client_id);
3884 if (!silc_server_client_on_channel(client, channel, NULL)) {
3885 /* Client was not on the channel, add it. */
3886 SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3887 chl->client = client;
3889 chl->channel = channel;
3890 silc_hash_table_add(channel->user_list, chl->client, chl);
3891 silc_hash_table_add(client->channels, chl->channel, chl);
3892 channel->user_count++;
3897 /* Lookups route to the client indicated by the `id_data'. The connection
3898 object and internal data object is returned. Returns NULL if route
3899 could not be found to the client. If the `client_id' is specified then
3900 it is used and the `id_data' is ignored. */
3902 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3903 unsigned char *id_data,
3905 SilcClientID *client_id,
3906 SilcIDListData *idata)
3909 SilcClientEntry client;
3911 SILC_LOG_DEBUG(("Start"));
3913 /* Decode destination Client ID */
3915 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3917 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3921 id = silc_id_dup(client_id, SILC_ID_CLIENT);
3924 /* If the destination belongs to our server we don't have to route
3925 the packet anywhere but to send it to the local destination. */
3926 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
3930 /* If we are router and the client has router then the client is in
3931 our cell but not directly connected to us. */
3932 if (server->server_type == SILC_ROUTER && client->router) {
3933 /* We are of course in this case the client's router thus the route
3934 to the client is the server who owns the client. So, we will send
3935 the packet to that server. */
3937 *idata = (SilcIDListData)client->router;
3938 return client->router->connection;
3941 /* Seems that client really is directly connected to us */
3943 *idata = (SilcIDListData)client;
3944 return client->connection;
3947 /* Destination belongs to someone not in this server. If we are normal
3948 server our action is to send the packet to our router. */
3949 if (server->server_type != SILC_ROUTER && !server->standalone) {
3952 *idata = (SilcIDListData)server->router;
3953 return server->router->connection;
3956 /* We are router and we will perform route lookup for the destination
3957 and send the packet to fastest route. */
3958 if (server->server_type == SILC_ROUTER && !server->standalone) {
3959 /* Check first that the ID is valid */
3960 client = silc_idlist_find_client_by_id(server->global_list, id,
3963 SilcSocketConnection dst_sock;
3965 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3969 *idata = (SilcIDListData)dst_sock->user_data;
3978 /* Encodes and returns channel list of channels the `client' has joined.
3979 Secret channels are not put to the list. */
3981 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3982 SilcClientEntry client)
3984 SilcBuffer buffer = NULL;
3985 SilcChannelEntry channel;
3986 SilcChannelClientEntry chl;
3987 SilcHashTableList htl;
3990 SilcUInt16 name_len;
3993 silc_hash_table_list(client->channels, &htl);
3994 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3995 channel = chl->channel;
3997 if (channel->mode & SILC_CHANNEL_MODE_SECRET ||
3998 channel->mode & SILC_CHANNEL_MODE_PRIVATE)
4001 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4002 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4003 name_len = strlen(channel->channel_name);
4005 len = 4 + name_len + id_len + 4;
4006 buffer = silc_buffer_realloc(buffer,
4007 (buffer ? (buffer)->truelen + len : len));
4008 silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
4009 silc_buffer_format(buffer,
4010 SILC_STR_UI_SHORT(name_len),
4011 SILC_STR_UI_XNSTRING(channel->channel_name,
4013 SILC_STR_UI_SHORT(id_len),
4014 SILC_STR_UI_XNSTRING(cid, id_len),
4015 SILC_STR_UI_INT(chl->mode), /* Client's mode */
4017 silc_buffer_pull(buffer, len);
4020 silc_hash_table_list_reset(&htl);
4023 silc_buffer_push(buffer, buffer->data - buffer->head);
4028 /* Finds client entry by Client ID and if it is not found then resolves
4029 it using WHOIS command. */
4031 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4032 SilcClientID *client_id,
4035 SilcClientEntry client;
4040 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4043 client = silc_idlist_find_client_by_id(server->global_list,
4044 client_id, TRUE, NULL);
4045 if (!client && server->server_type == SILC_ROUTER)
4049 if (!client && server->standalone)
4052 if (!client || !client->nickname || !client->username) {
4053 SilcBuffer buffer, idp;
4055 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4056 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4057 client->resolve_cmd_ident = ++server->cmd_ident;
4059 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4060 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4061 server->cmd_ident, 1,
4062 3, idp->data, idp->len);
4063 silc_server_packet_send(server, client ? client->router->connection :
4064 server->router->connection,
4065 SILC_PACKET_COMMAND, 0,
4066 buffer->data, buffer->len, FALSE);
4067 silc_buffer_free(idp);
4068 silc_buffer_free(buffer);
4079 /* A timeout callback for the re-key. We will be the initiator of the
4082 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4084 SilcSocketConnection sock = (SilcSocketConnection)context;
4085 SilcIDListData idata = (SilcIDListData)sock->user_data;
4086 SilcServer server = (SilcServer)idata->rekey->context;
4087 SilcProtocol protocol;
4088 SilcServerRekeyInternalContext *proto_ctx;
4090 SILC_LOG_DEBUG(("Start"));
4092 /* Allocate internal protocol context. This is sent as context
4094 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4095 proto_ctx->server = (void *)server;
4096 proto_ctx->sock = sock;
4097 proto_ctx->responder = FALSE;
4098 proto_ctx->pfs = idata->rekey->pfs;
4100 /* Perform rekey protocol. Will call the final callback after the
4101 protocol is over. */
4102 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4103 &protocol, proto_ctx, silc_server_rekey_final);
4104 sock->protocol = protocol;
4106 /* Run the protocol */
4107 silc_protocol_execute(protocol, server->schedule, 0, 0);
4109 /* Re-register re-key timeout */
4110 silc_schedule_task_add(server->schedule, sock->sock,
4111 silc_server_rekey_callback,
4112 context, idata->rekey->timeout, 0,
4113 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4116 /* The final callback for the REKEY protocol. This will actually take the
4117 new key material into use. */
4119 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4121 SilcProtocol protocol = (SilcProtocol)context;
4122 SilcServerRekeyInternalContext *ctx =
4123 (SilcServerRekeyInternalContext *)protocol->context;
4124 SilcServer server = (SilcServer)ctx->server;
4125 SilcSocketConnection sock = ctx->sock;
4127 SILC_LOG_DEBUG(("Start"));
4129 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4130 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4131 /* Error occured during protocol */
4132 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4133 silc_protocol_cancel(protocol, server->schedule);
4134 silc_protocol_free(protocol);
4135 sock->protocol = NULL;
4137 silc_packet_context_free(ctx->packet);
4139 silc_ske_free(ctx->ske);
4144 /* Purge the outgoing data queue to assure that all rekey packets really
4145 go to the network before we quit the protocol. */
4146 silc_server_packet_queue_purge(server, sock);
4149 silc_protocol_free(protocol);
4150 sock->protocol = NULL;
4152 silc_packet_context_free(ctx->packet);
4154 silc_ske_free(ctx->ske);