5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2005, 2007 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; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 #include "serverincludes.h"
21 #include "server_internal.h"
23 /************************* Types and definitions ****************************/
25 SILC_TASK_CALLBACK(silc_server_get_stats);
26 SILC_TASK_CALLBACK(silc_server_connect_router);
27 SILC_TASK_CALLBACK(silc_server_do_rekey);
28 SILC_TASK_CALLBACK(silc_server_purge_expired_clients);
29 static void silc_server_accept_new_connection(SilcNetStatus status,
32 static void silc_server_packet_parse_type(SilcServer server,
33 SilcPacketStream sock,
35 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
39 /************************ Static utility functions **************************/
41 /* SKE public key verification callback */
44 silc_server_verify_key(SilcSKE ske,
45 SilcPublicKey public_key,
47 SilcSKEVerifyCbCompletion completion,
48 void *completion_context)
50 SilcPacketStream sock = context;
51 SilcUnknownEntry entry = silc_packet_get_context(sock);
53 SILC_LOG_DEBUG(("Verifying public key"));
55 if (silc_pkcs_get_type(public_key) != SILC_SKE_PK_TYPE_SILC) {
56 SILC_LOG_WARNING(("We don't support %s (%s) port %d public key type %d",
57 entry->hostname, entry->ip, entry->port,
58 silc_pkcs_get_type(public_key)));
59 completion(ske, SILC_SKE_STATUS_UNSUPPORTED_PUBLIC_KEY,
64 /* We accept all keys without explicit verification */
65 completion(ske, SILC_SKE_STATUS_OK, completion_context);
69 /************************ Packet engine callbacks ***************************/
71 /* Packet engine callback to receive a packet */
73 static SilcBool silc_server_packet_receive(SilcPacketEngine engine,
74 SilcPacketStream stream,
76 void *callback_context,
79 SilcServer server = callback_context;
80 SilcIDListData idata = stream_context;
82 /* Packets we do not handle */
83 switch (packet->type) {
84 case SILC_PACKET_HEARTBEAT:
85 case SILC_PACKET_SUCCESS:
86 case SILC_PACKET_FAILURE:
87 case SILC_PACKET_REJECT:
88 case SILC_PACKET_KEY_EXCHANGE:
89 case SILC_PACKET_KEY_EXCHANGE_1:
90 case SILC_PACKET_KEY_EXCHANGE_2:
91 case SILC_PACKET_REKEY_DONE:
92 case SILC_PACKET_CONNECTION_AUTH:
97 /* Only specific packets can come without source ID present. */
98 if ((!packet->src_id ||
99 !(idata->status & SILC_IDLIST_STATUS_REGISTERED)) &&
100 packet->type != SILC_PACKET_NEW_CLIENT &&
101 packet->type != SILC_PACKET_NEW_SERVER &&
102 packet->type != SILC_PACKET_CONNECTION_AUTH_REQUEST &&
103 packet->type != SILC_PACKET_DISCONNECT)
106 /* NEW_CLIENT and NEW_SERVER are accepted only without source ID
107 and for unregistered connection. */
108 if (packet->src_id && (packet->type == SILC_PACKET_NEW_CLIENT ||
109 packet->type == SILC_PACKET_NEW_SERVER) &&
110 (idata->status & SILC_IDLIST_STATUS_REGISTERED))
113 /* Ignore packets from disabled connection */
114 if (idata->status & SILC_IDLIST_STATUS_DISABLED &&
115 packet->type != SILC_PACKET_HEARTBEAT &&
116 packet->type != SILC_PACKET_RESUME_ROUTER &&
117 packet->type != SILC_PACKET_REKEY)
120 /* Check that the the current client ID is same as in the client's packet. */
121 if (idata->conn_type == SILC_CONN_CLIENT) {
122 SilcClientEntry client = (SilcClientEntry)silc_packet_get_context(stream);
123 SilcClientID client_id;
125 if (client->id && packet->src_id &&
126 silc_id_str2id(packet->src_id, packet->src_id_len,
127 packet->src_id_type, &client_id, sizeof(client_id))) {
128 if (!SILC_ID_CLIENT_COMPARE(client->id, &client_id)) {
129 SILC_LOG_DEBUG(("Packet source is not same as sender"));
135 if (server->server_type == SILC_ROUTER) {
136 /* Route the packet if it is not destined to us. Other ID types but
137 server are handled separately after processing them. */
138 if (packet->dst_id &&
139 !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
140 packet->dst_id_type == SILC_ID_SERVER &&
141 idata->conn_type != SILC_CONN_CLIENT &&
142 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
143 SilcPacketStream conn;
144 SilcServerID server_id;
146 silc_id_str2id(packet->dst_id, packet->dst_id_len, packet->dst_id_type,
147 &server_id, sizeof(server_id));
149 conn = silc_server_route_get(server, &server_id, SILC_ID_SERVER);
151 SILC_LOG_WARNING(("Packet to unknown server ID %s, dropped (no route)",
152 silc_id_render(&server_id, SILC_ID_SERVER)));
156 silc_server_packet_route(server, conn, packet);
157 silc_packet_free(packet);
162 /* Broadcast packet if it is marked as broadcast packet and it is
163 originated from router and we are router. */
164 if (server->server_type == SILC_ROUTER &&
165 idata->conn_type == SILC_CONN_ROUTER &&
166 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
167 /* Broadcast to our primary route */
168 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
170 /* If we have backup routers then we need to feed all broadcast
171 data to those servers. */
172 silc_server_backup_broadcast(server, stream, packet);
176 silc_server_packet_parse_type(server, stream, packet);
181 /* Packet engine callback to indicate end of stream */
183 static void silc_server_packet_eos(SilcPacketEngine engine,
184 SilcPacketStream stream,
185 void *callback_context,
186 void *stream_context)
188 SilcServer server = callback_context;
189 SilcIDListData idata = silc_packet_get_context(stream);
191 SILC_LOG_DEBUG(("End of stream received"));
196 if (server->router_conn && server->router_conn->sock == stream &&
197 !server->router && server->standalone) {
198 silc_server_create_connections(server);
200 /* If backup disconnected then mark that resuming will not be allowed */
201 if (server->server_type == SILC_ROUTER && !server->backup_router &&
202 idata->conn_type == SILC_CONN_SERVER) {
203 SilcServerEntry server_entry = (SilcServerEntry)idata;
204 if (server_entry->server_type == SILC_BACKUP_ROUTER)
205 server->backup_closed = TRUE;
208 silc_server_free_sock_user_data(server, stream, NULL);
211 silc_server_close_connection(server, stream);
214 /* Packet engine callback to indicate error */
216 static void silc_server_packet_error(SilcPacketEngine engine,
217 SilcPacketStream stream,
218 SilcPacketError error,
219 void *callback_context,
220 void *stream_context)
222 SilcIDListData idata = silc_packet_get_context(stream);
223 SilcStream sock = silc_packet_stream_get_stream(stream);
230 if (!silc_socket_stream_get_info(sock, NULL, NULL, &ip, &port))
233 SILC_LOG_ERROR(("Connection %s:%d [%s]: %s",
234 SILC_CONNTYPE_STRING(idata->conn_type), ip, port,
235 silc_packet_error_string(error)));
238 /* Packet stream callbacks */
239 static SilcPacketCallbacks silc_server_stream_cbs =
241 silc_server_packet_receive,
242 silc_server_packet_eos,
243 silc_server_packet_error
246 /* Parses the packet type and calls what ever routines the packet type
247 requires. This is done for all incoming packets. */
249 static void silc_server_packet_parse_type(SilcServer server,
250 SilcPacketStream sock,
253 SilcPacketType type = packet->type;
254 SilcIDListData idata = silc_packet_get_context(sock);
256 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
257 silc_get_packet_name(type), packet->flags));
259 /* Parse the packet type */
261 case SILC_PACKET_NOTIFY:
263 * Received notify packet. Server can receive notify packets from
264 * router. Server then relays the notify messages to clients if needed.
266 if (packet->flags & SILC_PACKET_FLAG_LIST)
267 silc_server_notify_list(server, sock, packet);
269 silc_server_notify(server, sock, packet);
273 * Private Message packets
275 case SILC_PACKET_PRIVATE_MESSAGE:
277 * Received private message packet. The packet is coming from either
280 if (packet->flags & SILC_PACKET_FLAG_LIST)
282 idata->last_receive = time(NULL);
283 silc_server_private_message(server, sock, packet);
289 case SILC_PACKET_CHANNEL_MESSAGE:
291 * Received channel message. Channel messages are special packets
292 * (although probably most common ones) thus they are handled
295 if (packet->flags & SILC_PACKET_FLAG_LIST)
297 idata->last_receive = time(NULL);
298 silc_server_channel_message(server, sock, packet);
304 case SILC_PACKET_COMMAND:
306 * Recived command. Processes the command request and allocates the
307 * command context and calls the command.
309 if (packet->flags & SILC_PACKET_FLAG_LIST)
311 server->stat.commands_received++;
312 silc_server_command_process(server, sock, packet);
315 case SILC_PACKET_COMMAND_REPLY:
317 * Received command reply packet. Received command reply to command. It
318 * may be reply to command sent by us or reply to command sent by client
319 * that we've routed further.
321 if (packet->flags & SILC_PACKET_FLAG_LIST)
323 server->stat.commands_received++;
324 silc_server_command_reply(server, sock, packet);
327 case SILC_PACKET_DISCONNECT:
330 char *message = NULL;
331 const char *hostname, *ip;
333 if (packet->flags & SILC_PACKET_FLAG_LIST)
335 if (silc_buffer_len(&packet->buffer) < 1)
338 status = (SilcStatus)packet->buffer.data[0];
339 if (silc_buffer_len(&packet->buffer) > 1 &&
340 silc_utf8_valid(packet->buffer.data + 1, silc_buffer_len(&packet->buffer) - 1))
341 message = silc_memdup(packet->buffer.data + 1,
342 silc_buffer_len(&packet->buffer) - 1);
344 if (!silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL))
347 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s", ip, hostname,
348 silc_get_status_message(status), status,
349 message ? message : ""));
353 /* Do not switch to backup in case of error */
354 server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
356 /* If backup disconnected then mark that resuming will not be allowed */
358 if (server->server_type == SILC_ROUTER && !server->backup_router &&
359 sock->type == SILC_CONN_SERVER && sock->user_data) {
360 SilcServerEntry server_entry = sock->user_data;
361 if (server_entry->server_type == SILC_BACKUP_ROUTER)
362 server->backup_closed = TRUE;
365 /* Handle the disconnection from our end too */
366 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
367 silc_server_free_sock_user_data(server, sock, NULL);
368 SILC_SET_DISCONNECTING(sock);
369 silc_server_close_connection(server, sock);
370 server->backup_noswitch = FALSE;
375 case SILC_PACKET_CHANNEL_KEY:
377 * Received key for channel. As channels are created by the router
378 * the keys are as well. We will distribute the key to all of our
379 * locally connected clients on the particular channel. Router
380 * never receives this channel and thus is ignored.
382 if (packet->flags & SILC_PACKET_FLAG_LIST)
384 silc_server_channel_key(server, sock, packet);
387 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
389 * Private message key packet.
391 if (packet->flags & SILC_PACKET_FLAG_LIST)
393 silc_server_private_message_key(server, sock, packet);
396 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
398 * Connection authentication request packet. When we receive this packet
399 * we will send to the other end information about our mandatory
400 * authentication method for the connection. This packet maybe received
403 if (packet->flags & SILC_PACKET_FLAG_LIST)
405 silc_server_connection_auth_request(server, sock, packet);
408 case SILC_PACKET_NEW_ID:
410 * Received New ID packet. This includes some new ID that has been
411 * created. It may be for client, server or channel. This is the way
412 * to distribute information about new registered entities in the
415 if (packet->flags & SILC_PACKET_FLAG_LIST)
416 silc_server_new_id_list(server, sock, packet);
418 silc_server_new_id(server, sock, packet);
421 case SILC_PACKET_NEW_CLIENT:
423 * Received new client packet. This includes client information that
424 * we will use to create initial client ID. After creating new
425 * ID we will send it to the client.
427 if (packet->flags & SILC_PACKET_FLAG_LIST)
429 silc_server_new_client(server, sock, packet);
432 case SILC_PACKET_NEW_SERVER:
434 * Received new server packet. This includes Server ID and some other
435 * information that we may save. This is received after server has
438 if (packet->flags & SILC_PACKET_FLAG_LIST)
440 silc_server_new_server(server, sock, packet);
443 case SILC_PACKET_NEW_CHANNEL:
445 * Received new channel packet. Information about new channel in the
446 * network are distributed using this packet.
448 if (packet->flags & SILC_PACKET_FLAG_LIST)
449 silc_server_new_channel_list(server, sock, packet);
451 silc_server_new_channel(server, sock, packet);
454 case SILC_PACKET_HEARTBEAT:
456 * Received heartbeat.
458 if (packet->flags & SILC_PACKET_FLAG_LIST)
462 case SILC_PACKET_KEY_AGREEMENT:
464 * Received heartbeat.
466 if (packet->flags & SILC_PACKET_FLAG_LIST)
468 silc_server_key_agreement(server, sock, packet);
471 case SILC_PACKET_REKEY:
473 * Received re-key packet. The sender wants to regenerate the session
476 if (packet->flags & SILC_PACKET_FLAG_LIST)
478 silc_server_rekey(server, sock, packet);
481 case SILC_PACKET_FTP:
483 if (packet->flags & SILC_PACKET_FLAG_LIST)
485 silc_server_ftp(server, sock, packet);
488 case SILC_PACKET_RESUME_CLIENT:
490 if (packet->flags & SILC_PACKET_FLAG_LIST)
492 silc_server_resume_client(server, sock, packet);
495 case SILC_PACKET_RESUME_ROUTER:
496 /* Resume router packet received. This packet is received for backup
497 router resuming protocol. */
498 if (packet->flags & SILC_PACKET_FLAG_LIST)
501 silc_server_backup_resume_router(server, sock, packet);
506 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
511 /****************************** Server API **********************************/
513 /* Allocates a new SILC server object. This has to be done before the server
514 can be used. After allocation one must call silc_server_init to initialize
515 the server. The new allocated server object is returned to the new_server
518 SilcBool silc_server_alloc(SilcServer *new_server)
522 SILC_LOG_DEBUG(("Allocating new server object"));
524 server = silc_calloc(1, sizeof(*server));
527 server->server_type = SILC_SERVER;
528 server->standalone = TRUE;
529 server->local_list = silc_calloc(1, sizeof(*server->local_list));
530 if (!server->local_list)
532 server->global_list = silc_calloc(1, sizeof(*server->global_list));
533 if (!server->global_list)
535 server->pending_commands = silc_dlist_init();
536 if (!server->pending_commands)
538 server->listeners = silc_dlist_init();
539 if (!server->listeners)
541 server->repository = silc_skr_alloc();
542 if (!server->repository)
544 server->conns = silc_dlist_init();
547 server->expired_clients = silc_dlist_init();
548 if (!server->expired_clients)
551 *new_server = server;
556 /* Free's the SILC server object. This is called at the very end before
559 void silc_server_free(SilcServer server)
562 SilcIDCacheEntry cache;
567 silc_server_backup_free(server);
568 silc_server_config_unref(&server->config_ref);
570 silc_rng_free(server->rng);
571 if (server->public_key)
572 silc_pkcs_public_key_free(server->public_key);
573 if (server->private_key)
574 silc_pkcs_private_key_free(server->private_key);
575 if (server->pending_commands)
576 silc_dlist_uninit(server->pending_commands);
577 if (server->id_entry)
578 silc_idlist_del_server(server->local_list, server->id_entry);
580 /* Delete all channels */
581 if (silc_idcache_get_all(server->local_list->channels, &list)) {
582 silc_list_start(list);
583 while ((cache = silc_list_get(list)))
584 silc_idlist_del_channel(server->local_list, cache->context);
586 if (silc_idcache_get_all(server->global_list->channels, &list)) {
587 silc_list_start(list);
588 while ((cache = silc_list_get(list)))
589 silc_idlist_del_channel(server->global_list, cache->context);
592 /* Delete all clients */
593 if (silc_idcache_get_all(server->local_list->clients, &list)) {
594 silc_list_start(list);
595 while ((cache = silc_list_get(list)))
596 silc_idlist_del_client(server->local_list, cache->context);
598 if (silc_idcache_get_all(server->global_list->clients, &list)) {
599 silc_list_start(list);
600 while ((cache = silc_list_get(list)))
601 silc_idlist_del_client(server->global_list, cache->context);
604 /* Delete all servers */
605 if (silc_idcache_get_all(server->local_list->servers, &list)) {
606 silc_list_start(list);
607 while ((cache = silc_list_get(list)))
608 silc_idlist_del_server(server->local_list, cache->context);
610 if (silc_idcache_get_all(server->global_list->servers, &list)) {
611 while ((cache = silc_list_get(list)))
612 silc_idlist_del_server(server->global_list, cache->context);
615 silc_idcache_free(server->local_list->clients);
616 silc_idcache_free(server->local_list->servers);
617 silc_idcache_free(server->local_list->channels);
618 silc_idcache_free(server->global_list->clients);
619 silc_idcache_free(server->global_list->servers);
620 silc_idcache_free(server->global_list->channels);
621 silc_hash_table_free(server->watcher_list);
622 silc_hash_table_free(server->watcher_list_pk);
623 silc_hash_free(server->md5hash);
624 silc_hash_free(server->sha1hash);
626 silc_dlist_uninit(server->listeners);
627 silc_dlist_uninit(server->conns);
628 silc_dlist_uninit(server->expired_clients);
629 silc_skr_free(server->repository);
630 silc_packet_engine_stop(server->packet_engine);
632 silc_free(server->local_list);
633 silc_free(server->global_list);
634 silc_free(server->server_name);
635 silc_free(server->purge_i);
636 silc_free(server->purge_g);
639 silc_hmac_unregister_all();
640 silc_hash_unregister_all();
641 silc_cipher_unregister_all();
642 silc_pkcs_unregister_all();
645 /* Creates a new server listener. */
647 static SilcNetListener
648 silc_server_listen(SilcServer server, const char *server_ip, SilcUInt16 port)
650 SilcNetListener listener;
653 silc_net_tcp_create_listener(&server_ip, 1, port, TRUE,
654 server->config->require_reverse_lookup,
656 silc_server_accept_new_connection, server);
658 SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
666 /* Adds a secondary listener. */
668 SilcBool silc_server_init_secondary(SilcServer server)
673 SilcPacketStream newsocket = NULL;
674 SilcServerConfigServerInfoInterface *interface;
676 for (interface = server->config->server_info->secondary; interface;
677 interface = interface->next, sock++) {
679 if (!silc_server_listen(server,
680 interface->server_ip, interface->port, &sock_list[sock]))
683 /* Set socket to non-blocking mode */
684 silc_net_set_socket_nonblock(sock_list[sock]);
686 /* Add ourselves also to the socket table. The entry allocated above
687 is sent as argument for fast referencing in the future. */
688 silc_socket_alloc(sock_list[sock],
689 SILC_CONN_SERVER, NULL, &newsocket);
690 server->sockets[sock_list[sock]] = newsocket;
691 SILC_SET_LISTENER(newsocket);
693 /* Perform name and address lookups to resolve the listenning address
695 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
697 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
699 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
700 newsocket->hostname ? newsocket->hostname :
701 newsocket->ip ? newsocket->ip : ""));
702 server->stat.conn_failures++;
705 if (!newsocket->hostname)
706 newsocket->hostname = strdup(newsocket->ip);
708 newsocket->port = silc_net_get_local_port(sock);
710 newsocket->user_data = (void *)server->id_entry;
711 silc_schedule_task_add(server->schedule, sock_list[sock],
712 silc_server_accept_new_connection,
713 (void *)server, 0, 0,
715 SILC_TASK_PRI_NORMAL);
721 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
726 /* Initializes the entire SILC server. This is called always before running
727 the server. This is called only once at the initialization of the program.
728 This binds the server to its listenning port. After this function returns
729 one should call silc_server_run to start the server. This returns TRUE
730 when everything is ok to run the server. Configuration file must be
731 read and parsed before calling this. */
733 SilcBool silc_server_init(SilcServer server)
736 SilcServerEntry id_entry;
737 SilcIDListPurge purge;
738 SilcNetListener listener;
742 SILC_LOG_DEBUG(("Initializing server"));
744 server->starttime = time(NULL);
746 /* Take config object for us */
747 silc_server_config_ref(&server->config_ref, server->config,
751 /* Set debugging on if configured */
752 if (server->config->debug_string) {
753 silc_log_debug(TRUE);
754 silc_log_set_debug_string(server->config->debug_string);
756 #endif /* SILC_DEBUG */
758 /* Steal public and private key from the config object */
759 server->public_key = server->config->server_info->public_key;
760 server->private_key = server->config->server_info->private_key;
761 server->config->server_info->public_key = NULL;
762 server->config->server_info->private_key = NULL;
764 /* Register all configured ciphers, PKCS and hash functions. */
765 if (!silc_server_config_register_ciphers(server))
766 silc_cipher_register_default();
767 if (!silc_server_config_register_pkcs(server))
768 silc_pkcs_register_default();
769 if (!silc_server_config_register_hashfuncs(server))
770 silc_hash_register_default();
771 if (!silc_server_config_register_hmacs(server))
772 silc_hmac_register_default();
774 /* Initialize random number generator for the server. */
775 server->rng = silc_rng_alloc();
776 silc_rng_init(server->rng);
777 silc_rng_global_init(server->rng);
779 /* Initialize hash functions for server to use */
780 silc_hash_alloc("md5", &server->md5hash);
781 silc_hash_alloc("sha1", &server->sha1hash);
783 /* Initialize the scheduler */
784 server->schedule = silc_schedule_init(server->config->param.connections_max,
786 if (!server->schedule)
789 /* First, register log files configuration for error output */
790 silc_server_config_setlogfiles(server);
792 /* Initialize ID caches */
793 server->local_list->clients =
794 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
796 server->local_list->servers =
797 silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
799 server->local_list->channels =
800 silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
803 /* These are allocated for normal server as well as these hold some
804 global information that the server has fetched from its router. For
805 router these are used as they are supposed to be used on router. */
806 server->global_list->clients =
807 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
809 server->global_list->servers =
810 silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
812 server->global_list->channels =
813 silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
816 /* Init watcher lists */
817 server->watcher_list =
818 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
819 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
821 if (!server->watcher_list)
823 server->watcher_list_pk =
824 silc_hash_table_alloc(1, silc_hash_public_key, NULL,
825 silc_hash_public_key_compare, NULL,
827 if (!server->watcher_list_pk)
830 /* Create TCP listener */
831 listener = silc_server_listen(
833 server->config->server_info->primary == NULL ? NULL :
834 server->config->server_info->primary->server_ip,
835 server->config->server_info->primary == NULL ? 0 :
836 server->config->server_info->primary->port);
840 silc_dlist_add(server->listeners, listener);
842 /* Create a Server ID for the server. */
843 port = silc_net_listener_get_port(listener, NULL);
844 ip = silc_net_listener_get_ip(listener, NULL);
845 silc_id_create_server_id(ip[0], port[0], server->rng, &id);
854 server->server_name = server->config->server_info->server_name;
855 server->config->server_info->server_name = NULL;
856 silc_id_id2str(server->id, SILC_ID_SERVER, server->id_string,
857 sizeof(server->id_string), &server->id_string_len);
859 /* Add ourselves to the server list. We don't have a router yet
860 beacuse we haven't established a route yet. It will be done later.
861 For now, NULL is sent as router. This allocates new entry to
864 silc_idlist_add_server(server->local_list, strdup(server->server_name),
865 server->server_type, server->id, NULL, NULL);
867 SILC_LOG_ERROR(("Could not add local server to cache"));
870 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
871 server->id_entry = id_entry;
873 /* Create secondary TCP listeners */
874 if (silc_server_init_secondary(server) == FALSE)
877 server->listenning = TRUE;
879 /* Create connections to configured routers. */
880 silc_server_create_connections(server);
882 /* If server connections has been configured then we must be router as
883 normal server cannot have server connections, only router connections. */
884 if (server->config->servers) {
885 SilcServerConfigServer *ptr = server->config->servers;
887 server->server_type = SILC_ROUTER;
889 if (ptr->backup_router) {
890 server->server_type = SILC_BACKUP_ROUTER;
891 server->backup_router = TRUE;
892 server->id_entry->server_type = SILC_BACKUP_ROUTER;
899 /* Register the ID Cache purge task. This periodically purges the ID cache
900 and removes the expired cache entries. */
902 /* Clients local list */
903 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
904 purge->cache = server->local_list->clients;
905 purge->timeout = 600;
906 silc_schedule_task_add_timeout(server->schedule, silc_idlist_purge,
907 (void *)purge, purge->timeout, 0);
909 /* Clients global list */
910 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
911 purge->cache = server->global_list->clients;
912 purge->timeout = 300;
913 silc_schedule_task_add_timeout(server->schedule, silc_idlist_purge,
914 (void *)purge, purge->timeout, 0);
916 /* If we are normal server we'll retrieve network statisticial information
917 once in a while from the router. */
918 if (server->server_type != SILC_ROUTER)
919 silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
922 if (server->server_type == SILC_ROUTER)
923 server->stat.routers++;
925 /* Start packet engine */
926 server->packet_engine =
927 silc_packet_engine_start(server->rng, server->server_type == SILC_ROUTER,
928 &silc_server_stream_cbs, server);
929 if (!server->packet_engine)
932 /* Register client entry expiration timeout */
933 silc_schedule_task_add_timeout(server->schedule,
934 silc_server_purge_expired_clients, server,
937 /* Initialize HTTP server */
938 silc_server_http_init(server);
940 SILC_LOG_DEBUG(("Server initialized"));
942 /* We are done here, return succesfully */
946 silc_server_config_unref(&server->config_ref);
951 /* Task callback to close a socket connection after rehash */
953 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
955 SilcServer server = context;
956 SilcPacketStream sock = server->sockets[fd];
961 SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
962 sock->hostname, sock->port,
963 (sock->type == SILC_CONN_UNKNOWN ? "Unknown" :
964 sock->type == SILC_CONN_CLIENT ? "Client" :
965 sock->type == SILC_CONN_SERVER ? "Server" :
967 silc_schedule_task_del_by_context(server->schedule, sock);
968 silc_server_disconnect_remote(server, sock,
969 SILC_STATUS_ERR_BANNED_FROM_SERVER,
970 "This connection is removed from "
973 silc_server_free_sock_user_data(server, sock, NULL);
977 /* This function basically reads the config file again and switches the config
978 object pointed by the server object. After that, we have to fix various
979 things such as the server_name and the listening ports.
980 Keep in mind that we no longer have the root privileges at this point. */
982 SilcBool silc_server_rehash(SilcServer server)
985 SilcServerConfig newconfig;
987 SILC_LOG_INFO(("Rehashing server"));
989 /* Reset the logging system */
990 silc_log_quick(TRUE);
991 silc_log_flush_all();
993 /* Start the main rehash phase (read again the config file) */
994 newconfig = silc_server_config_alloc(server->config_file, server);
996 SILC_LOG_ERROR(("Rehash FAILED."));
1000 /* Reinit scheduler if necessary */
1001 if (newconfig->param.connections_max > server->config->param.connections_max)
1002 if (!silc_schedule_reinit(server->schedule,
1003 newconfig->param.connections_max))
1006 /* Fix the server_name field */
1007 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
1008 silc_free(server->server_name);
1010 /* Check server name */
1011 server->server_name =
1012 silc_identifier_check(newconfig->server_info->server_name,
1013 strlen(newconfig->server_info->server_name),
1014 SILC_STRING_LOCALE, 256, NULL);
1015 if (!server->server_name) {
1016 SILC_LOG_ERROR(("Malformed server name string '%s'",
1017 server->config->server_info->server_name));
1021 /* Update the idcache list with a fresh pointer */
1022 silc_free(server->id_entry->server_name);
1023 server->id_entry->server_name = strdup(server->server_name);
1024 if (!silc_idcache_del_by_context(server->local_list->servers,
1027 if (!silc_idcache_add(server->local_list->servers,
1028 strdup(server->id_entry->server_name),
1029 server->id_entry->id, server->id_entry, 0, NULL))
1034 silc_server_config_setlogfiles(server);
1036 /* Change new key pair if necessary */
1037 if (newconfig->server_info->public_key &&
1038 !silc_pkcs_public_key_compare(server->public_key,
1039 newconfig->server_info->public_key)) {
1040 silc_pkcs_public_key_free(server->public_key);
1041 silc_pkcs_private_key_free(server->private_key);
1042 server->public_key = newconfig->server_info->public_key;
1043 server->private_key = newconfig->server_info->private_key;
1044 newconfig->server_info->public_key = NULL;
1045 newconfig->server_info->private_key = NULL;
1047 /* Allocate PKCS context for local public and private keys */
1048 silc_pkcs_free(server->pkcs);
1049 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
1051 silc_pkcs_public_key_set(server->pkcs, server->public_key);
1052 silc_pkcs_private_key_set(server->pkcs, server->private_key);
1055 /* Check for unconfigured server and router connections and close
1056 connections that were unconfigured. */
1058 if (server->config->routers) {
1059 SilcServerConfigRouter *ptr;
1060 SilcServerConfigRouter *newptr;
1063 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1066 /* Check whether new config has this one too */
1067 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
1068 if (silc_string_compare(newptr->host, ptr->host) &&
1069 newptr->port == ptr->port &&
1070 newptr->initiator == ptr->initiator) {
1076 if (!found && ptr->host) {
1077 /* Remove this connection */
1078 SilcPacketStream sock;
1079 sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1080 ptr->host, ptr->port);
1081 if (sock && !SILC_IS_LISTENER(sock))
1082 silc_schedule_task_add(server->schedule, sock->sock,
1083 silc_server_rehash_close_connection,
1084 server, 0, 1, SILC_TASK_TIMEOUT,
1085 SILC_TASK_PRI_NORMAL);
1090 if (server->config->servers) {
1091 SilcServerConfigServer *ptr;
1092 SilcServerConfigServer *newptr;
1095 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
1098 /* Check whether new config has this one too */
1099 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
1100 if (silc_string_compare(newptr->host, ptr->host)) {
1106 if (!found && ptr->host) {
1107 /* Remove this connection */
1108 SilcPacketStream sock;
1109 sock = silc_server_find_socket_by_host(server, SILC_CONN_SERVER,
1111 if (sock && !SILC_IS_LISTENER(sock))
1112 silc_schedule_task_add(server->schedule, sock->sock,
1113 silc_server_rehash_close_connection,
1114 server, 0, 1, SILC_TASK_TIMEOUT,
1115 SILC_TASK_PRI_NORMAL);
1120 if (server->config->clients) {
1121 SilcServerConfigClient *ptr;
1122 SilcServerConfigClient *newptr;
1125 for (ptr = server->config->clients; ptr; ptr = ptr->next) {
1128 /* Check whether new config has this one too */
1129 for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
1130 if (silc_string_compare(newptr->host, ptr->host)) {
1136 if (!found && ptr->host) {
1137 /* Remove this connection */
1138 SilcPacketStream sock;
1139 sock = silc_server_find_socket_by_host(server, SILC_CONN_CLIENT,
1142 silc_schedule_task_add(server->schedule, sock->sock,
1143 silc_server_rehash_close_connection,
1144 server, 0, 1, SILC_TASK_TIMEOUT,
1145 SILC_TASK_PRI_NORMAL);
1150 /* Create connections after rehash */
1151 silc_server_create_connections(server);
1153 /* Check whether our router status has changed */
1154 if (newconfig->servers) {
1155 SilcServerConfigServer *ptr = newconfig->servers;
1157 server->server_type = SILC_ROUTER;
1159 if (ptr->backup_router) {
1160 server->server_type = SILC_BACKUP_ROUTER;
1161 server->backup_router = TRUE;
1162 server->id_entry->server_type = SILC_BACKUP_ROUTER;
1169 /* Our old config is gone now. We'll unreference our reference made in
1170 silc_server_init and then destroy it since we are destroying it
1171 underneath the application (layer which called silc_server_init). */
1172 silc_server_config_unref(&server->config_ref);
1173 silc_server_config_destroy(server->config);
1175 /* Take new config context */
1176 server->config = newconfig;
1177 silc_server_config_ref(&server->config_ref, server->config, server->config);
1180 /* Set debugging on if configured */
1181 if (server->config->debug_string) {
1182 silc_log_debug(TRUE);
1183 silc_log_set_debug_string(server->config->debug_string);
1185 #endif /* SILC_DEBUG */
1187 SILC_LOG_DEBUG(("Server rehashed"));
1193 /* The heart of the server. This runs the scheduler thus runs the server.
1194 When this returns the server has been stopped and the program will
1197 void silc_server_run(SilcServer server)
1199 SILC_LOG_INFO(("SILC Server started"));
1201 /* Start the scheduler, the heart of the SILC server. When this returns
1202 the program will be terminated. */
1203 silc_schedule(server->schedule);
1206 /* Stops the SILC server. This function is used to shutdown the server.
1207 This is usually called after the scheduler has returned. After stopping
1208 the server one should call silc_server_free. */
1210 void silc_server_stop(SilcServer server)
1213 SilcPacketStream ps;
1214 SilcNetListener listener;
1216 SILC_LOG_INFO(("SILC Server shutting down"));
1218 server->server_shutdown = TRUE;
1220 /* Close all connections */
1221 if (server->packet_engine) {
1222 list = silc_packet_engine_get_streams(server->packet_engine);
1224 silc_dlist_start(list);
1225 while ((ps = silc_dlist_get(list))) {
1226 SilcIDListData idata = silc_packet_get_context(ps);
1229 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
1231 silc_server_disconnect_remote(server, ps, SILC_STATUS_OK,
1232 "Server is shutting down");
1233 silc_server_free_sock_user_data(server, ps,
1234 "Server is shutting down");
1236 silc_dlist_uninit(list);
1239 /* We are not connected to network anymore */
1240 server->standalone = TRUE;
1242 silc_dlist_start(server->listeners);
1243 while ((listener = silc_dlist_get(server->listeners)))
1244 silc_net_close_listener(listener);
1246 silc_server_http_uninit(server);
1248 silc_schedule_stop(server->schedule);
1249 silc_schedule_uninit(server->schedule);
1250 server->schedule = NULL;
1252 SILC_LOG_DEBUG(("Server stopped"));
1255 /* Purge expired client entries from the server */
1257 SILC_TASK_CALLBACK(silc_server_purge_expired_clients)
1259 SilcServer server = context;
1260 SilcClientEntry client;
1263 SILC_LOG_DEBUG(("Expire timeout"));
1265 silc_dlist_start(server->expired_clients);
1266 while ((client = silc_dlist_get(server->expired_clients))) {
1267 if (client->data.status & SILC_IDLIST_STATUS_REGISTERED)
1270 id_list = (client->data.status & SILC_IDLIST_STATUS_LOCAL ?
1271 server->local_list : server->global_list);
1273 silc_idlist_del_data(client);
1274 silc_idlist_del_client(id_list, client);
1275 silc_dlist_del(server->expired_clients, client);
1278 silc_schedule_task_add_timeout(server->schedule,
1279 silc_server_purge_expired_clients, server,
1284 /******************************* Connecting *********************************/
1286 /* Free connection context */
1288 static void silc_server_connection_free(SilcServerConnection sconn)
1290 silc_dlist_del(sconn->server->conns, sconn);
1291 silc_server_config_unref(&sconn->conn);
1292 silc_free(sconn->remote_host);
1293 silc_free(sconn->backup_replace_ip);
1297 /* Creates connection to a remote router. */
1299 void silc_server_create_connection(SilcServer server,
1301 const char *remote_host, SilcUInt32 port,
1302 SilcServerConnectCallback callback,
1305 SilcServerConnection sconn;
1307 /* Allocate connection object for hold connection specific stuff. */
1308 sconn = silc_calloc(1, sizeof(*sconn));
1311 sconn->remote_host = strdup(remote_host);
1312 sconn->remote_port = port;
1313 sconn->no_reconnect = reconnect == FALSE;
1314 sconn->callback = callback;
1315 sconn->callback_context = context;
1317 silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1321 /* Connection authentication completion callback */
1324 silc_server_ke_auth_compl(SilcConnAuth connauth, SilcBool success,
1327 SilcServerConnection sconn = context;
1328 SilcUnknownEntry entry = silc_packet_get_context(sconn->sock);
1329 SilcServer server = entry->server;
1330 SilcServerConfigServer *conn;
1331 SilcServerConfigConnParams *param;
1332 SilcIDListData idata;
1333 SilcServerEntry id_entry;
1334 unsigned char id[32];
1338 SILC_LOG_DEBUG(("Connection authentication completed"));
1340 if (success == FALSE) {
1341 /* Authentication failed */
1342 /* XXX retry connecting */
1344 silc_server_disconnect_remote(server, sconn->sock,
1345 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1349 SILC_LOG_INFO(("Connected to %s %s",
1350 SILC_CONNTYPE_STRING(entry->data.conn_type),
1351 sconn->remote_host));
1353 /* Create the actual entry for remote entity */
1354 switch (entry->data.conn_type) {
1355 case SILC_CONN_SERVER:
1356 SILC_LOG_DEBUG(("Remote is SILC server"));
1358 /* Add new server. The server must register itself to us before it
1359 becomes registered to SILC network. */
1360 id_entry = silc_idlist_add_server(server->local_list,
1361 strdup(sconn->remote_host),
1362 SILC_SERVER, NULL, NULL, sconn->sock);
1364 silc_server_disconnect_remote(server, sconn->sock,
1365 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1366 silc_server_connection_free(sconn);
1371 silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1374 case SILC_CONN_ROUTER:
1375 SILC_LOG_DEBUG(("Remote is SILC router"));
1377 /* Register to network */
1378 silc_id_id2str(server->id, SILC_ID_SERVER, id, sizeof(id), &id_len);
1379 if (!silc_packet_send_va(sconn->sock, SILC_PACKET_NEW_SERVER, 0,
1380 SILC_STR_UI_SHORT(id_len),
1381 SILC_STR_DATA(id, id_len),
1382 SILC_STR_UI_SHORT(strlen(server->server_name)),
1383 SILC_STR_DATA(server->server_name,
1384 strlen(server->server_name)),
1386 silc_server_disconnect_remote(server, sconn->sock,
1387 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1388 silc_server_connection_free(sconn);
1394 silc_packet_get_ids(sconn->sock, NULL, NULL, NULL, &remote_id);
1396 /* Check that we do not have this ID already */
1397 id_entry = silc_idlist_find_server_by_id(server->local_list,
1398 &remote_id.u.server_id,
1401 silc_idcache_del_by_context(server->local_list->servers, id_entry, NULL);
1403 id_entry = silc_idlist_find_server_by_id(server->global_list,
1404 &remote_id.u.server_id,
1407 silc_idcache_del_by_context(server->global_list->servers, id_entry,
1411 SILC_LOG_DEBUG(("New server id(%s)",
1412 silc_id_render(&remote_id.u.server_id, SILC_ID_SERVER)));
1414 /* Add the connected router to global server list. Router is sent
1415 as NULL since it's local to us. */
1416 id_entry = silc_idlist_add_server(server->global_list,
1417 strdup(sconn->remote_host),
1418 SILC_ROUTER, &remote_id.u.server_id,
1421 silc_server_disconnect_remote(server, sconn->sock,
1422 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1423 silc_server_connection_free(sconn);
1429 silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1430 idata = (SilcIDListData)entry;
1431 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1432 SILC_IDLIST_STATUS_LOCAL);
1434 if (!sconn->backup) {
1435 /* Mark this router our primary router if we're still standalone */
1436 if (server->standalone) {
1437 SILC_LOG_DEBUG(("This connection is our primary router"));
1438 server->id_entry->router = id_entry;
1439 server->router = id_entry;
1440 server->router->server_type = SILC_ROUTER;
1441 server->standalone = FALSE;
1442 server->backup_primary = FALSE;
1444 /* Announce data if we are not backup router (unless not as primary
1445 currently). Backup router announces later at the end of
1446 resuming protocol. */
1447 if (server->backup_router && server->server_type == SILC_ROUTER) {
1448 SILC_LOG_DEBUG(("Announce data after resume protocol"));
1450 /* If we are router then announce our possible servers. Backup
1451 router announces also global servers. */
1452 if (server->server_type == SILC_ROUTER)
1453 silc_server_announce_servers(server,
1454 server->backup_router ? TRUE : FALSE,
1455 0, SILC_PRIMARY_ROUTE(server));
1457 /* Announce our clients and channels to the router */
1458 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1459 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1463 /* If we are backup router then this primary router is whom we are
1465 if (server->server_type == SILC_BACKUP_ROUTER)
1466 silc_server_backup_add(server, server->id_entry, sock->ip,
1467 sconn->remote_port, TRUE);
1471 /* Add this server to be our backup router */
1472 id_entry->server_type = SILC_BACKUP_ROUTER;
1473 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1474 sconn->backup_replace_port, FALSE);
1480 silc_server_disconnect_remote(server, sconn->sock,
1481 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1482 silc_server_connection_free(sconn);
1487 conn = sconn->conn.ref_ptr;
1488 param = &server->config->param;
1489 if (conn && conn->param)
1490 param = conn->param;
1492 /* Register rekey timeout */
1493 sconn->rekey_timeout = param->key_exchange_rekey;
1494 silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
1495 sconn->sock, sconn->rekey_timeout, 0);
1498 /* Perform keepalive. */
1499 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
1500 silc_server_perform_heartbeat,
1504 /* Call the completion callback to indicate that we've connected to
1506 if (sconn && sconn->callback)
1507 (*sconn->callback)(server, id_entry, sconn->callback_context);
1509 /* Free the temporary connection data context */
1511 silc_server_config_unref(&sconn->conn);
1512 silc_free(sconn->remote_host);
1513 silc_free(sconn->backup_replace_ip);
1516 if (sconn == server->router_conn)
1517 server->router_conn = NULL;
1523 /* SKE completion callback */
1525 static void silc_server_ke_completed(SilcSKE ske, SilcSKEStatus status,
1526 SilcSKESecurityProperties prop,
1527 SilcSKEKeyMaterial keymat,
1528 SilcSKERekeyMaterial rekey,
1531 SilcServerConnection sconn = context;
1532 SilcUnknownEntry entry = silc_packet_get_context(sconn->sock);
1533 SilcServer server = entry->server;
1534 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1535 SilcAuthMethod auth_meth = SILC_AUTH_NONE;
1536 void *auth_data = NULL;
1537 SilcUInt32 auth_data_len = 0;
1538 SilcConnAuth connauth;
1539 SilcCipher send_key, receive_key;
1540 SilcHmac hmac_send, hmac_receive;
1543 if (status != SILC_SKE_STATUS_OK) {
1545 SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
1546 silc_ske_map_status(status), entry->hostname, entry->ip));
1548 /* XXX retry connecting */
1550 silc_server_disconnect_remote(server, sconn->sock,
1551 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1552 silc_server_connection_free(sconn);
1556 SILC_LOG_DEBUG(("Setting keys into use"));
1558 /* Set the keys into use. The data will be encrypted after this. */
1559 if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
1560 &hmac_send, &hmac_receive, &hash)) {
1562 /* XXX retry connecting */
1564 /* Error setting keys */
1566 silc_server_disconnect_remote(server, sconn->sock,
1567 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1568 silc_server_connection_free(sconn);
1571 silc_packet_set_keys(sconn->sock, send_key, receive_key, hmac_send,
1572 hmac_receive, FALSE);
1574 SILC_LOG_DEBUG(("Starting connection authentication"));
1576 connauth = silc_connauth_alloc(server->schedule, ske,
1577 server->config->conn_auth_timeout);
1579 /* XXX retry connecting */
1581 /** Error allocating auth protocol */
1583 silc_server_disconnect_remote(server, sconn->sock,
1584 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1585 silc_server_connection_free(sconn);
1589 /* Get authentication method */
1591 if (conn->passphrase) {
1592 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1593 auth_meth = SILC_AUTH_PUBLIC_KEY;
1594 auth_data = server->private_key;
1596 auth_meth = SILC_AUTH_PASSWORD;
1597 auth_data = conn->passphrase;
1598 auth_data_len = conn->passphrase_len;
1601 auth_meth = SILC_AUTH_PUBLIC_KEY;
1602 auth_data = server->private_key;
1606 /* Start connection authentication */
1607 silc_connauth_initiator(connauth, server->server_type == SILC_ROUTER ?
1608 SILC_CONN_ROUTER : SILC_CONN_SERVER, auth_meth,
1609 auth_data, auth_data_len,
1610 silc_server_ke_auth_compl, sconn);
1613 /* Function that is called when the network connection to a router has
1614 been established. This will continue with the key exchange protocol
1615 with the remote router. */
1617 void silc_server_start_key_exchange(SilcServerConnection sconn)
1619 SilcServer server = sconn->server;
1620 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1621 SilcUnknownEntry entry;
1622 SilcSKEParamsStruct params;
1625 /* Cancel any possible retry timeouts */
1626 silc_schedule_task_del_by_context(server->schedule, sconn);
1628 /* Create packet stream */
1629 sconn->sock = silc_packet_stream_create(server->packet_engine,
1630 server->schedule, sconn->stream);
1632 SILC_LOG_ERROR(("Cannot connect: cannot create packet stream"));
1633 silc_stream_destroy(sconn->stream);
1634 silc_server_connection_free(sconn);
1637 server->stat.conn_num++;
1639 /* Set source ID to packet stream */
1640 if (!silc_packet_set_ids(sconn->sock, SILC_ID_SERVER, server->id,
1642 silc_packet_stream_destroy(sconn->sock);
1643 silc_server_connection_free(sconn);
1647 /* Create entry for remote entity */
1648 entry = silc_calloc(1, sizeof(*entry));
1650 silc_packet_stream_destroy(sconn->sock);
1651 silc_server_connection_free(sconn);
1654 entry->server = server;
1655 silc_packet_set_context(sconn->sock, entry);
1657 /* Set Key Exchange flags from configuration, but fall back to global
1659 memset(¶ms, 0, sizeof(params));
1660 SILC_GET_SKE_FLAGS(conn, params.flags);
1661 if (server->config->param.key_exchange_pfs)
1662 params.flags |= SILC_SKE_SP_FLAG_PFS;
1664 /* Start SILC Key Exchange protocol */
1665 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1666 ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
1667 server->public_key, server->private_key, sconn->sock);
1670 silc_packet_stream_destroy(sconn->sock);
1671 silc_server_connection_free(sconn);
1674 silc_ske_set_callbacks(ske, silc_server_verify_key,
1675 silc_server_ke_completed, sconn->sock);
1677 /* Start key exchange protocol */
1678 params.version = silc_version_string;
1679 params.timeout_secs = server->config->key_exchange_timeout;
1680 silc_ske_initiator(ske, sconn->sock, ¶ms, NULL);
1683 /* Timeout callback that will be called to retry connecting to remote
1684 router. This is used by both normal and router server. This will wait
1685 before retrying the connecting. The timeout is generated by exponential
1686 backoff algorithm. */
1688 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
1690 SilcServerConnection sconn = context;
1691 SilcServer server = sconn->server;
1692 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1693 SilcServerConfigConnParams *param =
1694 (conn->param ? conn->param : &server->config->param);
1696 SILC_LOG_INFO(("Retrying connecting to %s:%d", sconn->remote_host,
1697 sconn->remote_port));
1699 /* Calculate next timeout */
1700 if (sconn->retry_count >= 1) {
1701 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
1702 if (sconn->retry_timeout > param->reconnect_interval_max)
1703 sconn->retry_timeout = param->reconnect_interval_max;
1705 sconn->retry_timeout = param->reconnect_interval;
1707 sconn->retry_count++;
1708 sconn->retry_timeout = sconn->retry_timeout +
1709 (silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER);
1711 /* If we've reached max retry count, give up. */
1712 if ((sconn->retry_count > param->reconnect_count) &&
1713 !param->reconnect_keep_trying) {
1714 SILC_LOG_ERROR(("Could not connect, giving up"));
1715 silc_server_connection_free(sconn);
1719 SILC_LOG_DEBUG(("Retrying connecting %d seconds", sconn->retry_timeout));
1721 /* We will lookup a fresh pointer later */
1722 silc_server_config_unref(&sconn->conn);
1724 /* Wait before retrying */
1725 silc_schedule_task_del_by_context(server->schedule, sconn);
1726 silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1727 sconn, sconn->retry_timeout, 0);
1730 /* Callback for async connection to remote router */
1732 static void silc_server_connection_established(SilcNetStatus status,
1736 SilcServerConnection sconn = context;
1737 SilcServer server = sconn->server;
1739 silc_schedule_task_del_by_context(server->schedule, sconn);
1744 SILC_LOG_DEBUG(("Connection to %s:%d established",
1745 sconn->remote_host, sconn->remote_port));
1747 /* Continue with key exchange protocol */
1748 sconn->stream = stream;
1749 silc_server_start_key_exchange(sconn);
1752 case SILC_NET_UNKNOWN_IP:
1753 case SILC_NET_UNKNOWN_HOST:
1754 SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1755 sconn->remote_host, sconn->remote_port,
1756 silc_net_get_error_string(status)));
1757 silc_server_connection_free(sconn);
1761 SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1762 sconn->remote_host, sconn->remote_port,
1763 silc_net_get_error_string(status)));
1764 if (!sconn->no_reconnect) {
1765 silc_schedule_task_add_timeout(sconn->server->schedule,
1766 silc_server_connect_to_router_retry,
1769 silc_server_connection_free(sconn);
1775 /* Generic routine to use connect to a router. */
1777 SILC_TASK_CALLBACK(silc_server_connect_router)
1779 SilcServerConnection sconn = context;
1780 SilcServer server = sconn->server;
1781 SilcServerConfigRouter *rconn;
1783 silc_schedule_task_del_by_context(server->schedule, sconn);
1785 /* Don't connect if we are shutting down. */
1786 if (server->server_shutdown) {
1787 silc_server_connection_free(sconn);
1791 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1792 (sconn->backup ? "backup router" : "router"),
1793 sconn->remote_host, sconn->remote_port));
1795 if (!server->no_conf) {
1796 /* Find connection configuration */
1797 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1798 sconn->remote_port);
1800 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1801 (sconn->backup ? "backup router" : "router"),
1802 sconn->remote_host, sconn->remote_port));
1803 silc_server_connection_free(sconn);
1806 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1809 /* Connect to remote host */
1811 silc_net_tcp_connect((!server->config->server_info->primary ? NULL :
1812 server->config->server_info->primary->server_ip),
1813 sconn->remote_host, sconn->remote_port,
1814 server->schedule, silc_server_connection_established,
1817 SILC_LOG_ERROR(("Could not connect to router %s:%d",
1818 sconn->remote_host, sconn->remote_port));
1819 silc_server_connection_free(sconn);
1823 /* Add to connection list */
1824 silc_dlist_add(server->conns, sconn);
1827 /* This function connects to our primary router or if we are a router this
1828 establishes all our primary routes. This is called at the start of the
1829 server to do authentication and key exchange with our router - called
1832 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1834 SilcServer server = context;
1835 SilcServerConnection sconn;
1836 SilcServerConfigRouter *ptr;
1838 /* Don't connect if we are shutting down. */
1839 if (server->server_shutdown)
1842 SILC_LOG_DEBUG(("We are %s",
1843 (server->server_type == SILC_SERVER ?
1844 "normal server" : server->server_type == SILC_ROUTER ?
1845 "router" : "backup router/normal server")));
1848 if (!server->config->routers) {
1849 /* There wasn't a configured router, we will continue but we don't
1850 have a connection to outside world. We will be standalone server. */
1851 SILC_LOG_DEBUG(("No router(s), we are standalone"));
1852 server->standalone = TRUE;
1856 /* Create the connections to all our routes */
1857 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1859 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1860 ptr->backup_router ? "Backup router" : "Router",
1861 ptr->initiator ? "Initiator" : "Responder",
1862 ptr->host, ptr->port));
1864 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1865 ptr->initiator == FALSE && !server->backup_router &&
1866 !silc_server_config_get_backup_router(server))
1867 server->wait_backup = TRUE;
1869 if (!ptr->initiator)
1872 /* Check whether we are connecting or connected to this host already */
1873 if (silc_server_num_sockets_by_remote(server,
1874 silc_net_is_ip(ptr->host) ?
1876 silc_net_is_ip(ptr->host) ?
1877 NULL : ptr->host, ptr->port)) {
1878 SILC_LOG_DEBUG(("We are already connected to %s:%d",
1879 ptr->host, ptr->port));
1881 /* If we don't have primary router and this connection is our
1882 primary router we are in desync. Reconnect to the primary. */
1883 if (server->standalone && !server->router) {
1885 SilcPacketStream sock;
1886 SilcServerConfigRouter *primary =
1887 silc_server_config_get_primary_router(server);
1890 sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1891 ptr->host, ptr->port);
1894 server->backup_noswitch = TRUE;
1896 if (sock->user_data)
1897 silc_server_free_sock_user_data(server, sock, NULL);
1898 silc_server_disconnect_remote(server, sock, 0, NULL);
1900 server->backup_noswitch = FALSE;
1901 SILC_LOG_DEBUG(("Reconnecting to primary router"));
1907 /* Allocate connection object for hold connection specific stuff. */
1908 sconn = silc_calloc(1, sizeof(*sconn));
1911 sconn->remote_host = strdup(ptr->host);
1912 sconn->remote_port = ptr->port;
1913 sconn->backup = ptr->backup_router;
1914 if (sconn->backup) {
1915 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1916 sconn->backup_replace_port = ptr->backup_replace_port;
1920 if (!server->router_conn && !sconn->backup)
1921 server->router_conn = sconn;
1924 silc_server_connect_router(server->schedule, server, SILC_TASK_EXPIRE,
1930 /************************ Accepting new connection **************************/
1932 /* After this is called, server don't wait for backup router anymore.
1933 This gets called automatically even after we have backup router
1934 connection established. */
1936 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1938 SilcServer server = context;
1939 server->wait_backup = FALSE;
1942 /* Authentication data callback */
1945 silc_server_accept_get_auth(SilcConnAuth connauth,
1946 SilcConnectionType conn_type,
1947 unsigned char **passphrase,
1948 SilcUInt32 *passphrase_len,
1949 SilcSKR *repository,
1952 SilcPacketStream sock = context;
1953 SilcUnknownEntry entry = silc_packet_get_context(sock);
1954 SilcServer server = entry->server;
1956 SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
1958 /* Remote end is client */
1959 if (conn_type == SILC_CONN_CLIENT) {
1960 SilcServerConfigClient *cconfig = entry->cconfig.ref_ptr;
1964 *passphrase = cconfig->passphrase;
1965 *passphrase_len = cconfig->passphrase_len;
1966 if (cconfig->publickeys)
1967 *repository = server->repository;
1969 entry->data.conn_type = conn_type;
1973 /* Remote end is server */
1974 if (conn_type == SILC_CONN_SERVER) {
1975 SilcServerConfigServer *sconfig = entry->sconfig.ref_ptr;
1979 *passphrase = sconfig->passphrase;
1980 *passphrase_len = sconfig->passphrase_len;
1981 if (sconfig->publickeys)
1982 *repository = server->repository;
1984 entry->data.conn_type = conn_type;
1988 /* Remote end is router */
1989 if (conn_type == SILC_CONN_ROUTER) {
1990 SilcServerConfigRouter *rconfig = entry->rconfig.ref_ptr;
1994 *passphrase = rconfig->passphrase;
1995 *passphrase_len = rconfig->passphrase_len;
1996 if (rconfig->publickeys)
1997 *repository = server->repository;
1999 entry->data.conn_type = conn_type;
2006 /* Authentication completion callback. */
2009 silc_server_accept_auth_compl(SilcConnAuth connauth, SilcBool success,
2012 SilcPacketStream sock = context;
2013 SilcUnknownEntry entry = silc_packet_get_context(sock);
2014 SilcIDListData idata = (SilcIDListData)entry;
2015 SilcServer server = entry->server;
2016 SilcServerConfigConnParams *param = &server->config->param;
2017 SilcServerConnection sconn;
2019 const char *hostname;
2022 silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2023 NULL, &hostname, NULL, &port);
2025 if (success == FALSE) {
2026 /* Authentication failed */
2027 SILC_LOG_INFO(("Authentication failed for %s (%s) [%s]", entry->hostname,
2028 entry->ip, SILC_CONNTYPE_STRING(entry->data.conn_type)));
2029 server->stat.auth_failures++;
2030 silc_server_disconnect_remote(server, sock,
2031 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2035 SILC_LOG_DEBUG(("Checking whether connection is allowed"));
2037 switch (entry->data.conn_type) {
2038 case SILC_CONN_CLIENT:
2040 SilcClientEntry client;
2041 SilcServerConfigClient *conn = entry->cconfig.ref_ptr;
2043 /* Verify whether this connection is after all allowed to connect */
2044 if (!silc_server_connection_allowed(server, sock, entry->data.conn_type,
2045 &server->config->param,
2047 silc_connauth_get_ske(connauth))) {
2048 server->stat.auth_failures++;
2052 /* If we are primary router and we have backup router configured
2053 but it has not connected to use yet, do not accept any other
2055 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2056 !server->backup_router) {
2057 SilcServerConfigRouter *router;
2058 router = silc_server_config_get_backup_router(server);
2059 if (router && strcmp(server->config->server_info->primary->server_ip,
2061 silc_server_find_socket_by_host(server,
2063 router->backup_replace_ip, 0)) {
2064 SILC_LOG_INFO(("Will not accept connections because we do "
2065 "not have backup router connection established"));
2066 silc_server_disconnect_remote(server, sock,
2067 SILC_STATUS_ERR_PERM_DENIED,
2068 "We do not have connection to backup "
2069 "router established, try later");
2070 server->stat.auth_failures++;
2072 /* From here on, wait 20 seconds for the backup router to appear. */
2073 silc_schedule_task_add_timeout(server->schedule,
2074 silc_server_backup_router_wait,
2075 (void *)server, 20, 0);
2080 SILC_LOG_DEBUG(("Remote host is client"));
2081 SILC_LOG_INFO(("Connection %s (%s) is client", entry->hostname,
2084 /* Add the client to the client ID cache. The nickname and Client ID
2085 and other information is created after we have received NEW_CLIENT
2086 packet from client. */
2087 client = silc_idlist_add_client(server->local_list,
2088 NULL, NULL, NULL, NULL, NULL, sock);
2090 SILC_LOG_ERROR(("Could not add new client to cache"));
2091 server->stat.auth_failures++;
2092 silc_server_disconnect_remote(server, sock,
2093 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2096 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2099 server->stat.my_clients++;
2100 server->stat.clients++;
2101 server->stat.cell_clients++;
2103 /* Get connection parameters */
2105 param = conn->param;
2107 if (!param->keepalive_secs)
2108 param->keepalive_secs = server->config->param.keepalive_secs;
2110 if (!param->qos && server->config->param.qos) {
2111 param->qos = server->config->param.qos;
2112 param->qos_rate_limit = server->config->param.qos_rate_limit;
2113 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2114 param->qos_limit_sec = server->config->param.qos_limit_sec;
2115 param->qos_limit_usec = server->config->param.qos_limit_usec;
2118 /* Check if to be anonymous connection */
2119 if (param->anonymous)
2120 client->mode |= SILC_UMODE_ANONYMOUS;
2123 /* Add public key to repository */
2124 if (!silc_server_get_public_key_by_client(server, client, NULL))
2125 silc_skr_add_public_key_simple(server->repository,
2126 entry->data.public_key,
2127 SILC_SKR_USAGE_IDENTIFICATION, client,
2130 id_entry = (void *)client;
2134 case SILC_CONN_SERVER:
2135 case SILC_CONN_ROUTER:
2137 SilcServerEntry new_server;
2138 SilcBool initiator = FALSE;
2139 SilcBool backup_local = FALSE;
2140 SilcBool backup_router = FALSE;
2141 char *backup_replace_ip = NULL;
2142 SilcUInt16 backup_replace_port = 0;
2143 SilcServerConfigServer *sconn = entry->sconfig.ref_ptr;
2144 SilcServerConfigRouter *rconn = entry->rconfig.ref_ptr;
2146 /* If we are backup router and this is incoming server connection
2147 and we do not have connection to primary router, do not allow
2149 if (server->server_type == SILC_BACKUP_ROUTER &&
2150 entry->data.conn_type == SILC_CONN_SERVER &&
2151 !SILC_PRIMARY_ROUTE(server)) {
2152 SILC_LOG_INFO(("Will not accept server connection because we do "
2153 "not have primary router connection established"));
2154 silc_server_disconnect_remote(server, sock,
2155 SILC_STATUS_ERR_PERM_DENIED,
2156 "We do not have connection to primary "
2157 "router established, try later");
2158 server->stat.auth_failures++;
2162 if (entry->data.conn_type == SILC_CONN_ROUTER) {
2163 /* Verify whether this connection is after all allowed to connect */
2164 if (!silc_server_connection_allowed(server, sock,
2165 entry->data.conn_type,
2166 &server->config->param,
2167 rconn ? rconn->param : NULL,
2168 silc_connauth_get_ske(connauth))) {
2169 server->stat.auth_failures++;
2175 param = rconn->param;
2177 if (!param->keepalive_secs)
2178 param->keepalive_secs = server->config->param.keepalive_secs;
2180 if (!param->qos && server->config->param.qos) {
2181 param->qos = server->config->param.qos;
2182 param->qos_rate_limit = server->config->param.qos_rate_limit;
2183 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2184 param->qos_limit_sec = server->config->param.qos_limit_sec;
2185 param->qos_limit_usec = server->config->param.qos_limit_usec;
2189 initiator = rconn->initiator;
2190 backup_local = rconn->backup_local;
2191 backup_router = rconn->backup_router;
2192 backup_replace_ip = rconn->backup_replace_ip;
2193 backup_replace_port = rconn->backup_replace_port;
2197 if (entry->data.conn_type == SILC_CONN_SERVER) {
2198 /* Verify whether this connection is after all allowed to connect */
2199 if (!silc_server_connection_allowed(server, sock,
2200 entry->data.conn_type,
2201 &server->config->param,
2202 sconn ? sconn->param : NULL,
2203 silc_connauth_get_ske(connauth))) {
2204 server->stat.auth_failures++;
2209 param = sconn->param;
2211 if (!param->keepalive_secs)
2212 param->keepalive_secs = server->config->param.keepalive_secs;
2214 if (!param->qos && server->config->param.qos) {
2215 param->qos = server->config->param.qos;
2216 param->qos_rate_limit = server->config->param.qos_rate_limit;
2217 param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2218 param->qos_limit_sec = server->config->param.qos_limit_sec;
2219 param->qos_limit_usec = server->config->param.qos_limit_usec;
2223 backup_router = sconn->backup_router;
2227 /* If we are primary router and we have backup router configured
2228 but it has not connected to use yet, do not accept any other
2231 if (server->wait_backup && server->server_type == SILC_ROUTER &&
2232 !server->backup_router && !backup_router) {
2233 SilcServerConfigRouter *router;
2234 router = silc_server_config_get_backup_router(server);
2235 if (router && strcmp(server->config->server_info->primary->server_ip,
2237 silc_server_find_socket_by_host(server,
2239 router->backup_replace_ip, 0)) {
2240 SILC_LOG_INFO(("Will not accept connections because we do "
2241 "not have backup router connection established"));
2242 silc_server_disconnect_remote(server, sock,
2243 SILC_STATUS_ERR_PERM_DENIED,
2244 "We do not have connection to backup "
2245 "router established, try later");
2246 server->stat.auth_failures++;
2248 /* From here on, wait 20 seconds for the backup router to appear. */
2249 silc_schedule_task_add_timeout(server->schedule,
2250 silc_server_backup_router_wait,
2251 (void *)server, 20, 0);
2257 SILC_LOG_DEBUG(("Remote host is %s",
2258 entry->data.conn_type == SILC_CONN_SERVER ?
2259 "server" : (backup_router ?
2260 "backup router" : "router")));
2261 SILC_LOG_INFO(("Connection %s (%s) is %s", entry->hostname,
2262 entry->ip, entry->data.conn_type == SILC_CONN_SERVER ?
2263 "server" : (backup_router ?
2264 "backup router" : "router")));
2266 /* Add the server into server cache. The server name and Server ID
2267 is updated after we have received NEW_SERVER packet from the
2268 server. We mark ourselves as router for this server if we really
2271 silc_idlist_add_server((entry->data.conn_type == SILC_CONN_SERVER ?
2272 server->local_list : (backup_router ?
2273 server->local_list :
2274 server->global_list)),
2276 (entry->data.conn_type == SILC_CONN_SERVER ?
2277 SILC_SERVER : SILC_ROUTER),
2279 (entry->data.conn_type == SILC_CONN_SERVER ?
2280 server->id_entry : (backup_router ?
2281 server->id_entry : NULL)),
2284 SILC_LOG_ERROR(("Could not add new server to cache"));
2285 silc_server_disconnect_remote(server, sock,
2286 SILC_STATUS_ERR_AUTH_FAILED, NULL);
2287 server->stat.auth_failures++;
2290 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2292 id_entry = (void *)new_server;
2294 /* If the incoming connection is router and marked as backup router
2295 then add it to be one of our backups */
2296 if (entry->data.conn_type == SILC_CONN_ROUTER && backup_router) {
2297 /* Change it back to SERVER type since that's what it really is. */
2299 entry->data.conn_type = SILC_CONN_SERVER;
2300 new_server->server_type = SILC_BACKUP_ROUTER;
2302 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2303 ("Backup router %s is now online",
2306 /* Remove the backup waiting with timeout */
2307 silc_schedule_task_add_timeout(server->schedule,
2308 silc_server_backup_router_wait,
2309 (void *)server, 10, 0);
2313 if (entry->data.conn_type == SILC_CONN_SERVER) {
2314 server->stat.my_servers++;
2315 server->stat.servers++;
2317 server->stat.my_routers++;
2318 server->stat.routers++;
2321 /* Check whether this connection is to be our primary router connection
2322 if we do not already have the primary route. */
2323 if (!backup_router &&
2324 server->standalone && entry->data.conn_type == SILC_CONN_ROUTER) {
2325 if (silc_server_config_is_primary_route(server) && !initiator)
2328 SILC_LOG_DEBUG(("We are not standalone server anymore"));
2329 server->standalone = FALSE;
2330 if (!server->id_entry->router) {
2331 server->id_entry->router = id_entry;
2332 server->router = id_entry;
2344 /* Add connection to server->conns so that we know we have connection
2346 sconn = silc_calloc(1, sizeof(*sconn));
2347 sconn->server = server;
2349 sconn->remote_host = strdup(hostname);
2350 sconn->remote_port = port;
2351 silc_dlist_add(server->conns, sconn);
2352 idata->sconn = sconn;
2353 idata->last_receive = time(NULL);
2355 /* Add the common data structure to the ID entry. */
2356 silc_idlist_add_data(id_entry, (SilcIDListData)entry);
2357 silc_packet_set_context(sock, id_entry);
2359 /* Connection has been fully established now. Everything is ok. */
2360 SILC_LOG_DEBUG(("New connection authenticated"));
2363 /* Perform keepalive. */
2364 if (param->keepalive_secs)
2365 silc_socket_set_heartbeat(sock, param->keepalive_secs, server,
2366 silc_server_perform_heartbeat,
2370 /* Perform Quality of Service */
2372 silc_socket_stream_set_qos(silc_packet_stream_get_stream(sock),
2373 param->qos_rate_limit, param->qos_bytes_limit,
2374 param->qos_limit_sec, param->qos_limit_usec);
2376 silc_server_config_unref(&entry->cconfig);
2377 silc_server_config_unref(&entry->sconfig);
2378 silc_server_config_unref(&entry->rconfig);
2382 silc_ske_free(silc_connauth_get_ske(connauth));
2383 silc_connauth_free(connauth);
2386 /* SKE completion callback. We set the new keys into use here. */
2389 silc_server_accept_completed(SilcSKE ske, SilcSKEStatus status,
2390 SilcSKESecurityProperties prop,
2391 SilcSKEKeyMaterial keymat,
2392 SilcSKERekeyMaterial rekey,
2395 SilcPacketStream sock = context;
2396 SilcUnknownEntry entry = silc_packet_get_context(sock);
2397 SilcIDListData idata = (SilcIDListData)entry;
2398 SilcServer server = entry->server;
2399 SilcConnAuth connauth;
2400 SilcCipher send_key, receive_key;
2401 SilcHmac hmac_send, hmac_receive;
2404 if (status != SILC_SKE_STATUS_OK) {
2406 SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
2407 silc_ske_map_status(status), entry->hostname, entry->ip));
2409 silc_server_disconnect_remote(server, sock,
2410 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2414 SILC_LOG_DEBUG(("Setting keys into use"));
2416 /* Set the keys into use. The data will be encrypted after this. */
2417 if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
2418 &hmac_send, &hmac_receive, &hash)) {
2419 /* Error setting keys */
2421 silc_server_disconnect_remote(server, sock,
2422 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2425 silc_packet_set_keys(sock, send_key, receive_key, hmac_send,
2426 hmac_receive, FALSE);
2428 idata->rekey = rekey;
2429 idata->public_key = silc_pkcs_public_key_copy(prop->public_key);
2431 SILC_LOG_DEBUG(("Starting connection authentication"));
2432 server->stat.auth_attempts++;
2434 connauth = silc_connauth_alloc(server->schedule, ske,
2435 server->config->conn_auth_timeout);
2437 /** Error allocating auth protocol */
2439 silc_server_disconnect_remote(server, sock,
2440 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2444 /* Start connection authentication */
2445 silc_connauth_responder(connauth, silc_server_accept_get_auth,
2446 silc_server_accept_auth_compl, sock);
2449 /* Accept new TCP connection */
2451 static void silc_server_accept_new_connection(SilcNetStatus status,
2455 SilcServer server = context;
2456 SilcPacketStream packet_stream;
2457 SilcServerConfigClient *cconfig = NULL;
2458 SilcServerConfigServer *sconfig = NULL;
2459 SilcServerConfigRouter *rconfig = NULL;
2460 SilcServerConfigDeny *deny;
2461 SilcUnknownEntry entry;
2463 SilcSKEParamsStruct params;
2464 char *hostname, *ip;
2467 SILC_LOG_DEBUG(("Accepting new connection"));
2469 /* Check for maximum allowed connections */
2470 server->stat.conn_attempts++;
2471 if (silc_dlist_count(server->conns) >
2472 server->config->param.connections_max) {
2473 SILC_LOG_ERROR(("Refusing connection, server is full"));
2474 server->stat.conn_failures++;
2475 silc_stream_destroy(stream);
2479 /* Get hostname, IP and port */
2480 if (!silc_socket_stream_get_info(stream, NULL, (const char **)&hostname,
2481 (const char **)&ip, &port)) {
2482 /* Bad socket stream */
2483 server->stat.conn_failures++;
2484 silc_stream_destroy(stream);
2488 /* Create packet stream */
2489 packet_stream = silc_packet_stream_create(server->packet_engine,
2490 server->schedule, stream);
2491 if (!packet_stream) {
2492 SILC_LOG_ERROR(("Refusing connection, cannot create packet stream"));
2493 server->stat.conn_failures++;
2494 silc_stream_destroy(stream);
2497 server->stat.conn_num++;
2499 /* Set source ID to packet stream */
2500 if (!silc_packet_set_ids(packet_stream, SILC_ID_SERVER, server->id,
2503 server->stat.conn_failures++;
2504 silc_packet_stream_destroy(packet_stream);
2508 /* Check whether this connection is denied to connect to us. */
2509 deny = silc_server_config_find_denied(server, ip);
2511 deny = silc_server_config_find_denied(server, hostname);
2513 /* The connection is denied */
2514 SILC_LOG_INFO(("Connection %s (%s) is denied", hostname, ip));
2515 silc_server_disconnect_remote(server, packet_stream,
2516 SILC_STATUS_ERR_BANNED_FROM_SERVER,
2521 /* Check whether we have configured this sort of connection at all. We
2522 have to check all configurations since we don't know what type of
2523 connection this is. */
2524 if (!(cconfig = silc_server_config_find_client(server, ip)))
2525 cconfig = silc_server_config_find_client(server, hostname);
2526 if (!(sconfig = silc_server_config_find_server_conn(server, ip)))
2527 sconfig = silc_server_config_find_server_conn(server, hostname);
2528 if (server->server_type == SILC_ROUTER)
2529 if (!(rconfig = silc_server_config_find_router_conn(server, ip, port)))
2530 rconfig = silc_server_config_find_router_conn(server, hostname, port);
2531 if (!cconfig && !sconfig && !rconfig) {
2532 SILC_LOG_INFO(("Connection %s (%s) is not allowed", hostname, ip));
2533 server->stat.conn_failures++;
2534 silc_server_disconnect_remote(server, packet_stream,
2535 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
2539 /* The connection is allowed */
2540 entry = silc_calloc(1, sizeof(*entry));
2542 server->stat.conn_failures++;
2543 silc_server_disconnect_remote(server, packet_stream,
2544 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2547 entry->hostname = hostname;
2550 entry->server = server;
2551 silc_packet_set_context(packet_stream, entry);
2553 silc_server_config_ref(&entry->cconfig, server->config, cconfig);
2554 silc_server_config_ref(&entry->sconfig, server->config, sconfig);
2555 silc_server_config_ref(&entry->rconfig, server->config, rconfig);
2557 /* Take flags for key exchange. Since we do not know what type of connection
2558 this is, we go through all found configurations and use the global ones
2559 as well. This will result always into strictest key exchange flags. */
2560 memset(¶ms, 0, sizeof(params));
2561 SILC_GET_SKE_FLAGS(cconfig, params.flags);
2562 SILC_GET_SKE_FLAGS(sconfig, params.flags);
2563 SILC_GET_SKE_FLAGS(rconfig, params.flags);
2564 if (server->config->param.key_exchange_pfs)
2565 params.flags |= SILC_SKE_SP_FLAG_PFS;
2567 SILC_LOG_INFO(("Incoming connection %s (%s)", hostname, ip));
2568 server->stat.conn_attempts++;
2570 /* Start SILC Key Exchange protocol */
2571 SILC_LOG_DEBUG(("Starting key exchange protocol"));
2572 ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2573 server->public_key, server->private_key,
2576 server->stat.conn_failures++;
2577 silc_server_disconnect_remote(server, packet_stream,
2578 SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2581 silc_ske_set_callbacks(ske, silc_server_verify_key,
2582 silc_server_accept_completed, packet_stream);
2584 /* Start key exchange protocol */
2585 params.version = silc_version_string;
2586 params.timeout_secs = server->config->key_exchange_timeout;
2587 silc_ske_responder(ske, packet_stream, ¶ms);
2591 /********************************** Rekey ***********************************/
2593 /* Initiator rekey completion callback */
2595 static void silc_server_rekey_completion(SilcSKE ske,
2596 SilcSKEStatus status,
2597 const SilcSKESecurityProperties prop,
2598 const SilcSKEKeyMaterial keymat,
2599 SilcSKERekeyMaterial rekey,
2602 SilcPacketStream sock = context;
2603 SilcIDListData idata = silc_packet_get_context(sock);
2604 SilcServer server = idata->sconn->server;
2606 idata->sconn->op = NULL;
2607 if (status != SILC_SKE_STATUS_OK) {
2608 SILC_LOG_ERROR(("Error during rekey protocol with %s",
2609 idata->sconn->remote_host));
2613 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2614 idata->sconn->remote_host, idata->sconn->remote_port,
2615 SILC_CONNTYPE_STRING(idata->conn_type)));
2617 /* Save rekey data for next rekey */
2618 idata->rekey = rekey;
2620 /* Register new rekey timeout */
2621 silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2622 sock, idata->sconn->rekey_timeout, 0);
2625 /* Rekey callback. Start rekey as initiator */
2627 SILC_TASK_CALLBACK(silc_server_do_rekey)
2629 SilcServer server = app_context;
2630 SilcPacketStream sock = context;
2631 SilcIDListData idata = silc_packet_get_context(sock);
2634 /* Do not execute rekey with disabled connections */
2635 if (idata->status & SILC_IDLIST_STATUS_DISABLED)
2638 /* If another protocol is active do not start rekey */
2639 if (idata->sconn->op) {
2640 SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
2641 silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2646 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2647 idata->sconn->remote_host, idata->sconn->remote_port,
2648 SILC_CONNTYPE_STRING(idata->conn_type)));
2651 ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2652 server->public_key, server->private_key, sock);
2656 /* Set SKE callbacks */
2657 silc_ske_set_callbacks(ske, NULL, silc_server_rekey_completion, sock);
2660 idata->sconn->op = silc_ske_rekey_initiator(ske, sock, idata->rekey);
2663 /* Responder rekey completion callback */
2666 silc_server_rekey_resp_completion(SilcSKE ske,
2667 SilcSKEStatus status,
2668 const SilcSKESecurityProperties prop,
2669 const SilcSKEKeyMaterial keymat,
2670 SilcSKERekeyMaterial rekey,
2673 SilcPacketStream sock = context;
2674 SilcIDListData idata = silc_packet_get_context(sock);
2676 idata->sconn->op = NULL;
2677 if (status != SILC_SKE_STATUS_OK) {
2678 SILC_LOG_ERROR(("Error during rekey protocol with %s",
2679 idata->sconn->remote_host));
2683 SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2684 idata->sconn->remote_host, idata->sconn->remote_port,
2685 SILC_CONNTYPE_STRING(idata->conn_type)));
2687 /* Save rekey data for next rekey */
2688 idata->rekey = rekey;
2691 /* Start rekey as responder */
2693 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
2696 SilcIDListData idata = silc_packet_get_context(sock);
2699 SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2700 idata->sconn->remote_host, idata->sconn->remote_port,
2701 SILC_CONNTYPE_STRING(idata->conn_type)));
2704 ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2705 server->public_key, server->private_key, sock);
2707 silc_packet_free(packet);
2711 /* Set SKE callbacks */
2712 silc_ske_set_callbacks(ske, NULL, silc_server_rekey_resp_completion, sock);
2715 idata->sconn->op = silc_ske_rekey_responder(ske, sock, idata->rekey,
2720 /****************************** Disconnection *******************************/
2722 /* Destroys packet stream. */
2724 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2726 silc_packet_stream_destroy(context);
2729 /* Closes connection to socket connection */
2731 void silc_server_close_connection(SilcServer server,
2732 SilcPacketStream sock)
2734 SilcIDListData idata = silc_packet_get_context(sock);
2736 const char *hostname;
2740 /* If any protocol is active cancel its execution. It will call
2741 the final callback which will finalize the disconnection. */
2742 if (sock->protocol && sock->protocol->protocol &&
2743 sock->protocol->protocol->type != SILC_PROTOCOL_SERVER_BACKUP) {
2744 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2745 silc_protocol_cancel(sock->protocol, server->schedule);
2746 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2747 silc_protocol_execute_final(sock->protocol, server->schedule);
2748 sock->protocol = NULL;
2753 memset(tmp, 0, sizeof(tmp));
2754 // silc_socket_get_error(sock, tmp, sizeof(tmp));
2755 silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2756 NULL, &hostname, NULL, &port);
2757 SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", hostname, port,
2758 idata ? SILC_CONNTYPE_STRING(idata->conn_type) : "",
2759 tmp[0] ? tmp : ""));
2761 // silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
2763 /* Close connection with timeout */
2764 server->stat.conn_num--;
2765 silc_schedule_task_add_timeout(server->schedule,
2766 silc_server_close_connection_final,
2770 /* Sends disconnect message to remote connection and disconnects the
2773 void silc_server_disconnect_remote(SilcServer server,
2774 SilcPacketStream sock,
2775 SilcStatus status, ...)
2777 unsigned char buf[512];
2784 SILC_LOG_DEBUG(("Disconnecting remote host"));
2786 va_start(ap, status);
2787 cp = va_arg(ap, char *);
2789 silc_vsnprintf(buf, sizeof(buf), cp, ap);
2792 /* Send SILC_PACKET_DISCONNECT */
2793 silc_packet_send_va(sock, SILC_PACKET_DISCONNECT, 0,
2794 SILC_STR_UI_CHAR(status),
2795 SILC_STR_UI8_STRING(cp ? buf : NULL),
2798 /* Close connection */
2799 silc_server_close_connection(server, sock);
2802 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2804 SilcClientEntry client = context;
2806 assert(!silc_hash_table_count(client->channels));
2808 silc_idlist_del_data(client);
2809 // silc_idcache_purge_by_context(server->local_list->clients, client);
2812 /* Frees client data and notifies about client's signoff. */
2814 void silc_server_free_client_data(SilcServer server,
2815 SilcPacketStream sock,
2816 SilcClientEntry client,
2818 const char *signoff)
2820 SILC_LOG_DEBUG(("Freeing client data"));
2823 /* Check if anyone is watching this nickname */
2824 if (server->server_type == SILC_ROUTER)
2825 silc_server_check_watcher_list(server, client, NULL,
2826 SILC_NOTIFY_TYPE_SIGNOFF);
2828 /* Send SIGNOFF notify to routers. */
2830 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2831 SILC_BROADCAST(server), client->id,
2835 /* Remove client from all channels */
2837 silc_server_remove_from_channels(server, NULL, client,
2838 TRUE, (char *)signoff, TRUE, FALSE);
2840 silc_server_remove_from_channels(server, NULL, client,
2841 FALSE, NULL, FALSE, FALSE);
2843 /* Remove this client from watcher list if it is */
2844 silc_server_del_from_watcher_list(server, client);
2846 /* Remove client's public key from repository, this will free it too. */
2847 if (client->data.public_key) {
2848 silc_skr_del_public_key(server->repository, client->data.public_key,
2850 client->data.public_key = NULL;
2853 /* Update statistics */
2854 server->stat.my_clients--;
2855 server->stat.clients--;
2856 if (server->stat.cell_clients)
2857 server->stat.cell_clients--;
2858 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2859 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2860 silc_schedule_task_del_by_context(server->schedule, client);
2862 /* We will not delete the client entry right away. We will take it
2863 into history (for WHOWAS command) for 5 minutes, unless we're
2864 shutting down server. */
2865 if (!server->server_shutdown) {
2866 silc_schedule_task_add_timeout(server->schedule,
2867 silc_server_free_client_data_timeout,
2869 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2870 client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
2872 client->router = NULL;
2873 client->connection = NULL;
2875 /* Delete directly since we're shutting down server */
2876 silc_idlist_del_data(client);
2877 silc_idlist_del_client(server->local_list, client);
2881 /* Frees user_data pointer from socket connection object. This also sends
2882 appropriate notify packets to the network to inform about leaving
2885 void silc_server_free_sock_user_data(SilcServer server,
2886 SilcPacketStream sock,
2887 const char *signoff_message)
2889 SilcIDListData idata = silc_packet_get_context(sock);
2894 switch (idata->conn_type) {
2895 case SILC_CONN_CLIENT:
2897 SilcClientEntry client_entry = (SilcClientEntry)idata;
2898 silc_server_free_client_data(server, sock, client_entry, TRUE,
2900 silc_packet_set_context(sock, NULL);
2904 case SILC_CONN_SERVER:
2905 case SILC_CONN_ROUTER:
2907 SilcServerEntry user_data = (SilcServerEntry)idata;
2908 SilcServerEntry backup_router = NULL;
2910 SILC_LOG_DEBUG(("Freeing server data"));
2913 backup_router = silc_server_backup_get(server, user_data->id);
2915 if (!server->backup_router && server->server_type == SILC_ROUTER &&
2916 backup_router == server->id_entry &&
2917 idata->conn_type != SILC_CONN_ROUTER)
2918 backup_router = NULL;
2920 if (server->server_shutdown || server->backup_noswitch)
2921 backup_router = NULL;
2923 /* If this was our primary router connection then we're lost to
2924 the outside world. */
2925 if (server->router == user_data) {
2926 /* Check whether we have a backup router connection */
2927 if (!backup_router || backup_router == user_data) {
2928 if (!server->no_reconnect)
2929 silc_server_create_connections(server);
2930 server->id_entry->router = NULL;
2931 server->router = NULL;
2932 server->standalone = TRUE;
2933 server->backup_primary = FALSE;
2934 backup_router = NULL;
2936 if (server->id_entry != backup_router) {
2937 SILC_LOG_INFO(("New primary router is backup router %s",
2938 backup_router->server_name));
2939 server->id_entry->router = backup_router;
2940 server->router = backup_router;
2941 server->router_connect = time(0);
2942 server->backup_primary = TRUE;
2943 backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
2945 /* Send START_USE to backup router to indicate we have switched */
2946 silc_server_backup_send_start_use(server,
2947 backup_router->connection,
2950 SILC_LOG_INFO(("We are now new primary router in this cell"));
2951 server->id_entry->router = NULL;
2952 server->router = NULL;
2953 server->standalone = TRUE;
2956 /* We stop here to take a breath */
2960 if (server->backup_router) {
2961 server->server_type = SILC_ROUTER;
2963 /* We'll need to constantly try to reconnect to the primary
2964 router so that we'll see when it comes back online. */
2965 silc_server_backup_reconnect(server, sock->ip, sock->port,
2966 silc_server_backup_connected,
2971 /* Mark this connection as replaced */
2972 silc_server_backup_replaced_add(server, user_data->id,
2975 } else if (backup_router) {
2976 SILC_LOG_INFO(("Enabling the use of backup router %s",
2977 backup_router->server_name));
2979 /* Mark this connection as replaced */
2980 silc_server_backup_replaced_add(server, user_data->id,
2982 } else if (server->server_type == SILC_SERVER &&
2983 idata->conn_type == SILC_CONN_ROUTER) {
2984 /* Reconnect to the router (backup) */
2985 if (!server->no_reconnect)
2986 silc_server_create_connections(server);
2989 if (user_data->server_name)
2990 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2991 ("Server %s signoff", user_data->server_name));
2993 if (!backup_router) {
2994 /* Remove all servers that are originated from this server, and
2995 remove the clients of those servers too. */
2996 silc_server_remove_servers_by_server(server, user_data, TRUE);
2999 /* Remove the clients that this server owns as they will become
3000 invalid now too. For backup router the server is actually
3001 coming from the primary router, so mark that as the owner
3003 if (server->server_type == SILC_BACKUP_ROUTER &&
3004 sock->type == SILC_CONN_SERVER)
3005 silc_server_remove_clients_by_server(server, server->router,
3009 silc_server_remove_clients_by_server(server, user_data,
3012 /* Remove channels owned by this server */
3013 if (server->server_type == SILC_SERVER)
3014 silc_server_remove_channels_by_server(server, user_data);
3016 /* Enable local server connections that may be disabled */
3017 silc_server_local_servers_toggle_enabled(server, TRUE);
3019 /* Update the client entries of this server to the new backup
3020 router. If we are the backup router we also resolve the real
3021 servers for the clients. After updating is over this also
3022 removes the clients that this server explicitly owns. */
3023 silc_server_update_clients_by_server(server, user_data,
3024 backup_router, TRUE);
3026 /* If we are router and just lost our primary router (now standlaone)
3027 we remove everything that was behind it, since we don't know
3029 if (server->server_type == SILC_ROUTER && server->standalone)
3030 /* Remove all servers that are originated from this server, and
3031 remove the clients of those servers too. */
3032 silc_server_remove_servers_by_server(server, user_data, TRUE);
3034 /* Finally remove the clients that are explicitly owned by this
3035 server. They go down with the server. */
3036 silc_server_remove_clients_by_server(server, user_data,
3039 /* Update our server cache to use the new backup router too. */
3040 silc_server_update_servers_by_server(server, user_data, backup_router);
3041 if (server->server_type == SILC_SERVER)
3042 silc_server_update_channels_by_server(server, user_data,
3045 /* Send notify about primary router going down to local operators */
3046 if (server->backup_router)
3047 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3048 SILC_NOTIFY_TYPE_NONE,
3049 ("%s switched to backup router %s "
3050 "(we are primary router now)",
3051 server->server_name, server->server_name));
3052 else if (server->router)
3053 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3054 SILC_NOTIFY_TYPE_NONE,
3055 ("%s switched to backup router %s",
3056 server->server_name,
3057 server->router->server_name));
3059 server->backup_noswitch = FALSE;
3061 /* Free the server entry */
3062 silc_server_backup_del(server, user_data);
3063 silc_server_backup_replaced_del(server, user_data);
3064 silc_idlist_del_data(user_data);
3065 if (!silc_idlist_del_server(server->local_list, user_data))
3066 silc_idlist_del_server(server->global_list, user_data);
3067 if (idata->conn_type == SILC_CONN_SERVER) {
3068 server->stat.my_servers--;
3069 server->stat.servers--;
3071 server->stat.my_routers--;
3072 server->stat.routers--;
3074 if (server->server_type == SILC_ROUTER)
3075 server->stat.cell_servers--;
3077 if (backup_router && backup_router != server->id_entry) {
3078 /* Announce all of our stuff that was created about 5 minutes ago.
3079 The backup router knows all the other stuff already. */
3080 if (server->server_type == SILC_ROUTER)
3081 silc_server_announce_servers(server, FALSE, time(0) - 300,
3082 backup_router->connection);
3084 /* Announce our clients and channels to the router */
3085 silc_server_announce_clients(server, time(0) - 300,
3086 backup_router->connection);
3087 silc_server_announce_channels(server, time(0) - 300,
3088 backup_router->connection);
3091 silc_packet_set_context(sock, NULL);
3097 SilcUnknownEntry entry = (SilcUnknownEntry)idata;
3099 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3101 silc_idlist_del_data(idata);
3103 silc_packet_set_context(sock, NULL);
3109 /* Removes client from all channels it has joined. This is used when client
3110 connection is disconnected. If the client on a channel is last, the
3111 channel is removed as well. This sends the SIGNOFF notify types. */
3113 void silc_server_remove_from_channels(SilcServer server,
3114 SilcPacketStream sock,
3115 SilcClientEntry client,
3117 const char *signoff_message,
3121 SilcChannelEntry channel;
3122 SilcChannelClientEntry chl;
3123 SilcHashTableList htl;
3124 SilcBuffer clidp = NULL;
3129 if (notify && !client->id)
3132 SILC_LOG_DEBUG(("Removing client %s from joined channels",
3133 notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3136 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3141 /* Remove the client from all channels. The client is removed from
3142 the channels' user list. */
3143 silc_hash_table_list(client->channels, &htl);
3144 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3145 channel = chl->channel;
3147 /* Remove channel if this is last client leaving the channel, unless
3148 the channel is permanent. */
3149 if (server->server_type != SILC_SERVER &&
3150 silc_hash_table_count(channel->user_list) < 2) {
3151 silc_server_channel_delete(server, channel);
3155 silc_hash_table_del(client->channels, channel);
3156 silc_hash_table_del(channel->user_list, client);
3157 channel->user_count--;
3159 /* If there is no global users on the channel anymore mark the channel
3160 as local channel. Do not check if the removed client is local client. */
3161 if (server->server_type == SILC_SERVER && channel->global_users &&
3162 chl->client->router && !silc_server_channel_has_global(channel))
3163 channel->global_users = FALSE;
3165 memset(chl, 'A', sizeof(*chl));
3168 /* Update statistics */
3169 if (SILC_IS_LOCAL(client))
3170 server->stat.my_chanclients--;
3171 if (server->server_type == SILC_ROUTER) {
3172 server->stat.cell_chanclients--;
3173 server->stat.chanclients--;
3176 /* If there is not at least one local user on the channel then we don't
3177 need the channel entry anymore, we can remove it safely, unless the
3178 channel is permanent channel */
3179 if (server->server_type == SILC_SERVER &&
3180 !silc_server_channel_has_local(channel)) {
3181 /* Notify about leaving client if this channel has global users. */
3182 if (notify && channel->global_users)
3183 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3184 SILC_NOTIFY_TYPE_SIGNOFF,
3185 signoff_message ? 2 : 1,
3186 clidp->data, silc_buffer_len(clidp),
3187 signoff_message, signoff_message ?
3188 strlen(signoff_message) : 0);
3190 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3191 silc_server_channel_delete(server, channel);
3195 /* Send notify to channel about client leaving SILC and channel too */
3197 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3198 SILC_NOTIFY_TYPE_SIGNOFF,
3199 signoff_message ? 2 : 1,
3200 clidp->data, silc_buffer_len(clidp),
3201 signoff_message, signoff_message ?
3202 strlen(signoff_message) : 0);
3204 if (killed && clidp) {
3205 /* Remove the client from channel's invite list */
3206 if (channel->invite_list &&
3207 silc_hash_table_count(channel->invite_list)) {
3209 SilcArgumentPayload iargs;
3210 ab = silc_argument_payload_encode_one(NULL, clidp->data,
3211 silc_buffer_len(clidp), 3);
3212 iargs = silc_argument_payload_parse(ab->data, silc_buffer_len(ab), 1);
3213 silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3214 silc_buffer_free(ab);
3215 silc_argument_payload_free(iargs);
3219 /* Don't create keys if we are shutting down */
3220 if (server->server_shutdown)
3223 /* Re-generate channel key if needed */
3224 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3225 if (!silc_server_create_channel_key(server, channel, 0))
3228 /* Send the channel key to the channel. The key of course is not sent
3229 to the client who was removed from the channel. */
3230 silc_server_send_channel_key(server, client->connection, channel,
3231 server->server_type == SILC_ROUTER ?
3232 FALSE : !server->standalone);
3236 silc_hash_table_list_reset(&htl);
3238 silc_buffer_free(clidp);
3241 /* Removes client from one channel. This is used for example when client
3242 calls LEAVE command to remove itself from the channel. Returns TRUE
3243 if channel still exists and FALSE if the channel is removed when
3244 last client leaves the channel. If `notify' is FALSE notify messages
3247 SilcBool silc_server_remove_from_one_channel(SilcServer server,
3248 SilcPacketStream sock,
3249 SilcChannelEntry channel,
3250 SilcClientEntry client,
3253 SilcChannelClientEntry chl;
3256 SILC_LOG_DEBUG(("Removing %s from channel %s",
3257 silc_id_render(client->id, SILC_ID_CLIENT),
3258 channel->channel_name));
3260 /* Get the entry to the channel, if this client is not on the channel
3262 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3265 /* Remove channel if this is last client leaving the channel, unless
3266 the channel is permanent. */
3267 if (server->server_type != SILC_SERVER &&
3268 silc_hash_table_count(channel->user_list) < 2) {
3269 silc_server_channel_delete(server, channel);
3273 silc_hash_table_del(client->channels, channel);
3274 silc_hash_table_del(channel->user_list, client);
3275 channel->user_count--;
3277 /* If there is no global users on the channel anymore mark the channel
3278 as local channel. Do not check if the client is local client. */
3279 if (server->server_type == SILC_SERVER && channel->global_users &&
3280 chl->client->router && !silc_server_channel_has_global(channel))
3281 channel->global_users = FALSE;
3283 memset(chl, 'O', sizeof(*chl));
3286 /* Update statistics */
3287 if (SILC_IS_LOCAL(client))
3288 server->stat.my_chanclients--;
3289 if (server->server_type == SILC_ROUTER) {
3290 server->stat.cell_chanclients--;
3291 server->stat.chanclients--;
3294 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3298 /* If there is not at least one local user on the channel then we don't
3299 need the channel entry anymore, we can remove it safely, unless the
3300 channel is permanent channel */
3301 if (server->server_type == SILC_SERVER &&
3302 !silc_server_channel_has_local(channel)) {
3303 /* Notify about leaving client if this channel has global users. */
3304 if (notify && channel->global_users)
3305 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3306 SILC_NOTIFY_TYPE_LEAVE, 1,
3307 clidp->data, silc_buffer_len(clidp));
3309 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3310 silc_server_channel_delete(server, channel);
3311 silc_buffer_free(clidp);
3315 /* Send notify to channel about client leaving the channel */
3317 silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3318 SILC_NOTIFY_TYPE_LEAVE, 1,
3319 clidp->data, silc_buffer_len(clidp));
3321 silc_buffer_free(clidp);
3325 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3326 function may be used only by router. In real SILC network all channels
3327 are created by routers thus this function is never used by normal
3330 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3331 SilcServerID *router_id,
3337 SilcChannelID *channel_id;
3338 SilcChannelEntry entry;
3339 SilcCipher send_key, receive_key;
3342 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3345 cipher = SILC_DEFAULT_CIPHER;
3347 hmac = SILC_DEFAULT_HMAC;
3349 /* Allocate cipher */
3350 if (!silc_cipher_alloc(cipher, &send_key))
3352 if (!silc_cipher_alloc(cipher, &receive_key)) {
3353 silc_cipher_free(send_key);
3358 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3359 silc_cipher_free(send_key);
3360 silc_cipher_free(receive_key);
3364 channel_name = strdup(channel_name);
3366 /* Create the channel ID */
3367 if (!silc_id_create_channel_id(server, router_id, server->rng,
3369 silc_free(channel_name);
3370 silc_cipher_free(send_key);
3371 silc_cipher_free(receive_key);
3372 silc_hmac_free(newhmac);
3376 /* Create the channel */
3377 entry = silc_idlist_add_channel(server->local_list, channel_name,
3378 SILC_CHANNEL_MODE_NONE, channel_id,
3379 NULL, send_key, receive_key, newhmac);
3381 silc_free(channel_name);
3382 silc_cipher_free(send_key);
3383 silc_cipher_free(receive_key);
3384 silc_hmac_free(newhmac);
3385 silc_free(channel_id);
3389 entry->cipher = strdup(cipher);
3390 entry->hmac_name = strdup(hmac);
3392 /* Now create the actual key material */
3393 if (!silc_server_create_channel_key(server, entry,
3394 silc_cipher_get_key_len(send_key) / 8)) {
3395 silc_idlist_del_channel(server->local_list, entry);
3399 /* Notify other routers about the new channel. We send the packet
3400 to our primary route. */
3402 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3403 channel_name, entry->id,
3404 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3407 /* Distribute to backup routers */
3408 if (broadcast && server->server_type == SILC_ROUTER) {
3410 unsigned char cid[32];
3411 SilcUInt32 name_len = strlen(channel_name);
3414 silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3415 packet = silc_channel_payload_encode(channel_name, name_len,
3416 cid, id_len, entry->mode);
3417 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3418 packet->data, silc_buffer_len(packet), FALSE,
3420 silc_buffer_free(packet);
3423 server->stat.my_channels++;
3424 if (server->server_type == SILC_ROUTER) {
3425 server->stat.channels++;
3426 server->stat.cell_channels++;
3427 entry->users_resolved = TRUE;
3433 /* Same as above but creates the channel with Channel ID `channel_id. */
3436 silc_server_create_new_channel_with_id(SilcServer server,
3440 SilcChannelID *channel_id,
3443 SilcChannelEntry entry;
3444 SilcCipher send_key, receive_key;
3447 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3450 cipher = SILC_DEFAULT_CIPHER;
3452 hmac = SILC_DEFAULT_HMAC;
3454 /* Allocate cipher */
3455 if (!silc_cipher_alloc(cipher, &send_key))
3457 if (!silc_cipher_alloc(cipher, &receive_key)) {
3458 silc_cipher_free(send_key);
3463 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3464 silc_cipher_free(send_key);
3465 silc_cipher_free(receive_key);
3469 channel_name = strdup(channel_name);
3471 /* Create the channel */
3472 entry = silc_idlist_add_channel(server->local_list, channel_name,
3473 SILC_CHANNEL_MODE_NONE, channel_id,
3474 NULL, send_key, receive_key, newhmac);
3476 silc_cipher_free(send_key);
3477 silc_cipher_free(receive_key);
3478 silc_hmac_free(newhmac);
3479 silc_free(channel_name);
3483 /* Now create the actual key material */
3484 if (!silc_server_create_channel_key(server, entry,
3485 silc_cipher_get_key_len(send_key) / 8)) {
3486 silc_idlist_del_channel(server->local_list, entry);
3490 /* Notify other routers about the new channel. We send the packet
3491 to our primary route. */
3493 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3494 channel_name, entry->id,
3495 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3498 /* Distribute to backup routers */
3499 if (broadcast && server->server_type == SILC_ROUTER) {
3501 unsigned char cid[32];
3502 SilcUInt32 name_len = strlen(channel_name);
3505 silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3506 packet = silc_channel_payload_encode(channel_name, name_len,
3507 cid, id_len, entry->mode);
3508 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3509 packet->data, silc_buffer_len(packet), FALSE,
3511 silc_buffer_free(packet);
3514 server->stat.my_channels++;
3515 if (server->server_type == SILC_ROUTER) {
3516 server->stat.channels++;
3517 server->stat.cell_channels++;
3518 entry->users_resolved = TRUE;
3524 /* Channel's key re-key timeout callback. */
3526 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3528 SilcServer server = app_context;
3529 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3533 /* Return now if we are shutting down */
3534 if (server->server_shutdown)
3537 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3540 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3543 /* Generates new channel key. This is used to create the initial channel key
3544 but also to re-generate new key for channel. If `key_len' is provided
3545 it is the bytes of the key length. */
3547 SilcBool silc_server_create_channel_key(SilcServer server,
3548 SilcChannelEntry channel,
3552 unsigned char channel_key[32], hash[SILC_HASH_MAXLEN];
3555 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3556 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3560 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3562 if (!channel->send_key)
3563 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->send_key)) {
3564 channel->send_key = NULL;
3567 if (!channel->receive_key)
3568 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->receive_key)) {
3569 silc_cipher_free(channel->send_key);
3570 channel->send_key = channel->receive_key = NULL;
3576 else if (channel->key_len)
3577 len = channel->key_len / 8;
3579 len = silc_cipher_get_key_len(channel->send_key) / 8;
3581 /* Create channel key */
3582 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3585 silc_cipher_set_key(channel->send_key, channel_key, len * 8, TRUE);
3586 silc_cipher_set_key(channel->receive_key, channel_key, len * 8, FALSE);
3588 /* Remove old key if exists */
3590 memset(channel->key, 0, channel->key_len / 8);
3591 silc_free(channel->key);
3595 channel->key_len = len * 8;
3596 channel->key = silc_memdup(channel_key, len);
3597 memset(channel_key, 0, sizeof(channel_key));
3599 /* Generate HMAC key from the channel key data and set it */
3601 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3602 memset(channel->key, 0, channel->key_len / 8);
3603 silc_free(channel->key);
3604 silc_cipher_free(channel->send_key);
3605 silc_cipher_free(channel->receive_key);
3606 channel->send_key = channel->receive_key = NULL;
3609 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3610 silc_hmac_set_key(channel->hmac, hash,
3611 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3612 memset(hash, 0, sizeof(hash));
3614 if (server->server_type == SILC_ROUTER) {
3615 if (!channel->rekey)
3616 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3617 channel->rekey->channel = channel;
3618 channel->rekey->key_len = key_len;
3619 if (channel->rekey->task)
3620 silc_schedule_task_del(server->schedule, channel->rekey->task);
3622 channel->rekey->task =
3623 silc_schedule_task_add_timeout(server->schedule,
3624 silc_server_channel_key_rekey,
3625 (void *)channel->rekey,
3626 server->config->channel_rekey_secs, 0);
3632 /* Saves the channel key found in the encoded `key_payload' buffer. This
3633 function is used when we receive Channel Key Payload and also when we're
3634 processing JOIN command reply. Returns entry to the channel. */
3636 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3637 SilcBuffer key_payload,
3638 SilcChannelEntry channel)
3640 SilcChannelKeyPayload payload = NULL;
3642 unsigned char *tmp, hash[SILC_HASH_MAXLEN];
3646 /* Decode channel key payload */
3647 payload = silc_channel_key_payload_parse(key_payload->data,
3648 silc_buffer_len(key_payload));
3650 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3655 /* Get the channel entry */
3658 /* Get channel ID */
3659 tmp = silc_channel_key_get_id(payload, &tmp_len);
3660 if (!silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL, &id, sizeof(id))) {
3665 channel = silc_idlist_find_channel_by_id(server->local_list, &id, NULL);
3667 channel = silc_idlist_find_channel_by_id(server->global_list, &id, NULL);
3669 if (server->server_type == SILC_ROUTER)
3670 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3671 silc_id_render(&id, SILC_ID_CHANNEL)));
3677 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3679 tmp = silc_channel_key_get_key(payload, &tmp_len);
3685 cipher = silc_channel_key_get_cipher(payload, NULL);
3691 /* Remove old key if exists */
3693 memset(channel->key, 0, channel->key_len / 8);
3694 silc_free(channel->key);
3695 silc_cipher_free(channel->send_key);
3696 silc_cipher_free(channel->receive_key);
3699 /* Create new cipher */
3700 if (!silc_cipher_alloc(cipher, &channel->send_key)) {
3701 channel->send_key = NULL;
3705 if (!silc_cipher_alloc(cipher, &channel->receive_key)) {
3706 silc_cipher_free(channel->send_key);
3707 channel->send_key = channel->receive_key = NULL;
3712 if (channel->cipher)
3713 silc_free(channel->cipher);
3714 channel->cipher = strdup(cipher);
3717 channel->key_len = tmp_len * 8;
3718 channel->key = silc_memdup(tmp, tmp_len);
3719 silc_cipher_set_key(channel->send_key, tmp, channel->key_len, TRUE);
3720 silc_cipher_set_key(channel->receive_key, tmp, channel->key_len, FALSE);
3722 /* Generate HMAC key from the channel key data and set it */
3724 if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3725 memset(channel->key, 0, channel->key_len / 8);
3726 silc_free(channel->key);
3727 silc_cipher_free(channel->send_key);
3728 silc_cipher_free(channel->receive_key);
3729 channel->send_key = channel->receive_key = NULL;
3732 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3733 silc_hmac_set_key(channel->hmac, hash,
3734 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3736 memset(hash, 0, sizeof(hash));
3737 memset(tmp, 0, tmp_len);
3739 if (server->server_type == SILC_ROUTER) {
3740 if (!channel->rekey)
3741 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3742 channel->rekey->channel = channel;
3743 if (channel->rekey->task)
3744 silc_schedule_task_del(server->schedule, channel->rekey->task);
3746 channel->rekey->task =
3747 silc_schedule_task_add_timeout(server->schedule,
3748 silc_server_channel_key_rekey,
3749 (void *)channel->rekey,
3750 server->config->channel_rekey_secs, 0);
3755 silc_channel_key_payload_free(payload);
3760 /* Returns assembled of all servers in the given ID list. The packet's
3761 form is dictated by the New ID payload. */
3763 static void silc_server_announce_get_servers(SilcServer server,
3764 SilcServerEntry remote,
3766 SilcBuffer *servers,
3767 unsigned long creation_time)
3770 SilcIDCacheEntry id_cache;
3771 SilcServerEntry entry;
3774 /* Go through all clients in the list */
3775 if (silc_idcache_get_all(id_list->servers, &list)) {
3776 silc_list_start(list);
3777 while ((id_cache = silc_list_get(list))) {
3778 entry = (SilcServerEntry)id_cache->context;
3780 /* Do not announce the one we've sending our announcements and
3781 do not announce ourself. Also check the creation time if it's
3783 if ((entry == remote) || (entry == server->id_entry) ||
3784 (creation_time && entry->data.created < creation_time))
3787 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3789 *servers = silc_buffer_realloc(*servers,
3791 silc_buffer_truelen((*servers)) +
3792 silc_buffer_len(idp) :
3793 silc_buffer_len(idp)));
3794 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3795 silc_buffer_put(*servers, idp->data, silc_buffer_len(idp));
3796 silc_buffer_pull(*servers, silc_buffer_len(idp));
3797 silc_buffer_free(idp);
3803 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3809 p = silc_notify_payload_encode(notify, argc, ap);
3815 /* This function is used by router to announce existing servers to our
3816 primary router when we've connected to it. If `creation_time' is non-zero
3817 then only the servers that has been created after the `creation_time'
3818 will be announced. */
3820 void silc_server_announce_servers(SilcServer server, SilcBool global,
3821 unsigned long creation_time,
3822 SilcPacketStream remote)
3824 SilcBuffer servers = NULL;
3826 SILC_LOG_DEBUG(("Announcing servers"));
3828 /* Get servers in local list */
3829 silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3830 server->local_list, &servers,
3834 /* Get servers in global list */
3835 silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3836 server->global_list, &servers,
3840 silc_buffer_push(servers, servers->data - servers->head);
3841 SILC_LOG_HEXDUMP(("servers"), servers->data, silc_buffer_len(servers));
3843 /* Send the packet */
3844 silc_server_packet_send(server, remote,
3845 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3846 servers->data, silc_buffer_len(servers));
3848 silc_buffer_free(servers);
3852 /* Returns assembled packet of all clients in the given ID list. The
3853 packet's form is dictated by the New ID Payload. */
3855 static void silc_server_announce_get_clients(SilcServer server,
3857 SilcBuffer *clients,
3859 unsigned long creation_time)
3862 SilcIDCacheEntry id_cache;
3863 SilcClientEntry client;
3866 unsigned char mode[4];
3868 /* Go through all clients in the list */
3869 if (silc_idcache_get_all(id_list->clients, &list)) {
3870 silc_list_start(list);
3871 while ((id_cache = silc_list_get(list))) {
3872 client = (SilcClientEntry)id_cache->context;
3874 if (creation_time && client->data.created < creation_time)
3876 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
3878 if (!client->connection && !client->router)
3881 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3883 *clients = silc_buffer_realloc(*clients,
3885 silc_buffer_truelen((*clients)) +
3886 silc_buffer_len(idp) :
3887 silc_buffer_len(idp)));
3888 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3889 silc_buffer_put(*clients, idp->data, silc_buffer_len(idp));
3890 silc_buffer_pull(*clients, silc_buffer_len(idp));
3892 SILC_PUT32_MSB(client->mode, mode);
3894 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3895 2, idp->data, silc_buffer_len(idp),
3897 *umodes = silc_buffer_realloc(*umodes,
3899 silc_buffer_truelen((*umodes)) +
3900 silc_buffer_len(tmp) :
3901 silc_buffer_len(tmp)));
3902 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3903 silc_buffer_put(*umodes, tmp->data, silc_buffer_len(tmp));
3904 silc_buffer_pull(*umodes, silc_buffer_len(tmp));
3905 silc_buffer_free(tmp);
3907 silc_buffer_free(idp);
3912 /* This function is used to announce our existing clients to our router
3913 when we've connected to it. If `creation_time' is non-zero then only
3914 the clients that has been created after the `creation_time' will be
3917 void silc_server_announce_clients(SilcServer server,
3918 unsigned long creation_time,
3919 SilcPacketStream remote)
3921 SilcBuffer clients = NULL;
3922 SilcBuffer umodes = NULL;
3924 SILC_LOG_DEBUG(("Announcing clients"));
3926 /* Get clients in local list */
3927 silc_server_announce_get_clients(server, server->local_list,
3928 &clients, &umodes, creation_time);
3930 /* As router we announce our global list as well */
3931 if (server->server_type == SILC_ROUTER)
3932 silc_server_announce_get_clients(server, server->global_list,
3933 &clients, &umodes, creation_time);
3936 silc_buffer_push(clients, clients->data - clients->head);
3937 SILC_LOG_HEXDUMP(("clients"), clients->data, silc_buffer_len(clients));
3939 /* Send the packet */
3940 silc_server_packet_send(server, remote,
3941 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3942 clients->data, silc_buffer_len(clients));
3944 silc_buffer_free(clients);
3948 silc_buffer_push(umodes, umodes->data - umodes->head);
3949 SILC_LOG_HEXDUMP(("umodes"), umodes->data, silc_buffer_len(umodes));
3951 /* Send the packet */
3952 silc_server_packet_send(server, remote,
3953 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3954 umodes->data, silc_buffer_len(umodes));
3956 silc_buffer_free(umodes);
3960 /* Returns channel's topic for announcing it */
3962 void silc_server_announce_get_channel_topic(SilcServer server,
3963 SilcChannelEntry channel,
3968 if (channel->topic) {
3969 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3970 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
3972 silc_buffer_len(chidp),
3974 strlen(channel->topic));
3975 silc_buffer_free(chidp);
3979 /* Returns channel's invite and ban lists */
3981 void silc_server_announce_get_inviteban(SilcServer server,
3982 SilcChannelEntry channel,
3986 SilcBuffer list, idp, idp2, tmp2;
3988 SilcHashTableList htl;
3989 const unsigned char a[1] = { 0x03 };
3991 idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
3993 /* Encode invite list */
3994 if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
3995 list = silc_buffer_alloc_size(2);
3996 type = silc_hash_table_count(channel->invite_list);
3997 SILC_PUT16_MSB(type, list->data);
3998 silc_hash_table_list(channel->invite_list, &htl);
3999 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4000 list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4002 silc_hash_table_list_reset(&htl);
4004 idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4006 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4007 idp->data, silc_buffer_len(idp),
4008 channel->channel_name,
4009 strlen(channel->channel_name),
4010 idp2->data, silc_buffer_len(idp2),
4012 list->data, silc_buffer_len(list));
4013 silc_buffer_free(idp2);
4014 silc_buffer_free(list);
4017 /* Encode ban list */
4018 if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4019 list = silc_buffer_alloc_size(2);
4020 type = silc_hash_table_count(channel->ban_list);
4021 SILC_PUT16_MSB(type, list->data);
4022 silc_hash_table_list(channel->ban_list, &htl);
4023 while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4024 list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4026 silc_hash_table_list_reset(&htl);
4029 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4030 idp->data, silc_buffer_len(idp),
4032 list->data, silc_buffer_len(list));
4033 silc_buffer_free(list);
4036 silc_buffer_free(idp);
4039 /* Returns assembled packets for channel users of the `channel'. */
4041 void silc_server_announce_get_channel_users(SilcServer server,
4042 SilcChannelEntry channel,
4043 SilcBuffer *channel_modes,
4044 SilcBuffer *channel_users,
4045 SilcBuffer *channel_users_modes)
4047 SilcChannelClientEntry chl;
4048 SilcHashTableList htl;
4049 SilcBuffer chidp, clidp, csidp;
4050 SilcBuffer tmp, fkey = NULL, chpklist;
4052 unsigned char mode[4], ulimit[4];
4055 SILC_LOG_DEBUG(("Start"));
4057 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4058 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4059 chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4062 SILC_PUT32_MSB(channel->mode, mode);
4063 if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4064 SILC_PUT32_MSB(channel->user_limit, ulimit);
4065 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4066 if (channel->founder_key)
4067 fkey = silc_public_key_payload_encode(channel->founder_key);
4069 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4071 silc_buffer_len(csidp),
4074 hmac, hmac ? strlen(hmac) : 0,
4075 channel->passphrase,
4076 channel->passphrase ?
4077 strlen(channel->passphrase) : 0,
4078 fkey ? fkey->data : NULL,
4079 fkey ? silc_buffer_len(fkey) : 0,
4080 chpklist ? chpklist->data : NULL,
4082 silc_buffer_len(chpklist) : 0,
4084 SILC_CHANNEL_MODE_ULIMIT ?
4087 SILC_CHANNEL_MODE_ULIMIT ?
4088 sizeof(ulimit) : 0));
4089 len = silc_buffer_len(tmp);
4091 silc_buffer_realloc(*channel_modes,
4093 silc_buffer_truelen((*channel_modes)) + len : len));
4094 silc_buffer_pull_tail(*channel_modes,
4095 ((*channel_modes)->end -
4096 (*channel_modes)->data));
4097 silc_buffer_put(*channel_modes, tmp->data, silc_buffer_len(tmp));
4098 silc_buffer_pull(*channel_modes, len);
4099 silc_buffer_free(tmp);
4100 silc_buffer_free(fkey);
4103 /* Now find all users on the channel */
4104 silc_hash_table_list(channel->user_list, &htl);
4105 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4106 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4109 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4111 silc_buffer_len(clidp),
4113 silc_buffer_len(chidp));
4114 len = silc_buffer_len(tmp);
4116 silc_buffer_realloc(*channel_users,
4118 silc_buffer_truelen((*channel_users)) + len : len));
4119 silc_buffer_pull_tail(*channel_users,
4120 ((*channel_users)->end -
4121 (*channel_users)->data));
4123 silc_buffer_put(*channel_users, tmp->data, silc_buffer_len(tmp));
4124 silc_buffer_pull(*channel_users, len);
4125 silc_buffer_free(tmp);
4127 /* CUMODE notify for mode change on the channel */
4128 SILC_PUT32_MSB(chl->mode, mode);
4129 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4130 fkey = silc_public_key_payload_encode(channel->founder_key);
4131 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4133 silc_buffer_len(csidp),
4136 silc_buffer_len(clidp),
4137 fkey ? fkey->data : NULL,
4138 fkey ? silc_buffer_len(fkey) : 0);
4139 len = silc_buffer_len(tmp);
4140 *channel_users_modes =
4141 silc_buffer_realloc(*channel_users_modes,
4142 (*channel_users_modes ?
4143 silc_buffer_truelen((*channel_users_modes)) +
4145 silc_buffer_pull_tail(*channel_users_modes,
4146 ((*channel_users_modes)->end -
4147 (*channel_users_modes)->data));
4149 silc_buffer_put(*channel_users_modes, tmp->data, silc_buffer_len(tmp));
4150 silc_buffer_pull(*channel_users_modes, len);
4151 silc_buffer_free(tmp);
4152 silc_buffer_free(fkey);
4154 silc_buffer_free(clidp);
4156 silc_hash_table_list_reset(&htl);
4157 silc_buffer_free(chidp);
4158 silc_buffer_free(csidp);
4161 /* Returns assembled packets for all channels and users on those channels
4162 from the given ID List. The packets are in the form dictated by the
4163 New Channel and New Channel User payloads. */
4165 void silc_server_announce_get_channels(SilcServer server,
4167 SilcBuffer *channels,
4168 SilcBuffer **channel_modes,
4169 SilcBuffer *channel_users,
4170 SilcBuffer **channel_users_modes,
4171 SilcUInt32 *channel_users_modes_c,
4172 SilcBuffer **channel_topics,
4173 SilcBuffer **channel_invites,
4174 SilcBuffer **channel_bans,
4175 SilcChannelID ***channel_ids,
4176 unsigned long creation_time)
4179 SilcIDCacheEntry id_cache;
4180 SilcChannelEntry channel;
4181 unsigned char cid[32];
4183 SilcUInt16 name_len;
4185 int i = *channel_users_modes_c;
4188 SILC_LOG_DEBUG(("Start"));
4190 /* Go through all channels in the list */
4191 if (silc_idcache_get_all(id_list->channels, &list)) {
4192 silc_list_start(list);
4193 while ((id_cache = silc_list_get(list))) {
4194 channel = (SilcChannelEntry)id_cache->context;
4196 if (creation_time && channel->created < creation_time)
4201 silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4202 name_len = strlen(channel->channel_name);
4205 len = 4 + name_len + id_len + 4;
4207 silc_buffer_realloc(*channels,
4209 silc_buffer_truelen((*channels)) +
4211 silc_buffer_pull_tail(*channels,
4212 ((*channels)->end - (*channels)->data));
4213 silc_buffer_format(*channels,
4214 SILC_STR_UI_SHORT(name_len),
4215 SILC_STR_UI_XNSTRING(channel->channel_name,
4217 SILC_STR_UI_SHORT(id_len),
4218 SILC_STR_UI_XNSTRING(cid, id_len),
4219 SILC_STR_UI_INT(channel->mode),
4221 silc_buffer_pull(*channels, len);
4224 if (creation_time && channel->updated < creation_time)
4230 /* Channel user modes */
4231 *channel_users_modes = silc_realloc(*channel_users_modes,
4232 sizeof(**channel_users_modes) *
4234 (*channel_users_modes)[i] = NULL;
4235 *channel_modes = silc_realloc(*channel_modes,
4236 sizeof(**channel_modes) * (i + 1));
4237 (*channel_modes)[i] = NULL;
4238 *channel_ids = silc_realloc(*channel_ids,
4239 sizeof(**channel_ids) * (i + 1));
4240 (*channel_ids)[i] = NULL;
4241 silc_server_announce_get_channel_users(server, channel,
4242 &(*channel_modes)[i],
4244 &(*channel_users_modes)[i]);
4245 (*channel_ids)[i] = channel->id;
4247 /* Channel's topic */
4248 *channel_topics = silc_realloc(*channel_topics,
4249 sizeof(**channel_topics) * (i + 1));
4250 (*channel_topics)[i] = NULL;
4251 silc_server_announce_get_channel_topic(server, channel,
4252 &(*channel_topics)[i]);
4254 /* Channel's invite and ban list */
4255 *channel_invites = silc_realloc(*channel_invites,
4256 sizeof(**channel_invites) * (i + 1));
4257 (*channel_invites)[i] = NULL;
4258 *channel_bans = silc_realloc(*channel_bans,
4259 sizeof(**channel_bans) * (i + 1));
4260 (*channel_bans)[i] = NULL;
4261 silc_server_announce_get_inviteban(server, channel,
4262 &(*channel_invites)[i],
4263 &(*channel_bans)[i]);
4265 (*channel_users_modes_c)++;
4273 /* This function is used to announce our existing channels to our router
4274 when we've connected to it. This also announces the users on the
4275 channels to the router. If the `creation_time' is non-zero only the
4276 channels that was created after the `creation_time' are announced.
4277 Note that the channel users are still announced even if the `creation_time'
4280 void silc_server_announce_channels(SilcServer server,
4281 unsigned long creation_time,
4282 SilcPacketStream remote)
4284 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4285 SilcBuffer *channel_users_modes = NULL;
4286 SilcBuffer *channel_topics = NULL;
4287 SilcBuffer *channel_invites = NULL;
4288 SilcBuffer *channel_bans = NULL;
4289 SilcUInt32 channel_users_modes_c = 0;
4290 SilcChannelID **channel_ids = NULL;
4292 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4294 /* Get channels and channel users in local list */
4295 silc_server_announce_get_channels(server, server->local_list,
4296 &channels, &channel_modes,
4298 &channel_users_modes,
4299 &channel_users_modes_c,
4303 &channel_ids, creation_time);
4305 /* Get channels and channel users in global list */
4306 if (server->server_type != SILC_SERVER)
4307 silc_server_announce_get_channels(server, server->global_list,
4308 &channels, &channel_modes,
4310 &channel_users_modes,
4311 &channel_users_modes_c,
4315 &channel_ids, creation_time);
4318 silc_buffer_push(channels, channels->data - channels->head);
4319 SILC_LOG_HEXDUMP(("channels"), channels->data, silc_buffer_len(channels));
4321 /* Send the packet */
4322 silc_server_packet_send(server, remote,
4323 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4324 channels->data, silc_buffer_len(channels));
4326 silc_buffer_free(channels);
4329 if (channel_users) {
4330 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4331 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4332 silc_buffer_len(channel_users));
4334 /* Send the packet */
4335 silc_server_packet_send(server, remote,
4336 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4337 channel_users->data, silc_buffer_len(channel_users));
4339 silc_buffer_free(channel_users);
4342 if (channel_modes) {
4345 for (i = 0; i < channel_users_modes_c; i++) {
4346 if (!channel_modes[i])
4348 silc_buffer_push(channel_modes[i],
4349 channel_modes[i]->data -
4350 channel_modes[i]->head);
4351 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4352 silc_buffer_len(channel_modes[i]));
4353 silc_server_packet_send_dest(server, remote,
4354 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4355 channel_ids[i], SILC_ID_CHANNEL,
4356 channel_modes[i]->data,
4357 silc_buffer_len(channel_modes[i]));
4358 silc_buffer_free(channel_modes[i]);
4360 silc_free(channel_modes);
4363 if (channel_users_modes) {
4366 for (i = 0; i < channel_users_modes_c; i++) {
4367 if (!channel_users_modes[i])
4369 silc_buffer_push(channel_users_modes[i],
4370 channel_users_modes[i]->data -
4371 channel_users_modes[i]->head);
4372 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4373 silc_buffer_len(channel_users_modes[i]));
4374 silc_server_packet_send_dest(server, remote,
4375 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4376 channel_ids[i], SILC_ID_CHANNEL,
4377 channel_users_modes[i]->data,
4378 silc_buffer_len(channel_users_modes[i]));
4379 silc_buffer_free(channel_users_modes[i]);
4381 silc_free(channel_users_modes);
4384 if (channel_topics) {
4387 for (i = 0; i < channel_users_modes_c; i++) {
4388 if (!channel_topics[i])
4391 silc_buffer_push(channel_topics[i],
4392 channel_topics[i]->data -
4393 channel_topics[i]->head);
4394 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4395 silc_buffer_len(channel_topics[i]));
4396 silc_server_packet_send_dest(server, remote,
4397 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4398 channel_ids[i], SILC_ID_CHANNEL,
4399 channel_topics[i]->data,
4400 silc_buffer_len(channel_topics[i]));
4401 silc_buffer_free(channel_topics[i]);
4403 silc_free(channel_topics);
4406 if (channel_invites) {
4409 for (i = 0; i < channel_users_modes_c; i++) {
4410 if (!channel_invites[i])
4413 silc_buffer_push(channel_invites[i],
4414 channel_invites[i]->data -
4415 channel_invites[i]->head);
4416 SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4417 silc_buffer_len(channel_invites[i]));
4418 silc_server_packet_send_dest(server, remote,
4419 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4420 channel_ids[i], SILC_ID_CHANNEL,
4421 channel_invites[i]->data,
4422 silc_buffer_len(channel_invites[i]));
4423 silc_buffer_free(channel_invites[i]);
4425 silc_free(channel_invites);
4431 for (i = 0; i < channel_users_modes_c; i++) {
4432 if (!channel_bans[i])
4435 silc_buffer_push(channel_bans[i],
4436 channel_bans[i]->data -
4437 channel_bans[i]->head);
4438 SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4439 silc_buffer_len(channel_bans[i]));
4440 silc_server_packet_send_dest(server, remote,
4441 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4442 channel_ids[i], SILC_ID_CHANNEL,
4443 channel_bans[i]->data,
4444 silc_buffer_len(channel_bans[i]));
4445 silc_buffer_free(channel_bans[i]);
4447 silc_free(channel_bans);
4450 silc_free(channel_ids);
4453 /* Announces WATCH list. */
4455 void silc_server_announce_watches(SilcServer server,
4456 SilcPacketStream remote)
4458 SilcHashTableList htl;
4459 SilcBuffer buffer, idp, args, pkp;
4460 SilcClientEntry client;
4463 SILC_LOG_DEBUG(("Announcing watch list"));
4465 /* XXX because way we save the nicks (hash) we cannot announce them. */
4467 /* XXX we should send all public keys in one command if client is
4468 watching more than one key */
4469 silc_hash_table_list(server->watcher_list_pk, &htl);
4470 while (silc_hash_table_get(&htl, &key, (void *)&client)) {
4471 if (!client || !client->id)
4474 server->stat.commands_sent++;
4476 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4477 args = silc_buffer_alloc_size(2);
4478 silc_buffer_format(args,
4479 SILC_STR_UI_SHORT(1),
4481 pkp = silc_public_key_payload_encode(key);
4482 args = silc_argument_payload_encode_one(args, pkp->data,
4483 silc_buffer_len(pkp), 0x00);
4484 buffer = silc_command_payload_encode_va(SILC_COMMAND_WATCH,
4485 ++server->cmd_ident, 2,
4486 1, idp->data, silc_buffer_len(idp),
4488 silc_buffer_len(args));
4491 silc_server_packet_send(server, remote, SILC_PACKET_COMMAND, 0,
4492 buffer->data, silc_buffer_len(buffer));
4494 silc_buffer_free(pkp);
4495 silc_buffer_free(args);
4496 silc_buffer_free(idp);
4497 silc_buffer_free(buffer);
4499 silc_hash_table_list_reset(&htl);
4502 /* Assembles user list and users mode list from the `channel'. */
4504 SilcBool silc_server_get_users_on_channel(SilcServer server,
4505 SilcChannelEntry channel,
4506 SilcBuffer *user_list,
4507 SilcBuffer *mode_list,
4508 SilcUInt32 *user_count)
4510 SilcChannelClientEntry chl;
4511 SilcHashTableList htl;
4512 SilcBuffer client_id_list;
4513 SilcBuffer client_mode_list;
4515 SilcUInt32 list_count = 0, len = 0;
4517 if (!silc_hash_table_count(channel->user_list))
4520 silc_hash_table_list(channel->user_list, &htl);
4521 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4522 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4523 silc_hash_table_list_reset(&htl);
4525 client_id_list = silc_buffer_alloc(len);
4527 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4528 silc_buffer_pull_tail(client_id_list, silc_buffer_truelen(client_id_list));
4529 silc_buffer_pull_tail(client_mode_list,
4530 silc_buffer_truelen(client_mode_list));
4532 silc_hash_table_list(channel->user_list, &htl);
4533 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4535 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4536 silc_buffer_put(client_id_list, idp->data, silc_buffer_len(idp));
4537 silc_buffer_pull(client_id_list, silc_buffer_len(idp));
4538 silc_buffer_free(idp);
4540 /* Client's mode on channel */
4541 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4542 silc_buffer_pull(client_mode_list, 4);
4546 silc_hash_table_list_reset(&htl);
4547 silc_buffer_push(client_id_list,
4548 client_id_list->data - client_id_list->head);
4549 silc_buffer_push(client_mode_list,
4550 client_mode_list->data - client_mode_list->head);
4552 *user_list = client_id_list;
4553 *mode_list = client_mode_list;
4554 *user_count = list_count;
4558 /* Saves users and their modes to the `channel'. */
4560 void silc_server_save_users_on_channel(SilcServer server,
4561 SilcPacketStream sock,
4562 SilcChannelEntry channel,
4563 SilcClientID *noadd,
4564 SilcBuffer user_list,
4565 SilcBuffer mode_list,
4566 SilcUInt32 user_count)
4572 SilcClientEntry client;
4573 SilcIDCacheEntry cache;
4574 SilcChannelClientEntry chl;
4576 SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4577 channel->channel_name));
4579 for (i = 0; i < user_count; i++) {
4581 SILC_GET16_MSB(idp_len, user_list->data + 2);
4583 if (!silc_id_payload_parse_id(user_list->data, idp_len, &id))
4585 silc_buffer_pull(user_list, idp_len);
4588 SILC_GET32_MSB(mode, mode_list->data);
4589 silc_buffer_pull(mode_list, 4);
4591 if (noadd && SILC_ID_CLIENT_COMPARE(&id.u.client_id, noadd))
4596 /* Check if we have this client cached already. */
4597 client = silc_idlist_find_client_by_id(server->local_list,
4599 server->server_type, &cache);
4601 client = silc_idlist_find_client_by_id(server->global_list,
4603 server->server_type, &cache);
4605 /* If router did not find such Client ID in its lists then this must
4606 be bogus client or some router in the net is buggy. */
4607 if (server->server_type != SILC_SERVER)
4610 /* We don't have that client anywhere, add it. The client is added
4611 to global list since server didn't have it in the lists so it must be
4613 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4614 silc_id_dup(&id.u.client_id,
4616 silc_packet_get_context(sock),
4619 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4623 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4626 if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4627 SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4628 "%s", channel->channel_name));
4632 if (!silc_server_client_on_channel(client, channel, &chl)) {
4633 /* Client was not on the channel, add it. */
4634 chl = silc_calloc(1, sizeof(*chl));
4635 chl->client = client;
4637 chl->channel = channel;
4638 silc_hash_table_add(channel->user_list, chl->client, chl);
4639 silc_hash_table_add(client->channels, chl->channel, chl);
4640 channel->user_count++;
4648 /* Saves channels and channels user modes to the `client'. Removes
4649 the client from those channels that are not sent in the list but
4652 void silc_server_save_user_channels(SilcServer server,
4653 SilcPacketStream sock,
4654 SilcClientEntry client,
4655 SilcBuffer channels,
4656 SilcBuffer channels_user_modes)
4659 SilcUInt32 *chumodes;
4660 SilcChannelPayload entry;
4661 SilcChannelEntry channel;
4662 SilcChannelID channel_id;
4663 SilcChannelClientEntry chl;
4664 SilcHashTable ht = NULL;
4665 SilcHashTableList htl;
4669 if (!channels || !channels_user_modes ||
4670 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4673 ch = silc_channel_payload_parse_list(channels->data,
4674 silc_buffer_len(channels));
4675 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4677 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4678 NULL, NULL, NULL, TRUE);
4679 silc_dlist_start(ch);
4680 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4681 /* Check if we have this channel, and add it if we don't have it.
4682 Also add the client on the channel unless it is there already. */
4683 if (!silc_channel_get_id_parse(entry, &channel_id))
4685 channel = silc_idlist_find_channel_by_id(server->local_list,
4688 channel = silc_idlist_find_channel_by_id(server->global_list,
4691 if (server->server_type != SILC_SERVER) {
4696 /* We don't have that channel anywhere, add it. */
4697 name = silc_channel_get_name(entry, NULL);
4698 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4699 silc_id_dup(&channel_id,
4701 server->router, NULL, NULL, 0);
4708 channel->mode = silc_channel_get_mode(entry);
4710 /* Add the client on the channel */
4711 if (!silc_server_client_on_channel(client, channel, &chl)) {
4712 chl = silc_calloc(1, sizeof(*chl));
4713 chl->client = client;
4714 chl->mode = chumodes[i++];
4715 chl->channel = channel;
4716 silc_hash_table_add(channel->user_list, chl->client, chl);
4717 silc_hash_table_add(client->channels, chl->channel, chl);
4718 channel->user_count++;
4721 chl->mode = chumodes[i++];
4724 silc_hash_table_add(ht, channel, channel);
4726 silc_channel_payload_list_free(ch);
4727 silc_free(chumodes);
4731 /* Go through the list again and remove client from channels that
4732 are no part of the list. */
4734 silc_hash_table_list(client->channels, &htl);
4735 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4736 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4737 silc_hash_table_del(chl->channel->user_list, chl->client);
4738 silc_hash_table_del(chl->client->channels, chl->channel);
4742 silc_hash_table_list_reset(&htl);
4743 silc_hash_table_free(ht);
4745 silc_hash_table_list(client->channels, &htl);
4746 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4747 silc_hash_table_del(chl->channel->user_list, chl->client);
4748 silc_hash_table_del(chl->client->channels, chl->channel);
4751 silc_hash_table_list_reset(&htl);
4755 /* Lookups route to the client indicated by the `id_data'. The connection
4756 object and internal data object is returned. Returns NULL if route
4757 could not be found to the client. If the `client_id' is specified then
4758 it is used and the `id_data' is ignored. */
4761 silc_server_get_client_route(SilcServer server,
4762 unsigned char *id_data,
4764 SilcClientID *client_id,
4765 SilcIDListData *idata,
4766 SilcClientEntry *client_entry)
4768 SilcClientID *id, clid;
4769 SilcClientEntry client;
4771 SILC_LOG_DEBUG(("Start"));
4774 *client_entry = NULL;
4776 /* Decode destination Client ID */
4778 if (!silc_id_str2id(id_data, id_len, SILC_ID_CLIENT, &clid, sizeof(clid)))
4780 id = silc_id_dup(&clid, SILC_ID_CLIENT);
4782 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4785 /* If the destination belongs to our server we don't have to route
4786 the packet anywhere but to send it to the local destination. */
4787 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4791 /* If we are router and the client has router then the client is in
4792 our cell but not directly connected to us. */
4793 if (server->server_type == SILC_ROUTER && client->router) {
4794 /* We are of course in this case the client's router thus the route
4795 to the client is the server who owns the client. So, we will send
4796 the packet to that server. */
4798 *idata = (SilcIDListData)client->router;
4799 return client->router->connection;
4802 /* Seems that client really is directly connected to us */
4804 *idata = (SilcIDListData)client;
4806 *client_entry = client;
4807 return client->connection;
4810 /* Destination belongs to someone not in this server. If we are normal
4811 server our action is to send the packet to our router. */
4812 if (server->server_type != SILC_ROUTER && !server->standalone) {
4815 *idata = (SilcIDListData)server->router;
4816 return SILC_PRIMARY_ROUTE(server);
4819 /* We are router and we will perform route lookup for the destination
4820 and send the packet to fastest route. */
4821 if (server->server_type == SILC_ROUTER && !server->standalone) {
4822 /* Check first that the ID is valid */
4823 client = silc_idlist_find_client_by_id(server->global_list, id,
4826 SilcPacketStream dst_sock;
4828 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4831 if (idata && dst_sock)
4832 *idata = silc_packet_get_context(dst_sock);
4841 /* Encodes and returns channel list of channels the `client' has joined.
4842 Secret channels are not put to the list. */
4844 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4845 SilcClientEntry client,
4846 SilcBool get_private,
4847 SilcBool get_secret,
4848 SilcBuffer *user_mode_list)
4850 SilcBuffer buffer = NULL;
4851 SilcChannelEntry channel;
4852 SilcChannelClientEntry chl;
4853 SilcHashTableList htl;
4854 unsigned char cid[32];
4856 SilcUInt16 name_len;
4860 *user_mode_list = NULL;
4862 silc_hash_table_list(client->channels, &htl);
4863 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4864 channel = chl->channel;
4866 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4868 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4871 silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4872 name_len = strlen(channel->channel_name);
4874 len = 4 + name_len + id_len + 4;
4875 buffer = silc_buffer_realloc(buffer,
4877 silc_buffer_truelen(buffer) + len : len));
4878 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4879 silc_buffer_format(buffer,
4880 SILC_STR_UI_SHORT(name_len),
4881 SILC_STR_DATA(channel->channel_name, name_len),
4882 SILC_STR_UI_SHORT(id_len),
4883 SILC_STR_DATA(cid, id_len),
4884 SILC_STR_UI_INT(chl->channel->mode),
4886 silc_buffer_pull(buffer, len);
4888 if (user_mode_list) {
4890 silc_buffer_realloc(*user_mode_list,
4892 silc_buffer_truelen((*user_mode_list)) + 4 : 4));
4893 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4894 (*user_mode_list)->data));
4895 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4896 silc_buffer_pull(*user_mode_list, 4);
4899 silc_hash_table_list_reset(&htl);
4902 silc_buffer_push(buffer, buffer->data - buffer->head);
4903 if (user_mode_list && *user_mode_list)
4904 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4905 (*user_mode_list)->head));
4910 /* Task callback used to retrieve network statistical information from
4911 router server once in a while. */
4913 SILC_TASK_CALLBACK(silc_server_get_stats)
4915 SilcServer server = (SilcServer)context;
4916 SilcBuffer idp, packet;
4918 if (!server->standalone) {
4919 SILC_LOG_DEBUG(("Retrieving stats from router"));
4920 server->stat.commands_sent++;
4921 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4922 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4923 ++server->cmd_ident, 1,
4925 silc_buffer_len(idp));
4926 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4927 SILC_PACKET_COMMAND, 0, packet->data,
4928 silc_buffer_len(packet));
4929 silc_buffer_free(packet);
4930 silc_buffer_free(idp);
4933 silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,