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_storage.c 94KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545
  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. /*
  17. * Rspamd fuzzy storage server
  18. */
  19. #include "config.h"
  20. #include "libserver/fuzzy_wire.h"
  21. #include "util.h"
  22. #include "rspamd.h"
  23. #include "libserver/maps/map.h"
  24. #include "libserver/maps/map_helpers.h"
  25. #include "libserver/fuzzy_backend/fuzzy_backend.h"
  26. #include "ottery.h"
  27. #include "ref.h"
  28. #include "xxhash.h"
  29. #include "libserver/worker_util.h"
  30. #include "libserver/rspamd_control.h"
  31. #include "libcryptobox/cryptobox.h"
  32. #include "libcryptobox/keypairs_cache.h"
  33. #include "libcryptobox/keypair.h"
  34. #include "libutil/hash.h"
  35. #include "libserver/maps/map_private.h"
  36. #include "contrib/uthash/utlist.h"
  37. #include "lua/lua_common.h"
  38. #include "unix-std.h"
  39. #include <math.h>
  40. /* Resync value in seconds */
  41. #define DEFAULT_SYNC_TIMEOUT 60.0
  42. #define DEFAULT_KEYPAIR_CACHE_SIZE 512
  43. #define DEFAULT_MASTER_TIMEOUT 10.0
  44. #define DEFAULT_UPDATES_MAXFAIL 3
  45. #define DEFAULT_MAX_BUCKETS 2000
  46. #define DEFAULT_BUCKET_TTL 3600
  47. #define DEFAULT_BUCKET_MASK 24
  48. /* Update stats on keys each 1 hour */
  49. #define KEY_STAT_INTERVAL 3600.0
  50. static const gchar *local_db_name = "local";
  51. /* Init functions */
  52. gpointer init_fuzzy(struct rspamd_config *cfg);
  53. void start_fuzzy(struct rspamd_worker *worker);
  54. worker_t fuzzy_worker = {
  55. "fuzzy", /* Name */
  56. init_fuzzy, /* Init function */
  57. start_fuzzy, /* Start function */
  58. RSPAMD_WORKER_HAS_SOCKET | RSPAMD_WORKER_NO_STRICT_CONFIG,
  59. RSPAMD_WORKER_SOCKET_UDP, /* UDP socket */
  60. RSPAMD_WORKER_VER /* Version info */
  61. };
  62. struct fuzzy_global_stat {
  63. uint64_t fuzzy_hashes;
  64. /**< number of fuzzy hashes stored */
  65. uint64_t fuzzy_hashes_expired;
  66. /**< number of fuzzy hashes expired */
  67. uint64_t fuzzy_hashes_checked[RSPAMD_FUZZY_EPOCH_MAX];
  68. /**< amount of check requests for each epoch */
  69. uint64_t fuzzy_shingles_checked[RSPAMD_FUZZY_EPOCH_MAX];
  70. /**< amount of shingle check requests for each epoch */
  71. uint64_t fuzzy_hashes_found[RSPAMD_FUZZY_EPOCH_MAX];
  72. /**< amount of invalid requests */
  73. uint64_t invalid_requests;
  74. /**< amount of delayed hashes found */
  75. uint64_t delayed_hashes;
  76. };
  77. struct fuzzy_key_stat {
  78. uint64_t checked;
  79. uint64_t matched;
  80. uint64_t added;
  81. uint64_t deleted;
  82. uint64_t errors;
  83. /* Store averages for checked/matched per minute */
  84. struct rspamd_counter_data checked_ctr;
  85. struct rspamd_counter_data matched_ctr;
  86. gdouble last_checked_time;
  87. uint64_t last_checked_count;
  88. uint64_t last_matched_count;
  89. struct rspamd_cryptobox_keypair *keypair;
  90. rspamd_lru_hash_t *last_ips;
  91. ref_entry_t ref;
  92. };
  93. struct rspamd_leaky_bucket_elt {
  94. rspamd_inet_addr_t *addr;
  95. gdouble last;
  96. gdouble cur;
  97. };
  98. static const uint64_t rspamd_fuzzy_storage_magic = 0x291a3253eb1b3ea5ULL;
  99. static int64_t
  100. fuzzy_kp_hash(const unsigned char *p)
  101. {
  102. int64_t res;
  103. memcpy(&res, p, sizeof(res));
  104. return res;
  105. }
  106. static bool
  107. fuzzy_kp_equal(gconstpointer a, gconstpointer b)
  108. {
  109. const guchar *pa = a, *pb = b;
  110. return (memcmp(pa, pb, RSPAMD_FUZZY_KEYLEN) == 0);
  111. }
  112. KHASH_SET_INIT_INT(fuzzy_key_ids_set);
  113. KHASH_INIT(fuzzy_key_flag_stat, int, struct fuzzy_key_stat, 1, kh_int_hash_func,
  114. kh_int_hash_equal);
  115. struct fuzzy_key {
  116. struct rspamd_cryptobox_keypair *key;
  117. struct rspamd_cryptobox_pubkey *pk;
  118. struct fuzzy_key_stat *stat;
  119. khash_t(fuzzy_key_flag_stat) * flags_stat;
  120. khash_t(fuzzy_key_ids_set) * forbidden_ids;
  121. ref_entry_t ref;
  122. };
  123. KHASH_INIT(rspamd_fuzzy_keys_hash,
  124. const unsigned char *, struct fuzzy_key *, 1,
  125. fuzzy_kp_hash, fuzzy_kp_equal);
  126. struct rspamd_fuzzy_storage_ctx {
  127. uint64_t magic;
  128. /* Events base */
  129. struct ev_loop *event_loop;
  130. /* DNS resolver */
  131. struct rspamd_dns_resolver *resolver;
  132. /* Config */
  133. struct rspamd_config *cfg;
  134. /* END OF COMMON PART */
  135. struct fuzzy_global_stat stat;
  136. gdouble expire;
  137. gdouble sync_timeout;
  138. gdouble delay;
  139. struct rspamd_radix_map_helper *update_ips;
  140. struct rspamd_hash_map_helper *update_keys;
  141. struct rspamd_radix_map_helper *blocked_ips;
  142. struct rspamd_radix_map_helper *ratelimit_whitelist;
  143. struct rspamd_radix_map_helper *delay_whitelist;
  144. const ucl_object_t *update_map;
  145. const ucl_object_t *update_keys_map;
  146. const ucl_object_t *delay_whitelist_map;
  147. const ucl_object_t *blocked_map;
  148. const ucl_object_t *ratelimit_whitelist_map;
  149. const ucl_object_t *dynamic_keys_map;
  150. guint keypair_cache_size;
  151. ev_timer stat_ev;
  152. ev_io peer_ev;
  153. /* Local keypair */
  154. struct rspamd_cryptobox_keypair *default_keypair; /* Bad clash, need for parse keypair */
  155. struct fuzzy_key *default_key;
  156. khash_t(rspamd_fuzzy_keys_hash) * keys;
  157. /* Those are loaded via map */
  158. khash_t(rspamd_fuzzy_keys_hash) * dynamic_keys;
  159. gboolean encrypted_only;
  160. gboolean read_only;
  161. gboolean dedicated_update_worker;
  162. struct rspamd_keypair_cache *keypair_cache;
  163. struct rspamd_http_context *http_ctx;
  164. rspamd_lru_hash_t *errors_ips;
  165. rspamd_lru_hash_t *ratelimit_buckets;
  166. struct rspamd_fuzzy_backend *backend;
  167. GArray *updates_pending;
  168. guint updates_failed;
  169. guint updates_maxfail;
  170. /* Used to send data between workers */
  171. gint peer_fd;
  172. /* Ratelimits */
  173. guint leaky_bucket_ttl;
  174. guint leaky_bucket_mask;
  175. guint max_buckets;
  176. gboolean ratelimit_log_only;
  177. gdouble leaky_bucket_burst;
  178. gdouble leaky_bucket_rate;
  179. struct rspamd_worker *worker;
  180. const ucl_object_t *skip_map;
  181. struct rspamd_hash_map_helper *skip_hashes;
  182. gint lua_pre_handler_cbref;
  183. gint lua_post_handler_cbref;
  184. gint lua_blacklist_cbref;
  185. khash_t(fuzzy_key_ids_set) * default_forbidden_ids;
  186. /* Ids that should not override other ids */
  187. khash_t(fuzzy_key_ids_set) * weak_ids;
  188. };
  189. enum fuzzy_cmd_type {
  190. CMD_NORMAL,
  191. CMD_SHINGLE,
  192. CMD_ENCRYPTED_NORMAL,
  193. CMD_ENCRYPTED_SHINGLE
  194. };
  195. struct fuzzy_session {
  196. struct rspamd_worker *worker;
  197. rspamd_inet_addr_t *addr;
  198. struct rspamd_fuzzy_storage_ctx *ctx;
  199. struct rspamd_fuzzy_shingle_cmd cmd; /* Can handle both shingles and non-shingles */
  200. struct rspamd_fuzzy_encrypted_reply reply; /* Again: contains everything */
  201. struct fuzzy_key_stat *ip_stat;
  202. enum rspamd_fuzzy_epoch epoch;
  203. enum fuzzy_cmd_type cmd_type;
  204. gint fd;
  205. ev_tstamp timestamp;
  206. struct ev_io io;
  207. ref_entry_t ref;
  208. struct fuzzy_key *key;
  209. struct rspamd_fuzzy_cmd_extension *extensions;
  210. guchar nm[rspamd_cryptobox_MAX_NMBYTES];
  211. };
  212. struct fuzzy_peer_request {
  213. ev_io io_ev;
  214. struct fuzzy_peer_cmd cmd;
  215. };
  216. struct rspamd_updates_cbdata {
  217. GArray *updates_pending;
  218. struct rspamd_fuzzy_storage_ctx *ctx;
  219. gchar *source;
  220. gboolean final;
  221. };
  222. static void rspamd_fuzzy_write_reply(struct fuzzy_session *session);
  223. static gboolean rspamd_fuzzy_process_updates_queue(struct rspamd_fuzzy_storage_ctx *ctx,
  224. const gchar *source, gboolean final);
  225. static gboolean rspamd_fuzzy_check_client(struct rspamd_fuzzy_storage_ctx *ctx,
  226. rspamd_inet_addr_t *addr);
  227. static void rspamd_fuzzy_maybe_call_blacklisted(struct rspamd_fuzzy_storage_ctx *ctx,
  228. rspamd_inet_addr_t *addr,
  229. const gchar *reason);
  230. static struct fuzzy_key *fuzzy_add_keypair_from_ucl(const ucl_object_t *obj,
  231. khash_t(rspamd_fuzzy_keys_hash) * target);
  232. struct fuzzy_keymap_ucl_buf {
  233. rspamd_fstring_t *buf;
  234. struct rspamd_fuzzy_storage_ctx *ctx;
  235. };
  236. /* Callbacks for reading json dynamic rules */
  237. static gchar *
  238. ucl_keymap_read_cb(gchar *chunk,
  239. gint len,
  240. struct map_cb_data *data,
  241. gboolean final)
  242. {
  243. struct fuzzy_keymap_ucl_buf *jb, *pd;
  244. pd = data->prev_data;
  245. g_assert(pd != NULL);
  246. if (data->cur_data == NULL) {
  247. jb = g_malloc0(sizeof(*jb));
  248. jb->ctx = pd->ctx;
  249. data->cur_data = jb;
  250. }
  251. else {
  252. jb = data->cur_data;
  253. }
  254. if (jb->buf == NULL) {
  255. /* Allocate memory for buffer */
  256. jb->buf = rspamd_fstring_sized_new(MAX(len, 4096));
  257. }
  258. jb->buf = rspamd_fstring_append(jb->buf, chunk, len);
  259. return NULL;
  260. }
  261. static void
  262. ucl_keymap_fin_cb(struct map_cb_data *data, void **target)
  263. {
  264. struct fuzzy_keymap_ucl_buf *jb;
  265. ucl_object_t *top;
  266. struct ucl_parser *parser;
  267. struct rspamd_config *cfg;
  268. /* Now parse ucl */
  269. if (data->cur_data) {
  270. jb = data->cur_data;
  271. cfg = jb->ctx->cfg;
  272. }
  273. else {
  274. msg_err("no cur data in the map! might be a bug");
  275. return;
  276. }
  277. if (jb->buf->len == 0) {
  278. msg_err_config("no data read");
  279. return;
  280. }
  281. parser = ucl_parser_new(UCL_PARSER_NO_FILEVARS);
  282. if (!ucl_parser_add_chunk(parser, jb->buf->str, jb->buf->len)) {
  283. msg_err_config("cannot load ucl data: parse error %s",
  284. ucl_parser_get_error(parser));
  285. ucl_parser_free(parser);
  286. return;
  287. }
  288. top = ucl_parser_get_object(parser);
  289. ucl_parser_free(parser);
  290. if (ucl_object_type(top) != UCL_ARRAY) {
  291. ucl_object_unref(top);
  292. msg_err_config("loaded ucl is not an array");
  293. return;
  294. }
  295. if (target) {
  296. *target = data->cur_data;
  297. }
  298. if (data->prev_data) {
  299. jb = data->prev_data;
  300. /* Clean prev data */
  301. if (jb->buf) {
  302. rspamd_fstring_free(jb->buf);
  303. }
  304. /* Clean the existing keys */
  305. struct fuzzy_key *key;
  306. kh_foreach_value(jb->ctx->dynamic_keys, key, {
  307. REF_RELEASE(key);
  308. });
  309. kh_clear(rspamd_fuzzy_keys_hash, jb->ctx->dynamic_keys);
  310. /* Insert new keys */
  311. const ucl_object_t *cur;
  312. ucl_object_iter_t it = NULL;
  313. int success = 0;
  314. while ((cur = ucl_object_iterate(top, &it, true)) != NULL) {
  315. struct fuzzy_key *nk;
  316. nk = fuzzy_add_keypair_from_ucl(cur, jb->ctx->dynamic_keys);
  317. if (nk == NULL) {
  318. msg_warn_config("cannot add dynamic keypair");
  319. }
  320. success++;
  321. }
  322. msg_info_config("loaded %d dynamic keypairs", success);
  323. g_free(jb);
  324. }
  325. ucl_object_unref(top);
  326. }
  327. static void
  328. ucl_keymap_dtor_cb(struct map_cb_data *data)
  329. {
  330. struct fuzzy_keymap_ucl_buf *jb;
  331. if (data->cur_data) {
  332. jb = data->cur_data;
  333. /* Clean prev data */
  334. if (jb->buf) {
  335. rspamd_fstring_free(jb->buf);
  336. }
  337. struct fuzzy_key *key;
  338. kh_foreach_value(jb->ctx->dynamic_keys, key, {
  339. REF_RELEASE(key);
  340. });
  341. kh_destroy(rspamd_fuzzy_keys_hash, jb->ctx->dynamic_keys);
  342. g_free(jb);
  343. }
  344. }
  345. static gboolean
  346. rspamd_fuzzy_check_ratelimit(struct fuzzy_session *session)
  347. {
  348. rspamd_inet_addr_t *masked;
  349. struct rspamd_leaky_bucket_elt *elt;
  350. if (!session->addr) {
  351. return TRUE;
  352. }
  353. if (session->ctx->ratelimit_whitelist != NULL) {
  354. if (rspamd_match_radix_map_addr(session->ctx->ratelimit_whitelist,
  355. session->addr) != NULL) {
  356. return TRUE;
  357. }
  358. }
  359. /*
  360. if (rspamd_inet_address_is_local (session->addr, TRUE)) {
  361. return TRUE;
  362. }
  363. */
  364. masked = rspamd_inet_address_copy(session->addr, NULL);
  365. if (rspamd_inet_address_get_af(masked) == AF_INET) {
  366. rspamd_inet_address_apply_mask(masked,
  367. MIN(session->ctx->leaky_bucket_mask, 32));
  368. }
  369. else {
  370. /* Must be at least /64 */
  371. rspamd_inet_address_apply_mask(masked,
  372. MIN(MAX(session->ctx->leaky_bucket_mask * 4, 64), 128));
  373. }
  374. elt = rspamd_lru_hash_lookup(session->ctx->ratelimit_buckets, masked,
  375. (time_t) session->timestamp);
  376. if (elt) {
  377. gboolean ratelimited = FALSE, new_ratelimit = FALSE;
  378. if (isnan(elt->cur)) {
  379. /* There is an issue with the previous logic: the TTL is updated each time
  380. * we see that new bucket. Hence, we need to check the `last` and act accordingly
  381. */
  382. if (elt->last < session->timestamp && session->timestamp - elt->last >= session->ctx->leaky_bucket_ttl) {
  383. /*
  384. * We reset bucket to it's 90% capacity to allow some requests
  385. * This should cope with the issue when we block an IP network for some burst and never unblock it
  386. */
  387. elt->cur = session->ctx->leaky_bucket_burst * 0.9;
  388. elt->last = session->timestamp;
  389. }
  390. else {
  391. ratelimited = TRUE;
  392. }
  393. }
  394. else {
  395. /* Update bucket: leak some elements */
  396. if (elt->last < session->timestamp) {
  397. elt->cur -= session->ctx->leaky_bucket_rate * (session->timestamp - elt->last);
  398. elt->last = session->timestamp;
  399. if (elt->cur < 0) {
  400. elt->cur = 0;
  401. }
  402. }
  403. else {
  404. elt->last = session->timestamp;
  405. }
  406. /* Check the bucket */
  407. if (elt->cur >= session->ctx->leaky_bucket_burst) {
  408. msg_info("ratelimiting %s (%s), %.1f max elts",
  409. rspamd_inet_address_to_string(session->addr),
  410. rspamd_inet_address_to_string(masked),
  411. session->ctx->leaky_bucket_burst);
  412. elt->cur = NAN;
  413. new_ratelimit = TRUE;
  414. ratelimited = TRUE;
  415. }
  416. else {
  417. elt->cur++; /* Allow one more request */
  418. }
  419. }
  420. if (ratelimited) {
  421. rspamd_fuzzy_maybe_call_blacklisted(session->ctx, session->addr, "ratelimit");
  422. }
  423. if (new_ratelimit) {
  424. struct rspamd_srv_command srv_cmd;
  425. srv_cmd.type = RSPAMD_SRV_FUZZY_BLOCKED;
  426. srv_cmd.cmd.fuzzy_blocked.af = rspamd_inet_address_get_af(masked);
  427. if (srv_cmd.cmd.fuzzy_blocked.af == AF_INET || srv_cmd.cmd.fuzzy_blocked.af == AF_INET6) {
  428. socklen_t slen;
  429. struct sockaddr *sa = rspamd_inet_address_get_sa(masked, &slen);
  430. if (slen <= sizeof(srv_cmd.cmd.fuzzy_blocked.addr)) {
  431. memcpy(&srv_cmd.cmd.fuzzy_blocked.addr, sa, slen);
  432. msg_debug("propagating blocked address to other workers");
  433. rspamd_srv_send_command(session->worker, session->ctx->event_loop, &srv_cmd, -1, NULL, NULL);
  434. }
  435. else {
  436. msg_err("bad address length: %d, expected to be %d", (int) slen, (int) sizeof(srv_cmd.cmd.fuzzy_blocked.addr));
  437. }
  438. }
  439. }
  440. rspamd_inet_address_free(masked);
  441. return !ratelimited;
  442. }
  443. else {
  444. /* New bucket */
  445. elt = g_malloc(sizeof(*elt));
  446. elt->addr = masked; /* transfer ownership */
  447. elt->cur = 1;
  448. elt->last = session->timestamp;
  449. rspamd_lru_hash_insert(session->ctx->ratelimit_buckets,
  450. masked,
  451. elt,
  452. session->timestamp,
  453. session->ctx->leaky_bucket_ttl);
  454. }
  455. return TRUE;
  456. }
  457. static void
  458. rspamd_fuzzy_maybe_call_blacklisted(struct rspamd_fuzzy_storage_ctx *ctx,
  459. rspamd_inet_addr_t *addr,
  460. const gchar *reason)
  461. {
  462. if (ctx->lua_blacklist_cbref != -1) {
  463. lua_State *L = ctx->cfg->lua_state;
  464. gint err_idx, ret;
  465. lua_pushcfunction(L, &rspamd_lua_traceback);
  466. err_idx = lua_gettop(L);
  467. lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  468. /* client IP */
  469. rspamd_lua_ip_push(L, addr);
  470. /* block reason */
  471. lua_pushstring(L, reason);
  472. if ((ret = lua_pcall(L, 2, 0, err_idx)) != 0) {
  473. msg_err("call to lua_blacklist_cbref "
  474. "script failed (%d): %s",
  475. ret, lua_tostring(L, -1));
  476. }
  477. lua_settop(L, 0);
  478. }
  479. }
  480. static gboolean
  481. rspamd_fuzzy_check_client(struct rspamd_fuzzy_storage_ctx *ctx,
  482. rspamd_inet_addr_t *addr)
  483. {
  484. if (ctx->blocked_ips != NULL) {
  485. if (rspamd_match_radix_map_addr(ctx->blocked_ips,
  486. addr) != NULL) {
  487. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "blacklisted");
  488. return FALSE;
  489. }
  490. }
  491. return TRUE;
  492. }
  493. static gboolean
  494. rspamd_fuzzy_check_write(struct fuzzy_session *session)
  495. {
  496. if (session->ctx->read_only) {
  497. return FALSE;
  498. }
  499. if (session->ctx->update_ips != NULL && session->addr) {
  500. if (rspamd_inet_address_get_af(session->addr) == AF_UNIX) {
  501. return TRUE;
  502. }
  503. if (rspamd_match_radix_map_addr(session->ctx->update_ips,
  504. session->addr) == NULL) {
  505. return FALSE;
  506. }
  507. else {
  508. return TRUE;
  509. }
  510. }
  511. if (session->ctx->update_keys != NULL && session->key->stat && session->key->key) {
  512. static gchar base32_buf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  513. guint raw_len;
  514. const guchar *pk_raw = rspamd_keypair_component(session->key->key,
  515. RSPAMD_KEYPAIR_COMPONENT_ID, &raw_len);
  516. gint encoded_len = rspamd_encode_base32_buf(pk_raw, raw_len,
  517. base32_buf, sizeof(base32_buf),
  518. RSPAMD_BASE32_DEFAULT);
  519. if (rspamd_match_hash_map(session->ctx->update_keys, base32_buf, encoded_len)) {
  520. return TRUE;
  521. }
  522. }
  523. return FALSE;
  524. }
  525. static void
  526. fuzzy_key_stat_dtor(gpointer p)
  527. {
  528. struct fuzzy_key_stat *st = p;
  529. if (st->last_ips) {
  530. rspamd_lru_hash_destroy(st->last_ips);
  531. }
  532. if (st->keypair) {
  533. rspamd_keypair_unref(st->keypair);
  534. }
  535. g_free(st);
  536. }
  537. static void
  538. fuzzy_key_stat_unref(gpointer p)
  539. {
  540. struct fuzzy_key_stat *st = p;
  541. REF_RELEASE(st);
  542. }
  543. static void
  544. fuzzy_key_dtor(gpointer p)
  545. {
  546. struct fuzzy_key *key = p;
  547. if (key) {
  548. if (key->stat) {
  549. REF_RELEASE(key->stat);
  550. }
  551. if (key->flags_stat) {
  552. kh_destroy(fuzzy_key_flag_stat, key->flags_stat);
  553. }
  554. if (key->forbidden_ids) {
  555. kh_destroy(fuzzy_key_ids_set, key->forbidden_ids);
  556. }
  557. g_free(key);
  558. }
  559. }
  560. static void
  561. fuzzy_hash_table_dtor(khash_t(rspamd_fuzzy_keys_hash) * hash)
  562. {
  563. struct fuzzy_key *key;
  564. kh_foreach_value(hash, key, {
  565. REF_RELEASE(key);
  566. });
  567. kh_destroy(rspamd_fuzzy_keys_hash, hash);
  568. }
  569. static void
  570. fuzzy_count_callback(uint64_t count, void *ud)
  571. {
  572. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  573. ctx->stat.fuzzy_hashes = count;
  574. }
  575. static void
  576. fuzzy_rl_bucket_free(gpointer p)
  577. {
  578. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *) p;
  579. rspamd_inet_address_free(elt->addr);
  580. g_free(elt);
  581. }
  582. static void
  583. fuzzy_stat_count_callback(uint64_t count, void *ud)
  584. {
  585. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  586. ev_timer_again(ctx->event_loop, &ctx->stat_ev);
  587. ctx->stat.fuzzy_hashes = count;
  588. }
  589. static void
  590. rspamd_fuzzy_stat_callback(EV_P_ ev_timer *w, int revents)
  591. {
  592. struct rspamd_fuzzy_storage_ctx *ctx =
  593. (struct rspamd_fuzzy_storage_ctx *) w->data;
  594. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_stat_count_callback, ctx);
  595. }
  596. static void
  597. fuzzy_update_version_callback(uint64_t ver, void *ud)
  598. {
  599. }
  600. static void
  601. rspamd_fuzzy_updates_cb(gboolean success,
  602. guint nadded,
  603. guint ndeleted,
  604. guint nextended,
  605. guint nignored,
  606. void *ud)
  607. {
  608. struct rspamd_updates_cbdata *cbdata = ud;
  609. struct rspamd_fuzzy_storage_ctx *ctx;
  610. const gchar *source;
  611. ctx = cbdata->ctx;
  612. source = cbdata->source;
  613. if (success) {
  614. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  615. msg_info("successfully updated fuzzy storage %s: %d updates in queue; "
  616. "%d pending currently; "
  617. "%d added; %d deleted; %d extended; %d duplicates",
  618. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  619. cbdata->updates_pending->len,
  620. ctx->updates_pending->len,
  621. nadded, ndeleted, nextended, nignored);
  622. rspamd_fuzzy_backend_version(ctx->backend, source,
  623. fuzzy_update_version_callback, NULL);
  624. ctx->updates_failed = 0;
  625. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  626. /* Plan exit */
  627. ev_break(ctx->event_loop, EVBREAK_ALL);
  628. }
  629. }
  630. else {
  631. if (++ctx->updates_failed > ctx->updates_maxfail) {
  632. msg_err("cannot commit update transaction to fuzzy backend %s, discard "
  633. "%ud updates after %d retries",
  634. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  635. cbdata->updates_pending->len,
  636. ctx->updates_maxfail);
  637. ctx->updates_failed = 0;
  638. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  639. /* Plan exit */
  640. ev_break(ctx->event_loop, EVBREAK_ALL);
  641. }
  642. }
  643. else {
  644. if (ctx->updates_pending) {
  645. msg_err("cannot commit update transaction to fuzzy backend %s; "
  646. "%ud updates are still left; %ud currently pending;"
  647. " %d retries remaining",
  648. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  649. cbdata->updates_pending->len,
  650. ctx->updates_pending->len,
  651. ctx->updates_maxfail - ctx->updates_failed);
  652. /* Move the remaining updates to ctx queue */
  653. g_array_append_vals(ctx->updates_pending,
  654. cbdata->updates_pending->data,
  655. cbdata->updates_pending->len);
  656. if (cbdata->final) {
  657. /* Try one more time */
  658. rspamd_fuzzy_process_updates_queue(cbdata->ctx, cbdata->source,
  659. cbdata->final);
  660. }
  661. }
  662. else {
  663. /* We have lost our ctx, so it is a race condition case */
  664. msg_err("cannot commit update transaction to fuzzy backend %s; "
  665. "%ud updates are still left; no more retries: a worker is terminated",
  666. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  667. cbdata->updates_pending->len);
  668. }
  669. }
  670. }
  671. g_array_free(cbdata->updates_pending, TRUE);
  672. g_free(cbdata->source);
  673. g_free(cbdata);
  674. }
  675. static gboolean
  676. rspamd_fuzzy_process_updates_queue(struct rspamd_fuzzy_storage_ctx *ctx,
  677. const gchar *source, gboolean final)
  678. {
  679. struct rspamd_updates_cbdata *cbdata;
  680. if (ctx->updates_pending->len > 0) {
  681. cbdata = g_malloc(sizeof(*cbdata));
  682. cbdata->ctx = ctx;
  683. cbdata->final = final;
  684. cbdata->updates_pending = ctx->updates_pending;
  685. ctx->updates_pending = g_array_sized_new(FALSE, FALSE,
  686. sizeof(struct fuzzy_peer_cmd),
  687. MAX(cbdata->updates_pending->len, 1024));
  688. cbdata->source = g_strdup(source);
  689. rspamd_fuzzy_backend_process_updates(ctx->backend,
  690. cbdata->updates_pending,
  691. source, rspamd_fuzzy_updates_cb, cbdata);
  692. return TRUE;
  693. }
  694. else if (final) {
  695. /* No need to sync */
  696. ev_break(ctx->event_loop, EVBREAK_ALL);
  697. }
  698. return FALSE;
  699. }
  700. static void
  701. rspamd_fuzzy_reply_io(EV_P_ ev_io *w, int revents)
  702. {
  703. struct fuzzy_session *session = (struct fuzzy_session *) w->data;
  704. ev_io_stop(EV_A_ w);
  705. rspamd_fuzzy_write_reply(session);
  706. REF_RELEASE(session);
  707. }
  708. static void
  709. rspamd_fuzzy_write_reply(struct fuzzy_session *session)
  710. {
  711. gssize r;
  712. gsize len;
  713. gconstpointer data;
  714. if (session->cmd_type == CMD_ENCRYPTED_NORMAL ||
  715. session->cmd_type == CMD_ENCRYPTED_SHINGLE) {
  716. /* Encrypted reply */
  717. data = &session->reply;
  718. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  719. len = sizeof(session->reply);
  720. }
  721. else {
  722. len = sizeof(session->reply.hdr) + sizeof(session->reply.rep.v1);
  723. }
  724. }
  725. else {
  726. data = &session->reply.rep;
  727. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  728. len = sizeof(session->reply.rep);
  729. }
  730. else {
  731. len = sizeof(session->reply.rep.v1);
  732. }
  733. }
  734. r = rspamd_inet_address_sendto(session->fd, data, len, 0,
  735. session->addr);
  736. if (r == -1) {
  737. if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
  738. /* Grab reference to avoid early destruction */
  739. REF_RETAIN(session);
  740. session->io.data = session;
  741. ev_io_init(&session->io,
  742. rspamd_fuzzy_reply_io, session->fd, EV_WRITE);
  743. ev_io_start(session->ctx->event_loop, &session->io);
  744. }
  745. else {
  746. msg_err("error while writing reply: %s", strerror(errno));
  747. }
  748. }
  749. }
  750. static void
  751. rspamd_fuzzy_update_key_stat(gboolean matched,
  752. struct fuzzy_key_stat *key_stat,
  753. guint cmd,
  754. struct rspamd_fuzzy_reply *res,
  755. ev_tstamp timestamp)
  756. {
  757. if (!matched && res->v1.value != 0) {
  758. key_stat->errors++;
  759. }
  760. else {
  761. if (cmd == FUZZY_CHECK) {
  762. key_stat->checked++;
  763. if (matched) {
  764. key_stat->matched++;
  765. }
  766. if (G_UNLIKELY(key_stat->last_checked_time == 0.0)) {
  767. key_stat->last_checked_time = timestamp;
  768. key_stat->last_checked_count = key_stat->checked;
  769. key_stat->last_matched_count = key_stat->matched;
  770. }
  771. else if (G_UNLIKELY(timestamp > key_stat->last_checked_time + KEY_STAT_INTERVAL)) {
  772. uint64_t nchecked = key_stat->checked - key_stat->last_checked_count;
  773. uint64_t nmatched = key_stat->matched - key_stat->last_matched_count;
  774. rspamd_set_counter_ema(&key_stat->checked_ctr, nchecked, 0.5f);
  775. rspamd_set_counter_ema(&key_stat->matched_ctr, nmatched, 0.5f);
  776. key_stat->last_checked_time = timestamp;
  777. key_stat->last_checked_count = key_stat->checked;
  778. key_stat->last_matched_count = key_stat->matched;
  779. }
  780. }
  781. else if (cmd == FUZZY_WRITE) {
  782. key_stat->added++;
  783. }
  784. else if (cmd == FUZZY_DEL) {
  785. key_stat->deleted++;
  786. }
  787. }
  788. }
  789. static void
  790. rspamd_fuzzy_update_stats(struct rspamd_fuzzy_storage_ctx *ctx,
  791. enum rspamd_fuzzy_epoch epoch,
  792. gboolean matched,
  793. gboolean is_shingle,
  794. gboolean is_delayed,
  795. struct fuzzy_key *key,
  796. struct fuzzy_key_stat *ip_stat,
  797. guint cmd,
  798. struct rspamd_fuzzy_reply *res,
  799. ev_tstamp timestamp)
  800. {
  801. ctx->stat.fuzzy_hashes_checked[epoch]++;
  802. if (matched) {
  803. ctx->stat.fuzzy_hashes_found[epoch]++;
  804. }
  805. if (is_shingle) {
  806. ctx->stat.fuzzy_shingles_checked[epoch]++;
  807. }
  808. if (is_delayed) {
  809. ctx->stat.delayed_hashes++;
  810. }
  811. if (key) {
  812. rspamd_fuzzy_update_key_stat(matched, key->stat, cmd, res, timestamp);
  813. if (matched || ((cmd == FUZZY_WRITE || cmd == FUZZY_DEL) && res->v1.value == 0)) {
  814. /* Update per flag stats */
  815. khiter_t k;
  816. struct fuzzy_key_stat *flag_stat;
  817. k = kh_get(fuzzy_key_flag_stat, key->flags_stat, res->v1.flag);
  818. if (k == kh_end(key->flags_stat)) {
  819. /* Insert new flag */
  820. int r;
  821. k = kh_put(fuzzy_key_flag_stat, key->flags_stat, res->v1.flag, &r);
  822. memset(&kh_value(key->flags_stat, k), 0, sizeof(struct fuzzy_key_stat));
  823. }
  824. flag_stat = &kh_value(key->flags_stat, k);
  825. rspamd_fuzzy_update_key_stat(matched, flag_stat, cmd, res, timestamp);
  826. }
  827. }
  828. if (ip_stat) {
  829. if (!matched && res->v1.value != 0) {
  830. ip_stat->errors++;
  831. }
  832. else {
  833. if (cmd == FUZZY_CHECK) {
  834. ip_stat->checked++;
  835. if (matched) {
  836. ip_stat->matched++;
  837. }
  838. }
  839. else if (cmd == FUZZY_WRITE) {
  840. ip_stat->added++;
  841. }
  842. else if (cmd == FUZZY_DEL) {
  843. ip_stat->deleted++;
  844. }
  845. }
  846. }
  847. }
  848. enum rspamd_fuzzy_reply_flags {
  849. RSPAMD_FUZZY_REPLY_ENCRYPTED = 0x1u << 0u,
  850. RSPAMD_FUZZY_REPLY_SHINGLE = 0x1u << 1u,
  851. RSPAMD_FUZZY_REPLY_DELAY = 0x1u << 2u,
  852. };
  853. static void
  854. rspamd_fuzzy_make_reply(struct rspamd_fuzzy_cmd *cmd,
  855. struct rspamd_fuzzy_reply *result,
  856. struct fuzzy_session *session,
  857. gint flags)
  858. {
  859. gsize len;
  860. if (cmd) {
  861. result->v1.tag = cmd->tag;
  862. memcpy(&session->reply.rep, result, sizeof(*result));
  863. if (flags & RSPAMD_FUZZY_REPLY_DELAY) {
  864. /* Hash is too fresh, need to delay it */
  865. session->reply.rep.ts = 0;
  866. session->reply.rep.v1.prob = 0.0f;
  867. session->reply.rep.v1.value = 0;
  868. }
  869. bool default_disabled = false;
  870. {
  871. khiter_t k;
  872. k = kh_get(fuzzy_key_ids_set, session->ctx->default_forbidden_ids, session->reply.rep.v1.flag);
  873. if (k != kh_end(session->ctx->default_forbidden_ids)) {
  874. /* Hash is from a forbidden flag by default */
  875. default_disabled = true;
  876. }
  877. }
  878. if (flags & RSPAMD_FUZZY_REPLY_ENCRYPTED) {
  879. if (session->reply.rep.v1.prob > 0 && session->key && session->key->forbidden_ids) {
  880. khiter_t k;
  881. k = kh_get(fuzzy_key_ids_set, session->key->forbidden_ids, session->reply.rep.v1.flag);
  882. if (k != kh_end(session->key->forbidden_ids)) {
  883. /* Hash is from a forbidden flag for this key */
  884. session->reply.rep.ts = 0;
  885. session->reply.rep.v1.prob = 0.0f;
  886. session->reply.rep.v1.value = 0;
  887. session->reply.rep.v1.flag = 0;
  888. }
  889. }
  890. else if (default_disabled) {
  891. /* Hash is from a forbidden flag by default */
  892. session->reply.rep.ts = 0;
  893. session->reply.rep.v1.prob = 0.0f;
  894. session->reply.rep.v1.value = 0;
  895. session->reply.rep.v1.flag = 0;
  896. }
  897. /* We need also to encrypt reply */
  898. ottery_rand_bytes(session->reply.hdr.nonce,
  899. sizeof(session->reply.hdr.nonce));
  900. /*
  901. * For old replies we need to encrypt just old part, otherwise
  902. * decryption would fail due to mac verification mistake
  903. */
  904. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  905. len = sizeof(session->reply.rep);
  906. }
  907. else {
  908. len = sizeof(session->reply.rep.v1);
  909. }
  910. /* Update stats before encryption */
  911. if (cmd->cmd != FUZZY_STAT && cmd->cmd <= FUZZY_CLIENT_MAX) {
  912. rspamd_fuzzy_update_stats(session->ctx,
  913. session->epoch,
  914. session->reply.rep.v1.prob > 0.5f,
  915. flags & RSPAMD_FUZZY_REPLY_SHINGLE,
  916. flags & RSPAMD_FUZZY_REPLY_DELAY,
  917. session->key,
  918. session->ip_stat,
  919. cmd->cmd,
  920. &session->reply.rep,
  921. session->timestamp);
  922. }
  923. rspamd_cryptobox_encrypt_nm_inplace((guchar *) &session->reply.rep,
  924. len,
  925. session->reply.hdr.nonce,
  926. session->nm,
  927. session->reply.hdr.mac,
  928. RSPAMD_CRYPTOBOX_MODE_25519);
  929. }
  930. else if (default_disabled) {
  931. /* Hash is from a forbidden flag by default, and there is no encryption override */
  932. session->reply.rep.ts = 0;
  933. session->reply.rep.v1.prob = 0.0f;
  934. session->reply.rep.v1.value = 0;
  935. session->reply.rep.v1.flag = 0;
  936. }
  937. if (!(flags & RSPAMD_FUZZY_REPLY_ENCRYPTED)) {
  938. if (cmd->cmd != FUZZY_STAT && cmd->cmd <= FUZZY_CLIENT_MAX) {
  939. rspamd_fuzzy_update_stats(session->ctx,
  940. session->epoch,
  941. session->reply.rep.v1.prob > 0.5f,
  942. flags & RSPAMD_FUZZY_REPLY_SHINGLE,
  943. flags & RSPAMD_FUZZY_REPLY_DELAY,
  944. session->key,
  945. session->ip_stat,
  946. cmd->cmd,
  947. &session->reply.rep,
  948. session->timestamp);
  949. }
  950. }
  951. }
  952. rspamd_fuzzy_write_reply(session);
  953. }
  954. static gboolean
  955. fuzzy_peer_try_send(gint fd, struct fuzzy_peer_request *up_req)
  956. {
  957. gssize r;
  958. r = write(fd, &up_req->cmd, sizeof(up_req->cmd));
  959. if (r != sizeof(up_req->cmd)) {
  960. return FALSE;
  961. }
  962. return TRUE;
  963. }
  964. static void
  965. fuzzy_peer_send_io(EV_P_ ev_io *w, int revents)
  966. {
  967. struct fuzzy_peer_request *up_req = (struct fuzzy_peer_request *) w->data;
  968. if (!fuzzy_peer_try_send(w->fd, up_req)) {
  969. msg_err("cannot send update request to the peer: %s", strerror(errno));
  970. }
  971. ev_io_stop(EV_A_ w);
  972. g_free(up_req);
  973. }
  974. static void
  975. rspamd_fuzzy_extensions_tolua(lua_State *L,
  976. struct fuzzy_session *session)
  977. {
  978. struct rspamd_fuzzy_cmd_extension *ext;
  979. rspamd_inet_addr_t *addr;
  980. lua_createtable(L, 0, 0);
  981. LL_FOREACH(session->extensions, ext)
  982. {
  983. switch (ext->ext) {
  984. case RSPAMD_FUZZY_EXT_SOURCE_DOMAIN:
  985. lua_pushlstring(L, ext->payload, ext->length);
  986. lua_setfield(L, -2, "domain");
  987. break;
  988. case RSPAMD_FUZZY_EXT_SOURCE_IP4:
  989. addr = rspamd_inet_address_new(AF_INET, ext->payload);
  990. rspamd_lua_ip_push(L, addr);
  991. rspamd_inet_address_free(addr);
  992. lua_setfield(L, -2, "ip");
  993. break;
  994. case RSPAMD_FUZZY_EXT_SOURCE_IP6:
  995. addr = rspamd_inet_address_new(AF_INET6, ext->payload);
  996. rspamd_lua_ip_push(L, addr);
  997. rspamd_inet_address_free(addr);
  998. lua_setfield(L, -2, "ip");
  999. break;
  1000. }
  1001. }
  1002. }
  1003. static void
  1004. rspamd_fuzzy_check_callback(struct rspamd_fuzzy_reply *result, void *ud)
  1005. {
  1006. struct fuzzy_session *session = ud;
  1007. gboolean is_shingle = FALSE, __attribute__((unused)) encrypted = FALSE;
  1008. struct rspamd_fuzzy_cmd *cmd = NULL;
  1009. const struct rspamd_shingle *shingle = NULL;
  1010. struct rspamd_shingle sgl_cpy;
  1011. gint send_flags = 0;
  1012. switch (session->cmd_type) {
  1013. case CMD_ENCRYPTED_NORMAL:
  1014. encrypted = TRUE;
  1015. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1016. /* Fallthrough */
  1017. case CMD_NORMAL:
  1018. cmd = &session->cmd.basic;
  1019. break;
  1020. case CMD_ENCRYPTED_SHINGLE:
  1021. encrypted = TRUE;
  1022. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1023. /* Fallthrough */
  1024. case CMD_SHINGLE:
  1025. cmd = &session->cmd.basic;
  1026. memcpy(&sgl_cpy, &session->cmd.sgl, sizeof(sgl_cpy));
  1027. shingle = &sgl_cpy;
  1028. is_shingle = TRUE;
  1029. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  1030. break;
  1031. }
  1032. if (session->ctx->lua_post_handler_cbref != -1) {
  1033. /* Start lua post handler */
  1034. lua_State *L = session->ctx->cfg->lua_state;
  1035. gint err_idx, ret;
  1036. lua_pushcfunction(L, &rspamd_lua_traceback);
  1037. err_idx = lua_gettop(L);
  1038. /* Preallocate stack (small opt) */
  1039. lua_checkstack(L, err_idx + 9);
  1040. /* function */
  1041. lua_rawgeti(L, LUA_REGISTRYINDEX, session->ctx->lua_post_handler_cbref);
  1042. /* client IP */
  1043. if (session->addr) {
  1044. rspamd_lua_ip_push(L, session->addr);
  1045. }
  1046. else {
  1047. lua_pushnil(L);
  1048. }
  1049. /* client command */
  1050. lua_pushinteger(L, cmd->cmd);
  1051. /* command value (push as rspamd_text) */
  1052. (void) lua_new_text(L, result->digest, sizeof(result->digest), FALSE);
  1053. /* is shingle */
  1054. lua_pushboolean(L, is_shingle);
  1055. /* result value */
  1056. lua_pushinteger(L, result->v1.value);
  1057. /* result probability */
  1058. lua_pushnumber(L, result->v1.prob);
  1059. /* result flag */
  1060. lua_pushinteger(L, result->v1.flag);
  1061. /* result timestamp */
  1062. lua_pushinteger(L, result->ts);
  1063. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  1064. rspamd_fuzzy_extensions_tolua(L, session);
  1065. if ((ret = lua_pcall(L, 9, LUA_MULTRET, err_idx)) != 0) {
  1066. msg_err("call to lua_post_handler lua "
  1067. "script failed (%d): %s",
  1068. ret, lua_tostring(L, -1));
  1069. }
  1070. else {
  1071. /* Return values order:
  1072. * the first reply will be on err_idx + 1
  1073. * if it is true, then we need to read the former ones:
  1074. * 2-nd will be reply code
  1075. * 3-rd will be probability (or 0.0 if missing)
  1076. * 4-th value is flag (or default flag if missing)
  1077. */
  1078. ret = lua_toboolean(L, err_idx + 1);
  1079. if (ret) {
  1080. /* Artificial reply */
  1081. result->v1.value = lua_tointeger(L, err_idx + 2);
  1082. if (lua_isnumber(L, err_idx + 3)) {
  1083. result->v1.prob = lua_tonumber(L, err_idx + 3);
  1084. }
  1085. else {
  1086. result->v1.prob = 0.0f;
  1087. }
  1088. if (lua_isnumber(L, err_idx + 4)) {
  1089. result->v1.flag = lua_tointeger(L, err_idx + 4);
  1090. }
  1091. lua_settop(L, 0);
  1092. rspamd_fuzzy_make_reply(cmd, result, session, send_flags);
  1093. REF_RELEASE(session);
  1094. return;
  1095. }
  1096. }
  1097. lua_settop(L, 0);
  1098. }
  1099. if (!isnan(session->ctx->delay) &&
  1100. rspamd_match_radix_map_addr(session->ctx->delay_whitelist,
  1101. session->addr) == NULL) {
  1102. gdouble hash_age = rspamd_get_calendar_ticks() - result->ts;
  1103. gdouble jittered_age = rspamd_time_jitter(session->ctx->delay,
  1104. session->ctx->delay / 2.0);
  1105. if (hash_age < jittered_age) {
  1106. send_flags |= RSPAMD_FUZZY_REPLY_DELAY;
  1107. }
  1108. }
  1109. /* Refresh hash if found with strong confidence */
  1110. if (result->v1.prob > 0.9 && !session->ctx->read_only) {
  1111. struct fuzzy_peer_cmd up_cmd;
  1112. struct fuzzy_peer_request *up_req;
  1113. if (session->worker->index == 0) {
  1114. /* Just add to the queue */
  1115. memset(&up_cmd, 0, sizeof(up_cmd));
  1116. up_cmd.is_shingle = is_shingle;
  1117. memcpy(up_cmd.cmd.normal.digest, result->digest,
  1118. sizeof(up_cmd.cmd.normal.digest));
  1119. up_cmd.cmd.normal.flag = result->v1.flag;
  1120. up_cmd.cmd.normal.cmd = FUZZY_REFRESH;
  1121. up_cmd.cmd.normal.shingles_count = cmd->shingles_count;
  1122. if (is_shingle && shingle) {
  1123. memcpy(&up_cmd.cmd.shingle.sgl, shingle,
  1124. sizeof(up_cmd.cmd.shingle.sgl));
  1125. }
  1126. g_array_append_val(session->ctx->updates_pending, up_cmd);
  1127. }
  1128. else {
  1129. /* We need to send request to the peer */
  1130. up_req = g_malloc0(sizeof(*up_req));
  1131. up_req->cmd.is_shingle = is_shingle;
  1132. memcpy(up_req->cmd.cmd.normal.digest, result->digest,
  1133. sizeof(up_req->cmd.cmd.normal.digest));
  1134. up_req->cmd.cmd.normal.flag = result->v1.flag;
  1135. up_req->cmd.cmd.normal.cmd = FUZZY_REFRESH;
  1136. up_req->cmd.cmd.normal.shingles_count = cmd->shingles_count;
  1137. if (is_shingle && shingle) {
  1138. memcpy(&up_req->cmd.cmd.shingle.sgl, shingle,
  1139. sizeof(up_req->cmd.cmd.shingle.sgl));
  1140. }
  1141. if (!fuzzy_peer_try_send(session->ctx->peer_fd, up_req)) {
  1142. up_req->io_ev.data = up_req;
  1143. ev_io_init(&up_req->io_ev, fuzzy_peer_send_io,
  1144. session->ctx->peer_fd, EV_WRITE);
  1145. ev_io_start(session->ctx->event_loop, &up_req->io_ev);
  1146. }
  1147. else {
  1148. g_free(up_req);
  1149. }
  1150. }
  1151. }
  1152. rspamd_fuzzy_make_reply(cmd, result, session, send_flags);
  1153. REF_RELEASE(session);
  1154. }
  1155. static void
  1156. rspamd_fuzzy_process_command(struct fuzzy_session *session)
  1157. {
  1158. gboolean is_shingle = FALSE, __attribute__((unused)) encrypted = FALSE;
  1159. struct rspamd_fuzzy_cmd *cmd = NULL;
  1160. struct rspamd_fuzzy_reply result;
  1161. struct fuzzy_peer_cmd up_cmd;
  1162. struct fuzzy_peer_request *up_req;
  1163. struct fuzzy_key_stat *ip_stat = NULL;
  1164. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  1165. rspamd_inet_addr_t *naddr;
  1166. gpointer ptr;
  1167. gsize up_len = 0;
  1168. gint send_flags = 0;
  1169. cmd = &session->cmd.basic;
  1170. switch (session->cmd_type) {
  1171. case CMD_NORMAL:
  1172. up_len = sizeof(session->cmd.basic);
  1173. break;
  1174. case CMD_SHINGLE:
  1175. up_len = sizeof(session->cmd);
  1176. is_shingle = TRUE;
  1177. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  1178. break;
  1179. case CMD_ENCRYPTED_NORMAL:
  1180. up_len = sizeof(session->cmd.basic);
  1181. encrypted = TRUE;
  1182. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1183. break;
  1184. case CMD_ENCRYPTED_SHINGLE:
  1185. up_len = sizeof(session->cmd);
  1186. encrypted = TRUE;
  1187. is_shingle = TRUE;
  1188. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE | RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1189. break;
  1190. default:
  1191. msg_err("invalid command type: %d", session->cmd_type);
  1192. return;
  1193. }
  1194. memset(&result, 0, sizeof(result));
  1195. memcpy(result.digest, cmd->digest, sizeof(result.digest));
  1196. result.v1.flag = cmd->flag;
  1197. result.v1.tag = cmd->tag;
  1198. if (session->ctx->lua_pre_handler_cbref != -1) {
  1199. /* Start lua pre handler */
  1200. lua_State *L = session->ctx->cfg->lua_state;
  1201. gint err_idx, ret;
  1202. lua_pushcfunction(L, &rspamd_lua_traceback);
  1203. err_idx = lua_gettop(L);
  1204. /* Preallocate stack (small opt) */
  1205. lua_checkstack(L, err_idx + 5);
  1206. /* function */
  1207. lua_rawgeti(L, LUA_REGISTRYINDEX, session->ctx->lua_pre_handler_cbref);
  1208. /* client IP */
  1209. rspamd_lua_ip_push(L, session->addr);
  1210. /* client command */
  1211. lua_pushinteger(L, cmd->cmd);
  1212. /* command value (push as rspamd_text) */
  1213. (void) lua_new_text(L, cmd->digest, sizeof(cmd->digest), FALSE);
  1214. /* is shingle */
  1215. lua_pushboolean(L, is_shingle);
  1216. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  1217. rspamd_fuzzy_extensions_tolua(L, session);
  1218. if ((ret = lua_pcall(L, 5, LUA_MULTRET, err_idx)) != 0) {
  1219. msg_err("call to lua_pre_handler lua "
  1220. "script failed (%d): %s",
  1221. ret, lua_tostring(L, -1));
  1222. }
  1223. else {
  1224. /* Return values order:
  1225. * the first reply will be on err_idx + 1
  1226. * if it is true, then we need to read the former ones:
  1227. * 2-nd will be reply code
  1228. * 3-rd will be probability (or 0.0 if missing)
  1229. */
  1230. ret = lua_toboolean(L, err_idx + 1);
  1231. if (ret) {
  1232. /* Artificial reply */
  1233. result.v1.value = lua_tointeger(L, err_idx + 2);
  1234. if (lua_isnumber(L, err_idx + 3)) {
  1235. result.v1.prob = lua_tonumber(L, err_idx + 3);
  1236. }
  1237. else {
  1238. result.v1.prob = 0.0f;
  1239. }
  1240. lua_settop(L, 0);
  1241. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1242. return;
  1243. }
  1244. }
  1245. lua_settop(L, 0);
  1246. }
  1247. if (G_UNLIKELY(cmd == NULL || up_len == 0)) {
  1248. result.v1.value = 500;
  1249. result.v1.prob = 0.0f;
  1250. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1251. return;
  1252. }
  1253. if (session->ctx->encrypted_only && !encrypted) {
  1254. /* Do not accept unencrypted commands */
  1255. result.v1.value = 403;
  1256. result.v1.prob = 0.0f;
  1257. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1258. return;
  1259. }
  1260. if (session->key && session->addr) {
  1261. ip_stat = rspamd_lru_hash_lookup(session->key->stat->last_ips,
  1262. session->addr, -1);
  1263. if (ip_stat == NULL) {
  1264. naddr = rspamd_inet_address_copy(session->addr, NULL);
  1265. ip_stat = g_malloc0(sizeof(*ip_stat));
  1266. REF_INIT_RETAIN(ip_stat, fuzzy_key_stat_dtor);
  1267. rspamd_lru_hash_insert(session->key->stat->last_ips,
  1268. naddr, ip_stat, -1, 0);
  1269. }
  1270. REF_RETAIN(ip_stat);
  1271. session->ip_stat = ip_stat;
  1272. }
  1273. if (cmd->cmd == FUZZY_CHECK) {
  1274. bool can_continue = true;
  1275. if (session->ctx->ratelimit_buckets) {
  1276. if (session->ctx->ratelimit_log_only) {
  1277. (void) rspamd_fuzzy_check_ratelimit(session); /* Check but ignore */
  1278. }
  1279. else {
  1280. can_continue = rspamd_fuzzy_check_ratelimit(session);
  1281. }
  1282. }
  1283. if (can_continue) {
  1284. REF_RETAIN(session);
  1285. rspamd_fuzzy_backend_check(session->ctx->backend, cmd,
  1286. rspamd_fuzzy_check_callback, session);
  1287. }
  1288. else {
  1289. result.v1.value = 403;
  1290. result.v1.prob = 0.0f;
  1291. result.v1.flag = 0;
  1292. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1293. }
  1294. }
  1295. else if (cmd->cmd == FUZZY_STAT) {
  1296. /* Store approximation (if needed) */
  1297. result.v1.prob = session->ctx->stat.fuzzy_hashes;
  1298. /* Store high qword in value and low qword in flag */
  1299. result.v1.value = (int32_t) ((uint64_t) session->ctx->stat.fuzzy_hashes >> 32);
  1300. result.v1.flag = (uint32_t) (session->ctx->stat.fuzzy_hashes & G_MAXUINT32);
  1301. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1302. }
  1303. else if (cmd->cmd == FUZZY_PING) {
  1304. result.v1.prob = 1.0f;
  1305. result.v1.value = cmd->value;
  1306. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1307. }
  1308. else {
  1309. if (rspamd_fuzzy_check_write(session)) {
  1310. /* Check whitelist */
  1311. if (session->ctx->skip_hashes && cmd->cmd == FUZZY_WRITE) {
  1312. rspamd_encode_hex_buf(cmd->digest, sizeof(cmd->digest),
  1313. hexbuf, sizeof(hexbuf) - 1);
  1314. hexbuf[sizeof(hexbuf) - 1] = '\0';
  1315. if (rspamd_match_hash_map(session->ctx->skip_hashes,
  1316. hexbuf, sizeof(hexbuf) - 1)) {
  1317. result.v1.value = 401;
  1318. result.v1.prob = 0.0f;
  1319. goto reply;
  1320. }
  1321. }
  1322. if (session->ctx->weak_ids && kh_get(fuzzy_key_ids_set, session->ctx->weak_ids, cmd->flag) != kh_end(session->ctx->weak_ids)) {
  1323. /* Flag command as weak */
  1324. cmd->version |= RSPAMD_FUZZY_FLAG_WEAK;
  1325. }
  1326. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  1327. /* Just add to the queue */
  1328. up_cmd.is_shingle = is_shingle;
  1329. ptr = is_shingle ? (gpointer) &up_cmd.cmd.shingle : (gpointer) &up_cmd.cmd.normal;
  1330. memcpy(ptr, cmd, up_len);
  1331. g_array_append_val(session->ctx->updates_pending, up_cmd);
  1332. }
  1333. else {
  1334. /* We need to send request to the peer */
  1335. up_req = g_malloc0(sizeof(*up_req));
  1336. up_req->cmd.is_shingle = is_shingle;
  1337. ptr = is_shingle ? (gpointer) &up_req->cmd.cmd.shingle : (gpointer) &up_req->cmd.cmd.normal;
  1338. memcpy(ptr, cmd, up_len);
  1339. if (!fuzzy_peer_try_send(session->ctx->peer_fd, up_req)) {
  1340. up_req->io_ev.data = up_req;
  1341. ev_io_init(&up_req->io_ev, fuzzy_peer_send_io,
  1342. session->ctx->peer_fd, EV_WRITE);
  1343. ev_io_start(session->ctx->event_loop, &up_req->io_ev);
  1344. }
  1345. else {
  1346. g_free(up_req);
  1347. }
  1348. }
  1349. result.v1.value = 0;
  1350. result.v1.prob = 1.0f;
  1351. }
  1352. else {
  1353. result.v1.value = 403;
  1354. result.v1.prob = 0.0f;
  1355. }
  1356. reply:
  1357. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1358. }
  1359. }
  1360. static enum rspamd_fuzzy_epoch
  1361. rspamd_fuzzy_command_valid(struct rspamd_fuzzy_cmd *cmd, gint r)
  1362. {
  1363. enum rspamd_fuzzy_epoch ret = RSPAMD_FUZZY_EPOCH_MAX;
  1364. switch (cmd->version & RSPAMD_FUZZY_VERSION_MASK) {
  1365. case 4:
  1366. if (cmd->shingles_count > 0) {
  1367. if (r >= sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1368. ret = RSPAMD_FUZZY_EPOCH11;
  1369. }
  1370. }
  1371. else {
  1372. if (r >= sizeof(*cmd)) {
  1373. ret = RSPAMD_FUZZY_EPOCH11;
  1374. }
  1375. }
  1376. break;
  1377. case 3:
  1378. if (cmd->shingles_count > 0) {
  1379. if (r == sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1380. ret = RSPAMD_FUZZY_EPOCH10;
  1381. }
  1382. }
  1383. else {
  1384. if (r == sizeof(*cmd)) {
  1385. ret = RSPAMD_FUZZY_EPOCH10;
  1386. }
  1387. }
  1388. break;
  1389. default:
  1390. break;
  1391. }
  1392. return ret;
  1393. }
  1394. static gboolean
  1395. rspamd_fuzzy_decrypt_command(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1396. {
  1397. struct rspamd_fuzzy_encrypted_req_hdr hdr;
  1398. struct rspamd_cryptobox_pubkey *rk;
  1399. struct fuzzy_key *key = NULL;
  1400. if (s->ctx->default_key == NULL && s->ctx->dynamic_keys == NULL) {
  1401. msg_warn("received encrypted request when encryption is not enabled");
  1402. return FALSE;
  1403. }
  1404. if (buflen < sizeof(hdr)) {
  1405. msg_warn("XXX: should not be reached");
  1406. return FALSE;
  1407. }
  1408. memcpy(&hdr, buf, sizeof(hdr));
  1409. buf += sizeof(hdr);
  1410. buflen -= sizeof(hdr);
  1411. /* Try to find the desired key */
  1412. khiter_t k = kh_get(rspamd_fuzzy_keys_hash, s->ctx->keys, hdr.key_id);
  1413. if (k == kh_end(s->ctx->keys)) {
  1414. key = s->ctx->default_key;
  1415. /* Check dynamic keys */
  1416. if (s->ctx->dynamic_keys) {
  1417. k = kh_get(rspamd_fuzzy_keys_hash, s->ctx->dynamic_keys, hdr.key_id);
  1418. if (k != kh_end(s->ctx->keys)) {
  1419. key = kh_val(s->ctx->dynamic_keys, k);
  1420. }
  1421. }
  1422. }
  1423. else {
  1424. key = kh_val(s->ctx->keys, k);
  1425. }
  1426. if (key == NULL) {
  1427. /* Cannot find any suitable decryption key */
  1428. msg_debug("cannot find suitable decryption key");
  1429. return FALSE;
  1430. }
  1431. /* Now process the remote pubkey */
  1432. rk = rspamd_pubkey_from_bin(hdr.pubkey, sizeof(hdr.pubkey),
  1433. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  1434. if (rk == NULL) {
  1435. msg_err("bad key; ip=%s",
  1436. rspamd_inet_address_to_string(s->addr));
  1437. return FALSE;
  1438. }
  1439. /* Try to get the cached NM */
  1440. rspamd_keypair_cache_process(s->ctx->keypair_cache, key->key, rk);
  1441. /* Now decrypt request */
  1442. if (!rspamd_cryptobox_decrypt_nm_inplace(buf, buflen, hdr.nonce,
  1443. rspamd_pubkey_get_nm(rk, key->key),
  1444. hdr.mac, RSPAMD_CRYPTOBOX_MODE_25519)) {
  1445. msg_err("decryption failed; ip=%s",
  1446. rspamd_inet_address_to_string(s->addr));
  1447. rspamd_pubkey_unref(rk);
  1448. return FALSE;
  1449. }
  1450. s->key = key;
  1451. REF_RETAIN(key);
  1452. memcpy(s->nm, rspamd_pubkey_get_nm(rk, key->key), sizeof(s->nm));
  1453. rspamd_pubkey_unref(rk);
  1454. return TRUE;
  1455. }
  1456. static gboolean
  1457. rspamd_fuzzy_extensions_from_wire(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1458. {
  1459. struct rspamd_fuzzy_cmd_extension *ext, *prev_ext;
  1460. guchar *storage, *p = buf, *end = buf + buflen;
  1461. gsize st_len = 0, n_ext = 0;
  1462. /* Read number of extensions to allocate array */
  1463. while (p < end) {
  1464. guchar cmd = *p++;
  1465. if (p < end) {
  1466. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1467. /* Next byte is buf length */
  1468. guchar dom_len = *p++;
  1469. if (dom_len <= (end - p)) {
  1470. st_len += dom_len;
  1471. n_ext++;
  1472. }
  1473. else {
  1474. /* Truncation */
  1475. return FALSE;
  1476. }
  1477. p += dom_len;
  1478. }
  1479. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1480. if (end - p >= sizeof(in_addr_t)) {
  1481. n_ext++;
  1482. st_len += sizeof(in_addr_t);
  1483. }
  1484. else {
  1485. /* Truncation */
  1486. return FALSE;
  1487. }
  1488. p += sizeof(in_addr_t);
  1489. }
  1490. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1491. if (end - p >= sizeof(struct in6_addr)) {
  1492. n_ext++;
  1493. st_len += sizeof(struct in6_addr);
  1494. }
  1495. else {
  1496. /* Truncation */
  1497. return FALSE;
  1498. }
  1499. p += sizeof(struct in6_addr);
  1500. }
  1501. else {
  1502. /* Invalid command */
  1503. return FALSE;
  1504. }
  1505. }
  1506. else {
  1507. /* Truncated extension */
  1508. return FALSE;
  1509. }
  1510. }
  1511. if (n_ext > 0) {
  1512. p = buf;
  1513. /*
  1514. * Memory layout: n_ext of struct rspamd_fuzzy_cmd_extension
  1515. * payload for each extension in a continuous data segment
  1516. */
  1517. storage = g_malloc(n_ext * sizeof(struct rspamd_fuzzy_cmd_extension) +
  1518. st_len);
  1519. guchar *data_buf = storage +
  1520. n_ext * sizeof(struct rspamd_fuzzy_cmd_extension);
  1521. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1522. /* All validation has been done, so we can just go further */
  1523. while (p < end) {
  1524. prev_ext = ext;
  1525. guchar cmd = *p++;
  1526. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1527. /* Next byte is buf length */
  1528. guchar dom_len = *p++;
  1529. guchar *dest = data_buf;
  1530. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
  1531. ext->next = ext + 1;
  1532. ext->length = dom_len;
  1533. ext->payload = dest;
  1534. memcpy(dest, p, dom_len);
  1535. p += dom_len;
  1536. data_buf += dom_len;
  1537. ext = ext->next;
  1538. }
  1539. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1540. guchar *dest = data_buf;
  1541. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP4;
  1542. ext->next = ext + 1;
  1543. ext->length = sizeof(in_addr_t);
  1544. ext->payload = dest;
  1545. memcpy(dest, p, sizeof(in_addr_t));
  1546. p += sizeof(in_addr_t);
  1547. data_buf += sizeof(in_addr_t);
  1548. ext = ext->next;
  1549. }
  1550. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1551. guchar *dest = data_buf;
  1552. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP6;
  1553. ext->next = ext + 1;
  1554. ext->length = sizeof(struct in6_addr);
  1555. ext->payload = dest;
  1556. memcpy(dest, p, sizeof(struct in6_addr));
  1557. p += sizeof(struct in6_addr);
  1558. data_buf += sizeof(struct in6_addr);
  1559. ext = ext->next;
  1560. }
  1561. else {
  1562. g_assert_not_reached();
  1563. }
  1564. }
  1565. /* Last next should be NULL */
  1566. prev_ext->next = NULL;
  1567. /* Rewind to the begin */
  1568. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1569. s->extensions = ext;
  1570. }
  1571. return TRUE;
  1572. }
  1573. static gboolean
  1574. rspamd_fuzzy_cmd_from_wire(guchar *buf, guint buflen, struct fuzzy_session *s)
  1575. {
  1576. enum rspamd_fuzzy_epoch epoch;
  1577. gboolean encrypted = FALSE;
  1578. if (buflen < sizeof(struct rspamd_fuzzy_cmd)) {
  1579. msg_debug("truncated fuzzy command of size %d received", buflen);
  1580. return FALSE;
  1581. }
  1582. /* Now check encryption */
  1583. if (buflen >= sizeof(struct rspamd_fuzzy_encrypted_cmd)) {
  1584. if (memcmp(buf, fuzzy_encrypted_magic, sizeof(fuzzy_encrypted_magic)) == 0) {
  1585. /* Encrypted command */
  1586. encrypted = TRUE;
  1587. }
  1588. }
  1589. if (encrypted) {
  1590. /* Decrypt first */
  1591. if (!rspamd_fuzzy_decrypt_command(s, buf, buflen)) {
  1592. return FALSE;
  1593. }
  1594. else {
  1595. /*
  1596. * Advance buffer to skip encrypted header.
  1597. * Note that after rspamd_fuzzy_decrypt_command buf is unencrypted
  1598. */
  1599. buf += sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1600. buflen -= sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1601. }
  1602. }
  1603. /* Fill the normal command */
  1604. if (buflen < sizeof(s->cmd.basic)) {
  1605. msg_debug("truncated normal fuzzy command of size %d received", buflen);
  1606. return FALSE;
  1607. }
  1608. memcpy(&s->cmd.basic, buf, sizeof(s->cmd.basic));
  1609. epoch = rspamd_fuzzy_command_valid(&s->cmd.basic, buflen);
  1610. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1611. msg_debug("invalid fuzzy command of size %d received", buflen);
  1612. return FALSE;
  1613. }
  1614. s->epoch = epoch;
  1615. /* Advance buf */
  1616. buf += sizeof(s->cmd.basic);
  1617. buflen -= sizeof(s->cmd.basic);
  1618. if (s->cmd.basic.shingles_count > 0) {
  1619. if (buflen >= sizeof(s->cmd.sgl)) {
  1620. /* Copy the shingles part */
  1621. memcpy(&s->cmd.sgl, buf, sizeof(s->cmd.sgl));
  1622. }
  1623. else {
  1624. /* Truncated stuff */
  1625. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1626. return FALSE;
  1627. }
  1628. buf += sizeof(s->cmd.sgl);
  1629. buflen -= sizeof(s->cmd.sgl);
  1630. if (encrypted) {
  1631. s->cmd_type = CMD_ENCRYPTED_SHINGLE;
  1632. }
  1633. else {
  1634. s->cmd_type = CMD_SHINGLE;
  1635. }
  1636. }
  1637. else {
  1638. if (encrypted) {
  1639. s->cmd_type = CMD_ENCRYPTED_NORMAL;
  1640. }
  1641. else {
  1642. s->cmd_type = CMD_NORMAL;
  1643. }
  1644. }
  1645. if (buflen > 0) {
  1646. /* Process possible extensions */
  1647. if (!rspamd_fuzzy_extensions_from_wire(s, buf, buflen)) {
  1648. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1649. return FALSE;
  1650. }
  1651. }
  1652. return TRUE;
  1653. }
  1654. static void
  1655. fuzzy_session_destroy(gpointer d)
  1656. {
  1657. struct fuzzy_session *session = d;
  1658. rspamd_inet_address_free(session->addr);
  1659. rspamd_explicit_memzero(session->nm, sizeof(session->nm));
  1660. session->worker->nconns--;
  1661. if (session->ip_stat) {
  1662. REF_RELEASE(session->ip_stat);
  1663. }
  1664. if (session->extensions) {
  1665. g_free(session->extensions);
  1666. }
  1667. if (session->key) {
  1668. REF_RELEASE(session->key);
  1669. }
  1670. g_free(session);
  1671. }
  1672. #define FUZZY_INPUT_BUFLEN 1024
  1673. #ifdef HAVE_RECVMMSG
  1674. #define MSGVEC_LEN 16
  1675. #else
  1676. #define MSGVEC_LEN 1
  1677. #endif
  1678. union sa_union {
  1679. struct sockaddr sa;
  1680. struct sockaddr_in s4;
  1681. struct sockaddr_in6 s6;
  1682. struct sockaddr_un su;
  1683. struct sockaddr_storage ss;
  1684. };
  1685. /*
  1686. * Accept new connection and construct task
  1687. */
  1688. static void
  1689. accept_fuzzy_socket(EV_P_ ev_io *w, int revents)
  1690. {
  1691. struct rspamd_worker *worker = (struct rspamd_worker *) w->data;
  1692. struct rspamd_fuzzy_storage_ctx *ctx;
  1693. struct fuzzy_session *session;
  1694. gssize r, msg_len;
  1695. uint64_t *nerrors;
  1696. struct iovec iovs[MSGVEC_LEN];
  1697. guint8 bufs[MSGVEC_LEN][FUZZY_INPUT_BUFLEN];
  1698. union sa_union peer_sa[MSGVEC_LEN];
  1699. socklen_t salen = sizeof(peer_sa[0]);
  1700. #ifdef HAVE_RECVMMSG
  1701. #define MSG_FIELD(msg, field) msg.msg_hdr.field
  1702. struct mmsghdr msg[MSGVEC_LEN];
  1703. #else
  1704. #define MSG_FIELD(msg, field) msg.field
  1705. struct msghdr msg[MSGVEC_LEN];
  1706. #endif
  1707. memset(msg, 0, sizeof(*msg) * MSGVEC_LEN);
  1708. ctx = (struct rspamd_fuzzy_storage_ctx *) worker->ctx;
  1709. /* Prepare messages to receive */
  1710. for (int i = 0; i < MSGVEC_LEN; i++) {
  1711. /* Prepare msghdr structs */
  1712. iovs[i].iov_base = bufs[i];
  1713. iovs[i].iov_len = sizeof(bufs[i]);
  1714. MSG_FIELD(msg[i], msg_name) = (void *) &peer_sa[i];
  1715. MSG_FIELD(msg[i], msg_namelen) = salen;
  1716. MSG_FIELD(msg[i], msg_iov) = &iovs[i];
  1717. MSG_FIELD(msg[i], msg_iovlen) = 1;
  1718. }
  1719. /* Got some data */
  1720. if (revents == EV_READ) {
  1721. ev_now_update_if_cheap(ctx->event_loop);
  1722. for (;;) {
  1723. #ifdef HAVE_RECVMMSG
  1724. r = recvmmsg(w->fd, msg, MSGVEC_LEN, 0, NULL);
  1725. #else
  1726. r = recvmsg(w->fd, msg, 0);
  1727. #endif
  1728. if (r == -1) {
  1729. if (errno == EINTR) {
  1730. continue;
  1731. }
  1732. else if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1733. return;
  1734. }
  1735. msg_err("got error while reading from socket: %d, %s",
  1736. errno,
  1737. strerror(errno));
  1738. return;
  1739. }
  1740. #ifndef HAVE_RECVMMSG
  1741. msg_len = r; /* Save real length in bytes here */
  1742. r = 1; /* Assume that we have received a single message */
  1743. #endif
  1744. for (int i = 0; i < r; i++) {
  1745. rspamd_inet_addr_t *client_addr;
  1746. if (MSG_FIELD(msg[i], msg_namelen) >= sizeof(struct sockaddr)) {
  1747. client_addr = rspamd_inet_address_from_sa(MSG_FIELD(msg[i], msg_name),
  1748. MSG_FIELD(msg[i], msg_namelen));
  1749. if (!rspamd_fuzzy_check_client(worker->ctx, client_addr)) {
  1750. /* Disallow forbidden clients silently */
  1751. rspamd_inet_address_free(client_addr);
  1752. continue;
  1753. }
  1754. }
  1755. else {
  1756. client_addr = NULL;
  1757. }
  1758. session = g_malloc0(sizeof(*session));
  1759. REF_INIT_RETAIN(session, fuzzy_session_destroy);
  1760. session->worker = worker;
  1761. session->fd = w->fd;
  1762. session->ctx = ctx;
  1763. session->timestamp = ev_now(ctx->event_loop);
  1764. session->addr = client_addr;
  1765. worker->nconns++;
  1766. /* Each message can have its length in case of recvmmsg */
  1767. #ifdef HAVE_RECVMMSG
  1768. msg_len = msg[i].msg_len;
  1769. #endif
  1770. if (rspamd_fuzzy_cmd_from_wire(iovs[i].iov_base,
  1771. msg_len, session)) {
  1772. /* Check shingles count sanity */
  1773. rspamd_fuzzy_process_command(session);
  1774. }
  1775. else {
  1776. /* Discard input */
  1777. session->ctx->stat.invalid_requests++;
  1778. msg_debug("invalid fuzzy command of size %z received", r);
  1779. if (session->addr) {
  1780. nerrors = rspamd_lru_hash_lookup(session->ctx->errors_ips,
  1781. session->addr, -1);
  1782. if (nerrors == NULL) {
  1783. nerrors = g_malloc(sizeof(*nerrors));
  1784. *nerrors = 1;
  1785. rspamd_lru_hash_insert(session->ctx->errors_ips,
  1786. rspamd_inet_address_copy(session->addr, NULL),
  1787. nerrors, -1, -1);
  1788. }
  1789. else {
  1790. *nerrors = *nerrors + 1;
  1791. }
  1792. }
  1793. }
  1794. REF_RELEASE(session);
  1795. }
  1796. #ifdef HAVE_RECVMMSG
  1797. /* Stop reading as we are using recvmmsg instead of recvmsg */
  1798. break;
  1799. #endif
  1800. }
  1801. }
  1802. }
  1803. static gboolean
  1804. rspamd_fuzzy_storage_periodic_callback(void *ud)
  1805. {
  1806. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1807. if (ctx->updates_pending->len > 0) {
  1808. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1809. return TRUE;
  1810. }
  1811. return FALSE;
  1812. }
  1813. static gboolean
  1814. rspamd_fuzzy_storage_sync(struct rspamd_main *rspamd_main,
  1815. struct rspamd_worker *worker, gint fd,
  1816. gint attached_fd,
  1817. struct rspamd_control_command *cmd,
  1818. gpointer ud)
  1819. {
  1820. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1821. struct rspamd_control_reply rep;
  1822. rep.reply.fuzzy_sync.status = 0;
  1823. rep.type = RSPAMD_CONTROL_FUZZY_SYNC;
  1824. if (ctx->backend && worker->index == 0) {
  1825. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1826. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1827. rspamd_fuzzy_storage_periodic_callback, ctx);
  1828. }
  1829. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1830. msg_err("cannot write reply to the control socket: %s",
  1831. strerror(errno));
  1832. }
  1833. return TRUE;
  1834. }
  1835. static gboolean
  1836. rspamd_fuzzy_control_blocked(struct rspamd_main *rspamd_main,
  1837. struct rspamd_worker *worker, gint fd,
  1838. gint attached_fd,
  1839. struct rspamd_control_command *cmd,
  1840. gpointer ud)
  1841. {
  1842. struct rspamd_fuzzy_storage_ctx *ctx = (struct rspamd_fuzzy_storage_ctx *) ud;
  1843. struct rspamd_control_reply rep;
  1844. struct rspamd_leaky_bucket_elt *elt;
  1845. ev_tstamp now = ev_now(ctx->event_loop);
  1846. rspamd_inet_addr_t *addr = NULL;
  1847. rep.type = RSPAMD_CONTROL_FUZZY_BLOCKED;
  1848. rep.reply.fuzzy_blocked.status = 0;
  1849. if (cmd->cmd.fuzzy_blocked.af == AF_INET) {
  1850. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1851. sizeof(struct sockaddr_in));
  1852. }
  1853. else if (cmd->cmd.fuzzy_blocked.af == AF_INET6) {
  1854. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1855. sizeof(struct sockaddr_in6));
  1856. }
  1857. else {
  1858. msg_err("invalid address family: %d", cmd->cmd.fuzzy_blocked.af);
  1859. rep.reply.fuzzy_blocked.status = -1;
  1860. }
  1861. if (addr) {
  1862. elt = rspamd_lru_hash_lookup(ctx->ratelimit_buckets, addr,
  1863. (time_t) now);
  1864. if (elt) {
  1865. if (isnan(elt->cur)) {
  1866. /* Already ratelimited, ignore */
  1867. }
  1868. else {
  1869. elt->last = now;
  1870. elt->cur = NAN;
  1871. msg_info("propagating ratelimiting %s, %.1f max elts",
  1872. rspamd_inet_address_to_string(addr),
  1873. ctx->leaky_bucket_burst);
  1874. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1875. }
  1876. rspamd_inet_address_free(addr);
  1877. }
  1878. else {
  1879. /* New bucket */
  1880. elt = g_malloc(sizeof(*elt));
  1881. elt->addr = addr; /* transfer ownership */
  1882. elt->cur = NAN;
  1883. elt->last = now;
  1884. rspamd_lru_hash_insert(ctx->ratelimit_buckets,
  1885. addr,
  1886. elt,
  1887. (time_t) now,
  1888. ctx->leaky_bucket_ttl);
  1889. msg_info("propagating ratelimiting %s, %.1f max elts",
  1890. rspamd_inet_address_to_string(addr),
  1891. ctx->leaky_bucket_burst);
  1892. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1893. }
  1894. }
  1895. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1896. msg_err("cannot write reply to the control socket: %s",
  1897. strerror(errno));
  1898. }
  1899. return TRUE;
  1900. }
  1901. static gboolean
  1902. rspamd_fuzzy_storage_reload(struct rspamd_main *rspamd_main,
  1903. struct rspamd_worker *worker, gint fd,
  1904. gint attached_fd,
  1905. struct rspamd_control_command *cmd,
  1906. gpointer ud)
  1907. {
  1908. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1909. GError *err = NULL;
  1910. struct rspamd_control_reply rep;
  1911. msg_info("reloading fuzzy storage after receiving reload command");
  1912. if (ctx->backend) {
  1913. /* Close backend and reopen it one more time */
  1914. rspamd_fuzzy_backend_close(ctx->backend);
  1915. }
  1916. memset(&rep, 0, sizeof(rep));
  1917. rep.type = RSPAMD_CONTROL_RELOAD;
  1918. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  1919. worker->cf->options, rspamd_main->cfg,
  1920. &err)) == NULL) {
  1921. msg_err("cannot open backend after reload: %e", err);
  1922. rep.reply.reload.status = err->code;
  1923. g_error_free(err);
  1924. }
  1925. else {
  1926. rep.reply.reload.status = 0;
  1927. }
  1928. if (ctx->backend && worker->index == 0) {
  1929. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1930. rspamd_fuzzy_storage_periodic_callback, ctx);
  1931. }
  1932. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1933. msg_err("cannot write reply to the control socket: %s",
  1934. strerror(errno));
  1935. }
  1936. return TRUE;
  1937. }
  1938. static ucl_object_t *
  1939. rspamd_fuzzy_storage_stat_key(const struct fuzzy_key_stat *key_stat)
  1940. {
  1941. ucl_object_t *res;
  1942. res = ucl_object_typed_new(UCL_OBJECT);
  1943. ucl_object_insert_key(res, ucl_object_fromint(key_stat->checked),
  1944. "checked", 0, false);
  1945. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->checked_ctr.mean),
  1946. "checked_per_hour", 0, false);
  1947. ucl_object_insert_key(res, ucl_object_fromint(key_stat->matched),
  1948. "matched", 0, false);
  1949. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->matched_ctr.mean),
  1950. "matched_per_hour", 0, false);
  1951. ucl_object_insert_key(res, ucl_object_fromint(key_stat->added),
  1952. "added", 0, false);
  1953. ucl_object_insert_key(res, ucl_object_fromint(key_stat->deleted),
  1954. "deleted", 0, false);
  1955. ucl_object_insert_key(res, ucl_object_fromint(key_stat->errors),
  1956. "errors", 0, false);
  1957. return res;
  1958. }
  1959. static void
  1960. rspamd_fuzzy_key_stat_iter(const unsigned char *pk_iter, struct fuzzy_key *fuzzy_key, ucl_object_t *keys_obj, gboolean ip_stat)
  1961. {
  1962. struct fuzzy_key_stat *key_stat = fuzzy_key->stat;
  1963. gchar keyname[17];
  1964. if (key_stat) {
  1965. rspamd_snprintf(keyname, sizeof(keyname), "%8bs", pk_iter);
  1966. ucl_object_t *elt = rspamd_fuzzy_storage_stat_key(key_stat);
  1967. if (key_stat->last_ips && ip_stat) {
  1968. int i = 0;
  1969. ucl_object_t *ip_elt = ucl_object_typed_new(UCL_OBJECT);
  1970. gpointer k, v;
  1971. while ((i = rspamd_lru_hash_foreach(key_stat->last_ips,
  1972. i, &k, &v)) != -1) {
  1973. ucl_object_t *ip_cur = rspamd_fuzzy_storage_stat_key(v);
  1974. ucl_object_insert_key(ip_elt, ip_cur,
  1975. rspamd_inet_address_to_string(k), 0, true);
  1976. }
  1977. ucl_object_insert_key(elt, ip_elt, "ips", 0, false);
  1978. }
  1979. int flag;
  1980. struct fuzzy_key_stat *flag_stat;
  1981. ucl_object_t *flags_ucl = ucl_object_typed_new(UCL_OBJECT);
  1982. kh_foreach_key_value_ptr(fuzzy_key->flags_stat, flag, flag_stat, {
  1983. char intbuf[16];
  1984. rspamd_snprintf(intbuf, sizeof(intbuf), "%d", flag);
  1985. ucl_object_insert_key(flags_ucl, rspamd_fuzzy_storage_stat_key(flag_stat),
  1986. intbuf, 0, true);
  1987. });
  1988. ucl_object_insert_key(elt, flags_ucl, "flags", 0, false);
  1989. ucl_object_insert_key(elt,
  1990. rspamd_keypair_to_ucl(fuzzy_key->key, RSPAMD_KEYPAIR_DUMP_NO_SECRET | RSPAMD_KEYPAIR_DUMP_FLATTENED),
  1991. "keypair", 0, false);
  1992. ucl_object_insert_key(keys_obj, elt, keyname, 0, true);
  1993. }
  1994. }
  1995. static ucl_object_t *
  1996. rspamd_fuzzy_stat_to_ucl(struct rspamd_fuzzy_storage_ctx *ctx, gboolean ip_stat)
  1997. {
  1998. struct fuzzy_key *fuzzy_key;
  1999. ucl_object_t *obj, *keys_obj, *elt, *ip_elt;
  2000. const unsigned char *pk_iter;
  2001. obj = ucl_object_typed_new(UCL_OBJECT);
  2002. keys_obj = ucl_object_typed_new(UCL_OBJECT);
  2003. kh_foreach(ctx->keys, pk_iter, fuzzy_key, {
  2004. rspamd_fuzzy_key_stat_iter(pk_iter, fuzzy_key, keys_obj, ip_stat);
  2005. });
  2006. ucl_object_insert_key(obj, keys_obj, "keys", 0, false);
  2007. /* Now generic stats */
  2008. ucl_object_insert_key(obj,
  2009. ucl_object_fromint(ctx->stat.fuzzy_hashes),
  2010. "fuzzy_stored",
  2011. 0,
  2012. false);
  2013. ucl_object_insert_key(obj,
  2014. ucl_object_fromint(ctx->stat.fuzzy_hashes_expired),
  2015. "fuzzy_expired",
  2016. 0,
  2017. false);
  2018. ucl_object_insert_key(obj,
  2019. ucl_object_fromint(ctx->stat.invalid_requests),
  2020. "invalid_requests",
  2021. 0,
  2022. false);
  2023. ucl_object_insert_key(obj,
  2024. ucl_object_fromint(ctx->stat.delayed_hashes),
  2025. "delayed_hashes",
  2026. 0,
  2027. false);
  2028. if (ctx->errors_ips && ip_stat) {
  2029. gpointer k, v;
  2030. int i = 0;
  2031. ip_elt = ucl_object_typed_new(UCL_OBJECT);
  2032. while ((i = rspamd_lru_hash_foreach(ctx->errors_ips, i, &k, &v)) != -1) {
  2033. ucl_object_insert_key(ip_elt,
  2034. ucl_object_fromint(*(uint64_t *) v),
  2035. rspamd_inet_address_to_string(k), 0, true);
  2036. }
  2037. ucl_object_insert_key(obj,
  2038. ip_elt,
  2039. "errors_ips",
  2040. 0,
  2041. false);
  2042. }
  2043. /* Checked by epoch */
  2044. elt = ucl_object_typed_new(UCL_ARRAY);
  2045. for (int i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  2046. ucl_array_append(elt,
  2047. ucl_object_fromint(ctx->stat.fuzzy_hashes_checked[i]));
  2048. }
  2049. ucl_object_insert_key(obj, elt, "fuzzy_checked", 0, false);
  2050. /* Shingles by epoch */
  2051. elt = ucl_object_typed_new(UCL_ARRAY);
  2052. for (int i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  2053. ucl_array_append(elt,
  2054. ucl_object_fromint(ctx->stat.fuzzy_shingles_checked[i]));
  2055. }
  2056. ucl_object_insert_key(obj, elt, "fuzzy_shingles", 0, false);
  2057. /* Matched by epoch */
  2058. elt = ucl_object_typed_new(UCL_ARRAY);
  2059. for (int i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  2060. ucl_array_append(elt,
  2061. ucl_object_fromint(ctx->stat.fuzzy_hashes_found[i]));
  2062. }
  2063. ucl_object_insert_key(obj, elt, "fuzzy_found", 0, false);
  2064. return obj;
  2065. }
  2066. static void
  2067. rspamd_fuzzy_maybe_load_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  2068. {
  2069. char path[PATH_MAX];
  2070. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  2071. RSPAMD_DBDIR);
  2072. if (access(path, R_OK) != -1) {
  2073. struct ucl_parser *parser = ucl_parser_new(UCL_PARSER_NO_IMPLICIT_ARRAYS | UCL_PARSER_DISABLE_MACRO);
  2074. if (ucl_parser_add_file(parser, path)) {
  2075. ucl_object_t *obj = ucl_parser_get_object(parser);
  2076. int loaded = 0;
  2077. if (ucl_object_type(obj) == UCL_ARRAY) {
  2078. ucl_object_iter_t it = NULL;
  2079. const ucl_object_t *cur;
  2080. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2081. const ucl_object_t *ip, *value, *last;
  2082. const gchar *ip_str;
  2083. double limit_val, last_val;
  2084. ip = ucl_object_find_key(cur, "ip");
  2085. value = ucl_object_find_key(cur, "value");
  2086. last = ucl_object_find_key(cur, "last");
  2087. if (ip == NULL || value == NULL || last == NULL) {
  2088. msg_err("invalid ratelimit object");
  2089. continue;
  2090. }
  2091. ip_str = ucl_object_tostring(ip);
  2092. limit_val = ucl_object_todouble(value);
  2093. last_val = ucl_object_todouble(last);
  2094. if (ip_str == NULL || isnan(last_val)) {
  2095. msg_err("invalid ratelimit object");
  2096. continue;
  2097. }
  2098. rspamd_inet_addr_t *addr;
  2099. if (rspamd_parse_inet_address(&addr, ip_str, strlen(ip_str),
  2100. RSPAMD_INET_ADDRESS_PARSE_NO_UNIX | RSPAMD_INET_ADDRESS_PARSE_NO_PORT)) {
  2101. struct rspamd_leaky_bucket_elt *elt = g_malloc(sizeof(*elt));
  2102. elt->cur = limit_val;
  2103. elt->last = last_val;
  2104. elt->addr = addr;
  2105. rspamd_lru_hash_insert(ctx->ratelimit_buckets, addr, elt, elt->last, ctx->leaky_bucket_ttl);
  2106. loaded++;
  2107. }
  2108. else {
  2109. msg_err("invalid ratelimit ip: %s", ip_str);
  2110. continue;
  2111. }
  2112. }
  2113. msg_info("loaded %d ratelimit objects", loaded);
  2114. }
  2115. ucl_object_unref(obj);
  2116. }
  2117. ucl_parser_free(parser);
  2118. }
  2119. }
  2120. static void
  2121. rspamd_fuzzy_maybe_save_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  2122. {
  2123. char path[PATH_MAX];
  2124. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl.new",
  2125. RSPAMD_DBDIR);
  2126. FILE *f = fopen(path, "w");
  2127. if (f != NULL) {
  2128. ucl_object_t *top = ucl_object_typed_new(UCL_ARRAY);
  2129. int it = 0;
  2130. gpointer k, v;
  2131. ucl_object_reserve(top, rspamd_lru_hash_size(ctx->ratelimit_buckets));
  2132. while ((it = rspamd_lru_hash_foreach(ctx->ratelimit_buckets, it, &k, &v)) != -1) {
  2133. ucl_object_t *cur = ucl_object_typed_new(UCL_OBJECT);
  2134. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *) v;
  2135. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->cur), "value", 0, false);
  2136. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->last), "last", 0, false);
  2137. ucl_object_insert_key(cur, ucl_object_fromstring(rspamd_inet_address_to_string(elt->addr)), "ip", 0, false);
  2138. ucl_array_append(top, cur);
  2139. }
  2140. if (ucl_object_emit_full(top, UCL_EMIT_JSON_COMPACT, ucl_object_emit_file_funcs(f), NULL)) {
  2141. char npath[PATH_MAX];
  2142. fflush(f);
  2143. rspamd_snprintf(npath, sizeof(npath), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  2144. RSPAMD_DBDIR);
  2145. if (rename(path, npath) == -1) {
  2146. msg_warn("cannot rename %s to %s: %s", path, npath, strerror(errno));
  2147. }
  2148. else {
  2149. msg_info("saved %d ratelimits in %s", rspamd_lru_hash_size(ctx->ratelimit_buckets), npath);
  2150. }
  2151. }
  2152. else {
  2153. msg_warn("cannot serialize ratelimit buckets to %s: %s", path, strerror(errno));
  2154. }
  2155. fclose(f);
  2156. ucl_object_unref(top);
  2157. }
  2158. else {
  2159. msg_warn("cannot save ratelimit buckets to %s: %s", path, strerror(errno));
  2160. }
  2161. }
  2162. static int
  2163. lua_fuzzy_add_pre_handler(lua_State *L)
  2164. {
  2165. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2166. rspamd_lua_check_udata(L, 1, rspamd_worker_classname);
  2167. struct rspamd_fuzzy_storage_ctx *ctx;
  2168. if (!pwrk) {
  2169. return luaL_error(L, "invalid arguments, worker + function are expected");
  2170. }
  2171. wrk = *pwrk;
  2172. if (wrk && lua_isfunction(L, 2)) {
  2173. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2174. if (ctx->lua_pre_handler_cbref != -1) {
  2175. /* Should not happen */
  2176. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2177. }
  2178. lua_pushvalue(L, 2);
  2179. ctx->lua_pre_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2180. }
  2181. else {
  2182. return luaL_error(L, "invalid arguments, worker + function are expected");
  2183. }
  2184. return 0;
  2185. }
  2186. static int
  2187. lua_fuzzy_add_post_handler(lua_State *L)
  2188. {
  2189. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2190. rspamd_lua_check_udata(L, 1, rspamd_worker_classname);
  2191. struct rspamd_fuzzy_storage_ctx *ctx;
  2192. if (!pwrk) {
  2193. return luaL_error(L, "invalid arguments, worker + function are expected");
  2194. }
  2195. wrk = *pwrk;
  2196. if (wrk && lua_isfunction(L, 2)) {
  2197. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2198. if (ctx->lua_post_handler_cbref != -1) {
  2199. /* Should not happen */
  2200. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2201. }
  2202. lua_pushvalue(L, 2);
  2203. ctx->lua_post_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2204. }
  2205. else {
  2206. return luaL_error(L, "invalid arguments, worker + function are expected");
  2207. }
  2208. return 0;
  2209. }
  2210. static int
  2211. lua_fuzzy_add_blacklist_handler(lua_State *L)
  2212. {
  2213. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2214. rspamd_lua_check_udata(L, 1, rspamd_worker_classname);
  2215. struct rspamd_fuzzy_storage_ctx *ctx;
  2216. if (!pwrk) {
  2217. return luaL_error(L, "invalid arguments, worker + function are expected");
  2218. }
  2219. wrk = *pwrk;
  2220. if (wrk && lua_isfunction(L, 2)) {
  2221. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2222. if (ctx->lua_blacklist_cbref != -1) {
  2223. /* Should not happen */
  2224. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2225. }
  2226. lua_pushvalue(L, 2);
  2227. ctx->lua_blacklist_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2228. }
  2229. else {
  2230. return luaL_error(L, "invalid arguments, worker + function are expected");
  2231. }
  2232. return 0;
  2233. }
  2234. static gboolean
  2235. rspamd_fuzzy_storage_stat(struct rspamd_main *rspamd_main,
  2236. struct rspamd_worker *worker, gint fd,
  2237. gint attached_fd,
  2238. struct rspamd_control_command *cmd,
  2239. gpointer ud)
  2240. {
  2241. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2242. struct rspamd_control_reply rep;
  2243. ucl_object_t *obj;
  2244. struct ucl_emitter_functions *emit_subr;
  2245. guchar fdspace[CMSG_SPACE(sizeof(int))];
  2246. struct iovec iov;
  2247. struct msghdr msg;
  2248. struct cmsghdr *cmsg;
  2249. gint outfd = -1;
  2250. gchar tmppath[PATH_MAX];
  2251. memset(&rep, 0, sizeof(rep));
  2252. rep.type = RSPAMD_CONTROL_FUZZY_STAT;
  2253. rspamd_snprintf(tmppath, sizeof(tmppath), "%s%c%s-XXXXXXXXXX",
  2254. rspamd_main->cfg->temp_dir, G_DIR_SEPARATOR, "fuzzy-stat");
  2255. if ((outfd = mkstemp(tmppath)) == -1) {
  2256. rep.reply.fuzzy_stat.status = errno;
  2257. msg_info_main("cannot make temporary stat file for fuzzy stat: %s",
  2258. strerror(errno));
  2259. }
  2260. else {
  2261. rep.reply.fuzzy_stat.status = 0;
  2262. memcpy(rep.reply.fuzzy_stat.storage_id,
  2263. rspamd_fuzzy_backend_id(ctx->backend),
  2264. sizeof(rep.reply.fuzzy_stat.storage_id));
  2265. obj = rspamd_fuzzy_stat_to_ucl(ctx, TRUE);
  2266. emit_subr = ucl_object_emit_fd_funcs(outfd);
  2267. ucl_object_emit_full(obj, UCL_EMIT_JSON_COMPACT, emit_subr, NULL);
  2268. ucl_object_emit_funcs_free(emit_subr);
  2269. ucl_object_unref(obj);
  2270. /* Rewind output file */
  2271. close(outfd);
  2272. outfd = open(tmppath, O_RDONLY);
  2273. unlink(tmppath);
  2274. }
  2275. /* Now we can send outfd and status message */
  2276. memset(&msg, 0, sizeof(msg));
  2277. /* Attach fd to the message */
  2278. if (outfd != -1) {
  2279. memset(fdspace, 0, sizeof(fdspace));
  2280. msg.msg_control = fdspace;
  2281. msg.msg_controllen = sizeof(fdspace);
  2282. cmsg = CMSG_FIRSTHDR(&msg);
  2283. if (cmsg) {
  2284. cmsg->cmsg_level = SOL_SOCKET;
  2285. cmsg->cmsg_type = SCM_RIGHTS;
  2286. cmsg->cmsg_len = CMSG_LEN(sizeof(int));
  2287. memcpy(CMSG_DATA(cmsg), &outfd, sizeof(int));
  2288. }
  2289. }
  2290. iov.iov_base = &rep;
  2291. iov.iov_len = sizeof(rep);
  2292. msg.msg_iov = &iov;
  2293. msg.msg_iovlen = 1;
  2294. if (sendmsg(fd, &msg, 0) == -1) {
  2295. msg_err_main("cannot send fuzzy stat: %s", strerror(errno));
  2296. }
  2297. if (outfd != -1) {
  2298. close(outfd);
  2299. }
  2300. return TRUE;
  2301. }
  2302. static gboolean
  2303. fuzzy_parse_ids(rspamd_mempool_t *pool,
  2304. const ucl_object_t *obj,
  2305. gpointer ud,
  2306. struct rspamd_rcl_section *section,
  2307. GError **err)
  2308. {
  2309. struct rspamd_rcl_struct_parser *pd = (struct rspamd_rcl_struct_parser *) ud;
  2310. khash_t(fuzzy_key_ids_set) * target;
  2311. target = *(khash_t(fuzzy_key_ids_set) **) ((gchar *) pd->user_struct + pd->offset);
  2312. if (ucl_object_type(obj) == UCL_ARRAY) {
  2313. const ucl_object_t *cur;
  2314. ucl_object_iter_t it = NULL;
  2315. uint64_t id;
  2316. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2317. if (ucl_object_toint_safe(cur, &id)) {
  2318. int r;
  2319. kh_put(fuzzy_key_ids_set, target, id, &r);
  2320. }
  2321. else {
  2322. return FALSE;
  2323. }
  2324. }
  2325. return TRUE;
  2326. }
  2327. else if (ucl_object_type(obj) == UCL_INT) {
  2328. int r;
  2329. kh_put(fuzzy_key_ids_set, target, ucl_object_toint(obj), &r);
  2330. return TRUE;
  2331. }
  2332. return FALSE;
  2333. }
  2334. static struct fuzzy_key *
  2335. fuzzy_add_keypair_from_ucl(const ucl_object_t *obj, khash_t(rspamd_fuzzy_keys_hash) * target)
  2336. {
  2337. struct rspamd_cryptobox_keypair *kp = rspamd_keypair_from_ucl(obj);
  2338. if (kp == NULL) {
  2339. return NULL;
  2340. }
  2341. if (rspamd_keypair_alg(kp) != RSPAMD_CRYPTOBOX_MODE_25519 ||
  2342. rspamd_keypair_type(kp) != RSPAMD_KEYPAIR_KEX) {
  2343. return FALSE;
  2344. }
  2345. struct fuzzy_key *key = g_malloc0(sizeof(*key));
  2346. REF_INIT_RETAIN(key, fuzzy_key_dtor);
  2347. key->key = kp;
  2348. struct fuzzy_key_stat *keystat = g_malloc0(sizeof(*keystat));
  2349. REF_INIT_RETAIN(keystat, fuzzy_key_stat_dtor);
  2350. /* Hash of ip -> fuzzy_key_stat */
  2351. keystat->last_ips = rspamd_lru_hash_new_full(1024,
  2352. (GDestroyNotify) rspamd_inet_address_free,
  2353. fuzzy_key_stat_unref,
  2354. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2355. key->stat = keystat;
  2356. key->flags_stat = kh_init(fuzzy_key_flag_stat);
  2357. /* Preallocate some space for flags */
  2358. kh_resize(fuzzy_key_flag_stat, key->flags_stat, 8);
  2359. const guchar *pk = rspamd_keypair_component(kp, RSPAMD_KEYPAIR_COMPONENT_PK,
  2360. NULL);
  2361. keystat->keypair = rspamd_keypair_ref(kp);
  2362. /* We map entries by pubkey in binary form for faster lookup */
  2363. khiter_t k;
  2364. int r;
  2365. k = kh_put(rspamd_fuzzy_keys_hash, target, pk, &r);
  2366. if (r == 0) {
  2367. msg_err("duplicate keypair found: pk=%*bs",
  2368. 32, pk);
  2369. REF_RELEASE(key);
  2370. return FALSE;
  2371. }
  2372. else if (r == -1) {
  2373. msg_err("hash insertion error: pk=%*bs",
  2374. 32, pk);
  2375. REF_RELEASE(key);
  2376. return FALSE;
  2377. }
  2378. kh_val(target, k) = key;
  2379. const ucl_object_t *extensions = rspamd_keypair_get_extensions(kp);
  2380. if (extensions) {
  2381. const ucl_object_t *forbidden_ids = ucl_object_lookup(extensions, "forbidden_ids");
  2382. if (forbidden_ids && ucl_object_type(forbidden_ids) == UCL_ARRAY) {
  2383. key->forbidden_ids = kh_init(fuzzy_key_ids_set);
  2384. const ucl_object_t *cur;
  2385. ucl_object_iter_t it = NULL;
  2386. while ((cur = ucl_object_iterate(forbidden_ids, &it, true)) != NULL) {
  2387. if (ucl_object_type(cur) == UCL_INT || ucl_object_type(cur) == UCL_FLOAT) {
  2388. int id = ucl_object_toint(cur);
  2389. int r;
  2390. kh_put(fuzzy_key_ids_set, key->forbidden_ids, id, &r);
  2391. }
  2392. }
  2393. }
  2394. }
  2395. msg_debug("loaded keypair %*bs", rspamd_cryptobox_pk_bytes(RSPAMD_CRYPTOBOX_MODE_25519), pk);
  2396. return key;
  2397. }
  2398. static gboolean
  2399. fuzzy_parse_keypair(rspamd_mempool_t *pool,
  2400. const ucl_object_t *obj,
  2401. gpointer ud,
  2402. struct rspamd_rcl_section *section,
  2403. GError **err)
  2404. {
  2405. struct rspamd_rcl_struct_parser *pd = ud;
  2406. struct rspamd_fuzzy_storage_ctx *ctx;
  2407. struct fuzzy_key *key;
  2408. const ucl_object_t *cur;
  2409. ucl_object_iter_t it = NULL;
  2410. gboolean ret;
  2411. ctx = pd->user_struct;
  2412. pd->offset = G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_keypair);
  2413. /*
  2414. * Single key
  2415. */
  2416. if (ucl_object_type(obj) == UCL_STRING || ucl_object_type(obj) == UCL_OBJECT) {
  2417. ret = rspamd_rcl_parse_struct_keypair(pool, obj, pd, section, err);
  2418. if (!ret) {
  2419. return ret;
  2420. }
  2421. key = fuzzy_add_keypair_from_ucl(obj, ctx->keys);
  2422. if (key == NULL) {
  2423. return FALSE;
  2424. }
  2425. /* Use the last one ? */
  2426. ctx->default_key = key;
  2427. }
  2428. else if (ucl_object_type(obj) == UCL_ARRAY) {
  2429. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2430. if (!fuzzy_parse_keypair(pool, cur, pd, section, err)) {
  2431. msg_err_pool("cannot parse keypair");
  2432. }
  2433. }
  2434. }
  2435. return TRUE;
  2436. }
  2437. gpointer
  2438. init_fuzzy(struct rspamd_config *cfg)
  2439. {
  2440. struct rspamd_fuzzy_storage_ctx *ctx;
  2441. GQuark type;
  2442. type = g_quark_try_string("fuzzy");
  2443. ctx = rspamd_mempool_alloc0(cfg->cfg_pool,
  2444. sizeof(struct rspamd_fuzzy_storage_ctx));
  2445. ctx->magic = rspamd_fuzzy_storage_magic;
  2446. ctx->sync_timeout = DEFAULT_SYNC_TIMEOUT;
  2447. ctx->keypair_cache_size = DEFAULT_KEYPAIR_CACHE_SIZE;
  2448. ctx->lua_pre_handler_cbref = -1;
  2449. ctx->lua_post_handler_cbref = -1;
  2450. ctx->lua_blacklist_cbref = -1;
  2451. ctx->keys = kh_init(rspamd_fuzzy_keys_hash);
  2452. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2453. (rspamd_mempool_destruct_t) fuzzy_hash_table_dtor, ctx->keys);
  2454. ctx->errors_ips = rspamd_lru_hash_new_full(1024,
  2455. (GDestroyNotify) rspamd_inet_address_free, g_free,
  2456. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2457. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2458. (rspamd_mempool_destruct_t) rspamd_lru_hash_destroy, ctx->errors_ips);
  2459. ctx->cfg = cfg;
  2460. ctx->updates_maxfail = DEFAULT_UPDATES_MAXFAIL;
  2461. ctx->leaky_bucket_mask = DEFAULT_BUCKET_MASK;
  2462. ctx->leaky_bucket_ttl = DEFAULT_BUCKET_TTL;
  2463. ctx->max_buckets = DEFAULT_MAX_BUCKETS;
  2464. ctx->leaky_bucket_burst = NAN;
  2465. ctx->leaky_bucket_rate = NAN;
  2466. ctx->delay = NAN;
  2467. ctx->default_forbidden_ids = kh_init(fuzzy_key_ids_set);
  2468. ctx->weak_ids = kh_init(fuzzy_key_ids_set);
  2469. rspamd_rcl_register_worker_option(cfg,
  2470. type,
  2471. "sync",
  2472. rspamd_rcl_parse_struct_time,
  2473. ctx,
  2474. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2475. sync_timeout),
  2476. RSPAMD_CL_FLAG_TIME_FLOAT,
  2477. "Time to perform database sync, default: " G_STRINGIFY(DEFAULT_SYNC_TIMEOUT) " seconds");
  2478. rspamd_rcl_register_worker_option(cfg,
  2479. type,
  2480. "expire",
  2481. rspamd_rcl_parse_struct_time,
  2482. ctx,
  2483. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2484. expire),
  2485. RSPAMD_CL_FLAG_TIME_FLOAT,
  2486. "Default expire time for hashes, default: " G_STRINGIFY(DEFAULT_EXPIRE) " seconds");
  2487. rspamd_rcl_register_worker_option(cfg,
  2488. type,
  2489. "delay",
  2490. rspamd_rcl_parse_struct_time,
  2491. ctx,
  2492. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2493. delay),
  2494. RSPAMD_CL_FLAG_TIME_FLOAT,
  2495. "Default delay time for hashes, default: not enabled");
  2496. rspamd_rcl_register_worker_option(cfg,
  2497. type,
  2498. "allow_update",
  2499. rspamd_rcl_parse_struct_ucl,
  2500. ctx,
  2501. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_map),
  2502. 0,
  2503. "Allow modifications from the following IP addresses");
  2504. rspamd_rcl_register_worker_option(cfg,
  2505. type,
  2506. "allow_update_keys",
  2507. rspamd_rcl_parse_struct_ucl,
  2508. ctx,
  2509. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_keys_map),
  2510. 0,
  2511. "Allow modifications for those using specific public keys");
  2512. rspamd_rcl_register_worker_option(cfg,
  2513. type,
  2514. "delay_whitelist",
  2515. rspamd_rcl_parse_struct_ucl,
  2516. ctx,
  2517. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, delay_whitelist_map),
  2518. 0,
  2519. "Disable delay check for the following IP addresses");
  2520. rspamd_rcl_register_worker_option(cfg,
  2521. type,
  2522. "keypair",
  2523. fuzzy_parse_keypair,
  2524. ctx,
  2525. 0,
  2526. RSPAMD_CL_FLAG_MULTIPLE,
  2527. "Encryption keypair (can be repeated for different keys)");
  2528. rspamd_rcl_register_worker_option(cfg,
  2529. type,
  2530. "dynamic_keys_map",
  2531. rspamd_rcl_parse_struct_ucl,
  2532. ctx,
  2533. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, dynamic_keys_map),
  2534. 0,
  2535. "Dynamic encryption keypairs (can be repeated for different keys)");
  2536. rspamd_rcl_register_worker_option(cfg,
  2537. type,
  2538. "forbidden_ids",
  2539. fuzzy_parse_ids,
  2540. ctx,
  2541. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_forbidden_ids),
  2542. 0,
  2543. "Deny specific flags by default");
  2544. rspamd_rcl_register_worker_option(cfg,
  2545. type,
  2546. "weak_ids",
  2547. fuzzy_parse_ids,
  2548. ctx,
  2549. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, weak_ids),
  2550. 0,
  2551. "Treat these flags as weak (i.e. they do not overwrite strong flags)");
  2552. rspamd_rcl_register_worker_option(cfg,
  2553. type,
  2554. "keypair_cache_size",
  2555. rspamd_rcl_parse_struct_integer,
  2556. ctx,
  2557. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2558. keypair_cache_size),
  2559. RSPAMD_CL_FLAG_UINT,
  2560. "Size of keypairs cache, default: " G_STRINGIFY(DEFAULT_KEYPAIR_CACHE_SIZE));
  2561. rspamd_rcl_register_worker_option(cfg,
  2562. type,
  2563. "encrypted_only",
  2564. rspamd_rcl_parse_struct_boolean,
  2565. ctx,
  2566. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, encrypted_only),
  2567. 0,
  2568. "Allow encrypted requests only (and forbid all unknown keys or plaintext requests)");
  2569. rspamd_rcl_register_worker_option(cfg,
  2570. type,
  2571. "dedicated_update_worker",
  2572. rspamd_rcl_parse_struct_boolean,
  2573. ctx,
  2574. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, dedicated_update_worker),
  2575. 0,
  2576. "Use worker 0 for updates only");
  2577. rspamd_rcl_register_worker_option(cfg,
  2578. type,
  2579. "read_only",
  2580. rspamd_rcl_parse_struct_boolean,
  2581. ctx,
  2582. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, read_only),
  2583. 0,
  2584. "Work in read only mode");
  2585. rspamd_rcl_register_worker_option(cfg,
  2586. type,
  2587. "blocked",
  2588. rspamd_rcl_parse_struct_ucl,
  2589. ctx,
  2590. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, blocked_map),
  2591. 0,
  2592. "Block requests from specific networks");
  2593. rspamd_rcl_register_worker_option(cfg,
  2594. type,
  2595. "updates_maxfail",
  2596. rspamd_rcl_parse_struct_integer,
  2597. ctx,
  2598. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, updates_maxfail),
  2599. RSPAMD_CL_FLAG_UINT,
  2600. "Maximum number of updates to be failed before discarding");
  2601. rspamd_rcl_register_worker_option(cfg,
  2602. type,
  2603. "skip_hashes",
  2604. rspamd_rcl_parse_struct_ucl,
  2605. ctx,
  2606. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, skip_map),
  2607. 0,
  2608. "Skip specific hashes from the map");
  2609. /* Ratelimits */
  2610. rspamd_rcl_register_worker_option(cfg,
  2611. type,
  2612. "ratelimit_whitelist",
  2613. rspamd_rcl_parse_struct_ucl,
  2614. ctx,
  2615. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_whitelist_map),
  2616. 0,
  2617. "Skip specific addresses from rate limiting");
  2618. rspamd_rcl_register_worker_option(cfg,
  2619. type,
  2620. "ratelimit_max_buckets",
  2621. rspamd_rcl_parse_struct_integer,
  2622. ctx,
  2623. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, max_buckets),
  2624. RSPAMD_CL_FLAG_UINT,
  2625. "Maximum number of leaky buckets (default: " G_STRINGIFY(DEFAULT_MAX_BUCKETS) ")");
  2626. rspamd_rcl_register_worker_option(cfg,
  2627. type,
  2628. "ratelimit_network_mask",
  2629. rspamd_rcl_parse_struct_integer,
  2630. ctx,
  2631. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_mask),
  2632. RSPAMD_CL_FLAG_UINT,
  2633. "Network mask to apply for IPv4 rate addresses (default: " G_STRINGIFY(DEFAULT_BUCKET_MASK) ")");
  2634. rspamd_rcl_register_worker_option(cfg,
  2635. type,
  2636. "ratelimit_bucket_ttl",
  2637. rspamd_rcl_parse_struct_time,
  2638. ctx,
  2639. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_ttl),
  2640. RSPAMD_CL_FLAG_TIME_INTEGER,
  2641. "Time to live for ratelimit element (default: " G_STRINGIFY(DEFAULT_BUCKET_TTL) ")");
  2642. rspamd_rcl_register_worker_option(cfg,
  2643. type,
  2644. "ratelimit_rate",
  2645. rspamd_rcl_parse_struct_double,
  2646. ctx,
  2647. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_rate),
  2648. 0,
  2649. "Leak rate in requests per second");
  2650. rspamd_rcl_register_worker_option(cfg,
  2651. type,
  2652. "ratelimit_burst",
  2653. rspamd_rcl_parse_struct_double,
  2654. ctx,
  2655. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_burst),
  2656. 0,
  2657. "Peak value for ratelimit bucket");
  2658. rspamd_rcl_register_worker_option(cfg,
  2659. type,
  2660. "ratelimit_log_only",
  2661. rspamd_rcl_parse_struct_boolean,
  2662. ctx,
  2663. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_log_only),
  2664. 0,
  2665. "Don't really ban on ratelimit reaching, just log");
  2666. return ctx;
  2667. }
  2668. static void
  2669. rspamd_fuzzy_peer_io(EV_P_ ev_io *w, int revents)
  2670. {
  2671. struct fuzzy_peer_cmd cmd;
  2672. struct rspamd_fuzzy_storage_ctx *ctx =
  2673. (struct rspamd_fuzzy_storage_ctx *) w->data;
  2674. gssize r;
  2675. for (;;) {
  2676. r = read(w->fd, &cmd, sizeof(cmd));
  2677. if (r != sizeof(cmd)) {
  2678. if (errno == EINTR) {
  2679. continue;
  2680. }
  2681. if (errno != EAGAIN) {
  2682. msg_err("cannot read command from peers: %s", strerror(errno));
  2683. }
  2684. break;
  2685. }
  2686. else {
  2687. g_array_append_val(ctx->updates_pending, cmd);
  2688. }
  2689. }
  2690. }
  2691. static void
  2692. fuzzy_peer_rep(struct rspamd_worker *worker,
  2693. struct rspamd_srv_reply *rep, gint rep_fd,
  2694. gpointer ud)
  2695. {
  2696. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2697. GList *cur;
  2698. struct rspamd_worker_listen_socket *ls;
  2699. struct rspamd_worker_accept_event *ac_ev;
  2700. ctx->peer_fd = rep_fd;
  2701. if (rep_fd == -1) {
  2702. msg_err("cannot receive peer fd from the main process");
  2703. exit(EXIT_FAILURE);
  2704. }
  2705. else {
  2706. rspamd_socket_nonblocking(rep_fd);
  2707. }
  2708. msg_info("got peer fd reply from the main process");
  2709. /* Start listening */
  2710. cur = worker->cf->listen_socks;
  2711. while (cur) {
  2712. ls = cur->data;
  2713. if (ls->fd != -1) {
  2714. msg_info("start listening on %s",
  2715. rspamd_inet_address_to_string_pretty(ls->addr));
  2716. if (ls->type == RSPAMD_WORKER_SOCKET_UDP) {
  2717. ac_ev = g_malloc0(sizeof(*ac_ev));
  2718. ac_ev->accept_ev.data = worker;
  2719. ac_ev->event_loop = ctx->event_loop;
  2720. ev_io_init(&ac_ev->accept_ev, accept_fuzzy_socket, ls->fd,
  2721. EV_READ);
  2722. ev_io_start(ctx->event_loop, &ac_ev->accept_ev);
  2723. DL_APPEND(worker->accept_events, ac_ev);
  2724. }
  2725. else {
  2726. /* We allow TCP listeners only for a update worker */
  2727. g_assert_not_reached();
  2728. }
  2729. }
  2730. cur = g_list_next(cur);
  2731. }
  2732. if (ctx->peer_fd != -1) {
  2733. if (worker->index == 0) {
  2734. /* Listen for peer requests */
  2735. shutdown(ctx->peer_fd, SHUT_WR);
  2736. ctx->peer_ev.data = ctx;
  2737. ev_io_init(&ctx->peer_ev, rspamd_fuzzy_peer_io, ctx->peer_fd, EV_READ);
  2738. ev_io_start(ctx->event_loop, &ctx->peer_ev);
  2739. }
  2740. else {
  2741. shutdown(ctx->peer_fd, SHUT_RD);
  2742. }
  2743. }
  2744. }
  2745. /*
  2746. * Start worker process
  2747. */
  2748. __attribute__((noreturn)) void
  2749. start_fuzzy(struct rspamd_worker *worker)
  2750. {
  2751. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  2752. GError *err = NULL;
  2753. struct rspamd_srv_command srv_cmd;
  2754. struct rspamd_config *cfg = worker->srv->cfg;
  2755. g_assert(rspamd_worker_check_context(worker->ctx, rspamd_fuzzy_storage_magic));
  2756. ctx->event_loop = rspamd_prepare_worker(worker,
  2757. "fuzzy",
  2758. NULL);
  2759. ctx->peer_fd = -1;
  2760. ctx->worker = worker;
  2761. ctx->cfg = worker->srv->cfg;
  2762. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2763. ctx->event_loop,
  2764. worker->srv->cfg);
  2765. rspamd_upstreams_library_config(worker->srv->cfg, ctx->cfg->ups_ctx,
  2766. ctx->event_loop, ctx->resolver->r);
  2767. /* Since this worker uses maps it needs a valid HTTP context */
  2768. ctx->http_ctx = rspamd_http_context_create(ctx->cfg, ctx->event_loop,
  2769. ctx->cfg->ups_ctx);
  2770. if (ctx->keypair_cache_size > 0) {
  2771. /* Create keypairs cache */
  2772. ctx->keypair_cache = rspamd_keypair_cache_new(ctx->keypair_cache_size);
  2773. }
  2774. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  2775. worker->cf->options, cfg, &err)) == NULL) {
  2776. msg_err("cannot open backend: %e", err);
  2777. if (err) {
  2778. g_error_free(err);
  2779. }
  2780. exit(EXIT_SUCCESS);
  2781. }
  2782. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  2783. if (worker->index == 0) {
  2784. ctx->updates_pending = g_array_sized_new(FALSE, FALSE,
  2785. sizeof(struct fuzzy_peer_cmd), 1024);
  2786. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  2787. rspamd_fuzzy_storage_periodic_callback, ctx);
  2788. if (ctx->dedicated_update_worker && worker->cf->count > 1) {
  2789. msg_info_config("stop serving clients request in dedicated update mode");
  2790. rspamd_worker_stop_accept(worker);
  2791. GList *cur = worker->cf->listen_socks;
  2792. while (cur) {
  2793. struct rspamd_worker_listen_socket *ls =
  2794. (struct rspamd_worker_listen_socket *) cur->data;
  2795. if (ls->fd != -1) {
  2796. close(ls->fd);
  2797. }
  2798. cur = g_list_next(cur);
  2799. }
  2800. }
  2801. }
  2802. ctx->stat_ev.data = ctx;
  2803. ev_timer_init(&ctx->stat_ev, rspamd_fuzzy_stat_callback, ctx->sync_timeout,
  2804. ctx->sync_timeout);
  2805. ev_timer_start(ctx->event_loop, &ctx->stat_ev);
  2806. /* Register custom reload and stat commands for the control socket */
  2807. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_RELOAD,
  2808. rspamd_fuzzy_storage_reload, ctx);
  2809. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_STAT,
  2810. rspamd_fuzzy_storage_stat, ctx);
  2811. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_SYNC,
  2812. rspamd_fuzzy_storage_sync, ctx);
  2813. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_BLOCKED,
  2814. rspamd_fuzzy_control_blocked, ctx);
  2815. if (ctx->update_map != NULL) {
  2816. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->update_map,
  2817. "Allow fuzzy updates from specified addresses",
  2818. &ctx->update_ips, NULL, worker, "fuzzy update");
  2819. }
  2820. if (ctx->update_keys_map != NULL) {
  2821. struct rspamd_map *m;
  2822. if ((m = rspamd_map_add_from_ucl(worker->srv->cfg, ctx->update_keys_map,
  2823. "Allow fuzzy updates from specified public keys",
  2824. rspamd_kv_list_read,
  2825. rspamd_kv_list_fin,
  2826. rspamd_kv_list_dtor,
  2827. (void **) &ctx->update_keys, worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2828. msg_warn_config("cannot load allow keys map from %s",
  2829. ucl_object_tostring(ctx->update_keys_map));
  2830. }
  2831. else {
  2832. m->active_http = TRUE;
  2833. }
  2834. }
  2835. if (ctx->skip_map != NULL) {
  2836. struct rspamd_map *m;
  2837. if ((m = rspamd_map_add_from_ucl(cfg, ctx->skip_map,
  2838. "Skip hashes",
  2839. rspamd_kv_list_read,
  2840. rspamd_kv_list_fin,
  2841. rspamd_kv_list_dtor,
  2842. (void **) &ctx->skip_hashes,
  2843. worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2844. msg_warn_config("cannot load hashes list from %s",
  2845. ucl_object_tostring(ctx->skip_map));
  2846. }
  2847. else {
  2848. m->active_http = TRUE;
  2849. }
  2850. }
  2851. if (ctx->blocked_map != NULL) {
  2852. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->blocked_map,
  2853. "Block fuzzy requests from the specific IPs",
  2854. &ctx->blocked_ips,
  2855. NULL,
  2856. worker, "fuzzy blocked");
  2857. }
  2858. /* Create radix trees */
  2859. if (ctx->ratelimit_whitelist_map != NULL) {
  2860. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->ratelimit_whitelist_map,
  2861. "Skip ratelimits from specific ip addresses/networks",
  2862. &ctx->ratelimit_whitelist,
  2863. NULL,
  2864. worker, "fuzzy ratelimit whitelist");
  2865. }
  2866. if (ctx->dynamic_keys_map) {
  2867. struct fuzzy_keymap_ucl_buf *jb, **pjb;
  2868. ctx->dynamic_keys = kh_init(rspamd_fuzzy_keys_hash);
  2869. /* Now try to add map with ucl data */
  2870. jb = g_malloc(sizeof(struct fuzzy_keymap_ucl_buf));
  2871. pjb = g_malloc(sizeof(struct fuzzy_keymap_ucl_buf *));
  2872. jb->buf = NULL;
  2873. jb->ctx = ctx;
  2874. *pjb = jb;
  2875. rspamd_mempool_add_destructor(ctx->cfg->cfg_pool,
  2876. (rspamd_mempool_destruct_t) g_free,
  2877. pjb);
  2878. if (!rspamd_map_add_from_ucl(cfg,
  2879. ctx->dynamic_keys_map,
  2880. "Dynamic fuzzy keys map",
  2881. ucl_keymap_read_cb,
  2882. ucl_keymap_fin_cb,
  2883. ucl_keymap_dtor_cb,
  2884. (void **) pjb, worker, RSPAMD_MAP_DEFAULT)) {
  2885. msg_err("cannot add map for dynamic keys");
  2886. }
  2887. }
  2888. if (!isnan(ctx->delay) && ctx->delay_whitelist_map != NULL) {
  2889. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->delay_whitelist_map,
  2890. "Skip delay from the following ips",
  2891. &ctx->delay_whitelist, NULL, worker,
  2892. "fuzzy delayed whitelist");
  2893. }
  2894. /* Ratelimits */
  2895. if (!isnan(ctx->leaky_bucket_rate) && !isnan(ctx->leaky_bucket_burst)) {
  2896. ctx->ratelimit_buckets = rspamd_lru_hash_new_full(ctx->max_buckets,
  2897. NULL, fuzzy_rl_bucket_free,
  2898. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2899. rspamd_fuzzy_maybe_load_ratelimits(ctx);
  2900. }
  2901. /* Maps events */
  2902. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2903. ctx->event_loop,
  2904. worker->srv->cfg);
  2905. rspamd_map_watch(worker->srv->cfg, ctx->event_loop,
  2906. ctx->resolver, worker, RSPAMD_MAP_WATCH_WORKER);
  2907. /* Get peer pipe */
  2908. memset(&srv_cmd, 0, sizeof(srv_cmd));
  2909. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  2910. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  2911. srv_cmd.cmd.spair.pair_num = worker->index;
  2912. memset(srv_cmd.cmd.spair.pair_id, 0, sizeof(srv_cmd.cmd.spair.pair_id));
  2913. /* 6 bytes of id (including \0) and bind_conf id */
  2914. G_STATIC_ASSERT(sizeof(srv_cmd.cmd.spair.pair_id) >=
  2915. sizeof("fuzzy") + sizeof(uint64_t));
  2916. memcpy(srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof("fuzzy"));
  2917. /* Distinguish workers from each others... */
  2918. if (worker->cf->bind_conf && worker->cf->bind_conf->bind_line) {
  2919. uint64_t bind_hash = rspamd_cryptobox_fast_hash(worker->cf->bind_conf->bind_line,
  2920. strlen(worker->cf->bind_conf->bind_line), 0xdeadbabe);
  2921. /* 8 more bytes */
  2922. memcpy(srv_cmd.cmd.spair.pair_id + sizeof("fuzzy"), &bind_hash,
  2923. sizeof(bind_hash));
  2924. }
  2925. rspamd_srv_send_command(worker, ctx->event_loop, &srv_cmd, -1,
  2926. fuzzy_peer_rep, ctx);
  2927. /*
  2928. * Extra fields available for this particular worker
  2929. */
  2930. luaL_Reg fuzzy_lua_reg = {
  2931. .name = "add_fuzzy_pre_handler",
  2932. .func = lua_fuzzy_add_pre_handler,
  2933. };
  2934. rspamd_lua_add_metamethod(ctx->cfg->lua_state, rspamd_worker_classname, &fuzzy_lua_reg);
  2935. fuzzy_lua_reg = (luaL_Reg){
  2936. .name = "add_fuzzy_post_handler",
  2937. .func = lua_fuzzy_add_post_handler,
  2938. };
  2939. rspamd_lua_add_metamethod(ctx->cfg->lua_state, rspamd_worker_classname, &fuzzy_lua_reg);
  2940. fuzzy_lua_reg = (luaL_Reg){
  2941. .name = "add_fuzzy_blacklist_handler",
  2942. .func = lua_fuzzy_add_blacklist_handler,
  2943. };
  2944. rspamd_lua_add_metamethod(ctx->cfg->lua_state, rspamd_worker_classname, &fuzzy_lua_reg);
  2945. rspamd_lua_run_postloads(ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  2946. worker);
  2947. ev_loop(ctx->event_loop, 0);
  2948. rspamd_worker_block_signals();
  2949. if (ctx->peer_fd != -1) {
  2950. if (worker->index == 0) {
  2951. ev_io_stop(ctx->event_loop, &ctx->peer_ev);
  2952. }
  2953. close(ctx->peer_fd);
  2954. }
  2955. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  2956. msg_info_config("start another event loop to sync fuzzy storage");
  2957. if (rspamd_fuzzy_process_updates_queue(ctx, local_db_name, TRUE)) {
  2958. ev_loop(ctx->event_loop, 0);
  2959. msg_info_config("sync cycle is done");
  2960. }
  2961. else {
  2962. msg_info_config("no need to sync");
  2963. }
  2964. }
  2965. rspamd_fuzzy_backend_close(ctx->backend);
  2966. if (worker->index == 0) {
  2967. g_array_free(ctx->updates_pending, TRUE);
  2968. ctx->updates_pending = NULL;
  2969. }
  2970. if (ctx->keypair_cache) {
  2971. rspamd_keypair_cache_destroy(ctx->keypair_cache);
  2972. }
  2973. if (ctx->ratelimit_buckets) {
  2974. /* Try the best to save ratelimits from the proper worker */
  2975. if ((!ctx->dedicated_update_worker && worker->index == 0) ||
  2976. (ctx->dedicated_update_worker && worker->index == 1)) {
  2977. rspamd_fuzzy_maybe_save_ratelimits(ctx);
  2978. }
  2979. rspamd_lru_hash_destroy(ctx->ratelimit_buckets);
  2980. }
  2981. if (ctx->lua_pre_handler_cbref != -1) {
  2982. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2983. }
  2984. if (ctx->lua_post_handler_cbref != -1) {
  2985. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2986. }
  2987. if (ctx->lua_blacklist_cbref != -1) {
  2988. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2989. }
  2990. if (ctx->default_forbidden_ids) {
  2991. kh_destroy(fuzzy_key_ids_set, ctx->default_forbidden_ids);
  2992. }
  2993. if (ctx->weak_ids) {
  2994. kh_destroy(fuzzy_key_ids_set, ctx->weak_ids);
  2995. }
  2996. REF_RELEASE(ctx->cfg);
  2997. rspamd_log_close(worker->srv->logger);
  2998. rspamd_unset_crash_handler(worker->srv);
  2999. exit(EXIT_SUCCESS);
  3000. }