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

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