/*
 * Copyright 2025 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/***MODULE:fuzzy
 * rspamd module that checks fuzzy checksums for messages
 *
 * Allowed options:
 * - symbol (string): symbol to insert (default: 'R_FUZZY')
 * - hits_limit (double): number of fuzzy hash hits at which the normalized score reaches ~1.0 (default: 0 - no normalization)
 *   The score is calculated as tanh(e * hits / hits_limit). Legacy name: max_score
 *
 * - fuzzy_map (string): a string that contains map in format { fuzzy_key => [ symbol, weight ] } where fuzzy_key is number of
 *   fuzzy list. This string itself should be in format 1:R_FUZZY_SAMPLE1:10,2:R_FUZZY_SAMPLE2:1 etc, where first number is fuzzy
 *   key, second is symbol to insert and third - weight for normalization
 *
 * - min_length (integer): minimum length (in characters) for text part to be checked for fuzzy hash (default: 0 - no limit)
 * - whitelist (map string): map of ip addresses that should not be checked with this module
 * - servers (string): list of fuzzy servers in format "server1:port,server2:port" - these servers would be used for checking and storing
 *   fuzzy hashes
 * - checks (object): structured configuration of content hashing routines (e.g. checks { text { enabled = true; }, html { enabled = true; } })
 */

#include "config.h"
#include "libmime/message.h"
#include "libserver/maps/map.h"
#include "libserver/maps/map_helpers.h"
#include "libmime/images.h"
#include "libserver/worker_util.h"
#include "libserver/mempool_vars_internal.h"
#include "libserver/html/html_features.h"
#include "khash.h"
#include "fuzzy_wire.h"
#include "utlist.h"
#include "ottery.h"
#include "lua/lua_common.h"
#include "unix-std.h"
#include "libserver/http/http_private.h"
#include "libserver/http/http_router.h"
#include "libstat/stat_api.h"
#include <math.h>
#include "libutil/libev_helper.h"

#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h> /* for TCP_NODELAY */
#endif

#define DEFAULT_SYMBOL "R_FUZZY_HASH"
#define RSPAMD_FUZZY_SYMBOL_FORBIDDEN "FUZZY_FORBIDDEN"
#define RSPAMD_FUZZY_SYMBOL_RATELIMITED "FUZZY_RATELIMITED"
#define RSPAMD_FUZZY_SYMBOL_ENCRYPTION_REQUIRED "FUZZY_ENCRYPTION_REQUIRED"

#define DEFAULT_IO_TIMEOUT 1.0
#define DEFAULT_RETRANSMITS 3
#define DEFAULT_MAX_ERRORS 4
#define DEFAULT_REVIVE_TIME 60
#define DEFAULT_PORT 11335

#define RSPAMD_FUZZY_PLUGIN_VERSION RSPAMD_FUZZY_VERSION

static const int rspamd_fuzzy_hash_len = 5;
static const char *M = "fuzzy_check";
struct fuzzy_ctx;

struct fuzzy_mapping {
	uint64_t fuzzy_flag;
	const char *symbol;
	double weight;
};

enum fuzzy_rule_mode {
	fuzzy_rule_read_only,
	fuzzy_rule_write_only,
	fuzzy_rule_read_write
};

struct fuzzy_tcp_pending_command; /* Forward declaration */
KHASH_MAP_INIT_INT(fuzzy_pending_hash, struct fuzzy_tcp_pending_command *);

struct fuzzy_rule {
	struct upstream_list *read_servers;  /* Servers for read operations */
	struct upstream_list *write_servers; /* Servers for write operations */
	const char *symbol;
	const char *algorithm_str;
	const char *name;
	const ucl_object_t *ucl_obj;
	enum rspamd_shingle_alg alg;
	GHashTable *mappings;
	GPtrArray *fuzzy_headers;
	GString *hash_key;
	GString *shingles_key;
	double io_timeout;
	struct rspamd_cryptobox_keypair *local_key;
	struct rspamd_cryptobox_pubkey *peer_key;
	/* Separate encryption keys for read and write operations */
	struct rspamd_cryptobox_keypair *read_local_key;
	struct rspamd_cryptobox_pubkey *read_peer_key;
	struct rspamd_cryptobox_keypair *write_local_key;
	struct rspamd_cryptobox_pubkey *write_peer_key;
	double hits_limit;
	double weight_threshold;
	double html_weight; /* Weight multiplier for HTML hashes (default 1.0) */
	enum fuzzy_rule_mode mode;
	gboolean skip_unknown;
	gboolean no_share;
	gboolean no_subject;
	gboolean html_shingles;     /* Enable HTML fuzzy hashing */
	gboolean text_hashes;       /* Enable/disable generation of text hashes */
	unsigned int min_html_tags; /* Minimum tags for HTML hash */
	gboolean html_ignore_domains; /* Ignore link domains in HTML structural tokens */
	int learn_condition_cb;
	uint32_t retransmits;
	struct rspamd_hash_map_helper *skip_map;
	struct fuzzy_ctx *ctx;
	int lua_id;
	gboolean server_supports_v2;

	/* TCP configuration */
	gboolean tcp_enabled;   /* Explicitly enable TCP */
	gboolean tcp_auto;      /* Auto-switch to TCP based on request rate */
	double tcp_threshold;   /* Requests/sec threshold for auto-switch (default: 1.0) */
	double tcp_window;      /* Time window for rate calculation in seconds (default: 1.0) */
	double tcp_timeout;     /* TCP connection timeout (default: 5.0) */
	double tcp_retry_delay; /* Delay before retrying failed TCP connection (default: 10.0) */

	/* Rate tracking for TCP auto-switch */
	struct {
		uint32_t requests_count; /* Number of requests in current window */
		ev_tstamp window_start;  /* Start of the current window */
		gboolean last_was_tcp;   /* Last request used TCP (for transition logging) */
	} rate_tracker;

	/* TCP connection pool - array of connections, one per upstream */
	GPtrArray *tcp_connections;                     /* Array of fuzzy_tcp_connection* */
	khash_t(fuzzy_pending_hash) * pending_requests; /* Global: tag -> fuzzy_tcp_pending_command */
};

struct fuzzy_ctx {
	struct module_ctx ctx;
	rspamd_mempool_t *fuzzy_pool;
	GPtrArray *fuzzy_rules;
	struct rspamd_config *cfg;
	const char *default_symbol;
	struct rspamd_radix_map_helper *whitelist;
	struct rspamd_keypair_cache *keypairs_cache;
	unsigned int max_errors;
	double revive_time;
	double io_timeout;
	int check_mime_part_ref; /* Lua callback */
	int process_rule_ref;    /* Lua callback */
	int cleanup_rules_ref;
	uint32_t retransmits;
	gboolean enabled;
};

static inline uint8_t
fuzzy_cmd_version(const struct fuzzy_rule *rule)
{
	if (rule->server_supports_v2) {
		return 5; /* Native v5 after server confirmed v2 support */
	}
	return RSPAMD_FUZZY_VERSION | RSPAMD_FUZZY_V2_CAP; /* 4 | 0x10 = 0x14 */
}

enum fuzzy_result_type {
	FUZZY_RESULT_TXT,
	FUZZY_RESULT_IMG,
	FUZZY_RESULT_CONTENT,
	FUZZY_RESULT_BIN,
	FUZZY_RESULT_HTML
};

struct fuzzy_client_result {
	const char *symbol;
	char *option;
	double score;
	double prob;
	enum fuzzy_result_type type;
};

struct fuzzy_client_session {
	GPtrArray *commands;
	GPtrArray *results;
	struct rspamd_task *task;
	struct rspamd_symcache_dynamic_item *item;
	struct upstream *server;
	struct fuzzy_rule *rule;
	struct ev_loop *event_loop;
	struct rspamd_io_ev ev;
	ev_timer timer_ev; /* Pure timer for TCP session timeout */
	int state;
	int fd;
	int retransmits;
};

struct fuzzy_learn_session {
	GPtrArray *commands;
	int *saved;
	struct {
		const char *error_message;
		int error_code;
	} err;
	struct rspamd_http_connection_entry *http_entry;
	struct rspamd_async_session *session;
	struct upstream *server;
	struct fuzzy_rule *rule;
	struct rspamd_task *task;
	struct ev_loop *event_loop;
	struct rspamd_io_ev ev;
	int fd;
	int retransmits;
};

/**
 * Pending command awaiting TCP reply
 * Used to match replies with requests
 */
struct fuzzy_tcp_pending_command {
	struct fuzzy_cmd_io *io;                 /* Command I/O */
	struct rspamd_task *task;                /* Task associated with command */
	struct fuzzy_client_session *session;    /* Session for reply delivery */
	struct fuzzy_tcp_connection *connection; /* Connection this command was sent on */
	ev_tstamp send_time;                     /* When command was sent */
};

/**
 * TCP write queue element - contains framed command ready to send
 */
struct fuzzy_tcp_write_buf {
	uint16_t size_hdr;   /* Frame size in little-endian byte order */
	unsigned char *data; /* Command data (encrypted) */
	gsize total_len;     /* Total length: sizeof(size_hdr) + data_len */
	gsize bytes_written; /* How many bytes already written */
};

/**
 * TCP connection state for a fuzzy rule
 * One TCP connection per fuzzy_rule, shared across all tasks
 */
struct fuzzy_tcp_connection {
	struct fuzzy_rule *rule;  /* Parent rule */
	struct upstream *server;  /* Connected upstream */
	char *server_name;        /* Cached upstream name for logging */
	rspamd_inet_addr_t *addr; /* Server address */

	int fd;                     /* Socket file descriptor */
	struct ev_loop *event_loop; /* Event loop */
	struct rspamd_io_ev ev;     /* Event watcher */

	/* Write state */
	GQueue *write_queue; /* Queue of iovec to send */
	gsize bytes_sent;    /* Bytes sent from current iovec */

	/* Read state - TCP framing */
	uint16_t cur_frame_state;     /* 0x0000/0x8000/0xC000 like server */
	gsize bytes_unprocessed;      /* Bytes in read_buf not yet processed */
	unsigned char read_buf[8192]; /* Read buffer for incoming data */

	/* Encryption keys for this connection */
	struct rspamd_cryptobox_keypair *local_key; /* Local keypair (can be NULL) */
	struct rspamd_cryptobox_pubkey *peer_key;   /* Server public key (can be NULL) */
	gboolean encrypted;                         /* TRUE if connection uses encryption */

	/* Connection state */
	gboolean connected;  /* TCP handshake complete */
	gboolean connecting; /* Connection in progress */
	gboolean failed;     /* Connection failed */

	ev_tstamp connect_start; /* When connection started */
	ev_tstamp last_activity; /* Last I/O activity */
	ev_tstamp last_failure;  /* When connection last failed (for retry logic) */

	ref_entry_t ref; /* Reference counting */
};

#define FUZZY_CMD_FLAG_REPLIED (1 << 0)
#define FUZZY_CMD_FLAG_SENT (1 << 1)
#define FUZZY_CMD_FLAG_IMAGE (1 << 2)
#define FUZZY_CMD_FLAG_CONTENT (1 << 3)
#define FUZZY_CMD_FLAG_HTML (1 << 4)
#define FUZZY_CMD_FLAG_HTML_DOMAINS (1 << 5)

#define FUZZY_CHECK_FLAG_NOIMAGES (1 << 0)
#define FUZZY_CHECK_FLAG_NOATTACHMENTS (1 << 1)
#define FUZZY_CHECK_FLAG_NOTEXT (1 << 2)
#define FUZZY_CHECK_FLAG_NOHTML (1 << 3)

struct fuzzy_cmd_io {
	uint32_t tag;
	uint32_t flags;
	struct iovec io;
	struct rspamd_mime_part *part;
	struct rspamd_fuzzy_cmd cmd;
};


static const char *default_headers = "Subject,Content-Type,Reply-To,X-Mailer";

static void fuzzy_symbol_callback(struct rspamd_task *task,
								  struct rspamd_symcache_dynamic_item *item,
								  void *unused);

/* Initialization */
int fuzzy_check_module_init(struct rspamd_config *cfg,
							struct module_ctx **ctx);
int fuzzy_check_module_config(struct rspamd_config *cfg, bool valdate);
int fuzzy_check_module_reconfig(struct rspamd_config *cfg);
static int fuzzy_attach_controller(struct module_ctx *ctx,
								   GHashTable *commands);
static int fuzzy_lua_learn_handler(lua_State *L);
static int fuzzy_lua_unlearn_handler(lua_State *L);
static int fuzzy_lua_gen_hashes_handler(lua_State *L);
static int fuzzy_lua_hex_hashes_handler(lua_State *L);
static int fuzzy_lua_list_storages(lua_State *L);
static int fuzzy_lua_ping_storage(lua_State *L);

module_t fuzzy_check_module = {
	"fuzzy_check",
	fuzzy_check_module_init,
	fuzzy_check_module_config,
	fuzzy_check_module_reconfig,
	fuzzy_attach_controller,
	RSPAMD_MODULE_VER,
	(unsigned int) -1,
};

INIT_LOG_MODULE(fuzzy_check)
#define msg_debug_fuzzy_check(...) rspamd_conditional_debug_fast(NULL,                                                                 \
																 task ? task->from_addr : NULL,                                        \
																 rspamd_fuzzy_check_log_id, M, task ? task->task_pool->tag.uid : NULL, \
																 RSPAMD_LOG_FUNC,                                                      \
																 __VA_ARGS__)

static inline struct fuzzy_ctx *
fuzzy_get_context(struct rspamd_config *cfg)
{
	return (struct fuzzy_ctx *) g_ptr_array_index(cfg->c_modules,
												  fuzzy_check_module.ctx_offset);
}

static void
parse_flags(struct fuzzy_rule *rule,
			struct rspamd_config *cfg,
			const ucl_object_t *val,
			int cb_id)
{
	const ucl_object_t *elt;
	struct fuzzy_mapping *map;
	const char *sym = NULL;

	if (val->type == UCL_STRING) {
		msg_err_config(
			"string mappings are deprecated and no longer supported, use new style configuration");
	}
	else if (val->type == UCL_OBJECT) {
		elt = ucl_object_lookup(val, "symbol");
		if (elt == NULL || !ucl_object_tostring_safe(elt, &sym)) {
			sym = ucl_object_key(val);
		}
		if (sym != NULL) {
			map =
				rspamd_mempool_alloc(cfg->cfg_pool,
									 sizeof(struct fuzzy_mapping));
			map->symbol = sym;
			elt = ucl_object_lookup(val, "flag");

			if (elt != NULL) {
				map->fuzzy_flag = ucl_obj_toint(elt);

				elt = ucl_object_lookup(val, "hits_limit");
				if (elt == NULL) {
					elt = ucl_object_lookup(val, "max_score");
				}

				if (elt != NULL) {
					map->weight = ucl_obj_todouble(elt);
				}
				else {
					map->weight = rule->hits_limit;
				}
				/* Add flag to hash table */
				g_hash_table_insert(rule->mappings,
									GINT_TO_POINTER(map->fuzzy_flag), map);
				rspamd_symcache_add_symbol(cfg->cache,
										   map->symbol, 0,
										   NULL, NULL,
										   SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
										   cb_id);
			}
			else {
				msg_err_config("fuzzy_map parameter has no flag definition");
			}
		}
		else {
			msg_err_config("fuzzy_map parameter has no symbol definition");
		}
	}
	else {
		msg_err_config("fuzzy_map parameter is of an unsupported type");
	}
}

static GPtrArray *
parse_fuzzy_headers(struct rspamd_config *cfg, const char *str)
{
	char **strvec;
	int num, i;
	GPtrArray *res;

	strvec = g_strsplit_set(str, ",", 0);
	num = g_strv_length(strvec);
	res = g_ptr_array_sized_new(num);

	for (i = 0; i < num; i++) {
		g_strstrip(strvec[i]);
		g_ptr_array_add(res, rspamd_mempool_strdup(
								 cfg->cfg_pool, strvec[i]));
	}

	g_strfreev(strvec);

	return res;
}

static void
fuzzy_rule_apply_checks(struct fuzzy_rule *rule,
						struct rspamd_config *cfg,
						const ucl_object_t *checks)
{
	const ucl_object_t *cur, *opt;
	ucl_object_iter_t it = NULL;
	const char *rule_name;

	if (checks == NULL) {
		return;
	}

	if (checks->type != UCL_OBJECT) {
		rule_name = rule->name ? rule->name : (rule->symbol ? rule->symbol : "unknown");
		msg_warn_config("checks parameter for fuzzy rule %s must be an object", rule_name);
		return;
	}

	rule_name = rule->name ? rule->name : (rule->symbol ? rule->symbol : "unknown");

	while ((cur = ucl_object_iterate(checks, &it, true)) != NULL) {
		const char *check_name = ucl_object_key(cur);

		if (check_name == NULL) {
			continue;
		}

		if (cur->type != UCL_OBJECT) {
			msg_warn_config("check %s in fuzzy rule %s must be an object", check_name, rule_name);
			continue;
		}

		if (g_ascii_strcasecmp(check_name, "text") == 0) {
			gboolean enabled = TRUE;

			if ((opt = ucl_object_lookup(cur, "enabled")) != NULL) {
				enabled = ucl_obj_toboolean(opt);
			}

			rule->text_hashes = enabled;

			if ((opt = ucl_object_lookup(cur, "no_subject")) != NULL) {
				rule->no_subject = ucl_obj_toboolean(opt);
			}
		}
		else if (g_ascii_strcasecmp(check_name, "html") == 0) {
			gboolean enabled = TRUE;

			if ((opt = ucl_object_lookup(cur, "enabled")) != NULL) {
				enabled = ucl_obj_toboolean(opt);
			}

			rule->html_shingles = enabled;

			if ((opt = ucl_object_lookup(cur, "min_html_tags")) != NULL) {
				rule->min_html_tags = ucl_obj_toint(opt);
			}
			else if ((opt = ucl_object_lookup(cur, "min_tags")) != NULL) {
				rule->min_html_tags = ucl_obj_toint(opt);
			}

			if ((opt = ucl_object_lookup(cur, "html_weight")) != NULL) {
				rule->html_weight = ucl_obj_todouble(opt);
			}
			else if ((opt = ucl_object_lookup(cur, "weight")) != NULL) {
				rule->html_weight = ucl_obj_todouble(opt);
			}

			if ((opt = ucl_object_lookup(cur, "ignore_link_domains")) != NULL) {
				rule->html_ignore_domains = ucl_obj_toboolean(opt);
			}
		}
		else {
			/* Other checks are processed by lua_fuzzy; keep legacy behaviour */
			if (g_ascii_strcasecmp(check_name, "images") != 0 &&
				g_ascii_strcasecmp(check_name, "image") != 0 &&
				g_ascii_strcasecmp(check_name, "archives") != 0 &&
				g_ascii_strcasecmp(check_name, "archive") != 0) {
				msg_warn_config("unknown check type '%s' in fuzzy rule %s", check_name, rule_name);
			}
		}
	}
}

static double
fuzzy_normalize(int32_t in, double weight)
{
	if (weight == 0) {
		return 0;
	}
#ifdef HAVE_TANH
	return tanh(G_E * (double) in / weight);
#else
	return (in < weight ? in / weight : weight);
#endif
}

static struct fuzzy_rule *
fuzzy_rule_new(const char *default_symbol, rspamd_mempool_t *pool)
{
	struct fuzzy_rule *rule;

	rule = rspamd_mempool_alloc0(pool, sizeof(struct fuzzy_rule));

	rule->mappings = g_hash_table_new(g_direct_hash, g_direct_equal);
	rule->symbol = default_symbol;
	rspamd_mempool_add_destructor(pool,
								  (rspamd_mempool_destruct_t) g_hash_table_unref,
								  rule->mappings);
	rule->mode = fuzzy_rule_read_write;
	rule->weight_threshold = NAN;
	rule->html_weight = 1.0;
	rule->html_shingles = FALSE;
	rule->text_hashes = TRUE;
	rule->min_html_tags = 10;
	rule->html_ignore_domains = FALSE;

	return rule;
}

static void
fuzzy_free_rule(gpointer r)
{
	struct fuzzy_rule *rule = (struct fuzzy_rule *) r;

	g_string_free(rule->hash_key, TRUE);
	g_string_free(rule->shingles_key, TRUE);

	if (rule->local_key) {
		rspamd_keypair_unref(rule->local_key);
	}

	if (rule->peer_key) {
		rspamd_pubkey_unref(rule->peer_key);
	}

	if (rule->read_local_key) {
		rspamd_keypair_unref(rule->read_local_key);
	}

	if (rule->read_peer_key) {
		rspamd_pubkey_unref(rule->read_peer_key);
	}

	if (rule->write_local_key) {
		rspamd_keypair_unref(rule->write_local_key);
	}

	if (rule->write_peer_key) {
		rspamd_pubkey_unref(rule->write_peer_key);
	}

	/* Clean up TCP connections */
	if (rule->tcp_connections) {
		g_ptr_array_free(rule->tcp_connections, TRUE);
	}

	/* Clean up pending requests pool */
	if (rule->pending_requests) {
		struct fuzzy_tcp_pending_command *pending;

		kh_foreach_value(rule->pending_requests, pending, {
			g_free(pending);
		});
		kh_destroy(fuzzy_pending_hash, rule->pending_requests);
	}
}

/**
 * Update the rate tracker for TCP auto-switch decision
 * Uses a sliding window to track request rate
 */
static void
fuzzy_update_rate_tracker(struct fuzzy_rule *rule, ev_tstamp now)
{
	/* Check if we need to reset the window */
	if (rule->rate_tracker.window_start == 0 ||
		(now - rule->rate_tracker.window_start) >= rule->tcp_window) {
		/* Start new window */
		rule->rate_tracker.window_start = now;
		rule->rate_tracker.requests_count = 1;
	}
	else {
		/* Increment counter in current window */
		rule->rate_tracker.requests_count++;
	}
}

/**
 * Check if TCP should be attempted based on configuration and rate
 */
static gboolean
fuzzy_should_try_tcp(struct fuzzy_rule *rule, ev_tstamp now)
{
	/* TCP explicitly enabled - always try */
	if (rule->tcp_enabled) {
		return TRUE;
	}

	/* TCP auto-switch based on rate */
	if (rule->tcp_auto && rule->tcp_window > 0) {
		ev_tstamp elapsed = now - rule->rate_tracker.window_start;
		if (elapsed > 0) {
			double rate = (double) rule->rate_tracker.requests_count / elapsed;
			if (rate > rule->tcp_threshold) {
				return TRUE;
			}
		}
	}

	return FALSE;
}

/* Forward declarations for TCP functions */
static void fuzzy_tcp_io_handler(int fd, short what, gpointer ud);
static void fuzzy_tcp_write_handler(struct fuzzy_tcp_connection *conn);
static void fuzzy_tcp_read_handler(struct fuzzy_tcp_connection *conn);
static gboolean fuzzy_tcp_send_command(struct fuzzy_tcp_connection *conn,
									   GPtrArray *commands,
									   struct fuzzy_client_session *session);
static void fuzzy_tcp_connection_close(struct fuzzy_tcp_connection *conn);
static void fuzzy_tcp_connection_cleanup(struct fuzzy_tcp_connection *conn, const char *reason);
static gboolean fuzzy_check_session_is_completed(struct fuzzy_client_session *session);

/* Forward declarations for helper functions */
static gboolean fuzzy_rule_has_encryption(struct fuzzy_rule *rule);
static void fuzzy_insert_result(struct fuzzy_client_session *session,
								const struct rspamd_fuzzy_reply *rep,
								struct rspamd_fuzzy_cmd *cmd,
								struct fuzzy_cmd_io *io,
								unsigned int flag);

#define FUZZY_TCP_RETAIN(x) REF_RETAIN(x)
#define FUZZY_TCP_RELEASE(x) REF_RELEASE(x)

/**
 * Free TCP connection resources (called by reference counting)
 */
static void
fuzzy_tcp_connection_free(struct fuzzy_tcp_connection *conn)
{
	if (conn->fd != -1) {
		rspamd_ev_watcher_stop(conn->event_loop, &conn->ev);
		close(conn->fd);
		conn->fd = -1;
	}

	if (conn->write_queue) {
		g_queue_free(conn->write_queue);
	}

	msg_debug("fuzzy_tcp: freeing connection to %s for rule %s",
			  conn->server_name ? conn->server_name : "unknown",
			  conn->rule ? conn->rule->name : "unknown");

	if (conn->server_name) {
		g_free(conn->server_name);
	}

	g_free(conn);
}

/**
 * Wrapper for g_ptr_array free function - releases reference
 */
static void
fuzzy_tcp_connection_unref(gpointer conn_ptr)
{
	struct fuzzy_tcp_connection *conn = (struct fuzzy_tcp_connection *) conn_ptr;
	FUZZY_TCP_RELEASE(conn);
}

/**
 * Refresh TCP connection timeout after successful I/O activity
 * This prevents active connections from timing out during data transfer.
 * Uses ev_timer_again with a repeat interval for a single syscall instead
 * of the stop/set/start triple.
 */
static void
fuzzy_tcp_refresh_timeout(struct fuzzy_tcp_connection *conn)
{
	if (conn->rule->tcp_timeout > 0 && ev_is_active(&conn->ev.tm)) {
		conn->ev.tm.repeat = conn->rule->tcp_timeout;
		ev_timer_again(conn->event_loop, &conn->ev.tm);
	}
}

/**
 * Create new TCP connection structure
 */
static struct fuzzy_tcp_connection *
fuzzy_tcp_connection_new(struct fuzzy_rule *rule, struct ev_loop *event_loop)
{
	struct fuzzy_tcp_connection *conn;

	conn = g_malloc0(sizeof(struct fuzzy_tcp_connection));
	conn->rule = rule;
	conn->fd = -1;
	conn->event_loop = event_loop;
	conn->write_queue = g_queue_new();
	conn->connected = FALSE;
	conn->connecting = FALSE;
	conn->failed = FALSE;
	conn->cur_frame_state = 0x0000;
	conn->bytes_sent = 0;
	conn->bytes_unprocessed = 0;

	REF_INIT_RETAIN(conn, fuzzy_tcp_connection_free);

	return conn;
}

/**
 * Initiate asynchronous TCP connection for specific upstream
 */
static struct fuzzy_tcp_connection *
fuzzy_tcp_connect_async(struct fuzzy_rule *rule,
						struct upstream *upstream,
						struct rspamd_task *task,
						gboolean is_write_server)
{
	struct fuzzy_tcp_connection *conn;
	rspamd_inet_addr_t *addr;
	int fd;

	/* Get current server address (not next, to avoid address rotation) */
	addr = rspamd_upstream_addr_cur(upstream);
	if (!addr) {
		msg_warn_task("fuzzy_tcp: no address for upstream %s in rule %s",
					  rspamd_upstream_name(upstream),
					  rule->name);
		return NULL;
	}

	/* Create non-blocking TCP socket */
	fd = rspamd_inet_address_connect(addr, SOCK_STREAM, TRUE);
	if (fd == -1) {
		msg_warn_task("fuzzy_tcp: cannot connect to %s (%s): %s",
					  rspamd_upstream_name(upstream),
					  rspamd_inet_address_to_string_pretty(addr),
					  strerror(errno));
		rspamd_upstream_fail(upstream, FALSE, strerror(errno));
		return NULL;
	}

	/* Set TCP_NODELAY to disable Nagle's algorithm - reduces latency for request-response traffic */
#ifdef TCP_NODELAY
	{
		int nodelay = 1;
		if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) == -1) {
			msg_warn_task("fuzzy_tcp: cannot set TCP_NODELAY for %s: %s",
						  rspamd_inet_address_to_string_pretty(addr),
						  strerror(errno));
		}
	}
#endif

	/* Create connection structure */
	conn = fuzzy_tcp_connection_new(rule, task->event_loop);
	conn->fd = fd;
	conn->server = upstream;
	conn->server_name = g_strdup(rspamd_upstream_name(upstream));
	conn->addr = addr;
	conn->connecting = TRUE;
	conn->connect_start = rspamd_get_calendar_ticks();

	/* Determine encryption keys for this connection */
	if (fuzzy_rule_has_encryption(rule)) {
		if (is_write_server) {
			/* Write server - use write keys */
			conn->local_key = rule->write_local_key ? rule->write_local_key : rule->local_key;
			conn->peer_key = rule->write_peer_key ? rule->write_peer_key : rule->peer_key;
		}
		else {
			/* Read server - use read keys */
			conn->local_key = rule->read_local_key ? rule->read_local_key : rule->local_key;
			conn->peer_key = rule->read_peer_key ? rule->read_peer_key : rule->peer_key;
		}
		conn->encrypted = TRUE;
	}
	else {
		conn->local_key = NULL;
		conn->peer_key = NULL;
		conn->encrypted = FALSE;
	}

	/* Store in connection pool array BEFORE starting event watcher
	 * This prevents race condition where another task might create duplicate connection
	 * Array takes ownership of initial reference */
	g_ptr_array_add(rule->tcp_connections, conn);

	/* Initialize event watcher for connection establishment (wait for write) */
	rspamd_ev_watcher_init(&conn->ev, fd, EV_WRITE,
						   fuzzy_tcp_io_handler, conn);
	rspamd_ev_watcher_start(conn->event_loop, &conn->ev, rule->tcp_timeout);

	msg_debug_task("fuzzy_tcp: initiating connection to %s for rule %s",
				   rspamd_inet_address_to_string_pretty(addr),
				   rule->name);

	return conn;
}

/**
 * Get or create TCP connection for specific upstream
 * Returns existing connection if available, creates new one if needed
 */
static struct fuzzy_tcp_connection *
fuzzy_tcp_get_or_create_connection(struct fuzzy_rule *rule,
								   struct upstream *upstream,
								   struct rspamd_task *task,
								   gboolean is_write_server)
{
	struct fuzzy_tcp_connection *conn = NULL;
	guint i;

	/* Search for existing connection to this upstream */
	for (i = 0; i < rule->tcp_connections->len; i++) {
		struct fuzzy_tcp_connection *c = g_ptr_array_index(rule->tcp_connections, i);

		if (c->server == upstream) {
			conn = c;
			break;
		}
	}

	if (conn) {
		/* Connection exists - check state */
		if (conn->connected) {
			/* Ready to use */
			msg_debug_task("fuzzy_tcp: reusing established connection to %s for rule %s",
						   rspamd_upstream_name(upstream), rule->name);
			return conn;
		}
		else if (conn->connecting) {
			/* Connection in progress - cannot use yet */
			msg_debug_task("fuzzy_tcp: connection to %s is still connecting, using UDP fallback",
						   rspamd_upstream_name(upstream));
			return NULL;
		}
		else if (conn->failed) {
			/* Previous connection failed - check if enough time passed to retry */
			ev_tstamp now = rspamd_get_calendar_ticks();
			ev_tstamp time_since_failure = now - conn->last_failure;

			if (time_since_failure < rule->tcp_retry_delay) {
				/* Recent failure - don't retry TCP yet, fallback to UDP */
				msg_debug_task("fuzzy_tcp: connection failed %.1fs ago for %s (retry_delay=%.1fs), using UDP fallback",
							   time_since_failure,
							   rspamd_upstream_name(upstream),
							   rule->tcp_retry_delay);
				return NULL;
			}
			else {
				/* Old failure - remove and try reconnecting */
				/* Log at info for auto-switch (important), debug for always-on TCP */
				if (rule->tcp_auto) {
					msg_info_task("fuzzy_tcp: connection failed %.1fs ago for %s (retry_delay=%.1fs), retrying TCP",
								  time_since_failure,
								  rspamd_upstream_name(upstream),
								  rule->tcp_retry_delay);
				}
				else {
					msg_debug_task("fuzzy_tcp: connection failed %.1fs ago for %s (retry_delay=%.1fs), retrying TCP",
								   time_since_failure,
								   rspamd_upstream_name(upstream),
								   rule->tcp_retry_delay);
				}
				/* g_ptr_array_remove automatically calls fuzzy_tcp_connection_unref via free_func */
				g_ptr_array_remove(rule->tcp_connections, conn);
				conn = NULL;
			}
		}
	}

	/* No connection or failed - create new one */
	if (!conn) {
		conn = fuzzy_tcp_connect_async(rule, upstream, task, is_write_server);
	}

	return conn;
}

/**
 * Close connection socket and mark as failed
 * Stops event watcher, closes fd, marks connection as failed
 * Should be called before fuzzy_tcp_connection_cleanup
 */
static void
fuzzy_tcp_connection_close(struct fuzzy_tcp_connection *conn)
{
	if (conn->fd != -1) {
		rspamd_ev_watcher_stop(conn->event_loop, &conn->ev);
		close(conn->fd);
		conn->fd = -1;
	}
	conn->failed = TRUE;
	conn->last_failure = rspamd_get_calendar_ticks();
	conn->connecting = FALSE;
	conn->connected = FALSE;
}

/**
 * Cleanup pending requests for a failed connection
 * Removes all pending commands associated with this connection
 * This is called only for connection-level failures (socket errors, not session timeouts)
 */
static void
fuzzy_tcp_connection_cleanup(struct fuzzy_tcp_connection *conn, const char *reason)
{
	khash_t(fuzzy_pending_hash) * pending_ht;
	struct fuzzy_tcp_pending_command *pending;
	GHashTable *sessions_to_check;
	GHashTableIter session_iter;
	struct fuzzy_client_session *session;
	struct rspamd_task *task = NULL;
	int sessions_checked = 0;
	unsigned int removed = 0;

	if (!conn || !conn->rule || !(pending_ht = conn->rule->pending_requests)) {
		return;
	}

	msg_info("fuzzy_tcp: cleaning up connection to %s for rule %s, reason: %s",
			 conn->server_name ? conn->server_name : "unknown",
			 conn->rule->name,
			 reason ? reason : "unknown");

	sessions_to_check = g_hash_table_new(g_direct_hash, g_direct_equal);

	for (khiter_t k = kh_begin(pending_ht); k != kh_end(pending_ht); ++k) {
		if (!kh_exist(pending_ht, k)) {
			continue;
		}

		pending = kh_val(pending_ht, k);

		if (pending->connection == conn) {
			if (!(pending->io->flags & FUZZY_CMD_FLAG_REPLIED)) {
				pending->io->flags |= FUZZY_CMD_FLAG_REPLIED;
			}

			if (pending->session) {
				g_hash_table_add(sessions_to_check, pending->session);
			}

			if (!task && pending->task) {
				task = pending->task;
			}

			g_free(pending);
			kh_del(fuzzy_pending_hash, pending_ht, k);
			removed++;
		}
	}

	if (removed > 0 && task) {
		msg_warn_task("fuzzy_tcp: cleaned up %ud pending commands due to connection failure: %s",
					  removed, reason ? reason : "unknown");
	}

	g_hash_table_iter_init(&session_iter, sessions_to_check);
	while (g_hash_table_iter_next(&session_iter, (gpointer *) &session, NULL)) {
		sessions_checked++;
		fuzzy_check_session_is_completed(session);
	}

	if (sessions_checked > 0 && task) {
		msg_debug_task("fuzzy_tcp: checked %d sessions for completion after connection cleanup",
					   sessions_checked);
	}

	g_hash_table_unref(sessions_to_check);
}

/**
 * Check and cleanup timed out pending requests
 * Called periodically to remove requests that waited too long for reply
 */
static void
fuzzy_tcp_check_pending_timeouts(struct fuzzy_rule *rule, ev_tstamp now)
{
	khash_t(fuzzy_pending_hash) * pending_ht;
	struct fuzzy_tcp_pending_command *pending;
	GHashTable *sessions_to_check;
	GHashTableIter session_iter;
	struct fuzzy_client_session *session;
	ev_tstamp timeout;

	if (!rule || !(pending_ht = rule->pending_requests)) {
		return;
	}

	timeout = rule->io_timeout;
	sessions_to_check = g_hash_table_new(g_direct_hash, g_direct_equal);

	for (khiter_t k = kh_begin(pending_ht); k != kh_end(pending_ht); ++k) {
		if (!kh_exist(pending_ht, k)) {
			continue;
		}

		pending = kh_val(pending_ht, k);

		if ((now - pending->send_time) > timeout) {
			if (!(pending->io->flags & FUZZY_CMD_FLAG_REPLIED)) {
				pending->io->flags |= FUZZY_CMD_FLAG_REPLIED;
			}

			if (pending->session) {
				g_hash_table_add(sessions_to_check, pending->session);
			}

			if (pending->task) {
				struct rspamd_task *task = pending->task;

				if (rule->tcp_auto) {
					msg_info_task("fuzzy_tcp: request timeout after %.2fs for tag %ud to %s",
								  now - pending->send_time,
								  pending->io->tag,
								  rspamd_upstream_name(pending->connection->server));
				}
				else {
					msg_debug_task("fuzzy_tcp: request timeout after %.2fs for tag %ud to %s",
								   now - pending->send_time,
								   pending->io->tag,
								   rspamd_upstream_name(pending->connection->server));
				}
			}

			g_free(pending);
			kh_del(fuzzy_pending_hash, pending_ht, k);
		}
	}

	g_hash_table_iter_init(&session_iter, sessions_to_check);
	while (g_hash_table_iter_next(&session_iter, (gpointer *) &session, NULL)) {
		fuzzy_check_session_is_completed(session);
	}

	g_hash_table_unref(sessions_to_check);
}

/**
 * Main TCP I/O event handler
 * Handles connection establishment, reads, writes, and timeouts
 */
static void
fuzzy_tcp_io_handler(int fd, short what, gpointer ud)
{
	struct fuzzy_tcp_connection *conn = ud;
	int so_error = 0;
	socklen_t so_len = sizeof(so_error);

	FUZZY_TCP_RETAIN(conn);

	conn->last_activity = rspamd_get_calendar_ticks();

	if (what == EV_TIMEOUT) {
		ev_tstamp elapsed = rspamd_get_calendar_ticks() - conn->connect_start;
		msg_warn("fuzzy_tcp: connection timeout for rule %s to %s after %.2fs (connecting=%d, connected=%d)",
				 conn->rule->name,
				 rspamd_upstream_name(conn->server),
				 elapsed,
				 conn->connecting,
				 conn->connected);
		fuzzy_tcp_connection_close(conn);
		fuzzy_tcp_connection_cleanup(conn, "connection timeout");
		rspamd_upstream_fail(conn->server, TRUE, "connection timeout");
		FUZZY_TCP_RELEASE(conn);
		return;
	}

	if (what & EV_WRITE) {
		/* Check if we're still connecting */
		if (conn->connecting && !conn->connected) {
			/* Verify connection succeeded */
			if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &so_len) == -1) {
				msg_warn("fuzzy_tcp: getsockopt failed for rule %s to %s: %s",
						 conn->rule->name,
						 rspamd_upstream_name(conn->server),
						 strerror(errno));
				fuzzy_tcp_connection_close(conn);
				fuzzy_tcp_connection_cleanup(conn, "getsockopt failed");
				rspamd_upstream_fail(conn->server, TRUE, "getsockopt failed");
				FUZZY_TCP_RELEASE(conn);
				return;
			}

			if (so_error != 0) {
				char error_buf[128];
				rspamd_snprintf(error_buf, sizeof(error_buf), "connect error: %s", strerror(so_error));
				msg_warn("fuzzy_tcp: connection failed for rule %s to %s: %s",
						 conn->rule->name,
						 rspamd_upstream_name(conn->server),
						 strerror(so_error));
				fuzzy_tcp_connection_close(conn);
				fuzzy_tcp_connection_cleanup(conn, error_buf);
				rspamd_upstream_fail(conn->server, TRUE, strerror(so_error));
				FUZZY_TCP_RELEASE(conn);
				return;
			}

			/* Connection established! */
			conn->connected = TRUE;
			conn->connecting = FALSE;
			ev_tstamp elapsed = rspamd_get_calendar_ticks() - conn->connect_start;

			/* Log at info level only for auto-switch mode (important event), debug otherwise */
			if (conn->rule->tcp_auto) {
				msg_info("fuzzy_tcp: connection established to %s for rule %s in %.3fs (fd=%d, encrypted=%d)",
						 rspamd_inet_address_to_string_pretty(conn->addr),
						 conn->rule->name,
						 elapsed,
						 conn->fd,
						 conn->encrypted);
			}
			else {
				msg_debug("fuzzy_tcp: connection established to %s for rule %s in %.3fs (fd=%d, encrypted=%d)",
						  rspamd_inet_address_to_string_pretty(conn->addr),
						  conn->rule->name,
						  elapsed,
						  conn->fd,
						  conn->encrypted);
			}

			rspamd_upstream_ok(conn->server);

			/* Start reading; only arm EV_WRITE if there's queued data */
			rspamd_ev_watcher_reschedule(conn->event_loop, &conn->ev,
										 g_queue_is_empty(conn->write_queue) ? EV_READ : EV_READ | EV_WRITE);

			msg_debug("fuzzy_tcp: after reschedule - fd=%d, ev.io.fd=%d",
					  conn->fd, (int) conn->ev.io.fd);
		}
		else if (conn->connected) {
			/* Handle write */
			fuzzy_tcp_write_handler(conn);
		}
	}

	if (what & EV_READ && conn->connected) {
		/* Handle read */
		fuzzy_tcp_read_handler(conn);
	}

	FUZZY_TCP_RELEASE(conn);
}

/**
 * TCP write handler
 * Sends queued commands to the server with TCP framing
 */
static void
fuzzy_tcp_write_handler(struct fuzzy_tcp_connection *conn)
{
	struct fuzzy_tcp_write_buf *buf;
	ssize_t r;
	gboolean did_write = FALSE;

	while ((buf = g_queue_peek_head(conn->write_queue)) != NULL) {
		/* Write remaining data */
		gsize remaining;
		unsigned char *write_ptr;

		/* Determine what to write: size_hdr or data */
		if (buf->bytes_written < sizeof(buf->size_hdr)) {
			/* Still writing size header */
			write_ptr = (unsigned char *) &buf->size_hdr + buf->bytes_written;
			remaining = sizeof(buf->size_hdr) - buf->bytes_written;
		}
		else {
			/* Writing data */
			gsize data_offset = buf->bytes_written - sizeof(buf->size_hdr);
			gsize data_len = buf->total_len - sizeof(buf->size_hdr);
			write_ptr = buf->data + data_offset;
			remaining = data_len - data_offset;
		}

		r = write(conn->fd, write_ptr, remaining);

		if (r == -1) {
			if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
				/* Cannot write more, wait for next event */
				return;
			}
			char error_buf[128];
			rspamd_snprintf(error_buf, sizeof(error_buf), "write error: %s", strerror(errno));
			msg_err("fuzzy_tcp: write error for rule %s to %s: %s",
					conn->rule->name,
					rspamd_upstream_name(conn->server),
					strerror(errno));
			fuzzy_tcp_connection_close(conn);
			fuzzy_tcp_connection_cleanup(conn, error_buf);
			return;
		}
		else if (r == 0) {
			/* Connection closed by peer - log at info for auto mode, debug otherwise */
			if (conn->rule->tcp_auto) {
				msg_info("fuzzy_tcp: connection closed by %s for rule %s",
						 rspamd_upstream_name(conn->server),
						 conn->rule->name);
			}
			else {
				msg_debug("fuzzy_tcp: connection closed by %s for rule %s",
						  rspamd_upstream_name(conn->server),
						  conn->rule->name);
			}
			fuzzy_tcp_connection_close(conn);
			fuzzy_tcp_connection_cleanup(conn, "connection closed by peer");
			return;
		}

		buf->bytes_written += r;
		did_write = TRUE;

		if (buf->bytes_written >= buf->total_len) {
			/* Buffer fully sent, remove from queue and free */
			g_queue_pop_head(conn->write_queue);
			g_free(buf->data);
			g_free(buf);
		}
		else {
			/* Partial write, wait for next event */
			return;
		}
	}

	/* Refresh timeout once after all writes, not per-buffer */
	if (did_write) {
		fuzzy_tcp_refresh_timeout(conn);
	}

	/* Queue is empty, switch to read-only to avoid busy-looping on EV_WRITE */
	rspamd_ev_watcher_reschedule(conn->event_loop, &conn->ev, EV_READ);
}

/**
 * Send commands via TCP connection
 * Adds TCP framing and queues for sending, registers in pending pool
 */
static gboolean
fuzzy_tcp_send_command(struct fuzzy_tcp_connection *conn,
					   GPtrArray *commands,
					   struct fuzzy_client_session *session)
{
	struct fuzzy_cmd_io *io;
	struct fuzzy_tcp_write_buf *buf;
	struct fuzzy_tcp_pending_command *pending;
	unsigned int i;
	struct rspamd_task *task = session->task;

	msg_debug_task("fuzzy_tcp_send_command: fd=%d, ev.io.fd=%d, connected=%d, failed=%d",
				   conn->fd, (int) conn->ev.io.fd, conn->connected, conn->failed);

	/* Don't send if connection is failed or not connected */
	if (!conn->connected || conn->failed) {
		msg_warn_task("fuzzy_tcp: cannot send commands - connection not ready (connected=%d, failed=%d)",
					  conn->connected, conn->failed);
		return FALSE;
	}

	for (i = 0; i < commands->len; i++) {
		io = g_ptr_array_index(commands, i);

		/* Skip if already sent or replied */
		if (io->flags & (FUZZY_CMD_FLAG_SENT | FUZZY_CMD_FLAG_REPLIED)) {
			continue;
		}

		/* Prepare TCP framed buffer */
		buf = g_malloc0(sizeof(*buf));
		buf->data = g_malloc(io->io.iov_len);
		memcpy(buf->data, io->io.iov_base, io->io.iov_len);

		/* Set frame size in little endian byte order */
		buf->size_hdr = GUINT16_TO_LE((uint16_t) io->io.iov_len);
		buf->total_len = sizeof(buf->size_hdr) + io->io.iov_len;
		buf->bytes_written = 0;

		/* Add to write queue */
		g_queue_push_tail(conn->write_queue, buf);

		/* Register in pending requests pool */
		pending = g_malloc0(sizeof(*pending));
		pending->io = io;
		pending->task = task;
		pending->session = session;
		pending->connection = conn;
		pending->send_time = rspamd_get_calendar_ticks();

		khiter_t k;
		int kh_ret;

		k = kh_put(fuzzy_pending_hash, conn->rule->pending_requests, io->tag, &kh_ret);

		if (kh_ret < 0) {
			msg_err_task("fuzzy_tcp: cannot register pending command for tag %ud", io->tag);
			g_free(pending);
		}
		else {
			if (kh_ret == 0) {
				struct fuzzy_tcp_pending_command *old = kh_val(conn->rule->pending_requests, k);
				if (old) {
					g_free(old);
				}
			}

			kh_val(conn->rule->pending_requests, k) = pending;
		}

		/* Mark as sent */
		io->flags |= FUZZY_CMD_FLAG_SENT;

		msg_debug_fuzzy_check("fuzzy_tcp: queued command with tag %ud to %s",
							  io->tag, rspamd_upstream_name(conn->server));
	}

	/* Ensure write events are enabled */
	if (!g_queue_is_empty(conn->write_queue)) {
		msg_debug_task("fuzzy_tcp: checking watcher before reschedule - fd=%d, ev.io.fd=%d",
					   conn->fd, (int) conn->ev.io.fd);

		/* Verify fd is valid before rescheduling */
		if (conn->fd >= 0 && conn->ev.io.fd == conn->fd) {
			msg_debug_task("fuzzy_tcp: reschedule watcher for fd=%d", conn->fd);
			rspamd_ev_watcher_reschedule(conn->event_loop, &conn->ev, EV_READ | EV_WRITE);
		}
		else if (conn->fd >= 0 && conn->ev.io.fd != conn->fd) {
			/* Fd mismatch - reinitialize watcher */
			msg_warn_task("fuzzy_tcp: fd mismatch in watcher (ev.fd=%d, conn.fd=%d), reinitializing",
						  (int) conn->ev.io.fd, conn->fd);
			rspamd_ev_watcher_stop(conn->event_loop, &conn->ev);
			rspamd_ev_watcher_init(&conn->ev, conn->fd, EV_READ | EV_WRITE,
								   fuzzy_tcp_io_handler, conn);
			rspamd_ev_watcher_start(conn->event_loop, &conn->ev, conn->rule->tcp_timeout);
		}
		else {
			msg_warn_task("fuzzy_tcp: invalid fd in connection (fd=%d, ev.io.fd=%d), cannot reschedule",
						  conn->fd, (int) conn->ev.io.fd);
		}
	}

	return TRUE;
}

/**
 * Process a single TCP reply frame
 * Decrypts reply, matches with pending command by tag, delivers result
 */
static void
fuzzy_tcp_process_reply(struct fuzzy_tcp_connection *conn,
						unsigned char *data, gsize len)
{
	struct rspamd_fuzzy_encrypted_reply encrep;
	struct rspamd_fuzzy_encrypted_reply_v2 encrep_v2;
	const struct rspamd_fuzzy_reply *rep;
	const struct rspamd_fuzzy_reply_v2 *rep_v2 = NULL;
	struct rspamd_fuzzy_reply synthetic_rep;
	struct fuzzy_rule *rule = conn->rule;
	unsigned int required_size;
	struct fuzzy_tcp_pending_command *pending;
	uint32_t tag;
	gboolean is_v2 = FALSE;

	/* Check minimum size — accept v1 as minimum */
	if (conn->encrypted) {
		required_size = sizeof(encrep);
	}
	else {
		required_size = sizeof(struct rspamd_fuzzy_reply);
	}

	if (len < required_size) {
		msg_warn("fuzzy_tcp: invalid reply size %d from %s, expected at least %d",
				 (int) len, rspamd_upstream_name(conn->server), (int) required_size);
		return;
	}

	/* Detect v2 reply by size */
	if (conn->encrypted && len >= sizeof(encrep_v2)) {
		is_v2 = TRUE;
	}
	else if (!conn->encrypted && len >= sizeof(struct rspamd_fuzzy_reply_v2)) {
		is_v2 = TRUE;
	}

	/* Decrypt if needed - use keys from connection */
	if (conn->encrypted) {
		/* Process keys through cache */
		rspamd_keypair_cache_process(rule->ctx->keypairs_cache,
									 conn->local_key, conn->peer_key);

		if (is_v2) {
			memcpy(&encrep_v2, data, sizeof(encrep_v2));

			if (!rspamd_cryptobox_decrypt_nm_inplace((unsigned char *) &encrep_v2.rep,
													 sizeof(encrep_v2.rep),
													 encrep_v2.hdr.nonce,
													 rspamd_pubkey_get_nm(conn->peer_key, conn->local_key),
													 encrep_v2.hdr.mac)) {
				msg_warn("fuzzy_tcp: cannot decrypt v2 reply from %s",
						 rspamd_upstream_name(conn->server));
				return;
			}

			rep_v2 = &encrep_v2.rep;
			/* Build a v1-compatible rep from v2 for primary processing */
			memset(&synthetic_rep, 0, sizeof(synthetic_rep));
			synthetic_rep.v1 = rep_v2->v1;
			memcpy(synthetic_rep.digest, rep_v2->digest, sizeof(synthetic_rep.digest));
			synthetic_rep.ts = rep_v2->ts;
			rep = &synthetic_rep;
		}
		else {
			memcpy(&encrep, data, sizeof(encrep));

			if (!rspamd_cryptobox_decrypt_nm_inplace((unsigned char *) &encrep.rep,
													 sizeof(encrep.rep),
													 encrep.hdr.nonce,
													 rspamd_pubkey_get_nm(conn->peer_key, conn->local_key),
													 encrep.hdr.mac)) {
				msg_warn("fuzzy_tcp: cannot decrypt reply from %s",
						 rspamd_upstream_name(conn->server));
				return;
			}

			rep = &encrep.rep;
		}
	}
	else {
		if (is_v2) {
			rep_v2 = (const struct rspamd_fuzzy_reply_v2 *) data;
			memset(&synthetic_rep, 0, sizeof(synthetic_rep));
			synthetic_rep.v1 = rep_v2->v1;
			memcpy(synthetic_rep.digest, rep_v2->digest, sizeof(synthetic_rep.digest));
			synthetic_rep.ts = rep_v2->ts;
			rep = &synthetic_rep;
		}
		else {
			rep = (const struct rspamd_fuzzy_reply *) data;
		}
	}

	if (is_v2) {
		rule->server_supports_v2 = TRUE;
	}

	/* Extract tag and lookup pending command */
	tag = rep->v1.tag;
	khiter_t k = kh_get(fuzzy_pending_hash, rule->pending_requests, tag);

	if (k == kh_end(rule->pending_requests)) {
		msg_debug("fuzzy_tcp: unexpected tag %ud from %s",
				  tag, rspamd_upstream_name(conn->server));
		return;
	}

	pending = kh_val(rule->pending_requests, k);

	/* Get task for debug logging */
	struct rspamd_task *task = pending->task;

	/* Process the reply - similar to UDP code in fuzzy_check_try_read */
	if (rep->v1.prob > 0.5) {
		if (pending->io->cmd.cmd == FUZZY_CHECK) {
			/* Insert result for primary flag */
			fuzzy_insert_result(pending->session, rep, &pending->io->cmd,
								pending->io, rep->v1.flag);

			/* Insert results for extra flags from v2 reply */
			if (rep_v2 && rep_v2->n_extra_flags > 0) {
				for (uint8_t ei = 0; ei < rep_v2->n_extra_flags && ei < RSPAMD_FUZZY_MAX_EXTRA_FLAGS; ei++) {
					struct rspamd_fuzzy_reply extra_rep;
					memset(&extra_rep, 0, sizeof(extra_rep));
					extra_rep.v1.value = rep_v2->extra_flags[ei].value;
					extra_rep.v1.flag = rep_v2->extra_flags[ei].flag;
					extra_rep.v1.tag = rep->v1.tag;
					extra_rep.v1.prob = rep->v1.prob;
					memcpy(extra_rep.digest, rep_v2->digest, sizeof(extra_rep.digest));
					extra_rep.ts = rep_v2->ts;

					fuzzy_insert_result(pending->session, &extra_rep, &pending->io->cmd,
										pending->io, extra_rep.v1.flag);
				}
			}
		}
		else if (pending->io->cmd.cmd == FUZZY_STAT) {
			/*
			 * We store fuzzy stat in the following way:
			 * 1) We store fuzzy hashes as a hash of rspamd_fuzzy_stat_entry
			 * 2) We store the resulting hash table inside pool variable `fuzzy_stat`
			 */
			struct rspamd_fuzzy_stat_entry *pval;
			GHashTable *stats_hash;

			stats_hash = (GHashTable *) rspamd_mempool_get_variable(task->task_pool,
																	RSPAMD_MEMPOOL_FUZZY_STAT);

			if (stats_hash == NULL) {
				stats_hash = g_hash_table_new(rspamd_str_hash, rspamd_str_equal);
				rspamd_mempool_set_variable(task->task_pool, RSPAMD_MEMPOOL_FUZZY_STAT,
											stats_hash,
											(rspamd_mempool_destruct_t) g_hash_table_destroy);
			}

			pval = g_hash_table_lookup(stats_hash, rule->name);

			if (pval == NULL) {
				pval = rspamd_mempool_alloc(task->task_pool, sizeof(*pval));
				pval->name = rspamd_mempool_strdup(task->task_pool, rule->name);
				/* Safe, as pval->name is owned by the pool */
				g_hash_table_insert(stats_hash, (char *) pval->name, pval);
			}

			pval->fuzzy_cnt = (((uint64_t) rep->v1.value) << 32) + rep->v1.flag;
		}
	}
	else if (rep->v1.value == 403) {
		/* In fact, it should be 429, but we preserve compatibility */
		rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_RATELIMITED, 1.0,
								  rule->name);
	}
	else if (rep->v1.value == 503) {
		rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_FORBIDDEN, 1.0,
								  rule->name);
	}
	else if (rep->v1.value == 415) {
		rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_ENCRYPTION_REQUIRED, 1.0,
								  rule->name);
	}
	else if (rep->v1.value == 401) {
		if (pending->io->cmd.cmd != FUZZY_CHECK) {
			msg_info_task("fuzzy check error for %d: skipped by server",
						  rep->v1.flag);
		}
	}
	else if (rep->v1.value != 0) {
		msg_info_task("fuzzy check error for %d: unknown error (%d)",
					  rep->v1.flag, rep->v1.value);
	}

	/* Mark as replied */
	if (!(pending->io->flags & FUZZY_CMD_FLAG_REPLIED)) {
		pending->io->flags |= FUZZY_CMD_FLAG_REPLIED;
	}

	msg_debug_fuzzy_check("fuzzy_tcp: processed reply with tag %ud from %s (prob=%.2f)",
						  tag, rspamd_upstream_name(conn->server), (double) rep->v1.prob);

	/* Save session before removing pending (which may free it) */
	struct fuzzy_client_session *session_to_check = pending->session;

	/* Remove from pending requests */
	kh_del(fuzzy_pending_hash, rule->pending_requests, k);
	g_free(pending);

	/* Check if session is completed */
	fuzzy_check_session_is_completed(session_to_check);
}

/**
 * TCP read handler
 * Reads replies from server, parses framing, matches with pending commands
 */
static void
fuzzy_tcp_read_handler(struct fuzzy_tcp_connection *conn)
{
	ssize_t r;
	gsize available_space;

	/* Read data from socket into buffer */
	available_space = sizeof(conn->read_buf) - conn->bytes_unprocessed;
	if (available_space == 0) {
		msg_err("fuzzy_tcp: read buffer full for rule %s, closing connection",
				conn->rule->name);
		fuzzy_tcp_connection_close(conn);
		fuzzy_tcp_connection_cleanup(conn, "read buffer overflow");
		return;
	}

	r = read(conn->fd, conn->read_buf + conn->bytes_unprocessed, available_space);

	if (r == -1) {
		if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
			return; /* Try again later */
		}
		char error_buf[128];
		rspamd_snprintf(error_buf, sizeof(error_buf), "read error: %s", strerror(errno));
		msg_err("fuzzy_tcp: read error for rule %s: %s",
				conn->rule->name, strerror(errno));
		fuzzy_tcp_connection_close(conn);
		fuzzy_tcp_connection_cleanup(conn, error_buf);
		return;
	}
	else if (r == 0) {
		/* Connection closed by peer - log at info for auto mode, debug otherwise */
		if (conn->rule->tcp_auto) {
			msg_info("fuzzy_tcp: connection closed by %s for rule %s",
					 rspamd_upstream_name(conn->server),
					 conn->rule->name);
		}
		else {
			msg_debug("fuzzy_tcp: connection closed by %s for rule %s",
					  rspamd_upstream_name(conn->server),
					  conn->rule->name);
		}
		fuzzy_tcp_connection_close(conn);
		fuzzy_tcp_connection_cleanup(conn, "connection closed by peer");
		return;
	}

	conn->bytes_unprocessed += r;

	/* Refresh timeout after successful read - keeps connection alive during active data transfer */
	fuzzy_tcp_refresh_timeout(conn);

	/* Process frames using state machine */
	unsigned int processed_offset = 0;

	while (processed_offset < conn->bytes_unprocessed) {
		uint16_t frame_len;

		/* State: 0x0000 - need first byte of length */
		if ((conn->cur_frame_state & 0xC000) == 0x0000) {
			if (processed_offset < conn->bytes_unprocessed) {
				conn->cur_frame_state = 0x8000 | conn->read_buf[processed_offset];
				processed_offset++;
			}
			else {
				break;
			}
		}

		/* State: 0x8000 - need second byte of length */
		if ((conn->cur_frame_state & 0xC000) == 0x8000) {
			if (processed_offset < conn->bytes_unprocessed) {
				uint16_t first_byte = conn->cur_frame_state & 0xFF;
				uint16_t second_byte = conn->read_buf[processed_offset];
				/* Reconstruct in little-endian byte order */
				conn->cur_frame_state = 0xC000 | (first_byte | (second_byte << 8));
				processed_offset++;
			}
			else {
				break;
			}
		}

		/* State: 0xC000 - have length, reading data */
		frame_len = conn->cur_frame_state & 0x3FFF;

		if ((conn->encrypted && frame_len > sizeof(struct rspamd_fuzzy_encrypted_reply_v2)) ||
			(!conn->encrypted && frame_len > sizeof(struct rspamd_fuzzy_reply_v2))) {
			char error_buf[128];
			rspamd_snprintf(error_buf, sizeof(error_buf), "invalid frame length: %d", (int) frame_len);
			msg_err("fuzzy_tcp: invalid frame length %d from %s, closing",
					(int) frame_len,
					rspamd_upstream_name(conn->server));
			fuzzy_tcp_connection_close(conn);
			fuzzy_tcp_connection_cleanup(conn, error_buf);
			return;
		}

		/* Check if we have complete frame */
		if (conn->bytes_unprocessed - processed_offset >= frame_len) {
			/* Process complete frame - decrypt and deliver to session */
			fuzzy_tcp_process_reply(conn, conn->read_buf + processed_offset, frame_len);

			processed_offset += frame_len;
			conn->cur_frame_state = 0x0000; /* Reset for next frame */
		}
		else {
			/* Incomplete frame, wait for more data */
			break;
		}
	}

	/* Move unprocessed data to beginning of buffer */
	if (processed_offset > 0) {
		if (processed_offset < conn->bytes_unprocessed) {
			memmove(conn->read_buf,
					conn->read_buf + processed_offset,
					conn->bytes_unprocessed - processed_offset);
			conn->bytes_unprocessed -= processed_offset;
		}
		else {
			conn->bytes_unprocessed = 0;
		}
	}
}

static int
fuzzy_parse_rule(struct rspamd_config *cfg, const ucl_object_t *obj,
				 const char *name, int cb_id)
{
	const ucl_object_t *value, *cur;
	struct fuzzy_rule *rule;
	ucl_object_iter_t it = NULL;
	const char *k = NULL, *key_str = NULL, *shingles_key_str = NULL, *lua_script;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(cfg);

	if (obj->type != UCL_OBJECT) {
		msg_err_config("invalid rule definition");
		return -1;
	}

	if ((value = ucl_object_lookup_any(obj, "enabled", "enable", NULL)) != NULL) {
		if (!ucl_object_toboolean(value)) {
			msg_info_config("fuzzy rule %s is disabled by configuration", name);

			return 0;
		}
	}

	rule = fuzzy_rule_new(fuzzy_module_ctx->default_symbol,
						  cfg->cfg_pool);
	rule->ucl_obj = obj;
	rule->ctx = fuzzy_module_ctx;
	rule->learn_condition_cb = -1;
	rule->alg = RSPAMD_SHINGLES_OLD;
	rule->skip_map = NULL;

	msg_debug_config("parsing fuzzy rule '%s'", name ? name : "default");

	if ((value = ucl_object_lookup(obj, "skip_hashes")) != NULL) {
		rspamd_map_add_from_ucl(cfg, value,
								"Fuzzy hashes whitelist",
								rspamd_kv_list_read,
								rspamd_kv_list_fin,
								rspamd_kv_list_dtor,
								(void **) &rule->skip_map,
								NULL, RSPAMD_MAP_DEFAULT);
	}

	if ((value = ucl_object_lookup(obj, "headers")) != NULL) {
		it = NULL;
		while ((cur = ucl_object_iterate(value, &it, value->type == UCL_ARRAY)) != NULL) {
			GPtrArray *tmp;
			unsigned int i;
			gpointer ptr;

			tmp = parse_fuzzy_headers(cfg, ucl_obj_tostring(cur));

			if (tmp) {
				if (rule->fuzzy_headers) {
					PTR_ARRAY_FOREACH(tmp, i, ptr)
					{
						g_ptr_array_add(rule->fuzzy_headers, ptr);
					}

					g_ptr_array_free(tmp, TRUE);
				}
				else {
					rule->fuzzy_headers = tmp;
				}
			}
		}
	}
	else {
		rule->fuzzy_headers = parse_fuzzy_headers(cfg, default_headers);
	}

	if (rule->fuzzy_headers != NULL) {
		rspamd_mempool_add_destructor(cfg->cfg_pool,
									  (rspamd_mempool_destruct_t) rspamd_ptr_array_free_hard,
									  rule->fuzzy_headers);
	}


	/* hits_limit: number of fuzzy hits at which normalized score reaches ~1.0
	 * Legacy name: max_score (supported for backward compatibility) */
	if ((value = ucl_object_lookup(obj, "hits_limit")) != NULL) {
		rule->hits_limit = ucl_obj_todouble(value);
	}
	else if ((value = ucl_object_lookup(obj, "max_score")) != NULL) {
		rule->hits_limit = ucl_obj_todouble(value);
	}

	if ((value = ucl_object_lookup(obj, "retransmits")) != NULL) {
		rule->retransmits = ucl_obj_toint(value);
	}
	else {
		rule->retransmits = fuzzy_module_ctx->retransmits;
	}

	if ((value = ucl_object_lookup(obj, "timeout")) != NULL) {
		rule->io_timeout = ucl_obj_todouble(value);
	}
	else {
		rule->io_timeout = fuzzy_module_ctx->io_timeout;
	}

	if ((value = ucl_object_lookup(obj, "symbol")) != NULL) {
		rule->symbol = ucl_obj_tostring(value);
	}

	if (name) {
		rule->name = name;
	}
	else {
		rule->name = rule->symbol;
	}


	if ((value = ucl_object_lookup(obj, "read_only")) != NULL) {
		rule->mode = ucl_obj_toboolean(value) ? fuzzy_rule_read_only : fuzzy_rule_read_write;
	}

	if ((value = ucl_object_lookup(obj, "mode")) != NULL) {
		const char *mode_str = ucl_object_tostring(value);

		if (g_ascii_strcasecmp(mode_str, "read_only") == 0) {
			rule->mode = fuzzy_rule_read_only;
		}
		else if (g_ascii_strcasecmp(mode_str, "write_only") == 0) {
			rule->mode = fuzzy_rule_write_only;
		}
		else if (g_ascii_strcasecmp(mode_str, "read_write") == 0) {
			rule->mode = fuzzy_rule_read_write;
		}
		else {
			msg_warn_config("unknown mode: %s, use read_write by default",
							mode_str);
			rule->mode = fuzzy_rule_read_write;
		}
	}

	if ((value = ucl_object_lookup(obj, "skip_unknown")) != NULL) {
		rule->skip_unknown = ucl_obj_toboolean(value);
	}

	if ((value = ucl_object_lookup(obj, "no_share")) != NULL) {
		rule->no_share = ucl_obj_toboolean(value);
	}

	if ((value = ucl_object_lookup(obj, "no_subject")) != NULL) {
		rule->no_subject = ucl_obj_toboolean(value);
	}
	/* TCP configuration */
	if ((value = ucl_object_lookup(obj, "tcp")) != NULL) {
		const ucl_object_t *tcp_obj;

		if (ucl_object_type(value) == UCL_BOOLEAN) {
			/* Simple boolean: enable/disable TCP */
			rule->tcp_enabled = ucl_object_toboolean(value);
			rule->tcp_auto = FALSE;
		}
		else if (ucl_object_type(value) == UCL_OBJECT) {
			/* Object with detailed TCP configuration */

			if ((tcp_obj = ucl_object_lookup(value, "enabled")) != NULL) {
				rule->tcp_enabled = ucl_object_toboolean(tcp_obj);
			}

			if ((tcp_obj = ucl_object_lookup(value, "auto")) != NULL) {
				rule->tcp_auto = ucl_object_toboolean(tcp_obj);
			}

			if ((tcp_obj = ucl_object_lookup(value, "threshold")) != NULL) {
				rule->tcp_threshold = ucl_object_todouble(tcp_obj);
			}
			else {
				rule->tcp_threshold = 1.0; /* Default: >1 req/sec */
			}

			if ((tcp_obj = ucl_object_lookup(value, "window")) != NULL) {
				rule->tcp_window = ucl_object_todouble(tcp_obj);
			}
			else {
				rule->tcp_window = 1.0; /* Default: 1 second window */
			}

			if ((tcp_obj = ucl_object_lookup(value, "timeout")) != NULL) {
				rule->tcp_timeout = ucl_object_todouble(tcp_obj);
			}
			else {
				rule->tcp_timeout = 5.0; /* Default: 5 seconds */
			}

			if ((tcp_obj = ucl_object_lookup(value, "retry_delay")) != NULL) {
				rule->tcp_retry_delay = ucl_object_todouble(tcp_obj);
			}
			else {
				rule->tcp_retry_delay = 10.0; /* Default: 10 seconds */
			}
		}
	}
	else {
		/* Default values if no TCP configuration */
		rule->tcp_enabled = FALSE;
		rule->tcp_auto = FALSE;
		rule->tcp_threshold = 1.0;
		rule->tcp_window = 1.0;
		rule->tcp_timeout = 5.0;
		rule->tcp_retry_delay = 10.0;
	}


	if (rule->tcp_enabled) {
		msg_debug_config("rule %s: TCP explicitly enabled (timeout=%.1fs)",
						 rule->name ? rule->name : "default", rule->tcp_timeout);
	}
	else if (rule->tcp_auto) {
		msg_debug_config("rule %s: TCP auto-switch enabled (threshold=%.2f req/s, window=%.1fs)",
						 rule->name ? rule->name : "default",
						 rule->tcp_threshold, rule->tcp_window);
	}
	else {
		msg_debug_config("rule %s: TCP disabled (using UDP only)",
						 rule->name ? rule->name : "default");
	}

	if ((value = ucl_object_lookup(obj, "algorithm")) != NULL) {
		rule->algorithm_str = ucl_object_tostring(value);

		if (rule->algorithm_str) {
			if (g_ascii_strcasecmp(rule->algorithm_str, "old") == 0 ||
				g_ascii_strcasecmp(rule->algorithm_str, "siphash") == 0) {
				rule->alg = RSPAMD_SHINGLES_OLD;
			}
			else if (g_ascii_strcasecmp(rule->algorithm_str, "xxhash") == 0) {
				rule->alg = RSPAMD_SHINGLES_XXHASH;
			}
			else if (g_ascii_strcasecmp(rule->algorithm_str, "mumhash") == 0) {
				rule->alg = RSPAMD_SHINGLES_MUMHASH;
			}
			else if (g_ascii_strcasecmp(rule->algorithm_str, "fasthash") == 0 ||
					 g_ascii_strcasecmp(rule->algorithm_str, "fast") == 0) {
				rule->alg = RSPAMD_SHINGLES_FAST;
			}
			else {
				msg_warn_config("unknown algorithm: %s, use siphash by default",
								rule->algorithm_str);
			}
		}
	}

	/* Set a consistent and short string name */
	switch (rule->alg) {
	case RSPAMD_SHINGLES_OLD:
		rule->algorithm_str = "sip";
		break;
	case RSPAMD_SHINGLES_XXHASH:
		rule->algorithm_str = "xx";
		break;
	case RSPAMD_SHINGLES_MUMHASH:
		rule->algorithm_str = "mum";
		break;
	case RSPAMD_SHINGLES_FAST:
		rule->algorithm_str = "fast";
		break;
	}

	if ((value = ucl_object_lookup(obj, "servers")) != NULL) {
		rule->read_servers = rspamd_upstreams_create(cfg->ups_ctx);
		rspamd_upstreams_set_limits(rule->read_servers,
									(double) fuzzy_module_ctx->revive_time, NAN, NAN, NAN,
									(unsigned int) fuzzy_module_ctx->max_errors, 0);

		rspamd_mempool_add_destructor(cfg->cfg_pool,
									  (rspamd_mempool_destruct_t) rspamd_upstreams_destroy,
									  rule->read_servers);
		if (!rspamd_upstreams_from_ucl(rule->read_servers, value, DEFAULT_PORT, NULL)) {
			msg_err_config("cannot read servers definition");
			return -1;
		}

		rule->write_servers = rule->read_servers;
	}
	else {
		/* Check for read_servers and write_servers */
		gboolean has_read = FALSE, has_write = FALSE;

		if ((value = ucl_object_lookup(obj, "read_servers")) != NULL) {
			rule->read_servers = rspamd_upstreams_create(cfg->ups_ctx);
			rspamd_upstreams_set_limits(rule->read_servers,
										(double) fuzzy_module_ctx->revive_time, NAN, NAN, NAN,
										(unsigned int) fuzzy_module_ctx->max_errors, 0);

			rspamd_mempool_add_destructor(cfg->cfg_pool,
										  (rspamd_mempool_destruct_t) rspamd_upstreams_destroy,
										  rule->read_servers);
			if (!rspamd_upstreams_from_ucl(rule->read_servers, value, DEFAULT_PORT, NULL)) {
				msg_err_config("cannot read read_servers definition");
				return -1;
			}
			has_read = TRUE;
		}

		if ((value = ucl_object_lookup(obj, "write_servers")) != NULL) {
			rule->write_servers = rspamd_upstreams_create(cfg->ups_ctx);
			rspamd_upstreams_set_limits(rule->write_servers,
										(double) fuzzy_module_ctx->revive_time, NAN, NAN, NAN,
										(unsigned int) fuzzy_module_ctx->max_errors, 0);

			rspamd_mempool_add_destructor(cfg->cfg_pool,
										  (rspamd_mempool_destruct_t) rspamd_upstreams_destroy,
										  rule->write_servers);
			if (!rspamd_upstreams_from_ucl(rule->write_servers, value, DEFAULT_PORT, NULL)) {
				msg_err_config("cannot read write_servers definition");
				return -1;
			}
			has_write = TRUE;
		}

		/* If we have both read and write servers, we don't need the common servers list */
		if (has_read && !has_write) {
			/* Use read_servers for all operations */
			rule->write_servers = rule->read_servers;
		}
		else if (has_write && !has_read) {
			/* Use write_servers for all operations */
			rule->read_servers = rule->write_servers;
		}
	}

	if ((value = ucl_object_lookup(obj, "fuzzy_map")) != NULL) {
		it = NULL;
		while ((cur = ucl_object_iterate(value, &it, true)) != NULL) {
			parse_flags(rule, cfg, cur, cb_id);
		}
	}

	if ((value = ucl_object_lookup(obj, "encryption_key")) != NULL) {
		/* Create key from user's input */
		k = ucl_object_tostring(value);

		if (k == NULL || (rule->peer_key =
							  rspamd_pubkey_from_base32(k, 0, RSPAMD_KEYPAIR_KEX)) == NULL) {
			msg_err_config("bad encryption key value: %s",
						   k);
			return -1;
		}

		rule->local_key = rspamd_keypair_new(RSPAMD_KEYPAIR_KEX);
	}

	/* Check for separate read and write encryption keys */
	if ((value = ucl_object_lookup(obj, "read_encryption_key")) != NULL) {
		k = ucl_object_tostring(value);

		if (k == NULL || (rule->read_peer_key =
							  rspamd_pubkey_from_base32(k, 0, RSPAMD_KEYPAIR_KEX)) == NULL) {
			msg_err_config("bad read_encryption_key value: %s",
						   k);
			return -1;
		}

		rule->read_local_key = rspamd_keypair_new(RSPAMD_KEYPAIR_KEX);
		msg_debug_config("using separate read encryption key for rule %s", name);
	}
	else if (rule->peer_key) {
		/* Use common encryption key for read operations */
		rule->read_peer_key = rspamd_pubkey_ref(rule->peer_key);
		rule->read_local_key = rspamd_keypair_ref(rule->local_key);
	}

	if ((value = ucl_object_lookup(obj, "write_encryption_key")) != NULL) {
		k = ucl_object_tostring(value);

		if (k == NULL || (rule->write_peer_key =
							  rspamd_pubkey_from_base32(k, 0, RSPAMD_KEYPAIR_KEX)) == NULL) {
			msg_err_config("bad write_encryption_key value: %s",
						   k);
			return -1;
		}

		rule->write_local_key = rspamd_keypair_new(RSPAMD_KEYPAIR_KEX);
		msg_debug_config("using separate write encryption key for rule %s", name);
	}
	else if (rule->peer_key) {
		/* Use common encryption key for write operations */
		rule->write_peer_key = rspamd_pubkey_ref(rule->peer_key);
		rule->write_local_key = rspamd_keypair_ref(rule->local_key);
	}

	/* Fallback: if only one specific key is set, use it for both operations */
	if (!rule->read_peer_key && rule->write_peer_key) {
		/* No read key, but write key exists - use write key for read */
		rule->read_peer_key = rspamd_pubkey_ref(rule->write_peer_key);
		rule->read_local_key = rspamd_keypair_ref(rule->write_local_key);
		msg_debug_config("using write encryption key for read operations in rule %s", name);
	}
	if (!rule->write_peer_key && rule->read_peer_key) {
		/* No write key, but read key exists - use read key for write */
		rule->write_peer_key = rspamd_pubkey_ref(rule->read_peer_key);
		rule->write_local_key = rspamd_keypair_ref(rule->read_local_key);
		msg_debug_config("using read encryption key for write operations in rule %s", name);
	}

	if ((value = ucl_object_lookup(obj, "learn_condition")) != NULL) {
		lua_script = ucl_object_tostring(value);

		if (lua_script) {
			if (luaL_dostring(cfg->lua_state, lua_script) != 0) {
				msg_err_config("cannot execute lua script for fuzzy "
							   "learn condition: %s",
							   lua_tostring(cfg->lua_state, -1));
			}
			else {
				if (lua_type(cfg->lua_state, -1) == LUA_TFUNCTION) {
					rule->learn_condition_cb = luaL_ref(cfg->lua_state,
														LUA_REGISTRYINDEX);
					msg_info_config("loaded learn condition script for fuzzy rule:"
									" %s",
									rule->name);
				}
				else {
					msg_err_config("lua script must return "
								   "function(task) and not %s",
								   lua_typename(cfg->lua_state,
												lua_type(cfg->lua_state, -1)));
				}
			}
		}
	}

	key_str = NULL;
	if ((value = ucl_object_lookup(obj, "fuzzy_key")) != NULL) {
		/* Create key from user's input */
		key_str = ucl_object_tostring(value);
	}

	/* Setup keys */
	if (key_str == NULL) {
		/* Use some default key for all ops */
		key_str = "rspamd";
	}

	rule->hash_key = g_string_sized_new(rspamd_cryptobox_HASHBYTES);
	rspamd_cryptobox_hash(rule->hash_key->str, key_str, strlen(key_str), NULL, 0);
	rule->hash_key->len = rspamd_cryptobox_HASHKEYBYTES;

	shingles_key_str = NULL;
	if ((value = ucl_object_lookup(obj, "fuzzy_shingles_key")) != NULL) {
		shingles_key_str = ucl_object_tostring(value);
	}
	if (shingles_key_str == NULL) {
		shingles_key_str = "rspamd";
	}

	rule->shingles_key = g_string_sized_new(rspamd_cryptobox_HASHBYTES);
	rspamd_cryptobox_hash(rule->shingles_key->str, shingles_key_str,
						  strlen(shingles_key_str), NULL, 0);
	rule->shingles_key->len = 16;

	if (rspamd_upstreams_count(rule->read_servers) == 0) {
		msg_err_config("no servers defined for fuzzy rule with name: %s",
					   rule->name);
		return -1;
	}
	else {
		g_ptr_array_add(fuzzy_module_ctx->fuzzy_rules, rule);

		if (rule->symbol != fuzzy_module_ctx->default_symbol) {
			int vid = rspamd_symcache_add_symbol(cfg->cache, rule->symbol,
												 0,
												 NULL, NULL,
												 SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
												 cb_id);

			if (rule->io_timeout > 0) {
				char timeout_buf[32];
				rspamd_snprintf(timeout_buf, sizeof(timeout_buf), "%f",
								rule->io_timeout);
				rspamd_symcache_add_symbol_augmentation(cfg->cache,
														vid, "timeout",
														timeout_buf);
			}
		}

		msg_info_config("added fuzzy rule %s, key: %*xs, "
						"shingles_key: %*xs, algorithm: %s",
						rule->symbol,
						6, rule->hash_key->str,
						6, rule->shingles_key->str,
						rule->algorithm_str);
	}

	if ((value = ucl_object_lookup(obj, "weight_threshold")) != NULL) {
		rule->weight_threshold = ucl_object_todouble(value);
	}

	if ((value = ucl_object_lookup(obj, "text_hashes")) != NULL) {
		rule->text_hashes = ucl_obj_toboolean(value);
	}

	if ((value = ucl_object_lookup(obj, "html_shingles")) != NULL) {
		rule->html_shingles = ucl_object_toboolean(value);
	}

	if ((value = ucl_object_lookup(obj, "min_html_tags")) != NULL) {
		rule->min_html_tags = ucl_object_toint(value);
	}

	if ((value = ucl_object_lookup(obj, "html_weight")) != NULL) {
		rule->html_weight = ucl_object_todouble(value);
	}

	if ((value = ucl_object_lookup(obj, "checks")) != NULL) {
		fuzzy_rule_apply_checks(rule, cfg, value);
	}

	/* Initialize rate tracker */
	rule->rate_tracker.requests_count = 0;
	rule->rate_tracker.window_start = 0;
	rule->rate_tracker.last_was_tcp = FALSE;

	/* Initialize TCP connection pool - array of connections with proper free function */
	rule->tcp_connections = g_ptr_array_new_with_free_func(fuzzy_tcp_connection_unref);

	/* Initialize global pending requests pool - keyed by tag */
	rule->pending_requests = kh_init(fuzzy_pending_hash);

	/*
	 * Process rule in Lua
	 */
	int err_idx, ret;
	lua_State *L = (lua_State *) cfg->lua_state;

	lua_pushcfunction(L, &rspamd_lua_traceback);
	err_idx = lua_gettop(L);
	lua_rawgeti(L, LUA_REGISTRYINDEX, fuzzy_module_ctx->process_rule_ref);
	ucl_object_push_lua(L, obj, true);

	if ((ret = lua_pcall(L, 1, 1, err_idx)) != 0) {
		msg_err_config("call to process_rule lua "
					   "script failed (%d): %s",
					   ret, lua_tostring(L, -1));

		rule->lua_id = -1;
	}
	else {
		rule->lua_id = lua_tonumber(L, -1);
	}

	lua_settop(L, err_idx - 1);

	rspamd_mempool_add_destructor(cfg->cfg_pool, fuzzy_free_rule,
								  rule);

	return 0;
}

int fuzzy_check_module_init(struct rspamd_config *cfg, struct module_ctx **ctx)
{
	struct fuzzy_ctx *fuzzy_module_ctx;

	fuzzy_module_ctx = rspamd_mempool_alloc0(cfg->cfg_pool,
											 sizeof(struct fuzzy_ctx));

	fuzzy_module_ctx->fuzzy_pool = rspamd_mempool_new_long_lived(rspamd_mempool_suggest_size(),
																 "fuzzy");
	/* TODO: this should match rules count actually */
	fuzzy_module_ctx->keypairs_cache = rspamd_keypair_cache_new(32);
	fuzzy_module_ctx->fuzzy_rules = g_ptr_array_new();
	fuzzy_module_ctx->cfg = cfg;
	fuzzy_module_ctx->process_rule_ref = -1;
	fuzzy_module_ctx->check_mime_part_ref = -1;
	fuzzy_module_ctx->cleanup_rules_ref = -1;

	rspamd_mempool_add_destructor(cfg->cfg_pool,
								  (rspamd_mempool_destruct_t) rspamd_mempool_delete,
								  fuzzy_module_ctx->fuzzy_pool);
	rspamd_mempool_add_destructor(cfg->cfg_pool,
								  (rspamd_mempool_destruct_t) rspamd_keypair_cache_destroy,
								  fuzzy_module_ctx->keypairs_cache);
	rspamd_mempool_add_destructor(cfg->cfg_pool,
								  (rspamd_mempool_destruct_t) rspamd_ptr_array_free_hard,
								  fuzzy_module_ctx->fuzzy_rules);

	*ctx = (struct module_ctx *) fuzzy_module_ctx;

	rspamd_rcl_add_doc_by_path(cfg,
							   NULL,
							   "Fuzzy check plugin",
							   "fuzzy_check",
							   UCL_OBJECT,
							   NULL,
							   0,
							   NULL,
							   0);

	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Default symbol",
							   "symbol",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Minimum number of *words* to check a text part",
							   "min_length",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Minimum number of *bytes* to check a non-text part",
							   "min_bytes",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Multiplier for bytes limit when checking for text parts",
							   "text_multiplier",
							   UCL_FLOAT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Minimum height in pixels for embedded images to check using fuzzy storage",
							   "min_height",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Minimum width in pixels for embedded images to check using fuzzy storage",
							   "min_width",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Timeout for waiting reply from a fuzzy server",
							   "timeout",
							   UCL_TIME,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Maximum number of retransmits for a single request",
							   "retransmits",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Maximum number of upstream errors, affects error rate threshold",
							   "max_errors",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Time to lapse before re-resolve faulty upstream",
							   "revive_time",
							   UCL_FLOAT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Whitelisted IPs map",
							   "whitelist",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	/* Rules doc strings */
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check",
							   "Fuzzy check rule",
							   "rule",
							   UCL_OBJECT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Headers that are used to make a separate hash",
							   "headers",
							   UCL_ARRAY,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Whitelisted hashes map",
							   "skip_hashes",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Set of mime types (in form type/subtype, or type/*, or *) to check with fuzzy",
							   "mime_types",
							   UCL_ARRAY,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Number of fuzzy hash hits at which the normalized score reaches ~1.0. "
							   "Score is calculated as tanh(e * hits / hits_limit). "
							   "Legacy name: max_score",
							   "hits_limit",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "List of servers to check (or learn)",
							   "servers",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "List of servers to check (read-only operations)",
							   "read_servers",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "List of servers to learn (write operations)",
							   "write_servers",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "If true then never try to learn this fuzzy storage",
							   "read_only",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "If true then ignore unknown flags and not add the default fuzzy symbol",
							   "skip_unknown",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Default symbol for rule (if no flags defined or matched)",
							   "symbol",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Base32 value for the protocol encryption public key",
							   "encryption_key",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Base32 value for the protocol encryption public key for read operations",
							   "read_encryption_key",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Base32 value for the protocol encryption public key for write operations",
							   "write_encryption_key",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Base32 value for the hashing key (for private storages)",
							   "fuzzy_key",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Base32 value for the shingles hashing key (for private storages)",
							   "fuzzy_shingles_key",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Lua script that returns boolean function to check if this task "
							   "should be considered when learning fuzzy storage",
							   "learn_condition",
							   UCL_STRING,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Map of SYMBOL -> data for flags configuration",
							   "fuzzy_map",
							   UCL_OBJECT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Use direct hash for short texts",
							   "short_text_direct_hash",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "true",
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Enable hashing of text content (set to false to disable text hashes)",
							   "text_hashes",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "true",
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Enable HTML structure hashing for this rule",
							   "html_shingles",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "false",
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Minimum number of HTML tags required to generate HTML hashes",
							   "min_html_tags",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Multiplier applied to HTML fuzzy matches",
							   "html_weight",
							   UCL_FLOAT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Ignore link domains in HTML structural tokens (for template-only matching)",
							   "html_ignore_domains",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "false",
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Content hashing checks configuration object (e.g. { text = { enabled = true; }, html = { enabled = true; } })",
							   "checks",
							   UCL_OBJECT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Override module default min bytes for this rule",
							   "min_bytes",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	/* Fuzzy map doc strings */
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule.fuzzy_map",
							   "Number of fuzzy hash hits at which the normalized score reaches ~1.0 for this flag. "
							   "Legacy name: max_score",
							   "hits_limit",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule.fuzzy_map",
							   "Flag number",
							   "flag",
							   UCL_INT,
							   NULL,
							   0,
							   NULL,
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Do no use subject to distinguish short text hashes",
							   "no_subject",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "false",
							   0);
	rspamd_rcl_add_doc_by_path(cfg,
							   "fuzzy_check.rule",
							   "Disable sharing message stats with the fuzzy server",
							   "no_share",
							   UCL_BOOLEAN,
							   NULL,
							   0,
							   "false",
							   0);

	return 0;
}

int fuzzy_check_module_config(struct rspamd_config *cfg, bool validate)
{
	const ucl_object_t *value, *cur, *elt;
	ucl_object_iter_t it;
	int res = TRUE, cb_id, nrules = 0;
	lua_State *L = cfg->lua_state;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(cfg);

	if (!rspamd_config_is_module_enabled(cfg, "fuzzy_check")) {
		return TRUE;
	}

	fuzzy_module_ctx->enabled = TRUE;
	fuzzy_module_ctx->check_mime_part_ref = -1;
	fuzzy_module_ctx->process_rule_ref = -1;
	fuzzy_module_ctx->cleanup_rules_ref = -1;

	/* Interact with lua_fuzzy */
	int lua_fuzzy_top = lua_gettop(L);
	if (luaL_dostring(L, "return require \"lua_fuzzy\"") != 0) {
		msg_err_config("cannot require lua_fuzzy: %s",
					   lua_tostring(L, -1));
		fuzzy_module_ctx->enabled = FALSE;
	}
	else {
		/* Lua 5.4's require returns 2 values (module + path), keep only first */
		lua_settop(L, lua_fuzzy_top + 1);
		if (lua_type(L, -1) != LUA_TTABLE) {
			msg_err_config("lua fuzzy must return "
						   "table and not %s",
						   lua_typename(L, lua_type(L, -1)));
			fuzzy_module_ctx->enabled = FALSE;
		}
		else {
			lua_pushstring(L, "process_rule");
			lua_gettable(L, -2);

			if (lua_type(L, -1) != LUA_TFUNCTION) {
				msg_err_config("process_rule must return "
							   "function and not %s",
							   lua_typename(L, lua_type(L, -1)));
				fuzzy_module_ctx->enabled = FALSE;
			}
			else {
				fuzzy_module_ctx->process_rule_ref = luaL_ref(L, LUA_REGISTRYINDEX);
			}

			lua_pushstring(L, "check_mime_part");
			lua_gettable(L, -2);

			if (lua_type(L, -1) != LUA_TFUNCTION) {
				msg_err_config("check_mime_part must return "
							   "function and not %s",
							   lua_typename(L, lua_type(L, -1)));
				fuzzy_module_ctx->enabled = FALSE;
			}
			else {
				fuzzy_module_ctx->check_mime_part_ref = luaL_ref(L, LUA_REGISTRYINDEX);
			}

			lua_pushstring(L, "cleanup_rules");
			lua_gettable(L, -2);

			if (lua_type(L, -1) != LUA_TFUNCTION) {
				msg_err_config("cleanup_rules must return "
							   "function and not %s",
							   lua_typename(L, lua_type(L, -1)));
				fuzzy_module_ctx->enabled = FALSE;
			}
			else {
				fuzzy_module_ctx->cleanup_rules_ref = luaL_ref(L, LUA_REGISTRYINDEX);
			}
		}
	}

	lua_settop(L, 0);

	if (!fuzzy_module_ctx->enabled) {
		return TRUE;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check", "symbol")) != NULL) {
		fuzzy_module_ctx->default_symbol = ucl_obj_tostring(value);
	}
	else {
		fuzzy_module_ctx->default_symbol = DEFAULT_SYMBOL;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check", "timeout")) != NULL) {
		fuzzy_module_ctx->io_timeout = ucl_obj_todouble(value);
	}
	else {
		fuzzy_module_ctx->io_timeout = DEFAULT_IO_TIMEOUT;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg,
										  "fuzzy_check",
										  "retransmits")) != NULL) {
		fuzzy_module_ctx->retransmits = ucl_obj_toint(value);
	}
	else {
		fuzzy_module_ctx->retransmits = DEFAULT_RETRANSMITS;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check",
										  "max_errors")) != NULL) {
		fuzzy_module_ctx->max_errors = ucl_obj_toint(value);
	}
	else {
		fuzzy_module_ctx->max_errors = DEFAULT_MAX_ERRORS;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check",
										  "revive_time")) != NULL) {
		fuzzy_module_ctx->revive_time = ucl_obj_todouble(value);
	}
	else {
		fuzzy_module_ctx->revive_time = DEFAULT_REVIVE_TIME;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check",
										  "whitelist")) != NULL) {
		rspamd_config_radix_from_ucl(cfg, value, "Fuzzy whitelist",
									 &fuzzy_module_ctx->whitelist,
									 NULL,
									 NULL, "fuzzy ip whitelist");
	}
	else {
		fuzzy_module_ctx->whitelist = NULL;
	}

	if ((value =
			 rspamd_config_get_module_opt(cfg, "fuzzy_check", "rule")) != NULL) {

		cb_id = rspamd_symcache_add_symbol(cfg->cache,
										   "FUZZY_CALLBACK", 0, fuzzy_symbol_callback, NULL,
										   SYMBOL_TYPE_CALLBACK | SYMBOL_TYPE_FINE,
										   -1);
		rspamd_config_add_symbol(cfg,
								 "FUZZY_CALLBACK",
								 0.0,
								 "Fuzzy check callback",
								 "fuzzy",
								 RSPAMD_SYMBOL_FLAG_IGNORE_METRIC,
								 1,
								 1);

		/* Register meta symbols (blocked, ratelimited, etc) */
		rspamd_symcache_add_symbol(cfg->cache,
								   RSPAMD_FUZZY_SYMBOL_FORBIDDEN, 0, NULL, NULL,
								   SYMBOL_TYPE_VIRTUAL,
								   cb_id);
		rspamd_config_add_symbol(cfg,
								 RSPAMD_FUZZY_SYMBOL_FORBIDDEN,
								 0.0,
								 "Fuzzy access denied",
								 "fuzzy",
								 0,
								 1,
								 1);
		rspamd_symcache_add_symbol(cfg->cache,
								   RSPAMD_FUZZY_SYMBOL_RATELIMITED, 0, NULL, NULL,
								   SYMBOL_TYPE_VIRTUAL,
								   cb_id);
		rspamd_config_add_symbol(cfg,
								 RSPAMD_FUZZY_SYMBOL_RATELIMITED,
								 0.0,
								 "Fuzzy rate limit is reached",
								 "fuzzy",
								 0,
								 1,
								 1);
		rspamd_symcache_add_symbol(cfg->cache,
								   RSPAMD_FUZZY_SYMBOL_ENCRYPTION_REQUIRED, 0, NULL, NULL,
								   SYMBOL_TYPE_VIRTUAL,
								   cb_id);
		rspamd_config_add_symbol(cfg,
								 RSPAMD_FUZZY_SYMBOL_ENCRYPTION_REQUIRED,
								 0.0,
								 "Fuzzy encryption is required by a server",
								 "fuzzy",
								 0,
								 1,
								 1);

		/*
		 * Here we can have 2 possibilities:
		 *
		 * unnamed rules:
		 *
		 * rule {
		 * ...
		 * }
		 * rule {
		 * ...
		 * }
		 *
		 * - or - named rules:
		 *
		 * rule {
		 * 	"rule1": {
		 * 	...
		 * 	}
		 * 	"rule2": {
		 * 	...
		 * 	}
		 * }
		 *
		 * So, for each element, we check, if there 'servers' key. If 'servers' is
		 * presented, then we treat it as unnamed rule, otherwise we treat it as
		 * named rule.
		 */
		LL_FOREACH(value, cur)
		{

			if (ucl_object_lookup_any(cur, "servers", "read_servers", "write_servers", NULL) != NULL) {
				/* Unnamed rule */
				fuzzy_parse_rule(cfg, cur, NULL, cb_id);
				nrules++;
			}
			else {
				/* Named rule */
				it = NULL;

				while ((elt = ucl_object_iterate(cur, &it, true)) != NULL) {
					fuzzy_parse_rule(cfg, elt, ucl_object_key(elt), cb_id);
					nrules++;
				}
			}
		}

		/* We want that to check bad mime attachments */
		rspamd_symcache_add_delayed_dependency(cfg->cache,
											   "FUZZY_CALLBACK", "MIME_TYPES_CALLBACK", FALSE);
	}

	if (fuzzy_module_ctx->fuzzy_rules == NULL) {
		msg_warn_config("fuzzy module is enabled but no rules are defined");
	}

	msg_info_config("init internal fuzzy_check module, %d rules loaded",
					nrules);

	/* Register global methods */
	lua_getglobal(L, "rspamd_plugins");

	if (lua_type(L, -1) == LUA_TTABLE) {
		lua_pushstring(L, "fuzzy_check");
		lua_createtable(L, 0, 3);
		/* Set methods */
		lua_pushstring(L, "unlearn");
		lua_pushcfunction(L, fuzzy_lua_unlearn_handler);
		lua_settable(L, -3);
		lua_pushstring(L, "learn");
		lua_pushcfunction(L, fuzzy_lua_learn_handler);
		lua_settable(L, -3);
		lua_pushstring(L, "gen_hashes");
		lua_pushcfunction(L, fuzzy_lua_gen_hashes_handler);
		lua_settable(L, -3);
		lua_pushstring(L, "hex_hashes");
		lua_pushcfunction(L, fuzzy_lua_hex_hashes_handler);
		lua_settable(L, -3);
		lua_pushstring(L, "list_storages");
		lua_pushcfunction(L, fuzzy_lua_list_storages);
		lua_settable(L, -3);
		lua_pushstring(L, "ping_storage");
		lua_pushcfunction(L, fuzzy_lua_ping_storage);
		lua_settable(L, -3);
		/* Finish fuzzy_check key */
		lua_settable(L, -3);
	}

	lua_settop(L, 0);

	return res;
}

int fuzzy_check_module_reconfig(struct rspamd_config *cfg)
{
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(cfg);

	if (fuzzy_module_ctx->cleanup_rules_ref != -1) {
		/* Sync lua_fuzzy rules */
		int err_idx, ret;
		lua_State *L = (lua_State *) cfg->lua_state;

		lua_pushcfunction(L, &rspamd_lua_traceback);
		err_idx = lua_gettop(L);
		lua_rawgeti(L, LUA_REGISTRYINDEX, fuzzy_module_ctx->cleanup_rules_ref);

		if ((ret = lua_pcall(L, 0, 0, err_idx)) != 0) {
			msg_err_config("call to cleanup_rules lua "
						   "script failed (%d): %s",
						   ret, lua_tostring(L, -1));
		}

		luaL_unref(cfg->lua_state, LUA_REGISTRYINDEX,
				   fuzzy_module_ctx->cleanup_rules_ref);
		lua_settop(L, 0);
	}

	if (fuzzy_module_ctx->check_mime_part_ref != -1) {
		luaL_unref(cfg->lua_state, LUA_REGISTRYINDEX,
				   fuzzy_module_ctx->check_mime_part_ref);
	}

	if (fuzzy_module_ctx->process_rule_ref != -1) {
		luaL_unref(cfg->lua_state, LUA_REGISTRYINDEX,
				   fuzzy_module_ctx->process_rule_ref);
	}

	return fuzzy_check_module_config(cfg, false);
}

/**
 * Cleanup pending TCP requests for a session
 * Called when session finishes (task completes or times out)
 */
static void
fuzzy_tcp_session_cleanup(struct fuzzy_client_session *session)
{
	khash_t(fuzzy_pending_hash) * pending_ht;
	struct fuzzy_tcp_pending_command *pending;
	unsigned int removed = 0;
	struct rspamd_task *task = session->task;

	if (!session || !session->rule || !(pending_ht = session->rule->pending_requests)) {
		return;
	}

	for (khiter_t k = kh_begin(pending_ht); k != kh_end(pending_ht); ++k) {
		if (!kh_exist(pending_ht, k)) {
			continue;
		}

		pending = kh_val(pending_ht, k);

		if (pending->session == session) {
			if (!(pending->io->flags & FUZZY_CMD_FLAG_REPLIED)) {
				pending->io->flags |= FUZZY_CMD_FLAG_REPLIED;
			}

			g_free(pending);
			kh_del(fuzzy_pending_hash, pending_ht, k);
			removed++;
		}
	}

	if (removed > 0 && session->task) {
		msg_debug_fuzzy_check("fuzzy_tcp: cleaned up %ud pending commands for finished session",
							  removed);
	}
}

/* Finalize IO */
static void
fuzzy_io_fin(void *ud)
{
	struct fuzzy_client_session *session = ud;

	/* Remove any pending TCP requests for this session */
	if (session->fd == -1) {
		/* TCP session - cleanup pending requests and stop timer */
		fuzzy_tcp_session_cleanup(session);
		/* Stop timer */
		if (ev_is_active(&session->timer_ev)) {
			ev_timer_stop(session->event_loop, &session->timer_ev);
		}
	}

	if (session->commands) {
		g_ptr_array_free(session->commands, TRUE);
		session->commands = NULL;
	}

	if (session->results) {
		g_ptr_array_free(session->results, TRUE);
		session->results = NULL;
	}

	/* Only cleanup fd and ev_watcher for UDP sessions */
	if (session->fd != -1) {
		rspamd_ev_watcher_stop(session->event_loop, &session->ev);
		close(session->fd);
	}
	/* TCP sessions use shared connection, no cleanup needed here */
}

static rspamd_words_t *
fuzzy_preprocess_words(struct rspamd_mime_text_part *part, rspamd_mempool_t *pool)
{
	return &part->utf_words;
}

static inline gboolean
fuzzy_rule_has_encryption(struct fuzzy_rule *rule)
{
	return (rule->peer_key || rule->read_peer_key || rule->write_peer_key);
}

static inline void
fuzzy_select_encryption_keys(struct fuzzy_rule *rule,
							 int cmd,
							 struct rspamd_cryptobox_keypair **local_key,
							 struct rspamd_cryptobox_pubkey **peer_key)
{
	if (cmd == FUZZY_DEL || cmd == FUZZY_WRITE) {
		/* Write operation */
		*local_key = rule->write_local_key ? rule->write_local_key : rule->local_key;
		*peer_key = rule->write_peer_key ? rule->write_peer_key : rule->peer_key;
	}
	else {
		/* Read operation (CHECK, STAT, PING, etc.) */
		*local_key = rule->read_local_key ? rule->read_local_key : rule->local_key;
		*peer_key = rule->read_peer_key ? rule->read_peer_key : rule->peer_key;
	}
}

static void
fuzzy_encrypt_cmd(struct fuzzy_rule *rule,
				  struct rspamd_fuzzy_encrypted_req_hdr *hdr,
				  unsigned char *data, gsize datalen,
				  struct rspamd_cryptobox_keypair *local_key,
				  struct rspamd_cryptobox_pubkey *peer_key)
{
	const unsigned char *pk;
	unsigned int pklen;

	g_assert(hdr != NULL);
	g_assert(data != NULL);
	g_assert(rule != NULL);
	g_assert(local_key != NULL);
	g_assert(peer_key != NULL);

	/* Encrypt data */
	memcpy(hdr->magic,
		   fuzzy_encrypted_magic,
		   sizeof(hdr->magic));
	ottery_rand_bytes(hdr->nonce, sizeof(hdr->nonce));
	pk = rspamd_keypair_component(local_key,
								  RSPAMD_KEYPAIR_COMPONENT_PK, &pklen);
	memcpy(hdr->pubkey, pk, MIN(pklen, sizeof(hdr->pubkey)));
	pk = rspamd_pubkey_get_pk(peer_key, &pklen);
	memcpy(hdr->key_id, pk, MIN(sizeof(hdr->key_id), pklen));
	rspamd_keypair_cache_process(rule->ctx->keypairs_cache,
								 local_key, peer_key);
	rspamd_cryptobox_encrypt_nm_inplace(data, datalen,
										hdr->nonce, rspamd_pubkey_get_nm(peer_key, local_key),
										hdr->mac);
}

static struct fuzzy_cmd_io *
fuzzy_cmd_stat(struct fuzzy_rule *rule,
			   int c,
			   int flag,
			   uint32_t weight,
			   rspamd_mempool_t *pool)
{
	struct rspamd_fuzzy_cmd *cmd;
	struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
	struct fuzzy_cmd_io *io;

	if (fuzzy_rule_has_encryption(rule)) {
		enccmd = rspamd_mempool_alloc0(pool, sizeof(*enccmd));
		cmd = &enccmd->cmd;
	}
	else {
		cmd = rspamd_mempool_alloc0(pool, sizeof(*cmd));
	}

	cmd->cmd = c;
	cmd->version = fuzzy_cmd_version(rule);
	cmd->shingles_count = 0;
	cmd->tag = ottery_rand_uint32();

	io = rspamd_mempool_alloc(pool, sizeof(*io));
	io->flags = 0;
	io->tag = cmd->tag;
	memcpy(&io->cmd, cmd, sizeof(io->cmd));

	if (fuzzy_rule_has_encryption(rule) && enccmd) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, c, &local_key, &peer_key);
		fuzzy_encrypt_cmd(rule, &enccmd->hdr, (unsigned char *) cmd, sizeof(*cmd),
						  local_key, peer_key);
		io->io.iov_base = enccmd;
		io->io.iov_len = sizeof(*enccmd);
	}
	else {
		io->io.iov_base = cmd;
		io->io.iov_len = sizeof(*cmd);
	}

	return io;
}

static inline double
fuzzy_milliseconds_since_midnight(void)
{
	double now = rspamd_get_calendar_ticks();
	double ms = now - (int64_t) now;
	now = (((int64_t) now % 86400) + ms) * 1000;

	return now;
}

static struct fuzzy_cmd_io *
fuzzy_cmd_ping(struct fuzzy_rule *rule,
			   rspamd_mempool_t *pool)
{
	struct rspamd_fuzzy_cmd *cmd;
	struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
	struct fuzzy_cmd_io *io;

	if (fuzzy_rule_has_encryption(rule)) {
		enccmd = rspamd_mempool_alloc0(pool, sizeof(*enccmd));
		cmd = &enccmd->cmd;
	}
	else {
		cmd = rspamd_mempool_alloc0(pool, sizeof(*cmd));
	}

	/* Get milliseconds since midnight */


	cmd->cmd = FUZZY_PING;
	cmd->version = fuzzy_cmd_version(rule);
	cmd->shingles_count = 0;
	cmd->value = fuzzy_milliseconds_since_midnight(); /* Record timestamp */
	cmd->tag = ottery_rand_uint32();

	io = rspamd_mempool_alloc(pool, sizeof(*io));
	io->flags = 0;
	io->tag = cmd->tag;
	memcpy(&io->cmd, cmd, sizeof(io->cmd));

	if (fuzzy_rule_has_encryption(rule) && enccmd) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, cmd->cmd, &local_key, &peer_key);
		fuzzy_encrypt_cmd(rule, &enccmd->hdr, (unsigned char *) cmd, sizeof(*cmd),
						  local_key, peer_key);
		io->io.iov_base = enccmd;
		io->io.iov_len = sizeof(*enccmd);
	}
	else {
		io->io.iov_base = cmd;
		io->io.iov_len = sizeof(*cmd);
	}

	return io;
}

static struct fuzzy_cmd_io *
fuzzy_cmd_hash(struct fuzzy_rule *rule,
			   int c,
			   const rspamd_ftok_t *hash,
			   int flag,
			   uint32_t weight,
			   rspamd_mempool_t *pool)
{
	struct rspamd_fuzzy_cmd *cmd;
	struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
	struct fuzzy_cmd_io *io;

	if (fuzzy_rule_has_encryption(rule)) {
		enccmd = rspamd_mempool_alloc0(pool, sizeof(*enccmd));
		cmd = &enccmd->cmd;
	}
	else {
		cmd = rspamd_mempool_alloc0(pool, sizeof(*cmd));
	}

	if (hash->len == sizeof(cmd->digest) * 2) {
		/* It is hex encoding */
		if (rspamd_decode_hex_buf(hash->begin, hash->len, cmd->digest,
								  sizeof(cmd->digest)) == -1) {
			msg_err_pool("cannot decode hash, wrong encoding");
			return NULL;
		}
	}
	else {
		msg_err_pool("cannot decode hash, wrong length: %z", hash->len);
		return NULL;
	}

	cmd->cmd = c;
	cmd->version = fuzzy_cmd_version(rule);
	cmd->shingles_count = 0;
	cmd->tag = ottery_rand_uint32();

	io = rspamd_mempool_alloc(pool, sizeof(*io));
	io->flags = 0;
	io->tag = cmd->tag;

	memcpy(&io->cmd, cmd, sizeof(io->cmd));

	if (fuzzy_rule_has_encryption(rule) && enccmd) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, c, &local_key, &peer_key);
		fuzzy_encrypt_cmd(rule, &enccmd->hdr, (unsigned char *) cmd, sizeof(*cmd),
						  local_key, peer_key);
		io->io.iov_base = enccmd;
		io->io.iov_len = sizeof(*enccmd);
	}
	else {
		io->io.iov_base = cmd;
		io->io.iov_len = sizeof(*cmd);
	}

	return io;
}

struct rspamd_cached_shingles {
	struct rspamd_shingle *sh;
	unsigned char digest[rspamd_cryptobox_HASHBYTES];
	unsigned int additional_length;
	unsigned char *additional_data;
};


static struct rspamd_cached_shingles *
fuzzy_cmd_get_cached(struct fuzzy_rule *rule,
					 struct rspamd_task *task,
					 struct rspamd_mime_part *mp)
{
	char key[32];
	int key_part;
	struct rspamd_cached_shingles **cached;

	memcpy(&key_part, rule->shingles_key->str, sizeof(key_part));
	rspamd_snprintf(key, sizeof(key), "%s%d", rule->algorithm_str,
					key_part);

	cached = (struct rspamd_cached_shingles **) rspamd_mempool_get_variable(
		task->task_pool, key);

	if (cached && cached[mp->part_number]) {
		return cached[mp->part_number];
	}

	return NULL;
}

static void
fuzzy_cmd_set_cached(struct fuzzy_rule *rule,
					 struct rspamd_task *task,
					 struct rspamd_mime_part *mp,
					 struct rspamd_cached_shingles *data)
{
	char key[32];
	int key_part;
	struct rspamd_cached_shingles **cached;

	memcpy(&key_part, rule->shingles_key->str, sizeof(key_part));
	rspamd_snprintf(key, sizeof(key), "%s%d", rule->algorithm_str,
					key_part);

	cached = (struct rspamd_cached_shingles **) rspamd_mempool_get_variable(
		task->task_pool, key);

	if (cached) {
		cached[mp->part_number] = data;
	}
	else {
		cached = rspamd_mempool_alloc0(task->task_pool, sizeof(*cached) *
															(MESSAGE_FIELD(task, parts)->len + 1));
		cached[mp->part_number] = data;

		rspamd_mempool_set_variable(task->task_pool, key, cached, NULL);
	}
}

static gboolean
fuzzy_rule_check_mimepart(struct rspamd_task *task,
						  struct fuzzy_rule *rule,
						  struct rspamd_mime_part *part,
						  gboolean *need_check,
						  gboolean *fuzzy_check)
{
	lua_State *L = (lua_State *) task->cfg->lua_state;

	int old_top = lua_gettop(L);

	if (rule->lua_id != -1 && rule->ctx->check_mime_part_ref != -1) {
		int err_idx, ret;

		struct rspamd_task **ptask;
		struct rspamd_mime_part **ppart;

		lua_pushcfunction(L, &rspamd_lua_traceback);
		err_idx = lua_gettop(L);
		lua_rawgeti(L, LUA_REGISTRYINDEX, rule->ctx->check_mime_part_ref);

		ptask = lua_newuserdata(L, sizeof(*ptask));
		*ptask = task;
		rspamd_lua_setclass(L, rspamd_task_classname, -1);

		ppart = lua_newuserdata(L, sizeof(*ppart));
		*ppart = part;
		rspamd_lua_setclass(L, rspamd_mimepart_classname, -1);

		lua_pushnumber(L, rule->lua_id);

		if ((ret = lua_pcall(L, 3, 2, err_idx)) != 0) {
			msg_err_task("call to check_mime_part lua "
						 "script failed (%d): %s",
						 ret, lua_tostring(L, -1));

			ret = FALSE;
		}
		else {
			ret = TRUE;
			*need_check = lua_toboolean(L, -2);
			*fuzzy_check = lua_toboolean(L, -1);
		}

		lua_settop(L, old_top);

		return ret;
	}

	return FALSE;
}

#define MAX_FUZZY_DOMAIN 64

static unsigned int
fuzzy_cmd_extension_length(struct rspamd_task *task,
						   struct fuzzy_rule *rule)
{
	unsigned int total = 0;

	if (rule->no_share) {
		return 0;
	}

	/* From domain */
	if (MESSAGE_FIELD(task, from_mime) && MESSAGE_FIELD(task, from_mime)->len > 0) {
		struct rspamd_email_address *addr = g_ptr_array_index(MESSAGE_FIELD(task,
																			from_mime),
															  0);

		if (addr->domain_len > 0) {
			total += 2; /* 2 bytes: type + length */
			total += MIN(MAX_FUZZY_DOMAIN, addr->domain_len);
		}
	}

	if (task->from_addr && rspamd_inet_address_get_af(task->from_addr) == AF_INET) {
		total += sizeof(struct in_addr) + 1;
	}
	else if (task->from_addr && rspamd_inet_address_get_af(task->from_addr) == AF_INET6) {
		total += sizeof(struct in6_addr) + 1;
	}

	return total;
}

static unsigned int
fuzzy_cmd_write_extensions(struct rspamd_task *task,
						   struct fuzzy_rule *rule,
						   unsigned char *dest,
						   gsize available)
{
	unsigned int written = 0;

	if (rule->no_share) {
		return 0;
	}

	if (MESSAGE_FIELD(task, from_mime) && MESSAGE_FIELD(task, from_mime)->len > 0) {
		struct rspamd_email_address *addr = g_ptr_array_index(MESSAGE_FIELD(task,
																			from_mime),
															  0);

		if (addr->domain_len > 0) {
			/* Filter invalid domains */
			unsigned int to_write = MIN(MAX_FUZZY_DOMAIN, addr->domain_len) + 2;

			if (to_write > 0 && to_write <= available) {
				*dest++ = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
				*dest++ = to_write - 2;

				if (addr->domain_len < MAX_FUZZY_DOMAIN) {
					memcpy(dest, addr->domain, addr->domain_len);
					dest += addr->domain_len;
				}
				else {
					/* Trim from left */
					memcpy(dest,
						   addr->domain + (addr->domain_len - MAX_FUZZY_DOMAIN),
						   MAX_FUZZY_DOMAIN);
					dest += MAX_FUZZY_DOMAIN;
				}

				available -= to_write;
				written += to_write;
			}
		}
	}

	if (task->from_addr && rspamd_inet_address_get_af(task->from_addr) == AF_INET) {
		if (available >= sizeof(struct in_addr) + 1) {
			unsigned int klen;
			unsigned char *inet_data = rspamd_inet_address_get_hash_key(task->from_addr, &klen);

			*dest++ = RSPAMD_FUZZY_EXT_SOURCE_IP4;

			memcpy(dest, inet_data, klen);
			dest += klen;

			available -= klen + 1;
			written += klen + 1;
		}
	}
	else if (task->from_addr && rspamd_inet_address_get_af(task->from_addr) == AF_INET6) {
		if (available >= sizeof(struct in6_addr) + 1) {
			unsigned int klen;
			unsigned char *inet_data = rspamd_inet_address_get_hash_key(task->from_addr, &klen);

			*dest++ = RSPAMD_FUZZY_EXT_SOURCE_IP6;

			memcpy(dest, inet_data, klen);
			dest += klen;

			available -= klen + 1;
			written += klen + 1;
		}
	}

	return written;
}

/*
 * Create fuzzy command from a text part
 */
static struct fuzzy_cmd_io *
fuzzy_cmd_from_text_part(struct rspamd_task *task,
						 struct fuzzy_rule *rule,
						 int c,
						 int flag,
						 uint32_t weight,
						 gboolean short_text,
						 struct rspamd_mime_text_part *part,
						 struct rspamd_mime_part *mp)
{
	struct rspamd_fuzzy_shingle_cmd *shcmd = NULL;
	struct rspamd_fuzzy_cmd *cmd = NULL;
	struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd = NULL;
	struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
	struct rspamd_cached_shingles *cached = NULL;
	struct rspamd_shingle *sh = NULL;
	unsigned int i;
	rspamd_cryptobox_hash_state_t st;
	rspamd_stat_token_t *word;
	rspamd_words_t *words;
	struct fuzzy_cmd_io *io;
	unsigned int additional_length;
	unsigned char *additional_data;

	cached = fuzzy_cmd_get_cached(rule, task, mp);

	/*
	 * Important note:
	 *
	 * We assume that fuzzy io is a consistent memory layout to fit into
	 * iov structure of size 1
	 *
	 * However, there are 4 possibilities:
	 * 1) non encrypted, non shingle command - just one cmd
	 * 2) encrypted, non shingle command - encryption hdr + cmd
	 * 3) non encrypted, shingle command - cmd + shingle
	 * 4) encrypted, shingle command - encryption hdr + cmd + shingle
	 *
	 * Extensions are always at the end, but since we also have caching (sigh, meh...)
	 * then we have one piece that looks like cmd (+ shingle) + extensions
	 * To encrypt it optionally we take this memory and prepend encryption header
	 *
	 * In case of cached version we do the same: allocate, copy from cached (including extra)
	 * and optionally encrypt.
	 *
	 * However, there should be no extensions in case of unencrypted connection
	 * (for sanity + privacy).
	 */
	if (cached) {
		additional_length = cached->additional_length;
		additional_data = cached->additional_data;

		/* Copy cached */
		if (short_text) {
			enccmd = rspamd_mempool_alloc0(task->task_pool,
										   sizeof(*enccmd) + additional_length);
			cmd = &enccmd->cmd;
			memcpy(cmd->digest, cached->digest,
				   sizeof(cached->digest));
			cmd->shingles_count = 0;
			memcpy(((unsigned char *) enccmd) + sizeof(*enccmd), additional_data,
				   additional_length);
		}
		else if (cached->sh) {
			encshcmd = rspamd_mempool_alloc0(task->task_pool,
											 additional_length + sizeof(*encshcmd));
			shcmd = &encshcmd->cmd;
			memcpy(&shcmd->sgl, cached->sh, sizeof(struct rspamd_shingle));
			memcpy(shcmd->basic.digest, cached->digest,
				   sizeof(cached->digest));
			memcpy(((unsigned char *) encshcmd) + sizeof(*encshcmd), additional_data,
				   additional_length);
			shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
		}
		else {
			return NULL;
		}
	}
	else {
		additional_length = fuzzy_cmd_extension_length(task, rule);
		cached = rspamd_mempool_alloc0(task->task_pool, sizeof(*cached) +
															additional_length);
		/*
		 * Allocate extensions and never touch it except copying to avoid
		 * occasional encryption
		 */
		cached->additional_length = additional_length;
		cached->additional_data = ((unsigned char *) cached) + sizeof(*cached);

		if (additional_length > 0) {
			fuzzy_cmd_write_extensions(task, rule, cached->additional_data,
									   additional_length);
		}

		if (short_text) {
			enccmd = rspamd_mempool_alloc0(task->task_pool,
										   sizeof(*enccmd) + additional_length);
			cmd = &enccmd->cmd;
			rspamd_cryptobox_hash_init(&st, rule->hash_key->str,
									   rule->hash_key->len);

			rspamd_cryptobox_hash_update(&st, part->utf_stripped_content->data,
										 part->utf_stripped_content->len);

			if (!rule->no_subject && (MESSAGE_FIELD(task, subject))) {
				/* We also include subject */
				rspamd_cryptobox_hash_update(&st, MESSAGE_FIELD(task, subject),
											 strlen(MESSAGE_FIELD(task, subject)));
			}

			rspamd_cryptobox_hash_final(&st, cmd->digest);
			memcpy(cached->digest, cmd->digest, sizeof(cached->digest));
			cached->sh = NULL;

			additional_data = ((unsigned char *) enccmd) + sizeof(*enccmd);
			memcpy(additional_data, cached->additional_data, additional_length);
		}
		else {
			encshcmd = rspamd_mempool_alloc0(task->task_pool,
											 sizeof(*encshcmd) + additional_length);
			shcmd = &encshcmd->cmd;

			/*
			 * Generate hash from all words in the part
			 */
			rspamd_cryptobox_hash_init(&st, rule->hash_key->str, rule->hash_key->len);
			words = fuzzy_preprocess_words(part, task->task_pool);

			for (i = 0; i < kv_size(*words); i++) {
				word = &kv_A(*words, i);

				if (!((word->flags & RSPAMD_WORD_FLAG_SKIPPED) || word->stemmed.len == 0)) {
					rspamd_cryptobox_hash_update(&st, word->stemmed.begin,
												 word->stemmed.len);
				}
			}

			rspamd_cryptobox_hash_final(&st, shcmd->basic.digest);

			msg_debug_fuzzy_check("loading shingles of type %s with key %*xs",
								  rule->algorithm_str,
								  16, rule->shingles_key->str);
			sh = rspamd_shingles_from_text(words,
										   rule->shingles_key->str, task->task_pool,
										   rspamd_shingles_default_filter, NULL,
										   rule->alg);
			if (sh != NULL) {
				memcpy(&shcmd->sgl, sh, sizeof(shcmd->sgl));
				shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
			}
			else {
				/* No shingles, no check */
				return NULL;
			}

			cached->sh = sh;
			memcpy(cached->digest, shcmd->basic.digest, sizeof(cached->digest));
			additional_data = ((unsigned char *) encshcmd) + sizeof(*encshcmd);
			memcpy(additional_data, cached->additional_data, additional_length);
		}

		/*
		 * We always save encrypted command as it can handle both
		 * encrypted and unencrypted requests.
		 *
		 * Since it is copied when obtained from the cache, it is safe to use
		 * it this way.
		 */
		fuzzy_cmd_set_cached(rule, task, mp, cached);
	}

	io = rspamd_mempool_alloc(task->task_pool, sizeof(*io));
	io->part = mp;

	if (!short_text) {
		shcmd->basic.tag = ottery_rand_uint32();
		shcmd->basic.cmd = c;
		shcmd->basic.version = fuzzy_cmd_version(rule);

		if (c != FUZZY_CHECK) {
			shcmd->basic.flag = flag;
			shcmd->basic.value = weight;
		}
		io->tag = shcmd->basic.tag;
		memcpy(&io->cmd, &shcmd->basic, sizeof(io->cmd));
	}
	else {
		cmd->tag = ottery_rand_uint32();
		cmd->cmd = c;
		cmd->version = fuzzy_cmd_version(rule);

		if (c != FUZZY_CHECK) {
			cmd->flag = flag;
			cmd->value = weight;
		}
		io->tag = cmd->tag;
		memcpy(&io->cmd, cmd, sizeof(io->cmd));
	}

	io->flags = 0;


	if (fuzzy_rule_has_encryption(rule)) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, c, &local_key, &peer_key);

		/* Encrypt data */
		if (!short_text) {
			fuzzy_encrypt_cmd(rule, &encshcmd->hdr, (unsigned char *) shcmd,
							  sizeof(*shcmd) + additional_length, local_key, peer_key);
			io->io.iov_base = encshcmd;
			io->io.iov_len = sizeof(*encshcmd) + additional_length;
		}
		else {
			fuzzy_encrypt_cmd(rule, &enccmd->hdr, (unsigned char *) cmd,
							  sizeof(*cmd) + additional_length, local_key, peer_key);
			io->io.iov_base = enccmd;
			io->io.iov_len = sizeof(*enccmd) + additional_length;
		}
	}
	else {

		if (!short_text) {
			io->io.iov_base = shcmd;
			io->io.iov_len = sizeof(*shcmd) + additional_length;
		}
		else {
			io->io.iov_base = cmd;
			io->io.iov_len = sizeof(*cmd) + additional_length;
		}
	}

	return io;
}

/*
 * Create fuzzy command from HTML structure (if part is HTML)
 */
static struct fuzzy_cmd_io *
fuzzy_cmd_from_html_part(struct rspamd_task *task,
						 struct fuzzy_rule *rule,
						 int c,
						 int flag,
						 uint32_t weight,
						 struct rspamd_mime_text_part *part,
						 struct rspamd_mime_part *mp,
						 gboolean ignore_link_domains)
{
	struct rspamd_fuzzy_shingle_cmd *shcmd = NULL;
	struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd = NULL;
	struct rspamd_cached_shingles *cached = NULL;
	struct rspamd_html_shingle *html_sh = NULL;
	struct fuzzy_cmd_io *io;
	unsigned int additional_length;
	unsigned char *additional_data;


	/* Check if HTML shingles are enabled for this rule */
	if (!rule->html_shingles) {
		return NULL;
	}

	/* Check if this is an HTML part */
	if (!IS_TEXT_PART_HTML(part) || part->html == NULL) {
		return NULL;
	}

	/* Check if HTML features are available */
	if (!part->html_features) {
		msg_debug_fuzzy_check("HTML part has no features available");
		return NULL;
	}

	/* Check minimum tags threshold */
	if (part->html_features->tags_count < rule->min_html_tags) {
		msg_debug_fuzzy_check("HTML part has %d tags, less than minimum %d",
							  part->html_features->tags_count, rule->min_html_tags);
		return NULL;
	}

	/*
	 * Additional safety checks for short HTML to prevent false positives:
	 * - Require at least 2 links (single-link emails too generic)
	 * - Require at least some DOM depth (flat structure too common)
	 */
	if (part->html_features->links.total_links < 2) {
		msg_debug_fuzzy_check("HTML part has only %d links, too few for reliable matching",
							  part->html_features->links.total_links);
		return NULL;
	}
	if (part->html_features->max_dom_depth < 3) {
		msg_debug_fuzzy_check("HTML part has depth %d, too shallow for reliable matching",
							  part->html_features->max_dom_depth);
		return NULL;
	}

	/*
	 * HTML fuzzy uses separate cache key to avoid conflicts with text fuzzy.
	 * Text parts can have both text hash (short text, no shingles) and HTML hash.
	 */
	char html_cache_key[64];
	int key_part;
	struct rspamd_cached_shingles **html_cached_ptr;

	memcpy(&key_part, rule->shingles_key->str, sizeof(key_part));
	rspamd_snprintf(html_cache_key, sizeof(html_cache_key), "%s%d_html%s",
					rule->algorithm_str, key_part,
					ignore_link_domains ? "_nd" : "");

	html_cached_ptr = (struct rspamd_cached_shingles **) rspamd_mempool_get_variable(
		task->task_pool, html_cache_key);

	if (html_cached_ptr && html_cached_ptr[mp->part_number]) {
		cached = html_cached_ptr[mp->part_number];
		/* Copy from HTML-specific cache */
		additional_length = cached->additional_length;
		additional_data = cached->additional_data;

		if (cached->sh) {
			encshcmd = rspamd_mempool_alloc0(task->task_pool,
											 sizeof(*encshcmd) + additional_length);
			shcmd = &encshcmd->cmd;
			memcpy(&shcmd->sgl, cached->sh, sizeof(struct rspamd_shingle));
			memcpy(shcmd->basic.digest, cached->digest, sizeof(cached->digest));
			memcpy(((unsigned char *) encshcmd) + sizeof(*encshcmd), additional_data,
				   additional_length);
			shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
		}
		else {
			return NULL;
		}
	}
	else {
		/* Generate HTML shingles */
		additional_length = fuzzy_cmd_extension_length(task, rule);
		cached = rspamd_mempool_alloc0(task->task_pool, sizeof(*cached) + additional_length);
		cached->additional_length = additional_length;
		cached->additional_data = ((unsigned char *) cached) + sizeof(*cached);

		if (additional_length > 0) {
			fuzzy_cmd_write_extensions(task, rule, cached->additional_data, additional_length);
		}

		encshcmd = rspamd_mempool_alloc0(task->task_pool,
										 sizeof(*encshcmd) + additional_length);
		shcmd = &encshcmd->cmd;

		html_sh = rspamd_shingles_from_html(part->html,
											(const unsigned char *) rule->shingles_key->str, task->task_pool,
											rspamd_shingles_default_filter, NULL,
											rule->alg, ignore_link_domains);

		if (html_sh != NULL) {
			/* Use structure shingles for fuzzy matching */
			memcpy(&shcmd->sgl, &html_sh->structure_shingles, sizeof(struct rspamd_shingle));
			/* Use direct hash as digest for exact matching */
			memcpy(shcmd->basic.digest, html_sh->direct_hash, sizeof(shcmd->basic.digest));
			shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;

			/* Cache results */
			cached->sh = &html_sh->structure_shingles;
			memcpy(cached->digest, html_sh->direct_hash, sizeof(cached->digest));
			additional_data = ((unsigned char *) encshcmd) + sizeof(*encshcmd);
			memcpy(additional_data, cached->additional_data, additional_length);
		}
		else {
			/* No HTML shingles generated */
			return NULL;
		}

		/* Save to HTML-specific cache (not standard text cache) */
		if (!html_cached_ptr) {
			html_cached_ptr = rspamd_mempool_alloc0(task->task_pool, sizeof(*html_cached_ptr) *
																		 (MESSAGE_FIELD(task, parts)->len + 1));
			rspamd_mempool_set_variable(task->task_pool, html_cache_key, html_cached_ptr, NULL);
		}
		html_cached_ptr[mp->part_number] = cached;
	}

	io = rspamd_mempool_alloc(task->task_pool, sizeof(*io));
	io->part = mp;

	shcmd->basic.tag = ottery_rand_uint32();
	shcmd->basic.cmd = c;
	shcmd->basic.version = fuzzy_cmd_version(rule);

	if (c != FUZZY_CHECK) {
		shcmd->basic.flag = flag;
		shcmd->basic.value = weight;
	}

	io->tag = shcmd->basic.tag;
	io->flags = FUZZY_CMD_FLAG_HTML;
	memcpy(&io->cmd, &shcmd->basic, sizeof(io->cmd));

	if (fuzzy_rule_has_encryption(rule)) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, c, &local_key, &peer_key);

		/* Encrypt data */
		fuzzy_encrypt_cmd(rule, &encshcmd->hdr, (unsigned char *) shcmd,
						  sizeof(*shcmd) + additional_length, local_key, peer_key);
		io->io.iov_base = encshcmd;
		io->io.iov_len = sizeof(*encshcmd) + additional_length;
	}
	else {
		io->io.iov_base = shcmd;
		io->io.iov_len = sizeof(*shcmd) + additional_length;
	}

	return io;
}

#if 0
static struct fuzzy_cmd_io *
fuzzy_cmd_from_image_part (struct fuzzy_rule *rule,
						   int c,
						   int flag,
						   uint32_t weight,
						   struct rspamd_task *task,
						   struct rspamd_image *img,
						   struct rspamd_mime_part *mp)
{
	struct rspamd_fuzzy_shingle_cmd *shcmd;
	struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd;
	struct fuzzy_cmd_io *io;
	struct rspamd_shingle *sh;
	struct rspamd_cached_shingles *cached;

	cached = fuzzy_cmd_get_cached (rule, task, mp);

	if (cached) {
		/* Copy cached */
		encshcmd = rspamd_mempool_alloc0 (task->task_pool, sizeof (*encshcmd));
		shcmd = &encshcmd->cmd;
		memcpy (&shcmd->sgl, cached->sh, sizeof (struct rspamd_shingle));
		memcpy (shcmd->basic.digest, cached->digest,
				sizeof (cached->digest));
		shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
	}
	else {
		encshcmd = rspamd_mempool_alloc0 (task->task_pool, sizeof (*encshcmd));
		shcmd = &encshcmd->cmd;

		/*
		 * Generate shingles
		 */
		sh = rspamd_shingles_from_image (img->dct,
				rule->shingles_key->str, task->task_pool,
				rspamd_shingles_default_filter, NULL,
				rule->alg);
		if (sh != NULL) {
			memcpy (&shcmd->sgl, sh->hashes, sizeof (shcmd->sgl));
			shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
#if 0
			for (unsigned int i = 0; i < RSPAMD_SHINGLE_SIZE; i ++) {
				msg_err ("shingle %d: %L", i, sh->hashes[i]);
			}
#endif
		}

		rspamd_cryptobox_hash (shcmd->basic.digest,
				(const unsigned char *)img->dct, RSPAMD_DCT_LEN / NBBY,
				rule->hash_key->str, rule->hash_key->len);

		msg_debug_fuzzy_check ("loading shingles of type %s with key %*xs",
				rule->algorithm_str,
				16, rule->shingles_key->str);

		/*
		 * We always save encrypted command as it can handle both
		 * encrypted and unencrypted requests.
		 *
		 * Since it is copied when obtained from the cache, it is safe to use
		 * it this way.
		 */
		cached = rspamd_mempool_alloc (task->task_pool, sizeof (*cached));
		cached->sh = sh;
		memcpy (cached->digest, shcmd->basic.digest, sizeof (cached->digest));
		fuzzy_cmd_set_cached (rule, task, mp, cached);
	}

	shcmd->basic.tag = ottery_rand_uint32 ();
	shcmd->basic.cmd = c;
	shcmd->basic.version = fuzzy_cmd_version(rule);

	if (c != FUZZY_CHECK) {
		shcmd->basic.flag = flag;
		shcmd->basic.value = weight;
	}

	io = rspamd_mempool_alloc (task->task_pool, sizeof (*io));
	io->part = mp;
	io->tag = shcmd->basic.tag;
	io->flags = FUZZY_CMD_FLAG_IMAGE;
	memcpy (&io->cmd, &shcmd->basic, sizeof (io->cmd));

	if (rule->peer_key) {
		/* Encrypt data */
		fuzzy_encrypt_cmd (rule, &encshcmd->hdr, (unsigned char *) shcmd, sizeof (*shcmd));
		io->io.iov_base = encshcmd;
		io->io.iov_len = sizeof (*encshcmd);
	}
	else {
		io->io.iov_base = shcmd;
		io->io.iov_len = sizeof (*shcmd);
	}

	return io;
}
#endif

static struct fuzzy_cmd_io *
fuzzy_cmd_from_data_part(struct fuzzy_rule *rule,
						 int c,
						 int flag,
						 uint32_t weight,
						 struct rspamd_task *task,
						 unsigned char digest[rspamd_cryptobox_HASHBYTES],
						 struct rspamd_mime_part *mp)
{
	struct rspamd_fuzzy_cmd *cmd;
	struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
	struct fuzzy_cmd_io *io;
	unsigned int additional_length;
	unsigned char *additional_data;

	additional_length = fuzzy_cmd_extension_length(task, rule);

	if (fuzzy_rule_has_encryption(rule)) {
		enccmd = rspamd_mempool_alloc0(task->task_pool,
									   sizeof(*enccmd) + additional_length);
		cmd = &enccmd->cmd;
		additional_data = ((unsigned char *) enccmd) + sizeof(*enccmd);
	}
	else {
		cmd = rspamd_mempool_alloc0(task->task_pool,
									sizeof(*cmd) + additional_length);
		additional_data = ((unsigned char *) cmd) + sizeof(*cmd);
	}

	cmd->cmd = c;
	cmd->version = fuzzy_cmd_version(rule);
	if (c != FUZZY_CHECK) {
		cmd->flag = flag;
		cmd->value = weight;
	}
	cmd->shingles_count = 0;
	cmd->tag = ottery_rand_uint32();
	memcpy(cmd->digest, digest, sizeof(cmd->digest));

	io = rspamd_mempool_alloc(task->task_pool, sizeof(*io));
	io->flags = 0;
	io->tag = cmd->tag;
	io->part = mp;
	memcpy(&io->cmd, cmd, sizeof(io->cmd));

	if (additional_length > 0) {
		fuzzy_cmd_write_extensions(task, rule, additional_data,
								   additional_length);
	}

	if (fuzzy_rule_has_encryption(rule)) {
		struct rspamd_cryptobox_keypair *local_key;
		struct rspamd_cryptobox_pubkey *peer_key;

		fuzzy_select_encryption_keys(rule, c, &local_key, &peer_key);

		g_assert(enccmd != NULL);
		fuzzy_encrypt_cmd(rule, &enccmd->hdr, (unsigned char *) cmd,
						  sizeof(*cmd) + additional_length, local_key, peer_key);
		io->io.iov_base = enccmd;
		io->io.iov_len = sizeof(*enccmd) + additional_length;
	}
	else {
		io->io.iov_base = cmd;
		io->io.iov_len = sizeof(*cmd) + additional_length;
	}

	return io;
}

static gboolean
fuzzy_cmd_to_wire(int fd, struct iovec *io)
{
	struct msghdr msg;

	memset(&msg, 0, sizeof(msg));
	msg.msg_iov = io;
	msg.msg_iovlen = 1;

	while (sendmsg(fd, &msg, 0) == -1) {
		if (errno == EINTR) {
			continue;
		}
		return FALSE;
	}

	return TRUE;
}

static gboolean
fuzzy_cmd_vector_to_wire(int fd, GPtrArray *v)
{
	unsigned int i;
	gboolean all_sent = TRUE, all_replied = TRUE;
	struct fuzzy_cmd_io *io;
	gboolean processed = FALSE;

	/* First try to resend unsent commands */
	for (i = 0; i < v->len; i++) {
		io = g_ptr_array_index(v, i);

		if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
			continue;
		}

		all_replied = FALSE;

		if (!(io->flags & FUZZY_CMD_FLAG_SENT)) {
			if (!fuzzy_cmd_to_wire(fd, &io->io)) {
				return FALSE;
			}
			processed = TRUE;
			io->flags |= FUZZY_CMD_FLAG_SENT;
			all_sent = FALSE;
		}
	}

	if (all_sent && !all_replied) {
		/* Now try to resend each command in the vector */
		for (i = 0; i < v->len; i++) {
			io = g_ptr_array_index(v, i);

			if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
				io->flags &= ~FUZZY_CMD_FLAG_SENT;
			}
		}

		return fuzzy_cmd_vector_to_wire(fd, v);
	}

	return processed;
}

/*
 * Read replies one-by-one and remove them from req array
 */
static const struct rspamd_fuzzy_reply *
fuzzy_process_reply(unsigned char **pos, int *r, GPtrArray *req,
					struct fuzzy_rule *rule, struct rspamd_fuzzy_cmd **pcmd,
					struct fuzzy_cmd_io **pio,
					const struct rspamd_fuzzy_reply_v2 **p_rep_v2)
{
	unsigned char *p = *pos;
	int remain = *r;
	unsigned int i, required_size;
	struct fuzzy_cmd_io *io;
	const struct rspamd_fuzzy_reply *rep;
	struct rspamd_fuzzy_encrypted_reply encrep;
	struct rspamd_fuzzy_encrypted_reply_v2 encrep_v2;
	static struct rspamd_fuzzy_reply synthetic_rep;
	gboolean found = FALSE;
	gboolean is_v2 = FALSE;

	if (p_rep_v2) {
		*p_rep_v2 = NULL;
	}

	/* Use v1 size as minimum */
	if (fuzzy_rule_has_encryption(rule)) {
		required_size = sizeof(encrep);
	}
	else {
		required_size = sizeof(struct rspamd_fuzzy_reply);
	}

	if (remain <= 0 || (unsigned int) remain < required_size) {
		return NULL;
	}

	/* Detect v2 by available size */
	if (fuzzy_rule_has_encryption(rule) && (unsigned int) remain >= sizeof(encrep_v2)) {
		is_v2 = TRUE;
	}
	else if (!fuzzy_rule_has_encryption(rule) && (unsigned int) remain >= sizeof(struct rspamd_fuzzy_reply_v2)) {
		is_v2 = TRUE;
	}

	if (fuzzy_rule_has_encryption(rule)) {
		gsize actual_size = is_v2 ? sizeof(encrep_v2) : sizeof(encrep);
		*pos += actual_size;
		*r -= actual_size;

		/* Try to decrypt with available keys, starting with read keys (more common) */
		struct rspamd_cryptobox_keypair *local_keys[3];
		struct rspamd_cryptobox_pubkey *peer_keys[3];
		int nkeys = 0;
		gboolean decrypted = FALSE;

		/* Try read keys first (most common for CHECK operations) */
		if (rule->read_peer_key && rule->read_local_key) {
			local_keys[nkeys] = rule->read_local_key;
			peer_keys[nkeys] = rule->read_peer_key;
			nkeys++;
		}
		/* Then try write keys if not already added */
		if (rule->write_peer_key && rule->write_local_key) {
			gboolean already_added = FALSE;
			for (int j = 0; j < nkeys; j++) {
				if (peer_keys[j] == rule->write_peer_key) {
					already_added = TRUE;
					break;
				}
			}
			if (!already_added) {
				local_keys[nkeys] = rule->write_local_key;
				peer_keys[nkeys] = rule->write_peer_key;
				nkeys++;
			}
		}
		/* Finally try common keys if not already added */
		if (rule->peer_key && rule->local_key) {
			gboolean already_added = FALSE;
			for (int j = 0; j < nkeys; j++) {
				if (peer_keys[j] == rule->peer_key) {
					already_added = TRUE;
					break;
				}
			}
			if (!already_added) {
				local_keys[nkeys] = rule->local_key;
				peer_keys[nkeys] = rule->peer_key;
				nkeys++;
			}
		}

		if (is_v2) {
			memcpy(&encrep_v2, p, sizeof(encrep_v2));

			for (i = 0; i < (unsigned int) nkeys && !decrypted; i++) {
				struct rspamd_fuzzy_encrypted_reply_v2 encrep_v2_copy;
				memcpy(&encrep_v2_copy, &encrep_v2, sizeof(encrep_v2_copy));

				rspamd_keypair_cache_process(rule->ctx->keypairs_cache,
											 local_keys[i], peer_keys[i]);

				if (rspamd_cryptobox_decrypt_nm_inplace((unsigned char *) &encrep_v2_copy.rep,
														sizeof(encrep_v2_copy.rep),
														encrep_v2_copy.hdr.nonce,
														rspamd_pubkey_get_nm(peer_keys[i], local_keys[i]),
														encrep_v2_copy.hdr.mac)) {
					memcpy(&encrep_v2, &encrep_v2_copy, sizeof(encrep_v2));
					decrypted = TRUE;
					break;
				}
			}

			if (!decrypted) {
				/* Fallback: try as v1 */
				is_v2 = FALSE;
				memcpy(&encrep, p, sizeof(encrep));

				for (i = 0; i < (unsigned int) nkeys && !decrypted; i++) {
					struct rspamd_fuzzy_encrypted_reply encrep_copy;
					memcpy(&encrep_copy, &encrep, sizeof(encrep_copy));

					rspamd_keypair_cache_process(rule->ctx->keypairs_cache,
												 local_keys[i], peer_keys[i]);

					if (rspamd_cryptobox_decrypt_nm_inplace((unsigned char *) &encrep_copy.rep,
															sizeof(encrep_copy.rep),
															encrep_copy.hdr.nonce,
															rspamd_pubkey_get_nm(peer_keys[i], local_keys[i]),
															encrep_copy.hdr.mac)) {
						memcpy(&encrep, &encrep_copy, sizeof(encrep));
						decrypted = TRUE;
						break;
					}
				}

				if (!decrypted) {
					msg_info("cannot decrypt reply with any available keys");
					return NULL;
				}

				memcpy(p, &encrep.rep, sizeof(encrep.rep));
			}
			else {
				/* Copy decrypted v2 back and build synthetic v1 rep */
				memcpy(p, &encrep_v2.rep, sizeof(encrep_v2.rep));
			}
		}
		else {
			memcpy(&encrep, p, sizeof(encrep));

			for (i = 0; i < (unsigned int) nkeys && !decrypted; i++) {
				struct rspamd_fuzzy_encrypted_reply encrep_copy;
				memcpy(&encrep_copy, &encrep, sizeof(encrep_copy));

				rspamd_keypair_cache_process(rule->ctx->keypairs_cache,
											 local_keys[i], peer_keys[i]);

				if (rspamd_cryptobox_decrypt_nm_inplace((unsigned char *) &encrep_copy.rep,
														sizeof(encrep_copy.rep),
														encrep_copy.hdr.nonce,
														rspamd_pubkey_get_nm(peer_keys[i], local_keys[i]),
														encrep_copy.hdr.mac)) {
					memcpy(&encrep, &encrep_copy, sizeof(encrep));
					decrypted = TRUE;
					break;
				}
			}

			if (!decrypted) {
				msg_info("cannot decrypt reply with any available keys");
				return NULL;
			}

			memcpy(p, &encrep.rep, sizeof(encrep.rep));
		}
	}
	else {
		gsize actual_size = is_v2 ? sizeof(struct rspamd_fuzzy_reply_v2)
								  : sizeof(struct rspamd_fuzzy_reply);
		*pos += actual_size;
		*r -= actual_size;
	}

	if (is_v2) {
		const struct rspamd_fuzzy_reply_v2 *rv2 = (const struct rspamd_fuzzy_reply_v2 *) p;
		memset(&synthetic_rep, 0, sizeof(synthetic_rep));
		synthetic_rep.v1 = rv2->v1;
		memcpy(synthetic_rep.digest, rv2->digest, sizeof(synthetic_rep.digest));
		synthetic_rep.ts = rv2->ts;
		rep = &synthetic_rep;
		if (p_rep_v2) {
			*p_rep_v2 = rv2;
		}
	}
	else {
		rep = (const struct rspamd_fuzzy_reply *) p;
	}
	/*
	 * Search for tag
	 */
	for (i = 0; i < req->len; i++) {
		io = g_ptr_array_index(req, i);

		if (io->tag == rep->v1.tag) {
			if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
				io->flags |= FUZZY_CMD_FLAG_REPLIED;

				if (pcmd) {
					*pcmd = &io->cmd;
				}

				if (pio) {
					*pio = io;
				}

				return rep;
			}
			found = TRUE;
		}
	}

	if (!found) {
		msg_info("unexpected tag: %ud", rep->v1.tag);
	}

	return NULL;
}

static void
fuzzy_insert_result(struct fuzzy_client_session *session,
					const struct rspamd_fuzzy_reply *rep,
					struct rspamd_fuzzy_cmd *cmd,
					struct fuzzy_cmd_io *io,
					unsigned int flag)
{
	const char *symbol;
	struct fuzzy_mapping *map;
	struct rspamd_task *task = session->task;
	double weight;
	double nval;
	unsigned char buf[2048];
	const char *type = "bin";
	struct fuzzy_client_result *res;
	gboolean is_fuzzy = FALSE;
	char hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
	/* Discriminate scores for small images */
	static const unsigned int short_image_limit = 32 * 1024;

	/* Get mapping by flag */
	if ((map =
			 g_hash_table_lookup(session->rule->mappings,
								 GINT_TO_POINTER(rep->v1.flag))) == NULL) {
		/* Default symbol and default weight */
		symbol = session->rule->symbol;
		weight = session->rule->hits_limit;
	}
	else {
		/* Get symbol and weight from map */
		symbol = map->symbol;
		weight = map->weight;
	}

	res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
	res->prob = rep->v1.prob;
	res->symbol = symbol;
	/*
	 * Hash is assumed to be found if probability is more than 0.5
	 * In that case `value` means number of matches
	 * Otherwise `value` means error code
	 */

	msg_debug_fuzzy_check("got reply with probability %.2f and value %.2f",
						  (double) rep->v1.prob, (double) rep->v1.value);
	nval = fuzzy_normalize(rep->v1.value, weight);

	if (io) {
		if ((io->flags & FUZZY_CMD_FLAG_IMAGE)) {
			if (!io->part || io->part->parsed_data.len <= short_image_limit) {
				nval *= rspamd_normalize_probability(rep->v1.prob, 0.5);
			}

			type = "img";
			res->type = FUZZY_RESULT_IMG;
		}
		else if ((io->flags & FUZZY_CMD_FLAG_HTML_DOMAINS)) {
			/* HTML domain-sensitive hash (structure + domains) */
			nval *= sqrtf(rep->v1.prob);
			nval *= session->rule->html_weight;

			type = "htmld";
			res->type = FUZZY_RESULT_HTML;
		}
		else if ((io->flags & FUZZY_CMD_FLAG_HTML)) {
			/* HTML structural hash (template mode, domains ignored) */
			nval *= sqrtf(rep->v1.prob);
			/* Apply HTML weight multiplier from rule config */
			nval *= session->rule->html_weight;

			type = "html";
			res->type = FUZZY_RESULT_HTML;
		}
		else {
			/* Calc real probability */
			nval *= sqrtf(rep->v1.prob);

			if (cmd->shingles_count > 0) {
				type = "txt";
				res->type = FUZZY_RESULT_TXT;
			}
			else {
				if (io->flags & FUZZY_CMD_FLAG_CONTENT) {
					type = "content";
					res->type = FUZZY_RESULT_CONTENT;
				}
				else {
					res->type = FUZZY_RESULT_BIN;
				}
			}
		}
	}

	res->score = nval;

	if (memcmp(rep->digest, cmd->digest, sizeof(rep->digest)) != 0) {
		is_fuzzy = TRUE;
	}

	if (map != NULL || !session->rule->skip_unknown) {
		GList *fuzzy_var;
		rspamd_fstring_t *hex_result;
		char timebuf[64];
		struct tm tm_split;

		if (session->rule->skip_map) {
			rspamd_encode_hex_buf(cmd->digest, sizeof(cmd->digest),
								  hexbuf, sizeof(hexbuf) - 1);
			hexbuf[sizeof(hexbuf) - 1] = '\0';
			if (rspamd_match_hash_map(session->rule->skip_map, hexbuf,
									  sizeof(hexbuf) - 1)) {
				return;
			}
		}

		rspamd_encode_hex_buf(rep->digest, sizeof(rep->digest),
							  hexbuf, sizeof(hexbuf) - 1);
		hexbuf[sizeof(hexbuf) - 1] = '\0';

		rspamd_gmtime(rep->ts, &tm_split);
		rspamd_snprintf(timebuf, sizeof(timebuf), "%02d.%02d.%4d %02d:%02d:%02d GMT",
						tm_split.tm_mday,
						tm_split.tm_mon + 1,
						tm_split.tm_year + 1900,
						tm_split.tm_hour, tm_split.tm_min, tm_split.tm_sec);

		if (is_fuzzy) {
			msg_notice_task(
				"found fuzzy hash(%s) %s (%*xs requested) with weight: "
				"%.2f, probability %.2f, in list: %s:%d%s; added on %s",
				type,
				hexbuf,
				(int) sizeof(cmd->digest), cmd->digest,
				nval,
				(double) rep->v1.prob,
				symbol,
				rep->v1.flag,
				map == NULL ? "(unknown)" : "",
				timebuf);
		}
		else {
			msg_notice_task(
				"found exact fuzzy hash(%s) %s with weight: "
				"%.2f, probability %.2f, in list: %s:%d%s; added on %s",
				type,
				hexbuf,
				nval,
				(double) rep->v1.prob,
				symbol,
				rep->v1.flag,
				map == NULL ? "(unknown)" : "",
				timebuf);
		}

		rspamd_snprintf(buf,
						sizeof(buf),
						"%d:%*s:%.2f:%s",
						rep->v1.flag,
						(int) MIN(rspamd_fuzzy_hash_len * 2, sizeof(rep->digest) * 2), hexbuf,
						rep->v1.prob,
						type);
		res->option = rspamd_mempool_strdup(task->task_pool, buf);
		g_ptr_array_add(session->results, res);

		/* Store hex string in pool variable */
		hex_result = rspamd_mempool_alloc(task->task_pool,
										  sizeof(rspamd_fstring_t) + sizeof(hexbuf));
		memcpy(hex_result->str, hexbuf, sizeof(hexbuf));
		hex_result->len = sizeof(hexbuf) - 1;
		hex_result->allocated = (gsize) -1;
		fuzzy_var = rspamd_mempool_get_variable(task->task_pool,
												RSPAMD_MEMPOOL_FUZZY_RESULT);

		if (fuzzy_var == NULL) {
			fuzzy_var = g_list_prepend(NULL, hex_result);
			rspamd_mempool_set_variable(task->task_pool,
										RSPAMD_MEMPOOL_FUZZY_RESULT, fuzzy_var,
										(rspamd_mempool_destruct_t) g_list_free);
		}
		else {
			/* Not very efficient, but we don't really use it intensively */
			fuzzy_var = g_list_append(fuzzy_var, hex_result);
		}
	}
}

static int
fuzzy_check_try_read(struct fuzzy_client_session *session)
{
	struct rspamd_task *task;
	const struct rspamd_fuzzy_reply *rep;
	struct rspamd_fuzzy_cmd *cmd = NULL;
	struct fuzzy_cmd_io *io = NULL;
	int r, ret;
	unsigned char buf[2048], *p;

	task = session->task;

	if ((r = read(session->fd, buf, sizeof(buf) - 1)) == -1) {
		if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
			return 0;
		}
		else {
			return -1;
		}
	}
	else {
		p = buf;

		ret = 0;

		const struct rspamd_fuzzy_reply_v2 *rep_v2 = NULL;

		while ((rep = fuzzy_process_reply(&p, &r,
										  session->commands, session->rule, &cmd, &io, &rep_v2)) != NULL) {
			if (rep_v2) {
				session->rule->server_supports_v2 = TRUE;
			}
			if (rep->v1.prob > 0.5) {
				if (cmd->cmd == FUZZY_CHECK) {
					fuzzy_insert_result(session, rep, cmd, io, rep->v1.flag);

					/* Insert extra flag results from v2 reply */
					if (rep_v2 && rep_v2->n_extra_flags > 0) {
						for (uint8_t ei = 0; ei < rep_v2->n_extra_flags && ei < RSPAMD_FUZZY_MAX_EXTRA_FLAGS; ei++) {
							struct rspamd_fuzzy_reply extra_rep;
							memset(&extra_rep, 0, sizeof(extra_rep));
							extra_rep.v1.value = rep_v2->extra_flags[ei].value;
							extra_rep.v1.flag = rep_v2->extra_flags[ei].flag;
							extra_rep.v1.tag = rep->v1.tag;
							extra_rep.v1.prob = rep->v1.prob;
							memcpy(extra_rep.digest, rep_v2->digest, sizeof(extra_rep.digest));
							extra_rep.ts = rep_v2->ts;

							fuzzy_insert_result(session, &extra_rep, cmd, io, extra_rep.v1.flag);
						}
					}
				}
				else if (cmd->cmd == FUZZY_STAT) {
					/*
					 * We store fuzzy stat in the following way:
					 * 1) We store fuzzy hashes as a hash of rspamd_fuzzy_stat_entry
					 * 2) We store the resulting hash table inside pool variable `fuzzy_stat`
					 */
					struct rspamd_fuzzy_stat_entry *pval;
					GHashTable *stats_hash;

					stats_hash = (GHashTable *) rspamd_mempool_get_variable(task->task_pool,
																			RSPAMD_MEMPOOL_FUZZY_STAT);

					if (stats_hash == NULL) {
						stats_hash = g_hash_table_new(rspamd_str_hash, rspamd_str_equal);
						rspamd_mempool_set_variable(task->task_pool, RSPAMD_MEMPOOL_FUZZY_STAT,
													stats_hash,
													(rspamd_mempool_destruct_t) g_hash_table_destroy);
					}

					pval = g_hash_table_lookup(stats_hash, session->rule->name);

					if (pval == NULL) {
						pval = rspamd_mempool_alloc(task->task_pool,
													sizeof(*pval));
						pval->name = rspamd_mempool_strdup(task->task_pool,
														   session->rule->name);
						/* Safe, as pval->name is owned by the pool */
						g_hash_table_insert(stats_hash, (char *) pval->name, pval);
					}

					pval->fuzzy_cnt = (((uint64_t) rep->v1.value) << 32) + rep->v1.flag;
				}
			}
			else if (rep->v1.value == 403) {
				/* In fact, it should be 429, but we preserve compatibility */
				rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_RATELIMITED, 1.0,
										  session->rule->name);
			}
			else if (rep->v1.value == 503) {
				rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_FORBIDDEN, 1.0,
										  session->rule->name);
			}
			else if (rep->v1.value == 415) {
				rspamd_task_insert_result(task, RSPAMD_FUZZY_SYMBOL_ENCRYPTION_REQUIRED, 1.0,
										  session->rule->name);
			}
			else if (rep->v1.value == 401) {
				if (cmd->cmd != FUZZY_CHECK) {
					msg_info_task(
						"fuzzy check error for %d: skipped by server",
						rep->v1.flag);
				}
			}
			else if (rep->v1.value != 0) {
				msg_info_task(
					"fuzzy check error for %d: unknown error (%d)",
					rep->v1.flag,
					rep->v1.value);
			}

			ret = 1;
		}
	}

	return ret;
}

static void
fuzzy_insert_metric_results(struct rspamd_task *task, struct fuzzy_rule *rule,
							GPtrArray *results)
{
	struct fuzzy_client_result *res;
	unsigned int i;
	gboolean seen_text_hash = FALSE,
			 seen_img_hash = FALSE,
			 seen_text_part = FALSE,
			 seen_long_text = FALSE;
	double prob_txt = 0.0, mult;
	struct rspamd_mime_text_part *tp;

	/* About 5 words */
	static const unsigned int text_length_cutoff = 25;

	PTR_ARRAY_FOREACH(results, i, res)
	{
		if (res->type == FUZZY_RESULT_TXT) {
			seen_text_hash = TRUE;
			prob_txt = MAX(prob_txt, res->prob);
		}
		else if (res->type == FUZZY_RESULT_IMG) {
			seen_img_hash = TRUE;
		}
	}

	if (task->message) {
		PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, text_parts), i, tp)
		{
			if (!IS_TEXT_PART_EMPTY(tp) && kv_size(tp->utf_words) > 0) {
				seen_text_part = TRUE;

				if (tp->utf_stripped_text.magic == UTEXT_MAGIC) {
					if (utext_isLengthExpensive(&tp->utf_stripped_text)) {
						seen_long_text =
							utext_nativeLength(&tp->utf_stripped_text) >
							text_length_cutoff;
					}
					else {
						/* Cannot directly calculate length */
						seen_long_text =
							(tp->utf_stripped_content->len / 2) >
							text_length_cutoff;
					}
				}
			}
		}
	}

	PTR_ARRAY_FOREACH(results, i, res)
	{
		mult = 1.0;

		if (res->type == FUZZY_RESULT_IMG) {
			if (!seen_text_hash) {
				if (seen_long_text) {
					mult *= 0.25;
				}
				else if (seen_text_part) {
					/* We have some short text + image */
					mult *= 0.9;
				}
				/* Otherwise apply full score */
			}
			else if (prob_txt < 0.75) {
				/* Penalize sole image without matching text */
				if (prob_txt > 0.5) {
					mult *= prob_txt;
				}
				else {
					mult *= 0.5; /* cutoff */
				}
			}
		}
		else if (res->type == FUZZY_RESULT_TXT) {
			if (seen_img_hash) {
				/* Slightly increase score */
				mult = 1.1;
			}
		}

		double weight = res->score * mult;

		if (!isnan(rule->weight_threshold)) {
			if (weight >= rule->weight_threshold) {
				rspamd_task_insert_result_single(task, res->symbol,
												 weight, res->option);
			}
			else {
				msg_info_task("%s is not added: weight=%.4f below threshold",
							  res->symbol, weight);
			}
		}
		else {
			rspamd_task_insert_result_single(task, res->symbol,
											 weight, res->option);
		}
	}
}

static gboolean
fuzzy_check_session_is_completed(struct fuzzy_client_session *session)
{
	struct fuzzy_cmd_io *io;
	unsigned int nreplied = 0, i;
	struct rspamd_task *task = session->task;

	rspamd_upstream_ok(session->server);

	for (i = 0; i < session->commands->len; i++) {
		io = g_ptr_array_index(session->commands, i);

		if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
			nreplied++;
		}
	}

	if (nreplied == session->commands->len) {
		fuzzy_insert_metric_results(session->task, session->rule, session->results);

		if (session->item) {
			msg_debug_fuzzy_check("fuzzy_check: decrementing async counter for completed session");
			rspamd_symcache_item_async_dec_check(session->task, session->item, M);
		}

		rspamd_session_remove_event(session->task->s, fuzzy_io_fin, session);

		return TRUE;
	}
	else {
		msg_debug_fuzzy_check("fuzzy_check: session not completed (%d/%d replied)",
							  nreplied, (int) session->commands->len);
	}

	return FALSE;
}

/* Fuzzy check timeout callback */
static void
fuzzy_check_timer_callback(int fd, short what, void *arg)
{
	struct fuzzy_client_session *session = arg;
	struct rspamd_task *task;

	task = session->task;

	/* We might be here because of other checks being slow */
	if (fuzzy_check_try_read(session) > 0) {
		if (fuzzy_check_session_is_completed(session)) {
			return;
		}
	}

	if (session->retransmits >= 0) {
		if (session->retransmits >= session->rule->retransmits) {
			msg_err_task("got IO timeout with server %s(%s), after %d/%d retransmits",
						 rspamd_upstream_name(session->server),
						 rspamd_inet_address_to_string_pretty(
							 rspamd_upstream_addr_cur(session->server)),
						 session->retransmits,
						 session->rule->retransmits);
			rspamd_upstream_fail(session->server, TRUE, "timeout");

			if (session->item) {
				rspamd_symcache_item_async_dec_check(session->task, session->item, M);
			}
			rspamd_session_remove_event(session->task->s, fuzzy_io_fin, session);
		}
		else {
			/* Apply backpressure here: at least 100ms up to 500ms */
			session->retransmits++;
			double backpressure_time = MAX(session->rule->io_timeout * 0.1, 0.1) * session->retransmits;
			/* Do not make delay more than 500ms for performance considerations */
			backpressure_time = MIN(backpressure_time, 0.5);
			backpressure_time = rspamd_time_jitter(backpressure_time * 0.5, 0.0);
			backpressure_time = MAX(backpressure_time, 0.1);
			/* Inverse to distinguish */
			msg_debug_fuzzy_check("backpressure for %.2f milliseconds (server=%s), retransmits: %d;",
								  backpressure_time * 1000,
								  rspamd_upstream_name(session->server),
								  session->retransmits);
			session->retransmits = -(session->retransmits);
			/* Disable write event for the time of backpressure */
			rspamd_ev_watcher_reschedule_at(session->event_loop,
											&session->ev, EV_READ,
											backpressure_time);
		}
	}
	else {
		/* Plan write event */
		rspamd_ev_watcher_reschedule_at(session->event_loop,
										&session->ev, EV_READ | EV_WRITE,
										session->rule->io_timeout);
		session->retransmits = -(session->retransmits);
	}
}

/* TCP timeout callback - session-level timeout, does NOT mark connection as failed */
static void
fuzzy_tcp_timer_callback(EV_P_ ev_timer *w, int revents)
{
	struct fuzzy_client_session *session = (struct fuzzy_client_session *) w->data;
	struct rspamd_task *task = session->task;
	struct fuzzy_cmd_io *io;
	unsigned int i, nreplied = 0;
	ev_tstamp now = rspamd_get_calendar_ticks();

	/* Check pending timeouts for all requests in this rule (periodic check) */
	fuzzy_tcp_check_pending_timeouts(session->rule, now);
	if (session->commands == NULL) {
		return;
	}

	/* Check if all commands have been replied */
	for (i = 0; i < session->commands->len; i++) {
		io = g_ptr_array_index(session->commands, i);
		if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
			nreplied++;
		}
	}

	if (nreplied == session->commands->len) {
		/* All replied, just complete */
		msg_debug_fuzzy_check("fuzzy_tcp: all commands replied, completing session");
		fuzzy_check_session_is_completed(session);
		return;
	}

	/* Session timeout - mark unreplied commands as failed for this session only */
	msg_warn_task("fuzzy_tcp: session timeout waiting for replies from %s (%d/%d replied)",
				  rspamd_upstream_name(session->server),
				  nreplied, (int) session->commands->len);

	/* Mark all unreplied commands as failed */
	for (i = 0; i < session->commands->len; i++) {
		io = g_ptr_array_index(session->commands, i);
		if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
			io->flags |= FUZZY_CMD_FLAG_REPLIED;
		}
	}

	/* Report upstream issue but don't mark as completely failed */
	rspamd_upstream_fail(session->server, FALSE, "session timeout");

	/* NOTE: We do NOT mark connection->failed = TRUE here!
	 * Session timeout is not a connection failure - other sessions may still succeed.
	 * Connection failures (socket errors) are handled in IO handlers.
	 */

	/* Clean up pending requests for THIS session only */
	fuzzy_tcp_session_cleanup(session);

	/* Stop timer */
	if (ev_is_active(&session->timer_ev)) {
		ev_timer_stop(session->event_loop, &session->timer_ev);
	}

	/* Decrement async counter for TCP session */
	if (session->item) {
		rspamd_symcache_item_async_dec_check(session->task, session->item, M);
	}

	/* Remove TCP session event */
	rspamd_session_remove_event(session->task->s, fuzzy_io_fin, session);
}

/* Fuzzy check callback */
static void
fuzzy_check_io_callback(int fd, short what, void *arg)
{
	struct fuzzy_client_session *session = arg;
	struct rspamd_task *task;
	int r;

	enum {
		return_error = 0,
		return_want_more,
		return_finished
	} ret = return_error;

	task = session->task;

	if ((what & EV_READ) || session->state == 1) {
		/* Try to read reply */
		r = fuzzy_check_try_read(session);

		switch (r) {
		case 0:
			if (what & EV_READ) {
				ret = return_want_more;
			}
			else {
				if (what & EV_WRITE) {
					/* Retransmit attempt */
					if (!fuzzy_cmd_vector_to_wire(fd, session->commands)) {
						ret = return_error;
					}
					else {
						session->state = 1;
						ret = return_want_more;
					}
				}
				else {
					/* It is actually time out */
					fuzzy_check_timer_callback(fd, what, arg);
					return;
				}
			}
			break;
		case 1:
			ret = return_finished;
			break;
		default:
			ret = return_error;
			break;
		}
	}
	else if (what & EV_WRITE) {
		if (!fuzzy_cmd_vector_to_wire(fd, session->commands)) {
			ret = return_error;
		}
		else {
			session->state = 1;
			ret = return_want_more;
		}
	}
	else {
		fuzzy_check_timer_callback(fd, what, arg);
		return;
	}

	if (ret == return_want_more) {
		/* Processed write, switch to reading */
		rspamd_ev_watcher_reschedule(session->event_loop,
									 &session->ev, EV_READ);
	}
	else if (ret == return_error) {
		/* Error state */
		msg_err_task("got error on IO with server %s(%s), on %s, %d, %s",
					 rspamd_upstream_name(session->server),
					 rspamd_inet_address_to_string_pretty(
						 rspamd_upstream_addr_cur(session->server)),
					 session->state == 1 ? "read" : "write",
					 errno,
					 strerror(errno));
		rspamd_upstream_fail(session->server, TRUE, strerror(errno));

		if (session->item) {
			rspamd_symcache_item_async_dec_check(session->task, session->item, M);
		}

		rspamd_session_remove_event(session->task->s, fuzzy_io_fin, session);
	}
	else {
		/* Read something from network */
		if (!fuzzy_check_session_is_completed(session)) {
			/* Need to read more */
			rspamd_ev_watcher_reschedule(session->event_loop,
										 &session->ev, EV_READ);
		}
	}
}


static void
fuzzy_controller_lua_fin(void *ud)
{
	struct fuzzy_learn_session *session = ud;

	(*session->saved)--;

	rspamd_ev_watcher_stop(session->event_loop, &session->ev);
	close(session->fd);
}

/* Controller IO */

static void
fuzzy_controller_timer_callback(int fd, short what, void *arg)
{
	struct fuzzy_learn_session *session = arg;
	struct rspamd_task *task;

	task = session->task;

	if (session->retransmits >= 0) {
		if (session->retransmits >= session->rule->retransmits) {
			rspamd_upstream_fail(session->server, TRUE, "timeout");
			msg_err_task_check("got IO timeout with server %s(%s), "
							   "after %d/%d retransmits",
							   rspamd_upstream_name(session->server),
							   rspamd_inet_address_to_string_pretty(
								   rspamd_upstream_addr_cur(session->server)),
							   session->retransmits,
							   session->rule->retransmits);

			if (session->session) {
				rspamd_session_remove_event(session->session, fuzzy_controller_lua_fin,
											session);
			}
			else {
				if (session->http_entry) {
					rspamd_controller_send_error(session->http_entry,
												 500, "IO timeout with fuzzy storage");
				}

				if (*session->saved > 0) {
					(*session->saved)--;
					if (*session->saved == 0) {
						if (session->http_entry) {
							rspamd_task_free(session->task);
						}

						session->task = NULL;
					}
				}

				if (session->http_entry) {
					rspamd_http_connection_unref(session->http_entry->conn);
				}

				rspamd_ev_watcher_stop(session->event_loop,
									   &session->ev);
				close(session->fd);
			}
		}
		else {
			/* Apply backpressure here: at least 100ms up to 500ms */
			session->retransmits++;
			double backpressure_time = MAX(session->rule->io_timeout * 0.1, 0.1) * session->retransmits;
			/* Do not make delay more than 500ms for performance considerations */
			backpressure_time = MIN(backpressure_time, 0.5);
			backpressure_time = rspamd_time_jitter(backpressure_time * 0.5, 0.0);
			backpressure_time = MAX(backpressure_time, 0.1);
			/* Inverse to distinguish */
			msg_debug_fuzzy_check("backpressure for %.2f milliseconds (server=%s), retransmits: %d;",
								  backpressure_time * 1000,
								  rspamd_upstream_name(session->server),
								  session->retransmits);
			session->retransmits = -(session->retransmits);
			/* Disable write event for the time of backpressure */
			rspamd_ev_watcher_reschedule_at(session->event_loop,
											&session->ev, EV_READ,
											backpressure_time);
		}
	}
	else {
		/* Backpressure done, plan write event */
		rspamd_ev_watcher_reschedule_at(session->event_loop,
										&session->ev, EV_READ | EV_WRITE,
										session->rule->io_timeout);
		session->retransmits = -(session->retransmits);
	}
}

static void
fuzzy_controller_io_callback(int fd, short what, void *arg)
{
	struct fuzzy_learn_session *session = arg;
	const struct rspamd_fuzzy_reply *rep;
	struct fuzzy_mapping *map;
	struct rspamd_task *task;
	unsigned char buf[2048], *p;
	struct fuzzy_cmd_io *io;
	struct rspamd_fuzzy_cmd *cmd = NULL;
	const char *symbol, *ftype;
	int r;
	enum {
		return_error = 0,
		return_want_more,
		return_finished
	} ret = return_want_more;
	unsigned int i, nreplied;
	const char *op = "process";

	task = session->task;

	if (what & EV_READ) {
		if ((r = read(fd, buf, sizeof(buf) - 1)) == -1) {
			if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
				rspamd_ev_watcher_reschedule(session->event_loop,
											 &session->ev, EV_READ);
				return;
			}

			msg_info_task("cannot process fuzzy hash for message: %s",
						  strerror(errno));
			session->err.error_message = "read socket error";
			session->err.error_code = errno;

			ret = return_error;
		}
		else {
			p = buf;
			ret = return_want_more;

			while ((rep = fuzzy_process_reply(&p, &r,
											  session->commands, session->rule, &cmd, &io, NULL)) != NULL) {
				if ((map =
						 g_hash_table_lookup(session->rule->mappings,
											 GINT_TO_POINTER(rep->v1.flag))) == NULL) {
					/* Default symbol and default weight */
					symbol = session->rule->symbol;
				}
				else {
					/* Get symbol and weight from map */
					symbol = map->symbol;
				}

				ftype = "bin";

				if (io) {
					if ((io->flags & FUZZY_CMD_FLAG_IMAGE)) {
						ftype = "img";
					}
					else if ((io->flags & FUZZY_CMD_FLAG_HTML_DOMAINS)) {
						ftype = "htmld";
					}
					else if ((io->flags & FUZZY_CMD_FLAG_HTML)) {
						ftype = "html";
					}
					else if (io->flags & FUZZY_CMD_FLAG_CONTENT) {
						ftype = "content";
					}
					else if (cmd->shingles_count > 0) {
						ftype = "txt";
					}

					if (io->cmd.cmd == FUZZY_WRITE) {
						op = "added";
					}
					else if (io->cmd.cmd == FUZZY_DEL) {
						op = "deleted";
					}
				}

				if (rep->v1.prob > 0.5) {
					msg_info_task("%s fuzzy hash (%s) %*xs, list: %s:%d for "
								  "message <%s>",
								  op,
								  ftype,
								  (int) sizeof(rep->digest), rep->digest,
								  symbol,
								  rep->v1.flag,
								  MESSAGE_FIELD_CHECK(session->task, message_id));
				}
				else {
					if (rep->v1.value == 401) {
						msg_info_task(
							"fuzzy hash (%s) for message cannot be %s"
							"<%s>, %*xs, "
							"list %s:%d, skipped by server",
							ftype,
							op,
							MESSAGE_FIELD_CHECK(session->task, message_id),
							(int) sizeof(rep->digest), rep->digest,
							symbol,
							rep->v1.flag);

						session->err.error_message = "fuzzy hash is skipped";
						session->err.error_code = rep->v1.value;
					}
					else {
						msg_info_task(
							"fuzzy hash (%s) for message cannot be %s"
							"<%s>, %*xs, "
							"list %s:%d, error: %d",
							ftype,
							op,
							MESSAGE_FIELD_CHECK(session->task, message_id),
							(int) sizeof(rep->digest), rep->digest,
							symbol,
							rep->v1.flag,
							rep->v1.value);

						session->err.error_message = "process fuzzy error";
						session->err.error_code = rep->v1.value;
					}

					ret = return_finished;
				}
			}

			nreplied = 0;

			for (i = 0; i < session->commands->len; i++) {
				io = g_ptr_array_index(session->commands, i);

				if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
					nreplied++;
				}
			}

			if (nreplied == session->commands->len) {
				ret = return_finished;
			}
		}
	}
	else if (what & EV_WRITE) {
		/* Send commands to storage */
		if (!fuzzy_cmd_vector_to_wire(fd, session->commands)) {
			session->err.error_message = "write socket error";
			session->err.error_code = errno;
			ret = return_error;
		}
	}
	else {
		fuzzy_controller_timer_callback(fd, what, arg);

		return;
	}

	if (ret == return_want_more) {
		rspamd_ev_watcher_reschedule(session->event_loop,
									 &session->ev, EV_READ);

		return;
	}
	else if (ret == return_error) {
		msg_err_task("got error in IO with server %s(%s), %d, %s",
					 rspamd_upstream_name(session->server),
					 rspamd_inet_address_to_string_pretty(
						 rspamd_upstream_addr_cur(session->server)),
					 errno, strerror(errno));
		rspamd_upstream_fail(session->server, FALSE, strerror(errno));
	}

	/*
	 * XXX: actually, we check merely a single reply, which is not correct...
	 * XXX: when we send a command, we do not check if *all* commands have been
	 * written
	 * XXX: please, please, change this code some day
	 */

	if (session->session == NULL) {
		(*session->saved)--;

		if (session->http_entry) {
			rspamd_http_connection_unref(session->http_entry->conn);
		}

		rspamd_ev_watcher_stop(session->event_loop, &session->ev);
		close(session->fd);

		if (*session->saved == 0) {
			goto cleanup;
		}
	}
	else {
		/* Lua handler */
		rspamd_session_remove_event(session->session, fuzzy_controller_lua_fin, session);
	}

	return;

cleanup:
	/*
	 * When we send learn commands to fuzzy storages, this code is executed
	 * *once* when we have queried all storages. We also don't know which
	 * storage has been failed.
	 *
	 * Therefore, we cleanup sessions earlier and actually this code is wrong.
	 */

	if (session->err.error_code != 0) {
		if (session->http_entry) {
			rspamd_controller_send_error(session->http_entry,
										 session->err.error_code, session->err.error_message);
		}
	}
	else {
		rspamd_upstream_ok(session->server);

		if (session->http_entry) {
			ucl_object_t *reply, *hashes;
			char hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];

			reply = ucl_object_typed_new(UCL_OBJECT);

			ucl_object_insert_key(reply, ucl_object_frombool(true),
								  "success", 0, false);
			hashes = ucl_object_typed_new(UCL_ARRAY);

			for (i = 0; i < session->commands->len; i++) {
				io = g_ptr_array_index(session->commands, i);

				rspamd_snprintf(hexbuf, sizeof(hexbuf), "%*xs",
								(int) sizeof(io->cmd.digest), io->cmd.digest);
				ucl_array_append(hashes, ucl_object_fromstring(hexbuf));
			}

			ucl_object_insert_key(reply, hashes, "hashes", 0, false);
			rspamd_controller_send_ucl(session->http_entry, reply);
			ucl_object_unref(reply);
		}
	}

	if (session->task != NULL) {
		if (session->http_entry) {
			rspamd_task_free(session->task);
		}

		session->task = NULL;
	}
}

static GPtrArray *
fuzzy_generate_commands(struct rspamd_task *task, struct fuzzy_rule *rule,
						int c, int flag, uint32_t value, unsigned int flags)
{
	struct rspamd_mime_text_part *part;
	struct rspamd_mime_part *mime_part;
	struct rspamd_image *image;
	struct fuzzy_cmd_io *io, *cur;
	unsigned int i, j;
	GPtrArray *res = NULL;
	gboolean check_part, fuzzy_check;

	if (c == FUZZY_STAT) {
		res = g_ptr_array_sized_new(1);

		io = fuzzy_cmd_stat(rule, c, flag, value, task->task_pool);
		if (io) {
			g_ptr_array_add(res, io);
		}

		return res;
	}
	else if (c == FUZZY_PING) {
		res = g_ptr_array_sized_new(1);

		io = fuzzy_cmd_ping(rule, task->task_pool);
		if (io) {
			g_ptr_array_add(res, io);
		}

		return res;
	}

	if (task->message == NULL) {
		return res;
	}

	res = g_ptr_array_sized_new(MESSAGE_FIELD(task, parts)->len + 1);

	PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, parts), i, mime_part)
	{
		check_part = FALSE;
		fuzzy_check = FALSE;

		if (fuzzy_rule_check_mimepart(task, rule, mime_part, &check_part,
									  &fuzzy_check)) {
			io = NULL;

			if (check_part) {
				if (mime_part->part_type == RSPAMD_MIME_PART_TEXT &&
					!(flags & FUZZY_CHECK_FLAG_NOTEXT)) {
					part = mime_part->specific.txt;
					gboolean allow_html = rule->html_shingles &&
										  !(flags & FUZZY_CHECK_FLAG_NOHTML) &&
										  (check_part || !rule->text_hashes);

					if (check_part && rule->text_hashes) {
						io = fuzzy_cmd_from_text_part(task, rule,
													  c,
													  flag,
													  value,
													  !fuzzy_check,
													  part,
													  mime_part);
					}

					if (allow_html && part != NULL) {
						struct fuzzy_cmd_io *html_io;

						html_io = fuzzy_cmd_from_html_part(task, rule, c, flag, value,
														   part, mime_part,
														   rule->html_ignore_domains);

						if (html_io) {
							/* Add HTML hash as separate command (template mode) */
							g_ptr_array_add(res, html_io);
						}

						/* Generate domain-sensitive command when ignore_domains is on */
						if (rule->html_ignore_domains) {
							struct fuzzy_cmd_io *htmld_io;

							htmld_io = fuzzy_cmd_from_html_part(task, rule, c, flag, value,
																part, mime_part,
																FALSE);

							if (htmld_io) {
								/* Mark as domain-sensitive HTML command */
								htmld_io->flags |= FUZZY_CMD_FLAG_HTML_DOMAINS;
								g_ptr_array_add(res, htmld_io);
							}
						}
					}
				}
				else if (check_part && mime_part->part_type == RSPAMD_MIME_PART_IMAGE &&
						 !(flags & FUZZY_CHECK_FLAG_NOIMAGES)) {
					image = mime_part->specific.img;

					io = fuzzy_cmd_from_data_part(rule, c, flag, value,
												  task,
												  image->parent->digest,
												  mime_part);
					io->flags |= FUZZY_CMD_FLAG_IMAGE;
				}
				else if (check_part && mime_part->part_type == RSPAMD_MIME_PART_CUSTOM_LUA) {
					const struct rspamd_lua_specific_part *lua_spec;

					lua_spec = &mime_part->specific.lua_specific;

					if (lua_spec->type == RSPAMD_LUA_PART_TABLE) {
						lua_State *L = (lua_State *) task->cfg->lua_state;
						int old_top;

						old_top = lua_gettop(L);
						/* Push table */
						lua_rawgeti(L, LUA_REGISTRYINDEX, lua_spec->cbref);
						lua_pushstring(L, "fuzzy_hashes");
						lua_gettable(L, -2);

						if (lua_type(L, -1) == LUA_TTABLE) {
							int tbl_pos = lua_gettop(L);

							for (lua_pushnil(L); lua_next(L, tbl_pos);
								 lua_pop(L, 1)) {
								const char *h = NULL;
								gsize hlen = 0;

								if (lua_isstring(L, -1)) {
									h = lua_tolstring(L, -1, &hlen);
								}
								else if (lua_type(L, -1) == LUA_TUSERDATA) {
									struct rspamd_lua_text *t;

									t = lua_check_text(L, -1);

									if (t) {
										h = t->start;
										hlen = t->len;
									}
								}

								if (hlen == rspamd_cryptobox_HASHBYTES) {
									io = fuzzy_cmd_from_data_part(rule, c,
																  flag, value,
																  task,
																  (unsigned char *) h,
																  mime_part);

									if (io) {
										io->flags |= FUZZY_CMD_FLAG_CONTENT;
										g_ptr_array_add(res, io);
									}
								}
							}
						}

						lua_settop(L, old_top);

						/*
						 * Add part itself as well
						 */
						io = fuzzy_cmd_from_data_part(rule, c,
													  flag, value,
													  task,
													  mime_part->digest,
													  mime_part);
					}
				}
				else if (check_part) {
					io = fuzzy_cmd_from_data_part(rule, c, flag, value,
												  task,
												  mime_part->digest, mime_part);
				}

				if (io) {
					gboolean skip_existing = FALSE;

					PTR_ARRAY_FOREACH(res, j, cur)
					{
						if (memcmp(cur->cmd.digest, io->cmd.digest,
								   sizeof(io->cmd.digest)) == 0) {
							skip_existing = TRUE;
							break;
						}
					}

					if (!skip_existing) {
						g_ptr_array_add(res, io);
					}
				}
			}
		}
	}

	if (res && res->len == 0) {
		g_ptr_array_free(res, TRUE);

		return NULL;
	}

	return res;
}


static inline void
register_fuzzy_client_call(struct rspamd_task *task,
						   struct fuzzy_rule *rule,
						   GPtrArray *commands)
{
	struct fuzzy_client_session *session;
	struct upstream *selected;
	rspamd_inet_addr_t *addr;
	int sock;

	if (!rspamd_session_blocked(task->s)) {
		/* Update rate tracker for TCP auto-switch decision */
		ev_tstamp now = rspamd_get_calendar_ticks();
		fuzzy_update_rate_tracker(rule, now);

		/* Get upstream first - use read_servers for check operations */
		selected = rspamd_upstream_get(rule->read_servers, RSPAMD_UPSTREAM_ROUND_ROBIN,
									   NULL, 0);
		if (!selected) {
			msg_warn_task("cannot get upstream for rule %s", rule->name);
			g_ptr_array_free(commands, TRUE);
			return;
		}

		/* Try TCP if enabled/auto and rate threshold exceeded */
		struct fuzzy_tcp_connection *tcp_conn = NULL;
		gboolean should_try_tcp = fuzzy_should_try_tcp(rule, now);

		if (should_try_tcp) {
			/* Log transition to TCP only on auto-switch (not when explicitly enabled) */
			if (rule->tcp_auto && !rule->rate_tracker.last_was_tcp) {
				double time_diff = now - rule->rate_tracker.window_start;
				double current_rate = (time_diff > 0) ? (rule->rate_tracker.requests_count / time_diff) : 0;
				msg_info_task("fuzzy_check: auto-switching to TCP for rule %s to %s (rate=%.2f req/s > threshold %.2f)",
							  rule->name, rspamd_upstream_name(selected),
							  current_rate, rule->tcp_threshold);
			}
			else {
				msg_debug_fuzzy_check("fuzzy_check: using TCP for rule %s to %s",
									  rule->name, rspamd_upstream_name(selected));
			}
			/* This is read server (CHECK operation) */
			tcp_conn = fuzzy_tcp_get_or_create_connection(rule, selected, task, FALSE);
		}
		else {
			/* Log transition to UDP only when switching from TCP */
			if (rule->tcp_auto && rule->rate_tracker.last_was_tcp) {
				msg_info_task("fuzzy_check: switching back to UDP for rule %s to %s (rate below threshold)",
							  rule->name, rspamd_upstream_name(selected));
			}
			else {
				msg_debug_fuzzy_check("fuzzy_check: using UDP for rule %s to %s",
									  rule->name, rspamd_upstream_name(selected));
			}
		}

		/* Use TCP if available and connected */
		if (tcp_conn && tcp_conn->connected) {
			msg_debug_fuzzy_check("fuzzy_check: sending %d commands via TCP to %s",
								  (int) commands->len, rspamd_upstream_name(selected));
			/* Create session for TCP */
			session = rspamd_mempool_alloc0(task->task_pool,
											sizeof(struct fuzzy_client_session));
			session->state = 0;
			session->commands = commands;
			session->task = task;
			session->server = selected;
			session->rule = rule;
			session->results = g_ptr_array_sized_new(32);
			session->fd = -1; /* TCP uses shared connection, no dedicated fd */
			session->event_loop = task->event_loop;

			/* Send commands via TCP */
			if (fuzzy_tcp_send_command(tcp_conn, commands, session)) {
				msg_debug_fuzzy_check("fuzzy_tcp: sent %d commands to %s via TCP",
									  (int) commands->len, rspamd_upstream_name(selected));

				/* Mark that we used TCP for this request */
				rule->rate_tracker.last_was_tcp = TRUE;

				rspamd_session_add_event(task->s, fuzzy_io_fin, session, M);
				session->item = rspamd_symcache_get_cur_item(task);

				if (session->item) {
					rspamd_symcache_item_async_inc(task, session->item, M);
				}

				/* Start timer for TCP request timeout using libev directly */
				session->timer_ev.data = session;
				ev_timer_init(&session->timer_ev, fuzzy_tcp_timer_callback,
							  rule->io_timeout, 0.0);
				ev_timer_start(session->event_loop, &session->timer_ev);

				return; /* TCP send successful */
			}
			else {
				/* Log fallback to UDP only for auto-switch mode */
				if (rule->tcp_auto && rule->rate_tracker.last_was_tcp) {
					msg_info_task("fuzzy_tcp: failed to send commands, falling back to UDP");
				}
				else {
					msg_debug_fuzzy_check("fuzzy_tcp: failed to send commands, using UDP");
				}
				/* Fall through to UDP */
			}
		}
		else if (tcp_conn && !tcp_conn->connected) {
			/* Log fallback only for auto-switch or when transition happens */
			if (rule->tcp_auto && rule->rate_tracker.last_was_tcp) {
				msg_info_task("fuzzy_check: TCP connection not ready for rule %s to %s, falling back to UDP",
							  rule->name, rspamd_upstream_name(selected));
			}
			else {
				msg_debug_fuzzy_check("fuzzy_check: TCP connection not ready for rule %s to %s, using UDP",
									  rule->name, rspamd_upstream_name(selected));
			}
		}

		/* Use UDP as fallback or when TCP not available */
		if (selected) {
			msg_debug_fuzzy_check("fuzzy_check: sending %d commands via UDP to %s",
								  (int) commands->len, rspamd_upstream_name(selected));
			addr = rspamd_upstream_addr_next(selected);

			if ((sock = rspamd_inet_address_connect(addr, SOCK_DGRAM, TRUE)) == -1) {
				msg_warn_task("cannot connect to %s(%s), %d, %s",
							  rspamd_upstream_name(selected),
							  rspamd_inet_address_to_string_pretty(addr),
							  errno,
							  strerror(errno));
				rspamd_upstream_fail(selected, TRUE, strerror(errno));
				g_ptr_array_free(commands, TRUE);
			}
			else {
				/* Mark that we used UDP for this request */
				rule->rate_tracker.last_was_tcp = FALSE;

				/* Create session for a socket */
				session =
					rspamd_mempool_alloc0(task->task_pool,
										  sizeof(struct fuzzy_client_session));
				session->state = 0;
				session->commands = commands;
				session->task = task;
				session->fd = sock;
				session->server = selected;
				session->rule = rule;
				session->results = g_ptr_array_sized_new(32);
				session->event_loop = task->event_loop;

				rspamd_ev_watcher_init(&session->ev,
									   sock,
									   EV_WRITE,
									   fuzzy_check_io_callback,
									   session);
				rspamd_ev_watcher_start(session->event_loop, &session->ev,
										rule->io_timeout);

				rspamd_session_add_event(task->s, fuzzy_io_fin, session, M);
				session->item = rspamd_symcache_get_cur_item(task);

				if (session->item) {
					rspamd_symcache_item_async_inc(task, session->item, M);
				}
			}
		}
	}
}

/* This callback is called when we check message in fuzzy hashes storage */
static void
fuzzy_symbol_callback(struct rspamd_task *task,
					  struct rspamd_symcache_dynamic_item *item,
					  void *unused)
{
	struct fuzzy_rule *rule;
	unsigned int i;
	GPtrArray *commands;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);

	if (!fuzzy_module_ctx->enabled) {
		rspamd_symcache_finalize_item(task, item);

		return;
	}

	/* Check whitelist */
	if (fuzzy_module_ctx->whitelist) {
		if (rspamd_match_radix_map_addr(fuzzy_module_ctx->whitelist,
										task->from_addr) != NULL) {
			msg_info_task("<%s>, address %s is whitelisted, skip fuzzy check",
						  MESSAGE_FIELD(task, message_id),
						  rspamd_inet_address_to_string(task->from_addr));
			rspamd_symcache_finalize_item(task, item);

			return;
		}
	}

	rspamd_symcache_item_async_inc(task, item, M);

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		if (rule->mode != fuzzy_rule_write_only) {
			commands = fuzzy_generate_commands(task, rule, FUZZY_CHECK, 0, 0, 0);

			if (commands != NULL) {
				register_fuzzy_client_call(task, rule, commands);
			}
		}
		/* Skip write only rules from checks */
	}

	rspamd_symcache_item_async_dec_check(task, item, M);
}

void fuzzy_stat_command(struct rspamd_task *task)
{
	struct fuzzy_rule *rule;
	unsigned int i;
	GPtrArray *commands;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);

	if (!fuzzy_module_ctx->enabled) {
		return;
	}

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		commands = fuzzy_generate_commands(task, rule, FUZZY_STAT, 0, 0, 0);
		if (commands != NULL) {
			register_fuzzy_client_call(task, rule, commands);
		}
	}
}

static inline int
register_fuzzy_controller_call(struct rspamd_http_connection_entry *entry,
							   struct fuzzy_rule *rule,
							   struct rspamd_task *task,
							   GPtrArray *commands,
							   int *saved)
{
	struct fuzzy_learn_session *s;
	struct upstream *selected;
	rspamd_inet_addr_t *addr;
	struct rspamd_controller_session *session = entry->ud;
	int sock;
	int ret = -1;

	/* Get upstream - use write_servers for learn/unlearn operations */
	while ((selected = rspamd_upstream_get_forced(rule->write_servers,
												  RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
		/* Create UDP socket */
		addr = rspamd_upstream_addr_next(selected);

		if ((sock = rspamd_inet_address_connect(addr,
												SOCK_DGRAM, TRUE)) == -1) {
			msg_warn_task("cannot connect to fuzzy storage %s (%s rule): %s",
						  rspamd_inet_address_to_string_pretty(addr),
						  rule->name,
						  strerror(errno));
			rspamd_upstream_fail(selected, TRUE, strerror(errno));
		}
		else {
			msg_info_task("fuzzy storage %s (%s rule) is used for write",
						  rspamd_inet_address_to_string_pretty(addr),
						  rule->name);
			s =
				rspamd_mempool_alloc0(session->pool,
									  sizeof(struct fuzzy_learn_session));

			s->task = task;
			s->commands = commands;
			s->http_entry = entry;
			s->server = selected;
			s->saved = saved;
			s->fd = sock;
			s->rule = rule;
			s->event_loop = task->event_loop;
			/* We ref connection to avoid freeing before we process fuzzy rule */
			rspamd_http_connection_ref(entry->conn);

			rspamd_ev_watcher_init(&s->ev,
								   sock,
								   EV_WRITE,
								   fuzzy_controller_io_callback,
								   s);
			rspamd_ev_watcher_start(s->event_loop, &s->ev, rule->io_timeout);

			(*saved)++;
			ret = 1;
		}
	}

	return ret;
}

static void
fuzzy_modify_handler(struct rspamd_http_connection_entry *conn_ent,
					 struct rspamd_http_message *msg, int cmd, int value, int flag,
					 struct fuzzy_ctx *ctx, gboolean is_hash, unsigned int flags)
{
	struct fuzzy_rule *rule;
	struct rspamd_controller_session *session = conn_ent->ud;
	struct rspamd_task *task, **ptask;
	gboolean processed = FALSE, skip = FALSE;
	int res = 0;
	unsigned int i;
	GPtrArray *commands;
	lua_State *L;
	int r, *saved, rules = 0, err_idx;
	struct fuzzy_ctx *fuzzy_module_ctx;

	/* Prepare task */
	task = rspamd_task_new(session->wrk, session->cfg, NULL,
						   session->lang_det, conn_ent->rt->event_loop, FALSE);
	task->cfg = ctx->cfg;
	saved = rspamd_mempool_alloc0(session->pool, sizeof(int));
	fuzzy_module_ctx = fuzzy_get_context(ctx->cfg);

	if (!is_hash) {
		/* Allocate message from string */
		/* XXX: what about encrypted messages ? */
		if (!rspamd_task_load_message(task, msg, msg->body_buf.begin, msg->body_buf.len)) {
			msg_warn_task("cannot load message for fuzzy");
			rspamd_controller_send_error(conn_ent, 400, "Message load error");
			rspamd_task_free(task);

			return;
		}

		r = rspamd_message_parse(task);

		if (r == -1) {
			msg_warn_task("<%s>: cannot process message for fuzzy",
						  MESSAGE_FIELD(task, message_id));
			rspamd_task_free(task);
			rspamd_controller_send_error(conn_ent, 400,
										 "Message processing error");

			return;
		}

		rspamd_message_process(task);
	}

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		if (rule->mode == fuzzy_rule_read_only) {
			msg_debug_task("skip rule %s as it is read-only", rule->name);
			continue;
		}

		/* Check for flag */
		if (g_hash_table_lookup(rule->mappings,
								GINT_TO_POINTER(flag)) == NULL) {
			msg_info_task("skip rule %s as it has no flag %d defined",
						  rule->name, flag);
			continue;
		}

		/* Check learn condition */
		if (rule->learn_condition_cb != -1) {
			skip = FALSE;
			L = session->cfg->lua_state;
			lua_pushcfunction(L, &rspamd_lua_traceback);
			err_idx = lua_gettop(L);

			lua_rawgeti(L, LUA_REGISTRYINDEX, rule->learn_condition_cb);
			ptask = lua_newuserdata(L, sizeof(struct rspamd_task *));
			*ptask = task;
			rspamd_lua_setclass(L, rspamd_task_classname, -1);

			if (lua_pcall(L, 1, LUA_MULTRET, err_idx) != 0) {
				msg_err_task("call to fuzzy learn condition failed: %s",
							 lua_tostring(L, -1));
			}
			else {
				if (lua_gettop(L) > err_idx + 1) {
					/* 2 return values */
					skip = !(lua_toboolean(L, err_idx + 1));

					if (lua_isnumber(L, err_idx + 2)) {
						msg_info_task("learn condition changed flag from %d to "
									  "%d",
									  flag,
									  (int) lua_tonumber(L, err_idx + 2));
						flag = lua_tonumber(L, err_idx + 2);
					}
				}
				else {
					if (lua_isboolean(L, err_idx + 1)) {
						skip = !(lua_toboolean(L, err_idx + 1));
					}
					else {
						msg_warn_task("set skip for rule %s as its condition "
									  "callback returned"
									  " a valid boolean",
									  rule->name);
						skip = TRUE;
					}
				}
			}

			/* Result + error function */
			lua_settop(L, err_idx - 1);

			if (skip) {
				msg_info_task("skip rule %s by condition callback",
							  rule->name);
				continue;
			}
		}

		rules++;

		res = 0;

		if (is_hash) {
			GPtrArray *args;
			const rspamd_ftok_t *arg;
			unsigned int j;

			args = rspamd_http_message_find_header_multiple(msg, "Hash");

			if (args) {
				struct fuzzy_cmd_io *io;
				commands = g_ptr_array_sized_new(args->len);

				for (j = 0; j < args->len; j++) {
					arg = g_ptr_array_index(args, j);
					io = fuzzy_cmd_hash(rule, cmd, arg, flag, value,
										task->task_pool);

					if (io) {
						g_ptr_array_add(commands, io);
					}
				}

				res = register_fuzzy_controller_call(conn_ent,
													 rule,
													 task,
													 commands,
													 saved);
				rspamd_mempool_add_destructor(task->task_pool,
											  rspamd_ptr_array_free_hard, commands);
				g_ptr_array_free(args, TRUE);
			}
			else {
				rspamd_controller_send_error(conn_ent, 400,
											 "No hash defined");
				rspamd_task_free(task);
				return;
			}
		}
		else {
			commands = fuzzy_generate_commands(task, rule, cmd, flag, value,
											   flags);
			msg_debug_task("fuzzy command %d for rule %s, flag %d, value %d",
						   cmd, rule->name, flag, value);
			if (commands != NULL) {
				res = register_fuzzy_controller_call(conn_ent,
													 rule,
													 task,
													 commands,
													 saved);
				rspamd_mempool_add_destructor(task->task_pool,
											  rspamd_ptr_array_free_hard, commands);
			}
		}

		if (res > 0) {
			processed = TRUE;
		}
	}

	if (res == -1) {
		if (!processed) {
			msg_warn_task("cannot send fuzzy request: %s",
						  strerror(errno));
			rspamd_controller_send_error(conn_ent, 400, "Message sending error");
			rspamd_task_free(task);

			return;
		}
		else {
			/* Some rules failed and some rules are OK */
			msg_warn_task("some rules are not processed, but we still sent this request");
		}
	}
	else if (!processed) {
		if (rules) {
			msg_warn_task("no content to generate fuzzy");
			rspamd_controller_send_error(conn_ent, 404,
										 "No content to generate fuzzy for flag %d", flag);
		}
		else {
			if (skip) {
				rspamd_controller_send_error(conn_ent, 403,
											 "Message is conditionally skipped for flag %d", flag);
			}
			else {
				msg_warn_task("no fuzzy rules found for flag %d", flag);
				rspamd_controller_send_error(conn_ent, 404,
											 "No fuzzy rules matched for flag %d", flag);
			}
		}
		rspamd_task_free(task);
	}
}

static int
fuzzy_controller_handler(struct rspamd_http_connection_entry *conn_ent,
						 struct rspamd_http_message *msg, struct module_ctx *ctx, int cmd,
						 gboolean is_hash)
{
	const rspamd_ftok_t *arg;
	glong value = 1, flag = 0, send_flags = 0;
	struct fuzzy_ctx *fuzzy_module_ctx = (struct fuzzy_ctx *) ctx;

	if (!fuzzy_module_ctx->enabled) {
		msg_err("fuzzy_check module is not enabled");
		rspamd_controller_send_error(conn_ent, 500, "Module disabled");
		return 0;
	}

	if (fuzzy_module_ctx->fuzzy_rules == NULL) {
		msg_err("fuzzy_check module has no rules defined");
		rspamd_controller_send_error(conn_ent, 500, "Module has no rules");
		return 0;
	}

	/* Get size */
	arg = rspamd_http_message_find_header(msg, "Weight");
	if (arg) {
		errno = 0;

		if (!rspamd_strtol(arg->begin, arg->len, &value)) {
			msg_info("error converting numeric argument %T", arg);
		}
	}

	arg = rspamd_http_message_find_header(msg, "Flag");
	if (arg) {
		errno = 0;

		if (!rspamd_strtol(arg->begin, arg->len, &flag)) {
			msg_info("error converting numeric argument %T", arg);
			flag = 0;
		}
	}
	else {
		flag = 0;
		arg = rspamd_http_message_find_header(msg, "Symbol");

		/* Search flag by symbol */
		if (arg) {
			struct fuzzy_rule *rule;
			unsigned int i;
			GHashTableIter it;
			gpointer k, v;
			struct fuzzy_mapping *map;

			PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
			{
				if (flag != 0) {
					break;
				}

				g_hash_table_iter_init(&it, rule->mappings);

				while (g_hash_table_iter_next(&it, &k, &v)) {
					map = v;

					if (strlen(map->symbol) == arg->len &&
						rspamd_lc_cmp(map->symbol, arg->begin, arg->len) == 0) {
						flag = map->fuzzy_flag;
						break;
					}
				}
			}
		}
	}

	if (flag == 0) {
		msg_err("no flag defined to learn fuzzy");
		rspamd_controller_send_error(conn_ent, 404, "Unknown or missing flag");
		return 0;
	}

	arg = rspamd_http_message_find_header(msg, "Skip-Images");
	if (arg) {
		send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
	}

	arg = rspamd_http_message_find_header(msg, "Skip-Attachments");
	if (arg) {
		send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
	}

	arg = rspamd_http_message_find_header(msg, "Skip-Text");
	if (arg) {
		send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
	}

	fuzzy_modify_handler(conn_ent, msg, cmd, value, flag,
						 (struct fuzzy_ctx *) ctx, is_hash, send_flags);

	return 0;
}

static inline int
fuzzy_check_send_lua_learn(struct fuzzy_rule *rule,
						   struct rspamd_task *task,
						   GPtrArray *commands,
						   int *saved)
{
	struct fuzzy_learn_session *s;
	struct upstream *selected;
	rspamd_inet_addr_t *addr;
	int sock;
	int ret = -1;

	/* Get upstream */
	if (!rspamd_session_blocked(task->s)) {
		while ((selected = rspamd_upstream_get(rule->write_servers,
											   RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
			/* Create UDP socket */
			addr = rspamd_upstream_addr_next(selected);

			if ((sock = rspamd_inet_address_connect(addr,
													SOCK_DGRAM, TRUE)) == -1) {
				rspamd_upstream_fail(selected, TRUE, strerror(errno));
			}
			else {
				s =
					rspamd_mempool_alloc0(task->task_pool,
										  sizeof(struct fuzzy_learn_session));
				s->task = task;
				s->commands = commands;
				s->http_entry = NULL;
				s->server = selected;
				s->saved = saved;
				s->fd = sock;
				s->rule = rule;
				s->session = task->s;
				s->event_loop = task->event_loop;

				rspamd_ev_watcher_init(&s->ev,
									   sock,
									   EV_WRITE,
									   fuzzy_controller_io_callback,
									   s);
				rspamd_ev_watcher_start(s->event_loop, &s->ev,
										rule->io_timeout);

				rspamd_session_add_event(task->s,
										 fuzzy_controller_lua_fin,
										 s,
										 M);

				(*saved)++;
				ret = 1;
			}
		}
	}

	return ret;
}

static gboolean
fuzzy_check_lua_process_learn(struct rspamd_task *task,
							  int cmd, int value, int flag, unsigned int send_flags)
{
	struct fuzzy_rule *rule;
	gboolean processed = FALSE, res = TRUE;
	unsigned int i;
	GPtrArray *commands;
	int *saved, rules = 0;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);

	saved = rspamd_mempool_alloc0(task->task_pool, sizeof(int));

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		if (!res) {
			break;
		}
		if (rule->mode == fuzzy_rule_read_only) {
			continue;
		}

		/* Check for flag */
		if (g_hash_table_lookup(rule->mappings,
								GINT_TO_POINTER(flag)) == NULL) {
			msg_info_task("skip rule %s as it has no flag %d defined",
						  rule->name, flag);
			continue;
		}

		rules++;

		res = 0;
		commands = fuzzy_generate_commands(task, rule, cmd, flag,
										   value, send_flags);

		if (commands != NULL) {
			res = fuzzy_check_send_lua_learn(rule, task, commands,
											 saved);
			rspamd_mempool_add_destructor(task->task_pool,
										  rspamd_ptr_array_free_hard, commands);
		}

		if (res) {
			processed = TRUE;
		}
	}

	if (res == -1) {
		msg_warn_task("cannot send fuzzy request: %s",
					  strerror(errno));
	}
	else if (!processed) {
		if (rules) {
			msg_warn_task("no content to generate fuzzy");

			return FALSE;
		}
		else {
			msg_warn_task("no fuzzy rules found for flag %d", flag);
			return FALSE;
		}
	}

	return TRUE;
}

static int
fuzzy_lua_learn_handler(lua_State *L)
{
	struct rspamd_task *task = lua_check_task(L, 1);

	if (task == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	unsigned int flag = 0, weight = 1, send_flags = 0;
	const char *symbol;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);

	if (lua_type(L, 2) == LUA_TNUMBER) {
		flag = lua_tointeger(L, 2);
	}
	else if (lua_type(L, 2) == LUA_TSTRING) {
		struct fuzzy_rule *rule;
		unsigned int i;
		GHashTableIter it;
		gpointer k, v;
		struct fuzzy_mapping *map;

		symbol = lua_tostring(L, 2);

		PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
		{
			if (flag != 0) {
				break;
			}

			g_hash_table_iter_init(&it, rule->mappings);

			while (g_hash_table_iter_next(&it, &k, &v)) {
				map = v;

				if (g_ascii_strcasecmp(symbol, map->symbol) == 0) {
					flag = map->fuzzy_flag;
					break;
				}
			}
		}
	}

	if (flag == 0) {
		return luaL_error(L, "bad flag");
	}

	if (lua_type(L, 3) == LUA_TNUMBER) {
		weight = lua_tonumber(L, 3);
	}

	if (lua_type(L, 4) == LUA_TTABLE) {
		const char *sf;

		for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
			sf = lua_tostring(L, -1);

			if (sf) {
				if (g_ascii_strcasecmp(sf, "noimages") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
				}
				else if (g_ascii_strcasecmp(sf, "noattachments") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
				}
				else if (g_ascii_strcasecmp(sf, "notext") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
				}
			}
		}
	}

	lua_pushboolean(L,
					fuzzy_check_lua_process_learn(task, FUZZY_WRITE, weight, flag,
												  send_flags));
	return 1;
}

static int
fuzzy_lua_unlearn_handler(lua_State *L)
{
	struct rspamd_task *task = lua_check_task(L, 1);
	if (task == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	unsigned int flag = 0, weight = 1.0, send_flags = 0;
	const char *symbol;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);

	if (lua_type(L, 2) == LUA_TNUMBER) {
		flag = lua_tointeger(L, 2);
	}
	else if (lua_type(L, 2) == LUA_TSTRING) {
		struct fuzzy_rule *rule;
		unsigned int i;
		GHashTableIter it;
		gpointer k, v;
		struct fuzzy_mapping *map;

		symbol = lua_tostring(L, 2);

		PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
		{

			if (flag != 0) {
				break;
			}

			g_hash_table_iter_init(&it, rule->mappings);

			while (g_hash_table_iter_next(&it, &k, &v)) {
				map = v;

				if (g_ascii_strcasecmp(symbol, map->symbol) == 0) {
					flag = map->fuzzy_flag;
					break;
				}
			}
		}
	}

	if (flag == 0) {
		return luaL_error(L, "bad flag");
	}

	if (lua_type(L, 3) == LUA_TNUMBER) {
		weight = lua_tonumber(L, 3);
	}

	if (lua_type(L, 4) == LUA_TTABLE) {
		const char *sf;

		for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
			sf = lua_tostring(L, -1);

			if (sf) {
				if (g_ascii_strcasecmp(sf, "noimages") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
				}
				else if (g_ascii_strcasecmp(sf, "noattachments") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
				}
				else if (g_ascii_strcasecmp(sf, "notext") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
				}
			}
		}
	}

	lua_pushboolean(L,
					fuzzy_check_lua_process_learn(task, FUZZY_DEL, weight, flag,
												  send_flags));

	return 1;
}

static int
fuzzy_lua_gen_hashes_handler(lua_State *L)
{
	struct rspamd_task *task = lua_check_task(L, 1);

	if (task == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	unsigned int flag = 0, weight = 1, send_flags = 0;
	const char *symbol;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);
	struct fuzzy_rule *rule;
	GPtrArray *commands;
	int cmd = FUZZY_WRITE;
	int i;

	if (lua_type(L, 2) == LUA_TNUMBER) {
		flag = lua_tonumber(L, 2);
	}
	else if (lua_type(L, 2) == LUA_TSTRING) {
		struct fuzzy_rule *rule;
		GHashTableIter it;
		gpointer k, v;
		struct fuzzy_mapping *map;

		symbol = lua_tostring(L, 2);

		PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
		{
			if (flag != 0) {
				break;
			}

			g_hash_table_iter_init(&it, rule->mappings);

			while (g_hash_table_iter_next(&it, &k, &v)) {
				map = v;

				if (g_ascii_strcasecmp(symbol, map->symbol) == 0) {
					flag = map->fuzzy_flag;
					break;
				}
			}
		}
	}

	if (flag == 0) {
		return luaL_error(L, "bad flag");
	}

	if (lua_type(L, 3) == LUA_TNUMBER) {
		weight = lua_tonumber(L, 3);
	}

	/* Flags */
	if (lua_type(L, 4) == LUA_TTABLE) {
		const char *sf;

		for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
			sf = lua_tostring(L, -1);

			if (sf) {
				if (g_ascii_strcasecmp(sf, "noimages") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
				}
				else if (g_ascii_strcasecmp(sf, "noattachments") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
				}
				else if (g_ascii_strcasecmp(sf, "notext") == 0) {
					send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
				}
			}
		}
	}

	/* Type */
	if (lua_type(L, 5) == LUA_TSTRING) {
		const char *cmd_name = lua_tostring(L, 5);

		if (strcmp(cmd_name, "add") == 0 || strcmp(cmd_name, "write") == 0) {
			cmd = FUZZY_WRITE;
		}
		else if (strcmp(cmd_name, "delete") == 0 || strcmp(cmd_name, "remove") == 0) {
			cmd = FUZZY_DEL;
		}
		else {
			return luaL_error(L, "invalid command: %s", cmd_name);
		}
	}

	lua_createtable(L, 0, fuzzy_module_ctx->fuzzy_rules->len);

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		if (rule->mode == fuzzy_rule_read_only) {
			continue;
		}

		/* Check for flag */
		if (g_hash_table_lookup(rule->mappings,
								GINT_TO_POINTER(flag)) == NULL) {
			msg_info_task("skip rule %s as it has no flag %d defined",
						  rule->name, flag);
			continue;
		}

		commands = fuzzy_generate_commands(task, rule, cmd, flag,
										   weight, send_flags);

		if (commands != NULL) {
			struct fuzzy_cmd_io *io;
			int j;

			lua_pushstring(L, rule->name);
			lua_createtable(L, commands->len, 0);

			PTR_ARRAY_FOREACH(commands, j, io)
			{
				lua_pushlstring(L, io->io.iov_base, io->io.iov_len);
				lua_rawseti(L, -2, j + 1);
			}

			lua_settable(L, -3); /* ret[rule->name] = {raw_fuzzy1, ..., raw_fuzzyn} */

			g_ptr_array_free(commands, TRUE);
		}
	}


	return 1;
}

static int
fuzzy_lua_hex_hashes_handler(lua_State *L)
{
	struct rspamd_task *task = lua_check_task(L, 1);

	if (task == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	unsigned int flag = 0, weight = 1, send_flags = 0;
	const char *symbol;
	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);
	struct fuzzy_rule *rule;
	GPtrArray *commands;
	int i;

	if (lua_type(L, 2) == LUA_TNUMBER) {
		flag = lua_tonumber(L, 2);
	}
	else if (lua_type(L, 2) == LUA_TSTRING) {
		struct fuzzy_rule *rule;
		GHashTableIter it;
		gpointer k, v;
		struct fuzzy_mapping *map;

		symbol = lua_tostring(L, 2);

		PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
		{
			if (flag != 0) {
				break;
			}

			g_hash_table_iter_init(&it, rule->mappings);

			while (g_hash_table_iter_next(&it, &k, &v)) {
				map = v;

				if (g_ascii_strcasecmp(symbol, map->symbol) == 0) {
					flag = map->fuzzy_flag;
					break;
				}
			}
		}
	}

	if (flag == 0) {
		return luaL_error(L, "bad flag");
	}

	lua_createtable(L, 0, fuzzy_module_ctx->fuzzy_rules->len);

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		/* Check for flag */
		if (g_hash_table_lookup(rule->mappings,
								GINT_TO_POINTER(flag)) == NULL) {
			msg_debug_fuzzy_check("skip rule %s as it has no flag %d defined",
								  rule->name, flag);
			continue;
		}

		commands = fuzzy_generate_commands(task, rule, FUZZY_CHECK, flag,
										   weight, send_flags);

		lua_pushstring(L, rule->name);

		if (commands != NULL) {
			lua_createtable(L, commands->len, 0);
			/*
			 * We have all commands cached, so we can just read their cached value to
			 * get hex hashes
			 */
			struct rspamd_mime_part *mp;
			int j, part_idx = 1;

			PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, parts), j, mp)
			{
				struct rspamd_cached_shingles *cached;

				cached = fuzzy_cmd_get_cached(rule, task, mp);

				if (cached) {
					char hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
					int r = rspamd_encode_hex_buf(cached->digest, sizeof(cached->digest), hexbuf,
												  sizeof(hexbuf));
					lua_pushlstring(L, hexbuf, r);
					lua_rawseti(L, -2, part_idx++);
				}
			}

			g_ptr_array_free(commands, TRUE);
		}
		else {
			lua_pushnil(L);
		}

		/* res[rule->name] = {hex_hash1, ..., hex_hashn} */
		lua_settable(L, -3);
	}

	return 1;
}

static gboolean
fuzzy_add_handler(struct rspamd_http_connection_entry *conn_ent,
				  struct rspamd_http_message *msg, struct module_ctx *ctx)
{
	return fuzzy_controller_handler(conn_ent, msg,
									ctx, FUZZY_WRITE, FALSE);
}

static gboolean
fuzzy_delete_handler(struct rspamd_http_connection_entry *conn_ent,
					 struct rspamd_http_message *msg, struct module_ctx *ctx)
{
	return fuzzy_controller_handler(conn_ent, msg,
									ctx, FUZZY_DEL, FALSE);
}

static gboolean
fuzzy_deletehash_handler(struct rspamd_http_connection_entry *conn_ent,
						 struct rspamd_http_message *msg, struct module_ctx *ctx)
{
	return fuzzy_controller_handler(conn_ent, msg,
									ctx, FUZZY_DEL, TRUE);
}

static int
fuzzy_attach_controller(struct module_ctx *ctx, GHashTable *commands)
{
	struct fuzzy_ctx *fctx = (struct fuzzy_ctx *) ctx;
	struct rspamd_custom_controller_command *cmd;

	cmd = rspamd_mempool_alloc(fctx->fuzzy_pool, sizeof(*cmd));
	cmd->privileged = TRUE;
	cmd->require_message = TRUE;
	cmd->handler = fuzzy_add_handler;
	cmd->ctx = ctx;
	g_hash_table_insert(commands, "/fuzzyadd", cmd);

	cmd = rspamd_mempool_alloc(fctx->fuzzy_pool, sizeof(*cmd));
	cmd->privileged = TRUE;
	cmd->require_message = TRUE;
	cmd->handler = fuzzy_delete_handler;
	cmd->ctx = ctx;
	g_hash_table_insert(commands, "/fuzzydel", cmd);

	cmd = rspamd_mempool_alloc(fctx->fuzzy_pool, sizeof(*cmd));
	cmd->privileged = TRUE;
	cmd->require_message = FALSE;
	cmd->handler = fuzzy_deletehash_handler;
	cmd->ctx = ctx;
	g_hash_table_insert(commands, "/fuzzydelhash", cmd);

	return 0;
}

/* Lua handlers */
/* TODO: move to a separate unit, as this file is now a bit too hard to read */

static void
lua_upstream_str_inserter(struct upstream *up, unsigned int idx, void *ud)
{
	lua_State *L = (lua_State *) ud;

	lua_pushstring(L, rspamd_upstream_name(up));
	lua_rawseti(L, -2, idx + 1);
}

static int
fuzzy_lua_list_storages(lua_State *L)
{
	struct rspamd_config *cfg = lua_check_config(L, 1);

	if (cfg == NULL) {
		return luaL_error(L, "invalid arguments");
	}

	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(cfg);
	struct fuzzy_rule *rule;
	unsigned int i;

	lua_createtable(L, 0, fuzzy_module_ctx->fuzzy_rules->len);
	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		lua_newtable(L);

		lua_pushboolean(L, rule->mode == fuzzy_rule_read_only);
		lua_setfield(L, -2, "read_only");

		/* Push servers */
		if (rule->read_servers == rule->write_servers) {
			/* Same servers for both operations */
			lua_createtable(L, rspamd_upstreams_count(rule->read_servers), 0);
			rspamd_upstreams_foreach(rule->read_servers, lua_upstream_str_inserter, L);
			lua_setfield(L, -2, "servers");
		}
		else {
			/* Different servers for read and write */
			lua_createtable(L, rspamd_upstreams_count(rule->read_servers), 0);
			rspamd_upstreams_foreach(rule->read_servers, lua_upstream_str_inserter, L);
			lua_setfield(L, -2, "read_servers");
			lua_createtable(L, rspamd_upstreams_count(rule->write_servers), 0);
			rspamd_upstreams_foreach(rule->write_servers, lua_upstream_str_inserter, L);
			lua_setfield(L, -2, "write_servers");
		}

		/* Push flags */
		GHashTableIter it;

		lua_createtable(L, 0, g_hash_table_size(rule->mappings));
		gpointer k, v;
		struct fuzzy_mapping *map;

		g_hash_table_iter_init(&it, rule->mappings);
		while (g_hash_table_iter_next(&it, &k, &v)) {
			map = v;

			lua_pushinteger(L, map->fuzzy_flag);
			lua_setfield(L, -2, map->symbol);
		}
		lua_setfield(L, -2, "flags");

		/* Final table */
		lua_setfield(L, -2, rule->name);
	}

	return 1;
}

struct fuzzy_lua_session {
	struct rspamd_task *task;
	lua_State *L;
	rspamd_inet_addr_t *addr;
	GPtrArray *commands;
	struct fuzzy_rule *rule;
	struct rspamd_io_ev ev;
	int cbref;
	int fd;
};

static void
fuzzy_lua_session_fin(void *ud)
{
	struct fuzzy_lua_session *session = ud;

	if (session->commands) {
		g_ptr_array_free(session->commands, TRUE);
	}

	rspamd_ev_watcher_stop(session->task->event_loop, &session->ev);
	luaL_unref(session->L, LUA_REGISTRYINDEX, session->cbref);
}

static gboolean
fuzzy_lua_session_is_completed(struct fuzzy_lua_session *session)
{
	struct fuzzy_cmd_io *io;
	unsigned int nreplied = 0, i;


	for (i = 0; i < session->commands->len; i++) {
		io = g_ptr_array_index(session->commands, i);

		if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
			nreplied++;
		}
	}

	if (nreplied == session->commands->len) {

		rspamd_session_remove_event(session->task->s, fuzzy_lua_session_fin, session);

		return TRUE;
	}

	return FALSE;
}

static void
fuzzy_lua_push_result(struct fuzzy_lua_session *session, double latency)
{
	lua_rawgeti(session->L, LUA_REGISTRYINDEX, session->cbref);
	lua_pushboolean(session->L, TRUE);
	rspamd_lua_ip_push(session->L, session->addr);
	lua_pushnumber(session->L, latency);

	/* TODO: check results maybe? */
	lua_pcall(session->L, 3, 0, 0);
}

#ifdef __GNUC__
static void
fuzzy_lua_push_error(struct fuzzy_lua_session *session, const char *err_fmt, ...) __attribute__((format(printf, 2, 3)));
#endif

static void
fuzzy_lua_push_error(struct fuzzy_lua_session *session, const char *err_fmt, ...)
{
	va_list v;

	va_start(v, err_fmt);
	lua_rawgeti(session->L, LUA_REGISTRYINDEX, session->cbref);
	lua_pushboolean(session->L, FALSE);
	rspamd_lua_ip_push(session->L, session->addr);
	lua_pushvfstring(session->L, err_fmt, v);
	va_end(v);

	/* TODO: check results maybe? */
	lua_pcall(session->L, 3, 0, 0);
}

static int
fuzzy_lua_try_read(struct fuzzy_lua_session *session)
{
	const struct rspamd_fuzzy_reply *rep;
	struct rspamd_fuzzy_cmd *cmd = NULL;
	struct fuzzy_cmd_io *io = NULL;
	int r, ret;
	unsigned char buf[2048], *p;

	if ((r = read(session->fd, buf, sizeof(buf) - 1)) == -1) {
		if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
			return 0;
		}
		else {
			fuzzy_lua_push_error(session, "cannot read from socket: %s", strerror(errno));
			return -1;
		}
	}
	else {
		p = buf;

		ret = 0;

		while ((rep = fuzzy_process_reply(&p, &r,
										  session->commands, session->rule, &cmd, &io, NULL)) != NULL) {

			if (rep->v1.prob > 0.5) {
				if (cmd->cmd == FUZZY_PING) {
					fuzzy_lua_push_result(session, fuzzy_milliseconds_since_midnight() - rep->v1.value);
				}
				else {
					fuzzy_lua_push_error(session, "unsupported");
				}
			}
			else {
				fuzzy_lua_push_error(session, "invalid reply from server: %d", rep->v1.value);
			}

			ret = 1;
		}
	}

	return ret;
}

/* Fuzzy check callback */
static void
fuzzy_lua_io_callback(int fd, short what, void *arg)
{
	struct fuzzy_lua_session *session = arg;
	int r;

	enum {
		return_error = 0,
		return_want_more,
		return_finished
	} ret = return_error;

	if (what & EV_READ) {
		/* Try to read reply */
		r = fuzzy_lua_try_read(session);

		switch (r) {
		case 0:
			if (what & EV_READ) {
				ret = return_want_more;
			}
			else {
				if (what & EV_WRITE) {
					/* Retransmit attempt */
					if (!fuzzy_cmd_vector_to_wire(fd, session->commands)) {
						fuzzy_lua_push_error(session, "cannot write to socket");
						ret = return_error;
					}
					else {
						ret = return_want_more;
					}
				}
			}
			break;
		case 1:
			ret = return_finished;
			break;
		default:
			ret = return_error;
			break;
		}
	}
	else if (what & EV_WRITE) {
		if (!fuzzy_cmd_vector_to_wire(fd, session->commands)) {
			fuzzy_lua_push_error(session, "cannot write to socket");
			ret = return_error;
		}
		else {
			ret = return_want_more;
		}
	}
	else {
		/* Timeout */
		fuzzy_lua_push_error(session, "timeout waiting for the reply");
		ret = return_error;
	}

	if (ret == return_want_more) {
		/* Processed write, switch to reading */
		rspamd_ev_watcher_reschedule(session->task->event_loop,
									 &session->ev, EV_READ);
	}
	else if (ret == return_error) {
		rspamd_session_remove_event(session->task->s, fuzzy_lua_session_fin, session);
	}
	else {
		/* Read something from network */
		if (!fuzzy_lua_session_is_completed(session)) {
			/* Need to read more */
			rspamd_ev_watcher_reschedule(session->task->event_loop,
										 &session->ev, EV_READ);
		}
	}
}

/***
 * @function fuzzy_check.ping_storage(task, callback, rule, timeout[, server_override])
 * @return
 */
static int
fuzzy_lua_ping_storage(lua_State *L)
{
	struct rspamd_task *task = lua_check_task(L, 1);

	if (task == NULL) {
		return luaL_error(L, "invalid arguments: task");
	}

	/* Other arguments sanity */
	if (lua_type(L, 2) != LUA_TFUNCTION || lua_type(L, 3) != LUA_TSTRING || lua_type(L, 4) != LUA_TNUMBER) {
		return luaL_error(L, "invalid arguments: callback/rule/timeout argument");
	}

	struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context(task->cfg);
	struct fuzzy_rule *rule, *rule_found = NULL;
	int i;
	const char *rule_name = lua_tostring(L, 3);

	PTR_ARRAY_FOREACH(fuzzy_module_ctx->fuzzy_rules, i, rule)
	{
		if (strcmp(rule->name, rule_name) == 0) {
			rule_found = rule;
			break;
		}
	}

	if (rule_found == NULL) {
		return luaL_error(L, "invalid arguments: no such rule defined");
	}

	rspamd_inet_addr_t *addr = NULL;

	if (lua_type(L, 5) == LUA_TSTRING) {
		const char *server_name = lua_tostring(L, 5);
		enum rspamd_parse_host_port_result res;
		GPtrArray *addrs = g_ptr_array_new();

		/* We resolve address synchronously here! Why? Because it is an override... */
		res = rspamd_parse_host_port_priority(server_name, &addrs, 0, NULL,
											  11335, FALSE, task->task_pool);

		if (res == RSPAMD_PARSE_ADDR_FAIL) {
			lua_pushboolean(L, FALSE);
			lua_pushfstring(L, "invalid arguments: cannot resolve %s", server_name);
			return 2;
		}

		/* Get random address */
		addr = rspamd_inet_address_copy(g_ptr_array_index(addrs, rspamd_random_uint64_fast() % addrs->len),
										task->task_pool);
		rspamd_mempool_add_destructor(task->task_pool,
									  rspamd_ptr_array_free_hard, addrs);
	}
	else {
		struct upstream *selected = rspamd_upstream_get(rule_found->read_servers,
														RSPAMD_UPSTREAM_ROUND_ROBIN, NULL, 0);
		addr = rspamd_upstream_addr_next(selected);
	}

	if (addr != NULL) {
		int sock;
		GPtrArray *commands = fuzzy_generate_commands(task, rule_found, FUZZY_PING, 0, 0, 0);

		if ((sock = rspamd_inet_address_connect(addr, SOCK_DGRAM, TRUE)) == -1) {
			lua_pushboolean(L, FALSE);
			lua_pushfstring(L, "cannot connect to %s, %s",
							rspamd_inet_address_to_string_pretty(addr),
							strerror(errno));
			return 2;
		}
		else {
			/* Create a dedicated ping session for a socket */
			struct fuzzy_lua_session *session =
				rspamd_mempool_alloc0(task->task_pool,
									  sizeof(struct fuzzy_lua_session));
			session->task = task;
			session->fd = sock;
			session->addr = addr;
			session->commands = commands;
			session->L = L;
			session->rule = rule_found;
			/* Store callback */
			lua_pushvalue(L, 2);
			session->cbref = luaL_ref(L, LUA_REGISTRYINDEX);

			rspamd_session_add_event(task->s, fuzzy_lua_session_fin, session, M);
			rspamd_ev_watcher_init(&session->ev,
								   sock,
								   EV_WRITE,
								   fuzzy_lua_io_callback,
								   session);
			rspamd_ev_watcher_start(session->task->event_loop, &session->ev,
									lua_tonumber(L, 4));
		}
	}

	lua_pushboolean(L, TRUE);
	return 1;
}
