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_process.c 31KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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 "stat_internal.h"
  20. #include "libmime/message.h"
  21. #include "libmime/images.h"
  22. #include "libserver/html/html.h"
  23. #include "lua/lua_common.h"
  24. #include "libserver/mempool_vars_internal.h"
  25. #include "utlist.h"
  26. #include <math.h>
  27. #define RSPAMD_CLASSIFY_OP 0
  28. #define RSPAMD_LEARN_OP 1
  29. #define RSPAMD_UNLEARN_OP 2
  30. static const gdouble similarity_threshold = 80.0;
  31. static void
  32. rspamd_stat_tokenize_parts_metadata (struct rspamd_stat_ctx *st_ctx,
  33. struct rspamd_task *task)
  34. {
  35. GArray *ar;
  36. rspamd_stat_token_t elt;
  37. guint i;
  38. lua_State *L = task->cfg->lua_state;
  39. ar = g_array_sized_new (FALSE, FALSE, sizeof (elt), 16);
  40. memset (&elt, 0, sizeof (elt));
  41. elt.flags = RSPAMD_STAT_TOKEN_FLAG_META;
  42. if (st_ctx->lua_stat_tokens_ref != -1) {
  43. gint err_idx, ret;
  44. struct rspamd_task **ptask;
  45. lua_pushcfunction (L, &rspamd_lua_traceback);
  46. err_idx = lua_gettop (L);
  47. lua_rawgeti (L, LUA_REGISTRYINDEX, st_ctx->lua_stat_tokens_ref);
  48. ptask = lua_newuserdata (L, sizeof (*ptask));
  49. *ptask = task;
  50. rspamd_lua_setclass (L, "rspamd{task}", -1);
  51. if ((ret = lua_pcall (L, 1, 1, err_idx)) != 0) {
  52. msg_err_task ("call to stat_tokens lua "
  53. "script failed (%d): %s", ret, lua_tostring (L, -1));
  54. }
  55. else {
  56. if (lua_type (L, -1) != LUA_TTABLE) {
  57. msg_err_task ("stat_tokens invocation must return "
  58. "table and not %s",
  59. lua_typename (L, lua_type (L, -1)));
  60. }
  61. else {
  62. guint vlen;
  63. rspamd_ftok_t tok;
  64. vlen = rspamd_lua_table_size (L, -1);
  65. for (i = 0; i < vlen; i ++) {
  66. lua_rawgeti (L, -1, i + 1);
  67. tok.begin = lua_tolstring (L, -1, &tok.len);
  68. if (tok.begin && tok.len > 0) {
  69. elt.original.begin =
  70. rspamd_mempool_ftokdup (task->task_pool, &tok);
  71. elt.original.len = tok.len;
  72. elt.stemmed.begin = elt.original.begin;
  73. elt.stemmed.len = elt.original.len;
  74. elt.normalized.begin = elt.original.begin;
  75. elt.normalized.len = elt.original.len;
  76. g_array_append_val (ar, elt);
  77. }
  78. lua_pop (L, 1);
  79. }
  80. }
  81. }
  82. lua_settop (L, 0);
  83. }
  84. if (ar->len > 0) {
  85. st_ctx->tokenizer->tokenize_func (st_ctx,
  86. task,
  87. ar,
  88. TRUE,
  89. "M",
  90. task->tokens);
  91. }
  92. rspamd_mempool_add_destructor (task->task_pool,
  93. rspamd_array_free_hard, ar);
  94. }
  95. /*
  96. * Tokenize task using the tokenizer specified
  97. */
  98. void
  99. rspamd_stat_process_tokenize (struct rspamd_stat_ctx *st_ctx,
  100. struct rspamd_task *task)
  101. {
  102. struct rspamd_mime_text_part *part;
  103. rspamd_cryptobox_hash_state_t hst;
  104. rspamd_token_t *st_tok;
  105. guint i, reserved_len = 0;
  106. gdouble *pdiff;
  107. guchar hout[rspamd_cryptobox_HASHBYTES];
  108. gchar *b32_hout;
  109. if (st_ctx == NULL) {
  110. st_ctx = rspamd_stat_get_ctx ();
  111. }
  112. g_assert (st_ctx != NULL);
  113. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, text_parts), i, part) {
  114. if (!IS_TEXT_PART_EMPTY (part) && part->utf_words != NULL) {
  115. reserved_len += part->utf_words->len;
  116. }
  117. /* XXX: normal window size */
  118. reserved_len += 5;
  119. }
  120. task->tokens = g_ptr_array_sized_new (reserved_len);
  121. rspamd_mempool_add_destructor (task->task_pool,
  122. rspamd_ptr_array_free_hard, task->tokens);
  123. rspamd_mempool_notify_alloc (task->task_pool, reserved_len * sizeof (gpointer));
  124. pdiff = rspamd_mempool_get_variable (task->task_pool, "parts_distance");
  125. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, text_parts), i, part) {
  126. if (!IS_TEXT_PART_EMPTY (part) && part->utf_words != NULL) {
  127. st_ctx->tokenizer->tokenize_func (st_ctx, task,
  128. part->utf_words, IS_TEXT_PART_UTF (part),
  129. NULL, task->tokens);
  130. }
  131. if (pdiff != NULL && (1.0 - *pdiff) * 100.0 > similarity_threshold) {
  132. msg_debug_bayes ("message has two common parts (%.2f), so skip the last one",
  133. *pdiff);
  134. break;
  135. }
  136. }
  137. if (task->meta_words != NULL) {
  138. st_ctx->tokenizer->tokenize_func (st_ctx,
  139. task,
  140. task->meta_words,
  141. TRUE,
  142. "SUBJECT",
  143. task->tokens);
  144. }
  145. rspamd_stat_tokenize_parts_metadata (st_ctx, task);
  146. /* Produce signature */
  147. rspamd_cryptobox_hash_init (&hst, NULL, 0);
  148. PTR_ARRAY_FOREACH (task->tokens, i, st_tok) {
  149. rspamd_cryptobox_hash_update (&hst, (guchar *)&st_tok->data,
  150. sizeof (st_tok->data));
  151. }
  152. rspamd_cryptobox_hash_final (&hst, hout);
  153. b32_hout = rspamd_encode_base32 (hout, sizeof (hout), RSPAMD_BASE32_DEFAULT);
  154. /*
  155. * We need to strip it to 32 characters providing ~160 bits of
  156. * hash distribution
  157. */
  158. b32_hout[32] = '\0';
  159. rspamd_mempool_set_variable (task->task_pool, RSPAMD_MEMPOOL_STAT_SIGNATURE,
  160. b32_hout, g_free);
  161. }
  162. static gboolean
  163. rspamd_stat_classifier_is_skipped (struct rspamd_task *task,
  164. struct rspamd_classifier *cl, gboolean is_learn, gboolean is_spam)
  165. {
  166. GList *cur = is_learn ? cl->cfg->learn_conditions : cl->cfg->classify_conditions;
  167. lua_State *L = task->cfg->lua_state;
  168. gboolean ret = FALSE;
  169. while (cur) {
  170. gint cb_ref = GPOINTER_TO_INT (cur->data);
  171. gint old_top = lua_gettop (L);
  172. gint nargs;
  173. lua_rawgeti (L, LUA_REGISTRYINDEX, cb_ref);
  174. /* Push task and two booleans: is_spam and is_unlearn */
  175. struct rspamd_task **ptask = lua_newuserdata (L, sizeof (*ptask));
  176. *ptask = task;
  177. rspamd_lua_setclass (L, "rspamd{task}", -1);
  178. if (is_learn) {
  179. lua_pushboolean(L, is_spam);
  180. lua_pushboolean(L,
  181. task->flags & RSPAMD_TASK_FLAG_UNLEARN ? true : false);
  182. nargs = 3;
  183. }
  184. else {
  185. nargs = 1;
  186. }
  187. if (lua_pcall (L, nargs, LUA_MULTRET, 0) != 0) {
  188. msg_err_task ("call to %s failed: %s",
  189. "condition callback",
  190. lua_tostring (L, -1));
  191. }
  192. else {
  193. if (lua_isboolean (L, 1)) {
  194. if (!lua_toboolean (L, 1)) {
  195. ret = TRUE;
  196. }
  197. }
  198. if (lua_isstring (L, 2)) {
  199. if (ret) {
  200. msg_notice_task ("%s condition for classifier %s returned: %s; skip classifier",
  201. is_learn ? "learn" : "classify", cl->cfg->name,
  202. lua_tostring(L, 2));
  203. }
  204. else {
  205. msg_info_task ("%s condition for classifier %s returned: %s",
  206. is_learn ? "learn" : "classify", cl->cfg->name,
  207. lua_tostring(L, 2));
  208. }
  209. }
  210. else if (ret) {
  211. msg_notice_task("%s condition for classifier %s returned false; skip classifier",
  212. is_learn ? "learn" : "classify", cl->cfg->name);
  213. }
  214. if (ret) {
  215. lua_settop (L, old_top);
  216. break;
  217. }
  218. }
  219. lua_settop (L, old_top);
  220. cur = g_list_next (cur);
  221. }
  222. return ret;
  223. }
  224. static void
  225. rspamd_stat_preprocess (struct rspamd_stat_ctx *st_ctx,
  226. struct rspamd_task *task, gboolean is_learn, gboolean is_spam)
  227. {
  228. guint i;
  229. struct rspamd_statfile *st;
  230. gpointer bk_run;
  231. if (task->tokens == NULL) {
  232. rspamd_stat_process_tokenize (st_ctx, task);
  233. }
  234. task->stat_runtimes = g_ptr_array_sized_new (st_ctx->statfiles->len);
  235. g_ptr_array_set_size (task->stat_runtimes, st_ctx->statfiles->len);
  236. rspamd_mempool_add_destructor (task->task_pool,
  237. rspamd_ptr_array_free_hard, task->stat_runtimes);
  238. /* Temporary set all stat_runtimes to some max size to distinguish from NULL */
  239. for (i = 0; i < st_ctx->statfiles->len; i ++) {
  240. g_ptr_array_index (task->stat_runtimes, i) = GSIZE_TO_POINTER(G_MAXSIZE);
  241. }
  242. for (i = 0; i < st_ctx->classifiers->len; i++) {
  243. struct rspamd_classifier *cl = g_ptr_array_index (st_ctx->classifiers, i);
  244. gboolean skip_classifier = FALSE;
  245. if (cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND) {
  246. skip_classifier = TRUE;
  247. }
  248. else {
  249. if (rspamd_stat_classifier_is_skipped (task, cl, is_learn , is_spam)) {
  250. skip_classifier = TRUE;
  251. }
  252. }
  253. if (skip_classifier) {
  254. /* Set NULL for all statfiles indexed by id */
  255. for (int j = 0; j < cl->statfiles_ids->len; j++) {
  256. int id = g_array_index (cl->statfiles_ids, gint, j);
  257. g_ptr_array_index (task->stat_runtimes, id) = NULL;
  258. }
  259. }
  260. }
  261. for (i = 0; i < st_ctx->statfiles->len; i ++) {
  262. st = g_ptr_array_index (st_ctx->statfiles, i);
  263. g_assert (st != NULL);
  264. if (g_ptr_array_index (task->stat_runtimes, i) == NULL) {
  265. /* The whole classifier is skipped */
  266. continue;
  267. }
  268. if (is_learn && st->backend->read_only) {
  269. /* Read only backend, skip it */
  270. g_ptr_array_index (task->stat_runtimes, i) = NULL;
  271. continue;
  272. }
  273. if (!rspamd_symcache_is_symbol_enabled (task, task->cfg->cache,
  274. st->stcf->symbol)) {
  275. g_ptr_array_index (task->stat_runtimes, i) = NULL;
  276. msg_debug_bayes ("symbol %s is disabled, skip classification",
  277. st->stcf->symbol);
  278. continue;
  279. }
  280. bk_run = st->backend->runtime (task, st->stcf, is_learn, st->bkcf);
  281. if (bk_run == NULL) {
  282. msg_err_task ("cannot init backend %s for statfile %s",
  283. st->backend->name, st->stcf->symbol);
  284. }
  285. g_ptr_array_index (task->stat_runtimes, i) = bk_run;
  286. }
  287. }
  288. static void
  289. rspamd_stat_backends_process (struct rspamd_stat_ctx *st_ctx,
  290. struct rspamd_task *task)
  291. {
  292. guint i;
  293. struct rspamd_statfile *st;
  294. gpointer bk_run;
  295. g_assert (task->stat_runtimes != NULL);
  296. for (i = 0; i < st_ctx->statfiles->len; i++) {
  297. st = g_ptr_array_index (st_ctx->statfiles, i);
  298. bk_run = g_ptr_array_index (task->stat_runtimes, i);
  299. if (bk_run != NULL) {
  300. st->backend->process_tokens (task, task->tokens, i, bk_run);
  301. }
  302. }
  303. }
  304. static void
  305. rspamd_stat_classifiers_process (struct rspamd_stat_ctx *st_ctx,
  306. struct rspamd_task *task)
  307. {
  308. guint i, j, id;
  309. struct rspamd_classifier *cl;
  310. struct rspamd_statfile *st;
  311. gpointer bk_run;
  312. gboolean skip;
  313. if (st_ctx->classifiers->len == 0) {
  314. return;
  315. }
  316. /*
  317. * Do not classify a message if some class is missing
  318. */
  319. if (!(task->flags & RSPAMD_TASK_FLAG_HAS_SPAM_TOKENS)) {
  320. msg_info_task ("skip statistics as SPAM class is missing");
  321. return;
  322. }
  323. if (!(task->flags & RSPAMD_TASK_FLAG_HAS_HAM_TOKENS)) {
  324. msg_info_task ("skip statistics as HAM class is missing");
  325. return;
  326. }
  327. for (i = 0; i < st_ctx->classifiers->len; i++) {
  328. cl = g_ptr_array_index (st_ctx->classifiers, i);
  329. cl->spam_learns = 0;
  330. cl->ham_learns = 0;
  331. }
  332. g_assert (task->stat_runtimes != NULL);
  333. for (i = 0; i < st_ctx->statfiles->len; i++) {
  334. st = g_ptr_array_index (st_ctx->statfiles, i);
  335. cl = st->classifier;
  336. bk_run = g_ptr_array_index (task->stat_runtimes, i);
  337. g_assert (st != NULL);
  338. if (bk_run != NULL) {
  339. if (st->stcf->is_spam) {
  340. cl->spam_learns += st->backend->total_learns (task,
  341. bk_run,
  342. st_ctx);
  343. }
  344. else {
  345. cl->ham_learns += st->backend->total_learns (task,
  346. bk_run,
  347. st_ctx);
  348. }
  349. }
  350. }
  351. for (i = 0; i < st_ctx->classifiers->len; i++) {
  352. cl = g_ptr_array_index (st_ctx->classifiers, i);
  353. g_assert (cl != NULL);
  354. skip = FALSE;
  355. /* Do not process classifiers on backend failures */
  356. for (j = 0; j < cl->statfiles_ids->len; j++) {
  357. id = g_array_index (cl->statfiles_ids, gint, j);
  358. bk_run = g_ptr_array_index (task->stat_runtimes, id);
  359. st = g_ptr_array_index (st_ctx->statfiles, id);
  360. if (bk_run != NULL) {
  361. if (!st->backend->finalize_process (task, bk_run, st_ctx)) {
  362. skip = TRUE;
  363. break;
  364. }
  365. }
  366. }
  367. /* Ensure that all symbols enabled */
  368. if (!skip && !(cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND)) {
  369. for (j = 0; j < cl->statfiles_ids->len; j++) {
  370. id = g_array_index (cl->statfiles_ids, gint, j);
  371. bk_run = g_ptr_array_index (task->stat_runtimes, id);
  372. st = g_ptr_array_index (st_ctx->statfiles, id);
  373. if (bk_run == NULL) {
  374. skip = TRUE;
  375. msg_debug_bayes ("disable classifier %s as statfile symbol %s is disabled",
  376. cl->cfg->name, st->stcf->symbol);
  377. break;
  378. }
  379. }
  380. }
  381. if (!skip) {
  382. if (cl->cfg->min_tokens > 0 && task->tokens->len < cl->cfg->min_tokens) {
  383. msg_debug_bayes (
  384. "contains less tokens than required for %s classifier: "
  385. "%ud < %ud",
  386. cl->cfg->name,
  387. task->tokens->len,
  388. cl->cfg->min_tokens);
  389. continue;
  390. }
  391. else if (cl->cfg->max_tokens > 0 && task->tokens->len > cl->cfg->max_tokens) {
  392. msg_debug_bayes (
  393. "contains more tokens than allowed for %s classifier: "
  394. "%ud > %ud",
  395. cl->cfg->name,
  396. task->tokens->len,
  397. cl->cfg->max_tokens);
  398. continue;
  399. }
  400. cl->subrs->classify_func (cl, task->tokens, task);
  401. }
  402. }
  403. }
  404. rspamd_stat_result_t
  405. rspamd_stat_classify (struct rspamd_task *task, lua_State *L, guint stage,
  406. GError **err)
  407. {
  408. struct rspamd_stat_ctx *st_ctx;
  409. rspamd_stat_result_t ret = RSPAMD_STAT_PROCESS_OK;
  410. st_ctx = rspamd_stat_get_ctx ();
  411. g_assert (st_ctx != NULL);
  412. if (st_ctx->classifiers->len == 0) {
  413. task->processed_stages |= stage;
  414. return ret;
  415. }
  416. if (stage == RSPAMD_TASK_STAGE_CLASSIFIERS_PRE) {
  417. /* Preprocess tokens */
  418. rspamd_stat_preprocess (st_ctx, task, FALSE, FALSE);
  419. }
  420. else if (stage == RSPAMD_TASK_STAGE_CLASSIFIERS) {
  421. /* Process backends */
  422. rspamd_stat_backends_process (st_ctx, task);
  423. }
  424. else if (stage == RSPAMD_TASK_STAGE_CLASSIFIERS_POST) {
  425. /* Process classifiers */
  426. rspamd_stat_classifiers_process (st_ctx, task);
  427. }
  428. task->processed_stages |= stage;
  429. return ret;
  430. }
  431. static gboolean
  432. rspamd_stat_cache_check (struct rspamd_stat_ctx *st_ctx,
  433. struct rspamd_task *task,
  434. const gchar *classifier,
  435. gboolean spam,
  436. GError **err)
  437. {
  438. rspamd_learn_t learn_res = RSPAMD_LEARN_OK;
  439. struct rspamd_classifier *cl, *sel = NULL;
  440. gpointer rt;
  441. guint i;
  442. /* Check whether we have learned that file */
  443. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  444. cl = g_ptr_array_index (st_ctx->classifiers, i);
  445. /* Skip other classifiers if they are not needed */
  446. if (classifier != NULL && (cl->cfg->name == NULL ||
  447. g_ascii_strcasecmp (classifier, cl->cfg->name) != 0)) {
  448. continue;
  449. }
  450. sel = cl;
  451. if (sel->cache && sel->cachecf) {
  452. rt = cl->cache->runtime (task, sel->cachecf, FALSE);
  453. learn_res = cl->cache->check (task, spam, rt);
  454. }
  455. if (learn_res == RSPAMD_LEARN_IGNORE) {
  456. /* Do not learn twice */
  457. g_set_error (err, rspamd_stat_quark (), 404, "<%s> has been already "
  458. "learned as %s, ignore it", MESSAGE_FIELD (task, message_id),
  459. spam ? "spam" : "ham");
  460. task->flags |= RSPAMD_TASK_FLAG_ALREADY_LEARNED;
  461. return FALSE;
  462. }
  463. else if (learn_res == RSPAMD_LEARN_UNLEARN) {
  464. task->flags |= RSPAMD_TASK_FLAG_UNLEARN;
  465. break;
  466. }
  467. }
  468. if (sel == NULL) {
  469. if (classifier) {
  470. g_set_error (err, rspamd_stat_quark (), 404, "cannot find classifier "
  471. "with name %s", classifier);
  472. }
  473. else {
  474. g_set_error (err, rspamd_stat_quark (), 404, "no classifiers defined");
  475. }
  476. return FALSE;
  477. }
  478. return TRUE;
  479. }
  480. static gboolean
  481. rspamd_stat_classifiers_learn (struct rspamd_stat_ctx *st_ctx,
  482. struct rspamd_task *task,
  483. const gchar *classifier,
  484. gboolean spam,
  485. GError **err)
  486. {
  487. struct rspamd_classifier *cl, *sel = NULL;
  488. guint i;
  489. gboolean learned = FALSE, too_small = FALSE, too_large = FALSE;
  490. if ((task->flags & RSPAMD_TASK_FLAG_ALREADY_LEARNED) && err != NULL &&
  491. *err == NULL) {
  492. /* Do not learn twice */
  493. g_set_error (err, rspamd_stat_quark (), 208, "<%s> has been already "
  494. "learned as %s, ignore it", MESSAGE_FIELD (task, message_id),
  495. spam ? "spam" : "ham");
  496. return FALSE;
  497. }
  498. /* Check whether we have learned that file */
  499. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  500. cl = g_ptr_array_index (st_ctx->classifiers, i);
  501. /* Skip other classifiers if they are not needed */
  502. if (classifier != NULL && (cl->cfg->name == NULL ||
  503. g_ascii_strcasecmp (classifier, cl->cfg->name) != 0)) {
  504. continue;
  505. }
  506. sel = cl;
  507. /* Now check max and min tokens */
  508. if (cl->cfg->min_tokens > 0 && task->tokens->len < cl->cfg->min_tokens) {
  509. msg_info_task (
  510. "<%s> contains less tokens than required for %s classifier: "
  511. "%ud < %ud",
  512. MESSAGE_FIELD (task, message_id),
  513. cl->cfg->name,
  514. task->tokens->len,
  515. cl->cfg->min_tokens);
  516. too_small = TRUE;
  517. continue;
  518. }
  519. else if (cl->cfg->max_tokens > 0 && task->tokens->len > cl->cfg->max_tokens) {
  520. msg_info_task (
  521. "<%s> contains more tokens than allowed for %s classifier: "
  522. "%ud > %ud",
  523. MESSAGE_FIELD (task, message_id),
  524. cl->cfg->name,
  525. task->tokens->len,
  526. cl->cfg->max_tokens);
  527. too_large = TRUE;
  528. continue;
  529. }
  530. if (cl->subrs->learn_spam_func (cl, task->tokens, task, spam,
  531. task->flags & RSPAMD_TASK_FLAG_UNLEARN, err)) {
  532. learned = TRUE;
  533. }
  534. }
  535. if (sel == NULL) {
  536. if (classifier) {
  537. g_set_error (err, rspamd_stat_quark (), 404, "cannot find classifier "
  538. "with name %s", classifier);
  539. }
  540. else {
  541. g_set_error (err, rspamd_stat_quark (), 404, "no classifiers defined");
  542. }
  543. return FALSE;
  544. }
  545. if (!learned && err && *err == NULL) {
  546. if (too_large) {
  547. g_set_error (err, rspamd_stat_quark (), 204,
  548. "<%s> contains more tokens than allowed for %s classifier: "
  549. "%d > %d",
  550. MESSAGE_FIELD (task, message_id),
  551. sel->cfg->name,
  552. task->tokens->len,
  553. sel->cfg->max_tokens);
  554. }
  555. else if (too_small) {
  556. g_set_error (err, rspamd_stat_quark (), 204,
  557. "<%s> contains less tokens than required for %s classifier: "
  558. "%d < %d",
  559. MESSAGE_FIELD (task, message_id),
  560. sel->cfg->name,
  561. task->tokens->len,
  562. sel->cfg->min_tokens);
  563. }
  564. }
  565. return learned;
  566. }
  567. static gboolean
  568. rspamd_stat_backends_learn (struct rspamd_stat_ctx *st_ctx,
  569. struct rspamd_task *task,
  570. const gchar *classifier,
  571. gboolean spam,
  572. GError **err)
  573. {
  574. struct rspamd_classifier *cl, *sel = NULL;
  575. struct rspamd_statfile *st;
  576. gpointer bk_run;
  577. guint i, j;
  578. gint id;
  579. gboolean res = FALSE, backend_found = FALSE;
  580. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  581. cl = g_ptr_array_index (st_ctx->classifiers, i);
  582. /* Skip other classifiers if they are not needed */
  583. if (classifier != NULL && (cl->cfg->name == NULL ||
  584. g_ascii_strcasecmp (classifier, cl->cfg->name) != 0)) {
  585. continue;
  586. }
  587. if (cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND) {
  588. res = TRUE;
  589. continue;
  590. }
  591. sel = cl;
  592. for (j = 0; j < cl->statfiles_ids->len; j ++) {
  593. id = g_array_index (cl->statfiles_ids, gint, j);
  594. st = g_ptr_array_index (st_ctx->statfiles, id);
  595. bk_run = g_ptr_array_index (task->stat_runtimes, id);
  596. g_assert (st != NULL);
  597. if (bk_run == NULL) {
  598. /* XXX: must be error */
  599. if (task->result->passthrough_result) {
  600. /* Passthrough email, cannot learn */
  601. g_set_error (err, rspamd_stat_quark (), 204,
  602. "Cannot learn statistics when passthrough "
  603. "result has been set; not classified");
  604. res = FALSE;
  605. goto end;
  606. }
  607. msg_debug_task ("no runtime for backend %s; classifier %s; symbol %s",
  608. st->backend->name, cl->cfg->name, st->stcf->symbol);
  609. continue;
  610. }
  611. /* We set sel merely when we have runtime */
  612. backend_found = TRUE;
  613. if (!(task->flags & RSPAMD_TASK_FLAG_UNLEARN)) {
  614. if (!!spam != !!st->stcf->is_spam) {
  615. /* If we are not unlearning, then do not touch another class */
  616. continue;
  617. }
  618. }
  619. if (!st->backend->learn_tokens (task, task->tokens, id, bk_run)) {
  620. g_set_error (err, rspamd_stat_quark (), 500,
  621. "Cannot push "
  622. "learned results to the backend");
  623. res = FALSE;
  624. goto end;
  625. }
  626. else {
  627. if (!!spam == !!st->stcf->is_spam) {
  628. st->backend->inc_learns (task, bk_run, st_ctx);
  629. }
  630. else if (task->flags & RSPAMD_TASK_FLAG_UNLEARN) {
  631. st->backend->dec_learns (task, bk_run, st_ctx);
  632. }
  633. res = TRUE;
  634. }
  635. }
  636. }
  637. end:
  638. if (!res) {
  639. if (err && *err) {
  640. /* Error has been set already */
  641. return res;
  642. }
  643. if (sel == NULL) {
  644. if (classifier) {
  645. g_set_error(err, rspamd_stat_quark(), 404, "cannot find classifier "
  646. "with name %s", classifier);
  647. }
  648. else {
  649. g_set_error(err, rspamd_stat_quark(), 404, "no classifiers defined");
  650. }
  651. return FALSE;
  652. }
  653. else if (!backend_found) {
  654. g_set_error(err, rspamd_stat_quark(), 204, "all learn conditions "
  655. "denied learning %s in %s",
  656. spam ? "spam" : "ham",
  657. classifier ? classifier : "default classifier");
  658. }
  659. else {
  660. g_set_error(err, rspamd_stat_quark(), 404, "cannot find statfile "
  661. "backend to learn %s in %s",
  662. spam ? "spam" : "ham",
  663. classifier ? classifier : "default classifier");
  664. }
  665. }
  666. return res;
  667. }
  668. static gboolean
  669. rspamd_stat_backends_post_learn (struct rspamd_stat_ctx *st_ctx,
  670. struct rspamd_task *task,
  671. const gchar *classifier,
  672. gboolean spam,
  673. GError **err)
  674. {
  675. struct rspamd_classifier *cl;
  676. struct rspamd_statfile *st;
  677. gpointer bk_run, cache_run;
  678. guint i, j;
  679. gint id;
  680. gboolean res = TRUE;
  681. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  682. cl = g_ptr_array_index (st_ctx->classifiers, i);
  683. /* Skip other classifiers if they are not needed */
  684. if (classifier != NULL && (cl->cfg->name == NULL ||
  685. g_ascii_strcasecmp (classifier, cl->cfg->name) != 0)) {
  686. continue;
  687. }
  688. if (cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND) {
  689. res = TRUE;
  690. continue;
  691. }
  692. for (j = 0; j < cl->statfiles_ids->len; j ++) {
  693. id = g_array_index (cl->statfiles_ids, gint, j);
  694. st = g_ptr_array_index (st_ctx->statfiles, id);
  695. bk_run = g_ptr_array_index (task->stat_runtimes, id);
  696. g_assert (st != NULL);
  697. if (bk_run == NULL) {
  698. /* XXX: must be error */
  699. continue;
  700. }
  701. if (!st->backend->finalize_learn (task, bk_run, st_ctx, err)) {
  702. return RSPAMD_STAT_PROCESS_ERROR;
  703. }
  704. }
  705. if (cl->cache) {
  706. cache_run = cl->cache->runtime (task, cl->cachecf, TRUE);
  707. cl->cache->learn (task, spam, cache_run);
  708. }
  709. }
  710. g_atomic_int_add (&task->worker->srv->stat->messages_learned, 1);
  711. return res;
  712. }
  713. rspamd_stat_result_t
  714. rspamd_stat_learn (struct rspamd_task *task,
  715. gboolean spam, lua_State *L, const gchar *classifier, guint stage,
  716. GError **err)
  717. {
  718. struct rspamd_stat_ctx *st_ctx;
  719. rspamd_stat_result_t ret = RSPAMD_STAT_PROCESS_OK;
  720. /*
  721. * We assume now that a task has been already classified before
  722. * coming to learn
  723. */
  724. g_assert (RSPAMD_TASK_IS_CLASSIFIED (task));
  725. st_ctx = rspamd_stat_get_ctx ();
  726. g_assert (st_ctx != NULL);
  727. if (st_ctx->classifiers->len == 0) {
  728. task->processed_stages |= stage;
  729. return ret;
  730. }
  731. if (stage == RSPAMD_TASK_STAGE_LEARN_PRE) {
  732. /* Process classifiers */
  733. rspamd_stat_preprocess (st_ctx, task, TRUE, spam);
  734. if (!rspamd_stat_cache_check (st_ctx, task, classifier, spam, err)) {
  735. return RSPAMD_STAT_PROCESS_ERROR;
  736. }
  737. }
  738. else if (stage == RSPAMD_TASK_STAGE_LEARN) {
  739. /* Process classifiers */
  740. if (!rspamd_stat_classifiers_learn (st_ctx, task, classifier,
  741. spam, err)) {
  742. if (err && *err == NULL) {
  743. g_set_error (err, rspamd_stat_quark (), 500,
  744. "Unknown statistics error, found when learning classifiers;"
  745. " classifier: %s",
  746. task->classifier);
  747. }
  748. return RSPAMD_STAT_PROCESS_ERROR;
  749. }
  750. /* Process backends */
  751. if (!rspamd_stat_backends_learn (st_ctx, task, classifier, spam, err)) {
  752. if (err && *err == NULL) {
  753. g_set_error (err, rspamd_stat_quark (), 500,
  754. "Unknown statistics error, found when storing data on backend;"
  755. " classifier: %s",
  756. task->classifier);
  757. }
  758. return RSPAMD_STAT_PROCESS_ERROR;
  759. }
  760. }
  761. else if (stage == RSPAMD_TASK_STAGE_LEARN_POST) {
  762. if (!rspamd_stat_backends_post_learn (st_ctx, task, classifier, spam, err)) {
  763. return RSPAMD_STAT_PROCESS_ERROR;
  764. }
  765. }
  766. task->processed_stages |= stage;
  767. return ret;
  768. }
  769. static gboolean
  770. rspamd_stat_has_classifier_symbols (struct rspamd_task *task,
  771. struct rspamd_scan_result *mres,
  772. struct rspamd_classifier *cl)
  773. {
  774. guint i;
  775. gint id;
  776. struct rspamd_statfile *st;
  777. struct rspamd_stat_ctx *st_ctx;
  778. gboolean is_spam;
  779. if (mres == NULL) {
  780. return FALSE;
  781. }
  782. st_ctx = rspamd_stat_get_ctx ();
  783. is_spam = !!(task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM);
  784. for (i = 0; i < cl->statfiles_ids->len; i ++) {
  785. id = g_array_index (cl->statfiles_ids, gint, i);
  786. st = g_ptr_array_index (st_ctx->statfiles, id);
  787. if (rspamd_task_find_symbol_result (task, st->stcf->symbol, NULL)) {
  788. if (is_spam == !!st->stcf->is_spam) {
  789. msg_debug_bayes ("do not autolearn %s as symbol %s is already "
  790. "added", is_spam ? "spam" : "ham", st->stcf->symbol);
  791. return TRUE;
  792. }
  793. }
  794. }
  795. return FALSE;
  796. }
  797. gboolean
  798. rspamd_stat_check_autolearn (struct rspamd_task *task)
  799. {
  800. struct rspamd_stat_ctx *st_ctx;
  801. struct rspamd_classifier *cl;
  802. const ucl_object_t *obj, *elt1, *elt2;
  803. struct rspamd_scan_result *mres = NULL;
  804. struct rspamd_task **ptask;
  805. lua_State *L;
  806. guint i;
  807. gint err_idx;
  808. gboolean ret = FALSE;
  809. gdouble ham_score, spam_score;
  810. const gchar *lua_script, *lua_ret;
  811. g_assert (RSPAMD_TASK_IS_CLASSIFIED (task));
  812. st_ctx = rspamd_stat_get_ctx ();
  813. g_assert (st_ctx != NULL);
  814. L = task->cfg->lua_state;
  815. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  816. cl = g_ptr_array_index (st_ctx->classifiers, i);
  817. ret = FALSE;
  818. if (cl->cfg->opts) {
  819. obj = ucl_object_lookup (cl->cfg->opts, "autolearn");
  820. if (ucl_object_type (obj) == UCL_BOOLEAN) {
  821. /* Legacy true/false */
  822. if (ucl_object_toboolean (obj)) {
  823. /*
  824. * Default learning algorithm:
  825. *
  826. * - We learn spam if action is ACTION_REJECT
  827. * - We learn ham if score is less than zero
  828. */
  829. mres = task->result;
  830. if (mres) {
  831. if (mres->score > rspamd_task_get_required_score (task, mres)) {
  832. task->flags |= RSPAMD_TASK_FLAG_LEARN_SPAM;
  833. ret = TRUE;
  834. }
  835. else if (mres->score < 0) {
  836. task->flags |= RSPAMD_TASK_FLAG_LEARN_HAM;
  837. ret = TRUE;
  838. }
  839. }
  840. }
  841. }
  842. else if (ucl_object_type (obj) == UCL_ARRAY && obj->len == 2) {
  843. /* Legacy thresholds */
  844. /*
  845. * We have an array of 2 elements, treat it as a
  846. * ham_score, spam_score
  847. */
  848. elt1 = ucl_array_find_index (obj, 0);
  849. elt2 = ucl_array_find_index (obj, 1);
  850. if ((ucl_object_type (elt1) == UCL_FLOAT ||
  851. ucl_object_type (elt1) == UCL_INT) &&
  852. (ucl_object_type (elt2) == UCL_FLOAT ||
  853. ucl_object_type (elt2) == UCL_INT)) {
  854. ham_score = ucl_object_todouble (elt1);
  855. spam_score = ucl_object_todouble (elt2);
  856. if (ham_score > spam_score) {
  857. gdouble t;
  858. t = ham_score;
  859. ham_score = spam_score;
  860. spam_score = t;
  861. }
  862. mres = task->result;
  863. if (mres) {
  864. if (mres->score >= spam_score) {
  865. task->flags |= RSPAMD_TASK_FLAG_LEARN_SPAM;
  866. ret = TRUE;
  867. }
  868. else if (mres->score <= ham_score) {
  869. task->flags |= RSPAMD_TASK_FLAG_LEARN_HAM;
  870. ret = TRUE;
  871. }
  872. }
  873. }
  874. }
  875. else if (ucl_object_type (obj) == UCL_STRING) {
  876. /* Legacy script */
  877. lua_script = ucl_object_tostring (obj);
  878. if (luaL_dostring (L, lua_script) != 0) {
  879. msg_err_task ("cannot execute lua script for autolearn "
  880. "extraction: %s", lua_tostring (L, -1));
  881. }
  882. else {
  883. if (lua_type (L, -1) == LUA_TFUNCTION) {
  884. lua_pushcfunction (L, &rspamd_lua_traceback);
  885. err_idx = lua_gettop (L);
  886. lua_pushvalue (L, -2); /* Function itself */
  887. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  888. *ptask = task;
  889. rspamd_lua_setclass (L, "rspamd{task}", -1);
  890. if (lua_pcall (L, 1, 1, err_idx) != 0) {
  891. msg_err_task ("call to autolearn script failed: "
  892. "%s", lua_tostring (L, -1));
  893. }
  894. else {
  895. lua_ret = lua_tostring (L, -1);
  896. /* We can have immediate results */
  897. if (lua_ret) {
  898. if (strcmp (lua_ret, "ham") == 0) {
  899. task->flags |= RSPAMD_TASK_FLAG_LEARN_HAM;
  900. ret = TRUE;
  901. }
  902. else if (strcmp (lua_ret, "spam") == 0) {
  903. task->flags |= RSPAMD_TASK_FLAG_LEARN_SPAM;
  904. ret = TRUE;
  905. }
  906. }
  907. }
  908. /* Result + error function + original function */
  909. lua_pop (L, 3);
  910. }
  911. else {
  912. msg_err_task ("lua script must return "
  913. "function(task) and not %s",
  914. lua_typename (L, lua_type (
  915. L, -1)));
  916. }
  917. }
  918. }
  919. else if (ucl_object_type (obj) == UCL_OBJECT) {
  920. /* Try to find autolearn callback */
  921. if (cl->autolearn_cbref == 0) {
  922. /* We don't have preprocessed cb id, so try to get it */
  923. if (!rspamd_lua_require_function (L, "lua_bayes_learn",
  924. "autolearn")) {
  925. msg_err_task ("cannot get autolearn library from "
  926. "`lua_bayes_learn`");
  927. }
  928. else {
  929. cl->autolearn_cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  930. }
  931. }
  932. if (cl->autolearn_cbref != -1) {
  933. lua_pushcfunction (L, &rspamd_lua_traceback);
  934. err_idx = lua_gettop (L);
  935. lua_rawgeti (L, LUA_REGISTRYINDEX, cl->autolearn_cbref);
  936. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  937. *ptask = task;
  938. rspamd_lua_setclass (L, "rspamd{task}", -1);
  939. /* Push the whole object as well */
  940. ucl_object_push_lua (L, obj, true);
  941. if (lua_pcall (L, 2, 1, err_idx) != 0) {
  942. msg_err_task ("call to autolearn script failed: "
  943. "%s", lua_tostring (L, -1));
  944. }
  945. else {
  946. lua_ret = lua_tostring (L, -1);
  947. if (lua_ret) {
  948. if (strcmp (lua_ret, "ham") == 0) {
  949. task->flags |= RSPAMD_TASK_FLAG_LEARN_HAM;
  950. ret = TRUE;
  951. }
  952. else if (strcmp (lua_ret, "spam") == 0) {
  953. task->flags |= RSPAMD_TASK_FLAG_LEARN_SPAM;
  954. ret = TRUE;
  955. }
  956. }
  957. }
  958. lua_settop (L, err_idx - 1);
  959. }
  960. }
  961. if (ret) {
  962. /* Do not autolearn if we have this symbol already */
  963. if (rspamd_stat_has_classifier_symbols (task, mres, cl)) {
  964. ret = FALSE;
  965. task->flags &= ~(RSPAMD_TASK_FLAG_LEARN_HAM |
  966. RSPAMD_TASK_FLAG_LEARN_SPAM);
  967. }
  968. else if (mres != NULL) {
  969. if (task->flags & RSPAMD_TASK_FLAG_LEARN_HAM) {
  970. msg_info_task ("<%s>: autolearn ham for classifier "
  971. "'%s' as message's "
  972. "score is negative: %.2f",
  973. MESSAGE_FIELD (task, message_id), cl->cfg->name,
  974. mres->score);
  975. }
  976. else {
  977. msg_info_task ("<%s>: autolearn spam for classifier "
  978. "'%s' as message's "
  979. "action is reject, score: %.2f",
  980. MESSAGE_FIELD (task, message_id), cl->cfg->name,
  981. mres->score);
  982. }
  983. task->classifier = cl->cfg->name;
  984. break;
  985. }
  986. }
  987. }
  988. }
  989. return ret;
  990. }
  991. /**
  992. * Get the overall statistics for all statfile backends
  993. * @param cfg configuration
  994. * @param total_learns the total number of learns is stored here
  995. * @return array of statistical information
  996. */
  997. rspamd_stat_result_t
  998. rspamd_stat_statistics (struct rspamd_task *task,
  999. struct rspamd_config *cfg,
  1000. guint64 *total_learns,
  1001. ucl_object_t **target)
  1002. {
  1003. struct rspamd_stat_ctx *st_ctx;
  1004. struct rspamd_classifier *cl;
  1005. struct rspamd_statfile *st;
  1006. gpointer backend_runtime;
  1007. ucl_object_t *res = NULL, *elt;
  1008. guint64 learns = 0;
  1009. guint i, j;
  1010. gint id;
  1011. st_ctx = rspamd_stat_get_ctx ();
  1012. g_assert (st_ctx != NULL);
  1013. res = ucl_object_typed_new (UCL_ARRAY);
  1014. for (i = 0; i < st_ctx->classifiers->len; i ++) {
  1015. cl = g_ptr_array_index (st_ctx->classifiers, i);
  1016. if (cl->cfg->flags & RSPAMD_FLAG_CLASSIFIER_NO_BACKEND) {
  1017. continue;
  1018. }
  1019. for (j = 0; j < cl->statfiles_ids->len; j ++) {
  1020. id = g_array_index (cl->statfiles_ids, gint, j);
  1021. st = g_ptr_array_index (st_ctx->statfiles, id);
  1022. backend_runtime = st->backend->runtime (task, st->stcf, FALSE,
  1023. st->bkcf);
  1024. elt = st->backend->get_stat (backend_runtime, st->bkcf);
  1025. if (elt && ucl_object_type (elt) == UCL_OBJECT) {
  1026. const ucl_object_t *rev = ucl_object_lookup (elt, "revision");
  1027. learns += ucl_object_toint (rev);
  1028. }
  1029. else {
  1030. learns += st->backend->total_learns (task, backend_runtime,
  1031. st->bkcf);
  1032. }
  1033. if (elt != NULL) {
  1034. ucl_array_append (res, elt);
  1035. }
  1036. }
  1037. }
  1038. if (total_learns != NULL) {
  1039. *total_learns = learns;
  1040. }
  1041. if (target) {
  1042. *target = res;
  1043. }
  1044. else {
  1045. ucl_object_unref (res);
  1046. }
  1047. return RSPAMD_STAT_PROCESS_OK;
  1048. }