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);
47 SILC_TASK_CALLBACK(silc_server_get_stats);
49 /* Allocates a new SILC server object. This has to be done before the server
50 can be used. After allocation one must call silc_server_init to initialize
51 the server. The new allocated server object is returned to the new_server
54 int silc_server_alloc(SilcServer *new_server)
58 SILC_LOG_DEBUG(("Allocating new server object"));
60 server = silc_calloc(1, sizeof(*server));
61 server->server_type = SILC_SERVER;
62 server->standalone = TRUE;
63 server->local_list = silc_calloc(1, sizeof(*server->local_list));
64 server->global_list = silc_calloc(1, sizeof(*server->global_list));
65 server->pending_commands = silc_dlist_init();
67 server->sim = silc_dlist_init();
75 /* Free's the SILC server object. This is called at the very end before
78 void silc_server_free(SilcServer server)
84 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
85 silc_dlist_del(server->sim, sim);
88 silc_dlist_uninit(server->sim);
91 silc_server_config_unref(&server->config_ref);
93 silc_rng_free(server->rng);
95 silc_pkcs_free(server->pkcs);
96 if (server->public_key)
97 silc_pkcs_public_key_free(server->public_key);
98 if (server->private_key)
99 silc_pkcs_private_key_free(server->private_key);
100 if (server->pending_commands)
101 silc_dlist_uninit(server->pending_commands);
102 if (server->id_entry)
103 silc_idlist_del_server(server->local_list, server->id_entry);
105 silc_idcache_free(server->local_list->clients);
106 silc_idcache_free(server->local_list->servers);
107 silc_idcache_free(server->local_list->channels);
108 silc_idcache_free(server->global_list->clients);
109 silc_idcache_free(server->global_list->servers);
110 silc_idcache_free(server->global_list->channels);
111 silc_hash_table_free(server->watcher_list);
113 silc_free(server->sockets);
118 /* Opens a listening port.
119 XXX This function will become more general and will support multiple
122 static bool silc_server_listen(SilcServer server, const char *server_ip,
123 SilcUInt16 port, int *sock)
125 *sock = silc_net_create_server(port, server_ip);
127 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
134 /* Adds a secondary listener. */
135 bool silc_server_init_secondary(SilcServer server)
137 int sock=0, sock_list[server->config->param.connections_max];
138 SilcSocketConnection newsocket = NULL;
139 SilcServerConfigServerInfoInterface *interface;
141 for (interface = server->config->server_info->secondary; interface;
142 interface = interface->next, sock++) {
144 if (!silc_server_listen(server,
145 interface->server_ip, interface->port, &sock_list[sock]))
148 /* Set socket to non-blocking mode */
149 silc_net_set_socket_nonblock(sock_list[sock]);
151 /* Add ourselves also to the socket table. The entry allocated above
152 is sent as argument for fast referencing in the future. */
153 silc_socket_alloc(sock_list[sock],
154 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
155 server->sockets[sock_list[sock]] = newsocket;
157 /* Perform name and address lookups to resolve the listenning address
159 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
161 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
163 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
164 newsocket->hostname ? newsocket->hostname :
165 newsocket->ip ? newsocket->ip : ""));
166 server->stat.conn_failures++;
169 if (!newsocket->hostname)
170 newsocket->hostname = strdup(newsocket->ip);
172 newsocket->port = silc_net_get_local_port(sock);
174 newsocket->user_data = (void *)server->id_entry;
175 silc_schedule_task_add(server->schedule, sock_list[sock],
176 silc_server_accept_new_connection,
177 (void *)server, 0, 0,
179 SILC_TASK_PRI_NORMAL);
187 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
192 /* Initializes the entire SILC server. This is called always before running
193 the server. This is called only once at the initialization of the program.
194 This binds the server to its listenning port. After this function returns
195 one should call silc_server_run to start the server. This returns TRUE
196 when everything is ok to run the server. Configuration file must be
197 read and parsed before calling this. */
199 bool silc_server_init(SilcServer server)
203 SilcServerEntry id_entry;
204 SilcIDListPurge purge;
205 SilcSocketConnection newsocket = NULL;
207 SILC_LOG_DEBUG(("Initializing server"));
209 server->starttime = time(NULL);
211 /* Take config object for us */
212 silc_server_config_ref(&server->config_ref, server->config,
215 /* Steal public and private key from the config object */
216 server->public_key = server->config->server_info->public_key;
217 server->private_key = server->config->server_info->private_key;
218 server->config->server_info->public_key = NULL;
219 server->config->server_info->private_key = NULL;
221 /* Register all configured ciphers, PKCS and hash functions. */
222 if (!silc_server_config_register_ciphers(server))
223 silc_cipher_register_default();
224 if (!silc_server_config_register_pkcs(server))
225 silc_pkcs_register_default();
226 if (!silc_server_config_register_hashfuncs(server))
227 silc_hash_register_default();
228 if (!silc_server_config_register_hmacs(server))
229 silc_hmac_register_default();
231 /* Initialize random number generator for the server. */
232 server->rng = silc_rng_alloc();
233 silc_rng_init(server->rng);
234 silc_rng_global_init(server->rng);
236 /* Initialize hash functions for server to use */
237 silc_hash_alloc("md5", &server->md5hash);
238 silc_hash_alloc("sha1", &server->sha1hash);
240 /* Allocate PKCS context for local public and private keys */
241 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
243 silc_pkcs_public_key_set(server->pkcs, server->public_key);
244 silc_pkcs_private_key_set(server->pkcs, server->private_key);
246 /* Initialize the scheduler */
247 server->schedule = silc_schedule_init(server->config->param.connections_max);
248 if (!server->schedule)
251 /* First, register log files configuration for error output */
252 silc_server_config_setlogfiles(server);
254 /* Initialize ID caches */
255 server->local_list->clients =
256 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
257 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
258 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
260 /* These are allocated for normal server as well as these hold some
261 global information that the server has fetched from its router. For
262 router these are used as they are supposed to be used on router. */
263 server->global_list->clients =
264 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
265 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
266 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
268 /* Init watcher list */
269 server->watcher_list =
270 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
271 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
273 if (!server->watcher_list)
276 /* Create a listening server */
277 if (!silc_server_listen(server,
278 server->config->server_info->primary == NULL ? NULL :
279 server->config->server_info->primary->server_ip,
280 server->config->server_info->primary == NULL ? 0 :
281 server->config->server_info->primary->port,
285 /* Set socket to non-blocking mode */
286 silc_net_set_socket_nonblock(sock);
289 /* Allocate the entire socket list that is used in server. Eventually
290 all connections will have entry in this table (it is a table of
291 pointers to the actual object that is allocated individually
293 server->sockets = silc_calloc(server->config->param.connections_max,
294 sizeof(*server->sockets));
295 if (!server->sockets)
298 /* Add ourselves also to the socket table. The entry allocated above
299 is sent as argument for fast referencing in the future. */
300 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
301 server->sockets[sock] = newsocket;
303 /* Perform name and address lookups to resolve the listenning address
305 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
307 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
309 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
310 newsocket->hostname ? newsocket->hostname :
311 newsocket->ip ? newsocket->ip : ""));
312 server->stat.conn_failures++;
315 if (!newsocket->hostname)
316 newsocket->hostname = strdup(newsocket->ip);
318 newsocket->port = silc_net_get_local_port(sock);
320 /* Create a Server ID for the server. */
321 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
326 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
327 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
328 server->id_type = SILC_ID_SERVER;
329 server->server_name = server->config->server_info->server_name;
330 server->config->server_info->server_name = NULL;
332 /* Add ourselves to the server list. We don't have a router yet
333 beacuse we haven't established a route yet. It will be done later.
334 For now, NULL is sent as router. This allocates new entry to
337 silc_idlist_add_server(server->local_list, strdup(server->server_name),
338 server->server_type, server->id, NULL, NULL);
340 SILC_LOG_ERROR(("Could not add ourselves to cache"));
343 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
345 /* Put the allocated socket pointer also to the entry allocated above
346 for fast back-referencing to the socket list. */
347 newsocket->user_data = (void *)id_entry;
348 id_entry->connection = (void *)newsocket;
349 server->id_entry = id_entry;
351 /* Register protocols */
352 silc_server_protocols_register();
354 /* Add the first task to the scheduler. This is task that is executed by
355 timeout. It expires as soon as the caller calls silc_server_run. This
356 task performs authentication protocol and key exchange with our
358 silc_schedule_task_add(server->schedule, 0,
359 silc_server_connect_to_router,
360 (void *)server, 0, 1,
362 SILC_TASK_PRI_NORMAL);
364 /* Add listener task to the scheduler. This task receives new connections
365 to the server. This task remains on the queue until the end of the
367 silc_schedule_task_add(server->schedule, sock,
368 silc_server_accept_new_connection,
369 (void *)server, 0, 0,
371 SILC_TASK_PRI_NORMAL);
373 if (silc_server_init_secondary(server) == FALSE)
376 server->listenning = TRUE;
378 /* If server connections has been configured then we must be router as
379 normal server cannot have server connections, only router connections. */
380 if (server->config->servers) {
381 SilcServerConfigServer *ptr = server->config->servers;
383 server->server_type = SILC_ROUTER;
385 if (ptr->backup_router) {
386 server->server_type = SILC_BACKUP_ROUTER;
387 server->backup_router = TRUE;
388 server->id_entry->server_type = SILC_BACKUP_ROUTER;
395 /* Register the ID Cache purge task. This periodically purges the ID cache
396 and removes the expired cache entries. */
398 /* Clients local list */
399 purge = silc_calloc(1, sizeof(*purge));
400 purge->cache = server->local_list->clients;
401 purge->schedule = server->schedule;
402 purge->timeout = 600;
403 silc_schedule_task_add(purge->schedule, 0,
405 (void *)purge, purge->timeout, 0,
406 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
408 /* Clients global list */
409 purge = silc_calloc(1, sizeof(*purge));
410 purge->cache = server->global_list->clients;
411 purge->schedule = server->schedule;
412 purge->timeout = 300;
413 silc_schedule_task_add(purge->schedule, 0,
415 (void *)purge, purge->timeout, 0,
416 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
418 /* If we are normal server we'll retrieve network statisticial information
419 once in a while from the router. */
420 if (server->server_type == SILC_SERVER)
421 silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
422 server, 10, 0, SILC_TASK_TIMEOUT,
425 SILC_LOG_DEBUG(("Server initialized"));
427 /* We are done here, return succesfully */
431 silc_server_config_unref(&server->config_ref);
432 silc_net_close_server(sock);
436 /* This function basically reads the config file again and switches the config
437 object pointed by the server object. After that, we have to fix various
438 things such as the server_name and the listening ports.
439 Keep in mind that we no longer have the root privileges at this point. */
441 bool silc_server_rehash(SilcServer server)
443 SilcServerConfig newconfig;
445 SILC_LOG_INFO(("Rehashing server"));
447 /* Reset the logging system */
448 silc_log_quick = TRUE;
449 silc_log_flush_all();
451 /* Start the main rehash phase (read again the config file) */
452 newconfig = silc_server_config_alloc(server->config_file);
454 SILC_LOG_ERROR(("Rehash FAILED."));
458 /* Reinit scheduler if necessary */
459 if (newconfig->param.connections_max > server->config->param.connections_max)
460 if (!silc_schedule_reinit(server->schedule,
461 newconfig->param.connections_max))
464 /* Fix the server_name field */
465 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
466 silc_free(server->server_name);
467 server->server_name = newconfig->server_info->server_name;
468 newconfig->server_info->server_name = NULL;
470 /* Update the idcache list with a fresh pointer */
471 silc_free(server->id_entry->server_name);
472 server->id_entry->server_name = strdup(server->server_name);
473 if (!silc_idcache_del_by_context(server->local_list->servers,
476 if (!silc_idcache_add(server->local_list->servers,
477 server->id_entry->server_name,
478 server->id_entry->id, server->id_entry, 0, NULL))
483 silc_server_config_setlogfiles(server);
485 /* Change new key pair if necessary */
486 if (newconfig->server_info->public_key &&
487 !silc_pkcs_public_key_compare(server->public_key,
488 newconfig->server_info->public_key)) {
489 silc_pkcs_public_key_free(server->public_key);
490 silc_pkcs_private_key_free(server->private_key);
491 server->public_key = newconfig->server_info->public_key;
492 server->private_key = newconfig->server_info->private_key;
493 newconfig->server_info->public_key = NULL;
494 newconfig->server_info->private_key = NULL;
496 /* Allocate PKCS context for local public and private keys */
497 silc_pkcs_free(server->pkcs);
498 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
500 silc_pkcs_public_key_set(server->pkcs, server->public_key);
501 silc_pkcs_private_key_set(server->pkcs, server->private_key);
504 /* Go through all configured routers after rehash */
505 silc_schedule_task_add(server->schedule, 0,
506 silc_server_connect_to_router,
507 (void *)server, 0, 1,
509 SILC_TASK_PRI_NORMAL);
511 /* Check whether our router status has changed */
512 if (newconfig->servers) {
513 SilcServerConfigServer *ptr = newconfig->servers;
515 server->server_type = SILC_ROUTER;
517 if (ptr->backup_router) {
518 server->server_type = SILC_BACKUP_ROUTER;
519 server->backup_router = TRUE;
520 server->id_entry->server_type = SILC_BACKUP_ROUTER;
527 /* Our old config is gone now. We'll unreference our reference made in
528 silc_server_init and then destroy it since we are destroying it
529 underneath the application (layer which called silc_server_init). */
530 silc_server_config_unref(&server->config_ref);
531 silc_server_config_destroy(server->config);
533 /* Take new config context */
534 server->config = newconfig;
535 silc_server_config_ref(&server->config_ref, server->config, server->config);
537 SILC_LOG_DEBUG(("Server rehashed"));
542 /* The heart of the server. This runs the scheduler thus runs the server.
543 When this returns the server has been stopped and the program will
546 void silc_server_run(SilcServer server)
548 SILC_LOG_INFO(("SILC Server started"));
550 /* Start the scheduler, the heart of the SILC server. When this returns
551 the program will be terminated. */
552 silc_schedule(server->schedule);
555 /* Stops the SILC server. This function is used to shutdown the server.
556 This is usually called after the scheduler has returned. After stopping
557 the server one should call silc_server_free. */
559 void silc_server_stop(SilcServer server)
561 SILC_LOG_DEBUG(("Stopping server"));
563 if (server->schedule) {
564 silc_schedule_stop(server->schedule);
565 silc_schedule_uninit(server->schedule);
566 server->schedule = NULL;
569 silc_server_protocols_unregister();
571 SILC_LOG_DEBUG(("Server stopped"));
574 /* Function that is called when the network connection to a router has
575 been established. This will continue with the key exchange protocol
576 with the remote router. */
578 void silc_server_start_key_exchange(SilcServer server,
579 SilcServerConnection sconn,
582 SilcSocketConnection newsocket;
583 SilcProtocol protocol;
584 SilcServerKEInternalContext *proto_ctx;
585 SilcServerConfigRouter *conn =
586 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
589 /* Cancel any possible retry timeouts */
590 silc_schedule_task_del_by_callback(server->schedule,
591 silc_server_connect_to_router_retry);
593 /* Set socket options */
594 silc_net_set_socket_nonblock(sock);
595 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
597 /* Create socket connection for the connection. Even though we
598 know that we are connecting to a router we will mark the socket
599 to be unknown connection until we have executed authentication
601 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
602 server->sockets[sock] = newsocket;
603 newsocket->hostname = strdup(sconn->remote_host);
604 newsocket->ip = strdup(sconn->remote_host);
605 newsocket->port = sconn->remote_port;
606 sconn->sock = newsocket;
608 /* Allocate internal protocol context. This is sent as context
610 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
611 proto_ctx->server = (void *)server;
612 proto_ctx->context = (void *)sconn;
613 proto_ctx->sock = newsocket;
614 proto_ctx->rng = server->rng;
615 proto_ctx->responder = FALSE;
617 /* Set Key Exchange flags from configuration, but fall back to global
619 SILC_GET_SKE_FLAGS(conn, proto_ctx);
620 if (server->config->param.key_exchange_pfs)
621 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
623 /* Perform key exchange protocol. silc_server_connect_to_router_second
624 will be called after the protocol is finished. */
625 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
626 &protocol, proto_ctx,
627 silc_server_connect_to_router_second);
628 newsocket->protocol = protocol;
630 /* Register a timeout task that will be executed if the protocol
631 is not executed within set limit. */
632 proto_ctx->timeout_task =
633 silc_schedule_task_add(server->schedule, sock,
634 silc_server_timeout_remote,
635 server, server->config->key_exchange_timeout, 0,
639 /* Register the connection for network input and output. This sets
640 that scheduler will listen for incoming packets for this connection
641 and sets that outgoing packets may be sent to this connection as
642 well. However, this doesn't set the scheduler for outgoing traffic,
643 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
644 later when outgoing data is available. */
645 context = (void *)server;
646 SILC_REGISTER_CONNECTION_FOR_IO(sock);
648 /* Run the protocol */
649 silc_protocol_execute(protocol, server->schedule, 0, 0);
652 /* Timeout callback that will be called to retry connecting to remote
653 router. This is used by both normal and router server. This will wait
654 before retrying the connecting. The timeout is generated by exponential
655 backoff algorithm. */
657 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
659 SilcServerConnection sconn = (SilcServerConnection)context;
660 SilcServer server = sconn->server;
661 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
662 SilcServerConfigConnParams *param =
663 (conn->param ? conn->param : &server->config->param);
665 SILC_LOG_INFO(("Retrying connecting to a router"));
667 /* Calculate next timeout */
668 if (sconn->retry_count >= 1) {
669 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
670 if (sconn->retry_timeout > param->reconnect_interval_max)
671 sconn->retry_timeout = param->reconnect_interval_max;
673 sconn->retry_timeout = param->reconnect_interval;
675 sconn->retry_count++;
676 sconn->retry_timeout = sconn->retry_timeout +
677 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
679 /* If we've reached max retry count, give up. */
680 if ((sconn->retry_count > param->reconnect_count) &&
681 !param->reconnect_keep_trying) {
682 SILC_LOG_ERROR(("Could not connect to router, giving up"));
683 silc_server_config_unref(&sconn->conn);
684 silc_free(sconn->remote_host);
685 silc_free(sconn->backup_replace_ip);
690 /* We will lookup a fresh pointer later */
691 silc_server_config_unref(&sconn->conn);
693 /* Wait one before retrying */
694 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
695 context, sconn->retry_timeout, 0,
696 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
699 /* Generic routine to use connect to a router. */
701 SILC_TASK_CALLBACK(silc_server_connect_router)
703 SilcServerConnection sconn = (SilcServerConnection)context;
704 SilcServer server = sconn->server;
705 SilcServerConfigRouter *rconn;
708 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
709 (sconn->backup ? "backup router" : "router"),
710 sconn->remote_host, sconn->remote_port));
712 server->router_connect = time(NULL);
713 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
716 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
717 (sconn->backup ? "backup router" : "router"),
718 sconn->remote_host, sconn->remote_port));
719 silc_free(sconn->remote_host);
720 silc_free(sconn->backup_replace_ip);
724 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
726 /* Connect to remote host */
727 sock = silc_net_create_connection(
728 (!server->config->server_info->primary ? NULL :
729 server->config->server_info->primary->server_ip),
730 sconn->remote_port, sconn->remote_host);
732 SILC_LOG_ERROR(("Could not connect to router %s:%d",
733 sconn->remote_host, sconn->remote_port));
734 if (!sconn->no_reconnect)
735 silc_schedule_task_add(server->schedule, 0,
736 silc_server_connect_to_router_retry,
737 context, 0, 1, SILC_TASK_TIMEOUT,
738 SILC_TASK_PRI_NORMAL);
740 silc_server_config_unref(&sconn->conn);
744 /* Continue with key exchange protocol */
745 silc_server_start_key_exchange(server, sconn, sock);
748 /* This function connects to our primary router or if we are a router this
749 establishes all our primary routes. This is called at the start of the
750 server to do authentication and key exchange with our router - called
753 SILC_TASK_CALLBACK(silc_server_connect_to_router)
755 SilcServer server = (SilcServer)context;
756 SilcServerConnection sconn;
757 SilcServerConfigRouter *ptr;
759 SILC_LOG_DEBUG(("Connecting to router(s)"));
761 if (server->server_type == SILC_SERVER) {
762 SILC_LOG_DEBUG(("We are normal server"));
763 } else if (server->server_type == SILC_ROUTER) {
764 SILC_LOG_DEBUG(("We are router"));
766 SILC_LOG_DEBUG(("We are backup router/normal server"));
769 if (!server->config->routers) {
770 /* There wasn't a configured router, we will continue but we don't
771 have a connection to outside world. We will be standalone server. */
772 SILC_LOG_DEBUG(("No router(s), server will be standalone"));
773 server->standalone = TRUE;
777 /* Cancel any possible retry timeouts */
778 silc_schedule_task_del_by_callback(server->schedule,
779 silc_server_connect_router);
780 silc_schedule_task_del_by_callback(server->schedule,
781 silc_server_connect_to_router_retry);
783 /* Create the connections to all our routes */
784 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
786 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
787 ptr->backup_router ? "Backup router" : "Router",
788 ptr->initiator ? "Initiator" : "Responder",
789 ptr->host, ptr->port));
791 if (ptr->initiator) {
792 /* Check whether we are connected to this host already */
793 if (silc_server_num_sockets_by_remote(server,
794 silc_net_is_ip(ptr->host) ?
796 silc_net_is_ip(ptr->host) ?
797 NULL : ptr->host, ptr->port,
798 SILC_SOCKET_TYPE_ROUTER)) {
799 SILC_LOG_DEBUG(("We are already connected to this router"));
803 /* Allocate connection object for hold connection specific stuff. */
804 sconn = silc_calloc(1, sizeof(*sconn));
805 sconn->server = server;
806 sconn->remote_host = strdup(ptr->host);
807 sconn->remote_port = ptr->port;
808 sconn->backup = ptr->backup_router;
810 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
811 sconn->backup_replace_port = ptr->backup_replace_port;
814 if (!server->router_conn && !sconn->backup)
815 server->router_conn = sconn;
817 silc_schedule_task_add(server->schedule, 0,
818 silc_server_connect_router,
819 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
820 SILC_TASK_PRI_NORMAL);
825 /* Second part of connecting to router(s). Key exchange protocol has been
826 executed and now we will execute authentication protocol. */
828 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
830 SilcProtocol protocol = (SilcProtocol)context;
831 SilcServerKEInternalContext *ctx =
832 (SilcServerKEInternalContext *)protocol->context;
833 SilcServer server = (SilcServer)ctx->server;
834 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
835 SilcSocketConnection sock = ctx->sock;
836 SilcServerConnAuthInternalContext *proto_ctx;
837 SilcServerConfigRouter *conn = NULL;
839 SILC_LOG_DEBUG(("Start"));
841 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
842 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
843 /* Error occured during protocol */
844 silc_protocol_free(protocol);
845 sock->protocol = NULL;
846 silc_ske_free_key_material(ctx->keymat);
848 silc_packet_context_free(ctx->packet);
850 silc_ske_free(ctx->ske);
851 silc_free(ctx->dest_id);
853 silc_server_config_unref(&sconn->conn);
854 silc_free(sconn->remote_host);
855 silc_free(sconn->backup_replace_ip);
857 silc_schedule_task_del_by_callback(server->schedule,
858 silc_server_failure_callback);
859 silc_server_disconnect_remote(server, sock,
860 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
864 /* We now have the key material as the result of the key exchange
865 protocol. Take the key material into use. Free the raw key material
866 as soon as we've set them into use. */
867 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
868 ctx->sock, ctx->keymat,
869 ctx->ske->prop->cipher,
870 ctx->ske->prop->pkcs,
871 ctx->ske->prop->hash,
872 ctx->ske->prop->hmac,
873 ctx->ske->prop->group,
875 silc_protocol_free(protocol);
876 sock->protocol = NULL;
877 silc_ske_free_key_material(ctx->keymat);
879 silc_packet_context_free(ctx->packet);
881 silc_ske_free(ctx->ske);
882 silc_free(ctx->dest_id);
884 silc_server_config_unref(&sconn->conn);
885 silc_free(sconn->remote_host);
886 silc_free(sconn->backup_replace_ip);
888 silc_schedule_task_del_by_callback(server->schedule,
889 silc_server_failure_callback);
890 silc_server_disconnect_remote(server, sock,
891 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
894 silc_ske_free_key_material(ctx->keymat);
896 /* Allocate internal context for the authentication protocol. This
897 is sent as context for the protocol. */
898 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
899 proto_ctx->server = (void *)server;
900 proto_ctx->context = (void *)sconn;
901 proto_ctx->sock = sock;
902 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
903 proto_ctx->dest_id_type = ctx->dest_id_type;
904 proto_ctx->dest_id = ctx->dest_id;
906 /* Resolve the authentication method used in this connection. Check if
907 we find a match from user configured connections */
908 if (!sconn->conn.ref_ptr)
909 conn = silc_server_config_find_router_conn(server, sock->hostname,
912 conn = sconn->conn.ref_ptr;
915 /* Match found. Use the configured authentication method. Take only
916 the passphrase, since for public key auth we automatically use
917 our local key pair. */
918 if (conn->passphrase) {
919 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
920 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
922 proto_ctx->auth_data = strdup(conn->passphrase);
923 proto_ctx->auth_data_len = strlen(conn->passphrase);
924 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
926 } else if (conn->publickeys) {
927 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
929 proto_ctx->auth_meth = SILC_AUTH_NONE;
932 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
933 sock->hostname, sock->ip, sock->port));
934 silc_protocol_free(protocol);
935 sock->protocol = NULL;
937 silc_packet_context_free(ctx->packet);
939 silc_ske_free(ctx->ske);
940 silc_free(ctx->dest_id);
942 silc_server_config_unref(&sconn->conn);
943 silc_free(sconn->remote_host);
944 silc_free(sconn->backup_replace_ip);
946 silc_schedule_task_del_by_callback(server->schedule,
947 silc_server_failure_callback);
948 silc_server_disconnect_remote(server, sock,
949 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
953 /* Free old protocol as it is finished now */
954 silc_protocol_free(protocol);
956 silc_packet_context_free(ctx->packet);
958 sock->protocol = NULL;
960 /* Allocate the authentication protocol. This is allocated here
961 but we won't start it yet. We will be receiving party of this
962 protocol thus we will wait that connecting party will make
964 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
965 &sock->protocol, proto_ctx,
966 silc_server_connect_to_router_final);
968 /* Register timeout task. If the protocol is not executed inside
969 this timelimit the connection will be terminated. */
970 proto_ctx->timeout_task =
971 silc_schedule_task_add(server->schedule, sock->sock,
972 silc_server_timeout_remote,
974 server->config->conn_auth_timeout, 0,
978 /* Run the protocol */
979 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
982 /* Finalizes the connection to router. Registers a server task to the
983 queue so that we can accept new connections. */
985 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
987 SilcProtocol protocol = (SilcProtocol)context;
988 SilcServerConnAuthInternalContext *ctx =
989 (SilcServerConnAuthInternalContext *)protocol->context;
990 SilcServer server = (SilcServer)ctx->server;
991 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
992 SilcSocketConnection sock = ctx->sock;
993 SilcServerEntry id_entry;
995 SilcServerHBContext hb_context;
996 unsigned char *id_string;
998 SilcIDListData idata;
999 SilcServerConfigRouter *conn = NULL;
1000 SilcServerConfigConnParams *param = NULL;
1002 SILC_LOG_DEBUG(("Start"));
1004 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1005 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1006 /* Error occured during protocol */
1007 silc_free(ctx->dest_id);
1008 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1013 /* Add a task to the queue. This task receives new connections to the
1014 server. This task remains on the queue until the end of the program. */
1015 if (!server->listenning && !sconn->backup) {
1016 silc_schedule_task_add(server->schedule, server->sock,
1017 silc_server_accept_new_connection,
1018 (void *)server, 0, 0,
1020 SILC_TASK_PRI_NORMAL);
1021 server->listenning = TRUE;
1024 /* Send NEW_SERVER packet to the router. We will become registered
1025 to the SILC network after sending this packet. */
1026 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1027 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1028 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1029 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1030 silc_buffer_format(packet,
1031 SILC_STR_UI_SHORT(id_len),
1032 SILC_STR_UI_XNSTRING(id_string, id_len),
1033 SILC_STR_UI_SHORT(strlen(server->server_name)),
1034 SILC_STR_UI_XNSTRING(server->server_name,
1035 strlen(server->server_name)),
1038 /* Send the packet */
1039 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1040 packet->data, packet->len, TRUE);
1041 silc_buffer_free(packet);
1042 silc_free(id_string);
1044 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1046 /* Check that we do not have this ID already */
1047 id_entry = silc_idlist_find_server_by_id(server->local_list,
1048 ctx->dest_id, TRUE, NULL);
1050 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1052 id_entry = silc_idlist_find_server_by_id(server->global_list,
1053 ctx->dest_id, TRUE, NULL);
1055 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1058 SILC_LOG_DEBUG(("New server id(%s)",
1059 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1061 /* Add the connected router to global server list */
1062 id_entry = silc_idlist_add_server(server->global_list,
1063 strdup(sock->hostname),
1064 SILC_ROUTER, ctx->dest_id, NULL, sock);
1066 silc_free(ctx->dest_id);
1067 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1068 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1073 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1074 silc_free(sock->user_data);
1075 sock->user_data = (void *)id_entry;
1076 sock->type = SILC_SOCKET_TYPE_ROUTER;
1077 idata = (SilcIDListData)sock->user_data;
1078 idata->status |= SILC_IDLIST_STATUS_REGISTERED;
1080 conn = sconn->conn.ref_ptr;
1081 param = &server->config->param;
1082 if (conn && conn->param)
1083 param = conn->param;
1085 /* Perform keepalive. The `hb_context' will be freed automatically
1086 when finally calling the silc_socket_free function. */
1087 hb_context = silc_calloc(1, sizeof(*hb_context));
1088 hb_context->server = server;
1089 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1090 silc_server_perform_heartbeat,
1093 /* Register re-key timeout */
1094 idata->rekey->timeout = param->key_exchange_rekey;
1095 idata->rekey->context = (void *)server;
1096 silc_schedule_task_add(server->schedule, sock->sock,
1097 silc_server_rekey_callback,
1098 (void *)sock, idata->rekey->timeout, 0,
1099 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1101 if (!sconn->backup) {
1102 /* Mark this router our primary router if we're still standalone */
1103 if (server->standalone) {
1104 server->id_entry->router = id_entry;
1105 server->router = id_entry;
1106 server->standalone = FALSE;
1108 /* If we are router then announce our possible servers. */
1109 if (server->server_type == SILC_ROUTER)
1110 silc_server_announce_servers(server, FALSE, 0,
1111 server->router->connection);
1113 /* Announce our clients and channels to the router */
1114 silc_server_announce_clients(server, 0, server->router->connection);
1115 silc_server_announce_channels(server, 0, server->router->connection);
1117 #ifdef BACKUP_SINGLE_ROUTER
1118 /* If we are backup router then this primary router is whom we are
1120 if (server->server_type == SILC_BACKUP_ROUTER)
1121 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1122 #endif /* BACKUP_SINGLE_ROUTER */
1125 /* Add this server to be our backup router */
1126 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1127 sconn->backup_replace_port, FALSE);
1130 sock->protocol = NULL;
1132 /* Call the completion callback to indicate that we've connected to
1134 if (sconn->callback)
1135 (*sconn->callback)(server, id_entry, sconn->callback_context);
1138 /* Free the temporary connection data context */
1140 silc_server_config_unref(&sconn->conn);
1141 silc_free(sconn->remote_host);
1142 silc_free(sconn->backup_replace_ip);
1145 if (sconn == server->router_conn)
1146 server->router_conn = NULL;
1148 /* Free the protocol object */
1149 if (sock->protocol == protocol)
1150 sock->protocol = NULL;
1151 silc_protocol_free(protocol);
1153 silc_packet_context_free(ctx->packet);
1155 silc_ske_free(ctx->ske);
1156 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1157 silc_free(ctx->auth_data);
1161 /* Host lookup callback that is called after the incoming connection's
1162 IP and FQDN lookup is performed. This will actually check the acceptance
1163 of the incoming connection and will register the key exchange protocol
1164 for this connection. */
1167 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1170 SilcServerKEInternalContext *proto_ctx =
1171 (SilcServerKEInternalContext *)context;
1172 SilcServer server = (SilcServer)proto_ctx->server;
1173 SilcServerConfigClient *cconfig = NULL;
1174 SilcServerConfigServer *sconfig = NULL;
1175 SilcServerConfigRouter *rconfig = NULL;
1176 SilcServerConfigDeny *deny;
1179 context = (void *)server;
1181 SILC_LOG_DEBUG(("Start"));
1183 /* Check whether we could resolve both IP and FQDN. */
1184 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1185 server->config->require_reverse_lookup)) {
1186 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1187 sock->hostname ? sock->hostname :
1188 sock->ip ? sock->ip : ""));
1189 server->stat.conn_failures++;
1190 silc_server_disconnect_remote(server, sock,
1191 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1192 "Unknown host or IP");
1193 silc_free(proto_ctx);
1197 /* Register the connection for network input and output. This sets
1198 that scheduler will listen for incoming packets for this connection
1199 and sets that outgoing packets may be sent to this connection as well.
1200 However, this doesn't set the scheduler for outgoing traffic, it
1201 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1202 later when outgoing data is available. */
1203 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1205 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1208 /* Listenning port */
1209 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1211 /* Check whether this connection is denied to connect to us. */
1212 deny = silc_server_config_find_denied(server, sock->ip);
1214 deny = silc_server_config_find_denied(server, sock->hostname);
1216 /* The connection is denied */
1217 SILC_LOG_INFO(("Connection %s (%s) is denied",
1218 sock->hostname, sock->ip));
1219 silc_server_disconnect_remote(server, sock,
1220 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1222 server->stat.conn_failures++;
1223 silc_free(proto_ctx);
1227 /* Check whether we have configured this sort of connection at all. We
1228 have to check all configurations since we don't know what type of
1229 connection this is. */
1230 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1231 cconfig = silc_server_config_find_client(server, sock->hostname);
1232 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1233 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1234 if (server->server_type == SILC_ROUTER) {
1235 if (!(rconfig = silc_server_config_find_router_conn(server,
1236 sock->ip, sock->port)))
1237 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1240 if (!cconfig && !sconfig && !rconfig) {
1241 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1243 silc_server_disconnect_remote(server, sock,
1244 SILC_STATUS_ERR_BANNED_FROM_SERVER);
1245 server->stat.conn_failures++;
1246 silc_free(proto_ctx);
1250 /* The connection is allowed */
1252 /* Set internal context for key exchange protocol. This is
1253 sent as context for the protocol. */
1254 proto_ctx->sock = sock;
1255 proto_ctx->rng = server->rng;
1256 proto_ctx->responder = TRUE;
1257 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1258 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1259 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1261 /* Take flags for key exchange. Since we do not know what type of connection
1262 this is, we go through all found configurations and use the global ones
1263 as well. This will result always into strictest key exchange flags. */
1264 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1265 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1266 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1267 if (server->config->param.key_exchange_pfs)
1268 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1270 /* Prepare the connection for key exchange protocol. We allocate the
1271 protocol but will not start it yet. The connector will be the
1272 initiator of the protocol thus we will wait for initiation from
1273 there before we start the protocol. */
1274 server->stat.auth_attempts++;
1275 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1276 &sock->protocol, proto_ctx,
1277 silc_server_accept_new_connection_second);
1279 /* Register a timeout task that will be executed if the connector
1280 will not start the key exchange protocol within specified timeout
1281 and the connection will be closed. */
1282 proto_ctx->timeout_task =
1283 silc_schedule_task_add(server->schedule, sock->sock,
1284 silc_server_timeout_remote,
1286 server->config->key_exchange_timeout, 0,
1291 /* Accepts new connections to the server. Accepting new connections are
1292 done in three parts to make it async. */
1294 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1296 SilcServer server = (SilcServer)context;
1297 SilcSocketConnection newsocket;
1298 SilcServerKEInternalContext *proto_ctx;
1301 SILC_LOG_DEBUG(("Accepting new connection"));
1303 server->stat.conn_attempts++;
1305 sock = silc_net_accept_connection(fd);
1307 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1308 server->stat.conn_failures++;
1312 /* Check for maximum allowed connections */
1313 if (sock > server->config->param.connections_max) {
1314 SILC_LOG_ERROR(("Refusing connection, server is full"));
1315 server->stat.conn_failures++;
1316 silc_net_close_connection(sock);
1320 /* Set socket options */
1321 silc_net_set_socket_nonblock(sock);
1322 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1324 /* We don't create a ID yet, since we don't know what type of connection
1325 this is yet. But, we do add the connection to the socket table. */
1326 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1327 server->sockets[sock] = newsocket;
1329 /* Perform asynchronous host lookup. This will lookup the IP and the
1330 FQDN of the remote connection. After the lookup is done the connection
1331 is accepted further. */
1332 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1333 proto_ctx->server = server;
1334 proto_ctx->context = (void *)fd;
1335 silc_socket_host_lookup(newsocket, TRUE,
1336 silc_server_accept_new_connection_lookup,
1337 (void *)proto_ctx, server->schedule);
1340 /* Second part of accepting new connection. Key exchange protocol has been
1341 performed and now it is time to do little connection authentication
1342 protocol to figure out whether this connection is client or server
1343 and whether it has right to access this server (especially server
1344 connections needs to be authenticated). */
1346 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1348 SilcProtocol protocol = (SilcProtocol)context;
1349 SilcServerKEInternalContext *ctx =
1350 (SilcServerKEInternalContext *)protocol->context;
1351 SilcServer server = (SilcServer)ctx->server;
1352 SilcSocketConnection sock = ctx->sock;
1353 SilcServerConnAuthInternalContext *proto_ctx;
1355 SILC_LOG_DEBUG(("Start"));
1357 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1358 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1359 /* Error occured during protocol */
1360 silc_protocol_free(protocol);
1361 sock->protocol = NULL;
1362 silc_ske_free_key_material(ctx->keymat);
1364 silc_packet_context_free(ctx->packet);
1366 silc_ske_free(ctx->ske);
1367 silc_free(ctx->dest_id);
1368 silc_server_config_unref(&ctx->cconfig);
1369 silc_server_config_unref(&ctx->sconfig);
1370 silc_server_config_unref(&ctx->rconfig);
1372 silc_schedule_task_del_by_callback(server->schedule,
1373 silc_server_failure_callback);
1374 silc_server_disconnect_remote(server, sock,
1375 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1377 server->stat.auth_failures++;
1381 /* We now have the key material as the result of the key exchange
1382 protocol. Take the key material into use. Free the raw key material
1383 as soon as we've set them into use. */
1384 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1385 ctx->sock, ctx->keymat,
1386 ctx->ske->prop->cipher,
1387 ctx->ske->prop->pkcs,
1388 ctx->ske->prop->hash,
1389 ctx->ske->prop->hmac,
1390 ctx->ske->prop->group,
1392 silc_protocol_free(protocol);
1393 sock->protocol = NULL;
1394 silc_ske_free_key_material(ctx->keymat);
1396 silc_packet_context_free(ctx->packet);
1398 silc_ske_free(ctx->ske);
1399 silc_free(ctx->dest_id);
1400 silc_server_config_unref(&ctx->cconfig);
1401 silc_server_config_unref(&ctx->sconfig);
1402 silc_server_config_unref(&ctx->rconfig);
1404 silc_schedule_task_del_by_callback(server->schedule,
1405 silc_server_failure_callback);
1406 silc_server_disconnect_remote(server, sock,
1407 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1408 server->stat.auth_failures++;
1411 silc_ske_free_key_material(ctx->keymat);
1413 /* Allocate internal context for the authentication protocol. This
1414 is sent as context for the protocol. */
1415 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1416 proto_ctx->server = (void *)server;
1417 proto_ctx->sock = sock;
1418 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1419 proto_ctx->responder = TRUE;
1420 proto_ctx->dest_id_type = ctx->dest_id_type;
1421 proto_ctx->dest_id = ctx->dest_id;
1422 proto_ctx->cconfig = ctx->cconfig;
1423 proto_ctx->sconfig = ctx->sconfig;
1424 proto_ctx->rconfig = ctx->rconfig;
1426 /* Free old protocol as it is finished now */
1427 silc_protocol_free(protocol);
1429 silc_packet_context_free(ctx->packet);
1431 sock->protocol = NULL;
1433 /* Allocate the authentication protocol. This is allocated here
1434 but we won't start it yet. We will be receiving party of this
1435 protocol thus we will wait that connecting party will make
1436 their first move. */
1437 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1438 &sock->protocol, proto_ctx,
1439 silc_server_accept_new_connection_final);
1441 /* Register timeout task. If the protocol is not executed inside
1442 this timelimit the connection will be terminated. */
1443 proto_ctx->timeout_task =
1444 silc_schedule_task_add(server->schedule, sock->sock,
1445 silc_server_timeout_remote,
1447 server->config->conn_auth_timeout, 0,
1452 /* Final part of accepting new connection. The connection has now
1453 been authenticated and keys has been exchanged. We also know whether
1454 this is client or server connection. */
1456 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1458 SilcProtocol protocol = (SilcProtocol)context;
1459 SilcServerConnAuthInternalContext *ctx =
1460 (SilcServerConnAuthInternalContext *)protocol->context;
1461 SilcServer server = (SilcServer)ctx->server;
1462 SilcSocketConnection sock = ctx->sock;
1463 SilcServerHBContext hb_context;
1464 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1466 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1468 SILC_LOG_DEBUG(("Start"));
1470 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1471 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1472 /* Error occured during protocol */
1473 silc_protocol_free(protocol);
1474 sock->protocol = NULL;
1476 silc_packet_context_free(ctx->packet);
1478 silc_ske_free(ctx->ske);
1479 silc_free(ctx->dest_id);
1480 silc_server_config_unref(&ctx->cconfig);
1481 silc_server_config_unref(&ctx->sconfig);
1482 silc_server_config_unref(&ctx->rconfig);
1484 silc_schedule_task_del_by_callback(server->schedule,
1485 silc_server_failure_callback);
1486 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1488 server->stat.auth_failures++;
1492 entry->data.last_receive = time(NULL);
1494 switch (ctx->conn_type) {
1495 case SILC_SOCKET_TYPE_CLIENT:
1497 SilcClientEntry client;
1498 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1500 /* Verify whether this connection is after all allowed to connect */
1501 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1502 &server->config->param,
1503 conn->param, ctx->ske)) {
1504 server->stat.auth_failures++;
1508 SILC_LOG_DEBUG(("Remote host is client"));
1509 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1512 /* Add the client to the client ID cache. The nickname and Client ID
1513 and other information is created after we have received NEW_CLIENT
1514 packet from client. */
1515 client = silc_idlist_add_client(server->local_list,
1516 NULL, NULL, NULL, NULL, NULL, sock, 0);
1518 SILC_LOG_ERROR(("Could not add new client to cache"));
1519 silc_free(sock->user_data);
1520 silc_server_disconnect_remote(server, sock,
1521 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1522 server->stat.auth_failures++;
1527 server->stat.my_clients++;
1528 server->stat.clients++;
1529 server->stat.cell_clients++;
1531 /* Get connection parameters */
1533 if (conn->param->keepalive_secs)
1534 hearbeat_timeout = conn->param->keepalive_secs;
1537 id_entry = (void *)client;
1540 case SILC_SOCKET_TYPE_SERVER:
1541 case SILC_SOCKET_TYPE_ROUTER:
1543 SilcServerEntry new_server;
1544 bool initiator = FALSE;
1545 bool backup_local = FALSE;
1546 bool backup_router = FALSE;
1547 char *backup_replace_ip = NULL;
1548 SilcUInt16 backup_replace_port = 0;
1549 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1550 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1552 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1553 /* Verify whether this connection is after all allowed to connect */
1554 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1555 &server->config->param,
1556 rconn ? rconn->param : NULL,
1558 server->stat.auth_failures++;
1564 if (rconn->param->keepalive_secs)
1565 hearbeat_timeout = rconn->param->keepalive_secs;
1568 initiator = rconn->initiator;
1569 backup_local = rconn->backup_local;
1570 backup_router = rconn->backup_router;
1571 backup_replace_ip = rconn->backup_replace_ip;
1572 backup_replace_port = rconn->backup_replace_port;
1576 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1577 /* Verify whether this connection is after all allowed to connect */
1578 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1579 &server->config->param,
1580 sconn ? sconn->param : NULL,
1582 server->stat.auth_failures++;
1587 if (sconn->param->keepalive_secs)
1588 hearbeat_timeout = sconn->param->keepalive_secs;
1591 backup_router = sconn->backup_router;
1595 SILC_LOG_DEBUG(("Remote host is %s",
1596 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1597 "server" : (backup_router ?
1598 "backup router" : "router")));
1599 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1600 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1601 "server" : (backup_router ?
1602 "backup router" : "router")));
1604 /* Add the server into server cache. The server name and Server ID
1605 is updated after we have received NEW_SERVER packet from the
1606 server. We mark ourselves as router for this server if we really
1609 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1610 server->local_list : (backup_router ?
1611 server->local_list :
1612 server->global_list)),
1614 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1615 SILC_SERVER : SILC_ROUTER),
1617 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1618 server->id_entry : (backup_router ?
1619 server->id_entry : NULL)),
1622 SILC_LOG_ERROR(("Could not add new server to cache"));
1623 silc_free(sock->user_data);
1624 silc_server_disconnect_remote(server, sock,
1625 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1626 server->stat.auth_failures++;
1631 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER)
1632 server->stat.my_servers++;
1634 server->stat.my_routers++;
1635 server->stat.servers++;
1637 id_entry = (void *)new_server;
1639 /* If the incoming connection is router and marked as backup router
1640 then add it to be one of our backups */
1641 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1642 silc_server_backup_add(server, new_server, backup_replace_ip,
1643 backup_replace_port, backup_local);
1645 /* Change it back to SERVER type since that's what it really is. */
1647 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1649 new_server->server_type = SILC_BACKUP_ROUTER;
1652 /* Check whether this connection is to be our primary router connection
1653 if we do not already have the primary route. */
1654 if (!backup_router &&
1655 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1656 if (silc_server_config_is_primary_route(server) && !initiator)
1659 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1660 server->standalone = FALSE;
1661 if (!server->id_entry->router) {
1662 server->id_entry->router = id_entry;
1663 server->router = id_entry;
1674 sock->type = ctx->conn_type;
1676 /* Add the common data structure to the ID entry. */
1677 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1679 /* Add to sockets internal pointer for fast referencing */
1680 silc_free(sock->user_data);
1681 sock->user_data = id_entry;
1683 /* Connection has been fully established now. Everything is ok. */
1684 SILC_LOG_DEBUG(("New connection authenticated"));
1686 /* Perform keepalive. The `hb_context' will be freed automatically
1687 when finally calling the silc_socket_free function. */
1688 hb_context = silc_calloc(1, sizeof(*hb_context));
1689 hb_context->server = server;
1690 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1691 silc_server_perform_heartbeat,
1695 silc_schedule_task_del_by_callback(server->schedule,
1696 silc_server_failure_callback);
1697 silc_protocol_free(protocol);
1699 silc_packet_context_free(ctx->packet);
1701 silc_ske_free(ctx->ske);
1702 silc_free(ctx->dest_id);
1703 silc_server_config_unref(&ctx->cconfig);
1704 silc_server_config_unref(&ctx->sconfig);
1705 silc_server_config_unref(&ctx->rconfig);
1707 sock->protocol = NULL;
1710 /* This function is used to read packets from network and send packets to
1711 network. This is usually a generic task. */
1713 SILC_TASK_CALLBACK(silc_server_packet_process)
1715 SilcServer server = (SilcServer)context;
1716 SilcSocketConnection sock = server->sockets[fd];
1717 SilcIDListData idata;
1718 SilcCipher cipher = NULL;
1719 SilcHmac hmac = NULL;
1720 SilcUInt32 sequence = 0;
1726 SILC_LOG_DEBUG(("Processing packet"));
1728 /* Packet sending */
1730 if (type == SILC_TASK_WRITE) {
1731 /* Do not send data to disconnected connection */
1732 if (SILC_IS_DISCONNECTED(sock))
1735 server->stat.packets_sent++;
1737 /* Send the packet */
1738 ret = silc_packet_send(sock, TRUE);
1740 /* If returned -2 could not write to connection now, will do
1746 SILC_LOG_ERROR(("Error sending packet to connection "
1747 "%s:%d [%s]", sock->hostname, sock->port,
1748 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1749 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1750 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1755 /* The packet has been sent and now it is time to set the connection
1756 back to only for input. When there is again some outgoing data
1757 available for this connection it will be set for output as well.
1758 This call clears the output setting and sets it only for input. */
1759 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
1760 SILC_UNSET_OUTBUF_PENDING(sock);
1762 silc_buffer_clear(sock->outbuf);
1766 /* Packet receiving */
1768 /* Read some data from connection */
1769 ret = silc_packet_receive(sock);
1773 SILC_LOG_ERROR(("Error receiving packet from connection "
1774 "%s:%d [%s] %s", sock->hostname, sock->port,
1775 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1776 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1777 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1778 "Router"), strerror(errno)));
1784 SILC_LOG_DEBUG(("Read EOF"));
1786 /* If connection is disconnecting already we will finally
1787 close the connection */
1788 if (SILC_IS_DISCONNECTING(sock)) {
1789 if (sock->user_data)
1790 silc_server_free_sock_user_data(server, sock, NULL);
1791 silc_server_close_connection(server, sock);
1795 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1796 SILC_SET_DISCONNECTING(sock);
1798 if (sock->user_data) {
1800 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
1801 silc_server_free_sock_user_data(server, sock, tmp);
1803 silc_server_free_sock_user_data(server, sock, NULL);
1804 } else if (server->router_conn && server->router_conn->sock == sock &&
1805 !server->router && server->standalone)
1806 silc_schedule_task_add(server->schedule, 0,
1807 silc_server_connect_to_router,
1810 SILC_TASK_PRI_NORMAL);
1812 silc_server_close_connection(server, sock);
1816 /* If connection is disconnecting or disconnected we will ignore
1818 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1819 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
1823 server->stat.packets_received++;
1825 /* Get keys and stuff from ID entry */
1826 idata = (SilcIDListData)sock->user_data;
1828 cipher = idata->receive_key;
1829 hmac = idata->hmac_receive;
1830 sequence = idata->psn_receive;
1833 /* Process the packet. This will call the parser that will then
1834 decrypt and parse the packet. */
1835 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1836 TRUE : FALSE, cipher, hmac, sequence,
1837 silc_server_packet_parse, server);
1839 /* If this socket connection is not authenticated yet and the packet
1840 processing failed we will drop the connection since it can be
1841 a malicious flooder. */
1842 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
1843 (!sock->protocol || sock->protocol->protocol->type ==
1844 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
1845 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
1846 SILC_SET_DISCONNECTING(sock);
1848 if (sock->user_data)
1849 silc_server_free_sock_user_data(server, sock, NULL);
1850 silc_server_close_connection(server, sock);
1854 /* Parses whole packet, received earlier. */
1856 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1858 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1859 SilcServer server = (SilcServer)parse_ctx->context;
1860 SilcSocketConnection sock = parse_ctx->sock;
1861 SilcPacketContext *packet = parse_ctx->packet;
1862 SilcIDListData idata = (SilcIDListData)sock->user_data;
1865 SILC_LOG_DEBUG(("Start"));
1867 /* Parse the packet */
1868 if (parse_ctx->normal)
1869 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
1871 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
1873 /* If entry is disabled ignore what we got. */
1874 if (ret != SILC_PACKET_RESUME_ROUTER &&
1875 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
1876 SILC_LOG_DEBUG(("Connection is disabled"));
1880 if (ret == SILC_PACKET_NONE)
1883 /* Check that the the current client ID is same as in the client's packet. */
1884 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1885 SilcClientEntry client = (SilcClientEntry)sock->user_data;
1886 if (client && client->id) {
1887 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1888 packet->src_id_type);
1889 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
1897 if (server->server_type == SILC_ROUTER) {
1898 /* Route the packet if it is not destined to us. Other ID types but
1899 server are handled separately after processing them. */
1900 if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1901 packet->dst_id_type == SILC_ID_SERVER &&
1902 sock->type != SILC_SOCKET_TYPE_CLIENT &&
1903 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1905 /* Route the packet to fastest route for the destination ID */
1906 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1907 packet->dst_id_type);
1910 silc_server_packet_route(server,
1911 silc_server_route_get(server, id,
1912 packet->dst_id_type),
1919 /* Parse the incoming packet type */
1920 silc_server_packet_parse_type(server, sock, packet);
1922 if (server->server_type == SILC_ROUTER) {
1923 /* Broadcast packet if it is marked as broadcast packet and it is
1924 originated from router and we are router. */
1925 if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1926 packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1927 !server->standalone) {
1928 /* Broadcast to our primary route */
1929 silc_server_packet_broadcast(server, server->router->connection, packet);
1931 /* If we have backup routers then we need to feed all broadcast
1932 data to those servers. */
1933 silc_server_backup_broadcast(server, sock, packet);
1938 silc_packet_context_free(packet);
1939 silc_free(parse_ctx);
1942 /* Parser callback called by silc_packet_receive_process. This merely
1943 registers timeout that will handle the actual parsing when appropriate. */
1945 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
1948 SilcServer server = (SilcServer)context;
1949 SilcSocketConnection sock = parser_context->sock;
1950 SilcIDListData idata = (SilcIDListData)sock->user_data;
1953 idata->psn_receive = parser_context->packet->sequence + 1;
1955 /* If protocol for this connection is key exchange or rekey then we'll
1956 process all packets synchronously, since there might be packets in
1957 queue that we are not able to decrypt without first processing the
1958 packets before them. */
1959 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
1960 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
1961 (sock->protocol && sock->protocol->protocol &&
1962 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1963 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
1964 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
1967 /* Reprocess data since we'll return FALSE here. This is because
1968 the idata->receive_key might have become valid in the last packet
1969 and we want to call this processor with valid cipher. */
1971 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1972 TRUE : FALSE, idata->receive_key,
1973 idata->hmac_receive, idata->psn_receive,
1974 silc_server_packet_parse, server);
1976 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
1977 TRUE : FALSE, NULL, NULL, 0,
1978 silc_server_packet_parse, server);
1982 switch (sock->type) {
1983 case SILC_SOCKET_TYPE_UNKNOWN:
1984 case SILC_SOCKET_TYPE_CLIENT:
1985 /* Parse the packet with timeout */
1986 silc_schedule_task_add(server->schedule, sock->sock,
1987 silc_server_packet_parse_real,
1988 (void *)parser_context, 0, 100000,
1990 SILC_TASK_PRI_NORMAL);
1992 case SILC_SOCKET_TYPE_SERVER:
1993 case SILC_SOCKET_TYPE_ROUTER:
1994 /* Packets from servers are parsed immediately */
1995 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2005 /* Parses the packet type and calls what ever routines the packet type
2006 requires. This is done for all incoming packets. */
2008 void silc_server_packet_parse_type(SilcServer server,
2009 SilcSocketConnection sock,
2010 SilcPacketContext *packet)
2012 SilcPacketType type = packet->type;
2013 SilcIDListData idata = (SilcIDListData)sock->user_data;
2015 SILC_LOG_DEBUG(("Parsing packet type %d", type));
2017 /* Parse the packet type */
2019 case SILC_PACKET_DISCONNECT:
2022 char *message = NULL;
2024 SILC_LOG_DEBUG(("Disconnect packet"));
2026 if (packet->flags & SILC_PACKET_FLAG_LIST)
2028 if (packet->buffer->len < 1)
2031 status = (SilcStatus)packet->buffer->data[0];
2032 if (packet->buffer->len > 1 &&
2033 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2034 message = silc_memdup(packet->buffer->data, packet->buffer->len);
2036 SILC_LOG_ERROR(("Disconnected by %s (%s): %s (%d) %s",
2037 sock->ip, sock->hostname,
2038 silc_get_status_message(status), status,
2039 message ? message : ""));
2044 case SILC_PACKET_SUCCESS:
2046 * Success received for something. For now we can have only
2047 * one protocol for connection executing at once hence this
2048 * success message is for whatever protocol is executing currently.
2050 SILC_LOG_DEBUG(("Success packet"));
2051 if (packet->flags & SILC_PACKET_FLAG_LIST)
2054 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2057 case SILC_PACKET_FAILURE:
2059 * Failure received for something. For now we can have only
2060 * one protocol for connection executing at once hence this
2061 * failure message is for whatever protocol is executing currently.
2063 SILC_LOG_DEBUG(("Failure packet"));
2064 if (packet->flags & SILC_PACKET_FLAG_LIST)
2066 if (sock->protocol) {
2067 SilcServerFailureContext f;
2068 f = silc_calloc(1, sizeof(*f));
2072 /* We will wait 5 seconds to process this failure packet */
2073 silc_schedule_task_add(server->schedule, sock->sock,
2074 silc_server_failure_callback, (void *)f, 5, 0,
2075 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2079 case SILC_PACKET_REJECT:
2080 SILC_LOG_DEBUG(("Reject packet"));
2081 if (packet->flags & SILC_PACKET_FLAG_LIST)
2086 case SILC_PACKET_NOTIFY:
2088 * Received notify packet. Server can receive notify packets from
2089 * router. Server then relays the notify messages to clients if needed.
2091 SILC_LOG_DEBUG(("Notify packet"));
2092 if (packet->flags & SILC_PACKET_FLAG_LIST)
2093 silc_server_notify_list(server, sock, packet);
2095 silc_server_notify(server, sock, packet);
2101 case SILC_PACKET_CHANNEL_MESSAGE:
2103 * Received channel message. Channel messages are special packets
2104 * (although probably most common ones) thus they are handled
2107 SILC_LOG_DEBUG(("Channel Message packet"));
2108 if (packet->flags & SILC_PACKET_FLAG_LIST)
2110 idata->last_receive = time(NULL);
2111 silc_server_channel_message(server, sock, packet);
2114 case SILC_PACKET_CHANNEL_KEY:
2116 * Received key for channel. As channels are created by the router
2117 * the keys are as well. We will distribute the key to all of our
2118 * locally connected clients on the particular channel. Router
2119 * never receives this channel and thus is ignored.
2121 SILC_LOG_DEBUG(("Channel Key packet"));
2122 if (packet->flags & SILC_PACKET_FLAG_LIST)
2124 silc_server_channel_key(server, sock, packet);
2130 case SILC_PACKET_COMMAND:
2132 * Recived command. Processes the command request and allocates the
2133 * command context and calls the command.
2135 SILC_LOG_DEBUG(("Command packet"));
2136 if (packet->flags & SILC_PACKET_FLAG_LIST)
2138 silc_server_command_process(server, sock, packet);
2141 case SILC_PACKET_COMMAND_REPLY:
2143 * Received command reply packet. Received command reply to command. It
2144 * may be reply to command sent by us or reply to command sent by client
2145 * that we've routed further.
2147 SILC_LOG_DEBUG(("Command Reply packet"));
2148 if (packet->flags & SILC_PACKET_FLAG_LIST)
2150 silc_server_command_reply(server, sock, packet);
2154 * Private Message packets
2156 case SILC_PACKET_PRIVATE_MESSAGE:
2158 * Received private message packet. The packet is coming from either
2161 SILC_LOG_DEBUG(("Private Message packet"));
2162 if (packet->flags & SILC_PACKET_FLAG_LIST)
2164 idata->last_receive = time(NULL);
2165 silc_server_private_message(server, sock, packet);
2168 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2170 * Private message key packet.
2172 if (packet->flags & SILC_PACKET_FLAG_LIST)
2174 silc_server_private_message_key(server, sock, packet);
2178 * Key Exchange protocol packets
2180 case SILC_PACKET_KEY_EXCHANGE:
2181 SILC_LOG_DEBUG(("KE packet"));
2182 if (packet->flags & SILC_PACKET_FLAG_LIST)
2185 if (sock->protocol && sock->protocol->protocol &&
2186 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2187 SilcServerKEInternalContext *proto_ctx =
2188 (SilcServerKEInternalContext *)sock->protocol->context;
2190 proto_ctx->packet = silc_packet_context_dup(packet);
2192 /* Let the protocol handle the packet */
2193 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2195 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2196 "protocol active, packet dropped."));
2200 case SILC_PACKET_KEY_EXCHANGE_1:
2201 SILC_LOG_DEBUG(("KE 1 packet"));
2202 if (packet->flags & SILC_PACKET_FLAG_LIST)
2205 if (sock->protocol && sock->protocol->protocol &&
2206 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2207 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2209 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2210 SilcServerRekeyInternalContext *proto_ctx =
2211 (SilcServerRekeyInternalContext *)sock->protocol->context;
2213 if (proto_ctx->packet)
2214 silc_packet_context_free(proto_ctx->packet);
2216 proto_ctx->packet = silc_packet_context_dup(packet);
2218 /* Let the protocol handle the packet */
2219 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2221 SilcServerKEInternalContext *proto_ctx =
2222 (SilcServerKEInternalContext *)sock->protocol->context;
2224 if (proto_ctx->packet)
2225 silc_packet_context_free(proto_ctx->packet);
2227 proto_ctx->packet = silc_packet_context_dup(packet);
2228 proto_ctx->dest_id_type = packet->src_id_type;
2229 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2230 packet->src_id_type);
2231 if (!proto_ctx->dest_id)
2234 /* Let the protocol handle the packet */
2235 silc_protocol_execute(sock->protocol, server->schedule,
2239 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2240 "protocol active, packet dropped."));
2244 case SILC_PACKET_KEY_EXCHANGE_2:
2245 SILC_LOG_DEBUG(("KE 2 packet"));
2246 if (packet->flags & SILC_PACKET_FLAG_LIST)
2249 if (sock->protocol && sock->protocol->protocol &&
2250 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2251 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2253 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2254 SilcServerRekeyInternalContext *proto_ctx =
2255 (SilcServerRekeyInternalContext *)sock->protocol->context;
2257 if (proto_ctx->packet)
2258 silc_packet_context_free(proto_ctx->packet);
2260 proto_ctx->packet = silc_packet_context_dup(packet);
2262 /* Let the protocol handle the packet */
2263 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2265 SilcServerKEInternalContext *proto_ctx =
2266 (SilcServerKEInternalContext *)sock->protocol->context;
2268 if (proto_ctx->packet)
2269 silc_packet_context_free(proto_ctx->packet);
2271 proto_ctx->packet = silc_packet_context_dup(packet);
2272 proto_ctx->dest_id_type = packet->src_id_type;
2273 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2274 packet->src_id_type);
2275 if (!proto_ctx->dest_id)
2278 /* Let the protocol handle the packet */
2279 silc_protocol_execute(sock->protocol, server->schedule,
2283 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2284 "protocol active, packet dropped."));
2288 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2290 * Connection authentication request packet. When we receive this packet
2291 * we will send to the other end information about our mandatory
2292 * authentication method for the connection. This packet maybe received
2295 SILC_LOG_DEBUG(("Connection authentication request packet"));
2296 if (packet->flags & SILC_PACKET_FLAG_LIST)
2298 silc_server_connection_auth_request(server, sock, packet);
2302 * Connection Authentication protocol packets
2304 case SILC_PACKET_CONNECTION_AUTH:
2305 /* Start of the authentication protocol. We receive here the
2306 authentication data and will verify it. */
2307 SILC_LOG_DEBUG(("Connection auth packet"));
2308 if (packet->flags & SILC_PACKET_FLAG_LIST)
2311 if (sock->protocol && sock->protocol->protocol->type
2312 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2314 SilcServerConnAuthInternalContext *proto_ctx =
2315 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2317 proto_ctx->packet = silc_packet_context_dup(packet);
2319 /* Let the protocol handle the packet */
2320 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2322 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2323 "protocol active, packet dropped."));
2327 case SILC_PACKET_NEW_ID:
2329 * Received New ID packet. This includes some new ID that has been
2330 * created. It may be for client, server or channel. This is the way
2331 * to distribute information about new registered entities in the
2334 SILC_LOG_DEBUG(("New ID packet"));
2335 if (packet->flags & SILC_PACKET_FLAG_LIST)
2336 silc_server_new_id_list(server, sock, packet);
2338 silc_server_new_id(server, sock, packet);
2341 case SILC_PACKET_NEW_CLIENT:
2343 * Received new client packet. This includes client information that
2344 * we will use to create initial client ID. After creating new
2345 * ID we will send it to the client.
2347 SILC_LOG_DEBUG(("New Client packet"));
2348 if (packet->flags & SILC_PACKET_FLAG_LIST)
2350 silc_server_new_client(server, sock, packet);
2353 case SILC_PACKET_NEW_SERVER:
2355 * Received new server packet. This includes Server ID and some other
2356 * information that we may save. This is received after server has
2359 SILC_LOG_DEBUG(("New Server packet"));
2360 if (packet->flags & SILC_PACKET_FLAG_LIST)
2362 silc_server_new_server(server, sock, packet);
2365 case SILC_PACKET_NEW_CHANNEL:
2367 * Received new channel packet. Information about new channel in the
2368 * network are distributed using this packet.
2370 SILC_LOG_DEBUG(("New Channel packet"));
2371 if (packet->flags & SILC_PACKET_FLAG_LIST)
2372 silc_server_new_channel_list(server, sock, packet);
2374 silc_server_new_channel(server, sock, packet);
2377 case SILC_PACKET_HEARTBEAT:
2379 * Received heartbeat.
2381 SILC_LOG_DEBUG(("Heartbeat packet"));
2382 if (packet->flags & SILC_PACKET_FLAG_LIST)
2386 case SILC_PACKET_KEY_AGREEMENT:
2388 * Received heartbeat.
2390 SILC_LOG_DEBUG(("Key agreement packet"));
2391 if (packet->flags & SILC_PACKET_FLAG_LIST)
2393 silc_server_key_agreement(server, sock, packet);
2396 case SILC_PACKET_REKEY:
2398 * Received re-key packet. The sender wants to regenerate the session
2401 SILC_LOG_DEBUG(("Re-key packet"));
2402 if (packet->flags & SILC_PACKET_FLAG_LIST)
2404 silc_server_rekey(server, sock, packet);
2407 case SILC_PACKET_REKEY_DONE:
2409 * The re-key is done.
2411 SILC_LOG_DEBUG(("Re-key done packet"));
2412 if (packet->flags & SILC_PACKET_FLAG_LIST)
2415 if (sock->protocol && sock->protocol->protocol &&
2416 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2418 SilcServerRekeyInternalContext *proto_ctx =
2419 (SilcServerRekeyInternalContext *)sock->protocol->context;
2421 if (proto_ctx->packet)
2422 silc_packet_context_free(proto_ctx->packet);
2424 proto_ctx->packet = silc_packet_context_dup(packet);
2426 /* Let the protocol handle the packet */
2427 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2429 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2430 "protocol active, packet dropped."));
2434 case SILC_PACKET_FTP:
2436 SILC_LOG_DEBUG(("FTP packet"));
2437 if (packet->flags & SILC_PACKET_FLAG_LIST)
2439 silc_server_ftp(server, sock, packet);
2442 case SILC_PACKET_RESUME_CLIENT:
2444 SILC_LOG_DEBUG(("Resume Client packet"));
2445 if (packet->flags & SILC_PACKET_FLAG_LIST)
2447 silc_server_resume_client(server, sock, packet);
2450 case SILC_PACKET_RESUME_ROUTER:
2451 /* Resume router packet received. This packet is received for backup
2452 router resuming protocol. */
2453 SILC_LOG_DEBUG(("Resume router packet"));
2454 if (packet->flags & SILC_PACKET_FLAG_LIST)
2456 silc_server_backup_resume_router(server, sock, packet);
2460 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2466 /* Creates connection to a remote router. */
2468 void silc_server_create_connection(SilcServer server,
2469 const char *remote_host, SilcUInt32 port)
2471 SilcServerConnection sconn;
2473 /* Allocate connection object for hold connection specific stuff. */
2474 sconn = silc_calloc(1, sizeof(*sconn));
2475 sconn->server = server;
2476 sconn->remote_host = strdup(remote_host);
2477 sconn->remote_port = port;
2478 sconn->no_reconnect = TRUE;
2480 silc_schedule_task_add(server->schedule, 0,
2481 silc_server_connect_router,
2482 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2483 SILC_TASK_PRI_NORMAL);
2486 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2488 silc_socket_free((SilcSocketConnection)context);
2491 /* Closes connection to socket connection */
2493 void silc_server_close_connection(SilcServer server,
2494 SilcSocketConnection sock)
2496 if (!server->sockets[sock->sock])
2499 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2501 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2502 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2503 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2506 /* We won't listen for this connection anymore */
2507 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2509 /* Unregister all tasks */
2510 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2512 /* Close the actual connection */
2513 silc_net_close_connection(sock->sock);
2514 server->sockets[sock->sock] = NULL;
2516 /* If sock->user_data is NULL then we'll check for active protocols
2517 here since the silc_server_free_sock_user_data has not been called
2518 for this connection. */
2519 if (!sock->user_data) {
2520 /* If any protocol is active cancel its execution. It will call
2521 the final callback which will finalize the disconnection. */
2522 if (sock->protocol) {
2523 silc_protocol_cancel(sock->protocol, server->schedule);
2524 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2525 silc_protocol_execute_final(sock->protocol, server->schedule);
2526 sock->protocol = NULL;
2531 silc_schedule_task_add(server->schedule, 0,
2532 silc_server_close_connection_final,
2533 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2534 SILC_TASK_PRI_NORMAL);
2537 /* Sends disconnect message to remote connection and disconnects the
2540 void silc_server_disconnect_remote(SilcServer server,
2541 SilcSocketConnection sock,
2542 SilcStatus status, ...)
2545 unsigned char buf[512];
2553 memset(buf, 0, sizeof(buf));
2554 va_start(ap, status);
2555 cp = va_arg(ap, char *);
2557 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2562 SILC_LOG_DEBUG(("Disconnecting remote host"));
2564 /* Notify remote end that the conversation is over. The notify message
2565 is tried to be sent immediately. */
2569 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2571 buffer = silc_buffer_alloc_size(len);
2575 buffer->data[0] = status;
2577 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2579 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2580 buffer->data, buffer->len, TRUE);
2581 silc_buffer_free(buffer);
2584 silc_server_packet_queue_purge(server, sock);
2586 /* Mark the connection to be disconnected */
2587 SILC_SET_DISCONNECTED(sock);
2588 silc_server_close_connection(server, sock);
2593 SilcClientEntry client;
2594 } *FreeClientInternal;
2596 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2598 FreeClientInternal i = (FreeClientInternal)context;
2600 silc_idlist_del_data(i->client);
2601 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2605 /* Frees client data and notifies about client's signoff. */
2607 void silc_server_free_client_data(SilcServer server,
2608 SilcSocketConnection sock,
2609 SilcClientEntry client,
2611 const char *signoff)
2613 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2615 /* If there is pending outgoing data for the client then purge it
2616 to the network before removing the client entry. */
2617 silc_server_packet_queue_purge(server, sock);
2620 /* Check if anyone is watching this nickname */
2621 if (server->server_type == SILC_ROUTER)
2622 silc_server_check_watcher_list(server, client, NULL,
2623 SILC_NOTIFY_TYPE_SIGNOFF);
2625 /* Send SIGNOFF notify to routers. */
2626 if (notify && !server->standalone && server->router)
2627 silc_server_send_notify_signoff(server, server->router->connection,
2628 server->server_type == SILC_SERVER ?
2629 FALSE : TRUE, client->id, signoff);
2631 /* Remove client from all channels */
2633 silc_server_remove_from_channels(server, NULL, client,
2634 TRUE, (char *)signoff, TRUE);
2636 silc_server_remove_from_channels(server, NULL, client,
2637 FALSE, NULL, FALSE);
2639 /* Remove this client from watcher list if it is */
2640 silc_server_del_from_watcher_list(server, client);
2643 /* Update statistics */
2644 server->stat.my_clients--;
2645 server->stat.clients--;
2646 if (server->stat.cell_clients)
2647 server->stat.cell_clients--;
2648 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2649 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2650 silc_schedule_task_del_by_context(server->schedule, client);
2652 /* We will not delete the client entry right away. We will take it
2653 into history (for WHOWAS command) for 5 minutes */
2656 silc_schedule_task_add(server->schedule, 0,
2657 silc_server_free_client_data_timeout,
2659 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2660 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2662 client->router = NULL;
2663 client->connection = NULL;
2666 /* Frees user_data pointer from socket connection object. This also sends
2667 appropriate notify packets to the network to inform about leaving
2670 void silc_server_free_sock_user_data(SilcServer server,
2671 SilcSocketConnection sock,
2672 const char *signoff_message)
2674 SILC_LOG_DEBUG(("Start"));
2676 switch (sock->type) {
2677 case SILC_SOCKET_TYPE_CLIENT:
2679 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2680 silc_server_free_client_data(server, sock, user_data, TRUE,
2684 case SILC_SOCKET_TYPE_SERVER:
2685 case SILC_SOCKET_TYPE_ROUTER:
2687 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2688 SilcServerEntry backup_router = NULL;
2691 backup_router = silc_server_backup_get(server, user_data->id);
2693 /* If this was our primary router connection then we're lost to
2694 the outside world. */
2695 if (server->router == user_data) {
2696 /* Check whether we have a backup router connection */
2697 if (!backup_router || backup_router == user_data) {
2698 silc_schedule_task_add(server->schedule, 0,
2699 silc_server_connect_to_router,
2702 SILC_TASK_PRI_NORMAL);
2704 server->id_entry->router = NULL;
2705 server->router = NULL;
2706 server->standalone = TRUE;
2707 backup_router = NULL;
2709 SILC_LOG_INFO(("New primary router is backup router %s",
2710 backup_router->server_name));
2711 SILC_LOG_DEBUG(("New primary router is backup router %s",
2712 backup_router->server_name));
2713 #ifdef BACKUP_SINGLE_ROUTER
2714 if (server->id_entry != backup_router) {
2715 #endif /* BACKUP_SINGLE_ROUTER */
2716 server->id_entry->router = backup_router;
2717 server->router = backup_router;
2718 server->router_connect = time(0);
2719 server->backup_primary = TRUE;
2720 #ifdef BACKUP_SINGLE_ROUTER
2722 server->id_entry->router = NULL;
2723 server->router = NULL;
2724 server->standalone = TRUE;
2726 #endif /* BACKUP_SINGLE_ROUTER */
2728 if (server->server_type == SILC_BACKUP_ROUTER) {
2729 server->server_type = SILC_ROUTER;
2731 /* We'll need to constantly try to reconnect to the primary
2732 router so that we'll see when it comes back online. */
2733 silc_server_backup_reconnect(server, sock->ip, sock->port,
2734 silc_server_backup_connected,
2738 /* Mark this connection as replaced */
2739 silc_server_backup_replaced_add(server, user_data->id,
2742 } else if (backup_router) {
2743 SILC_LOG_INFO(("Enabling the use of backup router %s",
2744 backup_router->server_name));
2745 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
2746 backup_router->server_name));
2748 /* Mark this connection as replaced */
2749 silc_server_backup_replaced_add(server, user_data->id,
2753 if (!backup_router) {
2754 /* Free all client entries that this server owns as they will
2755 become invalid now as well. */
2757 silc_server_remove_clients_by_server(server, user_data, TRUE);
2758 if (server->server_type == SILC_SERVER)
2759 silc_server_remove_channels_by_server(server, user_data);
2761 /* Update the client entries of this server to the new backup
2762 router. This also removes the clients that *really* was owned
2763 by the primary router and went down with the router. */
2764 silc_server_update_clients_by_server(server, user_data, backup_router,
2766 silc_server_update_servers_by_server(server, user_data, backup_router);
2767 if (server->server_type == SILC_SERVER)
2768 silc_server_update_channels_by_server(server, user_data,
2772 /* Free the server entry */
2773 silc_server_backup_del(server, user_data);
2774 silc_server_backup_replaced_del(server, user_data);
2775 silc_idlist_del_data(user_data);
2776 if (!silc_idlist_del_server(server->local_list, user_data))
2777 silc_idlist_del_server(server->global_list, user_data);
2778 server->stat.my_servers--;
2779 server->stat.servers--;
2780 if (server->server_type == SILC_ROUTER)
2781 server->stat.cell_servers--;
2783 if (backup_router) {
2784 /* Announce all of our stuff that was created about 5 minutes ago.
2785 The backup router knows all the other stuff already. */
2786 if (server->server_type == SILC_ROUTER)
2787 silc_server_announce_servers(server, FALSE, time(0) - 300,
2788 backup_router->connection);
2790 /* Announce our clients and channels to the router */
2791 silc_server_announce_clients(server, time(0) - 300,
2792 backup_router->connection);
2793 silc_server_announce_channels(server, time(0) - 300,
2794 backup_router->connection);
2800 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2802 silc_idlist_del_data(user_data);
2803 silc_free(user_data);
2808 /* If any protocol is active cancel its execution */
2809 if (sock->protocol) {
2810 silc_protocol_cancel(sock->protocol, server->schedule);
2811 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2812 silc_protocol_execute_final(sock->protocol, server->schedule);
2813 sock->protocol = NULL;
2816 sock->user_data = NULL;
2819 /* Removes client from all channels it has joined. This is used when client
2820 connection is disconnected. If the client on a channel is last, the
2821 channel is removed as well. This sends the SIGNOFF notify types. */
2823 void silc_server_remove_from_channels(SilcServer server,
2824 SilcSocketConnection sock,
2825 SilcClientEntry client,
2827 const char *signoff_message,
2830 SilcChannelEntry channel;
2831 SilcChannelClientEntry chl;
2832 SilcHashTableList htl;
2835 SILC_LOG_DEBUG(("Start"));
2837 if (!client || !client->id)
2840 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2844 /* Remove the client from all channels. The client is removed from
2845 the channels' user list. */
2846 silc_hash_table_list(client->channels, &htl);
2847 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
2848 channel = chl->channel;
2850 /* Remove channel if this is last client leaving the channel, unless
2851 the channel is permanent. */
2852 if (server->server_type == SILC_ROUTER &&
2853 silc_hash_table_count(channel->user_list) < 2) {
2854 silc_server_channel_delete(server, channel);
2858 silc_hash_table_del(client->channels, channel);
2859 silc_hash_table_del(channel->user_list, chl->client);
2860 channel->user_count--;
2862 /* If there is no global users on the channel anymore mark the channel
2863 as local channel. Do not check if the removed client is local client. */
2864 if (server->server_type != SILC_ROUTER && channel->global_users &&
2865 chl->client->router && !silc_server_channel_has_global(channel))
2866 channel->global_users = FALSE;
2869 server->stat.my_chanclients--;
2871 /* If there is not at least one local user on the channel then we don't
2872 need the channel entry anymore, we can remove it safely, unless the
2873 channel is permanent channel */
2874 if (server->server_type != SILC_ROUTER &&
2875 !silc_server_channel_has_local(channel)) {
2876 /* Notify about leaving client if this channel has global users. */
2877 if (notify && channel->global_users)
2878 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2879 SILC_NOTIFY_TYPE_SIGNOFF,
2880 signoff_message ? 2 : 1,
2881 clidp->data, clidp->len,
2882 signoff_message, signoff_message ?
2883 strlen(signoff_message) : 0);
2885 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2886 silc_server_channel_delete(server, channel);
2890 /* Send notify to channel about client leaving SILC and channel too */
2892 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2893 SILC_NOTIFY_TYPE_SIGNOFF,
2894 signoff_message ? 2 : 1,
2895 clidp->data, clidp->len,
2896 signoff_message, signoff_message ?
2897 strlen(signoff_message) : 0);
2899 /* Re-generate channel key if needed */
2900 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2901 if (!silc_server_create_channel_key(server, channel, 0))
2904 /* Send the channel key to the channel. The key of course is not sent
2905 to the client who was removed from the channel. */
2906 silc_server_send_channel_key(server, client->connection, channel,
2907 server->server_type == SILC_ROUTER ?
2908 FALSE : !server->standalone);
2912 silc_hash_table_list_reset(&htl);
2913 silc_buffer_free(clidp);
2916 /* Removes client from one channel. This is used for example when client
2917 calls LEAVE command to remove itself from the channel. Returns TRUE
2918 if channel still exists and FALSE if the channel is removed when
2919 last client leaves the channel. If `notify' is FALSE notify messages
2922 bool silc_server_remove_from_one_channel(SilcServer server,
2923 SilcSocketConnection sock,
2924 SilcChannelEntry channel,
2925 SilcClientEntry client,
2928 SilcChannelClientEntry chl;
2931 SILC_LOG_DEBUG(("Removing %s from channel %s",
2932 silc_id_render(client->id, SILC_ID_CLIENT),
2933 channel->channel_name));
2935 /* Get the entry to the channel, if this client is not on the channel
2937 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
2940 /* Remove channel if this is last client leaving the channel, unless
2941 the channel is permanent. */
2942 if (server->server_type == SILC_ROUTER &&
2943 silc_hash_table_count(channel->user_list) < 2) {
2944 silc_server_channel_delete(server, channel);
2948 silc_hash_table_del(client->channels, chl->channel);
2949 silc_hash_table_del(channel->user_list, chl->client);
2950 channel->user_count--;
2952 /* If there is no global users on the channel anymore mark the channel
2953 as local channel. Do not check if the client is local client. */
2954 if (server->server_type != SILC_ROUTER && channel->global_users &&
2955 chl->client->router && !silc_server_channel_has_global(channel))
2956 channel->global_users = FALSE;
2959 server->stat.my_chanclients--;
2961 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2965 /* If there is not at least one local user on the channel then we don't
2966 need the channel entry anymore, we can remove it safely, unless the
2967 channel is permanent channel */
2968 if (server->server_type != SILC_ROUTER &&
2969 !silc_server_channel_has_local(channel)) {
2970 /* Notify about leaving client if this channel has global users. */
2971 if (notify && channel->global_users)
2972 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2973 SILC_NOTIFY_TYPE_LEAVE, 1,
2974 clidp->data, clidp->len);
2976 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
2977 silc_server_channel_delete(server, channel);
2978 silc_buffer_free(clidp);
2982 /* Send notify to channel about client leaving the channel */
2984 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2985 SILC_NOTIFY_TYPE_LEAVE, 1,
2986 clidp->data, clidp->len);
2988 silc_buffer_free(clidp);
2992 /* Timeout callback. This is called if connection is idle or for some
2993 other reason is not responding within some period of time. This
2994 disconnects the remote end. */
2996 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2998 SilcServer server = (SilcServer)context;
2999 SilcSocketConnection sock = server->sockets[fd];
3000 SilcProtocolType protocol = 0;
3002 SILC_LOG_DEBUG(("Start"));
3007 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3008 sock->hostname, sock->ip));
3010 /* If we have protocol active we must assure that we call the protocol's
3011 final callback so that all the memory is freed. */
3012 if (sock->protocol) {
3013 protocol = sock->protocol->protocol->type;
3014 silc_protocol_cancel(sock->protocol, server->schedule);
3015 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3016 silc_protocol_execute_final(sock->protocol, server->schedule);
3017 sock->protocol = NULL;
3021 if (sock->user_data)
3022 silc_server_free_sock_user_data(server, sock, NULL);
3024 silc_server_disconnect_remote(server, sock,
3026 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3027 SILC_STATUS_ERR_AUTH_FAILED :
3028 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3029 "Connection timeout");
3032 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3033 function may be used only by router. In real SILC network all channels
3034 are created by routers thus this function is never used by normal
3037 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3038 SilcServerID *router_id,
3044 SilcChannelID *channel_id;
3045 SilcChannelEntry entry;
3049 SILC_LOG_DEBUG(("Creating new channel"));
3052 cipher = SILC_DEFAULT_CIPHER;
3054 hmac = SILC_DEFAULT_HMAC;
3056 /* Allocate cipher */
3057 if (!silc_cipher_alloc(cipher, &key))
3061 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3062 silc_cipher_free(key);
3066 channel_name = strdup(channel_name);
3068 /* Create the channel ID */
3069 if (!silc_id_create_channel_id(server, router_id, server->rng,
3071 silc_free(channel_name);
3072 silc_cipher_free(key);
3073 silc_hmac_free(newhmac);
3077 /* Create the channel */
3078 entry = silc_idlist_add_channel(server->local_list, channel_name,
3079 SILC_CHANNEL_MODE_NONE, channel_id,
3080 NULL, key, newhmac, 0);
3082 silc_free(channel_name);
3083 silc_cipher_free(key);
3084 silc_hmac_free(newhmac);
3085 silc_free(channel_id);
3089 entry->cipher = strdup(cipher);
3090 entry->hmac_name = strdup(hmac);
3092 /* Now create the actual key material */
3093 if (!silc_server_create_channel_key(server, entry,
3094 silc_cipher_get_key_len(key) / 8)) {
3095 silc_idlist_del_channel(server->local_list, entry);
3099 /* Notify other routers about the new channel. We send the packet
3100 to our primary route. */
3101 if (broadcast && server->standalone == FALSE)
3102 silc_server_send_new_channel(server, server->router->connection, TRUE,
3103 channel_name, entry->id,
3104 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3107 /* Distribute to backup routers */
3108 if (broadcast && server->server_type == SILC_ROUTER) {
3111 SilcUInt32 name_len = strlen(channel_name);
3112 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3113 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3115 packet = silc_channel_payload_encode(channel_name, name_len,
3116 cid, channel_id_len, entry->mode);
3117 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3118 packet->data, packet->len, FALSE, TRUE);
3120 silc_buffer_free(packet);
3123 server->stat.my_channels++;
3125 if (server->server_type == SILC_ROUTER)
3126 entry->users_resolved = TRUE;
3131 /* Same as above but creates the channel with Channel ID `channel_id. */
3134 silc_server_create_new_channel_with_id(SilcServer server,
3138 SilcChannelID *channel_id,
3141 SilcChannelEntry entry;
3145 SILC_LOG_DEBUG(("Creating new channel"));
3148 cipher = SILC_DEFAULT_CIPHER;
3150 hmac = SILC_DEFAULT_HMAC;
3152 /* Allocate cipher */
3153 if (!silc_cipher_alloc(cipher, &key))
3157 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3158 silc_cipher_free(key);
3162 channel_name = strdup(channel_name);
3164 /* Create the channel */
3165 entry = silc_idlist_add_channel(server->local_list, channel_name,
3166 SILC_CHANNEL_MODE_NONE, channel_id,
3167 NULL, key, newhmac, 0);
3169 silc_cipher_free(key);
3170 silc_hmac_free(newhmac);
3171 silc_free(channel_name);
3175 /* Now create the actual key material */
3176 if (!silc_server_create_channel_key(server, entry,
3177 silc_cipher_get_key_len(key) / 8)) {
3178 silc_idlist_del_channel(server->local_list, entry);
3182 /* Notify other routers about the new channel. We send the packet
3183 to our primary route. */
3184 if (broadcast && server->standalone == FALSE)
3185 silc_server_send_new_channel(server, server->router->connection, TRUE,
3186 channel_name, entry->id,
3187 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3190 /* Distribute to backup routers */
3191 if (broadcast && server->server_type == SILC_ROUTER) {
3194 SilcUInt32 name_len = strlen(channel_name);
3195 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3196 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3198 packet = silc_channel_payload_encode(channel_name, name_len,
3199 cid, channel_id_len, entry->mode);
3200 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3201 packet->data, packet->len, FALSE, TRUE);
3203 silc_buffer_free(packet);
3206 server->stat.my_channels++;
3208 if (server->server_type == SILC_ROUTER)
3209 entry->users_resolved = TRUE;
3214 /* Channel's key re-key timeout callback. */
3216 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3218 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3219 SilcServer server = (SilcServer)rekey->context;
3223 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3226 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3229 /* Generates new channel key. This is used to create the initial channel key
3230 but also to re-generate new key for channel. If `key_len' is provided
3231 it is the bytes of the key length. */
3233 bool silc_server_create_channel_key(SilcServer server,
3234 SilcChannelEntry channel,
3238 unsigned char channel_key[32], hash[32];
3241 SILC_LOG_DEBUG(("Generating channel key"));
3243 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3244 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3248 if (!channel->channel_key)
3249 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3250 channel->channel_key = NULL;
3256 else if (channel->key_len)
3257 len = channel->key_len / 8;
3259 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3261 /* Create channel key */
3262 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3265 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3267 /* Remove old key if exists */
3269 memset(channel->key, 0, channel->key_len / 8);
3270 silc_free(channel->key);
3274 channel->key_len = len * 8;
3275 channel->key = silc_memdup(channel_key, len);
3276 memset(channel_key, 0, sizeof(channel_key));
3278 /* Generate HMAC key from the channel key data and set it */
3280 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3281 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3282 silc_hmac_set_key(channel->hmac, hash,
3283 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3284 memset(hash, 0, sizeof(hash));
3286 if (server->server_type == SILC_ROUTER) {
3287 if (!channel->rekey)
3288 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3289 channel->rekey->context = (void *)server;
3290 channel->rekey->channel = channel;
3291 channel->rekey->key_len = key_len;
3292 if (channel->rekey->task)
3293 silc_schedule_task_del(server->schedule, channel->rekey->task);
3295 channel->rekey->task =
3296 silc_schedule_task_add(server->schedule, 0,
3297 silc_server_channel_key_rekey,
3298 (void *)channel->rekey,
3299 server->config->channel_rekey_secs, 0,
3301 SILC_TASK_PRI_NORMAL);
3307 /* Saves the channel key found in the encoded `key_payload' buffer. This
3308 function is used when we receive Channel Key Payload and also when we're
3309 processing JOIN command reply. Returns entry to the channel. */
3311 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3312 SilcBuffer key_payload,
3313 SilcChannelEntry channel)
3315 SilcChannelKeyPayload payload = NULL;
3316 SilcChannelID *id = NULL;
3317 unsigned char *tmp, hash[32];
3321 SILC_LOG_DEBUG(("Start"));
3323 /* Decode channel key payload */
3324 payload = silc_channel_key_payload_parse(key_payload->data,
3327 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3332 /* Get the channel entry */
3335 /* Get channel ID */
3336 tmp = silc_channel_key_get_id(payload, &tmp_len);
3337 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3343 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3345 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3347 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3348 silc_id_render(id, SILC_ID_CHANNEL)));
3354 tmp = silc_channel_key_get_key(payload, &tmp_len);
3360 cipher = silc_channel_key_get_cipher(payload, NULL);
3366 /* Remove old key if exists */
3368 memset(channel->key, 0, channel->key_len / 8);
3369 silc_free(channel->key);
3370 silc_cipher_free(channel->channel_key);
3373 /* Create new cipher */
3374 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3375 channel->channel_key = NULL;
3380 if (channel->cipher)
3381 silc_free(channel->cipher);
3382 channel->cipher = strdup(cipher);
3385 channel->key_len = tmp_len * 8;
3386 channel->key = silc_memdup(tmp, tmp_len);
3387 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3389 /* Generate HMAC key from the channel key data and set it */
3391 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3392 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3393 silc_hmac_set_key(channel->hmac, hash,
3394 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3396 memset(hash, 0, sizeof(hash));
3397 memset(tmp, 0, tmp_len);
3399 if (server->server_type == SILC_ROUTER) {
3400 if (!channel->rekey)
3401 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3402 channel->rekey->context = (void *)server;
3403 channel->rekey->channel = channel;
3404 if (channel->rekey->task)
3405 silc_schedule_task_del(server->schedule, channel->rekey->task);
3407 channel->rekey->task =
3408 silc_schedule_task_add(server->schedule, 0,
3409 silc_server_channel_key_rekey,
3410 (void *)channel->rekey,
3411 server->config->channel_rekey_secs, 0,
3413 SILC_TASK_PRI_NORMAL);
3419 silc_channel_key_payload_free(payload);
3424 /* Heartbeat callback. This function is set as argument for the
3425 silc_socket_set_heartbeat function. The library will call this function
3426 at the set time interval. */
3428 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3431 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3433 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3435 /* Send the heartbeat */
3436 silc_server_send_heartbeat(hb->server, sock);
3439 /* Returns assembled of all servers in the given ID list. The packet's
3440 form is dictated by the New ID payload. */
3442 static void silc_server_announce_get_servers(SilcServer server,
3443 SilcServerEntry remote,
3445 SilcBuffer *servers,
3446 unsigned long creation_time)
3448 SilcIDCacheList list;
3449 SilcIDCacheEntry id_cache;
3450 SilcServerEntry entry;
3453 /* Go through all clients in the list */
3454 if (silc_idcache_get_all(id_list->servers, &list)) {
3455 if (silc_idcache_list_first(list, &id_cache)) {
3457 entry = (SilcServerEntry)id_cache->context;
3459 /* Do not announce the one we've sending our announcements and
3460 do not announce ourself. Also check the creation time if it's
3462 if ((entry == remote) || (entry == server->id_entry) ||
3463 (creation_time && entry->data.created < creation_time)) {
3464 if (!silc_idcache_list_next(list, &id_cache))
3469 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3471 *servers = silc_buffer_realloc(*servers,
3473 (*servers)->truelen + idp->len :
3475 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3476 silc_buffer_put(*servers, idp->data, idp->len);
3477 silc_buffer_pull(*servers, idp->len);
3478 silc_buffer_free(idp);
3480 if (!silc_idcache_list_next(list, &id_cache))
3485 silc_idcache_list_free(list);
3490 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3496 p = silc_notify_payload_encode(notify, argc, ap);
3502 /* This function is used by router to announce existing servers to our
3503 primary router when we've connected to it. If `creation_time' is non-zero
3504 then only the servers that has been created after the `creation_time'
3505 will be announced. */
3507 void silc_server_announce_servers(SilcServer server, bool global,
3508 unsigned long creation_time,
3509 SilcSocketConnection remote)
3511 SilcBuffer servers = NULL;
3513 SILC_LOG_DEBUG(("Announcing servers"));
3515 /* Get servers in local list */
3516 silc_server_announce_get_servers(server, remote->user_data,
3517 server->local_list, &servers,
3521 /* Get servers in global list */
3522 silc_server_announce_get_servers(server, remote->user_data,
3523 server->global_list, &servers,
3527 silc_buffer_push(servers, servers->data - servers->head);
3528 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3530 /* Send the packet */
3531 silc_server_packet_send(server, remote,
3532 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3533 servers->data, servers->len, TRUE);
3535 silc_buffer_free(servers);
3539 /* Returns assembled packet of all clients in the given ID list. The
3540 packet's form is dictated by the New ID Payload. */
3542 static void silc_server_announce_get_clients(SilcServer server,
3544 SilcBuffer *clients,
3546 unsigned long creation_time)
3548 SilcIDCacheList list;
3549 SilcIDCacheEntry id_cache;
3550 SilcClientEntry client;
3553 unsigned char mode[4];
3555 /* Go through all clients in the list */
3556 if (silc_idcache_get_all(id_list->clients, &list)) {
3557 if (silc_idcache_list_first(list, &id_cache)) {
3559 client = (SilcClientEntry)id_cache->context;
3561 if (creation_time && client->data.created < creation_time) {
3562 if (!silc_idcache_list_next(list, &id_cache))
3567 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3569 *clients = silc_buffer_realloc(*clients,
3571 (*clients)->truelen + idp->len :
3573 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3574 silc_buffer_put(*clients, idp->data, idp->len);
3575 silc_buffer_pull(*clients, idp->len);
3577 SILC_PUT32_MSB(client->mode, mode);
3578 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3579 2, idp->data, idp->len,
3581 *umodes = silc_buffer_realloc(*umodes,
3583 (*umodes)->truelen + tmp->len :
3585 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3586 silc_buffer_put(*umodes, tmp->data, tmp->len);
3587 silc_buffer_pull(*umodes, tmp->len);
3588 silc_buffer_free(tmp);
3590 silc_buffer_free(idp);
3592 if (!silc_idcache_list_next(list, &id_cache))
3597 silc_idcache_list_free(list);
3601 /* This function is used to announce our existing clients to our router
3602 when we've connected to it. If `creation_time' is non-zero then only
3603 the clients that has been created after the `creation_time' will be
3606 void silc_server_announce_clients(SilcServer server,
3607 unsigned long creation_time,
3608 SilcSocketConnection remote)
3610 SilcBuffer clients = NULL;
3611 SilcBuffer umodes = NULL;
3613 SILC_LOG_DEBUG(("Announcing clients"));
3615 /* Get clients in local list */
3616 silc_server_announce_get_clients(server, server->local_list,
3617 &clients, &umodes, creation_time);
3619 /* As router we announce our global list as well */
3620 if (server->server_type == SILC_ROUTER)
3621 silc_server_announce_get_clients(server, server->global_list,
3622 &clients, &umodes, creation_time);
3625 silc_buffer_push(clients, clients->data - clients->head);
3626 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3628 /* Send the packet */
3629 silc_server_packet_send(server, remote,
3630 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3631 clients->data, clients->len, TRUE);
3633 silc_buffer_free(clients);
3637 silc_buffer_push(umodes, umodes->data - umodes->head);
3638 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3640 /* Send the packet */
3641 silc_server_packet_send(server, remote,
3642 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3643 umodes->data, umodes->len, TRUE);
3645 silc_buffer_free(umodes);
3649 /* Returns channel's topic for announcing it */
3651 void silc_server_announce_get_channel_topic(SilcServer server,
3652 SilcChannelEntry channel,
3657 if (channel->topic) {
3658 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3659 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3660 chidp->data, chidp->len,
3662 strlen(channel->topic));
3663 silc_buffer_free(chidp);
3667 /* Returns assembled packets for channel users of the `channel'. */
3669 void silc_server_announce_get_channel_users(SilcServer server,
3670 SilcChannelEntry channel,
3671 SilcBuffer *channel_modes,
3672 SilcBuffer *channel_users,
3673 SilcBuffer *channel_users_modes)
3675 SilcChannelClientEntry chl;
3676 SilcHashTableList htl;
3677 SilcBuffer chidp, clidp, csidp;
3680 unsigned char mode[4], *fkey = NULL;
3681 SilcUInt32 fkey_len = 0;
3684 SILC_LOG_DEBUG(("Start"));
3686 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3687 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
3690 SILC_PUT32_MSB(channel->mode, mode);
3691 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
3692 if (channel->founder_key)
3693 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3695 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
3696 6, csidp->data, csidp->len,
3699 hmac, hmac ? strlen(hmac) : 0,
3700 channel->passphrase,
3701 channel->passphrase ?
3702 strlen(channel->passphrase) : 0,
3706 silc_buffer_realloc(*channel_modes,
3708 (*channel_modes)->truelen + len : len));
3709 silc_buffer_pull_tail(*channel_modes,
3710 ((*channel_modes)->end -
3711 (*channel_modes)->data));
3712 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
3713 silc_buffer_pull(*channel_modes, len);
3714 silc_buffer_free(tmp);
3717 /* Now find all users on the channel */
3718 silc_hash_table_list(channel->user_list, &htl);
3719 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3720 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3723 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
3724 clidp->data, clidp->len,
3725 chidp->data, chidp->len);
3728 silc_buffer_realloc(*channel_users,
3730 (*channel_users)->truelen + len : len));
3731 silc_buffer_pull_tail(*channel_users,
3732 ((*channel_users)->end -
3733 (*channel_users)->data));
3735 silc_buffer_put(*channel_users, tmp->data, tmp->len);
3736 silc_buffer_pull(*channel_users, len);
3737 silc_buffer_free(tmp);
3739 /* CUMODE notify for mode change on the channel */
3740 SILC_PUT32_MSB(chl->mode, mode);
3741 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
3742 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
3743 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
3744 4, csidp->data, csidp->len,
3746 clidp->data, clidp->len,
3749 *channel_users_modes =
3750 silc_buffer_realloc(*channel_users_modes,
3751 (*channel_users_modes ?
3752 (*channel_users_modes)->truelen + len : len));
3753 silc_buffer_pull_tail(*channel_users_modes,
3754 ((*channel_users_modes)->end -
3755 (*channel_users_modes)->data));
3757 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
3758 silc_buffer_pull(*channel_users_modes, len);
3759 silc_buffer_free(tmp);
3761 silc_buffer_free(clidp);
3763 silc_hash_table_list_reset(&htl);
3764 silc_buffer_free(chidp);
3765 silc_buffer_free(csidp);
3768 /* Returns assembled packets for all channels and users on those channels
3769 from the given ID List. The packets are in the form dictated by the
3770 New Channel and New Channel User payloads. */
3772 void silc_server_announce_get_channels(SilcServer server,
3774 SilcBuffer *channels,
3775 SilcBuffer **channel_modes,
3776 SilcBuffer *channel_users,
3777 SilcBuffer **channel_users_modes,
3778 SilcUInt32 *channel_users_modes_c,
3779 SilcBuffer **channel_topics,
3780 SilcChannelID ***channel_ids,
3781 unsigned long creation_time)
3783 SilcIDCacheList list;
3784 SilcIDCacheEntry id_cache;
3785 SilcChannelEntry channel;
3788 SilcUInt16 name_len;
3790 int i = *channel_users_modes_c;
3793 SILC_LOG_DEBUG(("Start"));
3795 /* Go through all channels in the list */
3796 if (silc_idcache_get_all(id_list->channels, &list)) {
3797 if (silc_idcache_list_first(list, &id_cache)) {
3799 channel = (SilcChannelEntry)id_cache->context;
3801 if (creation_time && channel->created < creation_time)
3806 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3807 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3808 name_len = strlen(channel->channel_name);
3811 len = 4 + name_len + id_len + 4;
3813 silc_buffer_realloc(*channels,
3814 (*channels ? (*channels)->truelen +
3816 silc_buffer_pull_tail(*channels,
3817 ((*channels)->end - (*channels)->data));
3818 silc_buffer_format(*channels,
3819 SILC_STR_UI_SHORT(name_len),
3820 SILC_STR_UI_XNSTRING(channel->channel_name,
3822 SILC_STR_UI_SHORT(id_len),
3823 SILC_STR_UI_XNSTRING(cid, id_len),
3824 SILC_STR_UI_INT(channel->mode),
3826 silc_buffer_pull(*channels, len);
3829 /* Channel user modes */
3830 *channel_users_modes = silc_realloc(*channel_users_modes,
3831 sizeof(**channel_users_modes) *
3833 (*channel_users_modes)[i] = NULL;
3834 *channel_modes = silc_realloc(*channel_modes,
3835 sizeof(**channel_modes) * (i + 1));
3836 (*channel_modes)[i] = NULL;
3837 *channel_ids = silc_realloc(*channel_ids,
3838 sizeof(**channel_ids) * (i + 1));
3839 (*channel_ids)[i] = NULL;
3840 silc_server_announce_get_channel_users(server, channel,
3841 &(*channel_modes)[i],
3843 &(*channel_users_modes)[i]);
3844 (*channel_ids)[i] = channel->id;
3846 /* Channel's topic */
3847 *channel_topics = silc_realloc(*channel_topics,
3848 sizeof(**channel_topics) * (i + 1));
3849 (*channel_topics)[i] = NULL;
3850 silc_server_announce_get_channel_topic(server, channel,
3851 &(*channel_topics)[i]);
3854 if (!silc_idcache_list_next(list, &id_cache))
3858 *channel_users_modes_c += i;
3861 silc_idcache_list_free(list);
3865 /* This function is used to announce our existing channels to our router
3866 when we've connected to it. This also announces the users on the
3867 channels to the router. If the `creation_time' is non-zero only the
3868 channels that was created after the `creation_time' are announced.
3869 Note that the channel users are still announced even if the `creation_time'
3872 void silc_server_announce_channels(SilcServer server,
3873 unsigned long creation_time,
3874 SilcSocketConnection remote)
3876 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
3877 SilcBuffer *channel_users_modes = NULL;
3878 SilcBuffer *channel_topics = NULL;
3879 SilcUInt32 channel_users_modes_c = 0;
3880 SilcChannelID **channel_ids = NULL;
3882 SILC_LOG_DEBUG(("Announcing channels and channel users"));
3884 /* Get channels and channel users in local list */
3885 silc_server_announce_get_channels(server, server->local_list,
3886 &channels, &channel_modes,
3888 &channel_users_modes,
3889 &channel_users_modes_c,
3891 &channel_ids, creation_time);
3893 /* Get channels and channel users in global list */
3894 if (server->server_type != SILC_SERVER)
3895 silc_server_announce_get_channels(server, server->global_list,
3896 &channels, &channel_modes,
3898 &channel_users_modes,
3899 &channel_users_modes_c,
3901 &channel_ids, creation_time);
3904 silc_buffer_push(channels, channels->data - channels->head);
3905 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3907 /* Send the packet */
3908 silc_server_packet_send(server, remote,
3909 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3910 channels->data, channels->len,
3913 silc_buffer_free(channels);
3916 if (channel_modes) {
3919 for (i = 0; i < channel_users_modes_c; i++) {
3920 if (!channel_modes[i])
3922 silc_buffer_push(channel_modes[i],
3923 channel_modes[i]->data -
3924 channel_modes[i]->head);
3925 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
3926 channel_modes[i]->len);
3927 silc_server_packet_send_dest(server, remote,
3928 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3929 channel_ids[i], SILC_ID_CHANNEL,
3930 channel_modes[i]->data,
3931 channel_modes[i]->len,
3933 silc_buffer_free(channel_modes[i]);
3935 silc_free(channel_modes);
3938 if (channel_users) {
3939 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3940 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
3941 channel_users->len);
3943 /* Send the packet */
3944 silc_server_packet_send(server, remote,
3945 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3946 channel_users->data, channel_users->len,
3949 silc_buffer_free(channel_users);
3952 if (channel_users_modes) {
3955 for (i = 0; i < channel_users_modes_c; i++) {
3956 if (!channel_users_modes[i])
3958 silc_buffer_push(channel_users_modes[i],
3959 channel_users_modes[i]->data -
3960 channel_users_modes[i]->head);
3961 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
3962 channel_users_modes[i]->len);
3963 silc_server_packet_send_dest(server, remote,
3964 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3965 channel_ids[i], SILC_ID_CHANNEL,
3966 channel_users_modes[i]->data,
3967 channel_users_modes[i]->len,
3969 silc_buffer_free(channel_users_modes[i]);
3971 silc_free(channel_users_modes);
3974 if (channel_topics) {
3977 for (i = 0; i < channel_users_modes_c; i++) {
3978 if (!channel_topics[i])
3981 silc_buffer_push(channel_topics[i],
3982 channel_topics[i]->data -
3983 channel_topics[i]->head);
3984 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
3985 channel_topics[i]->len);
3986 silc_server_packet_send_dest(server, remote,
3987 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3988 channel_ids[i], SILC_ID_CHANNEL,
3989 channel_topics[i]->data,
3990 channel_topics[i]->len,
3992 silc_buffer_free(channel_topics[i]);
3994 silc_free(channel_topics);
3997 silc_free(channel_ids);
4000 /* Failure timeout callback. If this is called then we will immediately
4001 process the received failure. We always process the failure with timeout
4002 since we do not want to blindly trust to received failure packets.
4003 This won't be called (the timeout is cancelled) if the failure was
4004 bogus (it is bogus if remote does not close the connection after sending
4007 SILC_TASK_CALLBACK(silc_server_failure_callback)
4009 SilcServerFailureContext f = (SilcServerFailureContext)context;
4011 if (f->sock->protocol) {
4012 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4013 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4019 /* Assembles user list and users mode list from the `channel'. */
4021 bool silc_server_get_users_on_channel(SilcServer server,
4022 SilcChannelEntry channel,
4023 SilcBuffer *user_list,
4024 SilcBuffer *mode_list,
4025 SilcUInt32 *user_count)
4027 SilcChannelClientEntry chl;
4028 SilcHashTableList htl;
4029 SilcBuffer client_id_list;
4030 SilcBuffer client_mode_list;
4032 SilcUInt32 list_count = 0, len = 0;
4034 if (!silc_hash_table_count(channel->user_list))
4037 silc_hash_table_list(channel->user_list, &htl);
4038 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4039 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4040 silc_hash_table_list_reset(&htl);
4042 client_id_list = silc_buffer_alloc(len);
4044 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4045 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4046 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4048 silc_hash_table_list(channel->user_list, &htl);
4049 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4051 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4052 silc_buffer_put(client_id_list, idp->data, idp->len);
4053 silc_buffer_pull(client_id_list, idp->len);
4054 silc_buffer_free(idp);
4056 /* Client's mode on channel */
4057 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4058 silc_buffer_pull(client_mode_list, 4);
4062 silc_hash_table_list_reset(&htl);
4063 silc_buffer_push(client_id_list,
4064 client_id_list->data - client_id_list->head);
4065 silc_buffer_push(client_mode_list,
4066 client_mode_list->data - client_mode_list->head);
4068 *user_list = client_id_list;
4069 *mode_list = client_mode_list;
4070 *user_count = list_count;
4074 /* Saves users and their modes to the `channel'. */
4076 void silc_server_save_users_on_channel(SilcServer server,
4077 SilcSocketConnection sock,
4078 SilcChannelEntry channel,
4079 SilcClientID *noadd,
4080 SilcBuffer user_list,
4081 SilcBuffer mode_list,
4082 SilcUInt32 user_count)
4087 SilcClientID *client_id;
4088 SilcClientEntry client;
4089 SilcIDCacheEntry cache;
4090 SilcChannelClientEntry chl;
4093 SILC_LOG_DEBUG(("Start"));
4095 for (i = 0; i < user_count; i++) {
4097 SILC_GET16_MSB(idp_len, user_list->data + 2);
4099 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4100 silc_buffer_pull(user_list, idp_len);
4105 SILC_GET32_MSB(mode, mode_list->data);
4106 silc_buffer_pull(mode_list, 4);
4108 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4109 silc_free(client_id);
4115 /* Check if we have this client cached already. */
4116 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4117 server->server_type, &cache);
4119 client = silc_idlist_find_client_by_id(server->global_list,
4120 client_id, server->server_type,
4125 /* If router did not find such Client ID in its lists then this must
4126 be bogus client or some router in the net is buggy. */
4127 if (server->server_type == SILC_ROUTER) {
4128 silc_free(client_id);
4132 /* We don't have that client anywhere, add it. The client is added
4133 to global list since server didn't have it in the lists so it must be
4135 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4136 silc_id_dup(client_id, SILC_ID_CLIENT),
4137 sock->user_data, NULL, 0);
4139 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4140 silc_free(client_id);
4144 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4146 /* Found, if it is from global list we'll assure that we won't
4147 expire it now that the entry is on channel. */
4152 silc_free(client_id);
4154 if (!silc_server_client_on_channel(client, channel, &chl)) {
4155 /* Client was not on the channel, add it. */
4156 chl = silc_calloc(1, sizeof(*chl));
4157 chl->client = client;
4159 chl->channel = channel;
4160 silc_hash_table_add(channel->user_list, chl->client, chl);
4161 silc_hash_table_add(client->channels, chl->channel, chl);
4162 channel->user_count++;
4170 /* Saves channels and channels user modes to the `client'. Removes
4171 the client from those channels that are not sent in the list but
4174 void silc_server_save_user_channels(SilcServer server,
4175 SilcSocketConnection sock,
4176 SilcClientEntry client,
4177 SilcBuffer channels,
4178 SilcBuffer channels_user_modes)
4181 SilcUInt32 *chumodes;
4182 SilcChannelPayload entry;
4183 SilcChannelEntry channel;
4184 SilcChannelID *channel_id;
4185 SilcChannelClientEntry chl;
4186 SilcHashTable ht = NULL;
4187 SilcHashTableList htl;
4191 if (!channels ||!channels_user_modes)
4194 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4195 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4197 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4198 NULL, NULL, NULL, TRUE);
4199 silc_dlist_start(ch);
4200 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4201 /* Check if we have this channel, and add it if we don't have it.
4202 Also add the client on the channel unless it is there already. */
4203 channel_id = silc_channel_get_id_parse(entry);
4204 channel = silc_idlist_find_channel_by_id(server->local_list,
4207 channel = silc_idlist_find_channel_by_id(server->global_list,
4210 if (server->server_type != SILC_SERVER) {
4211 silc_free(channel_id);
4216 /* We don't have that channel anywhere, add it. */
4217 name = silc_channel_get_name(entry, NULL);
4218 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4219 channel_id, server->router,
4222 silc_free(channel_id);
4229 channel->mode = silc_channel_get_mode(entry);
4231 /* Add the client on the channel */
4232 if (!silc_server_client_on_channel(client, channel, &chl)) {
4233 chl = silc_calloc(1, sizeof(*chl));
4234 chl->client = client;
4235 chl->mode = chumodes[i++];
4236 chl->channel = channel;
4237 silc_hash_table_add(channel->user_list, chl->client, chl);
4238 silc_hash_table_add(client->channels, chl->channel, chl);
4239 channel->user_count++;
4242 chl->mode = chumodes[i++];
4245 silc_hash_table_add(ht, channel, channel);
4246 silc_free(channel_id);
4248 silc_channel_payload_list_free(ch);
4249 silc_free(chumodes);
4253 /* Go through the list again and remove client from channels that
4254 are no part of the list. */
4256 silc_hash_table_list(client->channels, &htl);
4257 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4258 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4259 silc_hash_table_del(chl->channel->user_list, chl->client);
4260 silc_hash_table_del(chl->client->channels, chl->channel);
4264 silc_hash_table_list_reset(&htl);
4265 silc_hash_table_free(ht);
4267 silc_hash_table_list(client->channels, &htl);
4268 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4269 silc_hash_table_del(chl->channel->user_list, chl->client);
4270 silc_hash_table_del(chl->client->channels, chl->channel);
4273 silc_hash_table_list_reset(&htl);
4277 /* Lookups route to the client indicated by the `id_data'. The connection
4278 object and internal data object is returned. Returns NULL if route
4279 could not be found to the client. If the `client_id' is specified then
4280 it is used and the `id_data' is ignored. */
4282 SilcSocketConnection
4283 silc_server_get_client_route(SilcServer server,
4284 unsigned char *id_data,
4286 SilcClientID *client_id,
4287 SilcIDListData *idata,
4288 SilcClientEntry *client_entry)
4291 SilcClientEntry client;
4293 SILC_LOG_DEBUG(("Start"));
4296 *client_entry = NULL;
4298 /* Decode destination Client ID */
4300 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4302 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4306 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4309 /* If the destination belongs to our server we don't have to route
4310 the packet anywhere but to send it to the local destination. */
4311 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4315 /* If we are router and the client has router then the client is in
4316 our cell but not directly connected to us. */
4317 if (server->server_type == SILC_ROUTER && client->router) {
4318 /* We are of course in this case the client's router thus the route
4319 to the client is the server who owns the client. So, we will send
4320 the packet to that server. */
4322 *idata = (SilcIDListData)client->router;
4323 return client->router->connection;
4326 /* Seems that client really is directly connected to us */
4328 *idata = (SilcIDListData)client;
4330 *client_entry = client;
4331 return client->connection;
4334 /* Destination belongs to someone not in this server. If we are normal
4335 server our action is to send the packet to our router. */
4336 if (server->server_type != SILC_ROUTER && !server->standalone) {
4339 *idata = (SilcIDListData)server->router;
4340 return server->router->connection;
4343 /* We are router and we will perform route lookup for the destination
4344 and send the packet to fastest route. */
4345 if (server->server_type == SILC_ROUTER && !server->standalone) {
4346 /* Check first that the ID is valid */
4347 client = silc_idlist_find_client_by_id(server->global_list, id,
4350 SilcSocketConnection dst_sock;
4352 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4356 *idata = (SilcIDListData)dst_sock->user_data;
4365 /* Encodes and returns channel list of channels the `client' has joined.
4366 Secret channels are not put to the list. */
4368 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4369 SilcClientEntry client,
4372 SilcBuffer *user_mode_list)
4374 SilcBuffer buffer = NULL;
4375 SilcChannelEntry channel;
4376 SilcChannelClientEntry chl;
4377 SilcHashTableList htl;
4380 SilcUInt16 name_len;
4384 *user_mode_list = NULL;
4386 silc_hash_table_list(client->channels, &htl);
4387 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4388 channel = chl->channel;
4390 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4392 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4395 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4396 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4397 name_len = strlen(channel->channel_name);
4399 len = 4 + name_len + id_len + 4;
4400 buffer = silc_buffer_realloc(buffer,
4401 (buffer ? buffer->truelen + len : len));
4402 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4403 silc_buffer_format(buffer,
4404 SILC_STR_UI_SHORT(name_len),
4405 SILC_STR_UI_XNSTRING(channel->channel_name,
4407 SILC_STR_UI_SHORT(id_len),
4408 SILC_STR_UI_XNSTRING(cid, id_len),
4409 SILC_STR_UI_INT(chl->channel->mode),
4411 silc_buffer_pull(buffer, len);
4414 if (user_mode_list) {
4415 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4417 (*user_mode_list)->truelen + 4 :
4419 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4420 (*user_mode_list)->data));
4421 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4422 silc_buffer_pull(*user_mode_list, 4);
4425 silc_hash_table_list_reset(&htl);
4428 silc_buffer_push(buffer, buffer->data - buffer->head);
4429 if (user_mode_list && *user_mode_list)
4430 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4431 (*user_mode_list)->head));
4436 /* Finds client entry by Client ID and if it is not found then resolves
4437 it using WHOIS command. */
4439 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4440 SilcClientID *client_id,
4441 bool always_resolve,
4444 SilcClientEntry client;
4449 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4452 client = silc_idlist_find_client_by_id(server->global_list,
4453 client_id, TRUE, NULL);
4454 if (!client && server->server_type == SILC_ROUTER)
4458 if (!client && server->standalone)
4461 if (!client || !client->nickname || !client->username ||
4463 SilcBuffer buffer, idp;
4466 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4467 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4468 client->resolve_cmd_ident = ++server->cmd_ident;
4471 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4472 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4473 server->cmd_ident, 1,
4474 4, idp->data, idp->len);
4475 silc_server_packet_send(server, client ? client->router->connection :
4476 server->router->connection,
4477 SILC_PACKET_COMMAND, 0,
4478 buffer->data, buffer->len, FALSE);
4479 silc_buffer_free(idp);
4480 silc_buffer_free(buffer);
4491 /* A timeout callback for the re-key. We will be the initiator of the
4494 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4496 SilcSocketConnection sock = (SilcSocketConnection)context;
4497 SilcIDListData idata = (SilcIDListData)sock->user_data;
4498 SilcServer server = (SilcServer)idata->rekey->context;
4499 SilcProtocol protocol;
4500 SilcServerRekeyInternalContext *proto_ctx;
4502 SILC_LOG_DEBUG(("Start"));
4504 /* Allocate internal protocol context. This is sent as context
4506 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4507 proto_ctx->server = (void *)server;
4508 proto_ctx->sock = sock;
4509 proto_ctx->responder = FALSE;
4510 proto_ctx->pfs = idata->rekey->pfs;
4512 /* Perform rekey protocol. Will call the final callback after the
4513 protocol is over. */
4514 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4515 &protocol, proto_ctx, silc_server_rekey_final);
4516 sock->protocol = protocol;
4518 /* Run the protocol */
4519 silc_protocol_execute(protocol, server->schedule, 0, 0);
4521 /* Re-register re-key timeout */
4522 silc_schedule_task_add(server->schedule, sock->sock,
4523 silc_server_rekey_callback,
4524 context, idata->rekey->timeout, 0,
4525 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4528 /* The final callback for the REKEY protocol. This will actually take the
4529 new key material into use. */
4531 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4533 SilcProtocol protocol = (SilcProtocol)context;
4534 SilcServerRekeyInternalContext *ctx =
4535 (SilcServerRekeyInternalContext *)protocol->context;
4536 SilcServer server = (SilcServer)ctx->server;
4537 SilcSocketConnection sock = ctx->sock;
4539 SILC_LOG_DEBUG(("Start"));
4541 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4542 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4543 /* Error occured during protocol */
4544 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4545 silc_protocol_cancel(protocol, server->schedule);
4546 silc_protocol_free(protocol);
4547 sock->protocol = NULL;
4549 silc_packet_context_free(ctx->packet);
4551 silc_ske_free(ctx->ske);
4556 /* Purge the outgoing data queue to assure that all rekey packets really
4557 go to the network before we quit the protocol. */
4558 silc_server_packet_queue_purge(server, sock);
4561 silc_protocol_free(protocol);
4562 sock->protocol = NULL;
4564 silc_packet_context_free(ctx->packet);
4566 silc_ske_free(ctx->ske);
4570 /* Task callback used to retrieve network statistical information from
4571 router server once in a while. */
4573 SILC_TASK_CALLBACK(silc_server_get_stats)
4575 SilcServer server = (SilcServer)context;
4576 SilcBuffer idp, packet;
4578 SILC_LOG_DEBUG(("Retrieving stats from router"));
4580 if (!server->standalone) {
4581 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4582 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4583 ++server->cmd_ident, 1,
4584 1, idp->data, idp->len);
4585 silc_server_packet_send(server, server->router->connection,
4586 SILC_PACKET_COMMAND, 0, packet->data,
4587 packet->len, FALSE);
4588 silc_buffer_free(packet);
4589 silc_buffer_free(idp);
4592 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4593 server, 120, 0, SILC_TASK_TIMEOUT,