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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  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. void
  1812. start_fuzzy (struct rspamd_worker *worker)
  1813. {
  1814. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  1815. GError *err = NULL;
  1816. struct rspamd_srv_command srv_cmd;
  1817. struct rspamd_config *cfg = worker->srv->cfg;
  1818. g_assert (rspamd_worker_check_context (worker->ctx, rspamd_fuzzy_storage_magic));
  1819. ctx->event_loop = rspamd_prepare_worker (worker,
  1820. "fuzzy",
  1821. NULL);
  1822. ctx->peer_fd = -1;
  1823. ctx->worker = worker;
  1824. ctx->cfg = worker->srv->cfg;
  1825. ctx->resolver = rspamd_dns_resolver_init (worker->srv->logger,
  1826. ctx->event_loop,
  1827. worker->srv->cfg);
  1828. rspamd_upstreams_library_config (worker->srv->cfg, ctx->cfg->ups_ctx,
  1829. ctx->event_loop, ctx->resolver->r);
  1830. /* Since this worker uses maps it needs a valid HTTP context */
  1831. ctx->http_ctx = rspamd_http_context_create (ctx->cfg, ctx->event_loop,
  1832. ctx->cfg->ups_ctx);
  1833. if (ctx->keypair_cache_size > 0) {
  1834. /* Create keypairs cache */
  1835. ctx->keypair_cache = rspamd_keypair_cache_new (ctx->keypair_cache_size);
  1836. }
  1837. if ((ctx->backend = rspamd_fuzzy_backend_create (ctx->event_loop,
  1838. worker->cf->options, cfg, &err)) == NULL) {
  1839. msg_err ("cannot open backend: %e", err);
  1840. if (err) {
  1841. g_error_free (err);
  1842. }
  1843. exit (EXIT_SUCCESS);
  1844. }
  1845. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_count_callback, ctx);
  1846. if (worker->index == 0) {
  1847. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  1848. sizeof (struct fuzzy_peer_cmd), 1024);
  1849. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  1850. rspamd_fuzzy_storage_periodic_callback, ctx);
  1851. }
  1852. ctx->stat_ev.data = ctx;
  1853. ev_timer_init (&ctx->stat_ev, rspamd_fuzzy_stat_callback, ctx->sync_timeout,
  1854. ctx->sync_timeout);
  1855. ev_timer_start (ctx->event_loop, &ctx->stat_ev);
  1856. /* Register custom reload and stat commands for the control socket */
  1857. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_RELOAD,
  1858. rspamd_fuzzy_storage_reload, ctx);
  1859. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_STAT,
  1860. rspamd_fuzzy_storage_stat, ctx);
  1861. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_SYNC,
  1862. rspamd_fuzzy_storage_sync, ctx);
  1863. /* Create radix trees */
  1864. if (ctx->update_map != NULL) {
  1865. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->update_map,
  1866. "Allow fuzzy updates from specified addresses",
  1867. &ctx->update_ips, NULL, worker);
  1868. }
  1869. if (ctx->skip_map != NULL) {
  1870. struct rspamd_map *m;
  1871. if ((m = rspamd_map_add_from_ucl (cfg, ctx->skip_map,
  1872. "Skip hashes",
  1873. rspamd_kv_list_read,
  1874. rspamd_kv_list_fin,
  1875. rspamd_kv_list_dtor,
  1876. (void **)&ctx->skip_hashes,
  1877. worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  1878. msg_warn_config ("cannot load hashes list from %s",
  1879. ucl_object_tostring (ctx->skip_map));
  1880. }
  1881. else {
  1882. m->active_http = TRUE;
  1883. }
  1884. }
  1885. if (ctx->blocked_map != NULL) {
  1886. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->blocked_map,
  1887. "Block fuzzy requests from the specific IPs",
  1888. &ctx->blocked_ips,
  1889. NULL,
  1890. worker);
  1891. }
  1892. /* Create radix trees */
  1893. if (ctx->ratelimit_whitelist_map != NULL) {
  1894. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->ratelimit_whitelist_map,
  1895. "Skip ratelimits from specific ip addresses/networks",
  1896. &ctx->ratelimit_whitelist,
  1897. NULL,
  1898. worker);
  1899. }
  1900. /* Ratelimits */
  1901. if (!isnan (ctx->leaky_bucket_rate) && !isnan (ctx->leaky_bucket_burst)) {
  1902. ctx->ratelimit_buckets = rspamd_lru_hash_new_full (ctx->max_buckets,
  1903. NULL, fuzzy_rl_bucket_free,
  1904. rspamd_inet_address_hash, rspamd_inet_address_equal);
  1905. }
  1906. /* Maps events */
  1907. ctx->resolver = rspamd_dns_resolver_init (worker->srv->logger,
  1908. ctx->event_loop,
  1909. worker->srv->cfg);
  1910. rspamd_map_watch (worker->srv->cfg, ctx->event_loop,
  1911. ctx->resolver, worker, RSPAMD_MAP_WATCH_WORKER);
  1912. /* Get peer pipe */
  1913. memset (&srv_cmd, 0, sizeof (srv_cmd));
  1914. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  1915. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  1916. srv_cmd.cmd.spair.pair_num = worker->index;
  1917. memset (srv_cmd.cmd.spair.pair_id, 0, sizeof (srv_cmd.cmd.spair.pair_id));
  1918. memcpy (srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof ("fuzzy"));
  1919. rspamd_srv_send_command (worker, ctx->event_loop, &srv_cmd, -1,
  1920. fuzzy_peer_rep, ctx);
  1921. luaL_Reg fuzzy_lua_reg = {
  1922. .name = "add_fuzzy_pre_handler",
  1923. .func = lua_fuzzy_add_pre_handler,
  1924. };
  1925. rspamd_lua_add_metamethod (ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  1926. fuzzy_lua_reg = (luaL_Reg){
  1927. .name = "add_fuzzy_post_handler",
  1928. .func = lua_fuzzy_add_post_handler,
  1929. };
  1930. rspamd_lua_add_metamethod (ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  1931. rspamd_lua_run_postloads (ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  1932. worker);
  1933. ev_loop (ctx->event_loop, 0);
  1934. rspamd_worker_block_signals ();
  1935. if (ctx->peer_fd != -1) {
  1936. if (worker->index == 0) {
  1937. ev_io_stop (ctx->event_loop, &ctx->peer_ev);
  1938. }
  1939. close (ctx->peer_fd);
  1940. }
  1941. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  1942. msg_info_config ("start another event loop to sync fuzzy storage");
  1943. if (rspamd_fuzzy_process_updates_queue (ctx, local_db_name, TRUE)) {
  1944. ev_loop (ctx->event_loop, 0);
  1945. msg_info_config ("sync cycle is done");
  1946. }
  1947. else {
  1948. msg_info_config ("no need to sync");
  1949. }
  1950. }
  1951. rspamd_fuzzy_backend_close (ctx->backend);
  1952. if (worker->index == 0) {
  1953. g_array_free (ctx->updates_pending, TRUE);
  1954. }
  1955. if (ctx->keypair_cache) {
  1956. rspamd_keypair_cache_destroy (ctx->keypair_cache);
  1957. }
  1958. if (ctx->ratelimit_buckets) {
  1959. rspamd_lru_hash_destroy (ctx->ratelimit_buckets);
  1960. }
  1961. if (ctx->lua_pre_handler_cbref != -1) {
  1962. luaL_unref (ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  1963. }
  1964. if (ctx->lua_post_handler_cbref != -1) {
  1965. luaL_unref (ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  1966. }
  1967. REF_RELEASE (ctx->cfg);
  1968. rspamd_log_close (worker->srv->logger);
  1969. exit (EXIT_SUCCESS);
  1970. }