5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 1997 - 2002 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
21 * This is the actual SILC server than handles everything relating to
22 * servicing the SILC connections. This is also a SILC router as a router
23 * is also normal server.
27 #include "serverincludes.h"
28 #include "server_internal.h"
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_rehash_close_connection);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
33 SILC_TASK_CALLBACK(silc_server_connect_router);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router);
35 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
36 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
38 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
39 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
40 SILC_TASK_CALLBACK(silc_server_packet_process);
41 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
42 SILC_TASK_CALLBACK(silc_server_close_connection_final);
43 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout);
44 SILC_TASK_CALLBACK(silc_server_timeout_remote);
45 SILC_TASK_CALLBACK(silc_server_channel_key_rekey);
46 SILC_TASK_CALLBACK(silc_server_failure_callback);
47 SILC_TASK_CALLBACK(silc_server_rekey_callback);
48 SILC_TASK_CALLBACK(silc_server_get_stats);
50 /* Allocates a new SILC server object. This has to be done before the server
51 can be used. After allocation one must call silc_server_init to initialize
52 the server. The new allocated server object is returned to the new_server
55 int silc_server_alloc(SilcServer *new_server)
59 SILC_LOG_DEBUG(("Allocating new server object"));
61 server = silc_calloc(1, sizeof(*server));
62 server->server_type = SILC_SERVER;
63 server->standalone = TRUE;
64 server->local_list = silc_calloc(1, sizeof(*server->local_list));
65 server->global_list = silc_calloc(1, sizeof(*server->global_list));
66 server->pending_commands = silc_dlist_init();
68 server->sim = silc_dlist_init();
76 /* Free's the SILC server object. This is called at the very end before
79 void silc_server_free(SilcServer server)
88 while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89 silc_dlist_del(server->sim, sim);
92 silc_dlist_uninit(server->sim);
96 silc_server_config_unref(&server->config_ref);
98 silc_rng_free(server->rng);
100 silc_pkcs_free(server->pkcs);
101 if (server->public_key)
102 silc_pkcs_public_key_free(server->public_key);
103 if (server->private_key)
104 silc_pkcs_private_key_free(server->private_key);
105 if (server->pending_commands)
106 silc_dlist_uninit(server->pending_commands);
107 if (server->id_entry)
108 silc_idlist_del_server(server->local_list, server->id_entry);
110 silc_idcache_free(server->local_list->clients);
111 silc_idcache_free(server->local_list->servers);
112 silc_idcache_free(server->local_list->channels);
113 silc_idcache_free(server->global_list->clients);
114 silc_idcache_free(server->global_list->servers);
115 silc_idcache_free(server->global_list->channels);
116 silc_hash_table_free(server->watcher_list);
118 silc_hash_free(server->md5hash);
119 silc_hash_free(server->sha1hash);
120 silc_hmac_unregister_all();
121 silc_hash_unregister_all();
122 silc_cipher_unregister_all();
123 silc_pkcs_unregister_all();
125 silc_free(server->local_list);
126 silc_free(server->global_list);
127 silc_free(server->server_name);
128 silc_free(server->id_string);
129 silc_free(server->purge_i);
130 silc_free(server->purge_g);
134 /* Creates a new server listener. */
136 static bool silc_server_listen(SilcServer server, const char *server_ip,
137 SilcUInt16 port, int *sock)
139 *sock = silc_net_create_server(port, server_ip);
141 SILC_LOG_ERROR(("Could not create server listener: %s on %hu",
148 /* Adds a secondary listener. */
150 bool silc_server_init_secondary(SilcServer server)
152 int sock = 0, sock_list[server->config->param.connections_max];
153 SilcSocketConnection newsocket = NULL;
154 SilcServerConfigServerInfoInterface *interface;
156 for (interface = server->config->server_info->secondary; interface;
157 interface = interface->next, sock++) {
159 if (!silc_server_listen(server,
160 interface->server_ip, interface->port, &sock_list[sock]))
163 /* Set socket to non-blocking mode */
164 silc_net_set_socket_nonblock(sock_list[sock]);
166 /* Add ourselves also to the socket table. The entry allocated above
167 is sent as argument for fast referencing in the future. */
168 silc_socket_alloc(sock_list[sock],
169 SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
170 server->sockets[sock_list[sock]] = newsocket;
171 SILC_SET_LISTENER(newsocket);
173 /* Perform name and address lookups to resolve the listenning address
175 if (!silc_net_check_local_by_sock(sock_list[sock], &newsocket->hostname,
177 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
179 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
180 newsocket->hostname ? newsocket->hostname :
181 newsocket->ip ? newsocket->ip : ""));
182 server->stat.conn_failures++;
185 if (!newsocket->hostname)
186 newsocket->hostname = strdup(newsocket->ip);
188 newsocket->port = silc_net_get_local_port(sock);
190 newsocket->user_data = (void *)server->id_entry;
191 silc_schedule_task_add(server->schedule, sock_list[sock],
192 silc_server_accept_new_connection,
193 (void *)server, 0, 0,
195 SILC_TASK_PRI_NORMAL);
201 do silc_net_close_server(sock_list[sock--]); while (sock >= 0);
205 /* Initializes the entire SILC server. This is called always before running
206 the server. This is called only once at the initialization of the program.
207 This binds the server to its listenning port. After this function returns
208 one should call silc_server_run to start the server. This returns TRUE
209 when everything is ok to run the server. Configuration file must be
210 read and parsed before calling this. */
212 bool silc_server_init(SilcServer server)
216 SilcServerEntry id_entry;
217 SilcIDListPurge purge;
218 SilcSocketConnection newsocket = NULL;
220 SILC_LOG_DEBUG(("Initializing server"));
222 server->starttime = time(NULL);
224 /* Take config object for us */
225 silc_server_config_ref(&server->config_ref, server->config,
228 /* Steal public and private key from the config object */
229 server->public_key = server->config->server_info->public_key;
230 server->private_key = server->config->server_info->private_key;
231 server->config->server_info->public_key = NULL;
232 server->config->server_info->private_key = NULL;
234 /* Register all configured ciphers, PKCS and hash functions. */
235 if (!silc_server_config_register_ciphers(server))
236 silc_cipher_register_default();
237 if (!silc_server_config_register_pkcs(server))
238 silc_pkcs_register_default();
239 if (!silc_server_config_register_hashfuncs(server))
240 silc_hash_register_default();
241 if (!silc_server_config_register_hmacs(server))
242 silc_hmac_register_default();
244 /* Initialize random number generator for the server. */
245 server->rng = silc_rng_alloc();
246 silc_rng_init(server->rng);
247 silc_rng_global_init(server->rng);
249 /* Initialize hash functions for server to use */
250 silc_hash_alloc("md5", &server->md5hash);
251 silc_hash_alloc("sha1", &server->sha1hash);
253 /* Allocate PKCS context for local public and private keys */
254 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
256 silc_pkcs_public_key_set(server->pkcs, server->public_key);
257 silc_pkcs_private_key_set(server->pkcs, server->private_key);
259 /* Initialize the scheduler */
260 server->schedule = silc_schedule_init(server->config->param.connections_max);
261 if (!server->schedule)
264 /* First, register log files configuration for error output */
265 silc_server_config_setlogfiles(server);
267 /* Initialize ID caches */
268 server->local_list->clients =
269 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
270 server->local_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
271 server->local_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
273 /* These are allocated for normal server as well as these hold some
274 global information that the server has fetched from its router. For
275 router these are used as they are supposed to be used on router. */
276 server->global_list->clients =
277 silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor);
278 server->global_list->servers = silc_idcache_alloc(0, SILC_ID_SERVER, NULL);
279 server->global_list->channels = silc_idcache_alloc(0, SILC_ID_CHANNEL, NULL);
281 /* Init watcher list */
282 server->watcher_list =
283 silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
284 silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
286 if (!server->watcher_list)
289 /* Create a listening server */
290 if (!silc_server_listen(server,
291 server->config->server_info->primary == NULL ? NULL :
292 server->config->server_info->primary->server_ip,
293 server->config->server_info->primary == NULL ? 0 :
294 server->config->server_info->primary->port,
298 /* Set socket to non-blocking mode */
299 silc_net_set_socket_nonblock(sock);
302 /* Allocate the entire socket list that is used in server. Eventually
303 all connections will have entry in this table (it is a table of
304 pointers to the actual object that is allocated individually
306 server->sockets = silc_calloc(server->config->param.connections_max,
307 sizeof(*server->sockets));
308 if (!server->sockets)
311 /* Add ourselves also to the socket table. The entry allocated above
312 is sent as argument for fast referencing in the future. */
313 silc_socket_alloc(sock, SILC_SOCKET_TYPE_SERVER, NULL, &newsocket);
314 server->sockets[sock] = newsocket;
315 SILC_SET_LISTENER(newsocket);
317 /* Perform name and address lookups to resolve the listenning address
319 if (!silc_net_check_local_by_sock(sock, &newsocket->hostname,
321 if ((server->config->require_reverse_lookup && !newsocket->hostname) ||
323 SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
324 newsocket->hostname ? newsocket->hostname :
325 newsocket->ip ? newsocket->ip : ""));
326 server->stat.conn_failures++;
329 if (!newsocket->hostname)
330 newsocket->hostname = strdup(newsocket->ip);
332 newsocket->port = silc_net_get_local_port(sock);
334 /* Create a Server ID for the server. */
335 silc_id_create_server_id(newsocket->ip, newsocket->port, server->rng, &id);
340 server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
341 server->id_string_len = silc_id_get_len(id, SILC_ID_SERVER);
342 server->server_name = server->config->server_info->server_name;
343 server->config->server_info->server_name = NULL;
345 /* Add ourselves to the server list. We don't have a router yet
346 beacuse we haven't established a route yet. It will be done later.
347 For now, NULL is sent as router. This allocates new entry to
350 silc_idlist_add_server(server->local_list, strdup(server->server_name),
351 server->server_type, server->id, NULL, NULL);
353 SILC_LOG_ERROR(("Could not add ourselves to cache"));
356 id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
358 /* Put the allocated socket pointer also to the entry allocated above
359 for fast back-referencing to the socket list. */
360 newsocket->user_data = (void *)id_entry;
361 id_entry->connection = (void *)newsocket;
362 server->id_entry = id_entry;
364 /* Register protocols */
365 silc_server_protocols_register();
367 /* Add the first task to the scheduler. This is task that is executed by
368 timeout. It expires as soon as the caller calls silc_server_run. This
369 task performs authentication protocol and key exchange with our
371 silc_schedule_task_add(server->schedule, 0,
372 silc_server_connect_to_router,
373 (void *)server, 0, 1,
375 SILC_TASK_PRI_NORMAL);
377 /* Add listener task to the scheduler. This task receives new connections
378 to the server. This task remains on the queue until the end of the
380 silc_schedule_task_add(server->schedule, sock,
381 silc_server_accept_new_connection,
382 (void *)server, 0, 0,
384 SILC_TASK_PRI_NORMAL);
386 if (silc_server_init_secondary(server) == FALSE)
389 server->listenning = TRUE;
391 /* If server connections has been configured then we must be router as
392 normal server cannot have server connections, only router connections. */
393 if (server->config->servers) {
394 SilcServerConfigServer *ptr = server->config->servers;
396 server->server_type = SILC_ROUTER;
398 if (ptr->backup_router) {
399 server->server_type = SILC_BACKUP_ROUTER;
400 server->backup_router = TRUE;
401 server->id_entry->server_type = SILC_BACKUP_ROUTER;
408 /* Register the ID Cache purge task. This periodically purges the ID cache
409 and removes the expired cache entries. */
411 /* Clients local list */
412 server->purge_i = purge = silc_calloc(1, sizeof(*purge));
413 purge->cache = server->local_list->clients;
414 purge->schedule = server->schedule;
415 purge->timeout = 600;
416 silc_schedule_task_add(purge->schedule, 0,
418 (void *)purge, purge->timeout, 0,
419 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
421 /* Clients global list */
422 server->purge_g = purge = silc_calloc(1, sizeof(*purge));
423 purge->cache = server->global_list->clients;
424 purge->schedule = server->schedule;
425 purge->timeout = 300;
426 silc_schedule_task_add(purge->schedule, 0,
428 (void *)purge, purge->timeout, 0,
429 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
431 /* If we are normal server we'll retrieve network statisticial information
432 once in a while from the router. */
433 if (server->server_type == SILC_SERVER)
434 silc_schedule_task_add(purge->schedule, 0, silc_server_get_stats,
435 server, 10, 0, SILC_TASK_TIMEOUT,
438 if (server->server_type == SILC_ROUTER)
439 server->stat.routers++;
441 SILC_LOG_DEBUG(("Server initialized"));
443 /* We are done here, return succesfully */
447 silc_server_config_unref(&server->config_ref);
448 silc_net_close_server(sock);
452 /* Task callback to close a socket connection after rehash */
454 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
456 SilcServer server = context;
457 SilcSocketConnection sock = server->sockets[fd];
462 SILC_LOG_INFO(("Closing connection %s:%d [%s]: connection is unconfigured",
463 sock->hostname, sock->port,
464 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
465 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
466 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
468 silc_schedule_task_del_by_context(server->schedule, sock);
469 silc_server_disconnect_remote(server, sock,
470 SILC_STATUS_ERR_BANNED_FROM_SERVER,
471 "This connection is removed from "
474 silc_server_free_sock_user_data(server, sock, NULL);
477 /* This function basically reads the config file again and switches the config
478 object pointed by the server object. After that, we have to fix various
479 things such as the server_name and the listening ports.
480 Keep in mind that we no longer have the root privileges at this point. */
482 bool silc_server_rehash(SilcServer server)
484 SilcServerConfig newconfig;
486 SILC_LOG_INFO(("Rehashing server"));
488 /* Reset the logging system */
489 silc_log_quick = TRUE;
490 silc_log_flush_all();
492 /* Start the main rehash phase (read again the config file) */
493 newconfig = silc_server_config_alloc(server->config_file);
495 SILC_LOG_ERROR(("Rehash FAILED."));
499 /* Reinit scheduler if necessary */
500 if (newconfig->param.connections_max > server->config->param.connections_max)
501 if (!silc_schedule_reinit(server->schedule,
502 newconfig->param.connections_max))
505 /* Fix the server_name field */
506 if (strcmp(server->server_name, newconfig->server_info->server_name)) {
507 silc_free(server->server_name);
508 server->server_name = newconfig->server_info->server_name;
509 newconfig->server_info->server_name = NULL;
511 /* Update the idcache list with a fresh pointer */
512 silc_free(server->id_entry->server_name);
513 server->id_entry->server_name = strdup(server->server_name);
514 if (!silc_idcache_del_by_context(server->local_list->servers,
517 if (!silc_idcache_add(server->local_list->servers,
518 server->id_entry->server_name,
519 server->id_entry->id, server->id_entry, 0, NULL))
524 silc_server_config_setlogfiles(server);
526 /* Change new key pair if necessary */
527 if (newconfig->server_info->public_key &&
528 !silc_pkcs_public_key_compare(server->public_key,
529 newconfig->server_info->public_key)) {
530 silc_pkcs_public_key_free(server->public_key);
531 silc_pkcs_private_key_free(server->private_key);
532 server->public_key = newconfig->server_info->public_key;
533 server->private_key = newconfig->server_info->private_key;
534 newconfig->server_info->public_key = NULL;
535 newconfig->server_info->private_key = NULL;
537 /* Allocate PKCS context for local public and private keys */
538 silc_pkcs_free(server->pkcs);
539 if (!silc_pkcs_alloc(server->public_key->name, &server->pkcs))
541 silc_pkcs_public_key_set(server->pkcs, server->public_key);
542 silc_pkcs_private_key_set(server->pkcs, server->private_key);
545 /* Check for unconfigured server and router connections and close
546 connections that were unconfigured. */
548 if (server->config->routers) {
549 SilcServerConfigRouter *ptr;
550 SilcServerConfigRouter *newptr;
553 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
556 /* Check whether new config has this one too */
557 for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
558 if (!strcmp(newptr->host, ptr->host) && newptr->port == ptr->port &&
559 newptr->initiator == ptr->initiator) {
566 /* Remove this connection */
567 SilcSocketConnection sock;
568 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_ROUTER,
569 ptr->host, ptr->port);
570 if (sock && !SILC_IS_LISTENER(sock))
571 silc_schedule_task_add(server->schedule, sock->sock,
572 silc_server_rehash_close_connection,
573 server, 0, 1, SILC_TASK_TIMEOUT,
574 SILC_TASK_PRI_NORMAL);
579 if (server->config->servers) {
580 SilcServerConfigServer *ptr;
581 SilcServerConfigServer *newptr;
584 for (ptr = server->config->servers; ptr; ptr = ptr->next) {
587 /* Check whether new config has this one too */
588 for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
589 if (!strcmp(newptr->host, ptr->host)) {
596 /* Remove this connection */
597 SilcSocketConnection sock;
598 sock = silc_server_find_socket_by_host(server, SILC_SOCKET_TYPE_SERVER,
600 if (sock && !SILC_IS_LISTENER(sock))
601 silc_schedule_task_add(server->schedule, sock->sock,
602 silc_server_rehash_close_connection,
603 server, 0, 1, SILC_TASK_TIMEOUT,
604 SILC_TASK_PRI_NORMAL);
609 /* Go through all configured routers after rehash */
610 silc_schedule_task_add(server->schedule, 0,
611 silc_server_connect_to_router,
612 (void *)server, 0, 1,
614 SILC_TASK_PRI_NORMAL);
616 /* Check whether our router status has changed */
617 if (newconfig->servers) {
618 SilcServerConfigServer *ptr = newconfig->servers;
620 server->server_type = SILC_ROUTER;
622 if (ptr->backup_router) {
623 server->server_type = SILC_BACKUP_ROUTER;
624 server->backup_router = TRUE;
625 server->id_entry->server_type = SILC_BACKUP_ROUTER;
632 /* Our old config is gone now. We'll unreference our reference made in
633 silc_server_init and then destroy it since we are destroying it
634 underneath the application (layer which called silc_server_init). */
635 silc_server_config_unref(&server->config_ref);
636 silc_server_config_destroy(server->config);
638 /* Take new config context */
639 server->config = newconfig;
640 silc_server_config_ref(&server->config_ref, server->config, server->config);
642 SILC_LOG_DEBUG(("Server rehashed"));
647 /* The heart of the server. This runs the scheduler thus runs the server.
648 When this returns the server has been stopped and the program will
651 void silc_server_run(SilcServer server)
653 SILC_LOG_INFO(("SILC Server started"));
655 /* Start the scheduler, the heart of the SILC server. When this returns
656 the program will be terminated. */
657 silc_schedule(server->schedule);
660 /* Stops the SILC server. This function is used to shutdown the server.
661 This is usually called after the scheduler has returned. After stopping
662 the server one should call silc_server_free. */
664 void silc_server_stop(SilcServer server)
666 SILC_LOG_DEBUG(("Stopping server"));
668 if (server->schedule) {
671 /* Close all connections */
672 for (i = 0; i < server->config->param.connections_max; i++) {
673 if (!server->sockets[i])
675 if (!SILC_IS_LISTENER(server->sockets[i])) {
676 SilcIDListData idata = server->sockets[i]->user_data;
679 idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
681 silc_schedule_task_del_by_context(server->schedule,
683 silc_server_disconnect_remote(server, server->sockets[i],
685 "Server is shutting down");
687 silc_socket_free(server->sockets[i]);
688 server->sockets[i] = NULL;
692 /* We are not connected to network anymore */
693 server->standalone = TRUE;
695 silc_schedule_stop(server->schedule);
696 silc_schedule_uninit(server->schedule);
697 server->schedule = NULL;
699 silc_free(server->sockets);
700 server->sockets = NULL;
703 silc_server_protocols_unregister();
705 SILC_LOG_DEBUG(("Server stopped"));
708 /* Function that is called when the network connection to a router has
709 been established. This will continue with the key exchange protocol
710 with the remote router. */
712 void silc_server_start_key_exchange(SilcServer server,
713 SilcServerConnection sconn,
716 SilcSocketConnection newsocket;
717 SilcProtocol protocol;
718 SilcServerKEInternalContext *proto_ctx;
719 SilcServerConfigRouter *conn =
720 (SilcServerConfigRouter *) sconn->conn.ref_ptr;
723 /* Cancel any possible retry timeouts */
724 silc_schedule_task_del_by_callback(server->schedule,
725 silc_server_connect_to_router_retry);
727 /* Set socket options */
728 silc_net_set_socket_nonblock(sock);
729 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
731 /* Create socket connection for the connection. Even though we
732 know that we are connecting to a router we will mark the socket
733 to be unknown connection until we have executed authentication
735 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
736 server->sockets[sock] = newsocket;
737 newsocket->hostname = strdup(sconn->remote_host);
738 newsocket->ip = strdup(sconn->remote_host);
739 newsocket->port = sconn->remote_port;
740 sconn->sock = newsocket;
742 /* Allocate internal protocol context. This is sent as context
744 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
745 proto_ctx->server = (void *)server;
746 proto_ctx->context = (void *)sconn;
747 proto_ctx->sock = newsocket;
748 proto_ctx->rng = server->rng;
749 proto_ctx->responder = FALSE;
751 /* Set Key Exchange flags from configuration, but fall back to global
753 SILC_GET_SKE_FLAGS(conn, proto_ctx);
754 if (server->config->param.key_exchange_pfs)
755 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
757 /* Perform key exchange protocol. silc_server_connect_to_router_second
758 will be called after the protocol is finished. */
759 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
760 &protocol, proto_ctx,
761 silc_server_connect_to_router_second);
762 newsocket->protocol = protocol;
764 /* Register a timeout task that will be executed if the protocol
765 is not executed within set limit. */
766 proto_ctx->timeout_task =
767 silc_schedule_task_add(server->schedule, sock,
768 silc_server_timeout_remote,
769 server, server->config->key_exchange_timeout, 0,
773 /* Register the connection for network input and output. This sets
774 that scheduler will listen for incoming packets for this connection
775 and sets that outgoing packets may be sent to this connection as
776 well. However, this doesn't set the scheduler for outgoing traffic,
777 it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
778 later when outgoing data is available. */
779 context = (void *)server;
780 SILC_REGISTER_CONNECTION_FOR_IO(sock);
782 /* Run the protocol */
783 silc_protocol_execute(protocol, server->schedule, 0, 0);
786 /* Timeout callback that will be called to retry connecting to remote
787 router. This is used by both normal and router server. This will wait
788 before retrying the connecting. The timeout is generated by exponential
789 backoff algorithm. */
791 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
793 SilcServerConnection sconn = (SilcServerConnection)context;
794 SilcServer server = sconn->server;
795 SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
796 SilcServerConfigConnParams *param =
797 (conn->param ? conn->param : &server->config->param);
799 SILC_LOG_INFO(("Retrying connecting to a router"));
801 /* Calculate next timeout */
802 if (sconn->retry_count >= 1) {
803 sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
804 if (sconn->retry_timeout > param->reconnect_interval_max)
805 sconn->retry_timeout = param->reconnect_interval_max;
807 sconn->retry_timeout = param->reconnect_interval;
809 sconn->retry_count++;
810 sconn->retry_timeout = sconn->retry_timeout +
811 silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
813 /* If we've reached max retry count, give up. */
814 if ((sconn->retry_count > param->reconnect_count) &&
815 !param->reconnect_keep_trying) {
816 SILC_LOG_ERROR(("Could not connect to router, giving up"));
817 silc_server_config_unref(&sconn->conn);
818 silc_free(sconn->remote_host);
819 silc_free(sconn->backup_replace_ip);
824 SILC_LOG_DEBUG(("Retrying connecting to a router in %d seconds",
825 sconn->retry_timeout));
827 /* We will lookup a fresh pointer later */
828 silc_server_config_unref(&sconn->conn);
830 /* Wait one before retrying */
831 silc_schedule_task_add(server->schedule, 0, silc_server_connect_router,
832 context, sconn->retry_timeout, 0,
833 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
836 /* Generic routine to use connect to a router. */
838 SILC_TASK_CALLBACK(silc_server_connect_router)
840 SilcServerConnection sconn = (SilcServerConnection)context;
841 SilcServer server = sconn->server;
842 SilcServerConfigRouter *rconn;
845 SILC_LOG_INFO(("Connecting to the %s %s on port %d",
846 (sconn->backup ? "backup router" : "router"),
847 sconn->remote_host, sconn->remote_port));
849 server->router_connect = time(NULL);
850 rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
853 SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
854 (sconn->backup ? "backup router" : "router"),
855 sconn->remote_host, sconn->remote_port));
856 silc_free(sconn->remote_host);
857 silc_free(sconn->backup_replace_ip);
861 silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
863 /* Connect to remote host */
864 sock = silc_net_create_connection(
865 (!server->config->server_info->primary ? NULL :
866 server->config->server_info->primary->server_ip),
867 sconn->remote_port, sconn->remote_host);
869 SILC_LOG_ERROR(("Could not connect to router %s:%d",
870 sconn->remote_host, sconn->remote_port));
871 if (!sconn->no_reconnect)
872 silc_schedule_task_add(server->schedule, 0,
873 silc_server_connect_to_router_retry,
874 context, 0, 1, SILC_TASK_TIMEOUT,
875 SILC_TASK_PRI_NORMAL);
877 silc_server_config_unref(&sconn->conn);
881 /* Continue with key exchange protocol */
882 silc_server_start_key_exchange(server, sconn, sock);
885 /* This function connects to our primary router or if we are a router this
886 establishes all our primary routes. This is called at the start of the
887 server to do authentication and key exchange with our router - called
890 SILC_TASK_CALLBACK(silc_server_connect_to_router)
892 SilcServer server = (SilcServer)context;
893 SilcServerConnection sconn;
894 SilcServerConfigRouter *ptr;
896 SILC_LOG_DEBUG(("We are %s",
897 (server->server_type == SILC_SERVER ?
898 "normal server" : server->server_type == SILC_ROUTER ?
899 "router" : "backup router/normal server")));
901 if (!server->config->routers) {
902 /* There wasn't a configured router, we will continue but we don't
903 have a connection to outside world. We will be standalone server. */
904 SILC_LOG_DEBUG(("No router(s), we are standalone"));
905 server->standalone = TRUE;
909 /* Cancel any possible retry timeouts */
910 silc_schedule_task_del_by_callback(server->schedule,
911 silc_server_connect_router);
912 silc_schedule_task_del_by_callback(server->schedule,
913 silc_server_connect_to_router_retry);
915 /* Create the connections to all our routes */
916 for (ptr = server->config->routers; ptr; ptr = ptr->next) {
918 SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
919 ptr->backup_router ? "Backup router" : "Router",
920 ptr->initiator ? "Initiator" : "Responder",
921 ptr->host, ptr->port));
923 if (server->server_type == SILC_ROUTER && ptr->backup_router &&
924 ptr->initiator == FALSE && !server->backup_router)
925 server->wait_backup = TRUE;
927 if (ptr->initiator) {
928 /* Check whether we are connected to this host already */
929 if (silc_server_num_sockets_by_remote(server,
930 silc_net_is_ip(ptr->host) ?
932 silc_net_is_ip(ptr->host) ?
933 NULL : ptr->host, ptr->port,
934 SILC_SOCKET_TYPE_ROUTER)) {
935 SILC_LOG_DEBUG(("We are already connected to this router"));
939 /* Allocate connection object for hold connection specific stuff. */
940 sconn = silc_calloc(1, sizeof(*sconn));
941 sconn->server = server;
942 sconn->remote_host = strdup(ptr->host);
943 sconn->remote_port = ptr->port;
944 sconn->backup = ptr->backup_router;
946 sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
947 sconn->backup_replace_port = ptr->backup_replace_port;
950 if (!server->router_conn && !sconn->backup)
951 server->router_conn = sconn;
953 silc_schedule_task_add(server->schedule, 0,
954 silc_server_connect_router,
955 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
956 SILC_TASK_PRI_NORMAL);
961 /* Second part of connecting to router(s). Key exchange protocol has been
962 executed and now we will execute authentication protocol. */
964 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
966 SilcProtocol protocol = (SilcProtocol)context;
967 SilcServerKEInternalContext *ctx =
968 (SilcServerKEInternalContext *)protocol->context;
969 SilcServer server = (SilcServer)ctx->server;
970 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
971 SilcSocketConnection sock = ctx->sock;
972 SilcServerConnAuthInternalContext *proto_ctx;
973 SilcServerConfigRouter *conn = NULL;
975 SILC_LOG_DEBUG(("Start"));
977 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
978 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
979 /* Error occured during protocol */
980 silc_protocol_free(protocol);
981 sock->protocol = NULL;
982 silc_ske_free_key_material(ctx->keymat);
984 silc_packet_context_free(ctx->packet);
986 silc_ske_free(ctx->ske);
987 silc_free(ctx->dest_id);
989 silc_schedule_task_del_by_callback(server->schedule,
990 silc_server_failure_callback);
991 silc_server_disconnect_remote(server, sock,
992 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
994 /* Try reconnecting if configuration wants it */
995 if (!sconn->no_reconnect) {
996 silc_schedule_task_add(server->schedule, 0,
997 silc_server_connect_to_router_retry,
998 sconn, 0, 1, SILC_TASK_TIMEOUT,
999 SILC_TASK_PRI_NORMAL);
1003 /* Call completion to indicate error */
1004 if (sconn->callback)
1005 (*sconn->callback)(server, NULL, sconn->callback_context);
1007 silc_server_config_unref(&sconn->conn);
1008 silc_free(sconn->remote_host);
1009 silc_free(sconn->backup_replace_ip);
1014 /* We now have the key material as the result of the key exchange
1015 protocol. Take the key material into use. Free the raw key material
1016 as soon as we've set them into use. */
1017 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1018 ctx->sock, ctx->keymat,
1019 ctx->ske->prop->cipher,
1020 ctx->ske->prop->pkcs,
1021 ctx->ske->prop->hash,
1022 ctx->ske->prop->hmac,
1023 ctx->ske->prop->group,
1025 silc_protocol_free(protocol);
1026 sock->protocol = NULL;
1027 silc_ske_free_key_material(ctx->keymat);
1029 silc_packet_context_free(ctx->packet);
1031 silc_ske_free(ctx->ske);
1032 silc_free(ctx->dest_id);
1034 silc_schedule_task_del_by_callback(server->schedule,
1035 silc_server_failure_callback);
1036 silc_server_disconnect_remote(server, sock,
1037 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1039 /* Try reconnecting if configuration wants it */
1040 if (!sconn->no_reconnect) {
1041 silc_schedule_task_add(server->schedule, 0,
1042 silc_server_connect_to_router_retry,
1043 sconn, 0, 1, SILC_TASK_TIMEOUT,
1044 SILC_TASK_PRI_NORMAL);
1048 /* Call completion to indicate error */
1049 if (sconn->callback)
1050 (*sconn->callback)(server, NULL, sconn->callback_context);
1052 silc_server_config_unref(&sconn->conn);
1053 silc_free(sconn->remote_host);
1054 silc_free(sconn->backup_replace_ip);
1058 silc_ske_free_key_material(ctx->keymat);
1060 /* Allocate internal context for the authentication protocol. This
1061 is sent as context for the protocol. */
1062 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1063 proto_ctx->server = (void *)server;
1064 proto_ctx->context = (void *)sconn;
1065 proto_ctx->sock = sock;
1066 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1067 proto_ctx->dest_id_type = ctx->dest_id_type;
1068 proto_ctx->dest_id = ctx->dest_id;
1070 /* Resolve the authentication method used in this connection. Check if
1071 we find a match from user configured connections */
1072 if (!sconn->conn.ref_ptr)
1073 conn = silc_server_config_find_router_conn(server, sock->hostname,
1076 conn = sconn->conn.ref_ptr;
1079 /* Match found. Use the configured authentication method. Take only
1080 the passphrase, since for public key auth we automatically use
1081 our local key pair. */
1082 if (conn->passphrase) {
1083 if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1084 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1086 proto_ctx->auth_data = strdup(conn->passphrase);
1087 proto_ctx->auth_data_len = strlen(conn->passphrase);
1088 proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
1090 } else if (conn->publickeys) {
1091 proto_ctx->auth_meth = SILC_AUTH_PUBLIC_KEY;
1093 proto_ctx->auth_meth = SILC_AUTH_NONE;
1096 SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
1097 sock->hostname, sock->ip, sock->port));
1098 silc_protocol_free(protocol);
1099 sock->protocol = NULL;
1101 silc_packet_context_free(ctx->packet);
1103 silc_ske_free(ctx->ske);
1104 silc_free(ctx->dest_id);
1106 silc_server_config_unref(&sconn->conn);
1107 silc_free(sconn->remote_host);
1108 silc_free(sconn->backup_replace_ip);
1110 silc_schedule_task_del_by_callback(server->schedule,
1111 silc_server_failure_callback);
1112 silc_server_disconnect_remote(server, sock,
1113 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1117 /* Free old protocol as it is finished now */
1118 silc_protocol_free(protocol);
1120 silc_packet_context_free(ctx->packet);
1122 sock->protocol = NULL;
1124 /* Allocate the authentication protocol. This is allocated here
1125 but we won't start it yet. We will be receiving party of this
1126 protocol thus we will wait that connecting party will make
1127 their first move. */
1128 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1129 &sock->protocol, proto_ctx,
1130 silc_server_connect_to_router_final);
1132 /* Register timeout task. If the protocol is not executed inside
1133 this timelimit the connection will be terminated. */
1134 proto_ctx->timeout_task =
1135 silc_schedule_task_add(server->schedule, sock->sock,
1136 silc_server_timeout_remote,
1138 server->config->conn_auth_timeout, 0,
1142 /* Run the protocol */
1143 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
1146 /* Finalizes the connection to router. Registers a server task to the
1147 queue so that we can accept new connections. */
1149 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
1151 SilcProtocol protocol = (SilcProtocol)context;
1152 SilcServerConnAuthInternalContext *ctx =
1153 (SilcServerConnAuthInternalContext *)protocol->context;
1154 SilcServer server = (SilcServer)ctx->server;
1155 SilcServerConnection sconn = (SilcServerConnection)ctx->context;
1156 SilcSocketConnection sock = ctx->sock;
1157 SilcServerEntry id_entry = NULL;
1159 SilcServerHBContext hb_context;
1160 unsigned char *id_string;
1162 SilcIDListData idata;
1163 SilcServerConfigRouter *conn = NULL;
1164 SilcServerConfigConnParams *param = NULL;
1166 SILC_LOG_DEBUG(("Start"));
1168 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1169 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1170 /* Error occured during protocol */
1171 silc_free(ctx->dest_id);
1172 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1175 /* Try reconnecting if configuration wants it */
1176 if (!sconn->no_reconnect) {
1177 silc_schedule_task_add(server->schedule, 0,
1178 silc_server_connect_to_router_retry,
1179 sconn, 0, 1, SILC_TASK_TIMEOUT,
1180 SILC_TASK_PRI_NORMAL);
1187 /* Add a task to the queue. This task receives new connections to the
1188 server. This task remains on the queue until the end of the program. */
1189 if (!server->listenning && !sconn->backup) {
1190 silc_schedule_task_add(server->schedule, server->sock,
1191 silc_server_accept_new_connection,
1192 (void *)server, 0, 0,
1194 SILC_TASK_PRI_NORMAL);
1195 server->listenning = TRUE;
1198 /* Send NEW_SERVER packet to the router. We will become registered
1199 to the SILC network after sending this packet. */
1200 id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
1201 id_len = silc_id_get_len(server->id, SILC_ID_SERVER);
1202 packet = silc_buffer_alloc(2 + 2 + id_len + strlen(server->server_name));
1203 silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
1204 silc_buffer_format(packet,
1205 SILC_STR_UI_SHORT(id_len),
1206 SILC_STR_UI_XNSTRING(id_string, id_len),
1207 SILC_STR_UI_SHORT(strlen(server->server_name)),
1208 SILC_STR_UI_XNSTRING(server->server_name,
1209 strlen(server->server_name)),
1212 /* Send the packet */
1213 silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
1214 packet->data, packet->len, TRUE);
1215 silc_buffer_free(packet);
1216 silc_free(id_string);
1218 SILC_LOG_INFO(("Connected to router %s", sock->hostname));
1220 /* Check that we do not have this ID already */
1221 id_entry = silc_idlist_find_server_by_id(server->local_list,
1222 ctx->dest_id, TRUE, NULL);
1224 silc_idcache_del_by_context(server->local_list->servers, id_entry);
1226 id_entry = silc_idlist_find_server_by_id(server->global_list,
1227 ctx->dest_id, TRUE, NULL);
1229 silc_idcache_del_by_context(server->global_list->servers, id_entry);
1232 SILC_LOG_DEBUG(("New server id(%s)",
1233 silc_id_render(ctx->dest_id, SILC_ID_SERVER)));
1235 /* Add the connected router to global server list. Router is sent
1236 as NULL since it's local to us. */
1237 id_entry = silc_idlist_add_server(server->global_list,
1238 strdup(sock->hostname),
1239 SILC_ROUTER, ctx->dest_id, NULL, sock);
1241 silc_free(ctx->dest_id);
1242 SILC_LOG_ERROR(("Cannot add new server entry to cache"));
1243 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1248 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1249 silc_free(sock->user_data);
1250 sock->user_data = (void *)id_entry;
1251 sock->type = SILC_SOCKET_TYPE_ROUTER;
1252 idata = (SilcIDListData)sock->user_data;
1253 idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1254 SILC_IDLIST_STATUS_LOCAL);
1256 conn = sconn->conn.ref_ptr;
1257 param = &server->config->param;
1258 if (conn && conn->param)
1259 param = conn->param;
1261 /* Perform keepalive. The `hb_context' will be freed automatically
1262 when finally calling the silc_socket_free function. */
1263 hb_context = silc_calloc(1, sizeof(*hb_context));
1264 hb_context->server = server;
1265 silc_socket_set_heartbeat(sock, param->keepalive_secs, hb_context,
1266 silc_server_perform_heartbeat,
1269 /* Register re-key timeout */
1270 idata->rekey->timeout = param->key_exchange_rekey;
1271 idata->rekey->context = (void *)server;
1272 silc_schedule_task_add(server->schedule, sock->sock,
1273 silc_server_rekey_callback,
1274 (void *)sock, idata->rekey->timeout, 0,
1275 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1277 if (!sconn->backup) {
1278 /* Mark this router our primary router if we're still standalone */
1279 if (server->standalone) {
1280 server->id_entry->router = id_entry;
1281 server->router = id_entry;
1282 server->standalone = FALSE;
1284 /* If we are router then announce our possible servers. Backup
1285 router announces also global servers. */
1286 if (server->server_type == SILC_ROUTER)
1287 silc_server_announce_servers(server,
1288 server->backup_router ? TRUE : FALSE,
1289 0, SILC_PRIMARY_ROUTE(server));
1291 /* Announce our clients and channels to the router */
1292 silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1293 silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1295 /* If we are backup router then this primary router is whom we are
1297 if (server->server_type == SILC_BACKUP_ROUTER)
1298 silc_server_backup_add(server, server->id_entry, sock->ip, 0, TRUE);
1301 /* Add this server to be our backup router */
1302 silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1303 sconn->backup_replace_port, FALSE);
1306 sock->protocol = NULL;
1309 /* Call the completion callback to indicate that we've connected to
1311 if (sconn->callback)
1312 (*sconn->callback)(server, id_entry, sconn->callback_context);
1314 /* Free the temporary connection data context */
1316 silc_server_config_unref(&sconn->conn);
1317 silc_free(sconn->remote_host);
1318 silc_free(sconn->backup_replace_ip);
1321 if (sconn == server->router_conn)
1322 server->router_conn = NULL;
1325 /* Free the protocol object */
1326 if (sock->protocol == protocol)
1327 sock->protocol = NULL;
1328 silc_protocol_free(protocol);
1330 silc_packet_context_free(ctx->packet);
1332 silc_ske_free(ctx->ske);
1333 if (ctx->auth_meth == SILC_AUTH_PASSWORD)
1334 silc_free(ctx->auth_data);
1338 /* Host lookup callback that is called after the incoming connection's
1339 IP and FQDN lookup is performed. This will actually check the acceptance
1340 of the incoming connection and will register the key exchange protocol
1341 for this connection. */
1344 silc_server_accept_new_connection_lookup(SilcSocketConnection sock,
1347 SilcServerKEInternalContext *proto_ctx =
1348 (SilcServerKEInternalContext *)context;
1349 SilcServer server = (SilcServer)proto_ctx->server;
1350 SilcServerConfigClient *cconfig = NULL;
1351 SilcServerConfigServer *sconfig = NULL;
1352 SilcServerConfigRouter *rconfig = NULL;
1353 SilcServerConfigDeny *deny;
1356 context = (void *)server;
1358 /* Check whether we could resolve both IP and FQDN. */
1359 if (!sock->ip || (!strcmp(sock->ip, sock->hostname) &&
1360 server->config->require_reverse_lookup)) {
1361 SILC_LOG_ERROR(("IP/DNS lookup failed %s",
1362 sock->hostname ? sock->hostname :
1363 sock->ip ? sock->ip : ""));
1364 server->stat.conn_failures++;
1365 silc_server_disconnect_remote(server, sock,
1366 SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1367 "Unknown host or IP");
1368 silc_free(proto_ctx);
1372 /* Register the connection for network input and output. This sets
1373 that scheduler will listen for incoming packets for this connection
1374 and sets that outgoing packets may be sent to this connection as well.
1375 However, this doesn't set the scheduler for outgoing traffic, it
1376 will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1377 later when outgoing data is available. */
1378 SILC_REGISTER_CONNECTION_FOR_IO(sock->sock);
1380 SILC_LOG_INFO(("Incoming connection %s (%s)", sock->hostname,
1383 /* Listenning port */
1384 if (!server->sockets[(SilcUInt32)proto_ctx->context]) {
1385 silc_server_disconnect_remote(server, sock,
1386 SILC_STATUS_ERR_RESOURCE_LIMIT,
1387 "Connection refused");
1388 server->stat.conn_failures++;
1389 silc_free(proto_ctx);
1392 port = server->sockets[(SilcUInt32)proto_ctx->context]->port;
1394 /* Check whether this connection is denied to connect to us. */
1395 deny = silc_server_config_find_denied(server, sock->ip);
1397 deny = silc_server_config_find_denied(server, sock->hostname);
1399 /* The connection is denied */
1400 SILC_LOG_INFO(("Connection %s (%s) is denied",
1401 sock->hostname, sock->ip));
1402 silc_server_disconnect_remote(server, sock,
1403 SILC_STATUS_ERR_BANNED_FROM_SERVER,
1405 server->stat.conn_failures++;
1406 silc_free(proto_ctx);
1410 /* Check whether we have configured this sort of connection at all. We
1411 have to check all configurations since we don't know what type of
1412 connection this is. */
1413 if (!(cconfig = silc_server_config_find_client(server, sock->ip)))
1414 cconfig = silc_server_config_find_client(server, sock->hostname);
1415 if (!(sconfig = silc_server_config_find_server_conn(server, sock->ip)))
1416 sconfig = silc_server_config_find_server_conn(server, sock->hostname);
1417 if (server->server_type == SILC_ROUTER) {
1418 if (!(rconfig = silc_server_config_find_router_conn(server,
1419 sock->ip, sock->port)))
1420 rconfig = silc_server_config_find_router_conn(server, sock->hostname,
1423 if (!cconfig && !sconfig && !rconfig) {
1424 SILC_LOG_INFO(("Connection %s (%s) is not allowed", sock->hostname,
1426 silc_server_disconnect_remote(server, sock,
1427 SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
1428 server->stat.conn_failures++;
1429 silc_free(proto_ctx);
1433 /* The connection is allowed */
1435 /* Set internal context for key exchange protocol. This is
1436 sent as context for the protocol. */
1437 proto_ctx->sock = sock;
1438 proto_ctx->rng = server->rng;
1439 proto_ctx->responder = TRUE;
1440 silc_server_config_ref(&proto_ctx->cconfig, server->config, cconfig);
1441 silc_server_config_ref(&proto_ctx->sconfig, server->config, sconfig);
1442 silc_server_config_ref(&proto_ctx->rconfig, server->config, rconfig);
1444 /* Take flags for key exchange. Since we do not know what type of connection
1445 this is, we go through all found configurations and use the global ones
1446 as well. This will result always into strictest key exchange flags. */
1447 SILC_GET_SKE_FLAGS(cconfig, proto_ctx);
1448 SILC_GET_SKE_FLAGS(sconfig, proto_ctx);
1449 SILC_GET_SKE_FLAGS(rconfig, proto_ctx);
1450 if (server->config->param.key_exchange_pfs)
1451 proto_ctx->flags |= SILC_SKE_SP_FLAG_PFS;
1453 /* Prepare the connection for key exchange protocol. We allocate the
1454 protocol but will not start it yet. The connector will be the
1455 initiator of the protocol thus we will wait for initiation from
1456 there before we start the protocol. */
1457 server->stat.auth_attempts++;
1458 SILC_LOG_DEBUG(("Starting key exchange protocol"));
1459 silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE,
1460 &sock->protocol, proto_ctx,
1461 silc_server_accept_new_connection_second);
1463 /* Register a timeout task that will be executed if the connector
1464 will not start the key exchange protocol within specified timeout
1465 and the connection will be closed. */
1466 proto_ctx->timeout_task =
1467 silc_schedule_task_add(server->schedule, sock->sock,
1468 silc_server_timeout_remote,
1470 server->config->key_exchange_timeout, 0,
1475 /* Accepts new connections to the server. Accepting new connections are
1476 done in three parts to make it async. */
1478 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
1480 SilcServer server = (SilcServer)context;
1481 SilcSocketConnection newsocket;
1482 SilcServerKEInternalContext *proto_ctx;
1485 SILC_LOG_DEBUG(("Accepting new connection"));
1487 server->stat.conn_attempts++;
1489 sock = silc_net_accept_connection(fd);
1491 SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
1492 server->stat.conn_failures++;
1496 /* Check for maximum allowed connections */
1497 if (sock > server->config->param.connections_max) {
1498 SILC_LOG_ERROR(("Refusing connection, server is full"));
1499 server->stat.conn_failures++;
1500 silc_net_close_connection(sock);
1504 /* Set socket options */
1505 silc_net_set_socket_nonblock(sock);
1506 silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
1508 /* We don't create a ID yet, since we don't know what type of connection
1509 this is yet. But, we do add the connection to the socket table. */
1510 silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
1511 server->sockets[sock] = newsocket;
1513 /* Perform asynchronous host lookup. This will lookup the IP and the
1514 FQDN of the remote connection. After the lookup is done the connection
1515 is accepted further. */
1516 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1517 proto_ctx->server = server;
1518 proto_ctx->context = (void *)fd;
1519 silc_socket_host_lookup(newsocket, TRUE,
1520 silc_server_accept_new_connection_lookup,
1521 (void *)proto_ctx, server->schedule);
1524 /* Second part of accepting new connection. Key exchange protocol has been
1525 performed and now it is time to do little connection authentication
1526 protocol to figure out whether this connection is client or server
1527 and whether it has right to access this server (especially server
1528 connections needs to be authenticated). */
1530 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1532 SilcProtocol protocol = (SilcProtocol)context;
1533 SilcServerKEInternalContext *ctx =
1534 (SilcServerKEInternalContext *)protocol->context;
1535 SilcServer server = (SilcServer)ctx->server;
1536 SilcSocketConnection sock = ctx->sock;
1537 SilcServerConnAuthInternalContext *proto_ctx;
1539 SILC_LOG_DEBUG(("Start"));
1541 if ((protocol->state == SILC_PROTOCOL_STATE_ERROR) ||
1542 (protocol->state == SILC_PROTOCOL_STATE_FAILURE)) {
1543 /* Error occured during protocol */
1544 SILC_LOG_DEBUG(("Error key exchange protocol"));
1545 silc_protocol_free(protocol);
1546 sock->protocol = NULL;
1547 silc_ske_free_key_material(ctx->keymat);
1549 silc_packet_context_free(ctx->packet);
1551 silc_ske_free(ctx->ske);
1552 silc_free(ctx->dest_id);
1553 silc_server_config_unref(&ctx->cconfig);
1554 silc_server_config_unref(&ctx->sconfig);
1555 silc_server_config_unref(&ctx->rconfig);
1557 silc_schedule_task_del_by_callback(server->schedule,
1558 silc_server_failure_callback);
1559 silc_server_disconnect_remote(server, sock,
1560 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
1562 server->stat.auth_failures++;
1566 /* We now have the key material as the result of the key exchange
1567 protocol. Take the key material into use. Free the raw key material
1568 as soon as we've set them into use. */
1569 if (!silc_server_protocol_ke_set_keys(server, ctx->ske,
1570 ctx->sock, ctx->keymat,
1571 ctx->ske->prop->cipher,
1572 ctx->ske->prop->pkcs,
1573 ctx->ske->prop->hash,
1574 ctx->ske->prop->hmac,
1575 ctx->ske->prop->group,
1577 SILC_LOG_ERROR(("Error setting key material in use"));
1578 silc_protocol_free(protocol);
1579 sock->protocol = NULL;
1580 silc_ske_free_key_material(ctx->keymat);
1582 silc_packet_context_free(ctx->packet);
1584 silc_ske_free(ctx->ske);
1585 silc_free(ctx->dest_id);
1586 silc_server_config_unref(&ctx->cconfig);
1587 silc_server_config_unref(&ctx->sconfig);
1588 silc_server_config_unref(&ctx->rconfig);
1590 silc_schedule_task_del_by_callback(server->schedule,
1591 silc_server_failure_callback);
1592 silc_server_disconnect_remote(server, sock,
1593 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1594 server->stat.auth_failures++;
1597 silc_ske_free_key_material(ctx->keymat);
1599 /* Allocate internal context for the authentication protocol. This
1600 is sent as context for the protocol. */
1601 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1602 proto_ctx->server = (void *)server;
1603 proto_ctx->sock = sock;
1604 proto_ctx->ske = ctx->ske; /* Save SKE object from previous protocol */
1605 proto_ctx->responder = TRUE;
1606 proto_ctx->dest_id_type = ctx->dest_id_type;
1607 proto_ctx->dest_id = ctx->dest_id;
1608 proto_ctx->cconfig = ctx->cconfig;
1609 proto_ctx->sconfig = ctx->sconfig;
1610 proto_ctx->rconfig = ctx->rconfig;
1612 /* Free old protocol as it is finished now */
1613 silc_protocol_free(protocol);
1615 silc_packet_context_free(ctx->packet);
1617 sock->protocol = NULL;
1619 /* Allocate the authentication protocol. This is allocated here
1620 but we won't start it yet. We will be receiving party of this
1621 protocol thus we will wait that connecting party will make
1622 their first move. */
1623 SILC_LOG_DEBUG(("Starting connection authentication protocol"));
1624 silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH,
1625 &sock->protocol, proto_ctx,
1626 silc_server_accept_new_connection_final);
1628 /* Register timeout task. If the protocol is not executed inside
1629 this timelimit the connection will be terminated. */
1630 proto_ctx->timeout_task =
1631 silc_schedule_task_add(server->schedule, sock->sock,
1632 silc_server_timeout_remote,
1634 server->config->conn_auth_timeout, 0,
1639 /* After this is called, server don't wait for backup router anymore */
1641 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
1643 SilcServer server = context;
1644 server->wait_backup = FALSE;
1647 /* Final part of accepting new connection. The connection has now
1648 been authenticated and keys has been exchanged. We also know whether
1649 this is client or server connection. */
1651 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1653 SilcProtocol protocol = (SilcProtocol)context;
1654 SilcServerConnAuthInternalContext *ctx =
1655 (SilcServerConnAuthInternalContext *)protocol->context;
1656 SilcServer server = (SilcServer)ctx->server;
1657 SilcSocketConnection sock = ctx->sock;
1658 SilcServerHBContext hb_context;
1659 SilcUnknownEntry entry = (SilcUnknownEntry)sock->user_data;
1661 SilcUInt32 hearbeat_timeout = server->config->param.keepalive_secs;
1663 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1664 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1665 /* Error occured during protocol */
1666 SILC_LOG_DEBUG(("Error during authentication protocol"));
1667 silc_protocol_free(protocol);
1668 sock->protocol = NULL;
1670 silc_packet_context_free(ctx->packet);
1672 silc_ske_free(ctx->ske);
1673 silc_free(ctx->dest_id);
1674 silc_server_config_unref(&ctx->cconfig);
1675 silc_server_config_unref(&ctx->sconfig);
1676 silc_server_config_unref(&ctx->rconfig);
1678 silc_schedule_task_del_by_callback(server->schedule,
1679 silc_server_failure_callback);
1680 silc_server_disconnect_remote(server, sock, SILC_STATUS_ERR_AUTH_FAILED,
1682 server->stat.auth_failures++;
1686 entry->data.last_receive = time(NULL);
1688 switch (ctx->conn_type) {
1689 case SILC_SOCKET_TYPE_CLIENT:
1691 SilcClientEntry client;
1692 SilcServerConfigClient *conn = ctx->cconfig.ref_ptr;
1694 /* Verify whether this connection is after all allowed to connect */
1695 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1696 &server->config->param,
1697 conn->param, ctx->ske)) {
1698 server->stat.auth_failures++;
1702 /* If we are primary router and we have backup router configured
1703 but it has not connected to use yet, do not accept any other
1705 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1706 !server->backup_router) {
1707 SilcServerConfigRouter *router;
1708 router = silc_server_config_get_backup_router(server);
1709 if (router && strcmp(server->config->server_info->primary->server_ip,
1711 silc_server_find_socket_by_host(server,
1712 SILC_SOCKET_TYPE_SERVER,
1713 router->backup_replace_ip, 0)) {
1714 SILC_LOG_INFO(("Will not accept connections because we do "
1715 "not have backup router connection established"));
1716 silc_server_disconnect_remote(server, sock,
1717 SILC_STATUS_ERR_PERM_DENIED,
1718 "We do not have connection to backup "
1719 "router established, try later");
1720 silc_free(sock->user_data);
1721 server->stat.auth_failures++;
1723 /* From here on, wait 10 seconds for the backup router to appear. */
1724 silc_schedule_task_add(server->schedule, 0,
1725 silc_server_backup_router_wait,
1726 (void *)server, 10, 0,
1727 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1732 SILC_LOG_DEBUG(("Remote host is client"));
1733 SILC_LOG_INFO(("Connection %s (%s) is client", sock->hostname,
1736 /* Add the client to the client ID cache. The nickname and Client ID
1737 and other information is created after we have received NEW_CLIENT
1738 packet from client. */
1739 client = silc_idlist_add_client(server->local_list,
1740 NULL, NULL, NULL, NULL, NULL, sock, 0);
1742 SILC_LOG_ERROR(("Could not add new client to cache"));
1743 silc_free(sock->user_data);
1744 silc_server_disconnect_remote(server, sock,
1745 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1746 server->stat.auth_failures++;
1749 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1752 server->stat.my_clients++;
1753 server->stat.clients++;
1754 server->stat.cell_clients++;
1756 /* Get connection parameters */
1758 if (conn->param->keepalive_secs)
1759 hearbeat_timeout = conn->param->keepalive_secs;
1762 id_entry = (void *)client;
1765 case SILC_SOCKET_TYPE_SERVER:
1766 case SILC_SOCKET_TYPE_ROUTER:
1768 SilcServerEntry new_server;
1769 bool initiator = FALSE;
1770 bool backup_local = FALSE;
1771 bool backup_router = FALSE;
1772 char *backup_replace_ip = NULL;
1773 SilcUInt16 backup_replace_port = 0;
1774 SilcServerConfigServer *sconn = ctx->sconfig.ref_ptr;
1775 SilcServerConfigRouter *rconn = ctx->rconfig.ref_ptr;
1777 /* If we are backup router and this is incoming server connection
1778 and we do not have connection to primary router, do not allow
1780 if (server->server_type == SILC_BACKUP_ROUTER &&
1781 ctx->conn_type == SILC_SOCKET_TYPE_SERVER &&
1782 !SILC_PRIMARY_ROUTE(server)) {
1783 SILC_LOG_INFO(("Will not accept server connection because we do "
1784 "not have primary router connection established"));
1785 silc_server_disconnect_remote(server, sock,
1786 SILC_STATUS_ERR_PERM_DENIED,
1787 "We do not have connection to primary "
1788 "router established, try later");
1789 silc_free(sock->user_data);
1790 server->stat.auth_failures++;
1794 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1795 /* Verify whether this connection is after all allowed to connect */
1796 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1797 &server->config->param,
1798 rconn ? rconn->param : NULL,
1800 silc_free(sock->user_data);
1801 server->stat.auth_failures++;
1807 if (rconn->param->keepalive_secs)
1808 hearbeat_timeout = rconn->param->keepalive_secs;
1811 initiator = rconn->initiator;
1812 backup_local = rconn->backup_local;
1813 backup_router = rconn->backup_router;
1814 backup_replace_ip = rconn->backup_replace_ip;
1815 backup_replace_port = rconn->backup_replace_port;
1819 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1820 /* Verify whether this connection is after all allowed to connect */
1821 if (!silc_server_connection_allowed(server, sock, ctx->conn_type,
1822 &server->config->param,
1823 sconn ? sconn->param : NULL,
1825 silc_free(sock->user_data);
1826 server->stat.auth_failures++;
1831 if (sconn->param->keepalive_secs)
1832 hearbeat_timeout = sconn->param->keepalive_secs;
1835 backup_router = sconn->backup_router;
1839 /* If we are primary router and we have backup router configured
1840 but it has not connected to use yet, do not accept any other
1842 if (server->wait_backup && server->server_type == SILC_ROUTER &&
1843 !server->backup_router && !backup_router) {
1844 SilcServerConfigRouter *router;
1845 router = silc_server_config_get_backup_router(server);
1846 if (router && strcmp(server->config->server_info->primary->server_ip,
1848 silc_server_find_socket_by_host(server,
1849 SILC_SOCKET_TYPE_SERVER,
1850 router->backup_replace_ip, 0)) {
1851 SILC_LOG_INFO(("Will not accept connections because we do "
1852 "not have backup router connection established"));
1853 silc_server_disconnect_remote(server, sock,
1854 SILC_STATUS_ERR_PERM_DENIED,
1855 "We do not have connection to backup "
1856 "router established, try later");
1857 silc_free(sock->user_data);
1858 server->stat.auth_failures++;
1860 /* From here on, wait 10 seconds for the backup router to appear. */
1861 silc_schedule_task_add(server->schedule, 0,
1862 silc_server_backup_router_wait,
1863 (void *)server, 10, 0,
1864 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1869 SILC_LOG_DEBUG(("Remote host is %s",
1870 ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1871 "server" : (backup_router ?
1872 "backup router" : "router")));
1873 SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
1874 sock->ip, ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1875 "server" : (backup_router ?
1876 "backup router" : "router")));
1878 /* Add the server into server cache. The server name and Server ID
1879 is updated after we have received NEW_SERVER packet from the
1880 server. We mark ourselves as router for this server if we really
1883 silc_idlist_add_server((ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1884 server->local_list : (backup_router ?
1885 server->local_list :
1886 server->global_list)),
1888 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1889 SILC_SERVER : SILC_ROUTER),
1891 (ctx->conn_type == SILC_SOCKET_TYPE_SERVER ?
1892 server->id_entry : (backup_router ?
1893 server->id_entry : NULL)),
1896 SILC_LOG_ERROR(("Could not add new server to cache"));
1897 silc_free(sock->user_data);
1898 silc_server_disconnect_remote(server, sock,
1899 SILC_STATUS_ERR_AUTH_FAILED, NULL);
1900 server->stat.auth_failures++;
1903 entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
1905 id_entry = (void *)new_server;
1907 /* If the incoming connection is router and marked as backup router
1908 then add it to be one of our backups */
1909 if (ctx->conn_type == SILC_SOCKET_TYPE_ROUTER && backup_router) {
1910 silc_server_backup_add(server, new_server, backup_replace_ip,
1911 backup_replace_port, backup_local);
1913 /* Change it back to SERVER type since that's what it really is. */
1915 ctx->conn_type = SILC_SOCKET_TYPE_SERVER;
1917 new_server->server_type = SILC_BACKUP_ROUTER;
1918 server->wait_backup = FALSE;
1922 if (ctx->conn_type == SILC_SOCKET_TYPE_SERVER) {
1923 server->stat.my_servers++;
1925 server->stat.my_routers++;
1926 server->stat.routers++;
1928 server->stat.servers++;
1930 /* Check whether this connection is to be our primary router connection
1931 if we do not already have the primary route. */
1932 if (!backup_router &&
1933 server->standalone && ctx->conn_type == SILC_SOCKET_TYPE_ROUTER) {
1934 if (silc_server_config_is_primary_route(server) && !initiator)
1937 SILC_LOG_DEBUG(("We are not standalone server anymore"));
1938 server->standalone = FALSE;
1939 if (!server->id_entry->router) {
1940 server->id_entry->router = id_entry;
1941 server->router = id_entry;
1952 sock->type = ctx->conn_type;
1954 /* Add the common data structure to the ID entry. */
1955 silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1957 /* Add to sockets internal pointer for fast referencing */
1958 silc_free(sock->user_data);
1959 sock->user_data = id_entry;
1961 /* Connection has been fully established now. Everything is ok. */
1962 SILC_LOG_DEBUG(("New connection authenticated"));
1964 /* Perform keepalive. The `hb_context' will be freed automatically
1965 when finally calling the silc_socket_free function. */
1966 hb_context = silc_calloc(1, sizeof(*hb_context));
1967 hb_context->server = server;
1968 silc_socket_set_heartbeat(sock, hearbeat_timeout, hb_context,
1969 silc_server_perform_heartbeat,
1973 silc_schedule_task_del_by_callback(server->schedule,
1974 silc_server_failure_callback);
1975 silc_protocol_free(protocol);
1977 silc_packet_context_free(ctx->packet);
1979 silc_ske_free(ctx->ske);
1980 silc_free(ctx->dest_id);
1981 silc_server_config_unref(&ctx->cconfig);
1982 silc_server_config_unref(&ctx->sconfig);
1983 silc_server_config_unref(&ctx->rconfig);
1985 sock->protocol = NULL;
1988 /* This function is used to read packets from network and send packets to
1989 network. This is usually a generic task. */
1991 SILC_TASK_CALLBACK(silc_server_packet_process)
1993 SilcServer server = (SilcServer)context;
1994 SilcSocketConnection sock = server->sockets[fd];
1995 SilcIDListData idata;
1996 SilcCipher cipher = NULL;
1997 SilcHmac hmac = NULL;
1998 SilcUInt32 sequence = 0;
2002 SILC_LOG_DEBUG(("Unknown socket connection"));
2006 /* Packet sending */
2008 if (type == SILC_TASK_WRITE) {
2009 /* Do not send data to disconnected connection */
2010 if (SILC_IS_DISCONNECTED(sock)) {
2011 SILC_LOG_DEBUG(("Disconnected socket connection, cannot send"));
2015 server->stat.packets_sent++;
2017 /* Send the packet */
2018 ret = silc_packet_send(sock, TRUE);
2020 /* If returned -2 could not write to connection now, will do
2026 SILC_LOG_ERROR(("Error sending packet to connection "
2027 "%s:%d [%s]", sock->hostname, sock->port,
2028 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2029 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2030 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2035 /* The packet has been sent and now it is time to set the connection
2036 back to only for input. When there is again some outgoing data
2037 available for this connection it will be set for output as well.
2038 This call clears the output setting and sets it only for input. */
2039 SILC_SET_CONNECTION_FOR_INPUT(server->schedule, fd);
2040 SILC_UNSET_OUTBUF_PENDING(sock);
2042 silc_buffer_clear(sock->outbuf);
2046 /* Packet receiving */
2048 /* Read some data from connection */
2049 ret = silc_packet_receive(sock);
2053 SILC_LOG_ERROR(("Error receiving packet from connection "
2054 "%s:%d [%s] %s", sock->hostname, sock->port,
2055 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2056 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2057 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2058 "Router"), strerror(errno)));
2064 SILC_LOG_DEBUG(("Read EOF"));
2066 /* If connection is disconnecting already we will finally
2067 close the connection */
2068 if (SILC_IS_DISCONNECTING(sock)) {
2069 if (sock->user_data)
2070 silc_server_free_sock_user_data(server, sock, NULL);
2071 silc_server_close_connection(server, sock);
2075 SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
2076 SILC_SET_DISCONNECTING(sock);
2078 if (sock->user_data) {
2080 if (silc_socket_get_error(sock, tmp, sizeof(tmp) - 1))
2081 silc_server_free_sock_user_data(server, sock, tmp);
2083 silc_server_free_sock_user_data(server, sock, NULL);
2084 } else if (server->router_conn && server->router_conn->sock == sock &&
2085 !server->router && server->standalone)
2086 silc_schedule_task_add(server->schedule, 0,
2087 silc_server_connect_to_router,
2090 SILC_TASK_PRI_NORMAL);
2092 silc_server_close_connection(server, sock);
2096 /* If connection is disconnecting or disconnected we will ignore
2098 if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
2099 SILC_LOG_DEBUG(("Ignoring read data from disconnected connection"));
2103 /* Get keys and stuff from ID entry */
2104 idata = (SilcIDListData)sock->user_data;
2106 cipher = idata->receive_key;
2107 hmac = idata->hmac_receive;
2108 sequence = idata->psn_receive;
2111 /* Process the packet. This will call the parser that will then
2112 decrypt and parse the packet. */
2113 ret = silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2114 TRUE : FALSE, cipher, hmac, sequence,
2115 silc_server_packet_parse, server);
2117 /* If this socket connection is not authenticated yet and the packet
2118 processing failed we will drop the connection since it can be
2119 a malicious flooder. */
2120 if (sock->type == SILC_SOCKET_TYPE_UNKNOWN && ret == FALSE &&
2121 (!sock->protocol || sock->protocol->protocol->type ==
2122 SILC_PROTOCOL_SERVER_KEY_EXCHANGE)) {
2123 SILC_LOG_DEBUG(("Bad data sent from unknown connection %d", sock->sock));
2124 SILC_SET_DISCONNECTING(sock);
2126 if (sock->user_data)
2127 silc_server_free_sock_user_data(server, sock, NULL);
2128 silc_server_close_connection(server, sock);
2132 /* Parses whole packet, received earlier. */
2134 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
2136 SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
2137 SilcServer server = (SilcServer)parse_ctx->context;
2138 SilcSocketConnection sock = parse_ctx->sock;
2139 SilcPacketContext *packet = parse_ctx->packet;
2140 SilcIDListData idata = (SilcIDListData)sock->user_data;
2143 server->stat.packets_received++;
2145 /* Parse the packet */
2146 if (parse_ctx->normal)
2147 ret = silc_packet_parse(packet, idata ? idata->receive_key : NULL);
2149 ret = silc_packet_parse_special(packet, idata ? idata->receive_key : NULL);
2151 /* If entry is disabled ignore what we got. */
2152 if (ret != SILC_PACKET_RESUME_ROUTER &&
2153 idata && idata->status & SILC_IDLIST_STATUS_DISABLED) {
2154 SILC_LOG_DEBUG(("Connection is disabled"));
2158 if (ret == SILC_PACKET_NONE) {
2159 SILC_LOG_DEBUG(("Error parsing packet"));
2163 /* Check that the the current client ID is same as in the client's packet. */
2164 if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
2165 SilcClientEntry client = (SilcClientEntry)sock->user_data;
2166 if (client && client->id && packet->src_id) {
2167 void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
2168 packet->src_id_type);
2169 if (!id || !SILC_ID_CLIENT_COMPARE(client->id, id)) {
2171 SILC_LOG_DEBUG(("Packet source is not same as sender"));
2178 if (server->server_type == SILC_ROUTER) {
2179 /* Route the packet if it is not destined to us. Other ID types but
2180 server are handled separately after processing them. */
2181 if (packet->dst_id && !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
2182 packet->dst_id_type == SILC_ID_SERVER &&
2183 sock->type != SILC_SOCKET_TYPE_CLIENT &&
2184 memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2186 /* Route the packet to fastest route for the destination ID */
2187 void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
2188 packet->dst_id_type);
2191 silc_server_packet_route(server,
2192 silc_server_route_get(server, id,
2193 packet->dst_id_type),
2200 /* Parse the incoming packet type */
2201 silc_server_packet_parse_type(server, sock, packet);
2203 /* Broadcast packet if it is marked as broadcast packet and it is
2204 originated from router and we are router. */
2205 if (server->server_type == SILC_ROUTER &&
2206 sock->type == SILC_SOCKET_TYPE_ROUTER &&
2207 packet->flags & SILC_PACKET_FLAG_BROADCAST) {
2208 /* Broadcast to our primary route */
2209 silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
2211 /* If we have backup routers then we need to feed all broadcast
2212 data to those servers. */
2213 silc_server_backup_broadcast(server, sock, packet);
2217 silc_packet_context_free(packet);
2218 silc_free(parse_ctx);
2221 /* Parser callback called by silc_packet_receive_process. This merely
2222 registers timeout that will handle the actual parsing when appropriate. */
2224 bool silc_server_packet_parse(SilcPacketParserContext *parser_context,
2227 SilcServer server = (SilcServer)context;
2228 SilcSocketConnection sock = parser_context->sock;
2229 SilcIDListData idata = (SilcIDListData)sock->user_data;
2232 idata->psn_receive = parser_context->packet->sequence + 1;
2234 /* If protocol for this connection is key exchange or rekey then we'll
2235 process all packets synchronously, since there might be packets in
2236 queue that we are not able to decrypt without first processing the
2237 packets before them. */
2238 if ((parser_context->packet->type == SILC_PACKET_REKEY ||
2239 parser_context->packet->type == SILC_PACKET_REKEY_DONE) ||
2240 (sock->protocol && sock->protocol->protocol &&
2241 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2242 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY))) {
2243 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2246 /* Reprocess data since we'll return FALSE here. This is because
2247 the idata->receive_key might have become valid in the last packet
2248 and we want to call this processor with valid cipher. */
2250 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2251 TRUE : FALSE, idata->receive_key,
2252 idata->hmac_receive, idata->psn_receive,
2253 silc_server_packet_parse, server);
2255 silc_packet_receive_process(sock, server->server_type == SILC_ROUTER ?
2256 TRUE : FALSE, NULL, NULL, 0,
2257 silc_server_packet_parse, server);
2261 switch (sock->type) {
2262 case SILC_SOCKET_TYPE_UNKNOWN:
2263 case SILC_SOCKET_TYPE_CLIENT:
2264 /* Parse the packet with timeout */
2265 silc_schedule_task_add(server->schedule, sock->sock,
2266 silc_server_packet_parse_real,
2267 (void *)parser_context, 0, 100000,
2269 SILC_TASK_PRI_NORMAL);
2271 case SILC_SOCKET_TYPE_SERVER:
2272 case SILC_SOCKET_TYPE_ROUTER:
2273 /* Packets from servers are parsed immediately */
2274 silc_server_packet_parse_real(server->schedule, 0, sock->sock,
2284 /* Parses the packet type and calls what ever routines the packet type
2285 requires. This is done for all incoming packets. */
2287 void silc_server_packet_parse_type(SilcServer server,
2288 SilcSocketConnection sock,
2289 SilcPacketContext *packet)
2291 SilcPacketType type = packet->type;
2292 SilcIDListData idata = (SilcIDListData)sock->user_data;
2294 SILC_LOG_DEBUG(("Received %s packet [flags %d]",
2295 silc_get_packet_name(type), packet->flags));
2297 /* Parse the packet type */
2299 case SILC_PACKET_DISCONNECT:
2302 char *message = NULL;
2304 if (packet->flags & SILC_PACKET_FLAG_LIST)
2306 if (packet->buffer->len < 1)
2309 status = (SilcStatus)packet->buffer->data[0];
2310 if (packet->buffer->len > 1 &&
2311 silc_utf8_valid(packet->buffer->data + 1, packet->buffer->len - 1))
2312 message = silc_memdup(packet->buffer->data + 1,
2313 packet->buffer->len - 1);
2315 SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s",
2316 sock->ip, sock->hostname,
2317 silc_get_status_message(status), status,
2318 message ? message : ""));
2321 /* Handle the disconnection from our end too */
2322 if (sock->user_data && SILC_IS_LOCAL(sock->user_data))
2323 silc_server_free_sock_user_data(server, sock, NULL);
2324 silc_server_close_connection(server, sock);
2328 case SILC_PACKET_SUCCESS:
2330 * Success received for something. For now we can have only
2331 * one protocol for connection executing at once hence this
2332 * success message is for whatever protocol is executing currently.
2334 if (packet->flags & SILC_PACKET_FLAG_LIST)
2337 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2340 case SILC_PACKET_FAILURE:
2342 * Failure received for something. For now we can have only
2343 * one protocol for connection executing at once hence this
2344 * failure message is for whatever protocol is executing currently.
2346 if (packet->flags & SILC_PACKET_FLAG_LIST)
2348 if (sock->protocol) {
2349 SilcServerFailureContext f;
2350 f = silc_calloc(1, sizeof(*f));
2354 /* We will wait 5 seconds to process this failure packet */
2355 silc_schedule_task_add(server->schedule, sock->sock,
2356 silc_server_failure_callback, (void *)f, 5, 0,
2357 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
2361 case SILC_PACKET_REJECT:
2362 if (packet->flags & SILC_PACKET_FLAG_LIST)
2367 case SILC_PACKET_NOTIFY:
2369 * Received notify packet. Server can receive notify packets from
2370 * router. Server then relays the notify messages to clients if needed.
2372 if (packet->flags & SILC_PACKET_FLAG_LIST)
2373 silc_server_notify_list(server, sock, packet);
2375 silc_server_notify(server, sock, packet);
2381 case SILC_PACKET_CHANNEL_MESSAGE:
2383 * Received channel message. Channel messages are special packets
2384 * (although probably most common ones) thus they are handled
2387 if (packet->flags & SILC_PACKET_FLAG_LIST)
2389 idata->last_receive = time(NULL);
2390 silc_server_channel_message(server, sock, packet);
2393 case SILC_PACKET_CHANNEL_KEY:
2395 * Received key for channel. As channels are created by the router
2396 * the keys are as well. We will distribute the key to all of our
2397 * locally connected clients on the particular channel. Router
2398 * never receives this channel and thus is ignored.
2400 if (packet->flags & SILC_PACKET_FLAG_LIST)
2402 silc_server_channel_key(server, sock, packet);
2408 case SILC_PACKET_COMMAND:
2410 * Recived command. Processes the command request and allocates the
2411 * command context and calls the command.
2413 if (packet->flags & SILC_PACKET_FLAG_LIST)
2415 silc_server_command_process(server, sock, packet);
2418 case SILC_PACKET_COMMAND_REPLY:
2420 * Received command reply packet. Received command reply to command. It
2421 * may be reply to command sent by us or reply to command sent by client
2422 * that we've routed further.
2424 if (packet->flags & SILC_PACKET_FLAG_LIST)
2426 silc_server_command_reply(server, sock, packet);
2430 * Private Message packets
2432 case SILC_PACKET_PRIVATE_MESSAGE:
2434 * Received private message packet. The packet is coming from either
2437 if (packet->flags & SILC_PACKET_FLAG_LIST)
2439 idata->last_receive = time(NULL);
2440 silc_server_private_message(server, sock, packet);
2443 case SILC_PACKET_PRIVATE_MESSAGE_KEY:
2445 * Private message key packet.
2447 if (packet->flags & SILC_PACKET_FLAG_LIST)
2449 silc_server_private_message_key(server, sock, packet);
2453 * Key Exchange protocol packets
2455 case SILC_PACKET_KEY_EXCHANGE:
2456 if (packet->flags & SILC_PACKET_FLAG_LIST)
2459 if (sock->protocol && sock->protocol->protocol &&
2460 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
2461 SilcServerKEInternalContext *proto_ctx =
2462 (SilcServerKEInternalContext *)sock->protocol->context;
2464 proto_ctx->packet = silc_packet_context_dup(packet);
2466 /* Let the protocol handle the packet */
2467 silc_protocol_execute(sock->protocol, server->schedule, 0, 100000);
2469 SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
2470 "protocol active, packet dropped."));
2474 case SILC_PACKET_KEY_EXCHANGE_1:
2475 if (packet->flags & SILC_PACKET_FLAG_LIST)
2478 if (sock->protocol && sock->protocol->protocol &&
2479 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2480 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2482 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2483 SilcServerRekeyInternalContext *proto_ctx =
2484 (SilcServerRekeyInternalContext *)sock->protocol->context;
2486 if (proto_ctx->packet)
2487 silc_packet_context_free(proto_ctx->packet);
2489 proto_ctx->packet = silc_packet_context_dup(packet);
2491 /* Let the protocol handle the packet */
2492 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2494 SilcServerKEInternalContext *proto_ctx =
2495 (SilcServerKEInternalContext *)sock->protocol->context;
2497 if (proto_ctx->packet)
2498 silc_packet_context_free(proto_ctx->packet);
2500 proto_ctx->packet = silc_packet_context_dup(packet);
2501 proto_ctx->dest_id_type = packet->src_id_type;
2502 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2503 packet->src_id_type);
2504 if (!proto_ctx->dest_id)
2507 /* Let the protocol handle the packet */
2508 silc_protocol_execute(sock->protocol, server->schedule,
2512 SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
2513 "protocol active, packet dropped."));
2517 case SILC_PACKET_KEY_EXCHANGE_2:
2518 if (packet->flags & SILC_PACKET_FLAG_LIST)
2521 if (sock->protocol && sock->protocol->protocol &&
2522 (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
2523 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
2525 if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2526 SilcServerRekeyInternalContext *proto_ctx =
2527 (SilcServerRekeyInternalContext *)sock->protocol->context;
2529 if (proto_ctx->packet)
2530 silc_packet_context_free(proto_ctx->packet);
2532 proto_ctx->packet = silc_packet_context_dup(packet);
2534 /* Let the protocol handle the packet */
2535 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2537 SilcServerKEInternalContext *proto_ctx =
2538 (SilcServerKEInternalContext *)sock->protocol->context;
2540 if (proto_ctx->packet)
2541 silc_packet_context_free(proto_ctx->packet);
2543 proto_ctx->packet = silc_packet_context_dup(packet);
2544 proto_ctx->dest_id_type = packet->src_id_type;
2545 proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2546 packet->src_id_type);
2547 if (!proto_ctx->dest_id)
2550 /* Let the protocol handle the packet */
2551 silc_protocol_execute(sock->protocol, server->schedule,
2555 SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
2556 "protocol active, packet dropped."));
2560 case SILC_PACKET_CONNECTION_AUTH_REQUEST:
2562 * Connection authentication request packet. When we receive this packet
2563 * we will send to the other end information about our mandatory
2564 * authentication method for the connection. This packet maybe received
2567 if (packet->flags & SILC_PACKET_FLAG_LIST)
2569 silc_server_connection_auth_request(server, sock, packet);
2573 * Connection Authentication protocol packets
2575 case SILC_PACKET_CONNECTION_AUTH:
2576 /* Start of the authentication protocol. We receive here the
2577 authentication data and will verify it. */
2578 if (packet->flags & SILC_PACKET_FLAG_LIST)
2581 if (sock->protocol && sock->protocol->protocol->type
2582 == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
2584 SilcServerConnAuthInternalContext *proto_ctx =
2585 (SilcServerConnAuthInternalContext *)sock->protocol->context;
2587 proto_ctx->packet = silc_packet_context_dup(packet);
2589 /* Let the protocol handle the packet */
2590 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2592 SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
2593 "protocol active, packet dropped."));
2597 case SILC_PACKET_NEW_ID:
2599 * Received New ID packet. This includes some new ID that has been
2600 * created. It may be for client, server or channel. This is the way
2601 * to distribute information about new registered entities in the
2604 if (packet->flags & SILC_PACKET_FLAG_LIST)
2605 silc_server_new_id_list(server, sock, packet);
2607 silc_server_new_id(server, sock, packet);
2610 case SILC_PACKET_NEW_CLIENT:
2612 * Received new client packet. This includes client information that
2613 * we will use to create initial client ID. After creating new
2614 * ID we will send it to the client.
2616 if (packet->flags & SILC_PACKET_FLAG_LIST)
2618 silc_server_new_client(server, sock, packet);
2621 case SILC_PACKET_NEW_SERVER:
2623 * Received new server packet. This includes Server ID and some other
2624 * information that we may save. This is received after server has
2627 if (packet->flags & SILC_PACKET_FLAG_LIST)
2629 silc_server_new_server(server, sock, packet);
2632 case SILC_PACKET_NEW_CHANNEL:
2634 * Received new channel packet. Information about new channel in the
2635 * network are distributed using this packet.
2637 if (packet->flags & SILC_PACKET_FLAG_LIST)
2638 silc_server_new_channel_list(server, sock, packet);
2640 silc_server_new_channel(server, sock, packet);
2643 case SILC_PACKET_HEARTBEAT:
2645 * Received heartbeat.
2647 if (packet->flags & SILC_PACKET_FLAG_LIST)
2651 case SILC_PACKET_KEY_AGREEMENT:
2653 * Received heartbeat.
2655 if (packet->flags & SILC_PACKET_FLAG_LIST)
2657 silc_server_key_agreement(server, sock, packet);
2660 case SILC_PACKET_REKEY:
2662 * Received re-key packet. The sender wants to regenerate the session
2665 if (packet->flags & SILC_PACKET_FLAG_LIST)
2667 silc_server_rekey(server, sock, packet);
2670 case SILC_PACKET_REKEY_DONE:
2672 * The re-key is done.
2674 if (packet->flags & SILC_PACKET_FLAG_LIST)
2677 if (sock->protocol && sock->protocol->protocol &&
2678 sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2680 SilcServerRekeyInternalContext *proto_ctx =
2681 (SilcServerRekeyInternalContext *)sock->protocol->context;
2683 if (proto_ctx->packet)
2684 silc_packet_context_free(proto_ctx->packet);
2686 proto_ctx->packet = silc_packet_context_dup(packet);
2688 /* Let the protocol handle the packet */
2689 silc_protocol_execute(sock->protocol, server->schedule, 0, 0);
2691 SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2692 "protocol active, packet dropped."));
2696 case SILC_PACKET_FTP:
2698 if (packet->flags & SILC_PACKET_FLAG_LIST)
2700 silc_server_ftp(server, sock, packet);
2703 case SILC_PACKET_RESUME_CLIENT:
2705 if (packet->flags & SILC_PACKET_FLAG_LIST)
2707 silc_server_resume_client(server, sock, packet);
2710 case SILC_PACKET_RESUME_ROUTER:
2711 /* Resume router packet received. This packet is received for backup
2712 router resuming protocol. */
2713 if (packet->flags & SILC_PACKET_FLAG_LIST)
2715 silc_server_backup_resume_router(server, sock, packet);
2719 SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2724 /* Creates connection to a remote router. */
2726 void silc_server_create_connection(SilcServer server,
2727 const char *remote_host, SilcUInt32 port)
2729 SilcServerConnection sconn;
2731 /* Allocate connection object for hold connection specific stuff. */
2732 sconn = silc_calloc(1, sizeof(*sconn));
2733 sconn->server = server;
2734 sconn->remote_host = strdup(remote_host);
2735 sconn->remote_port = port;
2736 sconn->no_reconnect = TRUE;
2738 silc_schedule_task_add(server->schedule, 0,
2739 silc_server_connect_router,
2740 (void *)sconn, 0, 1, SILC_TASK_TIMEOUT,
2741 SILC_TASK_PRI_NORMAL);
2744 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2746 silc_socket_free(context);
2749 /* Closes connection to socket connection */
2751 void silc_server_close_connection(SilcServer server,
2752 SilcSocketConnection sock)
2754 if (!server->sockets[sock->sock] && SILC_IS_DISCONNECTED(sock)) {
2755 silc_schedule_task_add(server->schedule, 0,
2756 silc_server_close_connection_final,
2757 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2758 SILC_TASK_PRI_NORMAL);
2762 SILC_LOG_INFO(("Closing connection %s:%d [%s]", sock->hostname,
2764 (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2765 sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2766 sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2769 /* We won't listen for this connection anymore */
2770 silc_schedule_unset_listen_fd(server->schedule, sock->sock);
2772 /* Unregister all tasks */
2773 silc_schedule_task_del_by_fd(server->schedule, sock->sock);
2775 /* Close the actual connection */
2776 silc_net_close_connection(sock->sock);
2777 server->sockets[sock->sock] = NULL;
2779 /* If sock->user_data is NULL then we'll check for active protocols
2780 here since the silc_server_free_sock_user_data has not been called
2781 for this connection. */
2782 if (!sock->user_data) {
2783 /* If any protocol is active cancel its execution. It will call
2784 the final callback which will finalize the disconnection. */
2785 if (sock->protocol) {
2786 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
2787 silc_protocol_cancel(sock->protocol, server->schedule);
2788 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
2789 silc_protocol_execute_final(sock->protocol, server->schedule);
2790 sock->protocol = NULL;
2795 silc_schedule_task_add(server->schedule, 0,
2796 silc_server_close_connection_final,
2797 (void *)sock, 0, 1, SILC_TASK_TIMEOUT,
2798 SILC_TASK_PRI_NORMAL);
2801 /* Sends disconnect message to remote connection and disconnects the
2804 void silc_server_disconnect_remote(SilcServer server,
2805 SilcSocketConnection sock,
2806 SilcStatus status, ...)
2809 unsigned char buf[512];
2817 memset(buf, 0, sizeof(buf));
2818 va_start(ap, status);
2819 cp = va_arg(ap, char *);
2821 vsnprintf(buf, sizeof(buf) - 1, cp, ap);
2826 SILC_LOG_DEBUG(("Disconnecting remote host"));
2828 /* Notify remote end that the conversation is over. The notify message
2829 is tried to be sent immediately. */
2833 len += silc_utf8_encoded_len(buf, strlen(buf), SILC_STRING_ASCII);
2835 buffer = silc_buffer_alloc_size(len);
2839 buffer->data[0] = status;
2841 silc_utf8_encode(buf, strlen(buf), SILC_STRING_ASCII, buffer->data + 1,
2843 silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,
2844 buffer->data, buffer->len, TRUE);
2845 silc_buffer_free(buffer);
2848 silc_server_packet_queue_purge(server, sock);
2850 /* Mark the connection to be disconnected */
2851 SILC_SET_DISCONNECTED(sock);
2852 silc_server_close_connection(server, sock);
2857 SilcClientEntry client;
2858 } *FreeClientInternal;
2860 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2862 FreeClientInternal i = (FreeClientInternal)context;
2864 silc_idlist_del_data(i->client);
2865 silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2869 /* Frees client data and notifies about client's signoff. */
2871 void silc_server_free_client_data(SilcServer server,
2872 SilcSocketConnection sock,
2873 SilcClientEntry client,
2875 const char *signoff)
2877 FreeClientInternal i = silc_calloc(1, sizeof(*i));
2879 SILC_LOG_DEBUG(("Freeing client data"));
2882 if (!client->router && !client->connection &&
2883 !(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
2884 SILC_LOG_ERROR(("****** freeing data for already unregistered client -s"));
2885 SILC_LOG_ERROR(("****** Contact Pekka"));
2886 SILC_LOG_ERROR(("****** freeing data for already unregistered client -e"));
2891 /* If there is pending outgoing data for the client then purge it
2892 to the network before removing the client entry. */
2893 silc_server_packet_queue_purge(server, sock);
2896 /* Check if anyone is watching this nickname */
2897 if (server->server_type == SILC_ROUTER)
2898 silc_server_check_watcher_list(server, client, NULL,
2899 SILC_NOTIFY_TYPE_SIGNOFF);
2901 /* Send SIGNOFF notify to routers. */
2903 silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2904 SILC_BROADCAST(server), client->id,
2908 /* Remove client from all channels */
2910 silc_server_remove_from_channels(server, NULL, client,
2911 TRUE, (char *)signoff, TRUE);
2913 silc_server_remove_from_channels(server, NULL, client,
2914 FALSE, NULL, FALSE);
2916 /* Remove this client from watcher list if it is */
2917 silc_server_del_from_watcher_list(server, client);
2919 /* Update statistics */
2920 server->stat.my_clients--;
2921 server->stat.clients--;
2922 if (server->stat.cell_clients)
2923 server->stat.cell_clients--;
2924 SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2925 SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2926 silc_schedule_task_del_by_context(server->schedule, client);
2928 /* We will not delete the client entry right away. We will take it
2929 into history (for WHOWAS command) for 5 minutes */
2932 silc_schedule_task_add(server->schedule, 0,
2933 silc_server_free_client_data_timeout,
2935 SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2936 client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2938 client->router = NULL;
2939 client->connection = NULL;
2942 /* Frees user_data pointer from socket connection object. This also sends
2943 appropriate notify packets to the network to inform about leaving
2946 void silc_server_free_sock_user_data(SilcServer server,
2947 SilcSocketConnection sock,
2948 const char *signoff_message)
2950 switch (sock->type) {
2951 case SILC_SOCKET_TYPE_CLIENT:
2953 SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2954 silc_server_free_client_data(server, sock, user_data, TRUE,
2958 case SILC_SOCKET_TYPE_SERVER:
2959 case SILC_SOCKET_TYPE_ROUTER:
2961 SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2962 SilcServerEntry backup_router = NULL;
2964 SILC_LOG_DEBUG(("Freeing server data"));
2967 backup_router = silc_server_backup_get(server, user_data->id);
2969 /* If this was our primary router connection then we're lost to
2970 the outside world. */
2971 if (server->router == user_data) {
2972 /* Check whether we have a backup router connection */
2973 if (!backup_router || backup_router == user_data) {
2974 silc_schedule_task_add(server->schedule, 0,
2975 silc_server_connect_to_router,
2978 SILC_TASK_PRI_NORMAL);
2980 server->id_entry->router = NULL;
2981 server->router = NULL;
2982 server->standalone = TRUE;
2983 backup_router = NULL;
2985 if (server->id_entry != backup_router) {
2986 SILC_LOG_INFO(("New primary router is backup router %s",
2987 backup_router->server_name));
2988 server->id_entry->router = backup_router;
2989 server->router = backup_router;
2990 server->router_connect = time(0);
2991 server->backup_primary = TRUE;
2993 SILC_LOG_INFO(("We are now new primary router in this cell"));
2994 server->id_entry->router = NULL;
2995 server->router = NULL;
2996 server->standalone = TRUE;
2998 /* We stop here to take a breath */
3002 if (server->server_type == SILC_BACKUP_ROUTER) {
3003 server->server_type = SILC_ROUTER;
3005 /* We'll need to constantly try to reconnect to the primary
3006 router so that we'll see when it comes back online. */
3007 silc_server_backup_reconnect(server, sock->ip, sock->port,
3008 silc_server_backup_connected,
3012 /* Mark this connection as replaced */
3013 silc_server_backup_replaced_add(server, user_data->id,
3016 } else if (backup_router) {
3017 SILC_LOG_INFO(("Enabling the use of backup router %s",
3018 backup_router->server_name));
3019 SILC_LOG_DEBUG(("Enabling the use of backup router %s",
3020 backup_router->server_name));
3022 /* Mark this connection as replaced */
3023 silc_server_backup_replaced_add(server, user_data->id,
3027 if (!backup_router) {
3028 /* Remove all servers that are originated from this server, and
3029 remove the clients of those servers too. */
3030 silc_server_remove_servers_by_server(server, user_data, TRUE);
3032 /* Remove the clients that this server owns as they will become
3034 silc_server_remove_clients_by_server(server, user_data,
3037 /* Remove channels owned by this server */
3038 if (server->server_type == SILC_SERVER)
3039 silc_server_remove_channels_by_server(server, user_data);
3041 /* Enable local server connections that may be disabled */
3042 silc_server_local_servers_toggle_enabled(server, TRUE);
3044 /* Update the client entries of this server to the new backup
3045 router. If we are the backup router we also resolve the real
3046 servers for the clients. After updating is over this also
3047 removes the clients that this server explicitly owns. */
3048 silc_server_update_clients_by_server(server, user_data,
3049 backup_router, TRUE);
3051 /* If we are router and just lost our primary router (now standlaone)
3052 we remove everything that was behind it, since we don't know
3054 if (server->server_type == SILC_ROUTER && server->standalone)
3055 /* Remove all servers that are originated from this server, and
3056 remove the clients of those servers too. */
3057 silc_server_remove_servers_by_server(server, user_data, TRUE);
3059 /* Finally remove the clients that are explicitly owned by this
3060 server. They go down with the server. */
3061 silc_server_remove_clients_by_server(server, user_data,
3064 /* Update our server cache to use the new backup router too. */
3065 silc_server_update_servers_by_server(server, user_data, backup_router);
3066 if (server->server_type == SILC_SERVER)
3067 silc_server_update_channels_by_server(server, user_data,
3070 /* Send notify about primary router going down to local operators */
3071 if (server->backup_router)
3072 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3073 SILC_NOTIFY_TYPE_NONE,
3074 ("%s switched to backup router %s "
3075 "(we are primary router now)",
3076 server->server_name, server->server_name));
3078 SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3079 SILC_NOTIFY_TYPE_NONE,
3080 ("%s switched to backup router %s",
3081 server->server_name,
3082 server->router->server_name));
3085 /* Free the server entry */
3086 silc_server_backup_del(server, user_data);
3087 silc_server_backup_replaced_del(server, user_data);
3088 silc_idlist_del_data(user_data);
3089 if (!silc_idlist_del_server(server->local_list, user_data))
3090 silc_idlist_del_server(server->global_list, user_data);
3091 if (sock->type == SILC_SOCKET_TYPE_SERVER) {
3092 server->stat.my_servers--;
3094 server->stat.my_routers--;
3095 server->stat.routers--;
3097 server->stat.servers--;
3098 if (server->server_type == SILC_ROUTER)
3099 server->stat.cell_servers--;
3101 if (backup_router && backup_router != server->id_entry) {
3102 /* Announce all of our stuff that was created about 5 minutes ago.
3103 The backup router knows all the other stuff already. */
3104 if (server->server_type == SILC_ROUTER)
3105 silc_server_announce_servers(server, FALSE, time(0) - 300,
3106 backup_router->connection);
3108 /* Announce our clients and channels to the router */
3109 silc_server_announce_clients(server, time(0) - 300,
3110 backup_router->connection);
3111 silc_server_announce_channels(server, time(0) - 300,
3112 backup_router->connection);
3118 SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
3120 SILC_LOG_DEBUG(("Freeing unknown connection data"));
3122 silc_idlist_del_data(user_data);
3123 silc_free(user_data);
3128 /* If any protocol is active cancel its execution */
3129 if (sock->protocol) {
3130 SILC_LOG_DEBUG(("Cancelling protocol, calling final callback"));
3131 silc_protocol_cancel(sock->protocol, server->schedule);
3132 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3133 silc_protocol_execute_final(sock->protocol, server->schedule);
3134 sock->protocol = NULL;
3137 sock->user_data = NULL;
3140 /* Removes client from all channels it has joined. This is used when client
3141 connection is disconnected. If the client on a channel is last, the
3142 channel is removed as well. This sends the SIGNOFF notify types. */
3144 void silc_server_remove_from_channels(SilcServer server,
3145 SilcSocketConnection sock,
3146 SilcClientEntry client,
3148 const char *signoff_message,
3151 SilcChannelEntry channel;
3152 SilcChannelClientEntry chl;
3153 SilcHashTableList htl;
3154 SilcBuffer clidp = NULL;
3159 SILC_LOG_DEBUG(("Removing client from joined channels"));
3161 if (notify && !client->id)
3165 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3170 /* Remove the client from all channels. The client is removed from
3171 the channels' user list. */
3172 silc_hash_table_list(client->channels, &htl);
3173 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3174 channel = chl->channel;
3176 /* Remove channel if this is last client leaving the channel, unless
3177 the channel is permanent. */
3178 if (server->server_type == SILC_ROUTER &&
3179 silc_hash_table_count(channel->user_list) < 2) {
3180 silc_server_channel_delete(server, channel);
3184 silc_hash_table_del(client->channels, channel);
3185 silc_hash_table_del(channel->user_list, chl->client);
3186 channel->user_count--;
3188 /* If there is no global users on the channel anymore mark the channel
3189 as local channel. Do not check if the removed client is local client. */
3190 if (server->server_type != SILC_ROUTER && channel->global_users &&
3191 chl->client->router && !silc_server_channel_has_global(channel))
3192 channel->global_users = FALSE;
3196 /* Update statistics */
3197 if (SILC_IS_LOCAL(client))
3198 server->stat.my_chanclients--;
3199 if (server->server_type == SILC_ROUTER) {
3200 server->stat.cell_chanclients--;
3201 server->stat.chanclients--;
3204 /* If there is not at least one local user on the channel then we don't
3205 need the channel entry anymore, we can remove it safely, unless the
3206 channel is permanent channel */
3207 if (server->server_type != SILC_ROUTER &&
3208 !silc_server_channel_has_local(channel)) {
3209 /* Notify about leaving client if this channel has global users. */
3210 if (notify && channel->global_users)
3211 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3212 SILC_NOTIFY_TYPE_SIGNOFF,
3213 signoff_message ? 2 : 1,
3214 clidp->data, clidp->len,
3215 signoff_message, signoff_message ?
3216 strlen(signoff_message) : 0);
3218 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3219 silc_server_channel_delete(server, channel);
3223 /* Send notify to channel about client leaving SILC and channel too */
3225 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3226 SILC_NOTIFY_TYPE_SIGNOFF,
3227 signoff_message ? 2 : 1,
3228 clidp->data, clidp->len,
3229 signoff_message, signoff_message ?
3230 strlen(signoff_message) : 0);
3232 /* Re-generate channel key if needed */
3233 if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3234 if (!silc_server_create_channel_key(server, channel, 0))
3237 /* Send the channel key to the channel. The key of course is not sent
3238 to the client who was removed from the channel. */
3239 silc_server_send_channel_key(server, client->connection, channel,
3240 server->server_type == SILC_ROUTER ?
3241 FALSE : !server->standalone);
3245 silc_hash_table_list_reset(&htl);
3247 silc_buffer_free(clidp);
3250 /* Removes client from one channel. This is used for example when client
3251 calls LEAVE command to remove itself from the channel. Returns TRUE
3252 if channel still exists and FALSE if the channel is removed when
3253 last client leaves the channel. If `notify' is FALSE notify messages
3256 bool silc_server_remove_from_one_channel(SilcServer server,
3257 SilcSocketConnection sock,
3258 SilcChannelEntry channel,
3259 SilcClientEntry client,
3262 SilcChannelClientEntry chl;
3265 SILC_LOG_DEBUG(("Removing %s from channel %s",
3266 silc_id_render(client->id, SILC_ID_CLIENT),
3267 channel->channel_name));
3269 /* Get the entry to the channel, if this client is not on the channel
3271 if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3274 /* Remove channel if this is last client leaving the channel, unless
3275 the channel is permanent. */
3276 if (server->server_type == SILC_ROUTER &&
3277 silc_hash_table_count(channel->user_list) < 2) {
3278 silc_server_channel_delete(server, channel);
3282 silc_hash_table_del(client->channels, chl->channel);
3283 silc_hash_table_del(channel->user_list, chl->client);
3284 channel->user_count--;
3286 /* If there is no global users on the channel anymore mark the channel
3287 as local channel. Do not check if the client is local client. */
3288 if (server->server_type != SILC_ROUTER && channel->global_users &&
3289 chl->client->router && !silc_server_channel_has_global(channel))
3290 channel->global_users = FALSE;
3294 /* Update statistics */
3295 if (SILC_IS_LOCAL(client))
3296 server->stat.my_chanclients--;
3297 if (server->server_type == SILC_ROUTER) {
3298 server->stat.cell_chanclients--;
3299 server->stat.chanclients--;
3302 clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3306 /* If there is not at least one local user on the channel then we don't
3307 need the channel entry anymore, we can remove it safely, unless the
3308 channel is permanent channel */
3309 if (server->server_type != SILC_ROUTER &&
3310 !silc_server_channel_has_local(channel)) {
3311 /* Notify about leaving client if this channel has global users. */
3312 if (notify && channel->global_users)
3313 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3314 SILC_NOTIFY_TYPE_LEAVE, 1,
3315 clidp->data, clidp->len);
3317 silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3318 silc_server_channel_delete(server, channel);
3319 silc_buffer_free(clidp);
3323 /* Send notify to channel about client leaving the channel */
3325 silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
3326 SILC_NOTIFY_TYPE_LEAVE, 1,
3327 clidp->data, clidp->len);
3329 silc_buffer_free(clidp);
3333 /* Timeout callback. This is called if connection is idle or for some
3334 other reason is not responding within some period of time. This
3335 disconnects the remote end. */
3337 SILC_TASK_CALLBACK(silc_server_timeout_remote)
3339 SilcServer server = (SilcServer)context;
3340 SilcSocketConnection sock = server->sockets[fd];
3341 SilcProtocolType protocol = 0;
3343 SILC_LOG_DEBUG(("Start"));
3348 SILC_LOG_ERROR(("No response from %s (%s), Connection timeout",
3349 sock->hostname, sock->ip));
3351 /* If we have protocol active we must assure that we call the protocol's
3352 final callback so that all the memory is freed. */
3353 if (sock->protocol) {
3354 protocol = sock->protocol->protocol->type;
3355 silc_protocol_cancel(sock->protocol, server->schedule);
3356 sock->protocol->state = SILC_PROTOCOL_STATE_ERROR;
3357 silc_protocol_execute_final(sock->protocol, server->schedule);
3358 sock->protocol = NULL;
3362 if (sock->user_data)
3363 silc_server_free_sock_user_data(server, sock, NULL);
3365 silc_server_disconnect_remote(server, sock,
3367 SILC_PROTOCOL_SERVER_CONNECTION_AUTH ?
3368 SILC_STATUS_ERR_AUTH_FAILED :
3369 SILC_STATUS_ERR_KEY_EXCHANGE_FAILED,
3370 "Connection timeout");
3373 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3374 function may be used only by router. In real SILC network all channels
3375 are created by routers thus this function is never used by normal
3378 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3379 SilcServerID *router_id,
3385 SilcChannelID *channel_id;
3386 SilcChannelEntry entry;
3390 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3393 cipher = SILC_DEFAULT_CIPHER;
3395 hmac = SILC_DEFAULT_HMAC;
3397 /* Allocate cipher */
3398 if (!silc_cipher_alloc(cipher, &key))
3402 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3403 silc_cipher_free(key);
3407 channel_name = strdup(channel_name);
3409 /* Create the channel ID */
3410 if (!silc_id_create_channel_id(server, router_id, server->rng,
3412 silc_free(channel_name);
3413 silc_cipher_free(key);
3414 silc_hmac_free(newhmac);
3418 /* Create the channel */
3419 entry = silc_idlist_add_channel(server->local_list, channel_name,
3420 SILC_CHANNEL_MODE_NONE, channel_id,
3421 NULL, key, newhmac, 0);
3423 silc_free(channel_name);
3424 silc_cipher_free(key);
3425 silc_hmac_free(newhmac);
3426 silc_free(channel_id);
3430 entry->cipher = strdup(cipher);
3431 entry->hmac_name = strdup(hmac);
3433 /* Now create the actual key material */
3434 if (!silc_server_create_channel_key(server, entry,
3435 silc_cipher_get_key_len(key) / 8)) {
3436 silc_idlist_del_channel(server->local_list, entry);
3440 /* Notify other routers about the new channel. We send the packet
3441 to our primary route. */
3443 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3444 channel_name, entry->id,
3445 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3448 /* Distribute to backup routers */
3449 if (broadcast && server->server_type == SILC_ROUTER) {
3452 SilcUInt32 name_len = strlen(channel_name);
3453 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3454 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3456 packet = silc_channel_payload_encode(channel_name, name_len,
3457 cid, channel_id_len, entry->mode);
3458 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3459 packet->data, packet->len, FALSE, TRUE);
3461 silc_buffer_free(packet);
3464 server->stat.my_channels++;
3465 if (server->server_type == SILC_ROUTER) {
3466 server->stat.channels++;
3467 server->stat.cell_channels++;
3468 entry->users_resolved = TRUE;
3474 /* Same as above but creates the channel with Channel ID `channel_id. */
3477 silc_server_create_new_channel_with_id(SilcServer server,
3481 SilcChannelID *channel_id,
3484 SilcChannelEntry entry;
3488 SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3491 cipher = SILC_DEFAULT_CIPHER;
3493 hmac = SILC_DEFAULT_HMAC;
3495 /* Allocate cipher */
3496 if (!silc_cipher_alloc(cipher, &key))
3500 if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3501 silc_cipher_free(key);
3505 channel_name = strdup(channel_name);
3507 /* Create the channel */
3508 entry = silc_idlist_add_channel(server->local_list, channel_name,
3509 SILC_CHANNEL_MODE_NONE, channel_id,
3510 NULL, key, newhmac, 0);
3512 silc_cipher_free(key);
3513 silc_hmac_free(newhmac);
3514 silc_free(channel_name);
3518 /* Now create the actual key material */
3519 if (!silc_server_create_channel_key(server, entry,
3520 silc_cipher_get_key_len(key) / 8)) {
3521 silc_idlist_del_channel(server->local_list, entry);
3525 /* Notify other routers about the new channel. We send the packet
3526 to our primary route. */
3528 silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3529 channel_name, entry->id,
3530 silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3533 /* Distribute to backup routers */
3534 if (broadcast && server->server_type == SILC_ROUTER) {
3537 SilcUInt32 name_len = strlen(channel_name);
3538 SilcUInt32 channel_id_len = silc_id_get_len(entry->id, SILC_ID_CHANNEL);
3539 cid = silc_id_id2str(entry->id, SILC_ID_CHANNEL);
3541 packet = silc_channel_payload_encode(channel_name, name_len,
3542 cid, channel_id_len, entry->mode);
3543 silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3544 packet->data, packet->len, FALSE, TRUE);
3546 silc_buffer_free(packet);
3549 server->stat.my_channels++;
3550 if (server->server_type == SILC_ROUTER) {
3551 server->stat.channels++;
3552 server->stat.cell_channels++;
3553 entry->users_resolved = TRUE;
3559 /* Channel's key re-key timeout callback. */
3561 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3563 SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3564 SilcServer server = (SilcServer)rekey->context;
3568 if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3571 silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3574 /* Generates new channel key. This is used to create the initial channel key
3575 but also to re-generate new key for channel. If `key_len' is provided
3576 it is the bytes of the key length. */
3578 bool silc_server_create_channel_key(SilcServer server,
3579 SilcChannelEntry channel,
3583 unsigned char channel_key[32], hash[32];
3586 if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3587 SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3591 SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3593 if (!channel->channel_key)
3594 if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->channel_key)) {
3595 channel->channel_key = NULL;
3601 else if (channel->key_len)
3602 len = channel->key_len / 8;
3604 len = silc_cipher_get_key_len(channel->channel_key) / 8;
3606 /* Create channel key */
3607 for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3610 silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
3612 /* Remove old key if exists */
3614 memset(channel->key, 0, channel->key_len / 8);
3615 silc_free(channel->key);
3619 channel->key_len = len * 8;
3620 channel->key = silc_memdup(channel_key, len);
3621 memset(channel_key, 0, sizeof(channel_key));
3623 /* Generate HMAC key from the channel key data and set it */
3625 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3626 silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3627 silc_hmac_set_key(channel->hmac, hash,
3628 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3629 memset(hash, 0, sizeof(hash));
3631 if (server->server_type == SILC_ROUTER) {
3632 if (!channel->rekey)
3633 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3634 channel->rekey->context = (void *)server;
3635 channel->rekey->channel = channel;
3636 channel->rekey->key_len = key_len;
3637 if (channel->rekey->task)
3638 silc_schedule_task_del(server->schedule, channel->rekey->task);
3640 channel->rekey->task =
3641 silc_schedule_task_add(server->schedule, 0,
3642 silc_server_channel_key_rekey,
3643 (void *)channel->rekey,
3644 server->config->channel_rekey_secs, 0,
3646 SILC_TASK_PRI_NORMAL);
3652 /* Saves the channel key found in the encoded `key_payload' buffer. This
3653 function is used when we receive Channel Key Payload and also when we're
3654 processing JOIN command reply. Returns entry to the channel. */
3656 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3657 SilcBuffer key_payload,
3658 SilcChannelEntry channel)
3660 SilcChannelKeyPayload payload = NULL;
3661 SilcChannelID *id = NULL;
3662 unsigned char *tmp, hash[32];
3666 /* Decode channel key payload */
3667 payload = silc_channel_key_payload_parse(key_payload->data,
3670 SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3675 /* Get the channel entry */
3678 /* Get channel ID */
3679 tmp = silc_channel_key_get_id(payload, &tmp_len);
3680 id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
3686 channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
3688 channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
3690 SILC_LOG_ERROR(("Received key for non-existent channel %s",
3691 silc_id_render(id, SILC_ID_CHANNEL)));
3697 SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3699 tmp = silc_channel_key_get_key(payload, &tmp_len);
3705 cipher = silc_channel_key_get_cipher(payload, NULL);
3711 /* Remove old key if exists */
3713 memset(channel->key, 0, channel->key_len / 8);
3714 silc_free(channel->key);
3715 silc_cipher_free(channel->channel_key);
3718 /* Create new cipher */
3719 if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3720 channel->channel_key = NULL;
3725 if (channel->cipher)
3726 silc_free(channel->cipher);
3727 channel->cipher = strdup(cipher);
3730 channel->key_len = tmp_len * 8;
3731 channel->key = silc_memdup(tmp, tmp_len);
3732 silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3734 /* Generate HMAC key from the channel key data and set it */
3736 silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac);
3737 silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3738 silc_hmac_set_key(channel->hmac, hash,
3739 silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3741 memset(hash, 0, sizeof(hash));
3742 memset(tmp, 0, tmp_len);
3744 if (server->server_type == SILC_ROUTER) {
3745 if (!channel->rekey)
3746 channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3747 channel->rekey->context = (void *)server;
3748 channel->rekey->channel = channel;
3749 if (channel->rekey->task)
3750 silc_schedule_task_del(server->schedule, channel->rekey->task);
3752 channel->rekey->task =
3753 silc_schedule_task_add(server->schedule, 0,
3754 silc_server_channel_key_rekey,
3755 (void *)channel->rekey,
3756 server->config->channel_rekey_secs, 0,
3758 SILC_TASK_PRI_NORMAL);
3764 silc_channel_key_payload_free(payload);
3769 /* Heartbeat callback. This function is set as argument for the
3770 silc_socket_set_heartbeat function. The library will call this function
3771 at the set time interval. */
3773 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3776 SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3778 SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname, sock->ip));
3780 /* Send the heartbeat */
3781 silc_server_send_heartbeat(hb->server, sock);
3784 /* Returns assembled of all servers in the given ID list. The packet's
3785 form is dictated by the New ID payload. */
3787 static void silc_server_announce_get_servers(SilcServer server,
3788 SilcServerEntry remote,
3790 SilcBuffer *servers,
3791 unsigned long creation_time)
3793 SilcIDCacheList list;
3794 SilcIDCacheEntry id_cache;
3795 SilcServerEntry entry;
3798 /* Go through all clients in the list */
3799 if (silc_idcache_get_all(id_list->servers, &list)) {
3800 if (silc_idcache_list_first(list, &id_cache)) {
3802 entry = (SilcServerEntry)id_cache->context;
3804 /* Do not announce the one we've sending our announcements and
3805 do not announce ourself. Also check the creation time if it's
3807 if ((entry == remote) || (entry == server->id_entry) ||
3808 (creation_time && entry->data.created < creation_time)) {
3809 if (!silc_idcache_list_next(list, &id_cache))
3814 idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3816 *servers = silc_buffer_realloc(*servers,
3818 (*servers)->truelen + idp->len :
3820 silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3821 silc_buffer_put(*servers, idp->data, idp->len);
3822 silc_buffer_pull(*servers, idp->len);
3823 silc_buffer_free(idp);
3825 if (!silc_idcache_list_next(list, &id_cache))
3830 silc_idcache_list_free(list);
3835 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3841 p = silc_notify_payload_encode(notify, argc, ap);
3847 /* This function is used by router to announce existing servers to our
3848 primary router when we've connected to it. If `creation_time' is non-zero
3849 then only the servers that has been created after the `creation_time'
3850 will be announced. */
3852 void silc_server_announce_servers(SilcServer server, bool global,
3853 unsigned long creation_time,
3854 SilcSocketConnection remote)
3856 SilcBuffer servers = NULL;
3858 SILC_LOG_DEBUG(("Announcing servers"));
3860 /* Get servers in local list */
3861 silc_server_announce_get_servers(server, remote->user_data,
3862 server->local_list, &servers,
3866 /* Get servers in global list */
3867 silc_server_announce_get_servers(server, remote->user_data,
3868 server->global_list, &servers,
3872 silc_buffer_push(servers, servers->data - servers->head);
3873 SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3875 /* Send the packet */
3876 silc_server_packet_send(server, remote,
3877 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3878 servers->data, servers->len, TRUE);
3880 silc_buffer_free(servers);
3884 /* Returns assembled packet of all clients in the given ID list. The
3885 packet's form is dictated by the New ID Payload. */
3887 static void silc_server_announce_get_clients(SilcServer server,
3889 SilcBuffer *clients,
3891 unsigned long creation_time)
3893 SilcIDCacheList list;
3894 SilcIDCacheEntry id_cache;
3895 SilcClientEntry client;
3898 unsigned char mode[4];
3900 /* Go through all clients in the list */
3901 if (silc_idcache_get_all(id_list->clients, &list)) {
3902 if (silc_idcache_list_first(list, &id_cache)) {
3904 client = (SilcClientEntry)id_cache->context;
3906 if (creation_time && client->data.created < creation_time) {
3907 if (!silc_idcache_list_next(list, &id_cache))
3912 idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3914 *clients = silc_buffer_realloc(*clients,
3916 (*clients)->truelen + idp->len :
3918 silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3919 silc_buffer_put(*clients, idp->data, idp->len);
3920 silc_buffer_pull(*clients, idp->len);
3922 SILC_PUT32_MSB(client->mode, mode);
3924 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
3925 2, idp->data, idp->len,
3927 *umodes = silc_buffer_realloc(*umodes,
3929 (*umodes)->truelen + tmp->len :
3931 silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
3932 silc_buffer_put(*umodes, tmp->data, tmp->len);
3933 silc_buffer_pull(*umodes, tmp->len);
3934 silc_buffer_free(tmp);
3936 silc_buffer_free(idp);
3938 if (!silc_idcache_list_next(list, &id_cache))
3943 silc_idcache_list_free(list);
3947 /* This function is used to announce our existing clients to our router
3948 when we've connected to it. If `creation_time' is non-zero then only
3949 the clients that has been created after the `creation_time' will be
3952 void silc_server_announce_clients(SilcServer server,
3953 unsigned long creation_time,
3954 SilcSocketConnection remote)
3956 SilcBuffer clients = NULL;
3957 SilcBuffer umodes = NULL;
3959 SILC_LOG_DEBUG(("Announcing clients"));
3961 /* Get clients in local list */
3962 silc_server_announce_get_clients(server, server->local_list,
3963 &clients, &umodes, creation_time);
3965 /* As router we announce our global list as well */
3966 if (server->server_type == SILC_ROUTER)
3967 silc_server_announce_get_clients(server, server->global_list,
3968 &clients, &umodes, creation_time);
3971 silc_buffer_push(clients, clients->data - clients->head);
3972 SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3974 /* Send the packet */
3975 silc_server_packet_send(server, remote,
3976 SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3977 clients->data, clients->len, TRUE);
3979 silc_buffer_free(clients);
3983 silc_buffer_push(umodes, umodes->data - umodes->head);
3984 SILC_LOG_HEXDUMP(("umodes"), umodes->data, umodes->len);
3986 /* Send the packet */
3987 silc_server_packet_send(server, remote,
3988 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3989 umodes->data, umodes->len, TRUE);
3991 silc_buffer_free(umodes);
3995 /* Returns channel's topic for announcing it */
3997 void silc_server_announce_get_channel_topic(SilcServer server,
3998 SilcChannelEntry channel,
4003 if (channel->topic) {
4004 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4005 *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4006 chidp->data, chidp->len,
4008 strlen(channel->topic));
4009 silc_buffer_free(chidp);
4013 /* Returns assembled packets for channel users of the `channel'. */
4015 void silc_server_announce_get_channel_users(SilcServer server,
4016 SilcChannelEntry channel,
4017 SilcBuffer *channel_modes,
4018 SilcBuffer *channel_users,
4019 SilcBuffer *channel_users_modes)
4021 SilcChannelClientEntry chl;
4022 SilcHashTableList htl;
4023 SilcBuffer chidp, clidp, csidp;
4026 unsigned char mode[4], *fkey = NULL;
4027 SilcUInt32 fkey_len = 0;
4030 SILC_LOG_DEBUG(("Start"));
4032 chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4033 csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4036 SILC_PUT32_MSB(channel->mode, mode);
4037 hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4038 if (channel->founder_key)
4039 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4041 silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4042 6, csidp->data, csidp->len,
4045 hmac, hmac ? strlen(hmac) : 0,
4046 channel->passphrase,
4047 channel->passphrase ?
4048 strlen(channel->passphrase) : 0,
4052 silc_buffer_realloc(*channel_modes,
4054 (*channel_modes)->truelen + len : len));
4055 silc_buffer_pull_tail(*channel_modes,
4056 ((*channel_modes)->end -
4057 (*channel_modes)->data));
4058 silc_buffer_put(*channel_modes, tmp->data, tmp->len);
4059 silc_buffer_pull(*channel_modes, len);
4060 silc_buffer_free(tmp);
4065 /* Now find all users on the channel */
4066 silc_hash_table_list(channel->user_list, &htl);
4067 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4068 clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4071 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4072 clidp->data, clidp->len,
4073 chidp->data, chidp->len);
4076 silc_buffer_realloc(*channel_users,
4078 (*channel_users)->truelen + len : len));
4079 silc_buffer_pull_tail(*channel_users,
4080 ((*channel_users)->end -
4081 (*channel_users)->data));
4083 silc_buffer_put(*channel_users, tmp->data, tmp->len);
4084 silc_buffer_pull(*channel_users, len);
4085 silc_buffer_free(tmp);
4087 /* CUMODE notify for mode change on the channel */
4088 SILC_PUT32_MSB(chl->mode, mode);
4089 if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4090 fkey = silc_pkcs_public_key_encode(channel->founder_key, &fkey_len);
4091 tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4092 4, csidp->data, csidp->len,
4094 clidp->data, clidp->len,
4097 *channel_users_modes =
4098 silc_buffer_realloc(*channel_users_modes,
4099 (*channel_users_modes ?
4100 (*channel_users_modes)->truelen + len : len));
4101 silc_buffer_pull_tail(*channel_users_modes,
4102 ((*channel_users_modes)->end -
4103 (*channel_users_modes)->data));
4105 silc_buffer_put(*channel_users_modes, tmp->data, tmp->len);
4106 silc_buffer_pull(*channel_users_modes, len);
4107 silc_buffer_free(tmp);
4111 silc_buffer_free(clidp);
4113 silc_hash_table_list_reset(&htl);
4114 silc_buffer_free(chidp);
4115 silc_buffer_free(csidp);
4118 /* Returns assembled packets for all channels and users on those channels
4119 from the given ID List. The packets are in the form dictated by the
4120 New Channel and New Channel User payloads. */
4122 void silc_server_announce_get_channels(SilcServer server,
4124 SilcBuffer *channels,
4125 SilcBuffer **channel_modes,
4126 SilcBuffer *channel_users,
4127 SilcBuffer **channel_users_modes,
4128 SilcUInt32 *channel_users_modes_c,
4129 SilcBuffer **channel_topics,
4130 SilcChannelID ***channel_ids,
4131 unsigned long creation_time)
4133 SilcIDCacheList list;
4134 SilcIDCacheEntry id_cache;
4135 SilcChannelEntry channel;
4138 SilcUInt16 name_len;
4140 int i = *channel_users_modes_c;
4143 SILC_LOG_DEBUG(("Start"));
4145 /* Go through all channels in the list */
4146 if (silc_idcache_get_all(id_list->channels, &list)) {
4147 if (silc_idcache_list_first(list, &id_cache)) {
4149 channel = (SilcChannelEntry)id_cache->context;
4151 if (creation_time && channel->created < creation_time)
4156 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4157 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4158 name_len = strlen(channel->channel_name);
4161 len = 4 + name_len + id_len + 4;
4163 silc_buffer_realloc(*channels,
4164 (*channels ? (*channels)->truelen +
4166 silc_buffer_pull_tail(*channels,
4167 ((*channels)->end - (*channels)->data));
4168 silc_buffer_format(*channels,
4169 SILC_STR_UI_SHORT(name_len),
4170 SILC_STR_UI_XNSTRING(channel->channel_name,
4172 SILC_STR_UI_SHORT(id_len),
4173 SILC_STR_UI_XNSTRING(cid, id_len),
4174 SILC_STR_UI_INT(channel->mode),
4176 silc_buffer_pull(*channels, len);
4179 if (creation_time && channel->updated < creation_time)
4185 /* Channel user modes */
4186 *channel_users_modes = silc_realloc(*channel_users_modes,
4187 sizeof(**channel_users_modes) *
4189 (*channel_users_modes)[i] = NULL;
4190 *channel_modes = silc_realloc(*channel_modes,
4191 sizeof(**channel_modes) * (i + 1));
4192 (*channel_modes)[i] = NULL;
4193 *channel_ids = silc_realloc(*channel_ids,
4194 sizeof(**channel_ids) * (i + 1));
4195 (*channel_ids)[i] = NULL;
4196 silc_server_announce_get_channel_users(server, channel,
4197 &(*channel_modes)[i],
4199 &(*channel_users_modes)[i]);
4200 (*channel_ids)[i] = channel->id;
4202 /* Channel's topic */
4203 *channel_topics = silc_realloc(*channel_topics,
4204 sizeof(**channel_topics) * (i + 1));
4205 (*channel_topics)[i] = NULL;
4206 silc_server_announce_get_channel_topic(server, channel,
4207 &(*channel_topics)[i]);
4208 (*channel_users_modes_c)++;
4212 if (!silc_idcache_list_next(list, &id_cache))
4217 silc_idcache_list_free(list);
4221 /* This function is used to announce our existing channels to our router
4222 when we've connected to it. This also announces the users on the
4223 channels to the router. If the `creation_time' is non-zero only the
4224 channels that was created after the `creation_time' are announced.
4225 Note that the channel users are still announced even if the `creation_time'
4228 void silc_server_announce_channels(SilcServer server,
4229 unsigned long creation_time,
4230 SilcSocketConnection remote)
4232 SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4233 SilcBuffer *channel_users_modes = NULL;
4234 SilcBuffer *channel_topics = NULL;
4235 SilcUInt32 channel_users_modes_c = 0;
4236 SilcChannelID **channel_ids = NULL;
4238 SILC_LOG_DEBUG(("Announcing channels and channel users"));
4240 /* Get channels and channel users in local list */
4241 silc_server_announce_get_channels(server, server->local_list,
4242 &channels, &channel_modes,
4244 &channel_users_modes,
4245 &channel_users_modes_c,
4247 &channel_ids, creation_time);
4249 /* Get channels and channel users in global list */
4250 if (server->server_type != SILC_SERVER)
4251 silc_server_announce_get_channels(server, server->global_list,
4252 &channels, &channel_modes,
4254 &channel_users_modes,
4255 &channel_users_modes_c,
4257 &channel_ids, creation_time);
4260 silc_buffer_push(channels, channels->data - channels->head);
4261 SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
4263 /* Send the packet */
4264 silc_server_packet_send(server, remote,
4265 SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4266 channels->data, channels->len,
4269 silc_buffer_free(channels);
4272 if (channel_users) {
4273 silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4274 SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4275 channel_users->len);
4277 /* Send the packet */
4278 silc_server_packet_send(server, remote,
4279 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4280 channel_users->data, channel_users->len,
4283 silc_buffer_free(channel_users);
4286 if (channel_modes) {
4289 for (i = 0; i < channel_users_modes_c; i++) {
4290 if (!channel_modes[i])
4292 silc_buffer_push(channel_modes[i],
4293 channel_modes[i]->data -
4294 channel_modes[i]->head);
4295 SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4296 channel_modes[i]->len);
4297 silc_server_packet_send_dest(server, remote,
4298 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4299 channel_ids[i], SILC_ID_CHANNEL,
4300 channel_modes[i]->data,
4301 channel_modes[i]->len,
4303 silc_buffer_free(channel_modes[i]);
4305 silc_free(channel_modes);
4308 if (channel_users_modes) {
4311 for (i = 0; i < channel_users_modes_c; i++) {
4312 if (!channel_users_modes[i])
4314 silc_buffer_push(channel_users_modes[i],
4315 channel_users_modes[i]->data -
4316 channel_users_modes[i]->head);
4317 SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4318 channel_users_modes[i]->len);
4319 silc_server_packet_send_dest(server, remote,
4320 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4321 channel_ids[i], SILC_ID_CHANNEL,
4322 channel_users_modes[i]->data,
4323 channel_users_modes[i]->len,
4325 silc_buffer_free(channel_users_modes[i]);
4327 silc_free(channel_users_modes);
4330 if (channel_topics) {
4333 for (i = 0; i < channel_users_modes_c; i++) {
4334 if (!channel_topics[i])
4337 silc_buffer_push(channel_topics[i],
4338 channel_topics[i]->data -
4339 channel_topics[i]->head);
4340 SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4341 channel_topics[i]->len);
4342 silc_server_packet_send_dest(server, remote,
4343 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4344 channel_ids[i], SILC_ID_CHANNEL,
4345 channel_topics[i]->data,
4346 channel_topics[i]->len,
4348 silc_buffer_free(channel_topics[i]);
4350 silc_free(channel_topics);
4353 silc_free(channel_ids);
4356 /* Failure timeout callback. If this is called then we will immediately
4357 process the received failure. We always process the failure with timeout
4358 since we do not want to blindly trust to received failure packets.
4359 This won't be called (the timeout is cancelled) if the failure was
4360 bogus (it is bogus if remote does not close the connection after sending
4363 SILC_TASK_CALLBACK(silc_server_failure_callback)
4365 SilcServerFailureContext f = (SilcServerFailureContext)context;
4367 if (f->sock->protocol) {
4368 f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
4369 silc_protocol_execute(f->sock->protocol, f->server->schedule, 0, 0);
4375 /* Assembles user list and users mode list from the `channel'. */
4377 bool silc_server_get_users_on_channel(SilcServer server,
4378 SilcChannelEntry channel,
4379 SilcBuffer *user_list,
4380 SilcBuffer *mode_list,
4381 SilcUInt32 *user_count)
4383 SilcChannelClientEntry chl;
4384 SilcHashTableList htl;
4385 SilcBuffer client_id_list;
4386 SilcBuffer client_mode_list;
4388 SilcUInt32 list_count = 0, len = 0;
4390 if (!silc_hash_table_count(channel->user_list))
4393 silc_hash_table_list(channel->user_list, &htl);
4394 while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4395 len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4396 silc_hash_table_list_reset(&htl);
4398 client_id_list = silc_buffer_alloc(len);
4400 silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4401 silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
4402 silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
4404 silc_hash_table_list(channel->user_list, &htl);
4405 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4407 idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4408 silc_buffer_put(client_id_list, idp->data, idp->len);
4409 silc_buffer_pull(client_id_list, idp->len);
4410 silc_buffer_free(idp);
4412 /* Client's mode on channel */
4413 SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4414 silc_buffer_pull(client_mode_list, 4);
4418 silc_hash_table_list_reset(&htl);
4419 silc_buffer_push(client_id_list,
4420 client_id_list->data - client_id_list->head);
4421 silc_buffer_push(client_mode_list,
4422 client_mode_list->data - client_mode_list->head);
4424 *user_list = client_id_list;
4425 *mode_list = client_mode_list;
4426 *user_count = list_count;
4430 /* Saves users and their modes to the `channel'. */
4432 void silc_server_save_users_on_channel(SilcServer server,
4433 SilcSocketConnection sock,
4434 SilcChannelEntry channel,
4435 SilcClientID *noadd,
4436 SilcBuffer user_list,
4437 SilcBuffer mode_list,
4438 SilcUInt32 user_count)
4443 SilcClientID *client_id;
4444 SilcClientEntry client;
4445 SilcIDCacheEntry cache;
4446 SilcChannelClientEntry chl;
4449 SILC_LOG_DEBUG(("Start"));
4451 for (i = 0; i < user_count; i++) {
4453 SILC_GET16_MSB(idp_len, user_list->data + 2);
4455 client_id = silc_id_payload_parse_id(user_list->data, idp_len, NULL);
4456 silc_buffer_pull(user_list, idp_len);
4461 SILC_GET32_MSB(mode, mode_list->data);
4462 silc_buffer_pull(mode_list, 4);
4464 if (noadd && SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
4465 silc_free(client_id);
4471 /* Check if we have this client cached already. */
4472 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4473 server->server_type, &cache);
4475 client = silc_idlist_find_client_by_id(server->global_list,
4476 client_id, server->server_type,
4481 /* If router did not find such Client ID in its lists then this must
4482 be bogus client or some router in the net is buggy. */
4483 if (server->server_type == SILC_ROUTER) {
4484 silc_free(client_id);
4488 /* We don't have that client anywhere, add it. The client is added
4489 to global list since server didn't have it in the lists so it must be
4491 client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4492 silc_id_dup(client_id, SILC_ID_CLIENT),
4493 sock->user_data, NULL, 0);
4495 SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4496 silc_free(client_id);
4500 client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4502 /* Found, if it is from global list we'll assure that we won't
4503 expire it now that the entry is on channel. */
4508 silc_free(client_id);
4510 if (!silc_server_client_on_channel(client, channel, &chl)) {
4511 /* Client was not on the channel, add it. */
4512 chl = silc_calloc(1, sizeof(*chl));
4513 chl->client = client;
4515 chl->channel = channel;
4516 silc_hash_table_add(channel->user_list, chl->client, chl);
4517 silc_hash_table_add(client->channels, chl->channel, chl);
4518 channel->user_count++;
4526 /* Saves channels and channels user modes to the `client'. Removes
4527 the client from those channels that are not sent in the list but
4530 void silc_server_save_user_channels(SilcServer server,
4531 SilcSocketConnection sock,
4532 SilcClientEntry client,
4533 SilcBuffer channels,
4534 SilcBuffer channels_user_modes)
4537 SilcUInt32 *chumodes;
4538 SilcChannelPayload entry;
4539 SilcChannelEntry channel;
4540 SilcChannelID *channel_id;
4541 SilcChannelClientEntry chl;
4542 SilcHashTable ht = NULL;
4543 SilcHashTableList htl;
4547 if (!channels ||!channels_user_modes)
4550 ch = silc_channel_payload_parse_list(channels->data, channels->len);
4551 if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4553 ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4554 NULL, NULL, NULL, TRUE);
4555 silc_dlist_start(ch);
4556 while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4557 /* Check if we have this channel, and add it if we don't have it.
4558 Also add the client on the channel unless it is there already. */
4559 channel_id = silc_channel_get_id_parse(entry);
4560 channel = silc_idlist_find_channel_by_id(server->local_list,
4563 channel = silc_idlist_find_channel_by_id(server->global_list,
4566 if (server->server_type != SILC_SERVER) {
4567 silc_free(channel_id);
4572 /* We don't have that channel anywhere, add it. */
4573 name = silc_channel_get_name(entry, NULL);
4574 channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4575 channel_id, server->router,
4578 silc_free(channel_id);
4585 channel->mode = silc_channel_get_mode(entry);
4587 /* Add the client on the channel */
4588 if (!silc_server_client_on_channel(client, channel, &chl)) {
4589 chl = silc_calloc(1, sizeof(*chl));
4590 chl->client = client;
4591 chl->mode = chumodes[i++];
4592 chl->channel = channel;
4593 silc_hash_table_add(channel->user_list, chl->client, chl);
4594 silc_hash_table_add(client->channels, chl->channel, chl);
4595 channel->user_count++;
4598 chl->mode = chumodes[i++];
4601 silc_hash_table_add(ht, channel, channel);
4602 silc_free(channel_id);
4604 silc_channel_payload_list_free(ch);
4605 silc_free(chumodes);
4609 /* Go through the list again and remove client from channels that
4610 are no part of the list. */
4612 silc_hash_table_list(client->channels, &htl);
4613 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4614 if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4615 silc_hash_table_del(chl->channel->user_list, chl->client);
4616 silc_hash_table_del(chl->client->channels, chl->channel);
4620 silc_hash_table_list_reset(&htl);
4621 silc_hash_table_free(ht);
4623 silc_hash_table_list(client->channels, &htl);
4624 while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
4625 silc_hash_table_del(chl->channel->user_list, chl->client);
4626 silc_hash_table_del(chl->client->channels, chl->channel);
4629 silc_hash_table_list_reset(&htl);
4633 /* Lookups route to the client indicated by the `id_data'. The connection
4634 object and internal data object is returned. Returns NULL if route
4635 could not be found to the client. If the `client_id' is specified then
4636 it is used and the `id_data' is ignored. */
4638 SilcSocketConnection
4639 silc_server_get_client_route(SilcServer server,
4640 unsigned char *id_data,
4642 SilcClientID *client_id,
4643 SilcIDListData *idata,
4644 SilcClientEntry *client_entry)
4647 SilcClientEntry client;
4649 SILC_LOG_DEBUG(("Start"));
4652 *client_entry = NULL;
4654 /* Decode destination Client ID */
4656 id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
4658 SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
4662 id = silc_id_dup(client_id, SILC_ID_CLIENT);
4665 /* If the destination belongs to our server we don't have to route
4666 the packet anywhere but to send it to the local destination. */
4667 client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4671 /* If we are router and the client has router then the client is in
4672 our cell but not directly connected to us. */
4673 if (server->server_type == SILC_ROUTER && client->router) {
4674 /* We are of course in this case the client's router thus the route
4675 to the client is the server who owns the client. So, we will send
4676 the packet to that server. */
4678 *idata = (SilcIDListData)client->router;
4679 return client->router->connection;
4682 /* Seems that client really is directly connected to us */
4684 *idata = (SilcIDListData)client;
4686 *client_entry = client;
4687 return client->connection;
4690 /* Destination belongs to someone not in this server. If we are normal
4691 server our action is to send the packet to our router. */
4692 if (server->server_type != SILC_ROUTER && !server->standalone) {
4695 *idata = (SilcIDListData)server->router;
4696 return SILC_PRIMARY_ROUTE(server);
4699 /* We are router and we will perform route lookup for the destination
4700 and send the packet to fastest route. */
4701 if (server->server_type == SILC_ROUTER && !server->standalone) {
4702 /* Check first that the ID is valid */
4703 client = silc_idlist_find_client_by_id(server->global_list, id,
4706 SilcSocketConnection dst_sock;
4708 dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4712 *idata = (SilcIDListData)dst_sock->user_data;
4721 /* Encodes and returns channel list of channels the `client' has joined.
4722 Secret channels are not put to the list. */
4724 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
4725 SilcClientEntry client,
4728 SilcBuffer *user_mode_list)
4730 SilcBuffer buffer = NULL;
4731 SilcChannelEntry channel;
4732 SilcChannelClientEntry chl;
4733 SilcHashTableList htl;
4736 SilcUInt16 name_len;
4740 *user_mode_list = NULL;
4742 silc_hash_table_list(client->channels, &htl);
4743 while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4744 channel = chl->channel;
4746 if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
4748 if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
4751 cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4752 id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
4753 name_len = strlen(channel->channel_name);
4755 len = 4 + name_len + id_len + 4;
4756 buffer = silc_buffer_realloc(buffer,
4757 (buffer ? buffer->truelen + len : len));
4758 silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
4759 silc_buffer_format(buffer,
4760 SILC_STR_UI_SHORT(name_len),
4761 SILC_STR_UI_XNSTRING(channel->channel_name,
4763 SILC_STR_UI_SHORT(id_len),
4764 SILC_STR_UI_XNSTRING(cid, id_len),
4765 SILC_STR_UI_INT(chl->channel->mode),
4767 silc_buffer_pull(buffer, len);
4770 if (user_mode_list) {
4771 *user_mode_list = silc_buffer_realloc(*user_mode_list,
4773 (*user_mode_list)->truelen + 4 :
4775 silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
4776 (*user_mode_list)->data));
4777 SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
4778 silc_buffer_pull(*user_mode_list, 4);
4781 silc_hash_table_list_reset(&htl);
4784 silc_buffer_push(buffer, buffer->data - buffer->head);
4785 if (user_mode_list && *user_mode_list)
4786 silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
4787 (*user_mode_list)->head));
4792 /* Finds client entry by Client ID and if it is not found then resolves
4793 it using WHOIS command. */
4795 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
4796 SilcClientID *client_id,
4797 bool always_resolve,
4800 SilcClientEntry client;
4805 client = silc_idlist_find_client_by_id(server->local_list, client_id,
4808 client = silc_idlist_find_client_by_id(server->global_list,
4809 client_id, TRUE, NULL);
4810 if (!client && server->server_type == SILC_ROUTER)
4814 if (!client && server->standalone)
4817 if (!client || !client->nickname || !client->username ||
4819 SilcBuffer buffer, idp;
4822 client->data.status |= SILC_IDLIST_STATUS_RESOLVING;
4823 client->data.status &= ~SILC_IDLIST_STATUS_RESOLVED;
4824 client->resolve_cmd_ident = ++server->cmd_ident;
4827 idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4828 buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
4829 server->cmd_ident, 1,
4830 4, idp->data, idp->len);
4831 silc_server_packet_send(server, client ? client->router->connection :
4832 SILC_PRIMARY_ROUTE(server),
4833 SILC_PACKET_COMMAND, 0,
4834 buffer->data, buffer->len, FALSE);
4835 silc_buffer_free(idp);
4836 silc_buffer_free(buffer);
4847 /* A timeout callback for the re-key. We will be the initiator of the
4850 SILC_TASK_CALLBACK(silc_server_rekey_callback)
4852 SilcSocketConnection sock = (SilcSocketConnection)context;
4853 SilcIDListData idata = (SilcIDListData)sock->user_data;
4854 SilcServer server = (SilcServer)idata->rekey->context;
4855 SilcProtocol protocol;
4856 SilcServerRekeyInternalContext *proto_ctx;
4858 /* Allocate internal protocol context. This is sent as context
4860 proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
4861 proto_ctx->server = (void *)server;
4862 proto_ctx->sock = sock;
4863 proto_ctx->responder = FALSE;
4864 proto_ctx->pfs = idata->rekey->pfs;
4866 /* Perform rekey protocol. Will call the final callback after the
4867 protocol is over. */
4868 silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
4869 &protocol, proto_ctx, silc_server_rekey_final);
4870 sock->protocol = protocol;
4872 /* Run the protocol */
4873 silc_protocol_execute(protocol, server->schedule, 0, 0);
4875 SILC_LOG_DEBUG(("Rekey protocol completed"));
4877 /* Re-register re-key timeout */
4878 silc_schedule_task_add(server->schedule, sock->sock,
4879 silc_server_rekey_callback,
4880 context, idata->rekey->timeout, 0,
4881 SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
4884 /* The final callback for the REKEY protocol. This will actually take the
4885 new key material into use. */
4887 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
4889 SilcProtocol protocol = (SilcProtocol)context;
4890 SilcServerRekeyInternalContext *ctx =
4891 (SilcServerRekeyInternalContext *)protocol->context;
4892 SilcServer server = (SilcServer)ctx->server;
4893 SilcSocketConnection sock = ctx->sock;
4895 SILC_LOG_DEBUG(("Start"));
4897 if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
4898 protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
4899 /* Error occured during protocol */
4900 SILC_LOG_ERROR(("Error occurred during rekey protocol"));
4901 silc_protocol_cancel(protocol, server->schedule);
4902 silc_protocol_free(protocol);
4903 sock->protocol = NULL;
4905 silc_packet_context_free(ctx->packet);
4907 silc_ske_free(ctx->ske);
4912 /* Purge the outgoing data queue to assure that all rekey packets really
4913 go to the network before we quit the protocol. */
4914 silc_server_packet_queue_purge(server, sock);
4917 silc_protocol_free(protocol);
4918 sock->protocol = NULL;
4920 silc_packet_context_free(ctx->packet);
4922 silc_ske_free(ctx->ske);
4926 /* Task callback used to retrieve network statistical information from
4927 router server once in a while. */
4929 SILC_TASK_CALLBACK(silc_server_get_stats)
4931 SilcServer server = (SilcServer)context;
4932 SilcBuffer idp, packet;
4934 SILC_LOG_DEBUG(("Retrieving stats from router"));
4936 if (!server->standalone) {
4937 idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
4938 packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
4939 ++server->cmd_ident, 1,
4940 1, idp->data, idp->len);
4941 silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4942 SILC_PACKET_COMMAND, 0, packet->data,
4943 packet->len, FALSE);
4944 silc_buffer_free(packet);
4945 silc_buffer_free(idp);
4948 silc_schedule_task_add(server->schedule, 0, silc_server_get_stats,
4949 server, 120, 0, SILC_TASK_TIMEOUT,