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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  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,
  59. RSPAMD_WORKER_SOCKET_UDP, /* UDP socket */
  60. RSPAMD_WORKER_VER /* Version info */
  61. };
  62. struct fuzzy_global_stat {
  63. guint64 fuzzy_hashes;
  64. /**< number of fuzzy hashes stored */
  65. guint64 fuzzy_hashes_expired;
  66. /**< number of fuzzy hashes expired */
  67. guint64 fuzzy_hashes_checked[RSPAMD_FUZZY_EPOCH_MAX];
  68. /**< amount of check requests for each epoch */
  69. guint64 fuzzy_shingles_checked[RSPAMD_FUZZY_EPOCH_MAX];
  70. /**< amount of shingle check requests for each epoch */
  71. guint64 fuzzy_hashes_found[RSPAMD_FUZZY_EPOCH_MAX];
  72. /**< amount of invalid requests */
  73. guint64 invalid_requests;
  74. /**< amount of delayed hashes found */
  75. guint64 delayed_hashes;
  76. };
  77. struct fuzzy_key_stat {
  78. guint64 checked;
  79. guint64 matched;
  80. guint64 added;
  81. guint64 deleted;
  82. guint64 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. guint64 last_checked_count;
  88. guint64 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 guint64 rspamd_fuzzy_storage_magic = 0x291a3253eb1b3ea5ULL;
  99. struct rspamd_fuzzy_storage_ctx {
  100. guint64 magic;
  101. /* Events base */
  102. struct ev_loop *event_loop;
  103. /* DNS resolver */
  104. struct rspamd_dns_resolver *resolver;
  105. /* Config */
  106. struct rspamd_config *cfg;
  107. /* END OF COMMON PART */
  108. struct fuzzy_global_stat stat;
  109. gdouble expire;
  110. gdouble sync_timeout;
  111. gdouble delay;
  112. struct rspamd_radix_map_helper *update_ips;
  113. struct rspamd_hash_map_helper *update_keys;
  114. struct rspamd_radix_map_helper *blocked_ips;
  115. struct rspamd_radix_map_helper *ratelimit_whitelist;
  116. struct rspamd_radix_map_helper *delay_whitelist;
  117. const ucl_object_t *update_map;
  118. const ucl_object_t *update_keys_map;
  119. const ucl_object_t *delay_whitelist_map;
  120. const ucl_object_t *blocked_map;
  121. const ucl_object_t *ratelimit_whitelist_map;
  122. guint keypair_cache_size;
  123. ev_timer stat_ev;
  124. ev_io peer_ev;
  125. /* Local keypair */
  126. struct rspamd_cryptobox_keypair *default_keypair; /* Bad clash, need for parse keypair */
  127. struct fuzzy_key *default_key;
  128. GHashTable *keys;
  129. gboolean encrypted_only;
  130. gboolean read_only;
  131. gboolean dedicated_update_worker;
  132. struct rspamd_keypair_cache *keypair_cache;
  133. struct rspamd_http_context *http_ctx;
  134. rspamd_lru_hash_t *errors_ips;
  135. rspamd_lru_hash_t *ratelimit_buckets;
  136. struct rspamd_fuzzy_backend *backend;
  137. GArray *updates_pending;
  138. guint updates_failed;
  139. guint updates_maxfail;
  140. /* Used to send data between workers */
  141. gint peer_fd;
  142. /* Ratelimits */
  143. guint leaky_bucket_ttl;
  144. guint leaky_bucket_mask;
  145. guint max_buckets;
  146. gboolean ratelimit_log_only;
  147. gdouble leaky_bucket_burst;
  148. gdouble leaky_bucket_rate;
  149. struct rspamd_worker *worker;
  150. const ucl_object_t *skip_map;
  151. struct rspamd_hash_map_helper *skip_hashes;
  152. gint lua_pre_handler_cbref;
  153. gint lua_post_handler_cbref;
  154. gint lua_blacklist_cbref;
  155. };
  156. enum fuzzy_cmd_type {
  157. CMD_NORMAL,
  158. CMD_SHINGLE,
  159. CMD_ENCRYPTED_NORMAL,
  160. CMD_ENCRYPTED_SHINGLE
  161. };
  162. struct fuzzy_session {
  163. struct rspamd_worker *worker;
  164. rspamd_inet_addr_t *addr;
  165. struct rspamd_fuzzy_storage_ctx *ctx;
  166. struct rspamd_fuzzy_shingle_cmd cmd; /* Can handle both shingles and non-shingles */
  167. struct rspamd_fuzzy_encrypted_reply reply; /* Again: contains everything */
  168. struct fuzzy_key_stat *ip_stat;
  169. enum rspamd_fuzzy_epoch epoch;
  170. enum fuzzy_cmd_type cmd_type;
  171. gint fd;
  172. ev_tstamp timestamp;
  173. struct ev_io io;
  174. ref_entry_t ref;
  175. struct fuzzy_key *key;
  176. struct rspamd_fuzzy_cmd_extension *extensions;
  177. guchar nm[rspamd_cryptobox_MAX_NMBYTES];
  178. };
  179. struct fuzzy_peer_request {
  180. ev_io io_ev;
  181. struct fuzzy_peer_cmd cmd;
  182. };
  183. KHASH_SET_INIT_INT(fuzzy_key_forbidden_ids);
  184. struct fuzzy_key {
  185. struct rspamd_cryptobox_keypair *key;
  186. struct rspamd_cryptobox_pubkey *pk;
  187. struct fuzzy_key_stat *stat;
  188. khash_t(fuzzy_key_forbidden_ids) *forbidden_ids;
  189. };
  190. struct rspamd_updates_cbdata {
  191. GArray *updates_pending;
  192. struct rspamd_fuzzy_storage_ctx *ctx;
  193. gchar *source;
  194. gboolean final;
  195. };
  196. static void rspamd_fuzzy_write_reply (struct fuzzy_session *session);
  197. static gboolean rspamd_fuzzy_process_updates_queue (struct rspamd_fuzzy_storage_ctx *ctx,
  198. const gchar *source, gboolean final);
  199. static gboolean rspamd_fuzzy_check_client (struct rspamd_fuzzy_storage_ctx *ctx,
  200. rspamd_inet_addr_t *addr);
  201. static void rspamd_fuzzy_maybe_call_blacklisted (struct rspamd_fuzzy_storage_ctx *ctx,
  202. rspamd_inet_addr_t *addr,
  203. const gchar *reason);
  204. static gboolean
  205. rspamd_fuzzy_check_ratelimit (struct fuzzy_session *session)
  206. {
  207. rspamd_inet_addr_t *masked;
  208. struct rspamd_leaky_bucket_elt *elt;
  209. if (!session->addr) {
  210. return TRUE;
  211. }
  212. if (session->ctx->ratelimit_whitelist != NULL) {
  213. if (rspamd_match_radix_map_addr (session->ctx->ratelimit_whitelist,
  214. session->addr) != NULL) {
  215. return TRUE;
  216. }
  217. }
  218. /*
  219. if (rspamd_inet_address_is_local (session->addr, TRUE)) {
  220. return TRUE;
  221. }
  222. */
  223. masked = rspamd_inet_address_copy(session->addr, NULL);
  224. if (rspamd_inet_address_get_af (masked) == AF_INET) {
  225. rspamd_inet_address_apply_mask (masked,
  226. MIN (session->ctx->leaky_bucket_mask, 32));
  227. }
  228. else {
  229. /* Must be at least /64 */
  230. rspamd_inet_address_apply_mask (masked,
  231. MIN (MAX (session->ctx->leaky_bucket_mask * 4, 64), 128));
  232. }
  233. elt = rspamd_lru_hash_lookup (session->ctx->ratelimit_buckets, masked,
  234. (time_t)session->timestamp);
  235. if (elt) {
  236. gboolean ratelimited = FALSE;
  237. if (isnan (elt->cur)) {
  238. /* Ratelimit exceeded, preserve it for the whole ttl */
  239. ratelimited = TRUE;
  240. }
  241. else {
  242. /* Update bucket */
  243. if (elt->last < session->timestamp) {
  244. elt->cur -= session->ctx->leaky_bucket_rate * (session->timestamp - elt->last);
  245. elt->last = session->timestamp;
  246. if (elt->cur < 0) {
  247. elt->cur = 0;
  248. }
  249. }
  250. else {
  251. elt->last = session->timestamp;
  252. }
  253. /* Check bucket */
  254. if (elt->cur >= session->ctx->leaky_bucket_burst) {
  255. msg_info ("ratelimiting %s (%s), %.1f max elts",
  256. rspamd_inet_address_to_string (session->addr),
  257. rspamd_inet_address_to_string (masked),
  258. session->ctx->leaky_bucket_burst);
  259. elt->cur = NAN;
  260. }
  261. else {
  262. elt->cur ++; /* Allow one more request */
  263. }
  264. }
  265. rspamd_inet_address_free (masked);
  266. if (ratelimited) {
  267. rspamd_fuzzy_maybe_call_blacklisted(session->ctx, session->addr, "ratelimit");
  268. }
  269. return !ratelimited;
  270. }
  271. else {
  272. /* New bucket */
  273. elt = g_malloc (sizeof (*elt));
  274. elt->addr = masked; /* transfer ownership */
  275. elt->cur = 1;
  276. elt->last = session->timestamp;
  277. rspamd_lru_hash_insert (session->ctx->ratelimit_buckets,
  278. masked,
  279. elt,
  280. session->timestamp,
  281. session->ctx->leaky_bucket_ttl);
  282. }
  283. return TRUE;
  284. }
  285. static void
  286. rspamd_fuzzy_maybe_call_blacklisted (struct rspamd_fuzzy_storage_ctx *ctx,
  287. rspamd_inet_addr_t *addr,
  288. const gchar *reason)
  289. {
  290. if (ctx->lua_blacklist_cbref != -1) {
  291. lua_State *L = ctx->cfg->lua_state;
  292. gint err_idx, ret;
  293. lua_pushcfunction (L, &rspamd_lua_traceback);
  294. err_idx = lua_gettop (L);
  295. lua_rawgeti (L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  296. /* client IP */
  297. rspamd_lua_ip_push (L, addr);
  298. /* block reason */
  299. lua_pushstring (L, reason);
  300. if ((ret = lua_pcall (L, 2, 0, err_idx)) != 0) {
  301. msg_err ("call to lua_blacklist_cbref "
  302. "script failed (%d): %s", ret, lua_tostring (L, -1));
  303. }
  304. lua_settop (L, 0);
  305. }
  306. }
  307. static gboolean
  308. rspamd_fuzzy_check_client (struct rspamd_fuzzy_storage_ctx *ctx,
  309. rspamd_inet_addr_t *addr)
  310. {
  311. if (ctx->blocked_ips != NULL) {
  312. if (rspamd_match_radix_map_addr (ctx->blocked_ips,
  313. addr) != NULL) {
  314. rspamd_fuzzy_maybe_call_blacklisted (ctx, addr, "blacklisted");
  315. return FALSE;
  316. }
  317. }
  318. return TRUE;
  319. }
  320. static gboolean
  321. rspamd_fuzzy_check_write (struct fuzzy_session *session)
  322. {
  323. if (session->ctx->read_only) {
  324. return FALSE;
  325. }
  326. if (session->ctx->update_ips != NULL && session->addr) {
  327. if (rspamd_inet_address_get_af (session->addr) == AF_UNIX) {
  328. return TRUE;
  329. }
  330. if (rspamd_match_radix_map_addr (session->ctx->update_ips,
  331. session->addr) == NULL) {
  332. return FALSE;
  333. }
  334. else {
  335. return TRUE;
  336. }
  337. }
  338. if (session->ctx->update_keys != NULL && session->key->stat && session->key->key) {
  339. static gchar base32_buf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  340. guint raw_len;
  341. const guchar *pk_raw = rspamd_keypair_component(session->key->key,
  342. RSPAMD_KEYPAIR_COMPONENT_ID, &raw_len);
  343. gint encoded_len = rspamd_encode_base32_buf(pk_raw, raw_len,
  344. base32_buf,sizeof(base32_buf),
  345. RSPAMD_BASE32_DEFAULT);
  346. if (rspamd_match_hash_map (session->ctx->update_keys, base32_buf, encoded_len)) {
  347. return TRUE;
  348. }
  349. }
  350. return FALSE;
  351. }
  352. static void
  353. fuzzy_key_stat_dtor (gpointer p)
  354. {
  355. struct fuzzy_key_stat *st = p;
  356. if (st->last_ips) {
  357. rspamd_lru_hash_destroy (st->last_ips);
  358. }
  359. if (st->keypair) {
  360. rspamd_keypair_unref(st->keypair);
  361. }
  362. g_free (st);
  363. }
  364. static void
  365. fuzzy_key_stat_unref (gpointer p)
  366. {
  367. struct fuzzy_key_stat *st = p;
  368. REF_RELEASE (st);
  369. }
  370. static void
  371. fuzzy_key_dtor (gpointer p)
  372. {
  373. struct fuzzy_key *key = p;
  374. if (key) {
  375. if (key->stat) {
  376. REF_RELEASE (key->stat);
  377. }
  378. if (key->forbidden_ids) {
  379. kh_destroy(fuzzy_key_forbidden_ids, key->forbidden_ids);
  380. }
  381. g_free (key);
  382. }
  383. }
  384. static void
  385. fuzzy_count_callback (guint64 count, void *ud)
  386. {
  387. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  388. ctx->stat.fuzzy_hashes = count;
  389. }
  390. static void
  391. fuzzy_rl_bucket_free (gpointer p)
  392. {
  393. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *)p;
  394. rspamd_inet_address_free (elt->addr);
  395. g_free (elt);
  396. }
  397. static void
  398. fuzzy_stat_count_callback (guint64 count, void *ud)
  399. {
  400. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  401. ev_timer_again (ctx->event_loop, &ctx->stat_ev);
  402. ctx->stat.fuzzy_hashes = count;
  403. }
  404. static void
  405. rspamd_fuzzy_stat_callback (EV_P_ ev_timer *w, int revents)
  406. {
  407. struct rspamd_fuzzy_storage_ctx *ctx =
  408. (struct rspamd_fuzzy_storage_ctx *)w->data;
  409. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_stat_count_callback, ctx);
  410. }
  411. static void
  412. fuzzy_update_version_callback (guint64 ver, void *ud)
  413. {
  414. }
  415. static void
  416. rspamd_fuzzy_updates_cb (gboolean success,
  417. guint nadded,
  418. guint ndeleted,
  419. guint nextended,
  420. guint nignored,
  421. void *ud)
  422. {
  423. struct rspamd_updates_cbdata *cbdata = ud;
  424. struct rspamd_fuzzy_storage_ctx *ctx;
  425. const gchar *source;
  426. ctx = cbdata->ctx;
  427. source = cbdata->source;
  428. if (success) {
  429. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  430. msg_info ("successfully updated fuzzy storage %s: %d updates in queue; "
  431. "%d pending currently; "
  432. "%d added; %d deleted; %d extended; %d duplicates",
  433. ctx->worker->cf->bind_conf ?
  434. ctx->worker->cf->bind_conf->bind_line :
  435. "unknown",
  436. cbdata->updates_pending->len,
  437. ctx->updates_pending->len,
  438. nadded, ndeleted, nextended, nignored);
  439. rspamd_fuzzy_backend_version(ctx->backend, source,
  440. fuzzy_update_version_callback, NULL);
  441. ctx->updates_failed = 0;
  442. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  443. /* Plan exit */
  444. ev_break(ctx->event_loop, EVBREAK_ALL);
  445. }
  446. }
  447. else {
  448. if (++ctx->updates_failed > ctx->updates_maxfail) {
  449. msg_err ("cannot commit update transaction to fuzzy backend %s, discard "
  450. "%ud updates after %d retries",
  451. ctx->worker->cf->bind_conf ?
  452. ctx->worker->cf->bind_conf->bind_line :
  453. "unknown",
  454. cbdata->updates_pending->len,
  455. ctx->updates_maxfail);
  456. ctx->updates_failed = 0;
  457. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  458. /* Plan exit */
  459. ev_break(ctx->event_loop, EVBREAK_ALL);
  460. }
  461. }
  462. else {
  463. if (ctx->updates_pending) {
  464. msg_err ("cannot commit update transaction to fuzzy backend %s; "
  465. "%ud updates are still left; %ud currently pending;"
  466. " %d retries remaining",
  467. ctx->worker->cf->bind_conf ?
  468. ctx->worker->cf->bind_conf->bind_line : "unknown",
  469. cbdata->updates_pending->len,
  470. ctx->updates_pending->len,
  471. ctx->updates_maxfail - ctx->updates_failed);
  472. /* Move the remaining updates to ctx queue */
  473. g_array_append_vals(ctx->updates_pending,
  474. cbdata->updates_pending->data,
  475. cbdata->updates_pending->len);
  476. if (cbdata->final) {
  477. /* Try one more time */
  478. rspamd_fuzzy_process_updates_queue(cbdata->ctx, cbdata->source,
  479. cbdata->final);
  480. }
  481. }
  482. else {
  483. /* We have lost our ctx, so it is a race condition case */
  484. msg_err ("cannot commit update transaction to fuzzy backend %s; "
  485. "%ud updates are still left; no more retries: a worker is terminated",
  486. ctx->worker->cf->bind_conf ?
  487. ctx->worker->cf->bind_conf->bind_line : "unknown",
  488. cbdata->updates_pending->len);
  489. }
  490. }
  491. }
  492. g_array_free (cbdata->updates_pending, TRUE);
  493. g_free (cbdata->source);
  494. g_free (cbdata);
  495. }
  496. static gboolean
  497. rspamd_fuzzy_process_updates_queue (struct rspamd_fuzzy_storage_ctx *ctx,
  498. const gchar *source, gboolean final)
  499. {
  500. struct rspamd_updates_cbdata *cbdata;
  501. if (ctx->updates_pending->len > 0) {
  502. cbdata = g_malloc (sizeof (*cbdata));
  503. cbdata->ctx = ctx;
  504. cbdata->final = final;
  505. cbdata->updates_pending = ctx->updates_pending;
  506. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  507. sizeof (struct fuzzy_peer_cmd),
  508. MAX (cbdata->updates_pending->len, 1024));
  509. cbdata->source = g_strdup (source);
  510. rspamd_fuzzy_backend_process_updates (ctx->backend,
  511. cbdata->updates_pending,
  512. source, rspamd_fuzzy_updates_cb, cbdata);
  513. return TRUE;
  514. }
  515. else if (final) {
  516. /* No need to sync */
  517. ev_break (ctx->event_loop, EVBREAK_ALL);
  518. }
  519. return FALSE;
  520. }
  521. static void
  522. rspamd_fuzzy_reply_io (EV_P_ ev_io *w, int revents)
  523. {
  524. struct fuzzy_session *session = (struct fuzzy_session *)w->data;
  525. ev_io_stop (EV_A_ w);
  526. rspamd_fuzzy_write_reply (session);
  527. REF_RELEASE (session);
  528. }
  529. static void
  530. rspamd_fuzzy_write_reply (struct fuzzy_session *session)
  531. {
  532. gssize r;
  533. gsize len;
  534. gconstpointer data;
  535. if (session->cmd_type == CMD_ENCRYPTED_NORMAL ||
  536. session->cmd_type == CMD_ENCRYPTED_SHINGLE) {
  537. /* Encrypted reply */
  538. data = &session->reply;
  539. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  540. len = sizeof (session->reply);
  541. }
  542. else {
  543. len = sizeof (session->reply.hdr) + sizeof (session->reply.rep.v1);
  544. }
  545. }
  546. else {
  547. data = &session->reply.rep;
  548. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  549. len = sizeof (session->reply.rep);
  550. }
  551. else {
  552. len = sizeof (session->reply.rep.v1);
  553. }
  554. }
  555. r = rspamd_inet_address_sendto (session->fd, data, len, 0,
  556. session->addr);
  557. if (r == -1) {
  558. if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
  559. /* Grab reference to avoid early destruction */
  560. REF_RETAIN (session);
  561. session->io.data = session;
  562. ev_io_init (&session->io,
  563. rspamd_fuzzy_reply_io, session->fd, EV_WRITE);
  564. ev_io_start (session->ctx->event_loop, &session->io);
  565. }
  566. else {
  567. msg_err ("error while writing reply: %s", strerror (errno));
  568. }
  569. }
  570. }
  571. static void
  572. rspamd_fuzzy_update_stats (struct rspamd_fuzzy_storage_ctx *ctx,
  573. enum rspamd_fuzzy_epoch epoch,
  574. gboolean matched,
  575. gboolean is_shingle,
  576. gboolean is_delayed,
  577. struct fuzzy_key_stat *key_stat,
  578. struct fuzzy_key_stat *ip_stat,
  579. guint cmd,
  580. guint reply,
  581. ev_tstamp timestamp)
  582. {
  583. ctx->stat.fuzzy_hashes_checked[epoch] ++;
  584. if (matched) {
  585. ctx->stat.fuzzy_hashes_found[epoch]++;
  586. }
  587. if (is_shingle) {
  588. ctx->stat.fuzzy_shingles_checked[epoch]++;
  589. }
  590. if (is_delayed) {
  591. ctx->stat.delayed_hashes ++;
  592. }
  593. if (key_stat) {
  594. if (!matched && reply != 0) {
  595. key_stat->errors ++;
  596. }
  597. else {
  598. if (cmd == FUZZY_CHECK) {
  599. key_stat->checked++;
  600. if (matched) {
  601. key_stat->matched ++;
  602. }
  603. if (G_UNLIKELY(key_stat->last_checked_time == 0.0)) {
  604. key_stat->last_checked_time = timestamp;
  605. key_stat->last_checked_count = key_stat->checked;
  606. key_stat->last_matched_count = key_stat->matched;
  607. }
  608. else if (G_UNLIKELY(timestamp > key_stat->last_checked_time + KEY_STAT_INTERVAL)) {
  609. guint64 nchecked = key_stat->checked - key_stat->last_checked_count;
  610. guint64 nmatched = key_stat->matched - key_stat->last_matched_count;
  611. rspamd_set_counter_ema (&key_stat->checked_ctr, nchecked, 0.5);
  612. rspamd_set_counter_ema (&key_stat->checked_ctr, nmatched, 0.5);
  613. key_stat->last_checked_time = timestamp;
  614. key_stat->last_checked_count = key_stat->checked;
  615. key_stat->last_matched_count = key_stat->matched;
  616. }
  617. }
  618. else if (cmd == FUZZY_WRITE) {
  619. key_stat->added++;
  620. }
  621. else if (cmd == FUZZY_DEL) {
  622. key_stat->deleted++;
  623. }
  624. }
  625. }
  626. if (ip_stat) {
  627. if (!matched && reply != 0) {
  628. ip_stat->errors++;
  629. }
  630. else {
  631. if (cmd == FUZZY_CHECK) {
  632. ip_stat->checked++;
  633. if (matched) {
  634. ip_stat->matched++;
  635. }
  636. }
  637. else if (cmd == FUZZY_WRITE) {
  638. ip_stat->added++;
  639. }
  640. else if (cmd == FUZZY_DEL) {
  641. ip_stat->deleted++;
  642. }
  643. }
  644. }
  645. }
  646. enum rspamd_fuzzy_reply_flags {
  647. RSPAMD_FUZZY_REPLY_ENCRYPTED = 0x1u << 0u,
  648. RSPAMD_FUZZY_REPLY_SHINGLE = 0x1u << 1u,
  649. RSPAMD_FUZZY_REPLY_DELAY = 0x1u << 2u,
  650. };
  651. static void
  652. rspamd_fuzzy_make_reply (struct rspamd_fuzzy_cmd *cmd,
  653. struct rspamd_fuzzy_reply *result,
  654. struct fuzzy_session *session,
  655. gint flags)
  656. {
  657. gsize len;
  658. if (cmd) {
  659. result->v1.tag = cmd->tag;
  660. memcpy (&session->reply.rep, result, sizeof (*result));
  661. rspamd_fuzzy_update_stats (session->ctx,
  662. session->epoch,
  663. result->v1.prob > 0.5,
  664. flags & RSPAMD_FUZZY_REPLY_SHINGLE,
  665. flags & RSPAMD_FUZZY_REPLY_DELAY,
  666. session->key ? session->key->stat : NULL,
  667. session->ip_stat,
  668. cmd->cmd,
  669. result->v1.value,
  670. session->timestamp);
  671. if (flags & RSPAMD_FUZZY_REPLY_DELAY) {
  672. /* Hash is too fresh, need to delay it */
  673. session->reply.rep.ts = 0;
  674. session->reply.rep.v1.prob = 0.0;
  675. session->reply.rep.v1.value = 0;
  676. }
  677. if (flags & RSPAMD_FUZZY_REPLY_ENCRYPTED) {
  678. if (session->reply.rep.v1.prob > 0 && session->key && session->key->forbidden_ids) {
  679. khiter_t k;
  680. k = kh_get(fuzzy_key_forbidden_ids, session->key->forbidden_ids, session->reply.rep.v1.flag);
  681. if (k != kh_end (session->key->forbidden_ids)) {
  682. /* Hash is from a forbidden flag for this key */
  683. session->reply.rep.ts = 0;
  684. session->reply.rep.v1.prob = 0.0;
  685. session->reply.rep.v1.value = 0;
  686. session->reply.rep.v1.flag = 0;
  687. }
  688. }
  689. /* We need also to encrypt reply */
  690. ottery_rand_bytes (session->reply.hdr.nonce,
  691. sizeof (session->reply.hdr.nonce));
  692. /*
  693. * For old replies we need to encrypt just old part, otherwise
  694. * decryption would fail due to mac verification mistake
  695. */
  696. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  697. len = sizeof (session->reply.rep);
  698. }
  699. else {
  700. len = sizeof (session->reply.rep.v1);
  701. }
  702. rspamd_cryptobox_encrypt_nm_inplace ((guchar *)&session->reply.rep,
  703. len,
  704. session->reply.hdr.nonce,
  705. session->nm,
  706. session->reply.hdr.mac,
  707. RSPAMD_CRYPTOBOX_MODE_25519);
  708. }
  709. }
  710. rspamd_fuzzy_write_reply (session);
  711. }
  712. static gboolean
  713. fuzzy_peer_try_send (gint fd, struct fuzzy_peer_request *up_req)
  714. {
  715. gssize r;
  716. r = write (fd, &up_req->cmd, sizeof (up_req->cmd));
  717. if (r != sizeof (up_req->cmd)) {
  718. return FALSE;
  719. }
  720. return TRUE;
  721. }
  722. static void
  723. fuzzy_peer_send_io (EV_P_ ev_io *w, int revents)
  724. {
  725. struct fuzzy_peer_request *up_req = (struct fuzzy_peer_request *)w->data;
  726. if (!fuzzy_peer_try_send (w->fd, up_req)) {
  727. msg_err ("cannot send update request to the peer: %s", strerror (errno));
  728. }
  729. ev_io_stop (EV_A_ w);
  730. g_free (up_req);
  731. }
  732. static void
  733. rspamd_fuzzy_extensions_tolua (lua_State *L,
  734. struct fuzzy_session *session)
  735. {
  736. struct rspamd_fuzzy_cmd_extension *ext;
  737. rspamd_inet_addr_t *addr;
  738. lua_createtable (L, 0, 0);
  739. LL_FOREACH (session->extensions, ext) {
  740. switch (ext->ext) {
  741. case RSPAMD_FUZZY_EXT_SOURCE_DOMAIN:
  742. lua_pushlstring (L, ext->payload, ext->length);
  743. lua_setfield (L, -2, "domain");
  744. break;
  745. case RSPAMD_FUZZY_EXT_SOURCE_IP4:
  746. addr = rspamd_inet_address_new (AF_INET, ext->payload);
  747. rspamd_lua_ip_push (L, addr);
  748. rspamd_inet_address_free (addr);
  749. lua_setfield (L, -2, "ip");
  750. break;
  751. case RSPAMD_FUZZY_EXT_SOURCE_IP6:
  752. addr = rspamd_inet_address_new (AF_INET6, ext->payload);
  753. rspamd_lua_ip_push (L, addr);
  754. rspamd_inet_address_free (addr);
  755. lua_setfield (L, -2, "ip");
  756. break;
  757. }
  758. }
  759. }
  760. static void
  761. rspamd_fuzzy_check_callback (struct rspamd_fuzzy_reply *result, void *ud)
  762. {
  763. struct fuzzy_session *session = ud;
  764. gboolean is_shingle = FALSE, __attribute__ ((unused)) encrypted = FALSE;
  765. struct rspamd_fuzzy_cmd *cmd = NULL;
  766. const struct rspamd_shingle *shingle = NULL;
  767. struct rspamd_shingle sgl_cpy;
  768. gint send_flags = 0;
  769. switch (session->cmd_type) {
  770. case CMD_ENCRYPTED_NORMAL:
  771. encrypted = TRUE;
  772. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  773. /* Fallthrough */
  774. case CMD_NORMAL:
  775. cmd = &session->cmd.basic;
  776. break;
  777. case CMD_ENCRYPTED_SHINGLE:
  778. encrypted = TRUE;
  779. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  780. /* Fallthrough */
  781. case CMD_SHINGLE:
  782. cmd = &session->cmd.basic;
  783. memcpy (&sgl_cpy, &session->cmd.sgl, sizeof (sgl_cpy));
  784. shingle = &sgl_cpy;
  785. is_shingle = TRUE;
  786. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  787. break;
  788. }
  789. if (session->ctx->lua_post_handler_cbref != -1) {
  790. /* Start lua post handler */
  791. lua_State *L = session->ctx->cfg->lua_state;
  792. gint err_idx, ret;
  793. lua_pushcfunction (L, &rspamd_lua_traceback);
  794. err_idx = lua_gettop (L);
  795. /* Preallocate stack (small opt) */
  796. lua_checkstack (L, err_idx + 9);
  797. /* function */
  798. lua_rawgeti (L, LUA_REGISTRYINDEX, session->ctx->lua_post_handler_cbref);
  799. /* client IP */
  800. if (session->addr) {
  801. rspamd_lua_ip_push(L, session->addr);
  802. }
  803. else {
  804. lua_pushnil (L);
  805. }
  806. /* client command */
  807. lua_pushinteger (L, cmd->cmd);
  808. /* command value (push as rspamd_text) */
  809. (void)lua_new_text (L, result->digest, sizeof (result->digest), FALSE);
  810. /* is shingle */
  811. lua_pushboolean (L, is_shingle);
  812. /* result value */
  813. lua_pushinteger (L, result->v1.value);
  814. /* result probability */
  815. lua_pushnumber (L, result->v1.prob);
  816. /* result flag */
  817. lua_pushinteger (L, result->v1.flag);
  818. /* result timestamp */
  819. lua_pushinteger (L, result->ts);
  820. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  821. rspamd_fuzzy_extensions_tolua (L, session);
  822. if ((ret = lua_pcall (L, 9, LUA_MULTRET, err_idx)) != 0) {
  823. msg_err ("call to lua_post_handler lua "
  824. "script failed (%d): %s", ret, lua_tostring (L, -1));
  825. }
  826. else {
  827. /* Return values order:
  828. * the first reply will be on err_idx + 1
  829. * if it is true, then we need to read the former ones:
  830. * 2-nd will be reply code
  831. * 3-rd will be probability (or 0.0 if missing)
  832. * 4-th value is flag (or default flag if missing)
  833. */
  834. ret = lua_toboolean (L, err_idx + 1);
  835. if (ret) {
  836. /* Artificial reply */
  837. result->v1.value = lua_tointeger (L, err_idx + 2);
  838. if (lua_isnumber (L, err_idx + 3)) {
  839. result->v1.prob = lua_tonumber (L, err_idx + 3);
  840. }
  841. else {
  842. result->v1.prob = 0.0f;
  843. }
  844. if (lua_isnumber (L, err_idx + 4)) {
  845. result->v1.flag = lua_tointeger (L, err_idx + 4);
  846. }
  847. lua_settop (L, 0);
  848. rspamd_fuzzy_make_reply (cmd, result, session, send_flags);
  849. REF_RELEASE (session);
  850. return;
  851. }
  852. }
  853. lua_settop (L, 0);
  854. }
  855. if (!isnan (session->ctx->delay) &&
  856. rspamd_match_radix_map_addr (session->ctx->delay_whitelist,
  857. session->addr) == NULL) {
  858. gdouble hash_age = rspamd_get_calendar_ticks () - result->ts;
  859. gdouble jittered_age = rspamd_time_jitter (session->ctx->delay,
  860. session->ctx->delay / 2.0);
  861. if (hash_age < jittered_age) {
  862. send_flags |= RSPAMD_FUZZY_REPLY_DELAY;
  863. }
  864. }
  865. /* Refresh hash if found with strong confidence */
  866. if (result->v1.prob > 0.9 && !session->ctx->read_only) {
  867. struct fuzzy_peer_cmd up_cmd;
  868. struct fuzzy_peer_request *up_req;
  869. if (session->worker->index == 0) {
  870. /* Just add to the queue */
  871. memset (&up_cmd, 0, sizeof (up_cmd));
  872. up_cmd.is_shingle = is_shingle;
  873. memcpy (up_cmd.cmd.normal.digest, result->digest,
  874. sizeof (up_cmd.cmd.normal.digest));
  875. up_cmd.cmd.normal.flag = result->v1.flag;
  876. up_cmd.cmd.normal.cmd = FUZZY_REFRESH;
  877. up_cmd.cmd.normal.shingles_count = cmd->shingles_count;
  878. if (is_shingle && shingle) {
  879. memcpy (&up_cmd.cmd.shingle.sgl, shingle,
  880. sizeof (up_cmd.cmd.shingle.sgl));
  881. }
  882. g_array_append_val (session->ctx->updates_pending, up_cmd);
  883. }
  884. else {
  885. /* We need to send request to the peer */
  886. up_req = g_malloc0 (sizeof (*up_req));
  887. up_req->cmd.is_shingle = is_shingle;
  888. memcpy (up_req->cmd.cmd.normal.digest, result->digest,
  889. sizeof (up_req->cmd.cmd.normal.digest));
  890. up_req->cmd.cmd.normal.flag = result->v1.flag;
  891. up_req->cmd.cmd.normal.cmd = FUZZY_REFRESH;
  892. up_req->cmd.cmd.normal.shingles_count = cmd->shingles_count;
  893. if (is_shingle && shingle) {
  894. memcpy (&up_req->cmd.cmd.shingle.sgl, shingle,
  895. sizeof (up_req->cmd.cmd.shingle.sgl));
  896. }
  897. if (!fuzzy_peer_try_send (session->ctx->peer_fd, up_req)) {
  898. up_req->io_ev.data = up_req;
  899. ev_io_init (&up_req->io_ev, fuzzy_peer_send_io,
  900. session->ctx->peer_fd, EV_WRITE);
  901. ev_io_start (session->ctx->event_loop, &up_req->io_ev);
  902. }
  903. else {
  904. g_free (up_req);
  905. }
  906. }
  907. }
  908. rspamd_fuzzy_make_reply (cmd, result, session, send_flags);
  909. REF_RELEASE (session);
  910. }
  911. static void
  912. rspamd_fuzzy_process_command (struct fuzzy_session *session)
  913. {
  914. gboolean is_shingle = FALSE, __attribute__ ((unused)) encrypted = FALSE;
  915. struct rspamd_fuzzy_cmd *cmd = NULL;
  916. struct rspamd_fuzzy_reply result;
  917. struct fuzzy_peer_cmd up_cmd;
  918. struct fuzzy_peer_request *up_req;
  919. struct fuzzy_key_stat *ip_stat = NULL;
  920. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  921. rspamd_inet_addr_t *naddr;
  922. gpointer ptr;
  923. gsize up_len = 0;
  924. gint send_flags = 0;
  925. cmd = &session->cmd.basic;
  926. switch (session->cmd_type) {
  927. case CMD_NORMAL:
  928. up_len = sizeof (session->cmd.basic);
  929. break;
  930. case CMD_SHINGLE:
  931. up_len = sizeof (session->cmd);
  932. is_shingle = TRUE;
  933. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  934. break;
  935. case CMD_ENCRYPTED_NORMAL:
  936. up_len = sizeof (session->cmd.basic);
  937. encrypted = TRUE;
  938. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  939. break;
  940. case CMD_ENCRYPTED_SHINGLE:
  941. up_len = sizeof (session->cmd);
  942. encrypted = TRUE;
  943. is_shingle = TRUE;
  944. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE|RSPAMD_FUZZY_REPLY_ENCRYPTED;
  945. break;
  946. default:
  947. msg_err ("invalid command type: %d", session->cmd_type);
  948. return;
  949. }
  950. memset (&result, 0, sizeof (result));
  951. memcpy (result.digest, cmd->digest, sizeof (result.digest));
  952. result.v1.flag = cmd->flag;
  953. result.v1.tag = cmd->tag;
  954. if (session->ctx->lua_pre_handler_cbref != -1) {
  955. /* Start lua pre handler */
  956. lua_State *L = session->ctx->cfg->lua_state;
  957. gint err_idx, ret;
  958. lua_pushcfunction (L, &rspamd_lua_traceback);
  959. err_idx = lua_gettop (L);
  960. /* Preallocate stack (small opt) */
  961. lua_checkstack (L, err_idx + 5);
  962. /* function */
  963. lua_rawgeti (L, LUA_REGISTRYINDEX, session->ctx->lua_pre_handler_cbref);
  964. /* client IP */
  965. rspamd_lua_ip_push (L, session->addr);
  966. /* client command */
  967. lua_pushinteger (L, cmd->cmd);
  968. /* command value (push as rspamd_text) */
  969. (void)lua_new_text (L, cmd->digest, sizeof (cmd->digest), FALSE);
  970. /* is shingle */
  971. lua_pushboolean (L, is_shingle);
  972. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  973. rspamd_fuzzy_extensions_tolua (L, session);
  974. if ((ret = lua_pcall (L, 5, LUA_MULTRET, err_idx)) != 0) {
  975. msg_err ("call to lua_pre_handler lua "
  976. "script failed (%d): %s", ret, lua_tostring (L, -1));
  977. }
  978. else {
  979. /* Return values order:
  980. * the first reply will be on err_idx + 1
  981. * if it is true, then we need to read the former ones:
  982. * 2-nd will be reply code
  983. * 3-rd will be probability (or 0.0 if missing)
  984. */
  985. ret = lua_toboolean (L, err_idx + 1);
  986. if (ret) {
  987. /* Artificial reply */
  988. result.v1.value = lua_tointeger (L, err_idx + 2);
  989. if (lua_isnumber (L, err_idx + 3)) {
  990. result.v1.prob = lua_tonumber (L, err_idx + 3);
  991. }
  992. else {
  993. result.v1.prob = 0.0f;
  994. }
  995. lua_settop (L, 0);
  996. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  997. return;
  998. }
  999. }
  1000. lua_settop (L, 0);
  1001. }
  1002. if (G_UNLIKELY (cmd == NULL || up_len == 0)) {
  1003. result.v1.value = 500;
  1004. result.v1.prob = 0.0f;
  1005. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  1006. return;
  1007. }
  1008. if (session->ctx->encrypted_only && !encrypted) {
  1009. /* Do not accept unencrypted commands */
  1010. result.v1.value = 403;
  1011. result.v1.prob = 0.0f;
  1012. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  1013. return;
  1014. }
  1015. if (session->key && session->addr) {
  1016. ip_stat = rspamd_lru_hash_lookup (session->key->stat->last_ips,
  1017. session->addr, -1);
  1018. if (ip_stat == NULL) {
  1019. naddr = rspamd_inet_address_copy(session->addr, NULL);
  1020. ip_stat = g_malloc0 (sizeof (*ip_stat));
  1021. REF_INIT_RETAIN (ip_stat, fuzzy_key_stat_dtor);
  1022. rspamd_lru_hash_insert (session->key->stat->last_ips,
  1023. naddr, ip_stat, -1, 0);
  1024. }
  1025. REF_RETAIN (ip_stat);
  1026. session->ip_stat = ip_stat;
  1027. }
  1028. if (cmd->cmd == FUZZY_CHECK) {
  1029. bool can_continue = true;
  1030. if (session->ctx->ratelimit_buckets) {
  1031. if (session->ctx->ratelimit_log_only) {
  1032. (void)rspamd_fuzzy_check_ratelimit (session); /* Check but ignore */
  1033. }
  1034. else {
  1035. can_continue = rspamd_fuzzy_check_ratelimit (session);
  1036. }
  1037. }
  1038. if (can_continue) {
  1039. REF_RETAIN (session);
  1040. rspamd_fuzzy_backend_check (session->ctx->backend, cmd,
  1041. rspamd_fuzzy_check_callback, session);
  1042. }
  1043. else {
  1044. result.v1.value = 403;
  1045. result.v1.prob = 0.0f;
  1046. result.v1.flag = 0;
  1047. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  1048. }
  1049. }
  1050. else if (cmd->cmd == FUZZY_STAT) {
  1051. result.v1.prob = 1.0f;
  1052. result.v1.value = 0;
  1053. result.v1.flag = session->ctx->stat.fuzzy_hashes;
  1054. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  1055. }
  1056. else {
  1057. if (rspamd_fuzzy_check_write (session)) {
  1058. /* Check whitelist */
  1059. if (session->ctx->skip_hashes && cmd->cmd == FUZZY_WRITE) {
  1060. rspamd_encode_hex_buf (cmd->digest, sizeof (cmd->digest),
  1061. hexbuf, sizeof (hexbuf) - 1);
  1062. hexbuf[sizeof (hexbuf) - 1] = '\0';
  1063. if (rspamd_match_hash_map (session->ctx->skip_hashes,
  1064. hexbuf, sizeof (hexbuf) - 1)) {
  1065. result.v1.value = 401;
  1066. result.v1.prob = 0.0f;
  1067. goto reply;
  1068. }
  1069. }
  1070. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  1071. /* Just add to the queue */
  1072. up_cmd.is_shingle = is_shingle;
  1073. ptr = is_shingle ?
  1074. (gpointer)&up_cmd.cmd.shingle :
  1075. (gpointer)&up_cmd.cmd.normal;
  1076. memcpy (ptr, cmd, up_len);
  1077. g_array_append_val (session->ctx->updates_pending, up_cmd);
  1078. }
  1079. else {
  1080. /* We need to send request to the peer */
  1081. up_req = g_malloc0 (sizeof (*up_req));
  1082. up_req->cmd.is_shingle = is_shingle;
  1083. ptr = is_shingle ?
  1084. (gpointer)&up_req->cmd.cmd.shingle :
  1085. (gpointer)&up_req->cmd.cmd.normal;
  1086. memcpy (ptr, cmd, up_len);
  1087. if (!fuzzy_peer_try_send (session->ctx->peer_fd, up_req)) {
  1088. up_req->io_ev.data = up_req;
  1089. ev_io_init (&up_req->io_ev, fuzzy_peer_send_io,
  1090. session->ctx->peer_fd, EV_WRITE);
  1091. ev_io_start (session->ctx->event_loop, &up_req->io_ev);
  1092. }
  1093. else {
  1094. g_free (up_req);
  1095. }
  1096. }
  1097. result.v1.value = 0;
  1098. result.v1.prob = 1.0f;
  1099. }
  1100. else {
  1101. result.v1.value = 403;
  1102. result.v1.prob = 0.0f;
  1103. }
  1104. reply:
  1105. rspamd_fuzzy_make_reply (cmd, &result, session, send_flags);
  1106. }
  1107. }
  1108. static enum rspamd_fuzzy_epoch
  1109. rspamd_fuzzy_command_valid (struct rspamd_fuzzy_cmd *cmd, gint r)
  1110. {
  1111. enum rspamd_fuzzy_epoch ret = RSPAMD_FUZZY_EPOCH_MAX;
  1112. switch (cmd->version) {
  1113. case 4:
  1114. if (cmd->shingles_count > 0) {
  1115. if (r >= sizeof (struct rspamd_fuzzy_shingle_cmd)) {
  1116. ret = RSPAMD_FUZZY_EPOCH11;
  1117. }
  1118. }
  1119. else {
  1120. if (r >= sizeof (*cmd)) {
  1121. ret = RSPAMD_FUZZY_EPOCH11;
  1122. }
  1123. }
  1124. break;
  1125. case 3:
  1126. if (cmd->shingles_count > 0) {
  1127. if (r == sizeof (struct rspamd_fuzzy_shingle_cmd)) {
  1128. ret = RSPAMD_FUZZY_EPOCH10;
  1129. }
  1130. }
  1131. else {
  1132. if (r == sizeof (*cmd)) {
  1133. ret = RSPAMD_FUZZY_EPOCH10;
  1134. }
  1135. }
  1136. break;
  1137. default:
  1138. break;
  1139. }
  1140. return ret;
  1141. }
  1142. static gboolean
  1143. rspamd_fuzzy_decrypt_command (struct fuzzy_session *s, guchar *buf, gsize buflen)
  1144. {
  1145. struct rspamd_fuzzy_encrypted_req_hdr hdr;
  1146. struct rspamd_cryptobox_pubkey *rk;
  1147. struct fuzzy_key *key;
  1148. if (s->ctx->default_key == NULL) {
  1149. msg_warn ("received encrypted request when encryption is not enabled");
  1150. return FALSE;
  1151. }
  1152. if (buflen < sizeof (hdr)) {
  1153. msg_warn ("XXX: should not be reached");
  1154. return FALSE;
  1155. }
  1156. memcpy (&hdr, buf, sizeof (hdr));
  1157. buf += sizeof (hdr);
  1158. buflen -= sizeof (hdr);
  1159. /* Try to find the desired key */
  1160. key = g_hash_table_lookup (s->ctx->keys, hdr.key_id);
  1161. if (key == NULL) {
  1162. /* Unknown key, assume default one */
  1163. key = s->ctx->default_key;
  1164. }
  1165. s->key = key;
  1166. /* Now process keypair */
  1167. rk = rspamd_pubkey_from_bin (hdr.pubkey, sizeof (hdr.pubkey),
  1168. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  1169. if (rk == NULL) {
  1170. msg_err ("bad key; ip=%s",
  1171. rspamd_inet_address_to_string (s->addr));
  1172. return FALSE;
  1173. }
  1174. rspamd_keypair_cache_process (s->ctx->keypair_cache, key->key, rk);
  1175. /* Now decrypt request */
  1176. if (!rspamd_cryptobox_decrypt_nm_inplace (buf, buflen, hdr.nonce,
  1177. rspamd_pubkey_get_nm (rk, key->key),
  1178. hdr.mac, RSPAMD_CRYPTOBOX_MODE_25519)) {
  1179. msg_err ("decryption failed; ip=%s",
  1180. rspamd_inet_address_to_string (s->addr));
  1181. rspamd_pubkey_unref (rk);
  1182. return FALSE;
  1183. }
  1184. memcpy (s->nm, rspamd_pubkey_get_nm (rk, key->key), sizeof (s->nm));
  1185. rspamd_pubkey_unref (rk);
  1186. return TRUE;
  1187. }
  1188. static gboolean
  1189. rspamd_fuzzy_extensions_from_wire (struct fuzzy_session *s, guchar *buf, gsize buflen)
  1190. {
  1191. struct rspamd_fuzzy_cmd_extension *ext, *prev_ext;
  1192. guchar *storage, *p = buf, *end = buf + buflen;
  1193. gsize st_len = 0, n_ext = 0;
  1194. /* Read number of extensions to allocate array */
  1195. while (p < end) {
  1196. guchar cmd = *p++;
  1197. if (p < end) {
  1198. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1199. /* Next byte is buf length */
  1200. guchar dom_len = *p++;
  1201. if (dom_len <= (end - p)) {
  1202. st_len += dom_len;
  1203. n_ext ++;
  1204. }
  1205. else {
  1206. /* Truncation */
  1207. return FALSE;
  1208. }
  1209. p += dom_len;
  1210. }
  1211. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1212. if (end - p >= sizeof (in_addr_t)) {
  1213. n_ext ++;
  1214. st_len += sizeof (in_addr_t);
  1215. }
  1216. else {
  1217. /* Truncation */
  1218. return FALSE;
  1219. }
  1220. p += sizeof (in_addr_t);
  1221. }
  1222. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1223. if (end - p >= sizeof (struct in6_addr)) {
  1224. n_ext ++;
  1225. st_len += sizeof (struct in6_addr);
  1226. }
  1227. else {
  1228. /* Truncation */
  1229. return FALSE;
  1230. }
  1231. p += sizeof (struct in6_addr);
  1232. }
  1233. else {
  1234. /* Invalid command */
  1235. return FALSE;
  1236. }
  1237. }
  1238. else {
  1239. /* Truncated extension */
  1240. return FALSE;
  1241. }
  1242. }
  1243. if (n_ext > 0) {
  1244. p = buf;
  1245. /*
  1246. * Memory layout: n_ext of struct rspamd_fuzzy_cmd_extension
  1247. * payload for each extension in a continuous data segment
  1248. */
  1249. storage = g_malloc (n_ext * sizeof (struct rspamd_fuzzy_cmd_extension) +
  1250. st_len);
  1251. guchar *data_buf = storage +
  1252. n_ext * sizeof (struct rspamd_fuzzy_cmd_extension);
  1253. ext = (struct rspamd_fuzzy_cmd_extension *)storage;
  1254. /* All validation has been done, so we can just go further */
  1255. while (p < end) {
  1256. prev_ext = ext;
  1257. guchar cmd = *p++;
  1258. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1259. /* Next byte is buf length */
  1260. guchar dom_len = *p++;
  1261. guchar *dest = data_buf;
  1262. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
  1263. ext->next = ext + 1;
  1264. ext->length = dom_len;
  1265. ext->payload = dest;
  1266. memcpy (dest, p, dom_len);
  1267. p += dom_len;
  1268. data_buf += dom_len;
  1269. ext = ext->next;
  1270. }
  1271. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1272. guchar *dest = data_buf;
  1273. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP4;
  1274. ext->next = ext + 1;
  1275. ext->length = sizeof (in_addr_t);
  1276. ext->payload = dest;
  1277. memcpy (dest, p, sizeof (in_addr_t));
  1278. p += sizeof (in_addr_t);
  1279. data_buf += sizeof (in_addr_t);
  1280. ext = ext->next;
  1281. }
  1282. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1283. guchar *dest = data_buf;
  1284. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP6;
  1285. ext->next = ext + 1;
  1286. ext->length = sizeof (struct in6_addr);
  1287. ext->payload = dest;
  1288. memcpy (dest, p, sizeof (struct in6_addr));
  1289. p += sizeof (struct in6_addr);
  1290. data_buf += sizeof (struct in6_addr);
  1291. ext = ext->next;
  1292. }
  1293. else {
  1294. g_assert_not_reached ();
  1295. }
  1296. }
  1297. /* Last next should be NULL */
  1298. prev_ext->next = NULL;
  1299. /* Rewind to the begin */
  1300. ext = (struct rspamd_fuzzy_cmd_extension *)storage;
  1301. s->extensions = ext;
  1302. }
  1303. return TRUE;
  1304. }
  1305. static gboolean
  1306. rspamd_fuzzy_cmd_from_wire (guchar *buf, guint buflen, struct fuzzy_session *s)
  1307. {
  1308. enum rspamd_fuzzy_epoch epoch;
  1309. gboolean encrypted = FALSE;
  1310. if (buflen < sizeof (struct rspamd_fuzzy_cmd)) {
  1311. msg_debug ("truncated fuzzy command of size %d received", buflen);
  1312. return FALSE;
  1313. }
  1314. /* Now check encryption */
  1315. if (buflen >= sizeof (struct rspamd_fuzzy_encrypted_cmd)) {
  1316. if (memcmp (buf, fuzzy_encrypted_magic, sizeof (fuzzy_encrypted_magic)) == 0) {
  1317. /* Encrypted command */
  1318. encrypted = TRUE;
  1319. }
  1320. }
  1321. if (encrypted) {
  1322. /* Decrypt first */
  1323. if (!rspamd_fuzzy_decrypt_command (s, buf, buflen)) {
  1324. return FALSE;
  1325. }
  1326. else {
  1327. /*
  1328. * Advance buffer to skip encrypted header.
  1329. * Note that after rspamd_fuzzy_decrypt_command buf is unencrypted
  1330. */
  1331. buf += sizeof (struct rspamd_fuzzy_encrypted_req_hdr);
  1332. buflen -= sizeof (struct rspamd_fuzzy_encrypted_req_hdr);
  1333. }
  1334. }
  1335. /* Fill the normal command */
  1336. if (buflen < sizeof (s->cmd.basic)) {
  1337. msg_debug ("truncated normal fuzzy command of size %d received", buflen);
  1338. return FALSE;
  1339. }
  1340. memcpy (&s->cmd.basic, buf, sizeof (s->cmd.basic));
  1341. epoch = rspamd_fuzzy_command_valid (&s->cmd.basic, buflen);
  1342. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1343. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1344. return FALSE;
  1345. }
  1346. s->epoch = epoch;
  1347. /* Advance buf */
  1348. buf += sizeof (s->cmd.basic);
  1349. buflen -= sizeof (s->cmd.basic);
  1350. if (s->cmd.basic.shingles_count > 0) {
  1351. if (buflen >= sizeof (s->cmd.sgl)) {
  1352. /* Copy the shingles part */
  1353. memcpy (&s->cmd.sgl, buf, sizeof (s->cmd.sgl));
  1354. }
  1355. else {
  1356. /* Truncated stuff */
  1357. msg_debug ("truncated fuzzy shingles command of size %d received", buflen);
  1358. return FALSE;
  1359. }
  1360. buf += sizeof (s->cmd.sgl);
  1361. buflen -= sizeof (s->cmd.sgl);
  1362. if (encrypted) {
  1363. s->cmd_type = CMD_ENCRYPTED_SHINGLE;
  1364. }
  1365. else {
  1366. s->cmd_type = CMD_SHINGLE;
  1367. }
  1368. }
  1369. else {
  1370. if (encrypted) {
  1371. s->cmd_type = CMD_ENCRYPTED_NORMAL;
  1372. }
  1373. else {
  1374. s->cmd_type = CMD_NORMAL;
  1375. }
  1376. }
  1377. if (buflen > 0) {
  1378. /* Process possible extensions */
  1379. if (!rspamd_fuzzy_extensions_from_wire (s, buf, buflen)) {
  1380. msg_debug ("truncated fuzzy shingles command of size %d received", buflen);
  1381. return FALSE;
  1382. }
  1383. }
  1384. return TRUE;
  1385. }
  1386. static void
  1387. fuzzy_session_destroy (gpointer d)
  1388. {
  1389. struct fuzzy_session *session = d;
  1390. rspamd_inet_address_free (session->addr);
  1391. rspamd_explicit_memzero (session->nm, sizeof (session->nm));
  1392. session->worker->nconns--;
  1393. if (session->ip_stat) {
  1394. REF_RELEASE (session->ip_stat);
  1395. }
  1396. if (session->extensions) {
  1397. g_free (session->extensions);
  1398. }
  1399. g_free (session);
  1400. }
  1401. #define FUZZY_INPUT_BUFLEN 1024
  1402. #ifdef HAVE_RECVMMSG
  1403. #define MSGVEC_LEN 16
  1404. #else
  1405. #define MSGVEC_LEN 1
  1406. #endif
  1407. union sa_union {
  1408. struct sockaddr sa;
  1409. struct sockaddr_in s4;
  1410. struct sockaddr_in6 s6;
  1411. struct sockaddr_un su;
  1412. struct sockaddr_storage ss;
  1413. };
  1414. /*
  1415. * Accept new connection and construct task
  1416. */
  1417. static void
  1418. accept_fuzzy_socket (EV_P_ ev_io *w, int revents)
  1419. {
  1420. struct rspamd_worker *worker = (struct rspamd_worker *)w->data;
  1421. struct rspamd_fuzzy_storage_ctx *ctx;
  1422. struct fuzzy_session *session;
  1423. gssize r, msg_len;
  1424. guint64 *nerrors;
  1425. struct iovec iovs[MSGVEC_LEN];
  1426. guint8 bufs[MSGVEC_LEN][FUZZY_INPUT_BUFLEN];
  1427. union sa_union peer_sa[MSGVEC_LEN];
  1428. socklen_t salen = sizeof (peer_sa[0]);
  1429. #ifdef HAVE_RECVMMSG
  1430. #define MSG_FIELD(msg, field) msg.msg_hdr.field
  1431. struct mmsghdr msg[MSGVEC_LEN];
  1432. #else
  1433. #define MSG_FIELD(msg, field) msg.field
  1434. struct msghdr msg[MSGVEC_LEN];
  1435. #endif
  1436. memset (msg, 0, sizeof (*msg) * MSGVEC_LEN);
  1437. ctx = (struct rspamd_fuzzy_storage_ctx *)worker->ctx;
  1438. /* Prepare messages to receive */
  1439. for (int i = 0; i < MSGVEC_LEN; i ++) {
  1440. /* Prepare msghdr structs */
  1441. iovs[i].iov_base = bufs[i];
  1442. iovs[i].iov_len = sizeof (bufs[i]);
  1443. MSG_FIELD(msg[i], msg_name) = (void *)&peer_sa[i];
  1444. MSG_FIELD(msg[i], msg_namelen) = salen;
  1445. MSG_FIELD(msg[i], msg_iov) = &iovs[i];
  1446. MSG_FIELD(msg[i], msg_iovlen) = 1;
  1447. }
  1448. /* Got some data */
  1449. if (revents == EV_READ) {
  1450. ev_now_update_if_cheap (ctx->event_loop);
  1451. for (;;) {
  1452. #ifdef HAVE_RECVMMSG
  1453. r = recvmmsg (w->fd, msg, MSGVEC_LEN, 0, NULL);
  1454. #else
  1455. r = recvmsg (w->fd, msg, 0);
  1456. #endif
  1457. if (r == -1) {
  1458. if (errno == EINTR) {
  1459. continue;
  1460. }
  1461. else if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1462. return;
  1463. }
  1464. msg_err ("got error while reading from socket: %d, %s",
  1465. errno,
  1466. strerror (errno));
  1467. return;
  1468. }
  1469. #ifndef HAVE_RECVMMSG
  1470. msg_len = r; /* Save real length in bytes here */
  1471. r = 1; /* Assume that we have received a single message */
  1472. #endif
  1473. for (int i = 0; i < r; i ++) {
  1474. rspamd_inet_addr_t *client_addr;
  1475. if (MSG_FIELD(msg[i], msg_namelen) >= sizeof(struct sockaddr)) {
  1476. client_addr = rspamd_inet_address_from_sa(MSG_FIELD(msg[i], msg_name),
  1477. MSG_FIELD(msg[i], msg_namelen));
  1478. if (!rspamd_fuzzy_check_client (worker->ctx, client_addr)) {
  1479. /* Disallow forbidden clients silently */
  1480. rspamd_inet_address_free (client_addr);
  1481. continue;
  1482. }
  1483. }
  1484. else {
  1485. client_addr = NULL;
  1486. }
  1487. session = g_malloc0 (sizeof (*session));
  1488. REF_INIT_RETAIN (session, fuzzy_session_destroy);
  1489. session->worker = worker;
  1490. session->fd = w->fd;
  1491. session->ctx = ctx;
  1492. session->timestamp = ev_now (ctx->event_loop);
  1493. session->addr = client_addr;
  1494. worker->nconns++;
  1495. /* Each message can have its length in case of recvmmsg */
  1496. #ifdef HAVE_RECVMMSG
  1497. msg_len = msg[i].msg_len;
  1498. #endif
  1499. if (rspamd_fuzzy_cmd_from_wire (iovs[i].iov_base,
  1500. msg_len, session)) {
  1501. /* Check shingles count sanity */
  1502. rspamd_fuzzy_process_command (session);
  1503. }
  1504. else {
  1505. /* Discard input */
  1506. session->ctx->stat.invalid_requests ++;
  1507. msg_debug ("invalid fuzzy command of size %z received", r);
  1508. if (session->addr) {
  1509. nerrors = rspamd_lru_hash_lookup(session->ctx->errors_ips,
  1510. session->addr, -1);
  1511. if (nerrors == NULL) {
  1512. nerrors = g_malloc(sizeof(*nerrors));
  1513. *nerrors = 1;
  1514. rspamd_lru_hash_insert(session->ctx->errors_ips,
  1515. rspamd_inet_address_copy(session->addr, NULL),
  1516. nerrors, -1, -1);
  1517. }
  1518. else {
  1519. *nerrors = *nerrors + 1;
  1520. }
  1521. }
  1522. }
  1523. REF_RELEASE (session);
  1524. }
  1525. #ifdef HAVE_RECVMMSG
  1526. /* Stop reading as we are using recvmmsg instead of recvmsg */
  1527. break;
  1528. #endif
  1529. }
  1530. }
  1531. }
  1532. static gboolean
  1533. rspamd_fuzzy_storage_periodic_callback (void *ud)
  1534. {
  1535. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1536. if (ctx->updates_pending->len > 0) {
  1537. rspamd_fuzzy_process_updates_queue (ctx, local_db_name, FALSE);
  1538. return TRUE;
  1539. }
  1540. return FALSE;
  1541. }
  1542. static gboolean
  1543. rspamd_fuzzy_storage_sync (struct rspamd_main *rspamd_main,
  1544. struct rspamd_worker *worker, gint fd,
  1545. gint attached_fd,
  1546. struct rspamd_control_command *cmd,
  1547. gpointer ud)
  1548. {
  1549. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1550. struct rspamd_control_reply rep;
  1551. rep.reply.fuzzy_sync.status = 0;
  1552. rep.type = RSPAMD_CONTROL_FUZZY_SYNC;
  1553. if (ctx->backend && worker->index == 0) {
  1554. rspamd_fuzzy_process_updates_queue (ctx, local_db_name, FALSE);
  1555. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  1556. rspamd_fuzzy_storage_periodic_callback, ctx);
  1557. }
  1558. if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
  1559. msg_err ("cannot write reply to the control socket: %s",
  1560. strerror (errno));
  1561. }
  1562. return TRUE;
  1563. }
  1564. static gboolean
  1565. rspamd_fuzzy_storage_reload (struct rspamd_main *rspamd_main,
  1566. struct rspamd_worker *worker, gint fd,
  1567. gint attached_fd,
  1568. struct rspamd_control_command *cmd,
  1569. gpointer ud)
  1570. {
  1571. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1572. GError *err = NULL;
  1573. struct rspamd_control_reply rep;
  1574. msg_info ("reloading fuzzy storage after receiving reload command");
  1575. if (ctx->backend) {
  1576. /* Close backend and reopen it one more time */
  1577. rspamd_fuzzy_backend_close (ctx->backend);
  1578. }
  1579. memset (&rep, 0, sizeof (rep));
  1580. rep.type = RSPAMD_CONTROL_RELOAD;
  1581. if ((ctx->backend = rspamd_fuzzy_backend_create (ctx->event_loop,
  1582. worker->cf->options, rspamd_main->cfg,
  1583. &err)) == NULL) {
  1584. msg_err ("cannot open backend after reload: %e", err);
  1585. rep.reply.reload.status = err->code;
  1586. g_error_free (err);
  1587. }
  1588. else {
  1589. rep.reply.reload.status = 0;
  1590. }
  1591. if (ctx->backend && worker->index == 0) {
  1592. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  1593. rspamd_fuzzy_storage_periodic_callback, ctx);
  1594. }
  1595. if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
  1596. msg_err ("cannot write reply to the control socket: %s",
  1597. strerror (errno));
  1598. }
  1599. return TRUE;
  1600. }
  1601. static ucl_object_t *
  1602. rspamd_fuzzy_storage_stat_key (struct fuzzy_key_stat *key_stat)
  1603. {
  1604. ucl_object_t *res;
  1605. res = ucl_object_typed_new (UCL_OBJECT);
  1606. ucl_object_insert_key (res, ucl_object_fromint (key_stat->checked),
  1607. "checked", 0, false);
  1608. ucl_object_insert_key (res, ucl_object_fromdouble(key_stat->checked_ctr.mean),
  1609. "checked_per_hour", 0, false);
  1610. ucl_object_insert_key (res, ucl_object_fromint (key_stat->matched),
  1611. "matched", 0, false);
  1612. ucl_object_insert_key (res, ucl_object_fromdouble(key_stat->matched_ctr.mean),
  1613. "matched_per_hour", 0, false);
  1614. ucl_object_insert_key (res, ucl_object_fromint (key_stat->added),
  1615. "added", 0, false);
  1616. ucl_object_insert_key (res, ucl_object_fromint (key_stat->deleted),
  1617. "deleted", 0, false);
  1618. ucl_object_insert_key (res, ucl_object_fromint (key_stat->errors),
  1619. "errors", 0, false);
  1620. return res;
  1621. }
  1622. static ucl_object_t *
  1623. rspamd_fuzzy_stat_to_ucl (struct rspamd_fuzzy_storage_ctx *ctx, gboolean ip_stat)
  1624. {
  1625. struct fuzzy_key_stat *key_stat;
  1626. GHashTableIter it;
  1627. struct fuzzy_key *fuzzy_key;
  1628. ucl_object_t *obj, *keys_obj, *elt, *ip_elt, *ip_cur;
  1629. gpointer k, v;
  1630. gint i;
  1631. gchar keyname[17];
  1632. obj = ucl_object_typed_new (UCL_OBJECT);
  1633. keys_obj = ucl_object_typed_new (UCL_OBJECT);
  1634. g_hash_table_iter_init (&it, ctx->keys);
  1635. while (g_hash_table_iter_next (&it, &k, &v)) {
  1636. fuzzy_key = v;
  1637. key_stat = fuzzy_key->stat;
  1638. if (key_stat) {
  1639. rspamd_snprintf (keyname, sizeof (keyname), "%8bs", k);
  1640. elt = rspamd_fuzzy_storage_stat_key (key_stat);
  1641. if (key_stat->last_ips && ip_stat) {
  1642. i = 0;
  1643. ip_elt = ucl_object_typed_new (UCL_OBJECT);
  1644. while ((i = rspamd_lru_hash_foreach (key_stat->last_ips,
  1645. i, &k, &v)) != -1) {
  1646. ip_cur = rspamd_fuzzy_storage_stat_key (v);
  1647. ucl_object_insert_key (ip_elt, ip_cur,
  1648. rspamd_inet_address_to_string (k), 0, true);
  1649. }
  1650. ucl_object_insert_key (elt, ip_elt, "ips", 0, false);
  1651. }
  1652. ucl_object_insert_key (elt,
  1653. rspamd_keypair_to_ucl (fuzzy_key->key, RSPAMD_KEYPAIR_DUMP_NO_SECRET|RSPAMD_KEYPAIR_DUMP_FLATTENED),
  1654. "keypair", 0, false);
  1655. ucl_object_insert_key (keys_obj, elt, keyname, 0, true);
  1656. }
  1657. }
  1658. ucl_object_insert_key (obj, keys_obj, "keys", 0, false);
  1659. /* Now generic stats */
  1660. ucl_object_insert_key (obj,
  1661. ucl_object_fromint (ctx->stat.fuzzy_hashes),
  1662. "fuzzy_stored",
  1663. 0,
  1664. false);
  1665. ucl_object_insert_key (obj,
  1666. ucl_object_fromint (ctx->stat.fuzzy_hashes_expired),
  1667. "fuzzy_expired",
  1668. 0,
  1669. false);
  1670. ucl_object_insert_key (obj,
  1671. ucl_object_fromint (ctx->stat.invalid_requests),
  1672. "invalid_requests",
  1673. 0,
  1674. false);
  1675. ucl_object_insert_key (obj,
  1676. ucl_object_fromint (ctx->stat.delayed_hashes),
  1677. "delayed_hashes",
  1678. 0,
  1679. false);
  1680. if (ctx->errors_ips && ip_stat) {
  1681. i = 0;
  1682. ip_elt = ucl_object_typed_new (UCL_OBJECT);
  1683. while ((i = rspamd_lru_hash_foreach (ctx->errors_ips, i, &k, &v)) != -1) {
  1684. ucl_object_insert_key (ip_elt,
  1685. ucl_object_fromint (*(guint64 *)v),
  1686. rspamd_inet_address_to_string (k), 0, true);
  1687. }
  1688. ucl_object_insert_key (obj,
  1689. ip_elt,
  1690. "errors_ips",
  1691. 0,
  1692. false);
  1693. }
  1694. /* Checked by epoch */
  1695. elt = ucl_object_typed_new (UCL_ARRAY);
  1696. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1697. ucl_array_append (elt,
  1698. ucl_object_fromint (ctx->stat.fuzzy_hashes_checked[i]));
  1699. }
  1700. ucl_object_insert_key (obj, elt, "fuzzy_checked", 0, false);
  1701. /* Shingles by epoch */
  1702. elt = ucl_object_typed_new (UCL_ARRAY);
  1703. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1704. ucl_array_append (elt,
  1705. ucl_object_fromint (ctx->stat.fuzzy_shingles_checked[i]));
  1706. }
  1707. ucl_object_insert_key (obj, elt, "fuzzy_shingles", 0, false);
  1708. /* Matched by epoch */
  1709. elt = ucl_object_typed_new (UCL_ARRAY);
  1710. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1711. ucl_array_append (elt,
  1712. ucl_object_fromint (ctx->stat.fuzzy_hashes_found[i]));
  1713. }
  1714. ucl_object_insert_key (obj, elt, "fuzzy_found", 0, false);
  1715. return obj;
  1716. }
  1717. static int
  1718. lua_fuzzy_add_pre_handler (lua_State *L)
  1719. {
  1720. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  1721. rspamd_lua_check_udata (L, 1, "rspamd{worker}");
  1722. struct rspamd_fuzzy_storage_ctx *ctx;
  1723. if (!pwrk) {
  1724. return luaL_error (L, "invalid arguments, worker + function are expected");
  1725. }
  1726. wrk = *pwrk;
  1727. if (wrk && lua_isfunction (L, 2)) {
  1728. ctx = (struct rspamd_fuzzy_storage_ctx *)wrk->ctx;
  1729. if (ctx->lua_pre_handler_cbref != -1) {
  1730. /* Should not happen */
  1731. luaL_unref (L, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  1732. }
  1733. lua_pushvalue (L, 2);
  1734. ctx->lua_pre_handler_cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  1735. }
  1736. else {
  1737. return luaL_error (L, "invalid arguments, worker + function are expected");
  1738. }
  1739. return 0;
  1740. }
  1741. static int
  1742. lua_fuzzy_add_post_handler (lua_State *L)
  1743. {
  1744. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  1745. rspamd_lua_check_udata (L, 1, "rspamd{worker}");
  1746. struct rspamd_fuzzy_storage_ctx *ctx;
  1747. if (!pwrk) {
  1748. return luaL_error (L, "invalid arguments, worker + function are expected");
  1749. }
  1750. wrk = *pwrk;
  1751. if (wrk && lua_isfunction (L, 2)) {
  1752. ctx = (struct rspamd_fuzzy_storage_ctx *)wrk->ctx;
  1753. if (ctx->lua_post_handler_cbref != -1) {
  1754. /* Should not happen */
  1755. luaL_unref (L, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  1756. }
  1757. lua_pushvalue (L, 2);
  1758. ctx->lua_post_handler_cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  1759. }
  1760. else {
  1761. return luaL_error (L, "invalid arguments, worker + function are expected");
  1762. }
  1763. return 0;
  1764. }
  1765. static int
  1766. lua_fuzzy_add_blacklist_handler (lua_State *L)
  1767. {
  1768. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  1769. rspamd_lua_check_udata (L, 1, "rspamd{worker}");
  1770. struct rspamd_fuzzy_storage_ctx *ctx;
  1771. if (!pwrk) {
  1772. return luaL_error (L, "invalid arguments, worker + function are expected");
  1773. }
  1774. wrk = *pwrk;
  1775. if (wrk && lua_isfunction (L, 2)) {
  1776. ctx = (struct rspamd_fuzzy_storage_ctx *)wrk->ctx;
  1777. if (ctx->lua_blacklist_cbref != -1) {
  1778. /* Should not happen */
  1779. luaL_unref (L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  1780. }
  1781. lua_pushvalue (L, 2);
  1782. ctx->lua_blacklist_cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  1783. }
  1784. else {
  1785. return luaL_error (L, "invalid arguments, worker + function are expected");
  1786. }
  1787. return 0;
  1788. }
  1789. static gboolean
  1790. rspamd_fuzzy_storage_stat (struct rspamd_main *rspamd_main,
  1791. struct rspamd_worker *worker, gint fd,
  1792. gint attached_fd,
  1793. struct rspamd_control_command *cmd,
  1794. gpointer ud)
  1795. {
  1796. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1797. struct rspamd_control_reply rep;
  1798. ucl_object_t *obj;
  1799. struct ucl_emitter_functions *emit_subr;
  1800. guchar fdspace[CMSG_SPACE(sizeof (int))];
  1801. struct iovec iov;
  1802. struct msghdr msg;
  1803. struct cmsghdr *cmsg;
  1804. gint outfd = -1;
  1805. gchar tmppath[PATH_MAX];
  1806. memset (&rep, 0, sizeof (rep));
  1807. rep.type = RSPAMD_CONTROL_FUZZY_STAT;
  1808. rspamd_snprintf (tmppath, sizeof (tmppath), "%s%c%s-XXXXXXXXXX",
  1809. rspamd_main->cfg->temp_dir, G_DIR_SEPARATOR, "fuzzy-stat");
  1810. if ((outfd = mkstemp (tmppath)) == -1) {
  1811. rep.reply.fuzzy_stat.status = errno;
  1812. msg_info_main ("cannot make temporary stat file for fuzzy stat: %s",
  1813. strerror (errno));
  1814. }
  1815. else {
  1816. rep.reply.fuzzy_stat.status = 0;
  1817. memcpy (rep.reply.fuzzy_stat.storage_id,
  1818. rspamd_fuzzy_backend_id (ctx->backend),
  1819. sizeof (rep.reply.fuzzy_stat.storage_id));
  1820. obj = rspamd_fuzzy_stat_to_ucl (ctx, TRUE);
  1821. emit_subr = ucl_object_emit_fd_funcs (outfd);
  1822. ucl_object_emit_full (obj, UCL_EMIT_JSON_COMPACT, emit_subr, NULL);
  1823. ucl_object_emit_funcs_free (emit_subr);
  1824. ucl_object_unref (obj);
  1825. /* Rewind output file */
  1826. close (outfd);
  1827. outfd = open (tmppath, O_RDONLY);
  1828. unlink (tmppath);
  1829. }
  1830. /* Now we can send outfd and status message */
  1831. memset (&msg, 0, sizeof (msg));
  1832. /* Attach fd to the message */
  1833. if (outfd != -1) {
  1834. memset (fdspace, 0, sizeof (fdspace));
  1835. msg.msg_control = fdspace;
  1836. msg.msg_controllen = sizeof (fdspace);
  1837. cmsg = CMSG_FIRSTHDR (&msg);
  1838. if (cmsg) {
  1839. cmsg->cmsg_level = SOL_SOCKET;
  1840. cmsg->cmsg_type = SCM_RIGHTS;
  1841. cmsg->cmsg_len = CMSG_LEN (sizeof (int));
  1842. memcpy (CMSG_DATA (cmsg), &outfd, sizeof (int));
  1843. }
  1844. }
  1845. iov.iov_base = &rep;
  1846. iov.iov_len = sizeof (rep);
  1847. msg.msg_iov = &iov;
  1848. msg.msg_iovlen = 1;
  1849. if (sendmsg (fd, &msg, 0) == -1) {
  1850. msg_err_main ("cannot send fuzzy stat: %s", strerror (errno));
  1851. }
  1852. if (outfd != -1) {
  1853. close (outfd);
  1854. }
  1855. return TRUE;
  1856. }
  1857. static gboolean
  1858. fuzzy_parse_keypair (rspamd_mempool_t *pool,
  1859. const ucl_object_t *obj,
  1860. gpointer ud,
  1861. struct rspamd_rcl_section *section,
  1862. GError **err)
  1863. {
  1864. struct rspamd_rcl_struct_parser *pd = ud;
  1865. struct rspamd_fuzzy_storage_ctx *ctx;
  1866. struct rspamd_cryptobox_keypair *kp;
  1867. struct fuzzy_key_stat *keystat;
  1868. struct fuzzy_key *key;
  1869. const ucl_object_t *cur;
  1870. const guchar *pk;
  1871. ucl_object_iter_t it = NULL;
  1872. gboolean ret;
  1873. ctx = pd->user_struct;
  1874. pd->offset = G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, default_keypair);
  1875. /*
  1876. * Single key
  1877. */
  1878. if (ucl_object_type (obj) == UCL_STRING || ucl_object_type (obj)
  1879. == UCL_OBJECT) {
  1880. ret = rspamd_rcl_parse_struct_keypair (pool, obj, pd, section, err);
  1881. if (!ret) {
  1882. return ret;
  1883. }
  1884. /* Insert key to the hash table */
  1885. kp = ctx->default_keypair;
  1886. if (kp == NULL) {
  1887. return FALSE;
  1888. }
  1889. if (rspamd_keypair_alg (kp) != RSPAMD_CRYPTOBOX_MODE_25519 ||
  1890. rspamd_keypair_type (kp) != RSPAMD_KEYPAIR_KEX) {
  1891. return FALSE;
  1892. }
  1893. key = g_malloc0 (sizeof (*key));
  1894. key->key = kp;
  1895. keystat = g_malloc0 (sizeof (*keystat));
  1896. REF_INIT_RETAIN (keystat, fuzzy_key_stat_dtor);
  1897. /* Hash of ip -> fuzzy_key_stat */
  1898. keystat->last_ips = rspamd_lru_hash_new_full (1024,
  1899. (GDestroyNotify) rspamd_inet_address_free,
  1900. fuzzy_key_stat_unref,
  1901. rspamd_inet_address_hash, rspamd_inet_address_equal);
  1902. key->stat = keystat;
  1903. pk = rspamd_keypair_component (kp, RSPAMD_KEYPAIR_COMPONENT_PK,
  1904. NULL);
  1905. keystat->keypair = rspamd_keypair_ref(kp);
  1906. /* We map entries by pubkey in binary form for speed lookup */
  1907. g_hash_table_insert (ctx->keys, (gpointer)pk, key);
  1908. ctx->default_key = key;
  1909. const ucl_object_t *extensions = rspamd_keypair_get_extensions(kp);
  1910. if (extensions) {
  1911. const ucl_object_t *forbidden_ids = ucl_object_lookup (extensions, "forbidden_ids");
  1912. if (forbidden_ids && ucl_object_type (forbidden_ids) == UCL_ARRAY) {
  1913. key->forbidden_ids = kh_init(fuzzy_key_forbidden_ids);
  1914. while ((cur = ucl_object_iterate (forbidden_ids, &it, true)) != NULL) {
  1915. if (ucl_object_type(cur) == UCL_INT || ucl_object_type(cur) == UCL_FLOAT) {
  1916. int id = ucl_object_toint(cur);
  1917. int r;
  1918. kh_put(fuzzy_key_forbidden_ids, key->forbidden_ids, id, &r);
  1919. }
  1920. }
  1921. }
  1922. }
  1923. msg_debug_pool_check("loaded keypair %*xs", 8, pk);
  1924. }
  1925. else if (ucl_object_type (obj) == UCL_ARRAY) {
  1926. while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
  1927. if (!fuzzy_parse_keypair (pool, cur, pd, section, err)) {
  1928. msg_err_pool ("cannot parse keypair");
  1929. }
  1930. }
  1931. }
  1932. return TRUE;
  1933. }
  1934. static guint
  1935. fuzzy_kp_hash (gconstpointer p)
  1936. {
  1937. return *(guint *)p;
  1938. }
  1939. static gboolean
  1940. fuzzy_kp_equal (gconstpointer a, gconstpointer b)
  1941. {
  1942. const guchar *pa = a, *pb = b;
  1943. return (memcmp (pa, pb, RSPAMD_FUZZY_KEYLEN) == 0);
  1944. }
  1945. gpointer
  1946. init_fuzzy (struct rspamd_config *cfg)
  1947. {
  1948. struct rspamd_fuzzy_storage_ctx *ctx;
  1949. GQuark type;
  1950. type = g_quark_try_string ("fuzzy");
  1951. ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
  1952. sizeof (struct rspamd_fuzzy_storage_ctx));
  1953. ctx->magic = rspamd_fuzzy_storage_magic;
  1954. ctx->sync_timeout = DEFAULT_SYNC_TIMEOUT;
  1955. ctx->keypair_cache_size = DEFAULT_KEYPAIR_CACHE_SIZE;
  1956. ctx->lua_pre_handler_cbref = -1;
  1957. ctx->lua_post_handler_cbref = -1;
  1958. ctx->lua_blacklist_cbref = -1;
  1959. ctx->keys = g_hash_table_new_full (fuzzy_kp_hash, fuzzy_kp_equal,
  1960. NULL, fuzzy_key_dtor);
  1961. rspamd_mempool_add_destructor (cfg->cfg_pool,
  1962. (rspamd_mempool_destruct_t)g_hash_table_unref, ctx->keys);
  1963. ctx->errors_ips = rspamd_lru_hash_new_full (1024,
  1964. (GDestroyNotify) rspamd_inet_address_free, g_free,
  1965. rspamd_inet_address_hash, rspamd_inet_address_equal);
  1966. rspamd_mempool_add_destructor (cfg->cfg_pool,
  1967. (rspamd_mempool_destruct_t)rspamd_lru_hash_destroy, ctx->errors_ips);
  1968. ctx->cfg = cfg;
  1969. ctx->updates_maxfail = DEFAULT_UPDATES_MAXFAIL;
  1970. ctx->leaky_bucket_mask = DEFAULT_BUCKET_MASK;
  1971. ctx->leaky_bucket_ttl = DEFAULT_BUCKET_TTL;
  1972. ctx->max_buckets = DEFAULT_MAX_BUCKETS;
  1973. ctx->leaky_bucket_burst = NAN;
  1974. ctx->leaky_bucket_rate = NAN;
  1975. ctx->delay = NAN;
  1976. rspamd_rcl_register_worker_option (cfg,
  1977. type,
  1978. "sync",
  1979. rspamd_rcl_parse_struct_time,
  1980. ctx,
  1981. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  1982. sync_timeout),
  1983. RSPAMD_CL_FLAG_TIME_FLOAT,
  1984. "Time to perform database sync, default: "
  1985. G_STRINGIFY (DEFAULT_SYNC_TIMEOUT) " seconds");
  1986. rspamd_rcl_register_worker_option (cfg,
  1987. type,
  1988. "expire",
  1989. rspamd_rcl_parse_struct_time,
  1990. ctx,
  1991. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  1992. expire),
  1993. RSPAMD_CL_FLAG_TIME_FLOAT,
  1994. "Default expire time for hashes, default: "
  1995. G_STRINGIFY (DEFAULT_EXPIRE) " seconds");
  1996. rspamd_rcl_register_worker_option (cfg,
  1997. type,
  1998. "delay",
  1999. rspamd_rcl_parse_struct_time,
  2000. ctx,
  2001. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  2002. delay),
  2003. RSPAMD_CL_FLAG_TIME_FLOAT,
  2004. "Default delay time for hashes, default: not enabled");
  2005. rspamd_rcl_register_worker_option (cfg,
  2006. type,
  2007. "allow_update",
  2008. rspamd_rcl_parse_struct_ucl,
  2009. ctx,
  2010. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, update_map),
  2011. 0,
  2012. "Allow modifications from the following IP addresses");
  2013. rspamd_rcl_register_worker_option (cfg,
  2014. type,
  2015. "allow_update_keys",
  2016. rspamd_rcl_parse_struct_ucl,
  2017. ctx,
  2018. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, update_keys_map),
  2019. 0,
  2020. "Allow modifications for those using specific public keys");
  2021. rspamd_rcl_register_worker_option (cfg,
  2022. type,
  2023. "delay_whitelist",
  2024. rspamd_rcl_parse_struct_ucl,
  2025. ctx,
  2026. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, delay_whitelist_map),
  2027. 0,
  2028. "Disable delay check for the following IP addresses");
  2029. rspamd_rcl_register_worker_option (cfg,
  2030. type,
  2031. "keypair",
  2032. fuzzy_parse_keypair,
  2033. ctx,
  2034. 0,
  2035. RSPAMD_CL_FLAG_MULTIPLE,
  2036. "Encryption keypair (can be repeated for different keys)");
  2037. rspamd_rcl_register_worker_option (cfg,
  2038. type,
  2039. "keypair_cache_size",
  2040. rspamd_rcl_parse_struct_integer,
  2041. ctx,
  2042. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  2043. keypair_cache_size),
  2044. RSPAMD_CL_FLAG_UINT,
  2045. "Size of keypairs cache, default: "
  2046. G_STRINGIFY (DEFAULT_KEYPAIR_CACHE_SIZE));
  2047. rspamd_rcl_register_worker_option (cfg,
  2048. type,
  2049. "encrypted_only",
  2050. rspamd_rcl_parse_struct_boolean,
  2051. ctx,
  2052. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, encrypted_only),
  2053. 0,
  2054. "Allow encrypted requests only (and forbid all unknown keys or plaintext requests)");
  2055. rspamd_rcl_register_worker_option (cfg,
  2056. type,
  2057. "dedicated_update_worker",
  2058. rspamd_rcl_parse_struct_boolean,
  2059. ctx,
  2060. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, dedicated_update_worker),
  2061. 0,
  2062. "Use worker 0 for updates only");
  2063. rspamd_rcl_register_worker_option (cfg,
  2064. type,
  2065. "read_only",
  2066. rspamd_rcl_parse_struct_boolean,
  2067. ctx,
  2068. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, read_only),
  2069. 0,
  2070. "Work in read only mode");
  2071. rspamd_rcl_register_worker_option (cfg,
  2072. type,
  2073. "blocked",
  2074. rspamd_rcl_parse_struct_ucl,
  2075. ctx,
  2076. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, blocked_map),
  2077. 0,
  2078. "Block requests from specific networks");
  2079. rspamd_rcl_register_worker_option (cfg,
  2080. type,
  2081. "updates_maxfail",
  2082. rspamd_rcl_parse_struct_integer,
  2083. ctx,
  2084. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, updates_maxfail),
  2085. RSPAMD_CL_FLAG_UINT,
  2086. "Maximum number of updates to be failed before discarding");
  2087. rspamd_rcl_register_worker_option (cfg,
  2088. type,
  2089. "skip_hashes",
  2090. rspamd_rcl_parse_struct_ucl,
  2091. ctx,
  2092. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, skip_map),
  2093. 0,
  2094. "Skip specific hashes from the map");
  2095. /* Ratelimits */
  2096. rspamd_rcl_register_worker_option (cfg,
  2097. type,
  2098. "ratelimit_whitelist",
  2099. rspamd_rcl_parse_struct_ucl,
  2100. ctx,
  2101. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, ratelimit_whitelist_map),
  2102. 0,
  2103. "Skip specific addresses from rate limiting");
  2104. rspamd_rcl_register_worker_option (cfg,
  2105. type,
  2106. "ratelimit_max_buckets",
  2107. rspamd_rcl_parse_struct_integer,
  2108. ctx,
  2109. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, max_buckets),
  2110. RSPAMD_CL_FLAG_UINT,
  2111. "Maximum number of leaky buckets (default: " G_STRINGIFY(DEFAULT_MAX_BUCKETS) ")");
  2112. rspamd_rcl_register_worker_option (cfg,
  2113. type,
  2114. "ratelimit_network_mask",
  2115. rspamd_rcl_parse_struct_integer,
  2116. ctx,
  2117. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, leaky_bucket_mask),
  2118. RSPAMD_CL_FLAG_UINT,
  2119. "Network mask to apply for IPv4 rate addresses (default: " G_STRINGIFY(DEFAULT_BUCKET_MASK) ")");
  2120. rspamd_rcl_register_worker_option (cfg,
  2121. type,
  2122. "ratelimit_bucket_ttl",
  2123. rspamd_rcl_parse_struct_time,
  2124. ctx,
  2125. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, leaky_bucket_ttl),
  2126. RSPAMD_CL_FLAG_TIME_INTEGER,
  2127. "Time to live for ratelimit element (default: " G_STRINGIFY(DEFAULT_BUCKET_TTL) ")");
  2128. rspamd_rcl_register_worker_option (cfg,
  2129. type,
  2130. "ratelimit_rate",
  2131. rspamd_rcl_parse_struct_double,
  2132. ctx,
  2133. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, leaky_bucket_rate),
  2134. 0,
  2135. "Leak rate in requests per second");
  2136. rspamd_rcl_register_worker_option (cfg,
  2137. type,
  2138. "ratelimit_burst",
  2139. rspamd_rcl_parse_struct_double,
  2140. ctx,
  2141. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, leaky_bucket_burst),
  2142. 0,
  2143. "Peak value for ratelimit bucket");
  2144. rspamd_rcl_register_worker_option (cfg,
  2145. type,
  2146. "ratelimit_log_only",
  2147. rspamd_rcl_parse_struct_boolean,
  2148. ctx,
  2149. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, ratelimit_log_only),
  2150. 0,
  2151. "Don't really ban on ratelimit reaching, just log");
  2152. return ctx;
  2153. }
  2154. static void
  2155. rspamd_fuzzy_peer_io (EV_P_ ev_io *w, int revents)
  2156. {
  2157. struct fuzzy_peer_cmd cmd;
  2158. struct rspamd_fuzzy_storage_ctx *ctx =
  2159. (struct rspamd_fuzzy_storage_ctx *)w->data;
  2160. gssize r;
  2161. for (;;) {
  2162. r = read (w->fd, &cmd, sizeof (cmd));
  2163. if (r != sizeof (cmd)) {
  2164. if (errno == EINTR) {
  2165. continue;
  2166. }
  2167. if (errno != EAGAIN) {
  2168. msg_err ("cannot read command from peers: %s", strerror (errno));
  2169. }
  2170. break;
  2171. }
  2172. else {
  2173. g_array_append_val (ctx->updates_pending, cmd);
  2174. }
  2175. }
  2176. }
  2177. static void
  2178. fuzzy_peer_rep (struct rspamd_worker *worker,
  2179. struct rspamd_srv_reply *rep, gint rep_fd,
  2180. gpointer ud)
  2181. {
  2182. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2183. GList *cur;
  2184. struct rspamd_worker_listen_socket *ls;
  2185. struct rspamd_worker_accept_event *ac_ev;
  2186. ctx->peer_fd = rep_fd;
  2187. if (rep_fd == -1) {
  2188. msg_err ("cannot receive peer fd from the main process");
  2189. exit (EXIT_FAILURE);
  2190. }
  2191. else {
  2192. rspamd_socket_nonblocking (rep_fd);
  2193. }
  2194. msg_info ("got peer fd reply from the main process");
  2195. /* Start listening */
  2196. cur = worker->cf->listen_socks;
  2197. while (cur) {
  2198. ls = cur->data;
  2199. if (ls->fd != -1) {
  2200. msg_info ("start listening on %s",
  2201. rspamd_inet_address_to_string_pretty (ls->addr));
  2202. if (ls->type == RSPAMD_WORKER_SOCKET_UDP) {
  2203. ac_ev = g_malloc0 (sizeof (*ac_ev));
  2204. ac_ev->accept_ev.data = worker;
  2205. ac_ev->event_loop = ctx->event_loop;
  2206. ev_io_init (&ac_ev->accept_ev, accept_fuzzy_socket, ls->fd,
  2207. EV_READ);
  2208. ev_io_start (ctx->event_loop, &ac_ev->accept_ev);
  2209. DL_APPEND (worker->accept_events, ac_ev);
  2210. }
  2211. else {
  2212. /* We allow TCP listeners only for a update worker */
  2213. g_assert_not_reached ();
  2214. }
  2215. }
  2216. cur = g_list_next (cur);
  2217. }
  2218. if (ctx->peer_fd != -1) {
  2219. if (worker->index == 0) {
  2220. /* Listen for peer requests */
  2221. shutdown (ctx->peer_fd, SHUT_WR);
  2222. ctx->peer_ev.data = ctx;
  2223. ev_io_init (&ctx->peer_ev, rspamd_fuzzy_peer_io, ctx->peer_fd, EV_READ);
  2224. ev_io_start (ctx->event_loop, &ctx->peer_ev);
  2225. }
  2226. else {
  2227. shutdown (ctx->peer_fd, SHUT_RD);
  2228. }
  2229. }
  2230. }
  2231. /*
  2232. * Start worker process
  2233. */
  2234. __attribute__((noreturn))
  2235. void
  2236. start_fuzzy (struct rspamd_worker *worker)
  2237. {
  2238. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  2239. GError *err = NULL;
  2240. struct rspamd_srv_command srv_cmd;
  2241. struct rspamd_config *cfg = worker->srv->cfg;
  2242. g_assert (rspamd_worker_check_context (worker->ctx, rspamd_fuzzy_storage_magic));
  2243. ctx->event_loop = rspamd_prepare_worker (worker,
  2244. "fuzzy",
  2245. NULL);
  2246. ctx->peer_fd = -1;
  2247. ctx->worker = worker;
  2248. ctx->cfg = worker->srv->cfg;
  2249. ctx->resolver = rspamd_dns_resolver_init (worker->srv->logger,
  2250. ctx->event_loop,
  2251. worker->srv->cfg);
  2252. rspamd_upstreams_library_config (worker->srv->cfg, ctx->cfg->ups_ctx,
  2253. ctx->event_loop, ctx->resolver->r);
  2254. /* Since this worker uses maps it needs a valid HTTP context */
  2255. ctx->http_ctx = rspamd_http_context_create (ctx->cfg, ctx->event_loop,
  2256. ctx->cfg->ups_ctx);
  2257. if (ctx->keypair_cache_size > 0) {
  2258. /* Create keypairs cache */
  2259. ctx->keypair_cache = rspamd_keypair_cache_new (ctx->keypair_cache_size);
  2260. }
  2261. if ((ctx->backend = rspamd_fuzzy_backend_create (ctx->event_loop,
  2262. worker->cf->options, cfg, &err)) == NULL) {
  2263. msg_err ("cannot open backend: %e", err);
  2264. if (err) {
  2265. g_error_free (err);
  2266. }
  2267. exit (EXIT_SUCCESS);
  2268. }
  2269. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_count_callback, ctx);
  2270. if (worker->index == 0) {
  2271. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  2272. sizeof (struct fuzzy_peer_cmd), 1024);
  2273. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  2274. rspamd_fuzzy_storage_periodic_callback, ctx);
  2275. if (ctx->dedicated_update_worker && worker->cf->count > 1) {
  2276. msg_info_config ("stop serving clients request in dedicated update mode");
  2277. rspamd_worker_stop_accept (worker);
  2278. GList *cur = worker->cf->listen_socks;
  2279. while (cur) {
  2280. struct rspamd_worker_listen_socket *ls =
  2281. (struct rspamd_worker_listen_socket *)cur->data;
  2282. if (ls->fd != -1) {
  2283. close (ls->fd);
  2284. }
  2285. cur = g_list_next (cur);
  2286. }
  2287. }
  2288. }
  2289. ctx->stat_ev.data = ctx;
  2290. ev_timer_init (&ctx->stat_ev, rspamd_fuzzy_stat_callback, ctx->sync_timeout,
  2291. ctx->sync_timeout);
  2292. ev_timer_start (ctx->event_loop, &ctx->stat_ev);
  2293. /* Register custom reload and stat commands for the control socket */
  2294. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_RELOAD,
  2295. rspamd_fuzzy_storage_reload, ctx);
  2296. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_STAT,
  2297. rspamd_fuzzy_storage_stat, ctx);
  2298. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_SYNC,
  2299. rspamd_fuzzy_storage_sync, ctx);
  2300. if (ctx->update_map != NULL) {
  2301. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->update_map,
  2302. "Allow fuzzy updates from specified addresses",
  2303. &ctx->update_ips, NULL, worker, "fuzzy update");
  2304. }
  2305. if (ctx->update_keys_map != NULL) {
  2306. struct rspamd_map *m;
  2307. if ((m = rspamd_map_add_from_ucl (worker->srv->cfg, ctx->update_keys_map,
  2308. "Allow fuzzy updates from specified public keys",
  2309. rspamd_kv_list_read,
  2310. rspamd_kv_list_fin,
  2311. rspamd_kv_list_dtor,
  2312. (void **)&ctx->update_keys, worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2313. msg_warn_config ("cannot load allow keys map from %s",
  2314. ucl_object_tostring (ctx->update_keys_map));
  2315. }
  2316. else {
  2317. m->active_http = TRUE;
  2318. }
  2319. }
  2320. if (ctx->skip_map != NULL) {
  2321. struct rspamd_map *m;
  2322. if ((m = rspamd_map_add_from_ucl (cfg, ctx->skip_map,
  2323. "Skip hashes",
  2324. rspamd_kv_list_read,
  2325. rspamd_kv_list_fin,
  2326. rspamd_kv_list_dtor,
  2327. (void **)&ctx->skip_hashes,
  2328. worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2329. msg_warn_config ("cannot load hashes list from %s",
  2330. ucl_object_tostring (ctx->skip_map));
  2331. }
  2332. else {
  2333. m->active_http = TRUE;
  2334. }
  2335. }
  2336. if (ctx->blocked_map != NULL) {
  2337. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->blocked_map,
  2338. "Block fuzzy requests from the specific IPs",
  2339. &ctx->blocked_ips,
  2340. NULL,
  2341. worker, "fuzzy blocked");
  2342. }
  2343. /* Create radix trees */
  2344. if (ctx->ratelimit_whitelist_map != NULL) {
  2345. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->ratelimit_whitelist_map,
  2346. "Skip ratelimits from specific ip addresses/networks",
  2347. &ctx->ratelimit_whitelist,
  2348. NULL,
  2349. worker, "fuzzy ratelimit whitelist");
  2350. }
  2351. if (!isnan (ctx->delay) && ctx->delay_whitelist_map != NULL) {
  2352. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->delay_whitelist_map,
  2353. "Skip delay from the following ips",
  2354. &ctx->delay_whitelist, NULL, worker,
  2355. "fuzzy delayed whitelist");
  2356. }
  2357. /* Ratelimits */
  2358. if (!isnan (ctx->leaky_bucket_rate) && !isnan (ctx->leaky_bucket_burst)) {
  2359. ctx->ratelimit_buckets = rspamd_lru_hash_new_full (ctx->max_buckets,
  2360. NULL, fuzzy_rl_bucket_free,
  2361. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2362. }
  2363. /* Maps events */
  2364. ctx->resolver = rspamd_dns_resolver_init (worker->srv->logger,
  2365. ctx->event_loop,
  2366. worker->srv->cfg);
  2367. rspamd_map_watch (worker->srv->cfg, ctx->event_loop,
  2368. ctx->resolver, worker, RSPAMD_MAP_WATCH_WORKER);
  2369. /* Get peer pipe */
  2370. memset (&srv_cmd, 0, sizeof (srv_cmd));
  2371. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  2372. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  2373. srv_cmd.cmd.spair.pair_num = worker->index;
  2374. memset (srv_cmd.cmd.spair.pair_id, 0, sizeof (srv_cmd.cmd.spair.pair_id));
  2375. /* 6 bytes of id (including \0) and bind_conf id */
  2376. G_STATIC_ASSERT (sizeof (srv_cmd.cmd.spair.pair_id) >=
  2377. sizeof ("fuzzy") + sizeof (guint64));
  2378. memcpy (srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof ("fuzzy"));
  2379. /* Distinguish workers from each others... */
  2380. if (worker->cf->bind_conf && worker->cf->bind_conf->bind_line) {
  2381. guint64 bind_hash = rspamd_cryptobox_fast_hash (worker->cf->bind_conf->bind_line,
  2382. strlen (worker->cf->bind_conf->bind_line), 0xdeadbabe);
  2383. /* 8 more bytes */
  2384. memcpy (srv_cmd.cmd.spair.pair_id + sizeof ("fuzzy"), &bind_hash,
  2385. sizeof (bind_hash));
  2386. }
  2387. rspamd_srv_send_command (worker, ctx->event_loop, &srv_cmd, -1,
  2388. fuzzy_peer_rep, ctx);
  2389. /*
  2390. * Extra fields available for this particular worker
  2391. */
  2392. luaL_Reg fuzzy_lua_reg = {
  2393. .name = "add_fuzzy_pre_handler",
  2394. .func = lua_fuzzy_add_pre_handler,
  2395. };
  2396. rspamd_lua_add_metamethod (ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2397. fuzzy_lua_reg = (luaL_Reg){
  2398. .name = "add_fuzzy_post_handler",
  2399. .func = lua_fuzzy_add_post_handler,
  2400. };
  2401. rspamd_lua_add_metamethod (ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2402. fuzzy_lua_reg = (luaL_Reg){
  2403. .name = "add_fuzzy_blacklist_handler",
  2404. .func = lua_fuzzy_add_blacklist_handler,
  2405. };
  2406. rspamd_lua_add_metamethod (ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2407. rspamd_lua_run_postloads (ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  2408. worker);
  2409. ev_loop (ctx->event_loop, 0);
  2410. rspamd_worker_block_signals ();
  2411. if (ctx->peer_fd != -1) {
  2412. if (worker->index == 0) {
  2413. ev_io_stop (ctx->event_loop, &ctx->peer_ev);
  2414. }
  2415. close (ctx->peer_fd);
  2416. }
  2417. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  2418. msg_info_config ("start another event loop to sync fuzzy storage");
  2419. if (rspamd_fuzzy_process_updates_queue (ctx, local_db_name, TRUE)) {
  2420. ev_loop (ctx->event_loop, 0);
  2421. msg_info_config ("sync cycle is done");
  2422. }
  2423. else {
  2424. msg_info_config ("no need to sync");
  2425. }
  2426. }
  2427. rspamd_fuzzy_backend_close (ctx->backend);
  2428. if (worker->index == 0) {
  2429. g_array_free (ctx->updates_pending, TRUE);
  2430. ctx->updates_pending = NULL;
  2431. }
  2432. if (ctx->keypair_cache) {
  2433. rspamd_keypair_cache_destroy (ctx->keypair_cache);
  2434. }
  2435. if (ctx->ratelimit_buckets) {
  2436. rspamd_lru_hash_destroy (ctx->ratelimit_buckets);
  2437. }
  2438. if (ctx->lua_pre_handler_cbref != -1) {
  2439. luaL_unref (ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2440. }
  2441. if (ctx->lua_post_handler_cbref != -1) {
  2442. luaL_unref (ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2443. }
  2444. if (ctx->lua_blacklist_cbref != -1) {
  2445. luaL_unref (ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2446. }
  2447. REF_RELEASE (ctx->cfg);
  2448. rspamd_log_close (worker->srv->logger);
  2449. rspamd_unset_crash_handler (worker->srv);
  2450. exit (EXIT_SUCCESS);
  2451. }