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 87KB

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