You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redis_cache.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "learn_cache.h"
  18. #include "rspamd.h"
  19. #include "stat_api.h"
  20. #include "stat_internal.h"
  21. #include "cryptobox.h"
  22. #include "ucl.h"
  23. #include "hiredis.h"
  24. #include "adapters/libev.h"
  25. #include "lua/lua_common.h"
  26. #include "libmime/message.h"
  27. #define REDIS_DEFAULT_TIMEOUT 0.5
  28. #define REDIS_STAT_TIMEOUT 30
  29. #define REDIS_DEFAULT_PORT 6379
  30. #define DEFAULT_REDIS_KEY "learned_ids"
  31. static const gchar *M = "redis learn cache";
  32. struct rspamd_redis_cache_ctx {
  33. lua_State *L;
  34. struct rspamd_statfile_config *stcf;
  35. const gchar *password;
  36. const gchar *dbname;
  37. const gchar *redis_object;
  38. gdouble timeout;
  39. gint conf_ref;
  40. };
  41. struct rspamd_redis_cache_runtime {
  42. struct rspamd_redis_cache_ctx *ctx;
  43. struct rspamd_task *task;
  44. struct upstream *selected;
  45. ev_timer timer_ev;
  46. redisAsyncContext *redis;
  47. gboolean has_event;
  48. };
  49. static GQuark
  50. rspamd_stat_cache_redis_quark (void)
  51. {
  52. return g_quark_from_static_string (M);
  53. }
  54. static inline struct upstream_list *
  55. rspamd_redis_get_servers (struct rspamd_redis_cache_ctx *ctx,
  56. const gchar *what)
  57. {
  58. lua_State *L = ctx->L;
  59. struct upstream_list *res;
  60. lua_rawgeti (L, LUA_REGISTRYINDEX, ctx->conf_ref);
  61. lua_pushstring (L, what);
  62. lua_gettable (L, -2);
  63. res = *((struct upstream_list**)lua_touserdata (L, -1));
  64. lua_settop (L, 0);
  65. return res;
  66. }
  67. static void
  68. rspamd_redis_cache_maybe_auth (struct rspamd_redis_cache_ctx *ctx,
  69. redisAsyncContext *redis)
  70. {
  71. if (ctx->password) {
  72. redisAsyncCommand (redis, NULL, NULL, "AUTH %s", ctx->password);
  73. }
  74. if (ctx->dbname) {
  75. redisAsyncCommand (redis, NULL, NULL, "SELECT %s", ctx->dbname);
  76. }
  77. }
  78. /* Called on connection termination */
  79. static void
  80. rspamd_redis_cache_fin (gpointer data)
  81. {
  82. struct rspamd_redis_cache_runtime *rt = data;
  83. redisAsyncContext *redis;
  84. rt->has_event = FALSE;
  85. ev_timer_stop (rt->task->event_loop, &rt->timer_ev);
  86. if (rt->redis) {
  87. redis = rt->redis;
  88. rt->redis = NULL;
  89. /* This calls for all callbacks pending */
  90. redisAsyncFree (redis);
  91. }
  92. }
  93. static void
  94. rspamd_redis_cache_timeout (EV_P_ ev_timer *w, int revents)
  95. {
  96. struct rspamd_redis_cache_runtime *rt =
  97. (struct rspamd_redis_cache_runtime *)w->data;
  98. struct rspamd_task *task;
  99. task = rt->task;
  100. msg_err_task ("connection to redis server %s timed out",
  101. rspamd_upstream_name (rt->selected));
  102. rspamd_upstream_fail (rt->selected, FALSE, "timeout");
  103. if (rt->has_event) {
  104. rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, rt);
  105. }
  106. }
  107. /* Called when we have checked the specified message id */
  108. static void
  109. rspamd_stat_cache_redis_get (redisAsyncContext *c, gpointer r, gpointer priv)
  110. {
  111. struct rspamd_redis_cache_runtime *rt = priv;
  112. redisReply *reply = r;
  113. struct rspamd_task *task;
  114. glong val = 0;
  115. task = rt->task;
  116. if (c->err == 0) {
  117. if (reply) {
  118. if (G_LIKELY (reply->type == REDIS_REPLY_INTEGER)) {
  119. val = reply->integer;
  120. }
  121. else if (reply->type == REDIS_REPLY_STRING) {
  122. rspamd_strtol (reply->str, reply->len, &val);
  123. }
  124. else {
  125. if (reply->type != REDIS_REPLY_NIL) {
  126. msg_err_task ("bad learned type for %s: %d",
  127. rt->ctx->stcf->symbol, reply->type);
  128. }
  129. val = 0;
  130. }
  131. }
  132. if ((val > 0 && (task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM)) ||
  133. (val < 0 && (task->flags & RSPAMD_TASK_FLAG_LEARN_HAM))) {
  134. /* Already learned */
  135. msg_info_task ("<%s> has been already "
  136. "learned as %s, ignore it", MESSAGE_FIELD (task, message_id),
  137. (task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM) ? "spam" : "ham");
  138. task->flags |= RSPAMD_TASK_FLAG_ALREADY_LEARNED;
  139. }
  140. else if (val != 0) {
  141. /* Unlearn flag */
  142. task->flags |= RSPAMD_TASK_FLAG_UNLEARN;
  143. }
  144. rspamd_upstream_ok (rt->selected);
  145. }
  146. else {
  147. rspamd_upstream_fail (rt->selected, FALSE, c->errstr);
  148. }
  149. if (rt->has_event) {
  150. rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, rt);
  151. }
  152. }
  153. /* Called when we have learned the specified message id */
  154. static void
  155. rspamd_stat_cache_redis_set (redisAsyncContext *c, gpointer r, gpointer priv)
  156. {
  157. struct rspamd_redis_cache_runtime *rt = priv;
  158. struct rspamd_task *task;
  159. task = rt->task;
  160. if (c->err == 0) {
  161. /* XXX: we ignore results here */
  162. rspamd_upstream_ok (rt->selected);
  163. }
  164. else {
  165. rspamd_upstream_fail (rt->selected, FALSE, c->errstr);
  166. }
  167. if (rt->has_event) {
  168. rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, rt);
  169. }
  170. }
  171. static void
  172. rspamd_stat_cache_redis_generate_id (struct rspamd_task *task)
  173. {
  174. rspamd_cryptobox_hash_state_t st;
  175. rspamd_token_t *tok;
  176. guint i;
  177. guchar out[rspamd_cryptobox_HASHBYTES];
  178. gchar *b32out;
  179. gchar *user = NULL;
  180. rspamd_cryptobox_hash_init (&st, NULL, 0);
  181. user = rspamd_mempool_get_variable (task->task_pool, "stat_user");
  182. /* Use dedicated hash space for per users cache */
  183. if (user != NULL) {
  184. rspamd_cryptobox_hash_update (&st, user, strlen (user));
  185. }
  186. for (i = 0; i < task->tokens->len; i ++) {
  187. tok = g_ptr_array_index (task->tokens, i);
  188. rspamd_cryptobox_hash_update (&st, (guchar *)&tok->data,
  189. sizeof (tok->data));
  190. }
  191. rspamd_cryptobox_hash_final (&st, out);
  192. b32out = rspamd_encode_base32 (out, sizeof (out));
  193. g_assert (b32out != NULL);
  194. rspamd_mempool_set_variable (task->task_pool, "words_hash", b32out, g_free);
  195. }
  196. gpointer
  197. rspamd_stat_cache_redis_init (struct rspamd_stat_ctx *ctx,
  198. struct rspamd_config *cfg,
  199. struct rspamd_statfile *st,
  200. const ucl_object_t *cf)
  201. {
  202. struct rspamd_redis_cache_ctx *cache_ctx;
  203. struct rspamd_statfile_config *stf = st->stcf;
  204. const ucl_object_t *obj;
  205. gboolean ret = FALSE;
  206. lua_State *L = (lua_State *)cfg->lua_state;
  207. gint conf_ref = -1;
  208. cache_ctx = g_malloc0 (sizeof (*cache_ctx));
  209. cache_ctx->timeout = REDIS_DEFAULT_TIMEOUT;
  210. cache_ctx->L = L;
  211. /* First search in backend configuration */
  212. obj = ucl_object_lookup (st->classifier->cfg->opts, "backend");
  213. if (obj != NULL && ucl_object_type (obj) == UCL_OBJECT) {
  214. ret = rspamd_lua_try_load_redis (L, obj, cfg, &conf_ref);
  215. }
  216. /* Now try statfiles config */
  217. if (!ret && stf->opts) {
  218. ret = rspamd_lua_try_load_redis (L, stf->opts, cfg, &conf_ref);
  219. }
  220. /* Now try classifier config */
  221. if (!ret && st->classifier->cfg->opts) {
  222. ret = rspamd_lua_try_load_redis (L, st->classifier->cfg->opts, cfg, &conf_ref);
  223. }
  224. /* Now try global redis settings */
  225. if (!ret) {
  226. obj = ucl_object_lookup (cfg->rcl_obj, "redis");
  227. if (obj) {
  228. const ucl_object_t *specific_obj;
  229. specific_obj = ucl_object_lookup (obj, "statistics");
  230. if (specific_obj) {
  231. ret = rspamd_lua_try_load_redis (L,
  232. specific_obj, cfg, &conf_ref);
  233. }
  234. else {
  235. ret = rspamd_lua_try_load_redis (L,
  236. obj, cfg, &conf_ref);
  237. }
  238. }
  239. }
  240. if (!ret) {
  241. msg_err_config ("cannot init redis cache for %s", stf->symbol);
  242. g_free (cache_ctx);
  243. return NULL;
  244. }
  245. obj = ucl_object_lookup (st->classifier->cfg->opts, "cache_key");
  246. if (obj) {
  247. cache_ctx->redis_object = ucl_object_tostring (obj);
  248. }
  249. else {
  250. cache_ctx->redis_object = DEFAULT_REDIS_KEY;
  251. }
  252. cache_ctx->conf_ref = conf_ref;
  253. /* Check some common table values */
  254. lua_rawgeti (L, LUA_REGISTRYINDEX, conf_ref);
  255. lua_pushstring (L, "timeout");
  256. lua_gettable (L, -2);
  257. if (lua_type (L, -1) == LUA_TNUMBER) {
  258. cache_ctx->timeout = lua_tonumber (L, -1);
  259. }
  260. lua_pop (L, 1);
  261. lua_pushstring (L, "db");
  262. lua_gettable (L, -2);
  263. if (lua_type (L, -1) == LUA_TSTRING) {
  264. cache_ctx->dbname = rspamd_mempool_strdup (cfg->cfg_pool,
  265. lua_tostring (L, -1));
  266. }
  267. lua_pop (L, 1);
  268. lua_pushstring (L, "password");
  269. lua_gettable (L, -2);
  270. if (lua_type (L, -1) == LUA_TSTRING) {
  271. cache_ctx->password = rspamd_mempool_strdup (cfg->cfg_pool,
  272. lua_tostring (L, -1));
  273. }
  274. lua_pop (L, 1);
  275. lua_settop (L, 0);
  276. cache_ctx->stcf = stf;
  277. return (gpointer)cache_ctx;
  278. }
  279. gpointer
  280. rspamd_stat_cache_redis_runtime (struct rspamd_task *task,
  281. gpointer c, gboolean learn)
  282. {
  283. struct rspamd_redis_cache_ctx *ctx = c;
  284. struct rspamd_redis_cache_runtime *rt;
  285. struct upstream *up;
  286. struct upstream_list *ups;
  287. rspamd_inet_addr_t *addr;
  288. g_assert (ctx != NULL);
  289. if (task->tokens == NULL || task->tokens->len == 0) {
  290. return NULL;
  291. }
  292. if (learn) {
  293. ups = rspamd_redis_get_servers (ctx, "write_servers");
  294. if (!ups) {
  295. msg_err_task ("no write servers defined for %s, cannot learn",
  296. ctx->stcf->symbol);
  297. return NULL;
  298. }
  299. up = rspamd_upstream_get (ups,
  300. RSPAMD_UPSTREAM_MASTER_SLAVE,
  301. NULL,
  302. 0);
  303. }
  304. else {
  305. ups = rspamd_redis_get_servers (ctx, "read_servers");
  306. if (!ups) {
  307. msg_err_task ("no read servers defined for %s, cannot check",
  308. ctx->stcf->symbol);
  309. return NULL;
  310. }
  311. up = rspamd_upstream_get (ups,
  312. RSPAMD_UPSTREAM_ROUND_ROBIN,
  313. NULL,
  314. 0);
  315. }
  316. if (up == NULL) {
  317. msg_err_task ("no upstreams reachable");
  318. return NULL;
  319. }
  320. rt = rspamd_mempool_alloc0 (task->task_pool, sizeof (*rt));
  321. rt->selected = up;
  322. rt->task = task;
  323. rt->ctx = ctx;
  324. addr = rspamd_upstream_addr_next (up);
  325. g_assert (addr != NULL);
  326. if (rspamd_inet_address_get_af (addr) == AF_UNIX) {
  327. rt->redis = redisAsyncConnectUnix (rspamd_inet_address_to_string (addr));
  328. }
  329. else {
  330. rt->redis = redisAsyncConnect (rspamd_inet_address_to_string (addr),
  331. rspamd_inet_address_get_port (addr));
  332. }
  333. if (rt->redis == NULL) {
  334. msg_warn_task ("cannot connect to redis server %s: %s",
  335. rspamd_inet_address_to_string_pretty (addr),
  336. strerror (errno));
  337. return NULL;
  338. }
  339. else if (rt->redis->err != REDIS_OK) {
  340. msg_warn_task ("cannot connect to redis server %s: %s",
  341. rspamd_inet_address_to_string_pretty (addr),
  342. rt->redis->errstr);
  343. redisAsyncFree (rt->redis);
  344. rt->redis = NULL;
  345. return NULL;
  346. }
  347. redisLibevAttach (task->event_loop, rt->redis);
  348. /* Now check stats */
  349. rt->timer_ev.data = rt;
  350. ev_timer_init (&rt->timer_ev, rspamd_redis_cache_timeout,
  351. rt->ctx->timeout, 0.0);
  352. rspamd_redis_cache_maybe_auth (ctx, rt->redis);
  353. if (!learn) {
  354. rspamd_stat_cache_redis_generate_id (task);
  355. }
  356. return rt;
  357. }
  358. gint
  359. rspamd_stat_cache_redis_check (struct rspamd_task *task,
  360. gboolean is_spam,
  361. gpointer runtime)
  362. {
  363. struct rspamd_redis_cache_runtime *rt = runtime;
  364. gchar *h;
  365. if (rspamd_session_blocked (task->s)) {
  366. return RSPAMD_LEARN_INGORE;
  367. }
  368. h = rspamd_mempool_get_variable (task->task_pool, "words_hash");
  369. if (h == NULL) {
  370. return RSPAMD_LEARN_INGORE;
  371. }
  372. if (redisAsyncCommand (rt->redis, rspamd_stat_cache_redis_get, rt,
  373. "HGET %s %s",
  374. rt->ctx->redis_object, h) == REDIS_OK) {
  375. rspamd_session_add_event (task->s,
  376. rspamd_redis_cache_fin,
  377. rt,
  378. M);
  379. ev_timer_start (rt->task->event_loop, &rt->timer_ev);
  380. rt->has_event = TRUE;
  381. }
  382. /* We need to return OK every time */
  383. return RSPAMD_LEARN_OK;
  384. }
  385. gint
  386. rspamd_stat_cache_redis_learn (struct rspamd_task *task,
  387. gboolean is_spam,
  388. gpointer runtime)
  389. {
  390. struct rspamd_redis_cache_runtime *rt = runtime;
  391. gchar *h;
  392. gint flag;
  393. if (rt == NULL || rt->ctx == NULL || rspamd_session_blocked (task->s)) {
  394. return RSPAMD_LEARN_INGORE;
  395. }
  396. h = rspamd_mempool_get_variable (task->task_pool, "words_hash");
  397. g_assert (h != NULL);
  398. flag = (task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM) ? 1 : -1;
  399. if (redisAsyncCommand (rt->redis, rspamd_stat_cache_redis_set, rt,
  400. "HSET %s %s %d",
  401. rt->ctx->redis_object, h, flag) == REDIS_OK) {
  402. rspamd_session_add_event (task->s,
  403. rspamd_redis_cache_fin, rt, M);
  404. ev_timer_start (rt->task->event_loop, &rt->timer_ev);
  405. rt->has_event = TRUE;
  406. }
  407. /* We need to return OK every time */
  408. return RSPAMD_LEARN_OK;
  409. }
  410. void
  411. rspamd_stat_cache_redis_close (gpointer c)
  412. {
  413. struct rspamd_redis_cache_ctx *ctx = (struct rspamd_redis_cache_ctx *)c;
  414. lua_State *L;
  415. L = ctx->L;
  416. if (ctx->conf_ref) {
  417. luaL_unref (L, LUA_REGISTRYINDEX, ctx->conf_ref);
  418. }
  419. g_free (ctx);
  420. }