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.

stat_config.c 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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 "stat_api.h"
  18. #include "rspamd.h"
  19. #include "cfg_rcl.h"
  20. #include "stat_internal.h"
  21. #include "lua/lua_common.h"
  22. static struct rspamd_stat_ctx *stat_ctx = NULL;
  23. static struct rspamd_stat_classifier lua_classifier = {
  24. .name = "lua",
  25. .init_func = lua_classifier_init,
  26. .classify_func = lua_classifier_classify,
  27. .learn_spam_func = lua_classifier_learn_spam,
  28. .fin_func = NULL,
  29. };
  30. static struct rspamd_stat_classifier stat_classifiers[] = {
  31. {
  32. .name = "bayes",
  33. .init_func = bayes_init,
  34. .classify_func = bayes_classify,
  35. .learn_spam_func = bayes_learn_spam,
  36. .fin_func = bayes_fin,
  37. }};
  38. static struct rspamd_stat_tokenizer stat_tokenizers[] = {
  39. {
  40. .name = "osb-text",
  41. .get_config = rspamd_tokenizer_osb_get_config,
  42. .tokenize_func = rspamd_tokenizer_osb,
  43. },
  44. {
  45. .name = "osb",
  46. .get_config = rspamd_tokenizer_osb_get_config,
  47. .tokenize_func = rspamd_tokenizer_osb,
  48. },
  49. };
  50. #define RSPAMD_STAT_BACKEND_ELT(nam, eltn) \
  51. { \
  52. .name = #nam, \
  53. .read_only = false, \
  54. .init = rspamd_##eltn##_init, \
  55. .runtime = rspamd_##eltn##_runtime, \
  56. .process_tokens = rspamd_##eltn##_process_tokens, \
  57. .finalize_process = rspamd_##eltn##_finalize_process, \
  58. .learn_tokens = rspamd_##eltn##_learn_tokens, \
  59. .finalize_learn = rspamd_##eltn##_finalize_learn, \
  60. .total_learns = rspamd_##eltn##_total_learns, \
  61. .inc_learns = rspamd_##eltn##_inc_learns, \
  62. .dec_learns = rspamd_##eltn##_dec_learns, \
  63. .get_stat = rspamd_##eltn##_get_stat, \
  64. .load_tokenizer_config = rspamd_##eltn##_load_tokenizer_config, \
  65. .close = rspamd_##eltn##_close \
  66. }
  67. #define RSPAMD_STAT_BACKEND_ELT_READONLY(nam, eltn) \
  68. { \
  69. .name = #nam, \
  70. .read_only = true, \
  71. .init = rspamd_##eltn##_init, \
  72. .runtime = rspamd_##eltn##_runtime, \
  73. .process_tokens = rspamd_##eltn##_process_tokens, \
  74. .finalize_process = rspamd_##eltn##_finalize_process, \
  75. .learn_tokens = NULL, \
  76. .finalize_learn = NULL, \
  77. .total_learns = rspamd_##eltn##_total_learns, \
  78. .inc_learns = NULL, \
  79. .dec_learns = NULL, \
  80. .get_stat = rspamd_##eltn##_get_stat, \
  81. .load_tokenizer_config = rspamd_##eltn##_load_tokenizer_config, \
  82. .close = rspamd_##eltn##_close \
  83. }
  84. static struct rspamd_stat_backend stat_backends[] = {
  85. RSPAMD_STAT_BACKEND_ELT(mmap, mmaped_file),
  86. RSPAMD_STAT_BACKEND_ELT(sqlite3, sqlite3),
  87. RSPAMD_STAT_BACKEND_ELT_READONLY(cdb, cdb),
  88. RSPAMD_STAT_BACKEND_ELT(redis, redis)};
  89. #define RSPAMD_STAT_CACHE_ELT(nam, eltn) \
  90. { \
  91. .name = #nam, \
  92. .init = rspamd_stat_cache_##eltn##_init, \
  93. .runtime = rspamd_stat_cache_##eltn##_runtime, \
  94. .check = rspamd_stat_cache_##eltn##_check, \
  95. .learn = rspamd_stat_cache_##eltn##_learn, \
  96. .close = rspamd_stat_cache_##eltn##_close \
  97. }
  98. static struct rspamd_stat_cache stat_caches[] = {
  99. RSPAMD_STAT_CACHE_ELT(sqlite3, sqlite3),
  100. RSPAMD_STAT_CACHE_ELT(redis, redis),
  101. };
  102. void rspamd_stat_init(struct rspamd_config *cfg, struct ev_loop *ev_base)
  103. {
  104. GList *cur, *curst;
  105. struct rspamd_classifier_config *clf;
  106. struct rspamd_statfile_config *stf;
  107. struct rspamd_stat_backend *bk;
  108. struct rspamd_statfile *st;
  109. struct rspamd_classifier *cl;
  110. const ucl_object_t *cache_obj = NULL, *cache_name_obj;
  111. const char *cache_name = NULL;
  112. lua_State *L = cfg->lua_state;
  113. unsigned int lua_classifiers_cnt = 0, i;
  114. gboolean skip_cache = FALSE;
  115. if (stat_ctx == NULL) {
  116. stat_ctx = g_malloc0(sizeof(*stat_ctx));
  117. }
  118. lua_getglobal(L, "rspamd_classifiers");
  119. if (lua_type(L, -1) == LUA_TTABLE) {
  120. lua_pushnil(L);
  121. while (lua_next(L, -2) != 0) {
  122. lua_classifiers_cnt++;
  123. lua_pop(L, 1);
  124. }
  125. }
  126. lua_pop(L, 1);
  127. stat_ctx->classifiers_count = G_N_ELEMENTS(stat_classifiers) +
  128. lua_classifiers_cnt;
  129. stat_ctx->classifiers_subrs = g_new0(struct rspamd_stat_classifier,
  130. stat_ctx->classifiers_count);
  131. for (i = 0; i < G_N_ELEMENTS(stat_classifiers); i++) {
  132. memcpy(&stat_ctx->classifiers_subrs[i], &stat_classifiers[i],
  133. sizeof(struct rspamd_stat_classifier));
  134. }
  135. lua_getglobal(L, "rspamd_classifiers");
  136. if (lua_type(L, -1) == LUA_TTABLE) {
  137. lua_pushnil(L);
  138. while (lua_next(L, -2) != 0) {
  139. lua_pushvalue(L, -2);
  140. memcpy(&stat_ctx->classifiers_subrs[i], &lua_classifier,
  141. sizeof(struct rspamd_stat_classifier));
  142. stat_ctx->classifiers_subrs[i].name = g_strdup(lua_tostring(L, -1));
  143. i++;
  144. lua_pop(L, 2);
  145. }
  146. }
  147. lua_pop(L, 1);
  148. stat_ctx->backends_subrs = stat_backends;
  149. stat_ctx->backends_count = G_N_ELEMENTS(stat_backends);
  150. stat_ctx->tokenizers_subrs = stat_tokenizers;
  151. stat_ctx->tokenizers_count = G_N_ELEMENTS(stat_tokenizers);
  152. stat_ctx->caches_subrs = stat_caches;
  153. stat_ctx->caches_count = G_N_ELEMENTS(stat_caches);
  154. stat_ctx->cfg = cfg;
  155. stat_ctx->statfiles = g_ptr_array_new();
  156. stat_ctx->classifiers = g_ptr_array_new();
  157. stat_ctx->async_elts = g_queue_new();
  158. stat_ctx->event_loop = ev_base;
  159. stat_ctx->lua_stat_tokens_ref = -1;
  160. /* Interact with lua_stat */
  161. if (luaL_dostring(L, "return require \"lua_stat\"") != 0) {
  162. msg_err_config("cannot require lua_stat: %s",
  163. lua_tostring(L, -1));
  164. }
  165. else {
  166. #if LUA_VERSION_NUM >= 504
  167. lua_settop(L, -2);
  168. #endif
  169. if (lua_type(L, -1) != LUA_TTABLE) {
  170. msg_err_config("lua stat must return "
  171. "table and not %s",
  172. lua_typename(L, lua_type(L, -1)));
  173. }
  174. else {
  175. lua_pushstring(L, "gen_stat_tokens");
  176. lua_gettable(L, -2);
  177. if (lua_type(L, -1) != LUA_TFUNCTION) {
  178. msg_err_config("gen_stat_tokens must return "
  179. "function and not %s",
  180. lua_typename(L, lua_type(L, -1)));
  181. }
  182. else {
  183. /* Call this function to obtain closure */
  184. int err_idx, ret;
  185. struct rspamd_config **pcfg;
  186. lua_pushcfunction(L, &rspamd_lua_traceback);
  187. err_idx = lua_gettop(L);
  188. lua_pushvalue(L, err_idx - 1);
  189. pcfg = lua_newuserdata(L, sizeof(*pcfg));
  190. *pcfg = cfg;
  191. rspamd_lua_setclass(L, rspamd_config_classname, -1);
  192. if ((ret = lua_pcall(L, 1, 1, err_idx)) != 0) {
  193. msg_err_config("call to gen_stat_tokens lua "
  194. "script failed (%d): %s",
  195. ret,
  196. lua_tostring(L, -1));
  197. }
  198. else {
  199. if (lua_type(L, -1) != LUA_TFUNCTION) {
  200. msg_err_config("gen_stat_tokens invocation must return "
  201. "function and not %s",
  202. lua_typename(L, lua_type(L, -1)));
  203. }
  204. else {
  205. stat_ctx->lua_stat_tokens_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  206. }
  207. }
  208. }
  209. }
  210. }
  211. /* Cleanup mess */
  212. lua_settop(L, 0);
  213. /* Create statfiles from the classifiers */
  214. cur = cfg->classifiers;
  215. while (cur) {
  216. bk = NULL;
  217. clf = cur->data;
  218. cl = g_malloc0(sizeof(*cl));
  219. cl->cfg = clf;
  220. cl->ctx = stat_ctx;
  221. cl->statfiles_ids = g_array_new(FALSE, FALSE, sizeof(int));
  222. cl->subrs = rspamd_stat_get_classifier(clf->classifier);
  223. if (cl->subrs == NULL) {
  224. g_free(cl);
  225. msg_err_config("cannot init classifier type %s", clf->name);
  226. cur = g_list_next(cur);
  227. continue;
  228. }
  229. if (!cl->subrs->init_func(cfg, ev_base, cl)) {
  230. g_free(cl);
  231. msg_err_config("cannot init classifier type %s", clf->name);
  232. cur = g_list_next(cur);
  233. continue;
  234. }
  235. if (!(clf->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND)) {
  236. bk = rspamd_stat_get_backend(clf->backend);
  237. if (bk == NULL) {
  238. msg_err_config("cannot get backend of type %s, so disable classifier"
  239. " %s completely",
  240. clf->backend, clf->name);
  241. cur = g_list_next(cur);
  242. continue;
  243. }
  244. }
  245. else {
  246. /* This actually is not implemented so it should never happen */
  247. g_free(cl);
  248. cur = g_list_next(cur);
  249. continue;
  250. }
  251. /* XXX:
  252. * Here we get the first classifier tokenizer config as the only one
  253. * We NO LONGER support multiple tokenizers per rspamd instance
  254. */
  255. if (stat_ctx->tkcf == NULL) {
  256. stat_ctx->tokenizer = rspamd_stat_get_tokenizer(clf->tokenizer->name);
  257. g_assert(stat_ctx->tokenizer != NULL);
  258. stat_ctx->tkcf = stat_ctx->tokenizer->get_config(cfg->cfg_pool,
  259. clf->tokenizer, NULL);
  260. }
  261. /* Init classifier cache */
  262. cache_name = NULL;
  263. if (!bk->read_only) {
  264. if (clf->opts) {
  265. cache_obj = ucl_object_lookup(clf->opts, "cache");
  266. cache_name_obj = NULL;
  267. if (cache_obj && ucl_object_type(cache_obj) == UCL_NULL) {
  268. skip_cache = TRUE;
  269. }
  270. else {
  271. if (cache_obj) {
  272. cache_name_obj = ucl_object_lookup_any(cache_obj,
  273. "name", "type", NULL);
  274. }
  275. if (cache_name_obj) {
  276. cache_name = ucl_object_tostring(cache_name_obj);
  277. }
  278. }
  279. }
  280. }
  281. else {
  282. skip_cache = true;
  283. }
  284. if (cache_name == NULL && !skip_cache) {
  285. /* We assume that learn cache is the same as backend */
  286. cache_name = clf->backend;
  287. }
  288. curst = clf->statfiles;
  289. while (curst) {
  290. stf = curst->data;
  291. st = g_malloc0(sizeof(*st));
  292. st->classifier = cl;
  293. st->stcf = stf;
  294. if (!(cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND)) {
  295. st->backend = bk;
  296. st->bkcf = bk->init(stat_ctx, cfg, st);
  297. msg_info_config("added backend %s for symbol %s",
  298. bk->name, stf->symbol);
  299. }
  300. else {
  301. msg_debug_config("added backend-less statfile for symbol %s",
  302. stf->symbol);
  303. }
  304. /* XXX: bad hack to pass statfiles configuration to cache */
  305. if (cl->cache == NULL && !skip_cache) {
  306. cl->cache = rspamd_stat_get_cache(cache_name);
  307. g_assert(cl->cache != NULL);
  308. cl->cachecf = cl->cache->init(stat_ctx, cfg, st, cache_obj);
  309. if (cl->cachecf == NULL) {
  310. msg_err_config("error adding cache %s for symbol %s",
  311. cl->cache->name, stf->symbol);
  312. cl->cache = NULL;
  313. }
  314. else {
  315. msg_debug_config("added cache %s for symbol %s",
  316. cl->cache->name, stf->symbol);
  317. }
  318. }
  319. if (st->bkcf == NULL &&
  320. !(cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND)) {
  321. msg_err_config("cannot init backend %s for statfile %s",
  322. clf->backend, stf->symbol);
  323. g_free(st);
  324. }
  325. else {
  326. st->id = stat_ctx->statfiles->len;
  327. g_ptr_array_add(stat_ctx->statfiles, st);
  328. g_array_append_val(cl->statfiles_ids, st->id);
  329. }
  330. curst = curst->next;
  331. }
  332. g_ptr_array_add(stat_ctx->classifiers, cl);
  333. cur = cur->next;
  334. }
  335. }
  336. void rspamd_stat_close(void)
  337. {
  338. struct rspamd_classifier *cl;
  339. struct rspamd_statfile *st;
  340. struct rspamd_stat_ctx *st_ctx;
  341. struct rspamd_stat_async_elt *aelt;
  342. GList *cur;
  343. unsigned int i, j;
  344. int id;
  345. st_ctx = rspamd_stat_get_ctx();
  346. g_assert(st_ctx != NULL);
  347. for (i = 0; i < st_ctx->classifiers->len; i++) {
  348. cl = g_ptr_array_index(st_ctx->classifiers, i);
  349. for (j = 0; j < cl->statfiles_ids->len; j++) {
  350. id = g_array_index(cl->statfiles_ids, int, j);
  351. st = g_ptr_array_index(st_ctx->statfiles, id);
  352. if (!(st->classifier->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND)) {
  353. st->backend->close(st->bkcf);
  354. }
  355. g_free(st);
  356. }
  357. if (cl->cache && cl->cachecf) {
  358. cl->cache->close(cl->cachecf);
  359. }
  360. g_array_free(cl->statfiles_ids, TRUE);
  361. if (cl->subrs->fin_func) {
  362. cl->subrs->fin_func(cl);
  363. }
  364. g_free(cl);
  365. }
  366. cur = st_ctx->async_elts->head;
  367. while (cur) {
  368. aelt = cur->data;
  369. REF_RELEASE(aelt);
  370. cur = g_list_next(cur);
  371. }
  372. g_queue_free(stat_ctx->async_elts);
  373. g_ptr_array_free(st_ctx->statfiles, TRUE);
  374. g_ptr_array_free(st_ctx->classifiers, TRUE);
  375. if (st_ctx->lua_stat_tokens_ref != -1) {
  376. luaL_unref(st_ctx->cfg->lua_state, LUA_REGISTRYINDEX,
  377. st_ctx->lua_stat_tokens_ref);
  378. }
  379. g_free(st_ctx->classifiers_subrs);
  380. g_free(st_ctx);
  381. /* Set global var to NULL */
  382. stat_ctx = NULL;
  383. }
  384. struct rspamd_stat_ctx *
  385. rspamd_stat_get_ctx(void)
  386. {
  387. return stat_ctx;
  388. }
  389. struct rspamd_stat_classifier *
  390. rspamd_stat_get_classifier(const char *name)
  391. {
  392. unsigned int i;
  393. if (name == NULL || name[0] == '\0') {
  394. name = RSPAMD_DEFAULT_CLASSIFIER;
  395. }
  396. for (i = 0; i < stat_ctx->classifiers_count; i++) {
  397. if (strcmp(name, stat_ctx->classifiers_subrs[i].name) == 0) {
  398. return &stat_ctx->classifiers_subrs[i];
  399. }
  400. }
  401. msg_err("cannot find classifier named %s", name);
  402. return NULL;
  403. }
  404. struct rspamd_stat_backend *
  405. rspamd_stat_get_backend(const char *name)
  406. {
  407. unsigned int i;
  408. if (name == NULL || name[0] == '\0') {
  409. name = RSPAMD_DEFAULT_BACKEND;
  410. }
  411. for (i = 0; i < stat_ctx->backends_count; i++) {
  412. if (strcmp(name, stat_ctx->backends_subrs[i].name) == 0) {
  413. return &stat_ctx->backends_subrs[i];
  414. }
  415. }
  416. msg_err("cannot find backend named %s", name);
  417. return NULL;
  418. }
  419. struct rspamd_stat_tokenizer *
  420. rspamd_stat_get_tokenizer(const char *name)
  421. {
  422. unsigned int i;
  423. if (name == NULL || name[0] == '\0') {
  424. name = RSPAMD_DEFAULT_TOKENIZER;
  425. }
  426. for (i = 0; i < stat_ctx->tokenizers_count; i++) {
  427. if (strcmp(name, stat_ctx->tokenizers_subrs[i].name) == 0) {
  428. return &stat_ctx->tokenizers_subrs[i];
  429. }
  430. }
  431. msg_err("cannot find tokenizer named %s", name);
  432. return NULL;
  433. }
  434. struct rspamd_stat_cache *
  435. rspamd_stat_get_cache(const char *name)
  436. {
  437. unsigned int i;
  438. if (name == NULL || name[0] == '\0') {
  439. name = RSPAMD_DEFAULT_CACHE;
  440. }
  441. for (i = 0; i < stat_ctx->caches_count; i++) {
  442. if (strcmp(name, stat_ctx->caches_subrs[i].name) == 0) {
  443. return &stat_ctx->caches_subrs[i];
  444. }
  445. }
  446. msg_err("cannot find cache named %s", name);
  447. return NULL;
  448. }
  449. static void
  450. rspamd_async_elt_dtor(struct rspamd_stat_async_elt *elt)
  451. {
  452. if (elt->cleanup) {
  453. elt->cleanup(elt, elt->ud);
  454. }
  455. ev_timer_stop(elt->event_loop, &elt->timer_ev);
  456. g_free(elt);
  457. }
  458. static void
  459. rspamd_async_elt_on_timer(EV_P_ ev_timer *w, int revents)
  460. {
  461. struct rspamd_stat_async_elt *elt = (struct rspamd_stat_async_elt *) w->data;
  462. double jittered_time;
  463. if (elt->enabled) {
  464. elt->handler(elt, elt->ud);
  465. }
  466. jittered_time = rspamd_time_jitter(elt->timeout, 0);
  467. elt->timer_ev.repeat = jittered_time;
  468. ev_timer_again(EV_A_ w);
  469. }
  470. struct rspamd_stat_async_elt *
  471. rspamd_stat_ctx_register_async(rspamd_stat_async_handler handler,
  472. rspamd_stat_async_cleanup cleanup,
  473. gpointer d,
  474. double timeout)
  475. {
  476. struct rspamd_stat_async_elt *elt;
  477. struct rspamd_stat_ctx *st_ctx;
  478. st_ctx = rspamd_stat_get_ctx();
  479. g_assert(st_ctx != NULL);
  480. elt = g_malloc0(sizeof(*elt));
  481. elt->handler = handler;
  482. elt->cleanup = cleanup;
  483. elt->ud = d;
  484. elt->timeout = timeout;
  485. elt->event_loop = st_ctx->event_loop;
  486. REF_INIT_RETAIN(elt, rspamd_async_elt_dtor);
  487. /* Enabled by default */
  488. if (st_ctx->event_loop) {
  489. elt->enabled = TRUE;
  490. /*
  491. * First we set timeval to zero as we want cb to be executed as
  492. * fast as possible
  493. */
  494. elt->timer_ev.data = elt;
  495. ev_timer_init(&elt->timer_ev, rspamd_async_elt_on_timer,
  496. 0.1, 0.0);
  497. ev_timer_start(st_ctx->event_loop, &elt->timer_ev);
  498. }
  499. else {
  500. elt->enabled = FALSE;
  501. }
  502. g_queue_push_tail(st_ctx->async_elts, elt);
  503. return elt;
  504. }