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.

fuzzy_check.c 99KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105
  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. /***MODULE:fuzzy
  17. * rspamd module that checks fuzzy checksums for messages
  18. *
  19. * Allowed options:
  20. * - symbol (string): symbol to insert (default: 'R_FUZZY')
  21. * - max_score (double): maximum score to that weights of hashes would be normalized (default: 0 - no normalization)
  22. *
  23. * - fuzzy_map (string): a string that contains map in format { fuzzy_key => [ symbol, weight ] } where fuzzy_key is number of
  24. * 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
  25. * key, second is symbol to insert and third - weight for normalization
  26. *
  27. * - min_length (integer): minimum length (in characters) for text part to be checked for fuzzy hash (default: 0 - no limit)
  28. * - whitelist (map string): map of ip addresses that should not be checked with this module
  29. * - servers (string): list of fuzzy servers in format "server1:port,server2:port" - these servers would be used for checking and storing
  30. * fuzzy hashes
  31. */
  32. #include "config.h"
  33. #include "libmime/message.h"
  34. #include "libserver/maps/map.h"
  35. #include "libserver/maps/map_helpers.h"
  36. #include "libmime/images.h"
  37. #include "libserver/worker_util.h"
  38. #include "libserver/mempool_vars_internal.h"
  39. #include "fuzzy_wire.h"
  40. #include "utlist.h"
  41. #include "ottery.h"
  42. #include "lua/lua_common.h"
  43. #include "unix-std.h"
  44. #include "libserver/http/http_private.h"
  45. #include "libserver/http/http_router.h"
  46. #include "libstat/stat_api.h"
  47. #include <math.h>
  48. #include "libutil/libev_helper.h"
  49. #define DEFAULT_SYMBOL "R_FUZZY_HASH"
  50. #define DEFAULT_IO_TIMEOUT 1.0
  51. #define DEFAULT_RETRANSMITS 3
  52. #define DEFAULT_MAX_ERRORS 4
  53. #define DEFAULT_REVIVE_TIME 60
  54. #define DEFAULT_PORT 11335
  55. #define RSPAMD_FUZZY_PLUGIN_VERSION RSPAMD_FUZZY_VERSION
  56. static const gint rspamd_fuzzy_hash_len = 5;
  57. static const gchar *M = "fuzzy check";
  58. struct fuzzy_ctx;
  59. struct fuzzy_mapping {
  60. guint64 fuzzy_flag;
  61. const gchar *symbol;
  62. double weight;
  63. };
  64. struct fuzzy_rule {
  65. struct upstream_list *servers;
  66. const gchar *symbol;
  67. const gchar *algorithm_str;
  68. const gchar *name;
  69. const ucl_object_t *ucl_obj;
  70. enum rspamd_shingle_alg alg;
  71. GHashTable *mappings;
  72. GPtrArray *fuzzy_headers;
  73. GString *hash_key;
  74. GString *shingles_key;
  75. gdouble io_timeout;
  76. struct rspamd_cryptobox_keypair *local_key;
  77. struct rspamd_cryptobox_pubkey *peer_key;
  78. double max_score;
  79. double weight_threshold;
  80. gboolean read_only;
  81. gboolean skip_unknown;
  82. gboolean no_share;
  83. gboolean no_subject;
  84. gint learn_condition_cb;
  85. guint32 retransmits;
  86. struct rspamd_hash_map_helper *skip_map;
  87. struct fuzzy_ctx *ctx;
  88. gint lua_id;
  89. };
  90. struct fuzzy_ctx {
  91. struct module_ctx ctx;
  92. rspamd_mempool_t *fuzzy_pool;
  93. GPtrArray *fuzzy_rules;
  94. struct rspamd_config *cfg;
  95. const gchar *default_symbol;
  96. struct rspamd_radix_map_helper *whitelist;
  97. struct rspamd_keypair_cache *keypairs_cache;
  98. guint max_errors;
  99. gdouble revive_time;
  100. gdouble io_timeout;
  101. gint check_mime_part_ref; /* Lua callback */
  102. gint process_rule_ref; /* Lua callback */
  103. gint cleanup_rules_ref;
  104. guint32 retransmits;
  105. gboolean enabled;
  106. };
  107. enum fuzzy_result_type {
  108. FUZZY_RESULT_TXT,
  109. FUZZY_RESULT_IMG,
  110. FUZZY_RESULT_CONTENT,
  111. FUZZY_RESULT_BIN
  112. };
  113. struct fuzzy_client_result {
  114. const gchar *symbol;
  115. gchar *option;
  116. gdouble score;
  117. gdouble prob;
  118. enum fuzzy_result_type type;
  119. };
  120. struct fuzzy_client_session {
  121. GPtrArray *commands;
  122. GPtrArray *results;
  123. struct rspamd_task *task;
  124. struct rspamd_symcache_item *item;
  125. struct upstream *server;
  126. struct fuzzy_rule *rule;
  127. struct ev_loop *event_loop;
  128. struct rspamd_io_ev ev;
  129. gint state;
  130. gint fd;
  131. guint retransmits;
  132. };
  133. struct fuzzy_learn_session {
  134. GPtrArray *commands;
  135. gint *saved;
  136. struct {
  137. const gchar *error_message;
  138. gint error_code;
  139. } err;
  140. struct rspamd_http_connection_entry *http_entry;
  141. struct rspamd_async_session *session;
  142. struct upstream *server;
  143. struct fuzzy_rule *rule;
  144. struct rspamd_task *task;
  145. struct ev_loop *event_loop;
  146. struct rspamd_io_ev ev;
  147. gint fd;
  148. guint retransmits;
  149. };
  150. #define FUZZY_CMD_FLAG_REPLIED (1 << 0)
  151. #define FUZZY_CMD_FLAG_SENT (1 << 1)
  152. #define FUZZY_CMD_FLAG_IMAGE (1 << 2)
  153. #define FUZZY_CMD_FLAG_CONTENT (1 << 3)
  154. #define FUZZY_CHECK_FLAG_NOIMAGES (1 << 0)
  155. #define FUZZY_CHECK_FLAG_NOATTACHMENTS (1 << 1)
  156. #define FUZZY_CHECK_FLAG_NOTEXT (1 << 2)
  157. struct fuzzy_cmd_io {
  158. guint32 tag;
  159. guint32 flags;
  160. struct iovec io;
  161. struct rspamd_mime_part *part;
  162. struct rspamd_fuzzy_cmd cmd;
  163. };
  164. static const char *default_headers = "Subject,Content-Type,Reply-To,X-Mailer";
  165. static void fuzzy_symbol_callback (struct rspamd_task *task,
  166. struct rspamd_symcache_item *item,
  167. void *unused);
  168. /* Initialization */
  169. gint fuzzy_check_module_init (struct rspamd_config *cfg,
  170. struct module_ctx **ctx);
  171. gint fuzzy_check_module_config (struct rspamd_config *cfg, bool valdate);
  172. gint fuzzy_check_module_reconfig (struct rspamd_config *cfg);
  173. static gint fuzzy_attach_controller (struct module_ctx *ctx,
  174. GHashTable *commands);
  175. static gint fuzzy_lua_learn_handler (lua_State *L);
  176. static gint fuzzy_lua_unlearn_handler (lua_State *L);
  177. static gint fuzzy_lua_gen_hashes_handler (lua_State *L);
  178. module_t fuzzy_check_module = {
  179. "fuzzy_check",
  180. fuzzy_check_module_init,
  181. fuzzy_check_module_config,
  182. fuzzy_check_module_reconfig,
  183. fuzzy_attach_controller,
  184. RSPAMD_MODULE_VER,
  185. (guint)-1,
  186. };
  187. static inline struct fuzzy_ctx *
  188. fuzzy_get_context (struct rspamd_config *cfg)
  189. {
  190. return (struct fuzzy_ctx *)g_ptr_array_index (cfg->c_modules,
  191. fuzzy_check_module.ctx_offset);
  192. }
  193. static void
  194. parse_flags (struct fuzzy_rule *rule,
  195. struct rspamd_config *cfg,
  196. const ucl_object_t *val,
  197. gint cb_id)
  198. {
  199. const ucl_object_t *elt;
  200. struct fuzzy_mapping *map;
  201. const gchar *sym = NULL;
  202. if (val->type == UCL_STRING) {
  203. msg_err_config (
  204. "string mappings are deprecated and no longer supported, use new style configuration");
  205. }
  206. else if (val->type == UCL_OBJECT) {
  207. elt = ucl_object_lookup (val, "symbol");
  208. if (elt == NULL || !ucl_object_tostring_safe (elt, &sym)) {
  209. sym = ucl_object_key (val);
  210. }
  211. if (sym != NULL) {
  212. map =
  213. rspamd_mempool_alloc (cfg->cfg_pool,
  214. sizeof (struct fuzzy_mapping));
  215. map->symbol = sym;
  216. elt = ucl_object_lookup (val, "flag");
  217. if (elt != NULL) {
  218. map->fuzzy_flag = ucl_obj_toint (elt);
  219. elt = ucl_object_lookup (val, "max_score");
  220. if (elt != NULL) {
  221. map->weight = ucl_obj_todouble (elt);
  222. }
  223. else {
  224. map->weight = rule->max_score;
  225. }
  226. /* Add flag to hash table */
  227. g_hash_table_insert (rule->mappings,
  228. GINT_TO_POINTER (map->fuzzy_flag), map);
  229. rspamd_symcache_add_symbol (cfg->cache,
  230. map->symbol, 0,
  231. NULL, NULL,
  232. SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
  233. cb_id);
  234. }
  235. else {
  236. msg_err_config ("fuzzy_map parameter has no flag definition");
  237. }
  238. }
  239. else {
  240. msg_err_config ("fuzzy_map parameter has no symbol definition");
  241. }
  242. }
  243. else {
  244. msg_err_config ("fuzzy_map parameter is of an unsupported type");
  245. }
  246. }
  247. static GPtrArray *
  248. parse_fuzzy_headers (struct rspamd_config *cfg, const gchar *str)
  249. {
  250. gchar **strvec;
  251. gint num, i;
  252. GPtrArray *res;
  253. strvec = g_strsplit_set (str, ",", 0);
  254. num = g_strv_length (strvec);
  255. res = g_ptr_array_sized_new (num);
  256. for (i = 0; i < num; i++) {
  257. g_strstrip (strvec[i]);
  258. g_ptr_array_add (res, rspamd_mempool_strdup (
  259. cfg->cfg_pool, strvec[i]));
  260. }
  261. g_strfreev (strvec);
  262. return res;
  263. }
  264. static double
  265. fuzzy_normalize (gint32 in, double weight)
  266. {
  267. if (weight == 0) {
  268. return 0;
  269. }
  270. #ifdef HAVE_TANH
  271. return tanh (G_E * (double)in / weight);
  272. #else
  273. return (in < weight ? in / weight : weight);
  274. #endif
  275. }
  276. static struct fuzzy_rule *
  277. fuzzy_rule_new (const char *default_symbol, rspamd_mempool_t *pool)
  278. {
  279. struct fuzzy_rule *rule;
  280. rule = rspamd_mempool_alloc0 (pool, sizeof (struct fuzzy_rule));
  281. rule->mappings = g_hash_table_new (g_direct_hash, g_direct_equal);
  282. rule->symbol = default_symbol;
  283. rspamd_mempool_add_destructor (pool,
  284. (rspamd_mempool_destruct_t)g_hash_table_unref,
  285. rule->mappings);
  286. rule->read_only = FALSE;
  287. rule->weight_threshold = NAN;
  288. return rule;
  289. }
  290. static void
  291. fuzzy_free_rule (gpointer r)
  292. {
  293. struct fuzzy_rule *rule = (struct fuzzy_rule *)r;
  294. g_string_free (rule->hash_key, TRUE);
  295. g_string_free (rule->shingles_key, TRUE);
  296. if (rule->local_key) {
  297. rspamd_keypair_unref (rule->local_key);
  298. }
  299. if (rule->peer_key) {
  300. rspamd_pubkey_unref (rule->peer_key);
  301. }
  302. }
  303. static gint
  304. fuzzy_parse_rule (struct rspamd_config *cfg, const ucl_object_t *obj,
  305. const gchar *name, gint cb_id)
  306. {
  307. const ucl_object_t *value, *cur;
  308. struct fuzzy_rule *rule;
  309. ucl_object_iter_t it = NULL;
  310. const char *k = NULL, *key_str = NULL, *shingles_key_str = NULL, *lua_script;
  311. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  312. if (obj->type != UCL_OBJECT) {
  313. msg_err_config ("invalid rule definition");
  314. return -1;
  315. }
  316. if ((value = ucl_object_lookup_any (obj, "enabled", "enable", NULL)) != NULL) {
  317. if (!ucl_object_toboolean (value)) {
  318. msg_info_config ("fuzzy rule %s is disabled by configuration", name);
  319. return 0;
  320. }
  321. }
  322. rule = fuzzy_rule_new (fuzzy_module_ctx->default_symbol,
  323. cfg->cfg_pool);
  324. rule->ucl_obj = obj;
  325. rule->ctx = fuzzy_module_ctx;
  326. rule->learn_condition_cb = -1;
  327. rule->alg = RSPAMD_SHINGLES_OLD;
  328. rule->skip_map = NULL;
  329. if ((value = ucl_object_lookup (obj, "skip_hashes")) != NULL) {
  330. rspamd_map_add_from_ucl (cfg, value,
  331. "Fuzzy hashes whitelist",
  332. rspamd_kv_list_read,
  333. rspamd_kv_list_fin,
  334. rspamd_kv_list_dtor,
  335. (void **)&rule->skip_map,
  336. NULL, RSPAMD_MAP_DEFAULT);
  337. }
  338. if ((value = ucl_object_lookup (obj, "headers")) != NULL) {
  339. it = NULL;
  340. while ((cur = ucl_object_iterate (value, &it, value->type == UCL_ARRAY))
  341. != NULL) {
  342. GPtrArray *tmp;
  343. guint i;
  344. gpointer ptr;
  345. tmp = parse_fuzzy_headers (cfg, ucl_obj_tostring (cur));
  346. if (tmp) {
  347. if (rule->fuzzy_headers) {
  348. PTR_ARRAY_FOREACH (tmp, i, ptr) {
  349. g_ptr_array_add (rule->fuzzy_headers, ptr);
  350. }
  351. g_ptr_array_free (tmp, TRUE);
  352. }
  353. else {
  354. rule->fuzzy_headers = tmp;
  355. }
  356. }
  357. }
  358. }
  359. else {
  360. rule->fuzzy_headers = parse_fuzzy_headers (cfg, default_headers);
  361. }
  362. if (rule->fuzzy_headers != NULL) {
  363. rspamd_mempool_add_destructor (cfg->cfg_pool,
  364. (rspamd_mempool_destruct_t) rspamd_ptr_array_free_hard,
  365. rule->fuzzy_headers);
  366. }
  367. if ((value = ucl_object_lookup (obj, "max_score")) != NULL) {
  368. rule->max_score = ucl_obj_todouble (value);
  369. }
  370. if ((value = ucl_object_lookup (obj, "retransmits")) != NULL) {
  371. rule->retransmits = ucl_obj_toint (value);
  372. }
  373. else {
  374. rule->retransmits = fuzzy_module_ctx->retransmits;
  375. }
  376. if ((value = ucl_object_lookup (obj, "timeout")) != NULL) {
  377. rule->io_timeout = ucl_obj_todouble (value);
  378. }
  379. else {
  380. rule->io_timeout = fuzzy_module_ctx->io_timeout;
  381. }
  382. if ((value = ucl_object_lookup (obj, "symbol")) != NULL) {
  383. rule->symbol = ucl_obj_tostring (value);
  384. }
  385. if (name) {
  386. rule->name = name;
  387. }
  388. else {
  389. rule->name = rule->symbol;
  390. }
  391. if ((value = ucl_object_lookup (obj, "read_only")) != NULL) {
  392. rule->read_only = ucl_obj_toboolean (value);
  393. }
  394. if ((value = ucl_object_lookup (obj, "skip_unknown")) != NULL) {
  395. rule->skip_unknown = ucl_obj_toboolean (value);
  396. }
  397. if ((value = ucl_object_lookup (obj, "no_share")) != NULL) {
  398. rule->no_share = ucl_obj_toboolean (value);
  399. }
  400. if ((value = ucl_object_lookup (obj, "no_subject")) != NULL) {
  401. rule->no_subject = ucl_obj_toboolean (value);
  402. }
  403. if ((value = ucl_object_lookup (obj, "algorithm")) != NULL) {
  404. rule->algorithm_str = ucl_object_tostring (value);
  405. if (rule->algorithm_str) {
  406. if (g_ascii_strcasecmp (rule->algorithm_str, "old") == 0 ||
  407. g_ascii_strcasecmp (rule->algorithm_str, "siphash") == 0) {
  408. rule->alg = RSPAMD_SHINGLES_OLD;
  409. }
  410. else if (g_ascii_strcasecmp (rule->algorithm_str, "xxhash") == 0) {
  411. rule->alg = RSPAMD_SHINGLES_XXHASH;
  412. }
  413. else if (g_ascii_strcasecmp (rule->algorithm_str, "mumhash") == 0) {
  414. rule->alg = RSPAMD_SHINGLES_MUMHASH;
  415. }
  416. else if (g_ascii_strcasecmp (rule->algorithm_str, "fasthash") == 0 ||
  417. g_ascii_strcasecmp (rule->algorithm_str, "fast") == 0) {
  418. rule->alg = RSPAMD_SHINGLES_FAST;
  419. }
  420. else {
  421. msg_warn_config ("unknown algorithm: %s, use siphash by default",
  422. rule->algorithm_str);
  423. }
  424. }
  425. }
  426. /* Set a consistent and short string name */
  427. switch (rule->alg) {
  428. case RSPAMD_SHINGLES_OLD:
  429. rule->algorithm_str = "sip";
  430. break;
  431. case RSPAMD_SHINGLES_XXHASH:
  432. rule->algorithm_str = "xx";
  433. break;
  434. case RSPAMD_SHINGLES_MUMHASH:
  435. rule->algorithm_str = "mum";
  436. break;
  437. case RSPAMD_SHINGLES_FAST:
  438. rule->algorithm_str = "fast";
  439. break;
  440. }
  441. if ((value = ucl_object_lookup (obj, "servers")) != NULL) {
  442. rule->servers = rspamd_upstreams_create (cfg->ups_ctx);
  443. /* pass max_error and revive_time configuration in upstream for fuzzy storage
  444. * it allows to configure error_rate threshold and upstream dead timer
  445. */
  446. rspamd_upstreams_set_limits (rule->servers,
  447. (gdouble) fuzzy_module_ctx->revive_time, NAN, NAN, NAN,
  448. (guint) fuzzy_module_ctx->max_errors, 0);
  449. rspamd_mempool_add_destructor (cfg->cfg_pool,
  450. (rspamd_mempool_destruct_t)rspamd_upstreams_destroy,
  451. rule->servers);
  452. if (!rspamd_upstreams_from_ucl (rule->servers, value, DEFAULT_PORT, NULL)) {
  453. msg_err_config ("cannot read servers definition");
  454. return -1;
  455. }
  456. }
  457. if ((value = ucl_object_lookup (obj, "fuzzy_map")) != NULL) {
  458. it = NULL;
  459. while ((cur = ucl_object_iterate (value, &it, true)) != NULL) {
  460. parse_flags (rule, cfg, cur, cb_id);
  461. }
  462. }
  463. if ((value = ucl_object_lookup (obj, "encryption_key")) != NULL) {
  464. /* Create key from user's input */
  465. k = ucl_object_tostring (value);
  466. if (k == NULL || (rule->peer_key =
  467. rspamd_pubkey_from_base32 (k, 0, RSPAMD_KEYPAIR_KEX,
  468. RSPAMD_CRYPTOBOX_MODE_25519)) == NULL) {
  469. msg_err_config ("bad encryption key value: %s",
  470. k);
  471. return -1;
  472. }
  473. rule->local_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
  474. RSPAMD_CRYPTOBOX_MODE_25519);
  475. }
  476. if ((value = ucl_object_lookup (obj, "learn_condition")) != NULL) {
  477. lua_script = ucl_object_tostring (value);
  478. if (lua_script) {
  479. if (luaL_dostring (cfg->lua_state, lua_script) != 0) {
  480. msg_err_config ("cannot execute lua script for fuzzy "
  481. "learn condition: %s", lua_tostring (cfg->lua_state, -1));
  482. }
  483. else {
  484. if (lua_type (cfg->lua_state, -1) == LUA_TFUNCTION) {
  485. rule->learn_condition_cb = luaL_ref (cfg->lua_state,
  486. LUA_REGISTRYINDEX);
  487. msg_info_config ("loaded learn condition script for fuzzy rule:"
  488. " %s", rule->name);
  489. }
  490. else {
  491. msg_err_config ("lua script must return "
  492. "function(task) and not %s",
  493. lua_typename (cfg->lua_state,
  494. lua_type (cfg->lua_state, -1)));
  495. }
  496. }
  497. }
  498. }
  499. key_str = NULL;
  500. if ((value = ucl_object_lookup (obj, "fuzzy_key")) != NULL) {
  501. /* Create key from user's input */
  502. key_str = ucl_object_tostring (value);
  503. }
  504. /* Setup keys */
  505. if (key_str == NULL) {
  506. /* Use some default key for all ops */
  507. key_str = "rspamd";
  508. }
  509. rule->hash_key = g_string_sized_new (rspamd_cryptobox_HASHBYTES);
  510. rspamd_cryptobox_hash (rule->hash_key->str, key_str, strlen (key_str), NULL, 0);
  511. rule->hash_key->len = rspamd_cryptobox_HASHKEYBYTES;
  512. shingles_key_str = NULL;
  513. if ((value = ucl_object_lookup (obj, "fuzzy_shingles_key")) != NULL) {
  514. shingles_key_str = ucl_object_tostring (value);
  515. }
  516. if (shingles_key_str == NULL) {
  517. shingles_key_str = "rspamd";
  518. }
  519. rule->shingles_key = g_string_sized_new (rspamd_cryptobox_HASHBYTES);
  520. rspamd_cryptobox_hash (rule->shingles_key->str, shingles_key_str,
  521. strlen (shingles_key_str), NULL, 0);
  522. rule->shingles_key->len = 16;
  523. if (rspamd_upstreams_count (rule->servers) == 0) {
  524. msg_err_config ("no servers defined for fuzzy rule with name: %s",
  525. rule->name);
  526. return -1;
  527. }
  528. else {
  529. g_ptr_array_add (fuzzy_module_ctx->fuzzy_rules, rule);
  530. if (rule->symbol != fuzzy_module_ctx->default_symbol) {
  531. rspamd_symcache_add_symbol (cfg->cache, rule->symbol,
  532. 0,
  533. NULL, NULL,
  534. SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
  535. cb_id);
  536. }
  537. msg_info_config ("added fuzzy rule %s, key: %*xs, "
  538. "shingles_key: %*xs, algorithm: %s",
  539. rule->symbol,
  540. 6, rule->hash_key->str,
  541. 6, rule->shingles_key->str,
  542. rule->algorithm_str);
  543. }
  544. if ((value = ucl_object_lookup (obj, "weight_threshold")) != NULL) {
  545. rule->weight_threshold = ucl_object_todouble (value);
  546. }
  547. /*
  548. * Process rule in Lua
  549. */
  550. gint err_idx, ret;
  551. lua_State *L = (lua_State *)cfg->lua_state;
  552. lua_pushcfunction (L, &rspamd_lua_traceback);
  553. err_idx = lua_gettop (L);
  554. lua_rawgeti (L, LUA_REGISTRYINDEX, fuzzy_module_ctx->process_rule_ref);
  555. ucl_object_push_lua (L, obj, true);
  556. if ((ret = lua_pcall (L, 1, 1, err_idx)) != 0) {
  557. msg_err_config ("call to process_rule lua "
  558. "script failed (%d): %s", ret, lua_tostring (L, -1));
  559. rule->lua_id = -1;
  560. }
  561. else {
  562. rule->lua_id = lua_tonumber (L, -1);
  563. }
  564. lua_settop (L, err_idx - 1);
  565. rspamd_mempool_add_destructor (cfg->cfg_pool, fuzzy_free_rule,
  566. rule);
  567. return 0;
  568. }
  569. gint
  570. fuzzy_check_module_init (struct rspamd_config *cfg, struct module_ctx **ctx)
  571. {
  572. struct fuzzy_ctx *fuzzy_module_ctx;
  573. fuzzy_module_ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
  574. sizeof (struct fuzzy_ctx));
  575. fuzzy_module_ctx->fuzzy_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
  576. NULL, 0);
  577. /* TODO: this should match rules count actually */
  578. fuzzy_module_ctx->keypairs_cache = rspamd_keypair_cache_new (32);
  579. fuzzy_module_ctx->fuzzy_rules = g_ptr_array_new ();
  580. fuzzy_module_ctx->cfg = cfg;
  581. fuzzy_module_ctx->process_rule_ref = -1;
  582. fuzzy_module_ctx->check_mime_part_ref = -1;
  583. fuzzy_module_ctx->cleanup_rules_ref = -1;
  584. rspamd_mempool_add_destructor (cfg->cfg_pool,
  585. (rspamd_mempool_destruct_t)rspamd_mempool_delete,
  586. fuzzy_module_ctx->fuzzy_pool);
  587. rspamd_mempool_add_destructor (cfg->cfg_pool,
  588. (rspamd_mempool_destruct_t)rspamd_keypair_cache_destroy,
  589. fuzzy_module_ctx->keypairs_cache);
  590. rspamd_mempool_add_destructor (cfg->cfg_pool,
  591. (rspamd_mempool_destruct_t)rspamd_ptr_array_free_hard,
  592. fuzzy_module_ctx->fuzzy_rules);
  593. *ctx = (struct module_ctx *)fuzzy_module_ctx;
  594. rspamd_rcl_add_doc_by_path (cfg,
  595. NULL,
  596. "Fuzzy check plugin",
  597. "fuzzy_check",
  598. UCL_OBJECT,
  599. NULL,
  600. 0,
  601. NULL,
  602. 0);
  603. rspamd_rcl_add_doc_by_path (cfg,
  604. "fuzzy_check",
  605. "Default symbol",
  606. "symbol",
  607. UCL_STRING,
  608. NULL,
  609. 0,
  610. NULL,
  611. 0);
  612. rspamd_rcl_add_doc_by_path (cfg,
  613. "fuzzy_check",
  614. "Minimum number of *words* to check a text part",
  615. "min_length",
  616. UCL_INT,
  617. NULL,
  618. 0,
  619. NULL,
  620. 0);
  621. rspamd_rcl_add_doc_by_path (cfg,
  622. "fuzzy_check",
  623. "Minimum number of *bytes* to check a non-text part",
  624. "min_bytes",
  625. UCL_INT,
  626. NULL,
  627. 0,
  628. NULL,
  629. 0);
  630. rspamd_rcl_add_doc_by_path (cfg,
  631. "fuzzy_check",
  632. "Multiplier for bytes limit when checking for text parts",
  633. "text_multiplier",
  634. UCL_FLOAT,
  635. NULL,
  636. 0,
  637. NULL,
  638. 0);
  639. rspamd_rcl_add_doc_by_path (cfg,
  640. "fuzzy_check",
  641. "Minimum height in pixels for embedded images to check using fuzzy storage",
  642. "min_height",
  643. UCL_INT,
  644. NULL,
  645. 0,
  646. NULL,
  647. 0);
  648. rspamd_rcl_add_doc_by_path (cfg,
  649. "fuzzy_check",
  650. "Minimum width in pixels for embedded images to check using fuzzy storage",
  651. "min_width",
  652. UCL_INT,
  653. NULL,
  654. 0,
  655. NULL,
  656. 0);
  657. rspamd_rcl_add_doc_by_path (cfg,
  658. "fuzzy_check",
  659. "Timeout for waiting reply from a fuzzy server",
  660. "timeout",
  661. UCL_TIME,
  662. NULL,
  663. 0,
  664. NULL,
  665. 0);
  666. rspamd_rcl_add_doc_by_path (cfg,
  667. "fuzzy_check",
  668. "Maximum number of retransmits for a single request",
  669. "retransmits",
  670. UCL_INT,
  671. NULL,
  672. 0,
  673. NULL,
  674. 0);
  675. rspamd_rcl_add_doc_by_path (cfg,
  676. "fuzzy_check",
  677. "Maximum number of upstream errors, affects error rate threshold",
  678. "max_errors",
  679. UCL_INT,
  680. NULL,
  681. 0,
  682. NULL,
  683. 0);
  684. rspamd_rcl_add_doc_by_path (cfg,
  685. "fuzzy_check",
  686. "Time to lapse before re-resolve faulty upstream",
  687. "revive_time",
  688. UCL_FLOAT,
  689. NULL,
  690. 0,
  691. NULL,
  692. 0);
  693. rspamd_rcl_add_doc_by_path (cfg,
  694. "fuzzy_check",
  695. "Whitelisted IPs map",
  696. "whitelist",
  697. UCL_STRING,
  698. NULL,
  699. 0,
  700. NULL,
  701. 0);
  702. /* Rules doc strings */
  703. rspamd_rcl_add_doc_by_path (cfg,
  704. "fuzzy_check",
  705. "Fuzzy check rule",
  706. "rule",
  707. UCL_OBJECT,
  708. NULL,
  709. 0,
  710. NULL,
  711. 0);
  712. rspamd_rcl_add_doc_by_path (cfg,
  713. "fuzzy_check.rule",
  714. "Headers that are used to make a separate hash",
  715. "headers",
  716. UCL_ARRAY,
  717. NULL,
  718. 0,
  719. NULL,
  720. 0);
  721. rspamd_rcl_add_doc_by_path (cfg,
  722. "fuzzy_check.rule",
  723. "Whitelisted hashes map",
  724. "skip_hashes",
  725. UCL_STRING,
  726. NULL,
  727. 0,
  728. NULL,
  729. 0);
  730. rspamd_rcl_add_doc_by_path (cfg,
  731. "fuzzy_check.rule",
  732. "Set of mime types (in form type/subtype, or type/*, or *) to check with fuzzy",
  733. "mime_types",
  734. UCL_ARRAY,
  735. NULL,
  736. 0,
  737. NULL,
  738. 0);
  739. rspamd_rcl_add_doc_by_path (cfg,
  740. "fuzzy_check.rule",
  741. "Maximum value for fuzzy hash when weight of symbol is exactly 1.0 (if value is higher then score is still 1.0)",
  742. "max_score",
  743. UCL_INT,
  744. NULL,
  745. 0,
  746. NULL,
  747. 0);
  748. rspamd_rcl_add_doc_by_path (cfg,
  749. "fuzzy_check.rule",
  750. "List of servers to check (or learn)",
  751. "servers",
  752. UCL_STRING,
  753. NULL,
  754. 0,
  755. NULL,
  756. 0);
  757. rspamd_rcl_add_doc_by_path (cfg,
  758. "fuzzy_check.rule",
  759. "If true then never try to learn this fuzzy storage",
  760. "read_only",
  761. UCL_BOOLEAN,
  762. NULL,
  763. 0,
  764. NULL,
  765. 0);
  766. rspamd_rcl_add_doc_by_path (cfg,
  767. "fuzzy_check.rule",
  768. "If true then ignore unknown flags and not add the default fuzzy symbol",
  769. "skip_unknown",
  770. UCL_BOOLEAN,
  771. NULL,
  772. 0,
  773. NULL,
  774. 0);
  775. rspamd_rcl_add_doc_by_path (cfg,
  776. "fuzzy_check.rule",
  777. "Default symbol for rule (if no flags defined or matched)",
  778. "symbol",
  779. UCL_STRING,
  780. NULL,
  781. 0,
  782. NULL,
  783. 0);
  784. rspamd_rcl_add_doc_by_path (cfg,
  785. "fuzzy_check.rule",
  786. "Base32 value for the protocol encryption public key",
  787. "encryption_key",
  788. UCL_STRING,
  789. NULL,
  790. 0,
  791. NULL,
  792. 0);
  793. rspamd_rcl_add_doc_by_path (cfg,
  794. "fuzzy_check.rule",
  795. "Base32 value for the hashing key (for private storages)",
  796. "fuzzy_key",
  797. UCL_STRING,
  798. NULL,
  799. 0,
  800. NULL,
  801. 0);
  802. rspamd_rcl_add_doc_by_path (cfg,
  803. "fuzzy_check.rule",
  804. "Base32 value for the shingles hashing key (for private storages)",
  805. "fuzzy_shingles_key",
  806. UCL_STRING,
  807. NULL,
  808. 0,
  809. NULL,
  810. 0);
  811. rspamd_rcl_add_doc_by_path (cfg,
  812. "fuzzy_check.rule",
  813. "Lua script that returns boolean function to check if this task "
  814. "should be considered when learning fuzzy storage",
  815. "learn_condition",
  816. UCL_STRING,
  817. NULL,
  818. 0,
  819. NULL,
  820. 0);
  821. rspamd_rcl_add_doc_by_path (cfg,
  822. "fuzzy_check.rule",
  823. "Map of SYMBOL -> data for flags configuration",
  824. "fuzzy_map",
  825. UCL_OBJECT,
  826. NULL,
  827. 0,
  828. NULL,
  829. 0);
  830. rspamd_rcl_add_doc_by_path (cfg,
  831. "fuzzy_check.rule",
  832. "Use direct hash for short texts",
  833. "short_text_direct_hash",
  834. UCL_BOOLEAN,
  835. NULL,
  836. 0,
  837. "true",
  838. 0);
  839. rspamd_rcl_add_doc_by_path (cfg,
  840. "fuzzy_check.rule",
  841. "Override module default min bytes for this rule",
  842. "min_bytes",
  843. UCL_INT,
  844. NULL,
  845. 0,
  846. NULL,
  847. 0);
  848. /* Fuzzy map doc strings */
  849. rspamd_rcl_add_doc_by_path (cfg,
  850. "fuzzy_check.rule.fuzzy_map",
  851. "Maximum score for this flag",
  852. "max_score",
  853. UCL_INT,
  854. NULL,
  855. 0,
  856. NULL,
  857. 0);
  858. rspamd_rcl_add_doc_by_path (cfg,
  859. "fuzzy_check.rule.fuzzy_map",
  860. "Flag number",
  861. "flag",
  862. UCL_INT,
  863. NULL,
  864. 0,
  865. NULL,
  866. 0);
  867. rspamd_rcl_add_doc_by_path (cfg,
  868. "fuzzy_check.rule",
  869. "Do no use subject to distinguish short text hashes",
  870. "no_subject",
  871. UCL_BOOLEAN,
  872. NULL,
  873. 0,
  874. "false",
  875. 0);
  876. rspamd_rcl_add_doc_by_path (cfg,
  877. "fuzzy_check.rule",
  878. "Disable sharing message stats with the fuzzy server",
  879. "no_share",
  880. UCL_BOOLEAN,
  881. NULL,
  882. 0,
  883. "false",
  884. 0);
  885. return 0;
  886. }
  887. gint
  888. fuzzy_check_module_config (struct rspamd_config *cfg, bool validate)
  889. {
  890. const ucl_object_t *value, *cur, *elt;
  891. ucl_object_iter_t it;
  892. gint res = TRUE, cb_id, nrules = 0;
  893. lua_State *L = cfg->lua_state;
  894. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  895. if (!rspamd_config_is_module_enabled (cfg, "fuzzy_check")) {
  896. return TRUE;
  897. }
  898. fuzzy_module_ctx->enabled = TRUE;
  899. fuzzy_module_ctx->check_mime_part_ref = -1;
  900. fuzzy_module_ctx->process_rule_ref = -1;
  901. fuzzy_module_ctx->cleanup_rules_ref = -1;
  902. /* Interact with lua_fuzzy */
  903. if (luaL_dostring (L, "return require \"lua_fuzzy\"") != 0) {
  904. msg_err_config ("cannot require lua_fuzzy: %s",
  905. lua_tostring (L, -1));
  906. fuzzy_module_ctx->enabled = FALSE;
  907. }
  908. else {
  909. #if LUA_VERSION_NUM >= 504
  910. lua_settop(L, -2);
  911. #endif
  912. if (lua_type (L, -1) != LUA_TTABLE) {
  913. msg_err_config ("lua fuzzy must return "
  914. "table and not %s",
  915. lua_typename (L, lua_type (L, -1)));
  916. fuzzy_module_ctx->enabled = FALSE;
  917. }
  918. else {
  919. lua_pushstring (L, "process_rule");
  920. lua_gettable (L, -2);
  921. if (lua_type (L, -1) != LUA_TFUNCTION) {
  922. msg_err_config ("process_rule must return "
  923. "function and not %s",
  924. lua_typename (L, lua_type (L, -1)));
  925. fuzzy_module_ctx->enabled = FALSE;
  926. }
  927. else {
  928. fuzzy_module_ctx->process_rule_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  929. }
  930. lua_pushstring (L, "check_mime_part");
  931. lua_gettable (L, -2);
  932. if (lua_type (L, -1) != LUA_TFUNCTION) {
  933. msg_err_config ("check_mime_part must return "
  934. "function and not %s",
  935. lua_typename (L, lua_type (L, -1)));
  936. fuzzy_module_ctx->enabled = FALSE;
  937. }
  938. else {
  939. fuzzy_module_ctx->check_mime_part_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  940. }
  941. lua_pushstring (L, "cleanup_rules");
  942. lua_gettable (L, -2);
  943. if (lua_type (L, -1) != LUA_TFUNCTION) {
  944. msg_err_config ("cleanup_rules must return "
  945. "function and not %s",
  946. lua_typename (L, lua_type (L, -1)));
  947. fuzzy_module_ctx->enabled = FALSE;
  948. }
  949. else {
  950. fuzzy_module_ctx->cleanup_rules_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  951. }
  952. }
  953. }
  954. lua_settop (L, 0);
  955. if (!fuzzy_module_ctx->enabled) {
  956. return TRUE;
  957. }
  958. if ((value =
  959. rspamd_config_get_module_opt (cfg, "fuzzy_check", "symbol")) != NULL) {
  960. fuzzy_module_ctx->default_symbol = ucl_obj_tostring (value);
  961. }
  962. else {
  963. fuzzy_module_ctx->default_symbol = DEFAULT_SYMBOL;
  964. }
  965. if ((value =
  966. rspamd_config_get_module_opt (cfg, "fuzzy_check", "timeout")) != NULL) {
  967. fuzzy_module_ctx->io_timeout = ucl_obj_todouble (value);
  968. }
  969. else {
  970. fuzzy_module_ctx->io_timeout = DEFAULT_IO_TIMEOUT;
  971. }
  972. if ((value =
  973. rspamd_config_get_module_opt (cfg,
  974. "fuzzy_check",
  975. "retransmits")) != NULL) {
  976. fuzzy_module_ctx->retransmits = ucl_obj_toint (value);
  977. }
  978. else {
  979. fuzzy_module_ctx->retransmits = DEFAULT_RETRANSMITS;
  980. }
  981. if ((value =
  982. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  983. "max_errors")) != NULL) {
  984. fuzzy_module_ctx->max_errors = ucl_obj_toint (value);
  985. }
  986. else {
  987. fuzzy_module_ctx->max_errors = DEFAULT_MAX_ERRORS;
  988. }
  989. if ((value =
  990. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  991. "revive_time")) != NULL) {
  992. fuzzy_module_ctx->revive_time = ucl_obj_todouble (value);
  993. }
  994. else {
  995. fuzzy_module_ctx->revive_time = DEFAULT_REVIVE_TIME;
  996. }
  997. if ((value =
  998. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  999. "whitelist")) != NULL) {
  1000. rspamd_config_radix_from_ucl (cfg, value, "Fuzzy whitelist",
  1001. &fuzzy_module_ctx->whitelist,
  1002. NULL,
  1003. NULL, "fuzzy ip whitelist");
  1004. }
  1005. else {
  1006. fuzzy_module_ctx->whitelist = NULL;
  1007. }
  1008. if ((value =
  1009. rspamd_config_get_module_opt (cfg, "fuzzy_check", "rule")) != NULL) {
  1010. cb_id = rspamd_symcache_add_symbol (cfg->cache,
  1011. "FUZZY_CALLBACK", 0, fuzzy_symbol_callback, NULL,
  1012. SYMBOL_TYPE_CALLBACK | SYMBOL_TYPE_FINE,
  1013. -1);
  1014. rspamd_config_add_symbol (cfg,
  1015. "FUZZY_CALLBACK",
  1016. 0.0,
  1017. "Fuzzy check callback",
  1018. "fuzzy",
  1019. RSPAMD_SYMBOL_FLAG_IGNORE_METRIC,
  1020. 1,
  1021. 1);
  1022. /*
  1023. * Here we can have 2 possibilities:
  1024. *
  1025. * unnamed rules:
  1026. *
  1027. * rule {
  1028. * ...
  1029. * }
  1030. * rule {
  1031. * ...
  1032. * }
  1033. *
  1034. * - or - named rules:
  1035. *
  1036. * rule {
  1037. * "rule1": {
  1038. * ...
  1039. * }
  1040. * "rule2": {
  1041. * ...
  1042. * }
  1043. * }
  1044. *
  1045. * So, for each element, we check, if there 'servers' key. If 'servers' is
  1046. * presented, then we treat it as unnamed rule, otherwise we treat it as
  1047. * named rule.
  1048. */
  1049. LL_FOREACH (value, cur) {
  1050. if (ucl_object_lookup (cur, "servers")) {
  1051. /* Unnamed rule */
  1052. fuzzy_parse_rule (cfg, cur, NULL, cb_id);
  1053. nrules ++;
  1054. }
  1055. else {
  1056. /* Named rule */
  1057. it = NULL;
  1058. while ((elt = ucl_object_iterate (cur, &it, true)) != NULL) {
  1059. fuzzy_parse_rule (cfg, elt, ucl_object_key (elt), cb_id);
  1060. nrules ++;
  1061. }
  1062. }
  1063. }
  1064. /* We want that to check bad mime attachments */
  1065. rspamd_symcache_add_delayed_dependency (cfg->cache,
  1066. "FUZZY_CALLBACK", "MIME_TYPES_CALLBACK");
  1067. }
  1068. if (fuzzy_module_ctx->fuzzy_rules == NULL) {
  1069. msg_warn_config ("fuzzy module is enabled but no rules are defined");
  1070. }
  1071. msg_info_config ("init internal fuzzy_check module, %d rules loaded",
  1072. nrules);
  1073. /* Register global methods */
  1074. lua_getglobal (L, "rspamd_plugins");
  1075. if (lua_type (L, -1) == LUA_TTABLE) {
  1076. lua_pushstring (L, "fuzzy_check");
  1077. lua_createtable (L, 0, 3);
  1078. /* Set methods */
  1079. lua_pushstring (L, "unlearn");
  1080. lua_pushcfunction (L, fuzzy_lua_unlearn_handler);
  1081. lua_settable (L, -3);
  1082. lua_pushstring (L, "learn");
  1083. lua_pushcfunction (L, fuzzy_lua_learn_handler);
  1084. lua_settable (L, -3);
  1085. lua_pushstring (L, "gen_hashes");
  1086. lua_pushcfunction (L, fuzzy_lua_gen_hashes_handler);
  1087. lua_settable (L, -3);
  1088. /* Finish fuzzy_check key */
  1089. lua_settable (L, -3);
  1090. }
  1091. lua_settop (L, 0);
  1092. return res;
  1093. }
  1094. gint
  1095. fuzzy_check_module_reconfig (struct rspamd_config *cfg)
  1096. {
  1097. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  1098. if (fuzzy_module_ctx->cleanup_rules_ref != -1) {
  1099. /* Sync lua_fuzzy rules */
  1100. gint err_idx, ret;
  1101. lua_State *L = (lua_State *)cfg->lua_state;
  1102. lua_pushcfunction (L, &rspamd_lua_traceback);
  1103. err_idx = lua_gettop (L);
  1104. lua_rawgeti (L, LUA_REGISTRYINDEX, fuzzy_module_ctx->cleanup_rules_ref);
  1105. if ((ret = lua_pcall (L, 0, 0, err_idx)) != 0) {
  1106. msg_err_config ("call to cleanup_rules lua "
  1107. "script failed (%d): %s", ret, lua_tostring (L, -1));
  1108. }
  1109. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1110. fuzzy_module_ctx->cleanup_rules_ref);
  1111. lua_settop (L, 0);
  1112. }
  1113. if (fuzzy_module_ctx->check_mime_part_ref != -1) {
  1114. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1115. fuzzy_module_ctx->check_mime_part_ref);
  1116. }
  1117. if (fuzzy_module_ctx->process_rule_ref != -1) {
  1118. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1119. fuzzy_module_ctx->process_rule_ref);
  1120. }
  1121. return fuzzy_check_module_config (cfg, false);
  1122. }
  1123. /* Finalize IO */
  1124. static void
  1125. fuzzy_io_fin (void *ud)
  1126. {
  1127. struct fuzzy_client_session *session = ud;
  1128. if (session->commands) {
  1129. g_ptr_array_free (session->commands, TRUE);
  1130. }
  1131. if (session->results) {
  1132. g_ptr_array_free (session->results, TRUE);
  1133. }
  1134. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  1135. close (session->fd);
  1136. }
  1137. static GArray *
  1138. fuzzy_preprocess_words (struct rspamd_mime_text_part *part, rspamd_mempool_t *pool)
  1139. {
  1140. return part->utf_words;
  1141. }
  1142. static void
  1143. fuzzy_encrypt_cmd (struct fuzzy_rule *rule,
  1144. struct rspamd_fuzzy_encrypted_req_hdr *hdr,
  1145. guchar *data, gsize datalen)
  1146. {
  1147. const guchar *pk;
  1148. guint pklen;
  1149. g_assert (hdr != NULL);
  1150. g_assert (data != NULL);
  1151. g_assert (rule != NULL);
  1152. /* Encrypt data */
  1153. memcpy (hdr->magic,
  1154. fuzzy_encrypted_magic,
  1155. sizeof (hdr->magic));
  1156. ottery_rand_bytes (hdr->nonce, sizeof (hdr->nonce));
  1157. pk = rspamd_keypair_component (rule->local_key,
  1158. RSPAMD_KEYPAIR_COMPONENT_PK, &pklen);
  1159. memcpy (hdr->pubkey, pk, MIN (pklen, sizeof (hdr->pubkey)));
  1160. pk = rspamd_pubkey_get_pk (rule->peer_key, &pklen);
  1161. memcpy (hdr->key_id, pk, MIN (sizeof (hdr->key_id), pklen));
  1162. rspamd_keypair_cache_process (rule->ctx->keypairs_cache,
  1163. rule->local_key, rule->peer_key);
  1164. rspamd_cryptobox_encrypt_nm_inplace (data, datalen,
  1165. hdr->nonce, rspamd_pubkey_get_nm (rule->peer_key, rule->local_key),
  1166. hdr->mac,
  1167. rspamd_pubkey_alg (rule->peer_key));
  1168. }
  1169. static struct fuzzy_cmd_io *
  1170. fuzzy_cmd_stat (struct fuzzy_rule *rule,
  1171. int c,
  1172. gint flag,
  1173. guint32 weight,
  1174. rspamd_mempool_t *pool)
  1175. {
  1176. struct rspamd_fuzzy_cmd *cmd;
  1177. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1178. struct fuzzy_cmd_io *io;
  1179. if (rule->peer_key) {
  1180. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1181. cmd = &enccmd->cmd;
  1182. }
  1183. else {
  1184. cmd = rspamd_mempool_alloc0 (pool, sizeof (*cmd));
  1185. }
  1186. cmd->cmd = c;
  1187. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1188. cmd->shingles_count = 0;
  1189. cmd->tag = ottery_rand_uint32 ();
  1190. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1191. io->flags = 0;
  1192. io->tag = cmd->tag;
  1193. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1194. if (rule->peer_key && enccmd) {
  1195. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd, sizeof (*cmd));
  1196. io->io.iov_base = enccmd;
  1197. io->io.iov_len = sizeof (*enccmd);
  1198. }
  1199. else {
  1200. io->io.iov_base = cmd;
  1201. io->io.iov_len = sizeof (*cmd);
  1202. }
  1203. return io;
  1204. }
  1205. static struct fuzzy_cmd_io *
  1206. fuzzy_cmd_hash (struct fuzzy_rule *rule,
  1207. int c,
  1208. const rspamd_ftok_t *hash,
  1209. gint flag,
  1210. guint32 weight,
  1211. rspamd_mempool_t *pool)
  1212. {
  1213. struct rspamd_fuzzy_cmd *cmd;
  1214. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1215. struct fuzzy_cmd_io *io;
  1216. if (rule->peer_key) {
  1217. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1218. cmd = &enccmd->cmd;
  1219. }
  1220. else {
  1221. cmd = rspamd_mempool_alloc0 (pool, sizeof (*cmd));
  1222. }
  1223. if (hash->len == sizeof (cmd->digest) * 2) {
  1224. /* It is hex encoding */
  1225. if (rspamd_decode_hex_buf (hash->begin, hash->len, cmd->digest,
  1226. sizeof (cmd->digest)) == -1) {
  1227. msg_err_pool ("cannot decode hash, wrong encoding");
  1228. return NULL;
  1229. }
  1230. }
  1231. else {
  1232. msg_err_pool ("cannot decode hash, wrong length: %z", hash->len);
  1233. return NULL;
  1234. }
  1235. cmd->cmd = c;
  1236. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1237. cmd->shingles_count = 0;
  1238. cmd->tag = ottery_rand_uint32 ();
  1239. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1240. io->flags = 0;
  1241. io->tag = cmd->tag;
  1242. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1243. if (rule->peer_key && enccmd) {
  1244. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd, sizeof (*cmd));
  1245. io->io.iov_base = enccmd;
  1246. io->io.iov_len = sizeof (*enccmd);
  1247. }
  1248. else {
  1249. io->io.iov_base = cmd;
  1250. io->io.iov_len = sizeof (*cmd);
  1251. }
  1252. return io;
  1253. }
  1254. struct rspamd_cached_shingles {
  1255. struct rspamd_shingle *sh;
  1256. guchar digest[rspamd_cryptobox_HASHBYTES];
  1257. guint additional_length;
  1258. guchar *additional_data;
  1259. };
  1260. static struct rspamd_cached_shingles *
  1261. fuzzy_cmd_get_cached (struct fuzzy_rule *rule,
  1262. struct rspamd_task *task,
  1263. struct rspamd_mime_part *mp)
  1264. {
  1265. gchar key[32];
  1266. gint key_part;
  1267. struct rspamd_cached_shingles **cached;
  1268. memcpy (&key_part, rule->shingles_key->str, sizeof (key_part));
  1269. rspamd_snprintf (key, sizeof (key), "%s%d", rule->algorithm_str,
  1270. key_part);
  1271. cached = (struct rspamd_cached_shingles **)rspamd_mempool_get_variable (
  1272. task->task_pool, key);
  1273. if (cached && cached[mp->part_number]) {
  1274. return cached[mp->part_number];
  1275. }
  1276. return NULL;
  1277. }
  1278. static void
  1279. fuzzy_cmd_set_cached (struct fuzzy_rule *rule,
  1280. struct rspamd_task *task,
  1281. struct rspamd_mime_part *mp,
  1282. struct rspamd_cached_shingles *data)
  1283. {
  1284. gchar key[32];
  1285. gint key_part;
  1286. struct rspamd_cached_shingles **cached;
  1287. memcpy (&key_part, rule->shingles_key->str, sizeof (key_part));
  1288. rspamd_snprintf (key, sizeof (key), "%s%d", rule->algorithm_str,
  1289. key_part);
  1290. cached = (struct rspamd_cached_shingles **)rspamd_mempool_get_variable (
  1291. task->task_pool, key);
  1292. if (cached) {
  1293. cached[mp->part_number] = data;
  1294. }
  1295. else {
  1296. cached = rspamd_mempool_alloc0 (task->task_pool, sizeof (*cached) *
  1297. (MESSAGE_FIELD (task, parts)->len + 1));
  1298. cached[mp->part_number] = data;
  1299. rspamd_mempool_set_variable (task->task_pool, key, cached, NULL);
  1300. }
  1301. }
  1302. static gboolean
  1303. fuzzy_rule_check_mimepart (struct rspamd_task *task,
  1304. struct fuzzy_rule *rule,
  1305. struct rspamd_mime_part *part,
  1306. gboolean *need_check,
  1307. gboolean *fuzzy_check)
  1308. {
  1309. lua_State *L = (lua_State *)task->cfg->lua_state;
  1310. gint old_top = lua_gettop (L);
  1311. if (rule->lua_id != -1 && rule->ctx->check_mime_part_ref != -1) {
  1312. gint err_idx, ret;
  1313. struct rspamd_task **ptask;
  1314. struct rspamd_mime_part **ppart;
  1315. lua_pushcfunction (L, &rspamd_lua_traceback);
  1316. err_idx = lua_gettop (L);
  1317. lua_rawgeti (L, LUA_REGISTRYINDEX, rule->ctx->check_mime_part_ref);
  1318. ptask = lua_newuserdata (L, sizeof (*ptask));
  1319. *ptask = task;
  1320. rspamd_lua_setclass (L, "rspamd{task}", -1);
  1321. ppart = lua_newuserdata (L, sizeof (*ppart));
  1322. *ppart = part;
  1323. rspamd_lua_setclass (L, "rspamd{mimepart}", -1);
  1324. lua_pushnumber (L, rule->lua_id);
  1325. if ((ret = lua_pcall (L, 3, 2, err_idx)) != 0) {
  1326. msg_err_task ("call to check_mime_part lua "
  1327. "script failed (%d): %s", ret, lua_tostring (L, -1));
  1328. ret = FALSE;
  1329. }
  1330. else {
  1331. ret = TRUE;
  1332. *need_check = lua_toboolean (L, -2);
  1333. *fuzzy_check = lua_toboolean (L, -1);
  1334. }
  1335. lua_settop (L, old_top);
  1336. return ret;
  1337. }
  1338. return FALSE;
  1339. }
  1340. #define MAX_FUZZY_DOMAIN 64
  1341. static guint
  1342. fuzzy_cmd_extension_length (struct rspamd_task *task,
  1343. struct fuzzy_rule *rule)
  1344. {
  1345. guint total = 0;
  1346. if (rule->no_share) {
  1347. return 0;
  1348. }
  1349. /* From domain */
  1350. if (MESSAGE_FIELD (task, from_mime) && MESSAGE_FIELD (task, from_mime)->len > 0) {
  1351. struct rspamd_email_address *addr = g_ptr_array_index (MESSAGE_FIELD (task,
  1352. from_mime), 0);
  1353. if (addr->domain_len > 0) {
  1354. total += 2; /* 2 bytes: type + length */
  1355. total += MIN (MAX_FUZZY_DOMAIN, addr->domain_len);
  1356. }
  1357. }
  1358. if (task->from_addr && rspamd_inet_address_get_af (task->from_addr) == AF_INET) {
  1359. total += sizeof (struct in_addr) + 1;
  1360. }
  1361. else if (task->from_addr&& rspamd_inet_address_get_af (task->from_addr) == AF_INET6) {
  1362. total += sizeof (struct in6_addr) + 1;
  1363. }
  1364. return total;
  1365. }
  1366. static guint
  1367. fuzzy_cmd_write_extensions (struct rspamd_task *task,
  1368. struct fuzzy_rule *rule,
  1369. guchar *dest,
  1370. gsize available)
  1371. {
  1372. guint written = 0;
  1373. if (rule->no_share) {
  1374. return 0;
  1375. }
  1376. if (MESSAGE_FIELD (task, from_mime) && MESSAGE_FIELD (task, from_mime)->len > 0) {
  1377. struct rspamd_email_address *addr = g_ptr_array_index (MESSAGE_FIELD (task,
  1378. from_mime), 0);
  1379. guint to_write = MIN (MAX_FUZZY_DOMAIN, addr->domain_len) + 2;
  1380. if (to_write > 0 && to_write <= available) {
  1381. *dest++ = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
  1382. *dest++ = to_write - 2;
  1383. if (addr->domain_len < MAX_FUZZY_DOMAIN) {
  1384. memcpy (dest, addr->domain, addr->domain_len);
  1385. dest += addr->domain_len;
  1386. }
  1387. else {
  1388. /* Trim from left */
  1389. memcpy (dest,
  1390. addr->domain + (addr->domain_len - MAX_FUZZY_DOMAIN),
  1391. MAX_FUZZY_DOMAIN);
  1392. dest += MAX_FUZZY_DOMAIN;
  1393. }
  1394. available -= to_write;
  1395. written += to_write;
  1396. }
  1397. }
  1398. if (task->from_addr && rspamd_inet_address_get_af (task->from_addr) == AF_INET) {
  1399. if (available >= sizeof (struct in_addr) + 1) {
  1400. guint klen;
  1401. guchar *inet_data = rspamd_inet_address_get_hash_key (task->from_addr, &klen);
  1402. *dest++ = RSPAMD_FUZZY_EXT_SOURCE_IP4;
  1403. memcpy (dest, inet_data, klen);
  1404. dest += klen;
  1405. available -= klen + 1;
  1406. written += klen + 1;
  1407. }
  1408. }
  1409. else if (task->from_addr && rspamd_inet_address_get_af (task->from_addr) == AF_INET6) {
  1410. if (available >= sizeof (struct in6_addr) + 1) {
  1411. guint klen;
  1412. guchar *inet_data = rspamd_inet_address_get_hash_key (task->from_addr, &klen);
  1413. *dest++ = RSPAMD_FUZZY_EXT_SOURCE_IP6;
  1414. memcpy (dest, inet_data, klen);
  1415. dest += klen;
  1416. available -= klen + 1;
  1417. written += klen + 1;
  1418. }
  1419. }
  1420. return written;
  1421. }
  1422. /*
  1423. * Create fuzzy command from a text part
  1424. */
  1425. static struct fuzzy_cmd_io *
  1426. fuzzy_cmd_from_text_part (struct rspamd_task *task,
  1427. struct fuzzy_rule *rule,
  1428. int c,
  1429. gint flag,
  1430. guint32 weight,
  1431. gboolean short_text,
  1432. struct rspamd_mime_text_part *part,
  1433. struct rspamd_mime_part *mp)
  1434. {
  1435. struct rspamd_fuzzy_shingle_cmd *shcmd = NULL;
  1436. struct rspamd_fuzzy_cmd *cmd = NULL;
  1437. struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd = NULL;
  1438. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1439. struct rspamd_cached_shingles *cached = NULL;
  1440. struct rspamd_shingle *sh = NULL;
  1441. guint i;
  1442. rspamd_cryptobox_hash_state_t st;
  1443. rspamd_stat_token_t *word;
  1444. GArray *words;
  1445. struct fuzzy_cmd_io *io;
  1446. guint additional_length;
  1447. guchar *additional_data;
  1448. cached = fuzzy_cmd_get_cached (rule, task, mp);
  1449. /*
  1450. * Important note:
  1451. *
  1452. * We assume that fuzzy io is a consistent memory layout to fit into
  1453. * iov structure of size 1
  1454. *
  1455. * However, there are 4 possibilities:
  1456. * 1) non encrypted, non shingle command - just one cmd
  1457. * 2) encrypted, non shingle command - encryption hdr + cmd
  1458. * 3) non encrypted, shingle command - cmd + shingle
  1459. * 4) encrypted, shingle command - encryption hdr + cmd + shingle
  1460. *
  1461. * Extensions are always at the end, but since we also have caching (sigh, meh...)
  1462. * then we have one piece that looks like cmd (+ shingle) + extensions
  1463. * To encrypt it optionally we take this memory and prepend encryption header
  1464. *
  1465. * In case of cached version we do the same: allocate, copy from cached (including extra)
  1466. * and optionally encrypt.
  1467. *
  1468. * However, there should be no extensions in case of unencrypted connection
  1469. * (for sanity + privacy).
  1470. */
  1471. if (cached) {
  1472. additional_length = cached->additional_length;
  1473. additional_data = cached->additional_data;
  1474. /* Copy cached */
  1475. if (short_text) {
  1476. enccmd = rspamd_mempool_alloc0 (task->task_pool,
  1477. sizeof (*enccmd) + additional_length);
  1478. cmd = &enccmd->cmd;
  1479. memcpy (cmd->digest, cached->digest,
  1480. sizeof (cached->digest));
  1481. cmd->shingles_count = 0;
  1482. memcpy (((guchar *)enccmd) + sizeof (*enccmd), additional_data,
  1483. additional_length);
  1484. }
  1485. else if (cached->sh) {
  1486. encshcmd = rspamd_mempool_alloc0 (task->task_pool,
  1487. additional_length + sizeof (*encshcmd));
  1488. shcmd = &encshcmd->cmd;
  1489. memcpy (&shcmd->sgl, cached->sh, sizeof (struct rspamd_shingle));
  1490. memcpy (shcmd->basic.digest, cached->digest,
  1491. sizeof (cached->digest));
  1492. memcpy (((guchar *)encshcmd) + sizeof (*encshcmd), additional_data,
  1493. additional_length);
  1494. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1495. }
  1496. else {
  1497. return NULL;
  1498. }
  1499. }
  1500. else {
  1501. additional_length = fuzzy_cmd_extension_length (task, rule);
  1502. cached = rspamd_mempool_alloc0 (task->task_pool, sizeof (*cached) +
  1503. additional_length);
  1504. /*
  1505. * Allocate extensions and never touch it except copying to avoid
  1506. * occasional encryption
  1507. */
  1508. cached->additional_length = additional_length;
  1509. cached->additional_data = ((guchar *)cached) + sizeof (*cached);
  1510. if (additional_length > 0) {
  1511. fuzzy_cmd_write_extensions (task, rule, cached->additional_data,
  1512. additional_length);
  1513. }
  1514. if (short_text) {
  1515. enccmd = rspamd_mempool_alloc0 (task->task_pool,
  1516. sizeof (*enccmd) + additional_length);
  1517. cmd = &enccmd->cmd;
  1518. rspamd_cryptobox_hash_init (&st, rule->hash_key->str,
  1519. rule->hash_key->len);
  1520. rspamd_cryptobox_hash_update (&st, part->utf_stripped_content->data,
  1521. part->utf_stripped_content->len);
  1522. if (!rule->no_subject && (MESSAGE_FIELD (task, subject))) {
  1523. /* We also include subject */
  1524. rspamd_cryptobox_hash_update (&st, MESSAGE_FIELD (task, subject),
  1525. strlen (MESSAGE_FIELD (task, subject)));
  1526. }
  1527. rspamd_cryptobox_hash_final (&st, cmd->digest);
  1528. memcpy (cached->digest, cmd->digest, sizeof (cached->digest));
  1529. cached->sh = NULL;
  1530. additional_data = ((guchar *)enccmd) + sizeof (*enccmd);
  1531. memcpy (additional_data, cached->additional_data, additional_length);
  1532. }
  1533. else {
  1534. encshcmd = rspamd_mempool_alloc0 (task->task_pool,
  1535. sizeof (*encshcmd) + additional_length);
  1536. shcmd = &encshcmd->cmd;
  1537. /*
  1538. * Generate hash from all words in the part
  1539. */
  1540. rspamd_cryptobox_hash_init (&st, rule->hash_key->str, rule->hash_key->len);
  1541. words = fuzzy_preprocess_words (part, task->task_pool);
  1542. for (i = 0; i < words->len; i ++) {
  1543. word = &g_array_index (words, rspamd_stat_token_t, i);
  1544. if (!((word->flags & RSPAMD_STAT_TOKEN_FLAG_SKIPPED)
  1545. || word->stemmed.len == 0)) {
  1546. rspamd_cryptobox_hash_update (&st, word->stemmed.begin,
  1547. word->stemmed.len);
  1548. }
  1549. }
  1550. rspamd_cryptobox_hash_final (&st, shcmd->basic.digest);
  1551. msg_debug_task ("loading shingles of type %s with key %*xs",
  1552. rule->algorithm_str,
  1553. 16, rule->shingles_key->str);
  1554. sh = rspamd_shingles_from_text (words,
  1555. rule->shingles_key->str, task->task_pool,
  1556. rspamd_shingles_default_filter, NULL,
  1557. rule->alg);
  1558. if (sh != NULL) {
  1559. memcpy (&shcmd->sgl, sh, sizeof (shcmd->sgl));
  1560. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1561. }
  1562. else {
  1563. /* No shingles, no check */
  1564. return NULL;
  1565. }
  1566. cached->sh = sh;
  1567. memcpy (cached->digest, shcmd->basic.digest, sizeof (cached->digest));
  1568. additional_data = ((guchar *)encshcmd) + sizeof (*encshcmd);
  1569. memcpy (additional_data, cached->additional_data, additional_length);
  1570. }
  1571. /*
  1572. * We always save encrypted command as it can handle both
  1573. * encrypted and unencrypted requests.
  1574. *
  1575. * Since it is copied when obtained from the cache, it is safe to use
  1576. * it this way.
  1577. */
  1578. fuzzy_cmd_set_cached (rule, task, mp, cached);
  1579. }
  1580. io = rspamd_mempool_alloc (task->task_pool, sizeof (*io));
  1581. io->part = mp;
  1582. if (!short_text) {
  1583. shcmd->basic.tag = ottery_rand_uint32 ();
  1584. shcmd->basic.cmd = c;
  1585. shcmd->basic.version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1586. if (c != FUZZY_CHECK) {
  1587. shcmd->basic.flag = flag;
  1588. shcmd->basic.value = weight;
  1589. }
  1590. io->tag = shcmd->basic.tag;
  1591. memcpy (&io->cmd, &shcmd->basic, sizeof (io->cmd));
  1592. }
  1593. else {
  1594. cmd->tag = ottery_rand_uint32 ();
  1595. cmd->cmd = c;
  1596. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1597. if (c != FUZZY_CHECK) {
  1598. cmd->flag = flag;
  1599. cmd->value = weight;
  1600. }
  1601. io->tag = cmd->tag;
  1602. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1603. }
  1604. io->flags = 0;
  1605. if (rule->peer_key) {
  1606. /* Encrypt data */
  1607. if (!short_text) {
  1608. fuzzy_encrypt_cmd (rule, &encshcmd->hdr, (guchar *) shcmd,
  1609. sizeof (*shcmd) + additional_length);
  1610. io->io.iov_base = encshcmd;
  1611. io->io.iov_len = sizeof (*encshcmd) + additional_length;
  1612. }
  1613. else {
  1614. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd,
  1615. sizeof (*cmd) + additional_length);
  1616. io->io.iov_base = enccmd;
  1617. io->io.iov_len = sizeof (*enccmd) + additional_length;
  1618. }
  1619. }
  1620. else {
  1621. if (!short_text) {
  1622. io->io.iov_base = shcmd;
  1623. io->io.iov_len = sizeof (*shcmd) + additional_length;
  1624. }
  1625. else {
  1626. io->io.iov_base = cmd;
  1627. io->io.iov_len = sizeof (*cmd) + additional_length;
  1628. }
  1629. }
  1630. return io;
  1631. }
  1632. #if 0
  1633. static struct fuzzy_cmd_io *
  1634. fuzzy_cmd_from_image_part (struct fuzzy_rule *rule,
  1635. int c,
  1636. gint flag,
  1637. guint32 weight,
  1638. struct rspamd_task *task,
  1639. struct rspamd_image *img,
  1640. struct rspamd_mime_part *mp)
  1641. {
  1642. struct rspamd_fuzzy_shingle_cmd *shcmd;
  1643. struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd;
  1644. struct fuzzy_cmd_io *io;
  1645. struct rspamd_shingle *sh;
  1646. struct rspamd_cached_shingles *cached;
  1647. cached = fuzzy_cmd_get_cached (rule, task, mp);
  1648. if (cached) {
  1649. /* Copy cached */
  1650. encshcmd = rspamd_mempool_alloc0 (task->task_pool, sizeof (*encshcmd));
  1651. shcmd = &encshcmd->cmd;
  1652. memcpy (&shcmd->sgl, cached->sh, sizeof (struct rspamd_shingle));
  1653. memcpy (shcmd->basic.digest, cached->digest,
  1654. sizeof (cached->digest));
  1655. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1656. }
  1657. else {
  1658. encshcmd = rspamd_mempool_alloc0 (task->task_pool, sizeof (*encshcmd));
  1659. shcmd = &encshcmd->cmd;
  1660. /*
  1661. * Generate shingles
  1662. */
  1663. sh = rspamd_shingles_from_image (img->dct,
  1664. rule->shingles_key->str, task->task_pool,
  1665. rspamd_shingles_default_filter, NULL,
  1666. rule->alg);
  1667. if (sh != NULL) {
  1668. memcpy (&shcmd->sgl, sh->hashes, sizeof (shcmd->sgl));
  1669. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1670. #if 0
  1671. for (unsigned int i = 0; i < RSPAMD_SHINGLE_SIZE; i ++) {
  1672. msg_err ("shingle %d: %L", i, sh->hashes[i]);
  1673. }
  1674. #endif
  1675. }
  1676. rspamd_cryptobox_hash (shcmd->basic.digest,
  1677. (const guchar *)img->dct, RSPAMD_DCT_LEN / NBBY,
  1678. rule->hash_key->str, rule->hash_key->len);
  1679. msg_debug_task ("loading shingles of type %s with key %*xs",
  1680. rule->algorithm_str,
  1681. 16, rule->shingles_key->str);
  1682. /*
  1683. * We always save encrypted command as it can handle both
  1684. * encrypted and unencrypted requests.
  1685. *
  1686. * Since it is copied when obtained from the cache, it is safe to use
  1687. * it this way.
  1688. */
  1689. cached = rspamd_mempool_alloc (task->task_pool, sizeof (*cached));
  1690. cached->sh = sh;
  1691. memcpy (cached->digest, shcmd->basic.digest, sizeof (cached->digest));
  1692. fuzzy_cmd_set_cached (rule, task, mp, cached);
  1693. }
  1694. shcmd->basic.tag = ottery_rand_uint32 ();
  1695. shcmd->basic.cmd = c;
  1696. shcmd->basic.version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1697. if (c != FUZZY_CHECK) {
  1698. shcmd->basic.flag = flag;
  1699. shcmd->basic.value = weight;
  1700. }
  1701. io = rspamd_mempool_alloc (task->task_pool, sizeof (*io));
  1702. io->part = mp;
  1703. io->tag = shcmd->basic.tag;
  1704. io->flags = FUZZY_CMD_FLAG_IMAGE;
  1705. memcpy (&io->cmd, &shcmd->basic, sizeof (io->cmd));
  1706. if (rule->peer_key) {
  1707. /* Encrypt data */
  1708. fuzzy_encrypt_cmd (rule, &encshcmd->hdr, (guchar *) shcmd, sizeof (*shcmd));
  1709. io->io.iov_base = encshcmd;
  1710. io->io.iov_len = sizeof (*encshcmd);
  1711. }
  1712. else {
  1713. io->io.iov_base = shcmd;
  1714. io->io.iov_len = sizeof (*shcmd);
  1715. }
  1716. return io;
  1717. }
  1718. #endif
  1719. static struct fuzzy_cmd_io *
  1720. fuzzy_cmd_from_data_part (struct fuzzy_rule *rule,
  1721. int c,
  1722. gint flag,
  1723. guint32 weight,
  1724. struct rspamd_task *task,
  1725. guchar digest[rspamd_cryptobox_HASHBYTES],
  1726. struct rspamd_mime_part *mp)
  1727. {
  1728. struct rspamd_fuzzy_cmd *cmd;
  1729. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1730. struct fuzzy_cmd_io *io;
  1731. guint additional_length;
  1732. guchar *additional_data;
  1733. additional_length = fuzzy_cmd_extension_length (task, rule);
  1734. if (rule->peer_key) {
  1735. enccmd = rspamd_mempool_alloc0 (task->task_pool,
  1736. sizeof (*enccmd) + additional_length);
  1737. cmd = &enccmd->cmd;
  1738. additional_data = ((guchar *)enccmd) + sizeof (*enccmd);
  1739. }
  1740. else {
  1741. cmd = rspamd_mempool_alloc0 (task->task_pool,
  1742. sizeof (*cmd) + additional_length);
  1743. additional_data = ((guchar *)cmd) + sizeof (*cmd);
  1744. }
  1745. cmd->cmd = c;
  1746. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1747. if (c != FUZZY_CHECK) {
  1748. cmd->flag = flag;
  1749. cmd->value = weight;
  1750. }
  1751. cmd->shingles_count = 0;
  1752. cmd->tag = ottery_rand_uint32 ();
  1753. memcpy (cmd->digest, digest, sizeof (cmd->digest));
  1754. io = rspamd_mempool_alloc (task->task_pool, sizeof (*io));
  1755. io->flags = 0;
  1756. io->tag = cmd->tag;
  1757. io->part = mp;
  1758. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1759. if (additional_length > 0) {
  1760. fuzzy_cmd_write_extensions (task, rule, additional_data,
  1761. additional_length);
  1762. }
  1763. if (rule->peer_key) {
  1764. g_assert (enccmd != NULL);
  1765. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd,
  1766. sizeof (*cmd) + additional_length);
  1767. io->io.iov_base = enccmd;
  1768. io->io.iov_len = sizeof (*enccmd) + additional_length;
  1769. }
  1770. else {
  1771. io->io.iov_base = cmd;
  1772. io->io.iov_len = sizeof (*cmd) + additional_length;
  1773. }
  1774. return io;
  1775. }
  1776. static gboolean
  1777. fuzzy_cmd_to_wire (gint fd, struct iovec *io)
  1778. {
  1779. struct msghdr msg;
  1780. memset (&msg, 0, sizeof (msg));
  1781. msg.msg_iov = io;
  1782. msg.msg_iovlen = 1;
  1783. while (sendmsg (fd, &msg, 0) == -1) {
  1784. if (errno == EINTR) {
  1785. continue;
  1786. }
  1787. return FALSE;
  1788. }
  1789. return TRUE;
  1790. }
  1791. static gboolean
  1792. fuzzy_cmd_vector_to_wire (gint fd, GPtrArray *v)
  1793. {
  1794. guint i;
  1795. gboolean all_sent = TRUE, all_replied = TRUE;
  1796. struct fuzzy_cmd_io *io;
  1797. gboolean processed = FALSE;
  1798. /* First try to resend unsent commands */
  1799. for (i = 0; i < v->len; i ++) {
  1800. io = g_ptr_array_index (v, i);
  1801. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  1802. continue;
  1803. }
  1804. all_replied = FALSE;
  1805. if (!(io->flags & FUZZY_CMD_FLAG_SENT)) {
  1806. if (!fuzzy_cmd_to_wire (fd, &io->io)) {
  1807. return FALSE;
  1808. }
  1809. processed = TRUE;
  1810. io->flags |= FUZZY_CMD_FLAG_SENT;
  1811. all_sent = FALSE;
  1812. }
  1813. }
  1814. if (all_sent && !all_replied) {
  1815. /* Now try to resend each command in the vector */
  1816. for (i = 0; i < v->len; i++) {
  1817. io = g_ptr_array_index (v, i);
  1818. if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
  1819. io->flags &= ~FUZZY_CMD_FLAG_SENT;
  1820. }
  1821. }
  1822. return fuzzy_cmd_vector_to_wire (fd, v);
  1823. }
  1824. return processed;
  1825. }
  1826. /*
  1827. * Read replies one-by-one and remove them from req array
  1828. */
  1829. static const struct rspamd_fuzzy_reply *
  1830. fuzzy_process_reply (guchar **pos, gint *r, GPtrArray *req,
  1831. struct fuzzy_rule *rule, struct rspamd_fuzzy_cmd **pcmd,
  1832. struct fuzzy_cmd_io **pio)
  1833. {
  1834. guchar *p = *pos;
  1835. gint remain = *r;
  1836. guint i, required_size;
  1837. struct fuzzy_cmd_io *io;
  1838. const struct rspamd_fuzzy_reply *rep;
  1839. struct rspamd_fuzzy_encrypted_reply encrep;
  1840. gboolean found = FALSE;
  1841. if (rule->peer_key) {
  1842. required_size = sizeof (encrep);
  1843. }
  1844. else {
  1845. required_size = sizeof (*rep);
  1846. }
  1847. if (remain <= 0 || (guint)remain < required_size) {
  1848. return NULL;
  1849. }
  1850. if (rule->peer_key) {
  1851. memcpy (&encrep, p, sizeof (encrep));
  1852. *pos += required_size;
  1853. *r -= required_size;
  1854. /* Try to decrypt reply */
  1855. rspamd_keypair_cache_process (rule->ctx->keypairs_cache,
  1856. rule->local_key, rule->peer_key);
  1857. if (!rspamd_cryptobox_decrypt_nm_inplace ((guchar *)&encrep.rep,
  1858. sizeof (encrep.rep),
  1859. encrep.hdr.nonce,
  1860. rspamd_pubkey_get_nm (rule->peer_key, rule->local_key),
  1861. encrep.hdr.mac,
  1862. rspamd_pubkey_alg (rule->peer_key))) {
  1863. msg_info ("cannot decrypt reply");
  1864. return NULL;
  1865. }
  1866. /* Copy decrypted over the input wire */
  1867. memcpy (p, &encrep.rep, sizeof (encrep.rep));
  1868. }
  1869. else {
  1870. *pos += required_size;
  1871. *r -= required_size;
  1872. }
  1873. rep = (const struct rspamd_fuzzy_reply *) p;
  1874. /*
  1875. * Search for tag
  1876. */
  1877. for (i = 0; i < req->len; i ++) {
  1878. io = g_ptr_array_index (req, i);
  1879. if (io->tag == rep->v1.tag) {
  1880. if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
  1881. io->flags |= FUZZY_CMD_FLAG_REPLIED;
  1882. if (pcmd) {
  1883. *pcmd = &io->cmd;
  1884. }
  1885. if (pio) {
  1886. *pio = io;
  1887. }
  1888. return rep;
  1889. }
  1890. found = TRUE;
  1891. }
  1892. }
  1893. if (!found) {
  1894. msg_info ("unexpected tag: %ud", rep->v1.tag);
  1895. }
  1896. return NULL;
  1897. }
  1898. static void
  1899. fuzzy_insert_result (struct fuzzy_client_session *session,
  1900. const struct rspamd_fuzzy_reply *rep,
  1901. struct rspamd_fuzzy_cmd *cmd,
  1902. struct fuzzy_cmd_io *io,
  1903. guint flag)
  1904. {
  1905. const gchar *symbol;
  1906. struct fuzzy_mapping *map;
  1907. struct rspamd_task *task = session->task;
  1908. double weight;
  1909. double nval;
  1910. guchar buf[2048];
  1911. const gchar *type = "bin";
  1912. struct fuzzy_client_result *res;
  1913. gboolean is_fuzzy = FALSE;
  1914. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  1915. /* Discriminate scores for small images */
  1916. static const guint short_image_limit = 32 * 1024;
  1917. /* Get mapping by flag */
  1918. if ((map =
  1919. g_hash_table_lookup (session->rule->mappings,
  1920. GINT_TO_POINTER (rep->v1.flag))) == NULL) {
  1921. /* Default symbol and default weight */
  1922. symbol = session->rule->symbol;
  1923. weight = session->rule->max_score;
  1924. }
  1925. else {
  1926. /* Get symbol and weight from map */
  1927. symbol = map->symbol;
  1928. weight = map->weight;
  1929. }
  1930. res = rspamd_mempool_alloc0 (task->task_pool, sizeof (*res));
  1931. res->prob = rep->v1.prob;
  1932. res->symbol = symbol;
  1933. /*
  1934. * Hash is assumed to be found if probability is more than 0.5
  1935. * In that case `value` means number of matches
  1936. * Otherwise `value` means error code
  1937. */
  1938. nval = fuzzy_normalize (rep->v1.value, weight);
  1939. if (io) {
  1940. if ((io->flags & FUZZY_CMD_FLAG_IMAGE)) {
  1941. if (!io->part || io->part->parsed_data.len <= short_image_limit) {
  1942. nval *= rspamd_normalize_probability (rep->v1.prob, 0.5);
  1943. }
  1944. type = "img";
  1945. res->type = FUZZY_RESULT_IMG;
  1946. }
  1947. else {
  1948. /* Calc real probability */
  1949. nval *= sqrtf (rep->v1.prob);
  1950. if (cmd->shingles_count > 0) {
  1951. type = "txt";
  1952. res->type = FUZZY_RESULT_TXT;
  1953. }
  1954. else {
  1955. if (io->flags & FUZZY_CMD_FLAG_CONTENT) {
  1956. type = "content";
  1957. res->type = FUZZY_RESULT_CONTENT;
  1958. }
  1959. else {
  1960. res->type = FUZZY_RESULT_BIN;
  1961. }
  1962. }
  1963. }
  1964. }
  1965. res->score = nval;
  1966. if (memcmp (rep->digest, cmd->digest, sizeof (rep->digest)) != 0) {
  1967. is_fuzzy = TRUE;
  1968. }
  1969. if (map != NULL || !session->rule->skip_unknown) {
  1970. GList *fuzzy_var;
  1971. rspamd_fstring_t *hex_result;
  1972. gchar timebuf[64];
  1973. struct tm tm_split;
  1974. if (session->rule->skip_map) {
  1975. rspamd_encode_hex_buf (cmd->digest, sizeof (cmd->digest),
  1976. hexbuf, sizeof (hexbuf) - 1);
  1977. hexbuf[sizeof (hexbuf) - 1] = '\0';
  1978. if (rspamd_match_hash_map (session->rule->skip_map, hexbuf,
  1979. sizeof (hexbuf) - 1)) {
  1980. return;
  1981. }
  1982. }
  1983. rspamd_encode_hex_buf (rep->digest, sizeof (rep->digest),
  1984. hexbuf, sizeof (hexbuf) - 1);
  1985. hexbuf[sizeof (hexbuf) - 1] = '\0';
  1986. rspamd_gmtime (rep->ts, &tm_split);
  1987. rspamd_snprintf (timebuf, sizeof (timebuf), "%02d.%02d.%4d %02d:%02d:%02d GMT",
  1988. tm_split.tm_mday,
  1989. tm_split.tm_mon + 1,
  1990. tm_split.tm_year + 1900,
  1991. tm_split.tm_hour, tm_split.tm_min, tm_split.tm_sec);
  1992. if (is_fuzzy) {
  1993. msg_info_task (
  1994. "found fuzzy hash(%s) %s (%*xs requested) with weight: "
  1995. "%.2f, probability %.2f, in list: %s:%d%s; added on %s",
  1996. type,
  1997. hexbuf,
  1998. (gint) sizeof (cmd->digest), cmd->digest,
  1999. nval,
  2000. (gdouble) rep->v1.prob,
  2001. symbol,
  2002. rep->v1.flag,
  2003. map == NULL ? "(unknown)" : "",
  2004. timebuf);
  2005. }
  2006. else {
  2007. msg_info_task (
  2008. "found exact fuzzy hash(%s) %s with weight: "
  2009. "%.2f, probability %.2f, in list: %s:%d%s; added on %s",
  2010. type,
  2011. hexbuf,
  2012. nval,
  2013. (gdouble) rep->v1.prob,
  2014. symbol,
  2015. rep->v1.flag,
  2016. map == NULL ? "(unknown)" : "",
  2017. timebuf);
  2018. }
  2019. rspamd_snprintf (buf,
  2020. sizeof (buf),
  2021. "%d:%*s:%.2f:%s",
  2022. rep->v1.flag,
  2023. (gint)MIN(rspamd_fuzzy_hash_len * 2, sizeof (rep->digest) * 2), hexbuf,
  2024. rep->v1.prob,
  2025. type);
  2026. res->option = rspamd_mempool_strdup (task->task_pool, buf);
  2027. g_ptr_array_add (session->results, res);
  2028. /* Store hex string in pool variable */
  2029. hex_result = rspamd_mempool_alloc (task->task_pool,
  2030. sizeof (rspamd_fstring_t) + sizeof (hexbuf));
  2031. memcpy (hex_result->str, hexbuf, sizeof (hexbuf));
  2032. hex_result->len = sizeof (hexbuf) - 1;
  2033. hex_result->allocated = (gsize)-1;
  2034. fuzzy_var = rspamd_mempool_get_variable (task->task_pool,
  2035. RSPAMD_MEMPOOL_FUZZY_RESULT);
  2036. if (fuzzy_var == NULL) {
  2037. fuzzy_var = g_list_prepend (NULL, hex_result);
  2038. rspamd_mempool_set_variable (task->task_pool,
  2039. RSPAMD_MEMPOOL_FUZZY_RESULT, fuzzy_var,
  2040. (rspamd_mempool_destruct_t)g_list_free);
  2041. }
  2042. else {
  2043. /* Not very efficient, but we don't really use it intensively */
  2044. fuzzy_var = g_list_append (fuzzy_var, hex_result);
  2045. }
  2046. }
  2047. }
  2048. static gint
  2049. fuzzy_check_try_read (struct fuzzy_client_session *session)
  2050. {
  2051. struct rspamd_task *task;
  2052. const struct rspamd_fuzzy_reply *rep;
  2053. struct rspamd_fuzzy_cmd *cmd = NULL;
  2054. struct fuzzy_cmd_io *io = NULL;
  2055. gint r, ret;
  2056. guchar buf[2048], *p;
  2057. task = session->task;
  2058. if ((r = read (session->fd, buf, sizeof (buf) - 1)) == -1) {
  2059. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  2060. return 0;
  2061. }
  2062. else {
  2063. return -1;
  2064. }
  2065. }
  2066. else {
  2067. p = buf;
  2068. ret = 0;
  2069. while ((rep = fuzzy_process_reply (&p, &r,
  2070. session->commands, session->rule, &cmd, &io)) != NULL) {
  2071. if (rep->v1.prob > 0.5) {
  2072. if (cmd->cmd == FUZZY_CHECK) {
  2073. fuzzy_insert_result (session, rep, cmd, io, rep->v1.flag);
  2074. }
  2075. else if (cmd->cmd == FUZZY_STAT) {
  2076. /* Just set pool variable to extract it in further */
  2077. struct rspamd_fuzzy_stat_entry *pval;
  2078. GList *res;
  2079. pval = rspamd_mempool_alloc (task->task_pool, sizeof (*pval));
  2080. pval->fuzzy_cnt = rep->v1.flag;
  2081. pval->name = session->rule->name;
  2082. res = rspamd_mempool_get_variable (task->task_pool, "fuzzy_stat");
  2083. if (res == NULL) {
  2084. res = g_list_append (NULL, pval);
  2085. rspamd_mempool_set_variable (task->task_pool, "fuzzy_stat",
  2086. res, (rspamd_mempool_destruct_t)g_list_free);
  2087. }
  2088. else {
  2089. res = g_list_append (res, pval);
  2090. }
  2091. }
  2092. }
  2093. else if (rep->v1.value == 403) {
  2094. rspamd_task_insert_result (task, "FUZZY_BLOCKED", 0.0,
  2095. session->rule->name);
  2096. }
  2097. else if (rep->v1.value == 401) {
  2098. if (cmd->cmd != FUZZY_CHECK) {
  2099. msg_info_task (
  2100. "fuzzy check error for %d: skipped by server",
  2101. rep->v1.flag);
  2102. }
  2103. }
  2104. else if (rep->v1.value != 0) {
  2105. msg_info_task (
  2106. "fuzzy check error for %d: unknown error (%d)",
  2107. rep->v1.flag,
  2108. rep->v1.value);
  2109. }
  2110. ret = 1;
  2111. }
  2112. }
  2113. return ret;
  2114. }
  2115. static void
  2116. fuzzy_insert_metric_results (struct rspamd_task *task, struct fuzzy_rule *rule,
  2117. GPtrArray *results)
  2118. {
  2119. struct fuzzy_client_result *res;
  2120. guint i;
  2121. gboolean seen_text_hash = FALSE,
  2122. seen_img_hash = FALSE,
  2123. seen_text_part = FALSE,
  2124. seen_long_text = FALSE;
  2125. gdouble prob_txt = 0.0, mult;
  2126. struct rspamd_mime_text_part *tp;
  2127. /* About 5 words */
  2128. static const unsigned int text_length_cutoff = 25;
  2129. PTR_ARRAY_FOREACH (results, i, res) {
  2130. if (res->type == FUZZY_RESULT_TXT) {
  2131. seen_text_hash = TRUE;
  2132. prob_txt = MAX (prob_txt, res->prob);
  2133. }
  2134. else if (res->type == FUZZY_RESULT_IMG) {
  2135. seen_img_hash = TRUE;
  2136. }
  2137. }
  2138. if (task->message) {
  2139. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, text_parts), i, tp) {
  2140. if (!IS_TEXT_PART_EMPTY (tp) && tp->utf_words != NULL && tp->utf_words->len > 0) {
  2141. seen_text_part = TRUE;
  2142. if (tp->utf_stripped_text.magic == UTEXT_MAGIC) {
  2143. if (utext_isLengthExpensive (&tp->utf_stripped_text)) {
  2144. seen_long_text =
  2145. utext_nativeLength (&tp->utf_stripped_text) >
  2146. text_length_cutoff;
  2147. }
  2148. else {
  2149. /* Cannot directly calculate length */
  2150. seen_long_text =
  2151. (tp->utf_stripped_content->len / 2) >
  2152. text_length_cutoff;
  2153. }
  2154. }
  2155. }
  2156. }
  2157. }
  2158. PTR_ARRAY_FOREACH (results, i, res) {
  2159. mult = 1.0;
  2160. if (res->type == FUZZY_RESULT_IMG) {
  2161. if (!seen_text_hash) {
  2162. if (seen_long_text) {
  2163. mult *= 0.25;
  2164. }
  2165. else if (seen_text_part) {
  2166. /* We have some short text + image */
  2167. mult *= 0.9;
  2168. }
  2169. /* Otherwise apply full score */
  2170. }
  2171. else if (prob_txt < 0.75) {
  2172. /* Penalize sole image without matching text */
  2173. if (prob_txt > 0.5) {
  2174. mult *= prob_txt;
  2175. }
  2176. else {
  2177. mult *= 0.5; /* cutoff */
  2178. }
  2179. }
  2180. }
  2181. else if (res->type == FUZZY_RESULT_TXT) {
  2182. if (seen_img_hash) {
  2183. /* Slightly increase score */
  2184. mult = 1.1;
  2185. }
  2186. }
  2187. gdouble weight = res->score * mult;
  2188. if (!isnan (rule->weight_threshold)) {
  2189. if (weight >= rule->weight_threshold) {
  2190. rspamd_task_insert_result_single (task, res->symbol,
  2191. weight, res->option);
  2192. }
  2193. else {
  2194. msg_info_task ("%s is not added: weight=%.4f below threshold",
  2195. res->symbol, weight);
  2196. }
  2197. }
  2198. else {
  2199. rspamd_task_insert_result_single (task, res->symbol,
  2200. weight, res->option);
  2201. }
  2202. }
  2203. }
  2204. static gboolean
  2205. fuzzy_check_session_is_completed (struct fuzzy_client_session *session)
  2206. {
  2207. struct fuzzy_cmd_io *io;
  2208. guint nreplied = 0, i;
  2209. rspamd_upstream_ok (session->server);
  2210. for (i = 0; i < session->commands->len; i++) {
  2211. io = g_ptr_array_index (session->commands, i);
  2212. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  2213. nreplied++;
  2214. }
  2215. }
  2216. if (nreplied == session->commands->len) {
  2217. fuzzy_insert_metric_results (session->task, session->rule, session->results);
  2218. if (session->item) {
  2219. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  2220. }
  2221. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  2222. return TRUE;
  2223. }
  2224. return FALSE;
  2225. }
  2226. /* Fuzzy check timeout callback */
  2227. static void
  2228. fuzzy_check_timer_callback (gint fd, short what, void *arg)
  2229. {
  2230. struct fuzzy_client_session *session = arg;
  2231. struct rspamd_task *task;
  2232. task = session->task;
  2233. /* We might be here because of other checks being slow */
  2234. if (fuzzy_check_try_read (session) > 0) {
  2235. if (fuzzy_check_session_is_completed (session)) {
  2236. return;
  2237. }
  2238. }
  2239. if (session->retransmits >= session->rule->retransmits) {
  2240. msg_err_task ("got IO timeout with server %s(%s), after %d/%d retransmits",
  2241. rspamd_upstream_name (session->server),
  2242. rspamd_inet_address_to_string_pretty (
  2243. rspamd_upstream_addr_cur (session->server)),
  2244. session->retransmits,
  2245. session->rule->retransmits);
  2246. rspamd_upstream_fail (session->server, TRUE, "timeout");
  2247. if (session->item) {
  2248. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  2249. }
  2250. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  2251. }
  2252. else {
  2253. /* Plan write event */
  2254. rspamd_ev_watcher_reschedule (session->event_loop,
  2255. &session->ev, EV_READ|EV_WRITE);
  2256. session->retransmits ++;
  2257. }
  2258. }
  2259. /* Fuzzy check callback */
  2260. static void
  2261. fuzzy_check_io_callback (gint fd, short what, void *arg)
  2262. {
  2263. struct fuzzy_client_session *session = arg;
  2264. struct rspamd_task *task;
  2265. gint r;
  2266. enum {
  2267. return_error = 0,
  2268. return_want_more,
  2269. return_finished
  2270. } ret = return_error;
  2271. task = session->task;
  2272. if ((what & EV_READ) || session->state == 1) {
  2273. /* Try to read reply */
  2274. r = fuzzy_check_try_read (session);
  2275. switch (r) {
  2276. case 0:
  2277. if (what & EV_READ) {
  2278. ret = return_want_more;
  2279. }
  2280. else {
  2281. if (what & EV_WRITE) {
  2282. /* Retransmit attempt */
  2283. if (!fuzzy_cmd_vector_to_wire (fd, session->commands)) {
  2284. ret = return_error;
  2285. }
  2286. else {
  2287. session->state = 1;
  2288. ret = return_want_more;
  2289. }
  2290. }
  2291. else {
  2292. /* It is actually time out */
  2293. fuzzy_check_timer_callback(fd, what, arg);
  2294. return;
  2295. }
  2296. }
  2297. break;
  2298. case 1:
  2299. ret = return_finished;
  2300. break;
  2301. default:
  2302. ret = return_error;
  2303. break;
  2304. }
  2305. }
  2306. else if (what & EV_WRITE) {
  2307. if (!fuzzy_cmd_vector_to_wire (fd, session->commands)) {
  2308. ret = return_error;
  2309. }
  2310. else {
  2311. session->state = 1;
  2312. ret = return_want_more;
  2313. }
  2314. }
  2315. else {
  2316. fuzzy_check_timer_callback (fd, what, arg);
  2317. return;
  2318. }
  2319. if (ret == return_want_more) {
  2320. /* Processed write, switch to reading */
  2321. rspamd_ev_watcher_reschedule (session->event_loop,
  2322. &session->ev, EV_READ);
  2323. }
  2324. else if (ret == return_error) {
  2325. /* Error state */
  2326. msg_err_task ("got error on IO with server %s(%s), on %s, %d, %s",
  2327. rspamd_upstream_name (session->server),
  2328. rspamd_inet_address_to_string_pretty (
  2329. rspamd_upstream_addr_cur (session->server)),
  2330. session->state == 1 ? "read" : "write",
  2331. errno,
  2332. strerror (errno));
  2333. rspamd_upstream_fail (session->server, TRUE, strerror (errno));
  2334. if (session->item) {
  2335. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  2336. }
  2337. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  2338. }
  2339. else {
  2340. /* Read something from network */
  2341. if (!fuzzy_check_session_is_completed (session)) {
  2342. /* Need to read more */
  2343. rspamd_ev_watcher_reschedule (session->event_loop,
  2344. &session->ev, EV_READ);
  2345. }
  2346. }
  2347. }
  2348. static void
  2349. fuzzy_lua_fin (void *ud)
  2350. {
  2351. struct fuzzy_learn_session *session = ud;
  2352. (*session->saved)--;
  2353. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  2354. close (session->fd);
  2355. }
  2356. /* Controller IO */
  2357. static void
  2358. fuzzy_controller_timer_callback (gint fd, short what, void *arg)
  2359. {
  2360. struct fuzzy_learn_session *session = arg;
  2361. struct rspamd_task *task;
  2362. task = session->task;
  2363. if (session->retransmits >= session->rule->retransmits) {
  2364. rspamd_upstream_fail (session->server, TRUE, "timeout");
  2365. msg_err_task_check ("got IO timeout with server %s(%s), "
  2366. "after %d/%d retransmits",
  2367. rspamd_upstream_name (session->server),
  2368. rspamd_inet_address_to_string_pretty (
  2369. rspamd_upstream_addr_cur (session->server)),
  2370. session->retransmits,
  2371. session->rule->retransmits);
  2372. if (session->session) {
  2373. rspamd_session_remove_event (session->session, fuzzy_lua_fin,
  2374. session);
  2375. }
  2376. else {
  2377. if (session->http_entry) {
  2378. rspamd_controller_send_error (session->http_entry,
  2379. 500, "IO timeout with fuzzy storage");
  2380. }
  2381. if (*session->saved > 0 ) {
  2382. (*session->saved)--;
  2383. if (*session->saved == 0) {
  2384. if (session->http_entry) {
  2385. rspamd_task_free (session->task);
  2386. }
  2387. session->task = NULL;
  2388. }
  2389. }
  2390. if (session->http_entry) {
  2391. rspamd_http_connection_unref (session->http_entry->conn);
  2392. }
  2393. rspamd_ev_watcher_stop (session->event_loop,
  2394. &session->ev);
  2395. close (session->fd);
  2396. }
  2397. }
  2398. else {
  2399. /* Plan write event */
  2400. rspamd_ev_watcher_reschedule (session->event_loop,
  2401. &session->ev, EV_READ|EV_WRITE);
  2402. session->retransmits ++;
  2403. }
  2404. }
  2405. static void
  2406. fuzzy_controller_io_callback (gint fd, short what, void *arg)
  2407. {
  2408. struct fuzzy_learn_session *session = arg;
  2409. const struct rspamd_fuzzy_reply *rep;
  2410. struct fuzzy_mapping *map;
  2411. struct rspamd_task *task;
  2412. guchar buf[2048], *p;
  2413. struct fuzzy_cmd_io *io;
  2414. struct rspamd_fuzzy_cmd *cmd = NULL;
  2415. const gchar *symbol, *ftype;
  2416. gint r;
  2417. enum {
  2418. return_error = 0,
  2419. return_want_more,
  2420. return_finished
  2421. } ret = return_want_more;
  2422. guint i, nreplied;
  2423. const gchar *op = "process";
  2424. task = session->task;
  2425. if (what & EV_READ) {
  2426. if ((r = read (fd, buf, sizeof (buf) - 1)) == -1) {
  2427. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  2428. rspamd_ev_watcher_reschedule (session->event_loop,
  2429. &session->ev, EV_READ);
  2430. return;
  2431. }
  2432. msg_info_task ("cannot process fuzzy hash for message: %s",
  2433. strerror (errno));
  2434. session->err.error_message = "read socket error";
  2435. session->err.error_code = errno;
  2436. ret = return_error;
  2437. }
  2438. else {
  2439. p = buf;
  2440. ret = return_want_more;
  2441. while ((rep = fuzzy_process_reply (&p, &r,
  2442. session->commands, session->rule, &cmd, &io)) != NULL) {
  2443. if ((map =
  2444. g_hash_table_lookup (session->rule->mappings,
  2445. GINT_TO_POINTER (rep->v1.flag))) == NULL) {
  2446. /* Default symbol and default weight */
  2447. symbol = session->rule->symbol;
  2448. }
  2449. else {
  2450. /* Get symbol and weight from map */
  2451. symbol = map->symbol;
  2452. }
  2453. ftype = "bin";
  2454. if (io) {
  2455. if ((io->flags & FUZZY_CMD_FLAG_IMAGE)) {
  2456. ftype = "img";
  2457. }
  2458. else if (io->flags & FUZZY_CMD_FLAG_CONTENT) {
  2459. ftype = "content";
  2460. }
  2461. else if (cmd->shingles_count > 0) {
  2462. ftype = "txt";
  2463. }
  2464. if (io->cmd.cmd == FUZZY_WRITE) {
  2465. op = "added";
  2466. }
  2467. else if (io->cmd.cmd == FUZZY_DEL) {
  2468. op = "deleted";
  2469. }
  2470. }
  2471. if (rep->v1.prob > 0.5) {
  2472. msg_info_task ("%s fuzzy hash (%s) %*xs, list: %s:%d for "
  2473. "message <%s>",
  2474. op,
  2475. ftype,
  2476. (gint)sizeof (rep->digest), rep->digest,
  2477. symbol,
  2478. rep->v1.flag,
  2479. MESSAGE_FIELD_CHECK (session->task, message_id));
  2480. }
  2481. else {
  2482. if (rep->v1.value == 401) {
  2483. msg_info_task (
  2484. "fuzzy hash (%s) for message cannot be %s"
  2485. "<%s>, %*xs, "
  2486. "list %s:%d, skipped by server",
  2487. ftype,
  2488. op,
  2489. MESSAGE_FIELD_CHECK (session->task, message_id),
  2490. (gint)sizeof (rep->digest), rep->digest,
  2491. symbol,
  2492. rep->v1.flag);
  2493. session->err.error_message = "fuzzy hash is skipped";
  2494. session->err.error_code = rep->v1.value;
  2495. }
  2496. else {
  2497. msg_info_task (
  2498. "fuzzy hash (%s) for message cannot be %s"
  2499. "<%s>, %*xs, "
  2500. "list %s:%d, error: %d",
  2501. ftype,
  2502. op,
  2503. MESSAGE_FIELD_CHECK (session->task, message_id),
  2504. (gint)sizeof (rep->digest), rep->digest,
  2505. symbol,
  2506. rep->v1.flag,
  2507. rep->v1.value);
  2508. session->err.error_message = "process fuzzy error";
  2509. session->err.error_code = rep->v1.value;
  2510. }
  2511. ret = return_finished;
  2512. }
  2513. }
  2514. nreplied = 0;
  2515. for (i = 0; i < session->commands->len; i++) {
  2516. io = g_ptr_array_index (session->commands, i);
  2517. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  2518. nreplied++;
  2519. }
  2520. }
  2521. if (nreplied == session->commands->len) {
  2522. ret = return_finished;
  2523. }
  2524. }
  2525. }
  2526. else if (what & EV_WRITE) {
  2527. /* Send commands to storage */
  2528. if (!fuzzy_cmd_vector_to_wire (fd, session->commands)) {
  2529. session->err.error_message = "write socket error";
  2530. session->err.error_code = errno;
  2531. ret = return_error;
  2532. }
  2533. }
  2534. else {
  2535. fuzzy_controller_timer_callback (fd, what, arg);
  2536. return;
  2537. }
  2538. if (ret == return_want_more) {
  2539. rspamd_ev_watcher_reschedule (session->event_loop,
  2540. &session->ev, EV_READ);
  2541. return;
  2542. }
  2543. else if (ret == return_error) {
  2544. msg_err_task ("got error in IO with server %s(%s), %d, %s",
  2545. rspamd_upstream_name (session->server),
  2546. rspamd_inet_address_to_string_pretty (
  2547. rspamd_upstream_addr_cur (session->server)),
  2548. errno, strerror (errno));
  2549. rspamd_upstream_fail (session->server, FALSE, strerror (errno));
  2550. }
  2551. /*
  2552. * XXX: actually, we check merely a single reply, which is not correct...
  2553. * XXX: when we send a command, we do not check if *all* commands have been
  2554. * written
  2555. * XXX: please, please, change this code some day
  2556. */
  2557. if (session->session == NULL) {
  2558. (*session->saved)--;
  2559. if (session->http_entry) {
  2560. rspamd_http_connection_unref (session->http_entry->conn);
  2561. }
  2562. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  2563. close (session->fd);
  2564. if (*session->saved == 0) {
  2565. goto cleanup;
  2566. }
  2567. }
  2568. else {
  2569. /* Lua handler */
  2570. rspamd_session_remove_event (session->session, fuzzy_lua_fin, session);
  2571. }
  2572. return;
  2573. cleanup:
  2574. /*
  2575. * When we send learn commands to fuzzy storages, this code is executed
  2576. * *once* when we have queried all storages. We also don't know which
  2577. * storage has been failed.
  2578. *
  2579. * Therefore, we cleanup sessions earlier and actually this code is wrong.
  2580. */
  2581. if (session->err.error_code != 0) {
  2582. if (session->http_entry) {
  2583. rspamd_controller_send_error (session->http_entry,
  2584. session->err.error_code, session->err.error_message);
  2585. }
  2586. }
  2587. else {
  2588. rspamd_upstream_ok (session->server);
  2589. if (session->http_entry) {
  2590. ucl_object_t *reply, *hashes;
  2591. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  2592. reply = ucl_object_typed_new (UCL_OBJECT);
  2593. ucl_object_insert_key (reply, ucl_object_frombool (true),
  2594. "success", 0, false);
  2595. hashes = ucl_object_typed_new (UCL_ARRAY);
  2596. for (i = 0; i < session->commands->len; i ++) {
  2597. io = g_ptr_array_index (session->commands, i);
  2598. rspamd_snprintf (hexbuf, sizeof (hexbuf), "%*xs",
  2599. (gint)sizeof (io->cmd.digest), io->cmd.digest);
  2600. ucl_array_append (hashes, ucl_object_fromstring (hexbuf));
  2601. }
  2602. ucl_object_insert_key (reply, hashes, "hashes", 0, false);
  2603. rspamd_controller_send_ucl (session->http_entry, reply);
  2604. ucl_object_unref (reply);
  2605. }
  2606. }
  2607. if (session->task != NULL) {
  2608. if (session->http_entry) {
  2609. rspamd_task_free (session->task);
  2610. }
  2611. session->task = NULL;
  2612. }
  2613. }
  2614. static GPtrArray *
  2615. fuzzy_generate_commands (struct rspamd_task *task, struct fuzzy_rule *rule,
  2616. gint c, gint flag, guint32 value, guint flags)
  2617. {
  2618. struct rspamd_mime_text_part *part;
  2619. struct rspamd_mime_part *mime_part;
  2620. struct rspamd_image *image;
  2621. struct fuzzy_cmd_io *io, *cur;
  2622. guint i, j;
  2623. GPtrArray *res = NULL;
  2624. gboolean check_part, fuzzy_check;
  2625. if (c == FUZZY_STAT) {
  2626. res = g_ptr_array_sized_new (1);
  2627. io = fuzzy_cmd_stat (rule, c, flag, value, task->task_pool);
  2628. if (io) {
  2629. g_ptr_array_add (res, io);
  2630. }
  2631. goto end;
  2632. }
  2633. if (task->message == NULL) {
  2634. goto end;
  2635. }
  2636. res = g_ptr_array_sized_new (MESSAGE_FIELD (task, parts)->len + 1);
  2637. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, parts), i, mime_part) {
  2638. check_part = FALSE;
  2639. fuzzy_check = FALSE;
  2640. if (fuzzy_rule_check_mimepart (task, rule, mime_part, &check_part,
  2641. &fuzzy_check)) {
  2642. io = NULL;
  2643. if (check_part) {
  2644. if (mime_part->part_type == RSPAMD_MIME_PART_TEXT &&
  2645. !(flags & FUZZY_CHECK_FLAG_NOTEXT)) {
  2646. part = mime_part->specific.txt;
  2647. io = fuzzy_cmd_from_text_part (task, rule,
  2648. c,
  2649. flag,
  2650. value,
  2651. !fuzzy_check,
  2652. part,
  2653. mime_part);
  2654. }
  2655. else if (mime_part->part_type == RSPAMD_MIME_PART_IMAGE &&
  2656. !(flags & FUZZY_CHECK_FLAG_NOIMAGES)) {
  2657. image = mime_part->specific.img;
  2658. io = fuzzy_cmd_from_data_part (rule, c, flag, value,
  2659. task,
  2660. image->parent->digest,
  2661. mime_part);
  2662. io->flags |= FUZZY_CMD_FLAG_IMAGE;
  2663. }
  2664. else if (mime_part->part_type == RSPAMD_MIME_PART_CUSTOM_LUA) {
  2665. const struct rspamd_lua_specific_part *lua_spec;
  2666. lua_spec = &mime_part->specific.lua_specific;
  2667. if (lua_spec->type == RSPAMD_LUA_PART_TABLE) {
  2668. lua_State *L = (lua_State *)task->cfg->lua_state;
  2669. gint old_top;
  2670. old_top = lua_gettop (L);
  2671. /* Push table */
  2672. lua_rawgeti (L, LUA_REGISTRYINDEX, lua_spec->cbref);
  2673. lua_pushstring (L, "fuzzy_hashes");
  2674. lua_gettable (L, -2);
  2675. if (lua_type (L, -1) == LUA_TTABLE) {
  2676. gint tbl_pos = lua_gettop (L);
  2677. for (lua_pushnil (L); lua_next (L, tbl_pos);
  2678. lua_pop (L, 1)) {
  2679. const gchar *h = NULL;
  2680. gsize hlen = 0;
  2681. if (lua_isstring (L, -1)) {
  2682. h = lua_tolstring (L, -1, &hlen);
  2683. }
  2684. else if (lua_type (L, -1) == LUA_TUSERDATA) {
  2685. struct rspamd_lua_text *t;
  2686. t = lua_check_text (L, -1);
  2687. if (t) {
  2688. h = t->start;
  2689. hlen = t->len;
  2690. }
  2691. }
  2692. if (hlen == rspamd_cryptobox_HASHBYTES) {
  2693. io = fuzzy_cmd_from_data_part (rule, c,
  2694. flag, value,
  2695. task,
  2696. (guchar *)h,
  2697. mime_part);
  2698. if (io) {
  2699. io->flags |= FUZZY_CMD_FLAG_CONTENT;
  2700. g_ptr_array_add (res, io);
  2701. }
  2702. }
  2703. }
  2704. }
  2705. lua_settop (L, old_top);
  2706. /*
  2707. * Add part itself as well
  2708. */
  2709. io = fuzzy_cmd_from_data_part (rule, c,
  2710. flag, value,
  2711. task,
  2712. mime_part->digest,
  2713. mime_part);
  2714. }
  2715. }
  2716. else {
  2717. io = fuzzy_cmd_from_data_part (rule, c, flag, value,
  2718. task,
  2719. mime_part->digest, mime_part);
  2720. }
  2721. if (io) {
  2722. gboolean skip_existing = FALSE;
  2723. PTR_ARRAY_FOREACH (res, j, cur) {
  2724. if (memcmp (cur->cmd.digest, io->cmd.digest,
  2725. sizeof (io->cmd.digest)) == 0) {
  2726. skip_existing = TRUE;
  2727. break;
  2728. }
  2729. }
  2730. if (!skip_existing) {
  2731. g_ptr_array_add (res, io);
  2732. }
  2733. }
  2734. }
  2735. }
  2736. }
  2737. end:
  2738. if (res && res->len == 0) {
  2739. g_ptr_array_free (res, TRUE);
  2740. return NULL;
  2741. }
  2742. return res;
  2743. }
  2744. static inline void
  2745. register_fuzzy_client_call (struct rspamd_task *task,
  2746. struct fuzzy_rule *rule,
  2747. GPtrArray *commands)
  2748. {
  2749. struct fuzzy_client_session *session;
  2750. struct upstream *selected;
  2751. rspamd_inet_addr_t *addr;
  2752. gint sock;
  2753. if (!rspamd_session_blocked (task->s)) {
  2754. /* Get upstream */
  2755. selected = rspamd_upstream_get (rule->servers, RSPAMD_UPSTREAM_ROUND_ROBIN,
  2756. NULL, 0);
  2757. if (selected) {
  2758. addr = rspamd_upstream_addr_next (selected);
  2759. if ((sock = rspamd_inet_address_connect (addr, SOCK_DGRAM, TRUE)) == -1) {
  2760. msg_warn_task ("cannot connect to %s(%s), %d, %s",
  2761. rspamd_upstream_name (selected),
  2762. rspamd_inet_address_to_string_pretty (addr),
  2763. errno,
  2764. strerror (errno));
  2765. rspamd_upstream_fail (selected, TRUE, strerror (errno));
  2766. g_ptr_array_free (commands, TRUE);
  2767. } else {
  2768. /* Create session for a socket */
  2769. session =
  2770. rspamd_mempool_alloc0 (task->task_pool,
  2771. sizeof (struct fuzzy_client_session));
  2772. session->state = 0;
  2773. session->commands = commands;
  2774. session->task = task;
  2775. session->fd = sock;
  2776. session->server = selected;
  2777. session->rule = rule;
  2778. session->results = g_ptr_array_sized_new (32);
  2779. session->event_loop = task->event_loop;
  2780. rspamd_ev_watcher_init (&session->ev,
  2781. sock,
  2782. EV_WRITE,
  2783. fuzzy_check_io_callback,
  2784. session);
  2785. rspamd_ev_watcher_start (session->event_loop, &session->ev,
  2786. rule->io_timeout);
  2787. rspamd_session_add_event (task->s, fuzzy_io_fin, session, M);
  2788. session->item = rspamd_symcache_get_cur_item (task);
  2789. if (session->item) {
  2790. rspamd_symcache_item_async_inc (task, session->item, M);
  2791. }
  2792. }
  2793. }
  2794. }
  2795. }
  2796. /* This callback is called when we check message in fuzzy hashes storage */
  2797. static void
  2798. fuzzy_symbol_callback (struct rspamd_task *task,
  2799. struct rspamd_symcache_item *item,
  2800. void *unused)
  2801. {
  2802. struct fuzzy_rule *rule;
  2803. guint i;
  2804. GPtrArray *commands;
  2805. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2806. if (!fuzzy_module_ctx->enabled) {
  2807. rspamd_symcache_finalize_item (task, item);
  2808. return;
  2809. }
  2810. /* Check whitelist */
  2811. if (fuzzy_module_ctx->whitelist) {
  2812. if (rspamd_match_radix_map_addr (fuzzy_module_ctx->whitelist,
  2813. task->from_addr) != NULL) {
  2814. msg_info_task ("<%s>, address %s is whitelisted, skip fuzzy check",
  2815. MESSAGE_FIELD (task, message_id),
  2816. rspamd_inet_address_to_string (task->from_addr));
  2817. rspamd_symcache_finalize_item (task, item);
  2818. return;
  2819. }
  2820. }
  2821. rspamd_symcache_item_async_inc (task, item, M);
  2822. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2823. commands = fuzzy_generate_commands (task, rule, FUZZY_CHECK, 0, 0, 0);
  2824. if (commands != NULL) {
  2825. register_fuzzy_client_call (task, rule, commands);
  2826. }
  2827. }
  2828. rspamd_symcache_item_async_dec_check (task, item, M);
  2829. }
  2830. void
  2831. fuzzy_stat_command (struct rspamd_task *task)
  2832. {
  2833. struct fuzzy_rule *rule;
  2834. guint i;
  2835. GPtrArray *commands;
  2836. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2837. if (!fuzzy_module_ctx->enabled) {
  2838. return;
  2839. }
  2840. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2841. commands = fuzzy_generate_commands (task, rule, FUZZY_STAT, 0, 0, 0);
  2842. if (commands != NULL) {
  2843. register_fuzzy_client_call (task, rule, commands);
  2844. }
  2845. }
  2846. }
  2847. static inline gint
  2848. register_fuzzy_controller_call (struct rspamd_http_connection_entry *entry,
  2849. struct fuzzy_rule *rule,
  2850. struct rspamd_task *task,
  2851. GPtrArray *commands,
  2852. gint *saved)
  2853. {
  2854. struct fuzzy_learn_session *s;
  2855. struct upstream *selected;
  2856. rspamd_inet_addr_t *addr;
  2857. struct rspamd_controller_session *session = entry->ud;
  2858. gint sock;
  2859. gint ret = -1;
  2860. /* Get upstream */
  2861. while ((selected = rspamd_upstream_get_forced (rule->servers,
  2862. RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
  2863. /* Create UDP socket */
  2864. addr = rspamd_upstream_addr_next (selected);
  2865. if ((sock = rspamd_inet_address_connect (addr,
  2866. SOCK_DGRAM, TRUE)) == -1) {
  2867. msg_warn_task ("cannot connect to fuzzy storage %s (%s rule): %s",
  2868. rspamd_inet_address_to_string_pretty (addr),
  2869. rule->name,
  2870. strerror (errno));
  2871. rspamd_upstream_fail (selected, TRUE, strerror (errno));
  2872. }
  2873. else {
  2874. s =
  2875. rspamd_mempool_alloc0 (session->pool,
  2876. sizeof (struct fuzzy_learn_session));
  2877. s->task = task;
  2878. s->commands = commands;
  2879. s->http_entry = entry;
  2880. s->server = selected;
  2881. s->saved = saved;
  2882. s->fd = sock;
  2883. s->rule = rule;
  2884. s->event_loop = task->event_loop;
  2885. /* We ref connection to avoid freeing before we process fuzzy rule */
  2886. rspamd_http_connection_ref (entry->conn);
  2887. rspamd_ev_watcher_init (&s->ev,
  2888. sock,
  2889. EV_WRITE,
  2890. fuzzy_controller_io_callback,
  2891. s);
  2892. rspamd_ev_watcher_start (s->event_loop, &s->ev, rule->io_timeout);
  2893. (*saved)++;
  2894. ret = 1;
  2895. }
  2896. }
  2897. return ret;
  2898. }
  2899. static void
  2900. fuzzy_process_handler (struct rspamd_http_connection_entry *conn_ent,
  2901. struct rspamd_http_message *msg, gint cmd, gint value, gint flag,
  2902. struct fuzzy_ctx *ctx, gboolean is_hash, guint flags)
  2903. {
  2904. struct fuzzy_rule *rule;
  2905. struct rspamd_controller_session *session = conn_ent->ud;
  2906. struct rspamd_task *task, **ptask;
  2907. gboolean processed = FALSE, skip = FALSE;
  2908. gint res = 0;
  2909. guint i;
  2910. GPtrArray *commands;
  2911. lua_State *L;
  2912. gint r, *saved, rules = 0, err_idx;
  2913. struct fuzzy_ctx *fuzzy_module_ctx;
  2914. /* Prepare task */
  2915. task = rspamd_task_new (session->wrk, session->cfg, NULL,
  2916. session->lang_det, conn_ent->rt->event_loop, FALSE);
  2917. task->cfg = ctx->cfg;
  2918. saved = rspamd_mempool_alloc0 (session->pool, sizeof (gint));
  2919. fuzzy_module_ctx = fuzzy_get_context (ctx->cfg);
  2920. if (!is_hash) {
  2921. /* Allocate message from string */
  2922. /* XXX: what about encrypted messages ? */
  2923. task->msg.begin = msg->body_buf.begin;
  2924. task->msg.len = msg->body_buf.len;
  2925. r = rspamd_message_parse (task);
  2926. if (r == -1) {
  2927. msg_warn_task ("<%s>: cannot process message for fuzzy",
  2928. MESSAGE_FIELD (task, message_id));
  2929. rspamd_task_free (task);
  2930. rspamd_controller_send_error (conn_ent, 400,
  2931. "Message processing error");
  2932. return;
  2933. }
  2934. rspamd_message_process (task);
  2935. }
  2936. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2937. if (rule->read_only) {
  2938. continue;
  2939. }
  2940. /* Check for flag */
  2941. if (g_hash_table_lookup (rule->mappings,
  2942. GINT_TO_POINTER (flag)) == NULL) {
  2943. msg_info_task ("skip rule %s as it has no flag %d defined"
  2944. " false", rule->name, flag);
  2945. continue;
  2946. }
  2947. /* Check learn condition */
  2948. if (rule->learn_condition_cb != -1) {
  2949. skip = FALSE;
  2950. L = session->cfg->lua_state;
  2951. lua_pushcfunction (L, &rspamd_lua_traceback);
  2952. err_idx = lua_gettop (L);
  2953. lua_rawgeti (L, LUA_REGISTRYINDEX, rule->learn_condition_cb);
  2954. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  2955. *ptask = task;
  2956. rspamd_lua_setclass (L, "rspamd{task}", -1);
  2957. if (lua_pcall (L, 1, LUA_MULTRET, err_idx) != 0) {
  2958. msg_err_task ("call to fuzzy learn condition failed: %s",
  2959. lua_tostring (L, -1));
  2960. }
  2961. else {
  2962. if (lua_gettop (L) > err_idx + 1) {
  2963. /* 2 return values */
  2964. skip = !(lua_toboolean (L, err_idx + 1));
  2965. if (lua_isnumber (L, err_idx + 2)) {
  2966. msg_info_task ("learn condition changed flag from %d to "
  2967. "%d", flag,
  2968. (gint)lua_tonumber (L, err_idx + 2));
  2969. flag = lua_tonumber (L, err_idx + 2);
  2970. }
  2971. }
  2972. else {
  2973. if (lua_isboolean (L, err_idx + 1)) {
  2974. skip = !(lua_toboolean (L, err_idx + 1));
  2975. }
  2976. else {
  2977. msg_warn_task ("set skip for rule %s as its condition "
  2978. "callback returned"
  2979. " a valid boolean", rule->name);
  2980. skip = TRUE;
  2981. }
  2982. }
  2983. }
  2984. /* Result + error function */
  2985. lua_settop (L, err_idx - 1);
  2986. if (skip) {
  2987. msg_info_task ("skip rule %s by condition callback",
  2988. rule->name);
  2989. continue;
  2990. }
  2991. }
  2992. rules ++;
  2993. res = 0;
  2994. if (is_hash) {
  2995. GPtrArray *args;
  2996. const rspamd_ftok_t *arg;
  2997. guint j;
  2998. args = rspamd_http_message_find_header_multiple (msg, "Hash");
  2999. if (args) {
  3000. struct fuzzy_cmd_io *io;
  3001. commands = g_ptr_array_sized_new (args->len);
  3002. for (j = 0; j < args->len; j ++) {
  3003. arg = g_ptr_array_index (args, j);
  3004. io = fuzzy_cmd_hash (rule, cmd, arg, flag, value,
  3005. task->task_pool);
  3006. if (io) {
  3007. g_ptr_array_add (commands, io);
  3008. }
  3009. }
  3010. res = register_fuzzy_controller_call (conn_ent,
  3011. rule,
  3012. task,
  3013. commands,
  3014. saved);
  3015. rspamd_mempool_add_destructor (task->task_pool,
  3016. rspamd_ptr_array_free_hard, commands);
  3017. g_ptr_array_free (args, TRUE);
  3018. }
  3019. else {
  3020. rspamd_controller_send_error (conn_ent, 400,
  3021. "No hash defined");
  3022. rspamd_task_free (task);
  3023. return;
  3024. }
  3025. }
  3026. else {
  3027. commands = fuzzy_generate_commands (task, rule, cmd, flag, value,
  3028. flags);
  3029. if (commands != NULL) {
  3030. res = register_fuzzy_controller_call (conn_ent,
  3031. rule,
  3032. task,
  3033. commands,
  3034. saved);
  3035. rspamd_mempool_add_destructor (task->task_pool,
  3036. rspamd_ptr_array_free_hard, commands);
  3037. }
  3038. }
  3039. if (res > 0) {
  3040. processed = TRUE;
  3041. }
  3042. }
  3043. if (res == -1) {
  3044. if (!processed) {
  3045. msg_warn_task ("cannot send fuzzy request: %s",
  3046. strerror (errno));
  3047. rspamd_controller_send_error (conn_ent, 400, "Message sending error");
  3048. rspamd_task_free (task);
  3049. return;
  3050. }
  3051. else {
  3052. /* Some rules failed and some rules are OK */
  3053. msg_warn_task ("some rules are not processed, but we still sent this request");
  3054. }
  3055. }
  3056. else if (!processed) {
  3057. if (rules) {
  3058. msg_warn_task ("no content to generate fuzzy");
  3059. rspamd_controller_send_error (conn_ent, 404,
  3060. "No content to generate fuzzy for flag %d", flag);
  3061. }
  3062. else {
  3063. if (skip) {
  3064. rspamd_controller_send_error (conn_ent, 403,
  3065. "Message is conditionally skipped for flag %d", flag);
  3066. }
  3067. else {
  3068. msg_warn_task ("no fuzzy rules found for flag %d", flag);
  3069. rspamd_controller_send_error (conn_ent, 404,
  3070. "No fuzzy rules matched for flag %d", flag);
  3071. }
  3072. }
  3073. rspamd_task_free (task);
  3074. }
  3075. }
  3076. static int
  3077. fuzzy_controller_handler (struct rspamd_http_connection_entry *conn_ent,
  3078. struct rspamd_http_message *msg, struct module_ctx *ctx, gint cmd,
  3079. gboolean is_hash)
  3080. {
  3081. const rspamd_ftok_t *arg;
  3082. glong value = 1, flag = 0, send_flags = 0;
  3083. struct fuzzy_ctx *fuzzy_module_ctx = (struct fuzzy_ctx *)ctx;
  3084. if (!fuzzy_module_ctx->enabled) {
  3085. msg_err ("fuzzy_check module is not enabled");
  3086. rspamd_controller_send_error (conn_ent, 500, "Module disabled");
  3087. return 0;
  3088. }
  3089. if (fuzzy_module_ctx->fuzzy_rules == NULL) {
  3090. msg_err ("fuzzy_check module has no rules defined");
  3091. rspamd_controller_send_error (conn_ent, 500, "Module has no rules");
  3092. return 0;
  3093. }
  3094. /* Get size */
  3095. arg = rspamd_http_message_find_header (msg, "Weight");
  3096. if (arg) {
  3097. errno = 0;
  3098. if (!rspamd_strtol (arg->begin, arg->len, &value)) {
  3099. msg_info ("error converting numeric argument %T", arg);
  3100. }
  3101. }
  3102. arg = rspamd_http_message_find_header (msg, "Flag");
  3103. if (arg) {
  3104. errno = 0;
  3105. if (!rspamd_strtol (arg->begin, arg->len, &flag)) {
  3106. msg_info ("error converting numeric argument %T", arg);
  3107. flag = 0;
  3108. }
  3109. }
  3110. else {
  3111. flag = 0;
  3112. arg = rspamd_http_message_find_header (msg, "Symbol");
  3113. /* Search flag by symbol */
  3114. if (arg) {
  3115. struct fuzzy_rule *rule;
  3116. guint i;
  3117. GHashTableIter it;
  3118. gpointer k, v;
  3119. struct fuzzy_mapping *map;
  3120. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3121. if (flag != 0) {
  3122. break;
  3123. }
  3124. g_hash_table_iter_init (&it, rule->mappings);
  3125. while (g_hash_table_iter_next (&it, &k, &v)) {
  3126. map = v;
  3127. if (strlen (map->symbol) == arg->len &&
  3128. rspamd_lc_cmp (map->symbol, arg->begin, arg->len) == 0) {
  3129. flag = map->fuzzy_flag;
  3130. break;
  3131. }
  3132. }
  3133. }
  3134. }
  3135. }
  3136. if (flag == 0) {
  3137. msg_err ("no flag defined to learn fuzzy");
  3138. rspamd_controller_send_error (conn_ent, 404, "Unknown or missing flag");
  3139. return 0;
  3140. }
  3141. arg = rspamd_http_message_find_header (msg, "Skip-Images");
  3142. if (arg) {
  3143. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  3144. }
  3145. arg = rspamd_http_message_find_header (msg, "Skip-Attachments");
  3146. if (arg) {
  3147. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  3148. }
  3149. arg = rspamd_http_message_find_header (msg, "Skip-Text");
  3150. if (arg) {
  3151. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  3152. }
  3153. fuzzy_process_handler (conn_ent, msg, cmd, value, flag,
  3154. (struct fuzzy_ctx *)ctx, is_hash, send_flags);
  3155. return 0;
  3156. }
  3157. static inline gint
  3158. fuzzy_check_send_lua_learn (struct fuzzy_rule *rule,
  3159. struct rspamd_task *task,
  3160. GPtrArray *commands,
  3161. gint *saved)
  3162. {
  3163. struct fuzzy_learn_session *s;
  3164. struct upstream *selected;
  3165. rspamd_inet_addr_t *addr;
  3166. gint sock;
  3167. gint ret = -1;
  3168. /* Get upstream */
  3169. if (!rspamd_session_blocked (task->s)) {
  3170. while ((selected = rspamd_upstream_get (rule->servers,
  3171. RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
  3172. /* Create UDP socket */
  3173. addr = rspamd_upstream_addr_next (selected);
  3174. if ((sock = rspamd_inet_address_connect (addr,
  3175. SOCK_DGRAM, TRUE)) == -1) {
  3176. rspamd_upstream_fail (selected, TRUE, strerror (errno));
  3177. } else {
  3178. s =
  3179. rspamd_mempool_alloc0 (task->task_pool,
  3180. sizeof (struct fuzzy_learn_session));
  3181. s->task = task;
  3182. s->commands = commands;
  3183. s->http_entry = NULL;
  3184. s->server = selected;
  3185. s->saved = saved;
  3186. s->fd = sock;
  3187. s->rule = rule;
  3188. s->session = task->s;
  3189. s->event_loop = task->event_loop;
  3190. rspamd_ev_watcher_init (&s->ev,
  3191. sock,
  3192. EV_WRITE,
  3193. fuzzy_controller_io_callback,
  3194. s);
  3195. rspamd_ev_watcher_start (s->event_loop, &s->ev,
  3196. rule->io_timeout);
  3197. rspamd_session_add_event (task->s,
  3198. fuzzy_lua_fin,
  3199. s,
  3200. M);
  3201. (*saved)++;
  3202. ret = 1;
  3203. }
  3204. }
  3205. }
  3206. return ret;
  3207. }
  3208. static gboolean
  3209. fuzzy_check_lua_process_learn (struct rspamd_task *task,
  3210. gint cmd, gint value, gint flag, guint send_flags)
  3211. {
  3212. struct fuzzy_rule *rule;
  3213. gboolean processed = FALSE, res = TRUE;
  3214. guint i;
  3215. GPtrArray *commands;
  3216. gint *saved, rules = 0;
  3217. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  3218. saved = rspamd_mempool_alloc0 (task->task_pool, sizeof (gint));
  3219. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3220. if (!res) {
  3221. break;
  3222. }
  3223. if (rule->read_only) {
  3224. continue;
  3225. }
  3226. /* Check for flag */
  3227. if (g_hash_table_lookup (rule->mappings,
  3228. GINT_TO_POINTER (flag)) == NULL) {
  3229. msg_info_task ("skip rule %s as it has no flag %d defined"
  3230. " false", rule->name, flag);
  3231. continue;
  3232. }
  3233. rules ++;
  3234. res = 0;
  3235. commands = fuzzy_generate_commands (task, rule, cmd, flag,
  3236. value, send_flags);
  3237. if (commands != NULL) {
  3238. res = fuzzy_check_send_lua_learn (rule, task, commands,
  3239. saved);
  3240. rspamd_mempool_add_destructor (task->task_pool,
  3241. rspamd_ptr_array_free_hard, commands);
  3242. }
  3243. if (res) {
  3244. processed = TRUE;
  3245. }
  3246. }
  3247. if (res == -1) {
  3248. msg_warn_task ("cannot send fuzzy request: %s",
  3249. strerror (errno));
  3250. }
  3251. else if (!processed) {
  3252. if (rules) {
  3253. msg_warn_task ("no content to generate fuzzy");
  3254. return FALSE;
  3255. }
  3256. else {
  3257. msg_warn_task ("no fuzzy rules found for flag %d", flag);
  3258. return FALSE;
  3259. }
  3260. }
  3261. return TRUE;
  3262. }
  3263. static gint
  3264. fuzzy_lua_learn_handler (lua_State *L)
  3265. {
  3266. struct rspamd_task *task = lua_check_task (L, 1);
  3267. if (task == NULL) {
  3268. return luaL_error(L, "invalid arguments");
  3269. }
  3270. guint flag = 0, weight = 1, send_flags = 0;
  3271. const gchar *symbol;
  3272. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  3273. if (lua_type (L, 2) == LUA_TNUMBER) {
  3274. flag = lua_tointeger (L, 2);
  3275. }
  3276. else if (lua_type (L, 2) == LUA_TSTRING) {
  3277. struct fuzzy_rule *rule;
  3278. guint i;
  3279. GHashTableIter it;
  3280. gpointer k, v;
  3281. struct fuzzy_mapping *map;
  3282. symbol = lua_tostring (L, 2);
  3283. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3284. if (flag != 0) {
  3285. break;
  3286. }
  3287. g_hash_table_iter_init (&it, rule->mappings);
  3288. while (g_hash_table_iter_next (&it, &k, &v)) {
  3289. map = v;
  3290. if (g_ascii_strcasecmp (symbol, map->symbol) == 0) {
  3291. flag = map->fuzzy_flag;
  3292. break;
  3293. }
  3294. }
  3295. }
  3296. }
  3297. if (flag == 0) {
  3298. return luaL_error (L, "bad flag");
  3299. }
  3300. if (lua_type (L, 3) == LUA_TNUMBER) {
  3301. weight = lua_tonumber (L, 3);
  3302. }
  3303. if (lua_type (L, 4) == LUA_TTABLE) {
  3304. const gchar *sf;
  3305. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  3306. sf = lua_tostring (L, -1);
  3307. if (sf) {
  3308. if (g_ascii_strcasecmp (sf, "noimages") == 0) {
  3309. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  3310. }
  3311. else if (g_ascii_strcasecmp (sf, "noattachments") == 0) {
  3312. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  3313. }
  3314. else if (g_ascii_strcasecmp (sf, "notext") == 0) {
  3315. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  3316. }
  3317. }
  3318. }
  3319. }
  3320. lua_pushboolean (L,
  3321. fuzzy_check_lua_process_learn (task, FUZZY_WRITE, weight, flag,
  3322. send_flags));
  3323. return 1;
  3324. }
  3325. static gint
  3326. fuzzy_lua_unlearn_handler (lua_State *L)
  3327. {
  3328. struct rspamd_task *task = lua_check_task (L, 1);
  3329. if (task == NULL) {
  3330. return luaL_error(L, "invalid arguments");
  3331. }
  3332. guint flag = 0, weight = 1.0, send_flags = 0;
  3333. const gchar *symbol;
  3334. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  3335. if (lua_type (L, 2) == LUA_TNUMBER) {
  3336. flag = lua_tonumber (L, 1);
  3337. }
  3338. else if (lua_type (L, 2) == LUA_TSTRING) {
  3339. struct fuzzy_rule *rule;
  3340. guint i;
  3341. GHashTableIter it;
  3342. gpointer k, v;
  3343. struct fuzzy_mapping *map;
  3344. symbol = lua_tostring (L, 2);
  3345. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3346. if (flag != 0) {
  3347. break;
  3348. }
  3349. g_hash_table_iter_init (&it, rule->mappings);
  3350. while (g_hash_table_iter_next (&it, &k, &v)) {
  3351. map = v;
  3352. if (g_ascii_strcasecmp (symbol, map->symbol) == 0) {
  3353. flag = map->fuzzy_flag;
  3354. break;
  3355. }
  3356. }
  3357. }
  3358. }
  3359. if (flag == 0) {
  3360. return luaL_error (L, "bad flag");
  3361. }
  3362. if (lua_type (L, 3) == LUA_TNUMBER) {
  3363. weight = lua_tonumber (L, 3);
  3364. }
  3365. if (lua_type (L, 4) == LUA_TTABLE) {
  3366. const gchar *sf;
  3367. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  3368. sf = lua_tostring (L, -1);
  3369. if (sf) {
  3370. if (g_ascii_strcasecmp (sf, "noimages") == 0) {
  3371. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  3372. }
  3373. else if (g_ascii_strcasecmp (sf, "noattachments") == 0) {
  3374. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  3375. }
  3376. else if (g_ascii_strcasecmp (sf, "notext") == 0) {
  3377. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  3378. }
  3379. }
  3380. }
  3381. }
  3382. lua_pushboolean (L,
  3383. fuzzy_check_lua_process_learn (task, FUZZY_DEL, weight, flag,
  3384. send_flags));
  3385. return 1;
  3386. }
  3387. static gint
  3388. fuzzy_lua_gen_hashes_handler (lua_State *L)
  3389. {
  3390. struct rspamd_task *task = lua_check_task (L, 1);
  3391. if (task == NULL) {
  3392. return luaL_error(L, "invalid arguments");
  3393. }
  3394. guint flag = 0, weight = 1, send_flags = 0;
  3395. const gchar *symbol;
  3396. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  3397. struct fuzzy_rule *rule;
  3398. GPtrArray *commands;
  3399. gint cmd = FUZZY_WRITE;
  3400. gint i;
  3401. if (lua_type (L, 2) == LUA_TNUMBER) {
  3402. flag = lua_tonumber (L, 2);
  3403. }
  3404. else if (lua_type (L, 2) == LUA_TSTRING) {
  3405. struct fuzzy_rule *rule;
  3406. guint i;
  3407. GHashTableIter it;
  3408. gpointer k, v;
  3409. struct fuzzy_mapping *map;
  3410. symbol = lua_tostring (L, 2);
  3411. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3412. if (flag != 0) {
  3413. break;
  3414. }
  3415. g_hash_table_iter_init (&it, rule->mappings);
  3416. while (g_hash_table_iter_next (&it, &k, &v)) {
  3417. map = v;
  3418. if (g_ascii_strcasecmp (symbol, map->symbol) == 0) {
  3419. flag = map->fuzzy_flag;
  3420. break;
  3421. }
  3422. }
  3423. }
  3424. }
  3425. if (flag == 0) {
  3426. return luaL_error (L, "bad flag");
  3427. }
  3428. if (lua_type (L, 3) == LUA_TNUMBER) {
  3429. weight = lua_tonumber (L, 3);
  3430. }
  3431. /* Flags */
  3432. if (lua_type (L, 4) == LUA_TTABLE) {
  3433. const gchar *sf;
  3434. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  3435. sf = lua_tostring (L, -1);
  3436. if (sf) {
  3437. if (g_ascii_strcasecmp (sf, "noimages") == 0) {
  3438. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  3439. }
  3440. else if (g_ascii_strcasecmp (sf, "noattachments") == 0) {
  3441. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  3442. }
  3443. else if (g_ascii_strcasecmp (sf, "notext") == 0) {
  3444. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  3445. }
  3446. }
  3447. }
  3448. }
  3449. /* Type */
  3450. if (lua_type (L, 5) == LUA_TSTRING) {
  3451. const gchar *cmd_name = lua_tostring (L, 5);
  3452. if (strcmp (cmd_name, "add") == 0 || strcmp (cmd_name, "write") == 0) {
  3453. cmd = FUZZY_WRITE;
  3454. }
  3455. else if (strcmp (cmd_name, "delete") == 0 || strcmp (cmd_name, "remove") == 0) {
  3456. cmd = FUZZY_DEL;
  3457. }
  3458. else {
  3459. return luaL_error (L, "invalid command: %s", cmd_name);
  3460. }
  3461. }
  3462. lua_createtable (L, 0, fuzzy_module_ctx->fuzzy_rules->len);
  3463. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3464. if (rule->read_only) {
  3465. continue;
  3466. }
  3467. /* Check for flag */
  3468. if (g_hash_table_lookup (rule->mappings,
  3469. GINT_TO_POINTER (flag)) == NULL) {
  3470. msg_info_task ("skip rule %s as it has no flag %d defined"
  3471. " false", rule->name, flag);
  3472. continue;
  3473. }
  3474. commands = fuzzy_generate_commands (task, rule, cmd, flag,
  3475. weight, send_flags);
  3476. if (commands != NULL) {
  3477. struct fuzzy_cmd_io *io;
  3478. gint j;
  3479. lua_pushstring (L, rule->name);
  3480. lua_createtable (L, commands->len, 0);
  3481. PTR_ARRAY_FOREACH (commands, j, io) {
  3482. lua_pushlstring (L, io->io.iov_base, io->io.iov_len);
  3483. lua_rawseti (L, -2, j + 1);
  3484. }
  3485. lua_settable (L, -3); /* ret[rule->name] = {raw_fuzzy1, ..., raw_fuzzyn} */
  3486. g_ptr_array_free (commands, TRUE);
  3487. }
  3488. }
  3489. return 1;
  3490. }
  3491. static gboolean
  3492. fuzzy_add_handler (struct rspamd_http_connection_entry *conn_ent,
  3493. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3494. {
  3495. return fuzzy_controller_handler (conn_ent, msg,
  3496. ctx, FUZZY_WRITE, FALSE);
  3497. }
  3498. static gboolean
  3499. fuzzy_delete_handler (struct rspamd_http_connection_entry *conn_ent,
  3500. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3501. {
  3502. return fuzzy_controller_handler (conn_ent, msg,
  3503. ctx, FUZZY_DEL, FALSE);
  3504. }
  3505. static gboolean
  3506. fuzzy_deletehash_handler (struct rspamd_http_connection_entry *conn_ent,
  3507. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3508. {
  3509. return fuzzy_controller_handler (conn_ent, msg,
  3510. ctx, FUZZY_DEL, TRUE);
  3511. }
  3512. static int
  3513. fuzzy_attach_controller (struct module_ctx *ctx, GHashTable *commands)
  3514. {
  3515. struct fuzzy_ctx *fctx = (struct fuzzy_ctx *)ctx;
  3516. struct rspamd_custom_controller_command *cmd;
  3517. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3518. cmd->privileged = TRUE;
  3519. cmd->require_message = TRUE;
  3520. cmd->handler = fuzzy_add_handler;
  3521. cmd->ctx = ctx;
  3522. g_hash_table_insert (commands, "/fuzzyadd", cmd);
  3523. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3524. cmd->privileged = TRUE;
  3525. cmd->require_message = TRUE;
  3526. cmd->handler = fuzzy_delete_handler;
  3527. cmd->ctx = ctx;
  3528. g_hash_table_insert (commands, "/fuzzydel", cmd);
  3529. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3530. cmd->privileged = TRUE;
  3531. cmd->require_message = FALSE;
  3532. cmd->handler = fuzzy_deletehash_handler;
  3533. cmd->ctx = ctx;
  3534. g_hash_table_insert (commands, "/fuzzydelhash", cmd);
  3535. return 0;
  3536. }