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

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