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

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