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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038
  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 <src/libserver/fuzzy_wire.h>
  20. #include "config.h"
  21. #include "util.h"
  22. #include "rspamd.h"
  23. #include "map.h"
  24. #include "map_helpers.h"
  25. #include "fuzzy_wire.h"
  26. #include "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 "libserver/rspamd_control.h"
  36. #include "libutil/map_private.h"
  37. #include "libutil/hash.h"
  38. #include "libutil/http_private.h"
  39. #include "unix-std.h"
  40. /* Resync value in seconds */
  41. #define DEFAULT_SYNC_TIMEOUT 60.0
  42. #define DEFAULT_KEYPAIR_CACHE_SIZE 512
  43. #define DEFAULT_MASTER_TIMEOUT 10.0
  44. #define DEFAULT_UPDATES_MAXFAIL 3
  45. #define COOKIE_SIZE 128
  46. static const gchar *local_db_name = "local";
  47. #define msg_err_fuzzy_update(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \
  48. session->name, session->uid, \
  49. G_STRFUNC, \
  50. __VA_ARGS__)
  51. #define msg_warn_fuzzy_update(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  52. session->name, session->uid, \
  53. G_STRFUNC, \
  54. __VA_ARGS__)
  55. #define msg_info_fuzzy_update(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  56. session->name, session->uid, \
  57. G_STRFUNC, \
  58. __VA_ARGS__)
  59. #define msg_err_fuzzy_collection(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \
  60. "fuzzy_collection", session->uid, \
  61. G_STRFUNC, \
  62. __VA_ARGS__)
  63. #define msg_warn_fuzzy_collection(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  64. "fuzzy_collection", session->uid, \
  65. G_STRFUNC, \
  66. __VA_ARGS__)
  67. #define msg_info_fuzzy_collection(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  68. "fuzzy_collection", session->uid, \
  69. G_STRFUNC, \
  70. __VA_ARGS__)
  71. /* Init functions */
  72. gpointer init_fuzzy (struct rspamd_config *cfg);
  73. void start_fuzzy (struct rspamd_worker *worker);
  74. worker_t fuzzy_worker = {
  75. "fuzzy", /* Name */
  76. init_fuzzy, /* Init function */
  77. start_fuzzy, /* Start function */
  78. RSPAMD_WORKER_HAS_SOCKET,
  79. RSPAMD_WORKER_SOCKET_UDP|RSPAMD_WORKER_SOCKET_TCP, /* Both socket */
  80. RSPAMD_WORKER_VER /* Version info */
  81. };
  82. struct fuzzy_global_stat {
  83. guint64 fuzzy_hashes;
  84. /**< number of fuzzy hashes stored */
  85. guint64 fuzzy_hashes_expired;
  86. /**< number of fuzzy hashes expired */
  87. guint64 fuzzy_hashes_checked[RSPAMD_FUZZY_EPOCH_MAX];
  88. /**< amount of check requests for each epoch */
  89. guint64 fuzzy_shingles_checked[RSPAMD_FUZZY_EPOCH_MAX];
  90. /**< amount of shingle check requests for each epoch */
  91. guint64 fuzzy_hashes_found[RSPAMD_FUZZY_EPOCH_MAX];
  92. /**< amount of hashes found by epoch */
  93. guint64 invalid_requests;
  94. };
  95. struct fuzzy_key_stat {
  96. guint64 checked;
  97. guint64 matched;
  98. guint64 added;
  99. guint64 deleted;
  100. guint64 errors;
  101. rspamd_lru_hash_t *last_ips;
  102. };
  103. struct rspamd_fuzzy_mirror {
  104. gchar *name;
  105. struct upstream_list *u;
  106. struct rspamd_cryptobox_pubkey *key;
  107. };
  108. static const guint64 rspamd_fuzzy_storage_magic = 0x291a3253eb1b3ea5ULL;
  109. struct rspamd_fuzzy_storage_ctx {
  110. guint64 magic;
  111. /* Events base */
  112. struct event_base *ev_base;
  113. /* DNS resolver */
  114. struct rspamd_dns_resolver *resolver;
  115. /* Config */
  116. struct rspamd_config *cfg;
  117. /* END OF COMMON PART */
  118. struct fuzzy_global_stat stat;
  119. gdouble expire;
  120. gdouble sync_timeout;
  121. struct rspamd_radix_map_helper *update_ips;
  122. struct rspamd_radix_map_helper *master_ips;
  123. struct rspamd_radix_map_helper *blocked_ips;
  124. struct rspamd_cryptobox_keypair *sync_keypair;
  125. struct rspamd_cryptobox_pubkey *master_key;
  126. struct timeval master_io_tv;
  127. gdouble master_timeout;
  128. GPtrArray *mirrors;
  129. const ucl_object_t *update_map;
  130. const ucl_object_t *masters_map;
  131. const ucl_object_t *blocked_map;
  132. GHashTable *master_flags;
  133. guint keypair_cache_size;
  134. gint peer_fd;
  135. struct event peer_ev;
  136. struct event stat_ev;
  137. struct timeval stat_tv;
  138. /* Local keypair */
  139. struct rspamd_cryptobox_keypair *default_keypair; /* Bad clash, need for parse keypair */
  140. struct fuzzy_key *default_key;
  141. GHashTable *keys;
  142. gboolean encrypted_only;
  143. gboolean collection_mode;
  144. gboolean read_only;
  145. struct rspamd_cryptobox_keypair *collection_keypair;
  146. struct rspamd_cryptobox_pubkey *collection_sign_key;
  147. gchar *collection_id_file;
  148. struct rspamd_keypair_cache *keypair_cache;
  149. rspamd_lru_hash_t *errors_ips;
  150. struct rspamd_fuzzy_backend *backend;
  151. GArray *updates_pending;
  152. guint updates_failed;
  153. guint updates_maxfail;
  154. guint32 collection_id;
  155. struct rspamd_worker *worker;
  156. struct rspamd_http_connection_router *collection_rt;
  157. const ucl_object_t *skip_map;
  158. struct rspamd_hash_map_helper *skip_hashes;
  159. guchar cookie[COOKIE_SIZE];
  160. };
  161. enum fuzzy_cmd_type {
  162. CMD_NORMAL,
  163. CMD_SHINGLE,
  164. CMD_ENCRYPTED_NORMAL,
  165. CMD_ENCRYPTED_SHINGLE
  166. };
  167. struct fuzzy_session {
  168. struct rspamd_worker *worker;
  169. rspamd_inet_addr_t *addr;
  170. struct rspamd_fuzzy_storage_ctx *ctx;
  171. union {
  172. struct rspamd_fuzzy_encrypted_shingle_cmd enc_shingle;
  173. struct rspamd_fuzzy_encrypted_cmd enc_normal;
  174. struct rspamd_fuzzy_cmd normal;
  175. struct rspamd_fuzzy_shingle_cmd shingle;
  176. } cmd;
  177. struct rspamd_fuzzy_encrypted_reply reply;
  178. struct fuzzy_key_stat *ip_stat;
  179. enum rspamd_fuzzy_epoch epoch;
  180. enum fuzzy_cmd_type cmd_type;
  181. gint fd;
  182. guint64 time;
  183. struct event io;
  184. ref_entry_t ref;
  185. struct fuzzy_key_stat *key_stat;
  186. guchar nm[rspamd_cryptobox_MAX_NMBYTES];
  187. };
  188. struct fuzzy_peer_request {
  189. struct event io_ev;
  190. struct fuzzy_peer_cmd cmd;
  191. };
  192. struct fuzzy_key {
  193. struct rspamd_cryptobox_keypair *key;
  194. struct rspamd_cryptobox_pubkey *pk;
  195. struct fuzzy_key_stat *stat;
  196. };
  197. struct fuzzy_master_update_session {
  198. const gchar *name;
  199. gchar uid[16];
  200. struct rspamd_http_connection *conn;
  201. struct rspamd_http_message *msg;
  202. struct rspamd_fuzzy_storage_ctx *ctx;
  203. const gchar *src;
  204. gchar *psrc;
  205. rspamd_inet_addr_t *addr;
  206. gboolean replied;
  207. gint sock;
  208. };
  209. static void rspamd_fuzzy_write_reply (struct fuzzy_session *session);
  210. static gboolean
  211. rspamd_fuzzy_check_client (struct fuzzy_session *session, gboolean is_write)
  212. {
  213. if (session->ctx->blocked_ips != NULL) {
  214. if (rspamd_match_radix_map_addr (session->ctx->blocked_ips,
  215. session->addr) != NULL) {
  216. return FALSE;
  217. }
  218. }
  219. if (is_write) {
  220. if (session->ctx->read_only) {
  221. return FALSE;
  222. }
  223. if (session->ctx->update_ips != NULL) {
  224. if (rspamd_match_radix_map_addr (session->ctx->update_ips,
  225. session->addr) == NULL) {
  226. return FALSE;
  227. }
  228. else {
  229. return TRUE;
  230. }
  231. }
  232. return FALSE;
  233. }
  234. /* Non write */
  235. return TRUE;
  236. }
  237. static void
  238. fuzzy_key_stat_dtor (gpointer p)
  239. {
  240. struct fuzzy_key_stat *st = p;
  241. if (st->last_ips) {
  242. rspamd_lru_hash_destroy (st->last_ips);
  243. }
  244. }
  245. static void
  246. fuzzy_key_dtor (gpointer p)
  247. {
  248. struct fuzzy_key *key = p;
  249. if (key->stat) {
  250. fuzzy_key_stat_dtor (key->stat);
  251. }
  252. }
  253. static void
  254. fuzzy_count_callback (guint64 count, void *ud)
  255. {
  256. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  257. ctx->stat.fuzzy_hashes = count;
  258. }
  259. struct fuzzy_slave_connection {
  260. struct rspamd_cryptobox_keypair *local_key;
  261. struct rspamd_cryptobox_pubkey *remote_key;
  262. struct upstream *up;
  263. struct rspamd_http_connection *http_conn;
  264. struct rspamd_fuzzy_mirror *mirror;
  265. gint sock;
  266. };
  267. static void
  268. fuzzy_mirror_close_connection (struct fuzzy_slave_connection *conn)
  269. {
  270. if (conn) {
  271. if (conn->http_conn) {
  272. rspamd_http_connection_reset (conn->http_conn);
  273. rspamd_http_connection_unref (conn->http_conn);
  274. }
  275. close (conn->sock);
  276. g_free (conn);
  277. }
  278. }
  279. struct rspamd_fuzzy_updates_cbdata {
  280. struct rspamd_fuzzy_storage_ctx *ctx;
  281. struct rspamd_http_message *msg;
  282. struct fuzzy_slave_connection *conn;
  283. struct rspamd_fuzzy_mirror *m;
  284. GArray *updates_pending;
  285. };
  286. static void
  287. fuzzy_mirror_updates_version_cb (guint64 rev64, void *ud)
  288. {
  289. struct rspamd_fuzzy_updates_cbdata *cbdata = ud;
  290. struct fuzzy_peer_cmd *io_cmd;
  291. guint32 rev32 = rev64, len;
  292. const gchar *p;
  293. rspamd_fstring_t *reply;
  294. struct fuzzy_slave_connection *conn;
  295. struct rspamd_fuzzy_storage_ctx *ctx;
  296. struct rspamd_http_message *msg;
  297. struct rspamd_fuzzy_mirror *m;
  298. struct timeval tv;
  299. guint i;
  300. conn = cbdata->conn;
  301. ctx = cbdata->ctx;
  302. msg = cbdata->msg;
  303. m = cbdata->m;
  304. rev32 = GUINT32_TO_LE (rev32);
  305. len = sizeof (guint32) * 2; /* revision + last chunk */
  306. for (i = 0; i < cbdata->updates_pending->len; i ++) {
  307. io_cmd = &g_array_index (cbdata->updates_pending,
  308. struct fuzzy_peer_cmd, i);
  309. if (io_cmd->is_shingle) {
  310. len += sizeof (guint32) + sizeof (guint32) +
  311. sizeof (struct rspamd_fuzzy_shingle_cmd);
  312. }
  313. else {
  314. len += sizeof (guint32) + sizeof (guint32) +
  315. sizeof (struct rspamd_fuzzy_cmd);
  316. }
  317. }
  318. reply = rspamd_fstring_sized_new (len);
  319. reply = rspamd_fstring_append (reply, (const char *)&rev32,
  320. sizeof (rev32));
  321. for (i = 0; i < cbdata->updates_pending->len; i ++) {
  322. io_cmd = &g_array_index (cbdata->updates_pending, struct fuzzy_peer_cmd, i);
  323. if (io_cmd->is_shingle) {
  324. len = sizeof (guint32) +
  325. sizeof (struct rspamd_fuzzy_shingle_cmd);
  326. }
  327. else {
  328. len = sizeof (guint32) +
  329. sizeof (struct rspamd_fuzzy_cmd);
  330. }
  331. p = (const char *)io_cmd;
  332. len = GUINT32_TO_LE (len);
  333. reply = rspamd_fstring_append (reply, (const char *)&len, sizeof (len));
  334. reply = rspamd_fstring_append (reply, p, len);
  335. }
  336. /* Last chunk */
  337. len = 0;
  338. reply = rspamd_fstring_append (reply, (const char *)&len, sizeof (len));
  339. rspamd_http_message_set_body_from_fstring_steal (msg, reply);
  340. double_to_tv (ctx->sync_timeout, &tv);
  341. rspamd_http_connection_write_message (conn->http_conn,
  342. msg, NULL, NULL, conn,
  343. conn->sock,
  344. &tv, ctx->ev_base);
  345. msg_info ("send update request to %s", m->name);
  346. g_array_free (cbdata->updates_pending, TRUE);
  347. g_free (cbdata);
  348. }
  349. static void
  350. fuzzy_mirror_updates_to_http (struct rspamd_fuzzy_mirror *m,
  351. struct fuzzy_slave_connection *conn,
  352. struct rspamd_fuzzy_storage_ctx *ctx,
  353. struct rspamd_http_message *msg,
  354. GArray *updates)
  355. {
  356. struct rspamd_fuzzy_updates_cbdata *cbdata;
  357. cbdata = g_malloc (sizeof (*cbdata));
  358. cbdata->ctx = ctx;
  359. cbdata->msg = msg;
  360. cbdata->conn = conn;
  361. cbdata->m = m;
  362. /* Copy queue */
  363. cbdata->updates_pending = g_array_sized_new (FALSE, FALSE,
  364. sizeof (struct fuzzy_peer_cmd), updates->len);
  365. g_array_append_vals (cbdata->updates_pending, updates->data, updates->len);
  366. rspamd_fuzzy_backend_version (ctx->backend, local_db_name,
  367. fuzzy_mirror_updates_version_cb, cbdata);
  368. }
  369. static void
  370. fuzzy_mirror_error_handler (struct rspamd_http_connection *conn, GError *err)
  371. {
  372. struct fuzzy_slave_connection *bk_conn = conn->ud;
  373. msg_info ("abnormally closing connection from backend: %s:%s, "
  374. "error: %e",
  375. bk_conn->mirror->name,
  376. rspamd_inet_address_to_string (rspamd_upstream_addr (bk_conn->up)),
  377. err);
  378. fuzzy_mirror_close_connection (bk_conn);
  379. }
  380. static gint
  381. fuzzy_mirror_finish_handler (struct rspamd_http_connection *conn,
  382. struct rspamd_http_message *msg)
  383. {
  384. struct fuzzy_slave_connection *bk_conn = conn->ud;
  385. msg_info ("finished mirror connection to %s", bk_conn->mirror->name);
  386. fuzzy_mirror_close_connection (bk_conn);
  387. return 0;
  388. }
  389. static void
  390. rspamd_fuzzy_send_update_mirror (struct rspamd_fuzzy_storage_ctx *ctx,
  391. struct rspamd_fuzzy_mirror *m, GArray *updates)
  392. {
  393. struct fuzzy_slave_connection *conn;
  394. struct rspamd_http_message *msg;
  395. conn = g_malloc0 (sizeof (*conn));
  396. conn->up = rspamd_upstream_get (m->u,
  397. RSPAMD_UPSTREAM_MASTER_SLAVE, NULL, 0);
  398. conn->mirror = m;
  399. if (conn->up == NULL) {
  400. msg_err ("cannot select upstream for %s", m->name);
  401. return;
  402. }
  403. conn->sock = rspamd_inet_address_connect (
  404. rspamd_upstream_addr (conn->up),
  405. SOCK_STREAM, TRUE);
  406. if (conn->sock == -1) {
  407. msg_err ("cannot connect upstream for %s", m->name);
  408. rspamd_upstream_fail (conn->up, TRUE);
  409. return;
  410. }
  411. msg = rspamd_http_new_message (HTTP_REQUEST);
  412. rspamd_printf_fstring (&msg->url, "/update_v1/%s", m->name);
  413. conn->http_conn = rspamd_http_connection_new (NULL,
  414. fuzzy_mirror_error_handler,
  415. fuzzy_mirror_finish_handler,
  416. RSPAMD_HTTP_CLIENT_SIMPLE,
  417. RSPAMD_HTTP_CLIENT,
  418. ctx->keypair_cache,
  419. NULL);
  420. rspamd_http_connection_set_key (conn->http_conn,
  421. ctx->sync_keypair);
  422. msg->peer_key = rspamd_pubkey_ref (m->key);
  423. fuzzy_mirror_updates_to_http (m, conn, ctx, msg, updates);
  424. }
  425. struct rspamd_updates_cbdata {
  426. GArray *updates_pending;
  427. struct rspamd_fuzzy_storage_ctx *ctx;
  428. gchar *source;
  429. };
  430. static void
  431. fuzzy_update_version_callback (guint64 ver, void *ud)
  432. {
  433. msg_info ("updated fuzzy storage from %s: version: %d",
  434. (const char *)ud, (gint)ver);
  435. g_free (ud);
  436. }
  437. static void
  438. fuzzy_stat_count_callback (guint64 count, void *ud)
  439. {
  440. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  441. event_add (&ctx->stat_ev, &ctx->stat_tv);
  442. ctx->stat.fuzzy_hashes = count;
  443. }
  444. static void
  445. rspamd_fuzzy_stat_callback (gint fd, gshort what, gpointer ud)
  446. {
  447. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  448. event_del (&ctx->stat_ev);
  449. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_stat_count_callback, ctx);
  450. }
  451. static void
  452. rspamd_fuzzy_updates_cb (gboolean success,
  453. guint nadded,
  454. guint ndeleted,
  455. guint nextended,
  456. guint nignored,
  457. void *ud)
  458. {
  459. struct rspamd_updates_cbdata *cbdata = ud;
  460. struct rspamd_fuzzy_mirror *m;
  461. guint i;
  462. struct rspamd_fuzzy_storage_ctx *ctx;
  463. const gchar *source;
  464. ctx = cbdata->ctx;
  465. source = cbdata->source;
  466. if (success) {
  467. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_count_callback, ctx);
  468. if (ctx->updates_pending->len > 0) {
  469. for (i = 0; i < ctx->mirrors->len; i ++) {
  470. m = g_ptr_array_index (ctx->mirrors, i);
  471. rspamd_fuzzy_send_update_mirror (ctx, m,
  472. cbdata->updates_pending);
  473. }
  474. }
  475. msg_info ("successfully updated fuzzy storage: %d updates in queue; "
  476. "%d pending currently; "
  477. "%d added, %d deleted, %d extended, %d duplicates",
  478. cbdata->updates_pending->len,
  479. ctx->updates_pending->len,
  480. nadded, ndeleted, nextended, nignored);
  481. rspamd_fuzzy_backend_version (ctx->backend, source,
  482. fuzzy_update_version_callback, g_strdup (source));
  483. ctx->updates_failed = 0;
  484. }
  485. else {
  486. if (++ctx->updates_failed > ctx->updates_maxfail) {
  487. msg_err ("cannot commit update transaction to fuzzy backend, discard "
  488. "%ud updates after %d retries",
  489. cbdata->updates_pending->len,
  490. ctx->updates_maxfail);
  491. ctx->updates_failed = 0;
  492. }
  493. else {
  494. msg_err ("cannot commit update transaction to fuzzy backend, "
  495. "%ud updates are still left; %ud currently pending;"
  496. " %d updates left",
  497. cbdata->updates_pending->len,
  498. ctx->updates_pending->len,
  499. ctx->updates_maxfail - ctx->updates_failed);
  500. /* Move the remaining updates to ctx queue */
  501. g_array_append_vals (ctx->updates_pending,
  502. cbdata->updates_pending->data,
  503. cbdata->updates_pending->len);
  504. }
  505. }
  506. if (ctx->worker->wanna_die) {
  507. /* Plan exit */
  508. struct timeval tv;
  509. tv.tv_sec = 0;
  510. tv.tv_usec = 0;
  511. event_base_loopexit (ctx->ev_base, &tv);
  512. }
  513. g_array_free (cbdata->updates_pending, TRUE);
  514. g_free (cbdata->source);
  515. g_free (cbdata);
  516. }
  517. static void
  518. rspamd_fuzzy_process_updates_queue (struct rspamd_fuzzy_storage_ctx *ctx,
  519. const gchar *source, gboolean forced)
  520. {
  521. struct rspamd_updates_cbdata *cbdata;
  522. if ((forced ||ctx->updates_pending->len > 0)) {
  523. cbdata = g_malloc (sizeof (*cbdata));
  524. cbdata->ctx = ctx;
  525. cbdata->updates_pending = ctx->updates_pending;
  526. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  527. sizeof (struct fuzzy_peer_cmd),
  528. MAX (cbdata->updates_pending->len, 1024));
  529. cbdata->source = g_strdup (source);
  530. rspamd_fuzzy_backend_process_updates (ctx->backend,
  531. cbdata->updates_pending,
  532. source, rspamd_fuzzy_updates_cb, cbdata);
  533. }
  534. }
  535. static void
  536. rspamd_fuzzy_reply_io (gint fd, gshort what, gpointer d)
  537. {
  538. struct fuzzy_session *session = d;
  539. rspamd_fuzzy_write_reply (session);
  540. REF_RELEASE (session);
  541. }
  542. static void
  543. rspamd_fuzzy_write_reply (struct fuzzy_session *session)
  544. {
  545. gssize r;
  546. gsize len;
  547. gconstpointer data;
  548. if (session->cmd_type == CMD_ENCRYPTED_NORMAL ||
  549. session->cmd_type == CMD_ENCRYPTED_SHINGLE) {
  550. /* Encrypted reply */
  551. data = &session->reply;
  552. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  553. len = sizeof (session->reply);
  554. }
  555. else {
  556. len = sizeof (session->reply.hdr) + sizeof (session->reply.rep.v1);
  557. }
  558. }
  559. else {
  560. data = &session->reply.rep;
  561. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  562. len = sizeof (session->reply.rep);
  563. }
  564. else {
  565. len = sizeof (session->reply.rep.v1);
  566. }
  567. }
  568. r = rspamd_inet_address_sendto (session->fd, data, len, 0,
  569. session->addr);
  570. if (r == -1) {
  571. if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
  572. /* Grab reference to avoid early destruction */
  573. REF_RETAIN (session);
  574. event_set (&session->io, session->fd, EV_WRITE,
  575. rspamd_fuzzy_reply_io, session);
  576. event_base_set (session->ctx->ev_base, &session->io);
  577. event_add (&session->io, NULL);
  578. }
  579. else {
  580. msg_err ("error while writing reply: %s", strerror (errno));
  581. }
  582. }
  583. }
  584. static void
  585. fuzzy_peer_send_io (gint fd, gshort what, gpointer d)
  586. {
  587. struct fuzzy_peer_request *up_req = d;
  588. gssize r;
  589. r = write (fd, &up_req->cmd, sizeof (up_req->cmd));
  590. if (r != sizeof (up_req->cmd)) {
  591. msg_err ("cannot send update request to the peer: %s", strerror (errno));
  592. }
  593. event_del (&up_req->io_ev);
  594. g_free (up_req);
  595. }
  596. static void
  597. rspamd_fuzzy_update_stats (struct rspamd_fuzzy_storage_ctx *ctx,
  598. enum rspamd_fuzzy_epoch epoch,
  599. gboolean matched,
  600. gboolean is_shingle,
  601. struct fuzzy_key_stat *key_stat,
  602. struct fuzzy_key_stat *ip_stat,
  603. guint cmd, guint reply)
  604. {
  605. ctx->stat.fuzzy_hashes_checked[epoch] ++;
  606. if (matched) {
  607. ctx->stat.fuzzy_hashes_found[epoch]++;
  608. }
  609. if (is_shingle) {
  610. ctx->stat.fuzzy_shingles_checked[epoch]++;
  611. }
  612. if (key_stat) {
  613. if (!matched && reply != 0) {
  614. key_stat->errors ++;
  615. }
  616. else {
  617. if (cmd == FUZZY_CHECK) {
  618. key_stat->checked++;
  619. if (matched) {
  620. key_stat->matched ++;
  621. }
  622. }
  623. else if (cmd == FUZZY_WRITE) {
  624. key_stat->added++;
  625. }
  626. else if (cmd == FUZZY_DEL) {
  627. key_stat->deleted++;
  628. }
  629. }
  630. }
  631. if (ip_stat) {
  632. if (!matched && reply != 0) {
  633. ip_stat->errors++;
  634. }
  635. else {
  636. if (cmd == FUZZY_CHECK) {
  637. ip_stat->checked++;
  638. if (matched) {
  639. ip_stat->matched++;
  640. }
  641. }
  642. else if (cmd == FUZZY_WRITE) {
  643. ip_stat->added++;
  644. }
  645. else if (cmd == FUZZY_DEL) {
  646. ip_stat->deleted++;
  647. }
  648. }
  649. }
  650. }
  651. static void
  652. rspamd_fuzzy_make_reply (struct rspamd_fuzzy_cmd *cmd,
  653. struct rspamd_fuzzy_reply *result,
  654. struct fuzzy_session *session,
  655. gboolean encrypted, gboolean is_shingle)
  656. {
  657. gsize len;
  658. if (cmd) {
  659. result->v1.tag = cmd->tag;
  660. memcpy (&session->reply.rep, result, sizeof (*result));
  661. rspamd_fuzzy_update_stats (session->ctx,
  662. session->epoch,
  663. result->v1.prob > 0.5,
  664. is_shingle,
  665. session->key_stat,
  666. session->ip_stat,
  667. cmd->cmd,
  668. result->v1.value);
  669. if (encrypted) {
  670. /* We need also to encrypt reply */
  671. ottery_rand_bytes (session->reply.hdr.nonce,
  672. sizeof (session->reply.hdr.nonce));
  673. /*
  674. * For old replies we need to encrypt just old part, otherwise
  675. * decryption would fail due to mac verification mistake
  676. */
  677. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  678. len = sizeof (session->reply.rep);
  679. }
  680. else {
  681. len = sizeof (session->reply.rep.v1);
  682. }
  683. rspamd_cryptobox_encrypt_nm_inplace ((guchar *)&session->reply.rep,
  684. len,
  685. session->reply.hdr.nonce,
  686. session->nm,
  687. session->reply.hdr.mac,
  688. RSPAMD_CRYPTOBOX_MODE_25519);
  689. }
  690. }
  691. rspamd_fuzzy_write_reply (session);
  692. }
  693. static void
  694. rspamd_fuzzy_check_callback (struct rspamd_fuzzy_reply *result, void *ud)
  695. {
  696. struct fuzzy_session *session = ud;
  697. gboolean encrypted = FALSE, is_shingle = FALSE;
  698. struct rspamd_fuzzy_cmd *cmd = NULL;
  699. const struct rspamd_shingle *shingle = NULL;
  700. struct rspamd_shingle sgl_cpy;
  701. switch (session->cmd_type) {
  702. case CMD_NORMAL:
  703. cmd = &session->cmd.normal;
  704. break;
  705. case CMD_SHINGLE:
  706. cmd = &session->cmd.shingle.basic;
  707. memcpy (&sgl_cpy, &session->cmd.shingle.sgl, sizeof (sgl_cpy));
  708. shingle = &sgl_cpy;
  709. is_shingle = TRUE;
  710. break;
  711. case CMD_ENCRYPTED_NORMAL:
  712. cmd = &session->cmd.enc_normal.cmd;
  713. encrypted = TRUE;
  714. break;
  715. case CMD_ENCRYPTED_SHINGLE:
  716. cmd = &session->cmd.enc_shingle.cmd.basic;
  717. memcpy (&sgl_cpy, &session->cmd.enc_shingle.cmd.sgl, sizeof (sgl_cpy));
  718. shingle = &sgl_cpy;
  719. encrypted = TRUE;
  720. is_shingle = TRUE;
  721. break;
  722. }
  723. rspamd_fuzzy_make_reply (cmd, result, session, encrypted, is_shingle);
  724. /* Refresh hash if found with strong confidence */
  725. if (result->v1.prob > 0.9 && !session->ctx->read_only) {
  726. struct fuzzy_peer_cmd up_cmd;
  727. struct fuzzy_peer_request *up_req;
  728. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  729. /* Just add to the queue */
  730. memset (&up_cmd, 0, sizeof (up_cmd));
  731. up_cmd.is_shingle = is_shingle;
  732. memcpy (up_cmd.cmd.normal.digest, result->digest,
  733. sizeof (up_cmd.cmd.normal.digest));
  734. up_cmd.cmd.normal.flag = result->v1.flag;
  735. up_cmd.cmd.normal.cmd = FUZZY_REFRESH;
  736. up_cmd.cmd.normal.shingles_count = cmd->shingles_count;
  737. if (is_shingle && shingle) {
  738. memcpy (&up_cmd.cmd.shingle.sgl, shingle,
  739. sizeof (up_cmd.cmd.shingle.sgl));
  740. }
  741. g_array_append_val (session->ctx->updates_pending, up_cmd);
  742. }
  743. else {
  744. /* We need to send request to the peer */
  745. up_req = g_malloc0 (sizeof (*up_req));
  746. up_req->cmd.is_shingle = is_shingle;
  747. memcpy (up_req->cmd.cmd.normal.digest, result->digest,
  748. sizeof (up_req->cmd.cmd.normal.digest));
  749. up_req->cmd.cmd.normal.flag = result->v1.flag;
  750. up_req->cmd.cmd.normal.cmd = FUZZY_REFRESH;
  751. up_req->cmd.cmd.normal.shingles_count = cmd->shingles_count;
  752. if (is_shingle && shingle) {
  753. memcpy (&up_req->cmd.cmd.shingle.sgl, shingle,
  754. sizeof (up_req->cmd.cmd.shingle.sgl));
  755. }
  756. event_set (&up_req->io_ev, session->ctx->peer_fd, EV_WRITE,
  757. fuzzy_peer_send_io, up_req);
  758. event_base_set (session->ctx->ev_base, &up_req->io_ev);
  759. event_add (&up_req->io_ev, NULL);
  760. }
  761. }
  762. REF_RELEASE (session);
  763. }
  764. static void
  765. rspamd_fuzzy_process_command (struct fuzzy_session *session)
  766. {
  767. gboolean encrypted = FALSE, is_shingle = FALSE;
  768. struct rspamd_fuzzy_cmd *cmd = NULL;
  769. struct rspamd_fuzzy_reply result;
  770. struct fuzzy_peer_cmd up_cmd;
  771. struct fuzzy_peer_request *up_req;
  772. struct fuzzy_key_stat *ip_stat = NULL;
  773. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  774. rspamd_inet_addr_t *naddr;
  775. gpointer ptr;
  776. gsize up_len = 0;
  777. switch (session->cmd_type) {
  778. case CMD_NORMAL:
  779. cmd = &session->cmd.normal;
  780. up_len = sizeof (session->cmd.normal);
  781. break;
  782. case CMD_SHINGLE:
  783. cmd = &session->cmd.shingle.basic;
  784. up_len = sizeof (session->cmd.shingle);
  785. is_shingle = TRUE;
  786. break;
  787. case CMD_ENCRYPTED_NORMAL:
  788. cmd = &session->cmd.enc_normal.cmd;
  789. up_len = sizeof (session->cmd.normal);
  790. encrypted = TRUE;
  791. break;
  792. case CMD_ENCRYPTED_SHINGLE:
  793. cmd = &session->cmd.enc_shingle.cmd.basic;
  794. up_len = sizeof (session->cmd.shingle);
  795. encrypted = TRUE;
  796. is_shingle = TRUE;
  797. break;
  798. default:
  799. msg_err ("invalid command type: %d", session->cmd_type);
  800. return;
  801. }
  802. memset (&result, 0, sizeof (result));
  803. memcpy (result.digest, cmd->digest, sizeof (result.digest));
  804. result.v1.flag = cmd->flag;
  805. result.v1.tag = cmd->tag;
  806. if (G_UNLIKELY (cmd == NULL || up_len == 0)) {
  807. result.v1.value = 500;
  808. result.v1.prob = 0.0;
  809. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted, is_shingle);
  810. return;
  811. }
  812. if (session->ctx->encrypted_only && !encrypted) {
  813. /* Do not accept unencrypted commands */
  814. result.v1.value = 403;
  815. result.v1.prob = 0.0;
  816. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted, is_shingle);
  817. return;
  818. }
  819. if (session->key_stat) {
  820. ip_stat = rspamd_lru_hash_lookup (session->key_stat->last_ips,
  821. session->addr, -1);
  822. if (ip_stat == NULL) {
  823. naddr = rspamd_inet_address_copy (session->addr);
  824. ip_stat = g_malloc0 (sizeof (*ip_stat));
  825. rspamd_lru_hash_insert (session->key_stat->last_ips,
  826. naddr, ip_stat, -1, 0);
  827. }
  828. session->ip_stat = ip_stat;
  829. }
  830. if (cmd->cmd == FUZZY_CHECK) {
  831. if (rspamd_fuzzy_check_client (session, FALSE)) {
  832. if (G_UNLIKELY (session->ctx->collection_mode)) {
  833. result.v1.prob = 0;
  834. result.v1.value = 500;
  835. result.v1.flag = 0;
  836. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted,
  837. is_shingle);
  838. } else {
  839. REF_RETAIN (session);
  840. rspamd_fuzzy_backend_check (session->ctx->backend, cmd,
  841. rspamd_fuzzy_check_callback, session);
  842. }
  843. }
  844. else {
  845. result.v1.value = 403;
  846. result.v1.prob = 0.0;
  847. }
  848. }
  849. else if (cmd->cmd == FUZZY_STAT) {
  850. if (G_UNLIKELY (session->ctx->collection_mode)) {
  851. result.v1.prob = 0;
  852. result.v1.value = 500;
  853. result.v1.flag = 0;
  854. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted, is_shingle);
  855. }
  856. else {
  857. result.v1.prob = 1.0;
  858. result.v1.value = 0;
  859. result.v1.flag = session->ctx->stat.fuzzy_hashes;
  860. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted, is_shingle);
  861. }
  862. }
  863. else {
  864. if (rspamd_fuzzy_check_client (session, TRUE)) {
  865. /* Check whitelist */
  866. if (session->ctx->skip_hashes && cmd->cmd == FUZZY_WRITE) {
  867. rspamd_encode_hex_buf (cmd->digest, sizeof (cmd->digest),
  868. hexbuf, sizeof (hexbuf) - 1);
  869. hexbuf[sizeof (hexbuf) - 1] = '\0';
  870. if (rspamd_match_hash_map (session->ctx->skip_hashes, hexbuf)) {
  871. result.v1.value = 401;
  872. result.v1.prob = 0.0;
  873. goto reply;
  874. }
  875. }
  876. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  877. /* Just add to the queue */
  878. up_cmd.is_shingle = is_shingle;
  879. ptr = is_shingle ?
  880. (gpointer)&up_cmd.cmd.shingle :
  881. (gpointer)&up_cmd.cmd.normal;
  882. memcpy (ptr, cmd, up_len);
  883. g_array_append_val (session->ctx->updates_pending, up_cmd);
  884. }
  885. else {
  886. /* We need to send request to the peer */
  887. up_req = g_malloc0 (sizeof (*up_req));
  888. up_req->cmd.is_shingle = is_shingle;
  889. ptr = is_shingle ?
  890. (gpointer)&up_req->cmd.cmd.shingle :
  891. (gpointer)&up_req->cmd.cmd.normal;
  892. memcpy (ptr, cmd, up_len);
  893. event_set (&up_req->io_ev, session->ctx->peer_fd, EV_WRITE,
  894. fuzzy_peer_send_io, up_req);
  895. event_base_set (session->ctx->ev_base, &up_req->io_ev);
  896. event_add (&up_req->io_ev, NULL);
  897. }
  898. result.v1.value = 0;
  899. result.v1.prob = 1.0;
  900. }
  901. else {
  902. result.v1.value = 403;
  903. result.v1.prob = 0.0;
  904. }
  905. reply:
  906. rspamd_fuzzy_make_reply (cmd, &result, session, encrypted, is_shingle);
  907. }
  908. }
  909. static enum rspamd_fuzzy_epoch
  910. rspamd_fuzzy_command_valid (struct rspamd_fuzzy_cmd *cmd, gint r)
  911. {
  912. enum rspamd_fuzzy_epoch ret = RSPAMD_FUZZY_EPOCH_MAX;
  913. switch (cmd->version) {
  914. case 4:
  915. if (cmd->shingles_count > 0) {
  916. if (r == sizeof (struct rspamd_fuzzy_shingle_cmd)) {
  917. ret = RSPAMD_FUZZY_EPOCH11;
  918. }
  919. }
  920. else {
  921. if (r == sizeof (*cmd)) {
  922. ret = RSPAMD_FUZZY_EPOCH11;
  923. }
  924. }
  925. break;
  926. case 3:
  927. if (cmd->shingles_count > 0) {
  928. if (r == sizeof (struct rspamd_fuzzy_shingle_cmd)) {
  929. ret = RSPAMD_FUZZY_EPOCH10;
  930. }
  931. }
  932. else {
  933. if (r == sizeof (*cmd)) {
  934. ret = RSPAMD_FUZZY_EPOCH10;
  935. }
  936. }
  937. break;
  938. case 2:
  939. /*
  940. * rspamd 0.8 has slightly different tokenizer then it might be not
  941. * 100% compatible
  942. */
  943. if (cmd->shingles_count > 0) {
  944. if (r == sizeof (struct rspamd_fuzzy_shingle_cmd)) {
  945. ret = RSPAMD_FUZZY_EPOCH8;
  946. }
  947. }
  948. else {
  949. ret = RSPAMD_FUZZY_EPOCH8;
  950. }
  951. break;
  952. default:
  953. break;
  954. }
  955. return ret;
  956. }
  957. static gboolean
  958. rspamd_fuzzy_decrypt_command (struct fuzzy_session *s)
  959. {
  960. struct rspamd_fuzzy_encrypted_req_hdr *hdr;
  961. guchar *payload;
  962. gsize payload_len;
  963. struct rspamd_cryptobox_pubkey *rk;
  964. struct fuzzy_key *key;
  965. if (s->ctx->default_key == NULL) {
  966. msg_warn ("received encrypted request when encryption is not enabled");
  967. return FALSE;
  968. }
  969. if (s->cmd_type == CMD_ENCRYPTED_NORMAL) {
  970. hdr = &s->cmd.enc_normal.hdr;
  971. payload = (guchar *)&s->cmd.enc_normal.cmd;
  972. payload_len = sizeof (s->cmd.enc_normal.cmd);
  973. }
  974. else {
  975. hdr = &s->cmd.enc_shingle.hdr;
  976. payload = (guchar *) &s->cmd.enc_shingle.cmd;
  977. payload_len = sizeof (s->cmd.enc_shingle.cmd);
  978. }
  979. /* Compare magic */
  980. if (memcmp (hdr->magic, fuzzy_encrypted_magic, sizeof (hdr->magic)) != 0) {
  981. msg_debug ("invalid magic for the encrypted packet");
  982. return FALSE;
  983. }
  984. /* Try to find the desired key */
  985. key = g_hash_table_lookup (s->ctx->keys, hdr->key_id);
  986. if (key == NULL) {
  987. /* Unknown key, assume default one */
  988. key = s->ctx->default_key;
  989. }
  990. s->key_stat = key->stat;
  991. /* Now process keypair */
  992. rk = rspamd_pubkey_from_bin (hdr->pubkey, sizeof (hdr->pubkey),
  993. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  994. if (rk == NULL) {
  995. msg_err ("bad key");
  996. return FALSE;
  997. }
  998. rspamd_keypair_cache_process (s->ctx->keypair_cache, key->key, rk);
  999. /* Now decrypt request */
  1000. if (!rspamd_cryptobox_decrypt_nm_inplace (payload, payload_len, hdr->nonce,
  1001. rspamd_pubkey_get_nm (rk, key->key),
  1002. hdr->mac, RSPAMD_CRYPTOBOX_MODE_25519)) {
  1003. msg_err ("decryption failed");
  1004. rspamd_pubkey_unref (rk);
  1005. return FALSE;
  1006. }
  1007. memcpy (s->nm, rspamd_pubkey_get_nm (rk, key->key), sizeof (s->nm));
  1008. rspamd_pubkey_unref (rk);
  1009. return TRUE;
  1010. }
  1011. static gboolean
  1012. rspamd_fuzzy_cmd_from_wire (guchar *buf, guint buflen, struct fuzzy_session *s)
  1013. {
  1014. enum rspamd_fuzzy_epoch epoch;
  1015. /* For now, we assume that recvfrom returns a complete datagramm */
  1016. switch (buflen) {
  1017. case sizeof (struct rspamd_fuzzy_cmd):
  1018. s->cmd_type = CMD_NORMAL;
  1019. memcpy (&s->cmd.normal, buf, sizeof (s->cmd.normal));
  1020. epoch = rspamd_fuzzy_command_valid (&s->cmd.normal, buflen);
  1021. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1022. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1023. return FALSE;
  1024. }
  1025. s->epoch = epoch;
  1026. break;
  1027. case sizeof (struct rspamd_fuzzy_shingle_cmd):
  1028. s->cmd_type = CMD_SHINGLE;
  1029. memcpy (&s->cmd.shingle, buf, sizeof (s->cmd.shingle));
  1030. epoch = rspamd_fuzzy_command_valid (&s->cmd.shingle.basic, buflen);
  1031. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1032. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1033. return FALSE;
  1034. }
  1035. s->epoch = epoch;
  1036. break;
  1037. case sizeof (struct rspamd_fuzzy_encrypted_cmd):
  1038. s->cmd_type = CMD_ENCRYPTED_NORMAL;
  1039. memcpy (&s->cmd.enc_normal, buf, sizeof (s->cmd.enc_normal));
  1040. if (!rspamd_fuzzy_decrypt_command (s)) {
  1041. return FALSE;
  1042. }
  1043. epoch = rspamd_fuzzy_command_valid (&s->cmd.enc_normal.cmd,
  1044. sizeof (s->cmd.enc_normal.cmd));
  1045. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1046. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1047. return FALSE;
  1048. }
  1049. /* Encrypted is epoch 10 at least */
  1050. s->epoch = epoch;
  1051. break;
  1052. case sizeof (struct rspamd_fuzzy_encrypted_shingle_cmd):
  1053. s->cmd_type = CMD_ENCRYPTED_SHINGLE;
  1054. memcpy (&s->cmd.enc_shingle, buf, sizeof (s->cmd.enc_shingle));
  1055. if (!rspamd_fuzzy_decrypt_command (s)) {
  1056. return FALSE;
  1057. }
  1058. epoch = rspamd_fuzzy_command_valid (&s->cmd.enc_shingle.cmd.basic,
  1059. sizeof (s->cmd.enc_shingle.cmd));
  1060. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1061. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1062. return FALSE;
  1063. }
  1064. s->epoch = epoch;
  1065. break;
  1066. default:
  1067. msg_debug ("invalid fuzzy command of size %d received", buflen);
  1068. return FALSE;
  1069. }
  1070. return TRUE;
  1071. }
  1072. static void
  1073. rspamd_fuzzy_mirror_process_update (struct fuzzy_master_update_session *session,
  1074. struct rspamd_http_message *msg, guint our_rev)
  1075. {
  1076. const guchar *p;
  1077. gsize remain;
  1078. gint32 revision;
  1079. guint32 len = 0, cnt = 0;
  1080. struct fuzzy_peer_cmd cmd;
  1081. enum {
  1082. read_len = 0,
  1083. read_data,
  1084. finish_processing
  1085. } state = read_len;
  1086. gpointer flag_ptr;
  1087. /*
  1088. * Message format:
  1089. * <uint32_le> - revision
  1090. * <uint32_le> - size of the next element
  1091. * <data> - command data
  1092. * ...
  1093. * <0> - end of data
  1094. * ... - ignored
  1095. */
  1096. p = rspamd_http_message_get_body (msg, &remain);
  1097. if (p && remain >= sizeof (gint32) * 2) {
  1098. memcpy (&revision, p, sizeof (gint32));
  1099. revision = GINT32_TO_LE (revision);
  1100. if (revision <= our_rev) {
  1101. msg_err_fuzzy_update ("remote revision: %d is older than ours: %d, "
  1102. "refusing update",
  1103. revision, our_rev);
  1104. return;
  1105. }
  1106. else if (revision - our_rev > 1) {
  1107. msg_warn_fuzzy_update ("remote revision: %d is newer more than one revision "
  1108. "than ours: %d, cold sync is recommended",
  1109. revision, our_rev);
  1110. }
  1111. remain -= sizeof (gint32);
  1112. p += sizeof (gint32);
  1113. }
  1114. else {
  1115. msg_err_fuzzy_update ("short update message, not processing");
  1116. goto err;
  1117. }
  1118. while (remain > 0) {
  1119. switch (state) {
  1120. case read_len:
  1121. if (remain < sizeof (guint32)) {
  1122. msg_err_fuzzy_update ("short update message while reading "
  1123. "length, not processing");
  1124. goto err;
  1125. }
  1126. memcpy (&len, p, sizeof (guint32));
  1127. len = GUINT32_TO_LE (len);
  1128. remain -= sizeof (guint32);
  1129. p += sizeof (guint32);
  1130. if (len == 0) {
  1131. remain = 0;
  1132. state = finish_processing;
  1133. }
  1134. else {
  1135. state = read_data;
  1136. }
  1137. break;
  1138. case read_data:
  1139. if (remain < len) {
  1140. msg_err_fuzzy_update ("short update message while reading data, "
  1141. "not processing"
  1142. " (%zd is available, %d is required)", remain, len);
  1143. return;
  1144. }
  1145. if (len < sizeof (struct rspamd_fuzzy_cmd) + sizeof (guint32) ||
  1146. len > sizeof (cmd)) {
  1147. /* Bad size command */
  1148. msg_err_fuzzy_update ("incorrect element size: %d, at least "
  1149. "%d expected", len,
  1150. (gint)(sizeof (struct rspamd_fuzzy_cmd) + sizeof (guint32)));
  1151. goto err;
  1152. }
  1153. memcpy (&cmd, p, len);
  1154. if (cmd.is_shingle && len != sizeof (cmd)) {
  1155. /* Short command */
  1156. msg_err_fuzzy_update ("incorrect element size: %d, at least "
  1157. "%d expected", len,
  1158. (gint)(sizeof (cmd)));
  1159. goto err;
  1160. }
  1161. if (cmd.is_shingle) {
  1162. if ((flag_ptr = g_hash_table_lookup (session->ctx->master_flags,
  1163. GUINT_TO_POINTER (cmd.cmd.shingle.basic.flag))) != NULL) {
  1164. cmd.cmd.shingle.basic.flag = GPOINTER_TO_UINT (flag_ptr);
  1165. }
  1166. }
  1167. else {
  1168. if ((flag_ptr = g_hash_table_lookup (session->ctx->master_flags,
  1169. GUINT_TO_POINTER (cmd.cmd.normal.flag))) != NULL) {
  1170. cmd.cmd.normal.flag = GPOINTER_TO_UINT (flag_ptr);
  1171. }
  1172. }
  1173. g_array_append_val (session->ctx->updates_pending, cmd);
  1174. p += len;
  1175. remain -= len;
  1176. len = 0;
  1177. state = read_len;
  1178. cnt ++;
  1179. break;
  1180. case finish_processing:
  1181. /* Do nothing */
  1182. remain = 0;
  1183. break;
  1184. }
  1185. }
  1186. rspamd_fuzzy_process_updates_queue (session->ctx, session->src, TRUE);
  1187. msg_info_fuzzy_update ("processed updates from the master %s, "
  1188. "%ud operations processed,"
  1189. " revision: %d (local revision: %d)",
  1190. rspamd_inet_address_to_string (session->addr),
  1191. cnt, revision, our_rev);
  1192. err:
  1193. return;
  1194. }
  1195. static void
  1196. fuzzy_session_destroy (gpointer d)
  1197. {
  1198. struct fuzzy_session *session = d;
  1199. rspamd_inet_address_free (session->addr);
  1200. rspamd_explicit_memzero (session->nm, sizeof (session->nm));
  1201. session->worker->nconns--;
  1202. g_free (session);
  1203. }
  1204. static void
  1205. rspamd_fuzzy_mirror_session_destroy (struct fuzzy_master_update_session *session)
  1206. {
  1207. if (session) {
  1208. rspamd_http_connection_reset (session->conn);
  1209. rspamd_http_connection_unref (session->conn);
  1210. rspamd_inet_address_free (session->addr);
  1211. close (session->sock);
  1212. if (session->psrc) {
  1213. g_free (session->psrc);
  1214. }
  1215. g_free (session);
  1216. }
  1217. }
  1218. static void
  1219. rspamd_fuzzy_mirror_error_handler (struct rspamd_http_connection *conn, GError *err)
  1220. {
  1221. struct fuzzy_master_update_session *session = conn->ud;
  1222. msg_err_fuzzy_update ("abnormally closing connection from: %s, error: %e",
  1223. rspamd_inet_address_to_string (session->addr), err);
  1224. /* Terminate session immediately */
  1225. rspamd_fuzzy_mirror_session_destroy (session);
  1226. }
  1227. static void
  1228. rspamd_fuzzy_mirror_send_reply (struct fuzzy_master_update_session *session,
  1229. guint code, const gchar *str)
  1230. {
  1231. struct rspamd_http_message *msg;
  1232. msg = rspamd_http_new_message (HTTP_RESPONSE);
  1233. msg->url = rspamd_fstring_new_init (str, strlen (str));
  1234. msg->code = code;
  1235. session->replied = TRUE;
  1236. rspamd_http_connection_reset (session->conn);
  1237. rspamd_http_connection_write_message (session->conn, msg, NULL, "text/plain",
  1238. session, session->sock, &session->ctx->master_io_tv,
  1239. session->ctx->ev_base);
  1240. }
  1241. static void
  1242. rspamd_fuzzy_update_version_callback (guint64 version, void *ud)
  1243. {
  1244. struct fuzzy_master_update_session *session = ud;
  1245. rspamd_fuzzy_mirror_process_update (session, session->msg, version);
  1246. rspamd_fuzzy_mirror_send_reply (session, 200, "OK");
  1247. }
  1248. static gint
  1249. rspamd_fuzzy_mirror_finish_handler (struct rspamd_http_connection *conn,
  1250. struct rspamd_http_message *msg)
  1251. {
  1252. struct fuzzy_master_update_session *session = conn->ud;
  1253. const struct rspamd_cryptobox_pubkey *rk;
  1254. const gchar *err_str = NULL;
  1255. gchar *psrc;
  1256. const gchar *src = NULL;
  1257. gsize remain;
  1258. if (session->replied) {
  1259. rspamd_fuzzy_mirror_session_destroy (session);
  1260. return 0;
  1261. }
  1262. /* Check key */
  1263. if (!rspamd_http_connection_is_encrypted (conn)) {
  1264. msg_err_fuzzy_update ("refuse unencrypted update from: %s",
  1265. rspamd_inet_address_to_string (session->addr));
  1266. err_str = "Unencrypted update is not allowed";
  1267. goto end;
  1268. }
  1269. else {
  1270. if (session->ctx->master_key) {
  1271. rk = rspamd_http_connection_get_peer_key (conn);
  1272. g_assert (rk != NULL);
  1273. if (!rspamd_pubkey_equal (rk, session->ctx->master_key)) {
  1274. msg_err_fuzzy_update ("refuse unknown pubkey update from: %s",
  1275. rspamd_inet_address_to_string (session->addr));
  1276. err_str = "Unknown pubkey";
  1277. goto end;
  1278. }
  1279. }
  1280. else {
  1281. msg_warn_fuzzy_update ("no trusted key specified, accept any update from %s",
  1282. rspamd_inet_address_to_string (session->addr));
  1283. }
  1284. if (!rspamd_http_message_get_body (msg, NULL) || !msg->url
  1285. || msg->url->len == 0) {
  1286. msg_err_fuzzy_update ("empty update message, not processing");
  1287. err_str = "Empty update";
  1288. goto end;
  1289. }
  1290. /* Detect source from url: /update_v1/<source>, so we look for the last '/' */
  1291. remain = msg->url->len;
  1292. psrc = rspamd_fstringdup (msg->url);
  1293. src = psrc;
  1294. while (remain--) {
  1295. if (src[remain] == '/') {
  1296. src = &src[remain + 1];
  1297. break;
  1298. }
  1299. }
  1300. session->src = src;
  1301. session->psrc = psrc;
  1302. session->msg = msg;
  1303. rspamd_fuzzy_backend_version (session->ctx->backend, src,
  1304. rspamd_fuzzy_update_version_callback, session);
  1305. return 0;
  1306. }
  1307. end:
  1308. rspamd_fuzzy_mirror_send_reply (session, 403, err_str);
  1309. return 0;
  1310. }
  1311. struct rspamd_fuzzy_collection_session {
  1312. struct rspamd_fuzzy_storage_ctx *ctx;
  1313. struct rspamd_worker *worker;
  1314. rspamd_inet_addr_t *from_addr;
  1315. guchar uid[16];
  1316. };
  1317. static void
  1318. rspamd_fuzzy_collection_error_handler (struct rspamd_http_connection_entry *conn_ent,
  1319. GError *err)
  1320. {
  1321. struct rspamd_fuzzy_collection_session *session = conn_ent->ud;
  1322. msg_err_fuzzy_collection ("http error occurred: %s", err->message);
  1323. }
  1324. static void
  1325. rspamd_fuzzy_collection_finish_handler (struct rspamd_http_connection_entry *conn_ent)
  1326. {
  1327. struct rspamd_fuzzy_collection_session *session = conn_ent->ud;
  1328. rspamd_inet_address_free (session->from_addr);
  1329. g_free (session);
  1330. }
  1331. void
  1332. rspamd_fuzzy_collection_send_error (struct rspamd_http_connection_entry *entry,
  1333. gint code, const gchar *error_msg, ...)
  1334. {
  1335. struct rspamd_http_message *msg;
  1336. va_list args;
  1337. rspamd_fstring_t *reply;
  1338. msg = rspamd_http_new_message (HTTP_RESPONSE);
  1339. va_start (args, error_msg);
  1340. msg->status = rspamd_fstring_new ();
  1341. rspamd_vprintf_fstring (&msg->status, error_msg, args);
  1342. va_end (args);
  1343. msg->date = time (NULL);
  1344. msg->code = code;
  1345. reply = rspamd_fstring_sized_new (msg->status->len + 16);
  1346. rspamd_printf_fstring (&reply, "%V", msg->status);
  1347. rspamd_http_message_set_body_from_fstring_steal (msg, reply);
  1348. rspamd_http_connection_reset (entry->conn);
  1349. rspamd_http_router_insert_headers (entry->rt, msg);
  1350. rspamd_http_connection_write_message (entry->conn,
  1351. msg,
  1352. NULL,
  1353. "text/plain",
  1354. entry,
  1355. entry->conn->fd,
  1356. entry->rt->ptv,
  1357. entry->rt->ev_base);
  1358. entry->is_reply = TRUE;
  1359. }
  1360. /*
  1361. * Note: this function steals fstring
  1362. */
  1363. void
  1364. rspamd_fuzzy_collection_send_fstring (struct rspamd_http_connection_entry *entry,
  1365. rspamd_fstring_t *fstr)
  1366. {
  1367. struct rspamd_http_message *msg;
  1368. msg = rspamd_http_new_message (HTTP_RESPONSE);
  1369. msg->status = rspamd_fstring_new_init ("OK", 2);
  1370. msg->date = time (NULL);
  1371. msg->code = 200;
  1372. rspamd_http_message_set_body_from_fstring_steal (msg, fstr);
  1373. rspamd_http_connection_reset (entry->conn);
  1374. rspamd_http_router_insert_headers (entry->rt, msg);
  1375. rspamd_http_connection_write_message (entry->conn,
  1376. msg,
  1377. NULL,
  1378. "application/octet-stream",
  1379. entry,
  1380. entry->conn->fd,
  1381. entry->rt->ptv,
  1382. entry->rt->ev_base);
  1383. entry->is_reply = TRUE;
  1384. }
  1385. static int
  1386. rspamd_fuzzy_collection_cookie (struct rspamd_http_connection_entry *conn_ent,
  1387. struct rspamd_http_message *msg)
  1388. {
  1389. struct rspamd_fuzzy_collection_session *session = conn_ent->ud;
  1390. rspamd_fstring_t *cookie;
  1391. cookie = rspamd_fstring_new_init (session->ctx->cookie,
  1392. sizeof (session->ctx->cookie));
  1393. rspamd_fuzzy_collection_send_fstring (conn_ent, cookie);
  1394. return 0;
  1395. }
  1396. static int
  1397. rspamd_fuzzy_collection_data (struct rspamd_http_connection_entry *conn_ent,
  1398. struct rspamd_http_message *msg)
  1399. {
  1400. struct rspamd_fuzzy_collection_session *session = conn_ent->ud;
  1401. const rspamd_ftok_t *sign_header;
  1402. struct rspamd_fuzzy_storage_ctx *ctx;
  1403. guint i;
  1404. struct fuzzy_peer_cmd *io_cmd;
  1405. rspamd_fstring_t *reply;
  1406. GError *err = NULL;
  1407. guchar *decoded_signature;
  1408. gsize dec_len;
  1409. guint32 cmdlen, nupdates = 0;
  1410. sign_header = rspamd_http_message_find_header (msg, "Signature");
  1411. if (sign_header == NULL) {
  1412. rspamd_fuzzy_collection_send_error (conn_ent, 403, "Missing signature");
  1413. return 0;
  1414. }
  1415. ctx = session->ctx;
  1416. if (ctx->collection_sign_key == NULL) {
  1417. rspamd_fuzzy_collection_send_error (conn_ent, 500, "Misconfigured signature key");
  1418. return 0;
  1419. }
  1420. decoded_signature = g_malloc (sign_header->len * 2 + 1);
  1421. dec_len = rspamd_decode_hex_buf (sign_header->begin, sign_header->len,
  1422. decoded_signature, sign_header->len * 2 + 1);
  1423. if (dec_len == -1 || !rspamd_keypair_verify (ctx->collection_sign_key,
  1424. ctx->cookie, sizeof (ctx->cookie),
  1425. decoded_signature, dec_len, &err)) {
  1426. if (err) {
  1427. rspamd_fuzzy_collection_send_error (conn_ent, 403, "Signature verification error: %e",
  1428. err);
  1429. g_error_free (err);
  1430. }
  1431. else {
  1432. rspamd_fuzzy_collection_send_error (conn_ent, 403, "Signature verification error");
  1433. }
  1434. g_free (decoded_signature);
  1435. return 0;
  1436. }
  1437. g_free (decoded_signature);
  1438. /* Generate new cookie */
  1439. ottery_rand_bytes (ctx->cookie, sizeof (ctx->cookie));
  1440. /* Send&Clear updates */
  1441. reply = rspamd_fstring_sized_new (8192);
  1442. /*
  1443. * Message format:
  1444. * <uint32_le> - revision
  1445. * <uint32_le> - size of the next element
  1446. * <data> - command data
  1447. * ...
  1448. * <0> - end of data
  1449. * ... - ignored
  1450. */
  1451. reply = rspamd_fstring_append (reply, (const gchar *)&ctx->collection_id,
  1452. sizeof (ctx->collection_id));
  1453. for (i = 0; i < ctx->updates_pending->len; i ++) {
  1454. io_cmd = &g_array_index (ctx->updates_pending, struct fuzzy_peer_cmd, i);
  1455. if (io_cmd->is_shingle) {
  1456. cmdlen = sizeof (io_cmd->cmd.shingle) + sizeof (guint32);
  1457. }
  1458. else {
  1459. cmdlen = sizeof (io_cmd->cmd.normal) + sizeof (guint32);
  1460. }
  1461. cmdlen = GUINT32_TO_LE (cmdlen);
  1462. reply = rspamd_fstring_append (reply, (const gchar *)&cmdlen,
  1463. sizeof (cmdlen));
  1464. reply = rspamd_fstring_append (reply, (const gchar *)io_cmd,
  1465. cmdlen);
  1466. nupdates ++;
  1467. }
  1468. msg_info_fuzzy_collection ("collection %d done, send %d updates",
  1469. ctx->collection_id, nupdates);
  1470. /* Last command */
  1471. cmdlen = 0;
  1472. reply = rspamd_fstring_append (reply, (const gchar *)&cmdlen,
  1473. sizeof (cmdlen));
  1474. ctx->updates_pending->len = 0;
  1475. /* Clear failed attempts counter */
  1476. ctx->updates_failed = 0;
  1477. ctx->collection_id ++;
  1478. rspamd_fuzzy_collection_send_fstring (conn_ent, reply);
  1479. return 0;
  1480. }
  1481. static void
  1482. accept_fuzzy_collection_socket (gint fd, short what, void *arg)
  1483. {
  1484. struct rspamd_worker *worker = (struct rspamd_worker *)arg;
  1485. rspamd_inet_addr_t *addr;
  1486. gint nfd;
  1487. struct rspamd_fuzzy_storage_ctx *ctx;
  1488. struct rspamd_fuzzy_collection_session *session;
  1489. if ((nfd =
  1490. rspamd_accept_from_socket (fd, &addr, worker->accept_events)) == -1) {
  1491. msg_warn ("accept failed: %s", strerror (errno));
  1492. return;
  1493. }
  1494. /* Check for EAGAIN */
  1495. if (nfd == 0) {
  1496. return;
  1497. }
  1498. ctx = worker->ctx;
  1499. if (!ctx->collection_keypair) {
  1500. msg_err ("deny request from %s, as no local keypair is specified",
  1501. rspamd_inet_address_to_string (addr));
  1502. rspamd_inet_address_free (addr);
  1503. close (nfd);
  1504. return;
  1505. }
  1506. session = g_malloc0 (sizeof (*session));
  1507. session->ctx = ctx;
  1508. session->worker = worker;
  1509. rspamd_random_hex (session->uid, sizeof (session->uid) - 1);
  1510. session->uid[sizeof (session->uid) - 1] = '\0';
  1511. session->from_addr = addr;
  1512. rspamd_http_router_handle_socket (ctx->collection_rt, nfd, session);
  1513. msg_info_fuzzy_collection ("accepted connection from %s port %d, session ptr: %p",
  1514. rspamd_inet_address_to_string (addr),
  1515. rspamd_inet_address_get_port (addr),
  1516. session);
  1517. }
  1518. static void
  1519. rspamd_fuzzy_collection_periodic (gint fd, gshort what, gpointer ud)
  1520. {
  1521. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1522. if (++ctx->updates_failed > ctx->updates_maxfail) {
  1523. msg_err ("cannot store more data in workqueue, discard "
  1524. "%ud updates after %d missed collection points",
  1525. ctx->updates_pending->len,
  1526. ctx->updates_maxfail);
  1527. ctx->updates_failed = 0;
  1528. ctx->updates_pending->len = 0;
  1529. /* Regenerate cookie */
  1530. ottery_rand_bytes (ctx->cookie, sizeof (ctx->cookie));
  1531. }
  1532. else {
  1533. msg_err ("fuzzy data has not been collected in time, "
  1534. "%ud updates are still pending, %d updates left",
  1535. ctx->updates_pending->len,
  1536. ctx->updates_maxfail - ctx->updates_failed);
  1537. }
  1538. if (ctx->worker->wanna_die) {
  1539. /* Plan exit */
  1540. struct timeval tv;
  1541. tv.tv_sec = 0;
  1542. tv.tv_usec = 0;
  1543. event_base_loopexit (ctx->ev_base, &tv);
  1544. }
  1545. }
  1546. static void
  1547. accept_fuzzy_mirror_socket (gint fd, short what, void *arg)
  1548. {
  1549. struct rspamd_worker *worker = (struct rspamd_worker *)arg;
  1550. rspamd_inet_addr_t *addr;
  1551. gint nfd;
  1552. struct rspamd_http_connection *http_conn;
  1553. struct rspamd_fuzzy_storage_ctx *ctx;
  1554. struct fuzzy_master_update_session *session;
  1555. if ((nfd =
  1556. rspamd_accept_from_socket (fd, &addr, worker->accept_events)) == -1) {
  1557. msg_warn ("accept failed: %s", strerror (errno));
  1558. return;
  1559. }
  1560. /* Check for EAGAIN */
  1561. if (nfd == 0) {
  1562. return;
  1563. }
  1564. ctx = worker->ctx;
  1565. if (!ctx->master_ips) {
  1566. msg_err ("deny update request from %s as no masters defined",
  1567. rspamd_inet_address_to_string (addr));
  1568. rspamd_inet_address_free (addr);
  1569. close (nfd);
  1570. return;
  1571. }
  1572. else if (rspamd_match_radix_map_addr (ctx->master_ips, addr) == NULL) {
  1573. msg_err ("deny update request from %s",
  1574. rspamd_inet_address_to_string (addr));
  1575. rspamd_inet_address_free (addr);
  1576. close (nfd);
  1577. return;
  1578. }
  1579. if (!ctx->sync_keypair) {
  1580. msg_err ("deny update request from %s, as no local keypair is specified",
  1581. rspamd_inet_address_to_string (addr));
  1582. rspamd_inet_address_free (addr);
  1583. close (nfd);
  1584. return;
  1585. }
  1586. session = g_malloc0 (sizeof (*session));
  1587. session->name = rspamd_inet_address_to_string (addr);
  1588. rspamd_random_hex (session->uid, sizeof (session->uid) - 1);
  1589. session->uid[sizeof (session->uid) - 1] = '\0';
  1590. http_conn = rspamd_http_connection_new (NULL,
  1591. rspamd_fuzzy_mirror_error_handler,
  1592. rspamd_fuzzy_mirror_finish_handler,
  1593. 0,
  1594. RSPAMD_HTTP_SERVER,
  1595. ctx->keypair_cache,
  1596. NULL);
  1597. rspamd_http_connection_set_key (http_conn, ctx->sync_keypair);
  1598. session->ctx = ctx;
  1599. session->conn = http_conn;
  1600. session->addr = addr;
  1601. session->sock = nfd;
  1602. rspamd_http_connection_read_message (http_conn,
  1603. session,
  1604. nfd,
  1605. &ctx->master_io_tv,
  1606. ctx->ev_base);
  1607. }
  1608. /*
  1609. * Accept new connection and construct task
  1610. */
  1611. static void
  1612. accept_fuzzy_socket (gint fd, short what, void *arg)
  1613. {
  1614. struct rspamd_worker *worker = (struct rspamd_worker *)arg;
  1615. struct fuzzy_session *session;
  1616. rspamd_inet_addr_t *addr;
  1617. gssize r;
  1618. guint8 buf[512];
  1619. guint64 *nerrors;
  1620. /* Got some data */
  1621. if (what == EV_READ) {
  1622. for (;;) {
  1623. worker->nconns++;
  1624. r = rspamd_inet_address_recvfrom (fd,
  1625. buf,
  1626. sizeof (buf),
  1627. 0,
  1628. &addr);
  1629. if (r == -1) {
  1630. if (errno == EINTR) {
  1631. continue;
  1632. }
  1633. else if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1634. return;
  1635. }
  1636. msg_err ("got error while reading from socket: %d, %s",
  1637. errno,
  1638. strerror (errno));
  1639. return;
  1640. }
  1641. session = g_malloc0 (sizeof (*session));
  1642. REF_INIT_RETAIN (session, fuzzy_session_destroy);
  1643. session->worker = worker;
  1644. session->fd = fd;
  1645. session->ctx = worker->ctx;
  1646. session->time = (guint64) time (NULL);
  1647. session->addr = addr;
  1648. if (rspamd_fuzzy_cmd_from_wire (buf, r, session)) {
  1649. /* Check shingles count sanity */
  1650. rspamd_fuzzy_process_command (session);
  1651. }
  1652. else {
  1653. /* Discard input */
  1654. session->ctx->stat.invalid_requests ++;
  1655. msg_debug ("invalid fuzzy command of size %z received", r);
  1656. nerrors = rspamd_lru_hash_lookup (session->ctx->errors_ips,
  1657. addr, -1);
  1658. if (nerrors == NULL) {
  1659. nerrors = g_malloc (sizeof (*nerrors));
  1660. *nerrors = 1;
  1661. rspamd_lru_hash_insert (session->ctx->errors_ips,
  1662. rspamd_inet_address_copy (addr),
  1663. nerrors, -1, -1);
  1664. }
  1665. else {
  1666. *nerrors = *nerrors + 1;
  1667. }
  1668. }
  1669. REF_RELEASE (session);
  1670. }
  1671. }
  1672. }
  1673. static gboolean
  1674. rspamd_fuzzy_storage_periodic_callback (void *ud)
  1675. {
  1676. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1677. if (ctx->updates_pending->len > 0) {
  1678. rspamd_fuzzy_process_updates_queue (ctx, local_db_name, FALSE);
  1679. return TRUE;
  1680. }
  1681. return FALSE;
  1682. }
  1683. static gboolean
  1684. rspamd_fuzzy_storage_sync (struct rspamd_main *rspamd_main,
  1685. struct rspamd_worker *worker, gint fd,
  1686. gint attached_fd,
  1687. struct rspamd_control_command *cmd,
  1688. gpointer ud)
  1689. {
  1690. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1691. struct rspamd_control_reply rep;
  1692. rep.reply.fuzzy_sync.status = 0;
  1693. if (ctx->backend && worker->index == 0) {
  1694. rspamd_fuzzy_process_updates_queue (ctx, local_db_name, FALSE);
  1695. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  1696. rspamd_fuzzy_storage_periodic_callback, ctx);
  1697. }
  1698. if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
  1699. msg_err ("cannot write reply to the control socket: %s",
  1700. strerror (errno));
  1701. }
  1702. return TRUE;
  1703. }
  1704. static gboolean
  1705. rspamd_fuzzy_storage_reload (struct rspamd_main *rspamd_main,
  1706. struct rspamd_worker *worker, gint fd,
  1707. gint attached_fd,
  1708. struct rspamd_control_command *cmd,
  1709. gpointer ud)
  1710. {
  1711. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1712. GError *err = NULL;
  1713. struct rspamd_control_reply rep;
  1714. msg_info ("reloading fuzzy storage after receiving reload command");
  1715. if (ctx->backend) {
  1716. /* Close backend and reopen it one more time */
  1717. rspamd_fuzzy_backend_close (ctx->backend);
  1718. }
  1719. memset (&rep, 0, sizeof (rep));
  1720. rep.type = RSPAMD_CONTROL_RELOAD;
  1721. if ((ctx->backend = rspamd_fuzzy_backend_create (ctx->ev_base,
  1722. worker->cf->options, rspamd_main->cfg,
  1723. &err)) == NULL) {
  1724. msg_err ("cannot open backend after reload: %e", err);
  1725. g_error_free (err);
  1726. rep.reply.reload.status = err->code;
  1727. }
  1728. else {
  1729. rep.reply.reload.status = 0;
  1730. }
  1731. if (ctx->backend && worker->index == 0) {
  1732. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  1733. rspamd_fuzzy_storage_periodic_callback, ctx);
  1734. }
  1735. if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
  1736. msg_err ("cannot write reply to the control socket: %s",
  1737. strerror (errno));
  1738. }
  1739. return TRUE;
  1740. }
  1741. static ucl_object_t *
  1742. rspamd_fuzzy_storage_stat_key (struct fuzzy_key_stat *key_stat)
  1743. {
  1744. ucl_object_t *res;
  1745. res = ucl_object_typed_new (UCL_OBJECT);
  1746. ucl_object_insert_key (res, ucl_object_fromint (key_stat->checked),
  1747. "checked", 0, false);
  1748. ucl_object_insert_key (res, ucl_object_fromint (key_stat->matched),
  1749. "matched", 0, false);
  1750. ucl_object_insert_key (res, ucl_object_fromint (key_stat->added),
  1751. "added", 0, false);
  1752. ucl_object_insert_key (res, ucl_object_fromint (key_stat->deleted),
  1753. "deleted", 0, false);
  1754. ucl_object_insert_key (res, ucl_object_fromint (key_stat->errors),
  1755. "errors", 0, false);
  1756. return res;
  1757. }
  1758. static ucl_object_t *
  1759. rspamd_fuzzy_stat_to_ucl (struct rspamd_fuzzy_storage_ctx *ctx, gboolean ip_stat)
  1760. {
  1761. GHashTableIter it, ip_it;
  1762. GHashTable *ip_hash;
  1763. struct fuzzy_key_stat *key_stat;
  1764. struct fuzzy_key *key;
  1765. rspamd_lru_element_t *lru_elt;
  1766. ucl_object_t *obj, *keys_obj, *elt, *ip_elt, *ip_cur;
  1767. gpointer k, v;
  1768. gint i;
  1769. gchar keyname[17];
  1770. obj = ucl_object_typed_new (UCL_OBJECT);
  1771. keys_obj = ucl_object_typed_new (UCL_OBJECT);
  1772. g_hash_table_iter_init (&it, ctx->keys);
  1773. while (g_hash_table_iter_next (&it, &k, &v)) {
  1774. key = v;
  1775. key_stat = key->stat;
  1776. if (key_stat) {
  1777. rspamd_snprintf (keyname, sizeof (keyname), "%8bs", k);
  1778. elt = rspamd_fuzzy_storage_stat_key (key_stat);
  1779. if (key_stat->last_ips && ip_stat) {
  1780. ip_hash = rspamd_lru_hash_get_htable (key_stat->last_ips);
  1781. if (ip_hash) {
  1782. g_hash_table_iter_init (&ip_it, ip_hash);
  1783. ip_elt = ucl_object_typed_new (UCL_OBJECT);
  1784. while (g_hash_table_iter_next (&ip_it, &k, &v)) {
  1785. lru_elt = v;
  1786. ip_cur = rspamd_fuzzy_storage_stat_key (
  1787. rspamd_lru_hash_element_data (lru_elt));
  1788. ucl_object_insert_key (ip_elt, ip_cur,
  1789. rspamd_inet_address_to_string (k), 0, true);
  1790. }
  1791. ucl_object_insert_key (elt, ip_elt, "ips", 0, false);
  1792. }
  1793. }
  1794. ucl_object_insert_key (keys_obj, elt, keyname, 0, true);
  1795. }
  1796. }
  1797. ucl_object_insert_key (obj, keys_obj, "keys", 0, false);
  1798. /* Now generic stats */
  1799. ucl_object_insert_key (obj,
  1800. ucl_object_fromint (ctx->stat.fuzzy_hashes),
  1801. "fuzzy_stored",
  1802. 0,
  1803. false);
  1804. ucl_object_insert_key (obj,
  1805. ucl_object_fromint (ctx->stat.fuzzy_hashes_expired),
  1806. "fuzzy_expired",
  1807. 0,
  1808. false);
  1809. ucl_object_insert_key (obj,
  1810. ucl_object_fromint (ctx->stat.invalid_requests),
  1811. "invalid_requests",
  1812. 0,
  1813. false);
  1814. if (ctx->errors_ips && ip_stat) {
  1815. ip_hash = rspamd_lru_hash_get_htable (ctx->errors_ips);
  1816. if (ip_hash) {
  1817. g_hash_table_iter_init (&ip_it, ip_hash);
  1818. ip_elt = ucl_object_typed_new (UCL_OBJECT);
  1819. while (g_hash_table_iter_next (&ip_it, &k, &v)) {
  1820. lru_elt = v;
  1821. ucl_object_insert_key (ip_elt,
  1822. ucl_object_fromint (*(guint64 *)
  1823. rspamd_lru_hash_element_data (lru_elt)),
  1824. rspamd_inet_address_to_string (k), 0, true);
  1825. }
  1826. ucl_object_insert_key (obj,
  1827. ip_elt,
  1828. "errors_ips",
  1829. 0,
  1830. false);
  1831. }
  1832. }
  1833. /* Checked by epoch */
  1834. elt = ucl_object_typed_new (UCL_ARRAY);
  1835. for (i = RSPAMD_FUZZY_EPOCH6; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1836. ucl_array_append (elt,
  1837. ucl_object_fromint (ctx->stat.fuzzy_hashes_checked[i]));
  1838. }
  1839. ucl_object_insert_key (obj, elt, "fuzzy_checked", 0, false);
  1840. /* Shingles by epoch */
  1841. elt = ucl_object_typed_new (UCL_ARRAY);
  1842. for (i = RSPAMD_FUZZY_EPOCH6; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1843. ucl_array_append (elt,
  1844. ucl_object_fromint (ctx->stat.fuzzy_shingles_checked[i]));
  1845. }
  1846. ucl_object_insert_key (obj, elt, "fuzzy_shingles", 0, false);
  1847. /* Matched by epoch */
  1848. elt = ucl_object_typed_new (UCL_ARRAY);
  1849. for (i = RSPAMD_FUZZY_EPOCH6; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1850. ucl_array_append (elt,
  1851. ucl_object_fromint (ctx->stat.fuzzy_hashes_found[i]));
  1852. }
  1853. ucl_object_insert_key (obj, elt, "fuzzy_found", 0, false);
  1854. return obj;
  1855. }
  1856. static gboolean
  1857. rspamd_fuzzy_storage_stat (struct rspamd_main *rspamd_main,
  1858. struct rspamd_worker *worker, gint fd,
  1859. gint attached_fd,
  1860. struct rspamd_control_command *cmd,
  1861. gpointer ud)
  1862. {
  1863. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1864. struct rspamd_control_reply rep;
  1865. ucl_object_t *obj;
  1866. struct ucl_emitter_functions *emit_subr;
  1867. guchar fdspace[CMSG_SPACE(sizeof (int))];
  1868. struct iovec iov;
  1869. struct msghdr msg;
  1870. struct cmsghdr *cmsg;
  1871. gint outfd = -1;
  1872. gchar tmppath[PATH_MAX];
  1873. memset (&rep, 0, sizeof (rep));
  1874. rep.type = RSPAMD_CONTROL_FUZZY_STAT;
  1875. rspamd_snprintf (tmppath, sizeof (tmppath), "%s%c%s-XXXXXXXXXX",
  1876. rspamd_main->cfg->temp_dir, G_DIR_SEPARATOR, "fuzzy-stat");
  1877. if ((outfd = mkstemp (tmppath)) == -1) {
  1878. rep.reply.fuzzy_stat.status = errno;
  1879. msg_info_main ("cannot make temporary stat file for fuzzy stat: %s",
  1880. strerror (errno));
  1881. }
  1882. else {
  1883. rep.reply.fuzzy_stat.status = 0;
  1884. memcpy (rep.reply.fuzzy_stat.storage_id,
  1885. rspamd_fuzzy_backend_id (ctx->backend),
  1886. sizeof (rep.reply.fuzzy_stat.storage_id));
  1887. obj = rspamd_fuzzy_stat_to_ucl (ctx, TRUE);
  1888. emit_subr = ucl_object_emit_fd_funcs (outfd);
  1889. ucl_object_emit_full (obj, UCL_EMIT_JSON_COMPACT, emit_subr, NULL);
  1890. ucl_object_emit_funcs_free (emit_subr);
  1891. ucl_object_unref (obj);
  1892. /* Rewind output file */
  1893. close (outfd);
  1894. outfd = open (tmppath, O_RDONLY);
  1895. unlink (tmppath);
  1896. }
  1897. /* Now we can send outfd and status message */
  1898. memset (&msg, 0, sizeof (msg));
  1899. /* Attach fd to the message */
  1900. if (outfd != -1) {
  1901. memset (fdspace, 0, sizeof (fdspace));
  1902. msg.msg_control = fdspace;
  1903. msg.msg_controllen = sizeof (fdspace);
  1904. cmsg = CMSG_FIRSTHDR (&msg);
  1905. if (cmsg) {
  1906. cmsg->cmsg_level = SOL_SOCKET;
  1907. cmsg->cmsg_type = SCM_RIGHTS;
  1908. cmsg->cmsg_len = CMSG_LEN (sizeof (int));
  1909. memcpy (CMSG_DATA (cmsg), &outfd, sizeof (int));
  1910. }
  1911. }
  1912. iov.iov_base = &rep;
  1913. iov.iov_len = sizeof (rep);
  1914. msg.msg_iov = &iov;
  1915. msg.msg_iovlen = 1;
  1916. if (sendmsg (fd, &msg, 0) == -1) {
  1917. msg_err_main ("cannot send fuzzy stat: %s", strerror (errno));
  1918. }
  1919. if (outfd != -1) {
  1920. close (outfd);
  1921. }
  1922. return TRUE;
  1923. }
  1924. static gboolean
  1925. fuzzy_storage_parse_mirror (rspamd_mempool_t *pool,
  1926. const ucl_object_t *obj,
  1927. gpointer ud,
  1928. struct rspamd_rcl_section *section,
  1929. GError **err)
  1930. {
  1931. const ucl_object_t *elt;
  1932. struct rspamd_fuzzy_mirror *up = NULL;
  1933. struct rspamd_rcl_struct_parser *pd = ud;
  1934. struct rspamd_fuzzy_storage_ctx *ctx;
  1935. ctx = pd->user_struct;
  1936. if (ucl_object_type (obj) != UCL_OBJECT) {
  1937. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1938. "mirror/slave option must be an object");
  1939. return FALSE;
  1940. }
  1941. elt = ucl_object_lookup (obj, "name");
  1942. if (elt == NULL) {
  1943. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1944. "mirror option must have some name definition");
  1945. return FALSE;
  1946. }
  1947. up = g_malloc0 (sizeof (*up));
  1948. up->name = g_strdup (ucl_object_tostring (elt));
  1949. elt = ucl_object_lookup (obj, "key");
  1950. if (elt != NULL) {
  1951. up->key = rspamd_pubkey_from_base32 (ucl_object_tostring (elt), 0,
  1952. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  1953. }
  1954. if (up->key == NULL) {
  1955. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1956. "cannot read mirror key");
  1957. goto err;
  1958. }
  1959. elt = ucl_object_lookup (obj, "hosts");
  1960. if (elt == NULL) {
  1961. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1962. "mirror option must have some hosts definition");
  1963. goto err;
  1964. }
  1965. up->u = rspamd_upstreams_create (ctx->cfg->ups_ctx);
  1966. if (!rspamd_upstreams_from_ucl (up->u, elt, 11335, NULL)) {
  1967. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1968. "mirror has bad hosts definition");
  1969. goto err;
  1970. }
  1971. g_ptr_array_add (ctx->mirrors, up);
  1972. return TRUE;
  1973. err:
  1974. g_free (up->name);
  1975. rspamd_upstreams_destroy (up->u);
  1976. if (up->key) {
  1977. rspamd_pubkey_unref (up->key);
  1978. }
  1979. g_free (up);
  1980. return FALSE;
  1981. }
  1982. static gboolean
  1983. fuzzy_storage_parse_master_flags (rspamd_mempool_t *pool,
  1984. const ucl_object_t *obj,
  1985. gpointer ud,
  1986. struct rspamd_rcl_section *section,
  1987. GError **err)
  1988. {
  1989. const ucl_object_t *cur;
  1990. struct rspamd_rcl_struct_parser *pd = ud;
  1991. struct rspamd_fuzzy_storage_ctx *ctx;
  1992. ucl_object_iter_t it = NULL;
  1993. gulong remote_flag;
  1994. gint64 local_flag;
  1995. ctx = pd->user_struct;
  1996. if (ucl_object_type (obj) != UCL_OBJECT) {
  1997. g_set_error (err, g_quark_try_string ("fuzzy"), 100,
  1998. "master_flags option must be an object");
  1999. return FALSE;
  2000. }
  2001. while ((cur = ucl_iterate_object (obj, &it, true)) != NULL) {
  2002. if (rspamd_strtoul (cur->key, cur->keylen, &remote_flag) &&
  2003. ucl_object_toint_safe (cur, (int64_t *)&local_flag)) {
  2004. g_hash_table_insert (ctx->master_flags, GUINT_TO_POINTER (remote_flag),
  2005. GUINT_TO_POINTER (local_flag));
  2006. }
  2007. }
  2008. return TRUE;
  2009. }
  2010. static gboolean
  2011. fuzzy_parse_keypair (rspamd_mempool_t *pool,
  2012. const ucl_object_t *obj,
  2013. gpointer ud,
  2014. struct rspamd_rcl_section *section,
  2015. GError **err)
  2016. {
  2017. struct rspamd_rcl_struct_parser *pd = ud;
  2018. struct rspamd_fuzzy_storage_ctx *ctx;
  2019. struct rspamd_cryptobox_keypair *kp;
  2020. struct fuzzy_key_stat *keystat;
  2021. struct fuzzy_key *key;
  2022. const ucl_object_t *cur;
  2023. const guchar *pk;
  2024. ucl_object_iter_t it = NULL;
  2025. gboolean ret;
  2026. ctx = pd->user_struct;
  2027. pd->offset = G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, default_keypair);
  2028. /*
  2029. * Single key
  2030. */
  2031. if (ucl_object_type (obj) == UCL_STRING || ucl_object_type (obj)
  2032. == UCL_OBJECT) {
  2033. ret = rspamd_rcl_parse_struct_keypair (pool, obj, pd, section, err);
  2034. if (!ret) {
  2035. return ret;
  2036. }
  2037. /* Insert key to the hash table */
  2038. kp = ctx->default_keypair;
  2039. if (kp == NULL) {
  2040. return FALSE;
  2041. }
  2042. if (rspamd_keypair_alg (kp) != RSPAMD_CRYPTOBOX_MODE_25519 ||
  2043. rspamd_keypair_type (kp) != RSPAMD_KEYPAIR_KEX) {
  2044. return FALSE;
  2045. }
  2046. key = rspamd_mempool_alloc0 (pool, sizeof (*key));
  2047. key->key = kp;
  2048. keystat = rspamd_mempool_alloc0 (pool, sizeof (*keystat));
  2049. /* Hash of ip -> fuzzy_key_stat */
  2050. keystat->last_ips = rspamd_lru_hash_new_full (1024,
  2051. (GDestroyNotify) rspamd_inet_address_free, fuzzy_key_stat_dtor,
  2052. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2053. key->stat = keystat;
  2054. pk = rspamd_keypair_component (kp, RSPAMD_KEYPAIR_COMPONENT_PK,
  2055. NULL);
  2056. g_hash_table_insert (ctx->keys, (gpointer)pk, key);
  2057. ctx->default_key = key;
  2058. msg_info_pool ("loaded keypair %*xs", 8, pk);
  2059. }
  2060. else if (ucl_object_type (obj) == UCL_ARRAY) {
  2061. while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
  2062. if (!fuzzy_parse_keypair (pool, cur, pd, section, err)) {
  2063. msg_err_pool ("cannot parse keypair");
  2064. }
  2065. }
  2066. }
  2067. return TRUE;
  2068. }
  2069. static guint
  2070. fuzzy_kp_hash (gconstpointer p)
  2071. {
  2072. return *(guint *)p;
  2073. }
  2074. static gboolean
  2075. fuzzy_kp_equal (gconstpointer a, gconstpointer b)
  2076. {
  2077. const guchar *pa = a, *pb = b;
  2078. return (memcmp (pa, pb, RSPAMD_FUZZY_KEYLEN) == 0);
  2079. }
  2080. gpointer
  2081. init_fuzzy (struct rspamd_config *cfg)
  2082. {
  2083. struct rspamd_fuzzy_storage_ctx *ctx;
  2084. GQuark type;
  2085. type = g_quark_try_string ("fuzzy");
  2086. ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
  2087. sizeof (struct rspamd_fuzzy_storage_ctx));
  2088. ctx->magic = rspamd_fuzzy_storage_magic;
  2089. ctx->sync_timeout = DEFAULT_SYNC_TIMEOUT;
  2090. ctx->master_timeout = DEFAULT_MASTER_TIMEOUT;
  2091. ctx->keypair_cache_size = DEFAULT_KEYPAIR_CACHE_SIZE;
  2092. ctx->keys = g_hash_table_new_full (fuzzy_kp_hash, fuzzy_kp_equal,
  2093. NULL, fuzzy_key_dtor);
  2094. rspamd_mempool_add_destructor (cfg->cfg_pool,
  2095. (rspamd_mempool_destruct_t)g_hash_table_unref, ctx->keys);
  2096. ctx->master_flags = g_hash_table_new (g_direct_hash, g_direct_equal);
  2097. rspamd_mempool_add_destructor (cfg->cfg_pool,
  2098. (rspamd_mempool_destruct_t)g_hash_table_unref, ctx->master_flags);
  2099. ctx->errors_ips = rspamd_lru_hash_new_full (1024,
  2100. (GDestroyNotify) rspamd_inet_address_free, g_free,
  2101. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2102. rspamd_mempool_add_destructor (cfg->cfg_pool,
  2103. (rspamd_mempool_destruct_t)rspamd_lru_hash_destroy, ctx->errors_ips);
  2104. ctx->cfg = cfg;
  2105. ctx->mirrors = g_ptr_array_new ();
  2106. rspamd_mempool_add_destructor (cfg->cfg_pool,
  2107. (rspamd_mempool_destruct_t)rspamd_ptr_array_free_hard, ctx->mirrors);
  2108. ctx->updates_maxfail = DEFAULT_UPDATES_MAXFAIL;
  2109. ctx->collection_id_file = RSPAMD_DBDIR "/fuzzy_collection.id";
  2110. rspamd_rcl_register_worker_option (cfg,
  2111. type,
  2112. "sync",
  2113. rspamd_rcl_parse_struct_time,
  2114. ctx,
  2115. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  2116. sync_timeout),
  2117. RSPAMD_CL_FLAG_TIME_FLOAT,
  2118. "Time to perform database sync, default: "
  2119. G_STRINGIFY (DEFAULT_SYNC_TIMEOUT) " seconds");
  2120. rspamd_rcl_register_worker_option (cfg,
  2121. type,
  2122. "expire",
  2123. rspamd_rcl_parse_struct_time,
  2124. ctx,
  2125. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  2126. expire),
  2127. RSPAMD_CL_FLAG_TIME_FLOAT,
  2128. "Default expire time for hashes, default: "
  2129. G_STRINGIFY (DEFAULT_EXPIRE) " seconds");
  2130. rspamd_rcl_register_worker_option (cfg,
  2131. type,
  2132. "allow_update",
  2133. rspamd_rcl_parse_struct_ucl,
  2134. ctx,
  2135. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, update_map),
  2136. 0,
  2137. "Allow modifications from the following IP addresses");
  2138. rspamd_rcl_register_worker_option (cfg,
  2139. type,
  2140. "keypair",
  2141. fuzzy_parse_keypair,
  2142. ctx,
  2143. 0,
  2144. RSPAMD_CL_FLAG_MULTIPLE,
  2145. "Encryption keypair (can be repeated for different keys)");
  2146. rspamd_rcl_register_worker_option (cfg,
  2147. type,
  2148. "keypair_cache_size",
  2149. rspamd_rcl_parse_struct_integer,
  2150. ctx,
  2151. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx,
  2152. keypair_cache_size),
  2153. RSPAMD_CL_FLAG_UINT,
  2154. "Size of keypairs cache, default: "
  2155. G_STRINGIFY (DEFAULT_KEYPAIR_CACHE_SIZE));
  2156. rspamd_rcl_register_worker_option (cfg,
  2157. type,
  2158. "encrypted_only",
  2159. rspamd_rcl_parse_struct_boolean,
  2160. ctx,
  2161. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, encrypted_only),
  2162. 0,
  2163. "Allow encrypted requests only (and forbid all unknown keys or plaintext requests)");
  2164. rspamd_rcl_register_worker_option (cfg,
  2165. type,
  2166. "read_only",
  2167. rspamd_rcl_parse_struct_boolean,
  2168. ctx,
  2169. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, read_only),
  2170. 0,
  2171. "Work in read only mode");
  2172. rspamd_rcl_register_worker_option (cfg,
  2173. type,
  2174. "master_timeout",
  2175. rspamd_rcl_parse_struct_time,
  2176. ctx,
  2177. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, master_timeout),
  2178. RSPAMD_CL_FLAG_TIME_FLOAT,
  2179. "Master protocol IO timeout");
  2180. rspamd_rcl_register_worker_option (cfg,
  2181. type,
  2182. "sync_keypair",
  2183. rspamd_rcl_parse_struct_keypair,
  2184. ctx,
  2185. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, sync_keypair),
  2186. 0,
  2187. "Encryption key for master/slave updates");
  2188. rspamd_rcl_register_worker_option (cfg,
  2189. type,
  2190. "masters",
  2191. rspamd_rcl_parse_struct_ucl,
  2192. ctx,
  2193. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, masters_map),
  2194. 0,
  2195. "Allow master/slave updates from the following IP addresses");
  2196. rspamd_rcl_register_worker_option (cfg,
  2197. type,
  2198. "blocked",
  2199. rspamd_rcl_parse_struct_ucl,
  2200. ctx,
  2201. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, blocked_map),
  2202. 0,
  2203. "Block requests from specific networks");
  2204. rspamd_rcl_register_worker_option (cfg,
  2205. type,
  2206. "master_key",
  2207. rspamd_rcl_parse_struct_pubkey,
  2208. ctx,
  2209. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, master_key),
  2210. 0,
  2211. "Allow master/slave updates merely using the specified key");
  2212. rspamd_rcl_register_worker_option (cfg,
  2213. type,
  2214. "mirror",
  2215. fuzzy_storage_parse_mirror,
  2216. ctx,
  2217. 0,
  2218. RSPAMD_CL_FLAG_MULTIPLE,
  2219. "List of slave hosts");
  2220. rspamd_rcl_register_worker_option (cfg,
  2221. type,
  2222. "slave",
  2223. fuzzy_storage_parse_mirror,
  2224. ctx,
  2225. 0,
  2226. RSPAMD_CL_FLAG_MULTIPLE,
  2227. "List of slave hosts");
  2228. rspamd_rcl_register_worker_option (cfg,
  2229. type,
  2230. "master_flags",
  2231. fuzzy_storage_parse_master_flags,
  2232. ctx,
  2233. 0,
  2234. 0,
  2235. "Map of flags in form master_flags = { master_flag = local_flag; ... }; ");
  2236. rspamd_rcl_register_worker_option (cfg,
  2237. type,
  2238. "updates_maxfail",
  2239. rspamd_rcl_parse_struct_integer,
  2240. ctx,
  2241. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, updates_maxfail),
  2242. RSPAMD_CL_FLAG_UINT,
  2243. "Maximum number of updates to be failed before discarding");
  2244. rspamd_rcl_register_worker_option (cfg,
  2245. type,
  2246. "collection_only",
  2247. rspamd_rcl_parse_struct_boolean,
  2248. ctx,
  2249. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, collection_mode),
  2250. 0,
  2251. "Start fuzzy in collection only mode");
  2252. rspamd_rcl_register_worker_option (cfg,
  2253. type,
  2254. "collection_signkey",
  2255. rspamd_rcl_parse_struct_pubkey,
  2256. ctx,
  2257. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, collection_sign_key),
  2258. RSPAMD_CL_FLAG_SIGNKEY,
  2259. "Accept only signed requests with the specified key");
  2260. rspamd_rcl_register_worker_option (cfg,
  2261. type,
  2262. "collection_keypair",
  2263. rspamd_rcl_parse_struct_keypair,
  2264. ctx,
  2265. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, collection_keypair),
  2266. 0,
  2267. "Use the specified keypair to encrypt collection protocol");
  2268. rspamd_rcl_register_worker_option (cfg,
  2269. type,
  2270. "collection_id_file",
  2271. rspamd_rcl_parse_struct_string,
  2272. ctx,
  2273. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, collection_id_file),
  2274. RSPAMD_CL_FLAG_STRING_PATH,
  2275. "Store collection epoch in the desired file");
  2276. rspamd_rcl_register_worker_option (cfg,
  2277. type,
  2278. "skip_hashes",
  2279. rspamd_rcl_parse_struct_ucl,
  2280. ctx,
  2281. G_STRUCT_OFFSET (struct rspamd_fuzzy_storage_ctx, skip_map),
  2282. 0,
  2283. "Skip specific hashes from the map");
  2284. return ctx;
  2285. }
  2286. static void
  2287. rspamd_fuzzy_peer_io (gint fd, gshort what, gpointer d)
  2288. {
  2289. struct fuzzy_peer_cmd cmd;
  2290. struct rspamd_fuzzy_storage_ctx *ctx = d;
  2291. gssize r;
  2292. r = read (fd, &cmd, sizeof (cmd));
  2293. if (r != sizeof (cmd)) {
  2294. if (errno == EINTR) {
  2295. rspamd_fuzzy_peer_io (fd, what, d);
  2296. return;
  2297. }
  2298. if (errno != EAGAIN) {
  2299. msg_err ("cannot read command from peers: %s", strerror (errno));
  2300. }
  2301. }
  2302. else {
  2303. g_array_append_val (ctx->updates_pending, cmd);
  2304. }
  2305. }
  2306. static void
  2307. fuzzy_peer_rep (struct rspamd_worker *worker,
  2308. struct rspamd_srv_reply *rep, gint rep_fd,
  2309. gpointer ud)
  2310. {
  2311. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2312. GList *cur;
  2313. struct rspamd_worker_listen_socket *ls;
  2314. struct event *accept_events;
  2315. ctx->peer_fd = rep_fd;
  2316. if (rep_fd == -1) {
  2317. msg_err ("cannot receive peer fd from the main process");
  2318. exit (EXIT_FAILURE);
  2319. }
  2320. else {
  2321. rspamd_socket_nonblocking (rep_fd);
  2322. }
  2323. msg_info ("got peer fd reply from the main process");
  2324. /* Start listening */
  2325. cur = worker->cf->listen_socks;
  2326. while (cur) {
  2327. ls = cur->data;
  2328. if (ls->fd != -1) {
  2329. msg_info ("start listening on %s",
  2330. rspamd_inet_address_to_string_pretty (ls->addr));
  2331. if (ls->type == RSPAMD_WORKER_SOCKET_UDP) {
  2332. accept_events = g_malloc0 (sizeof (struct event) * 2);
  2333. event_set (&accept_events[0], ls->fd, EV_READ | EV_PERSIST,
  2334. accept_fuzzy_socket, worker);
  2335. event_base_set (ctx->ev_base, &accept_events[0]);
  2336. event_add (&accept_events[0], NULL);
  2337. worker->accept_events = g_list_prepend (worker->accept_events,
  2338. accept_events);
  2339. }
  2340. else if (worker->index == 0) {
  2341. /* We allow TCP listeners only for a update worker */
  2342. accept_events = g_malloc0 (sizeof (struct event) * 2);
  2343. if (ctx->collection_mode) {
  2344. event_set (&accept_events[0], ls->fd, EV_READ | EV_PERSIST,
  2345. accept_fuzzy_collection_socket, worker);
  2346. }
  2347. else {
  2348. event_set (&accept_events[0], ls->fd, EV_READ | EV_PERSIST,
  2349. accept_fuzzy_mirror_socket, worker);
  2350. }
  2351. event_base_set (ctx->ev_base, &accept_events[0]);
  2352. event_add (&accept_events[0], NULL);
  2353. worker->accept_events = g_list_prepend (worker->accept_events,
  2354. accept_events);
  2355. }
  2356. }
  2357. cur = g_list_next (cur);
  2358. }
  2359. if (worker->index == 0 && ctx->peer_fd != -1) {
  2360. /* Listen for peer requests */
  2361. event_set (&ctx->peer_ev, ctx->peer_fd, EV_READ | EV_PERSIST,
  2362. rspamd_fuzzy_peer_io, ctx);
  2363. event_base_set (ctx->ev_base, &ctx->peer_ev);
  2364. event_add (&ctx->peer_ev, NULL);
  2365. }
  2366. }
  2367. /*
  2368. * Start worker process
  2369. */
  2370. void
  2371. start_fuzzy (struct rspamd_worker *worker)
  2372. {
  2373. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  2374. GError *err = NULL;
  2375. struct rspamd_srv_command srv_cmd;
  2376. struct rspamd_config *cfg = worker->srv->cfg;
  2377. ctx->ev_base = rspamd_prepare_worker (worker,
  2378. "fuzzy",
  2379. NULL);
  2380. ctx->peer_fd = -1;
  2381. ctx->worker = worker;
  2382. ctx->cfg = worker->srv->cfg;
  2383. double_to_tv (ctx->master_timeout, &ctx->master_io_tv);
  2384. ctx->resolver = dns_resolver_init (worker->srv->logger,
  2385. ctx->ev_base,
  2386. worker->srv->cfg);
  2387. rspamd_upstreams_library_config (worker->srv->cfg, ctx->cfg->ups_ctx,
  2388. ctx->ev_base, ctx->resolver->r);
  2389. if (ctx->keypair_cache_size > 0) {
  2390. /* Create keypairs cache */
  2391. ctx->keypair_cache = rspamd_keypair_cache_new (ctx->keypair_cache_size);
  2392. }
  2393. if (!ctx->collection_mode) {
  2394. /*
  2395. * Open DB and perform VACUUM
  2396. */
  2397. if ((ctx->backend = rspamd_fuzzy_backend_create (ctx->ev_base,
  2398. worker->cf->options, cfg, &err)) == NULL) {
  2399. msg_err ("cannot open backend: %e", err);
  2400. if (err) {
  2401. g_error_free (err);
  2402. }
  2403. exit (EXIT_SUCCESS);
  2404. }
  2405. rspamd_fuzzy_backend_count (ctx->backend, fuzzy_count_callback, ctx);
  2406. if (worker->index == 0) {
  2407. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  2408. sizeof (struct fuzzy_peer_cmd), 1024);
  2409. rspamd_fuzzy_backend_start_update (ctx->backend, ctx->sync_timeout,
  2410. rspamd_fuzzy_storage_periodic_callback, ctx);
  2411. }
  2412. double_to_tv (ctx->sync_timeout, &ctx->stat_tv);
  2413. event_set (&ctx->stat_ev, -1, EV_TIMEOUT, rspamd_fuzzy_stat_callback, ctx);
  2414. event_base_set (ctx->ev_base, &ctx->stat_ev);
  2415. event_add (&ctx->stat_ev, &ctx->stat_tv);
  2416. /* Register custom reload and stat commands for the control socket */
  2417. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_RELOAD,
  2418. rspamd_fuzzy_storage_reload, ctx);
  2419. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_STAT,
  2420. rspamd_fuzzy_storage_stat, ctx);
  2421. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_FUZZY_SYNC,
  2422. rspamd_fuzzy_storage_sync, ctx);
  2423. }
  2424. else {
  2425. /*
  2426. * In collection mode we do a different thing:
  2427. * we collect fuzzy hashes in the updates queue and ignore all read commands
  2428. */
  2429. if (worker->index == 0) {
  2430. ctx->updates_pending = g_array_sized_new (FALSE, FALSE,
  2431. sizeof (struct fuzzy_peer_cmd), 1024);
  2432. double_to_tv (ctx->sync_timeout, &ctx->stat_tv);
  2433. event_set (&ctx->stat_ev, -1, EV_TIMEOUT|EV_PERSIST,
  2434. rspamd_fuzzy_collection_periodic, ctx);
  2435. event_base_set (ctx->ev_base, &ctx->stat_ev);
  2436. event_add (&ctx->stat_ev, &ctx->stat_tv);
  2437. ctx->collection_rt = rspamd_http_router_new (
  2438. rspamd_fuzzy_collection_error_handler,
  2439. rspamd_fuzzy_collection_finish_handler,
  2440. &ctx->stat_tv,
  2441. ctx->ev_base,
  2442. NULL, ctx->keypair_cache);
  2443. if (ctx->collection_keypair) {
  2444. rspamd_http_router_set_key (ctx->collection_rt,
  2445. ctx->collection_keypair);
  2446. }
  2447. /* Try to load collection id */
  2448. if (ctx->collection_id_file) {
  2449. gint fd;
  2450. fd = rspamd_file_xopen (ctx->collection_id_file, O_RDONLY, 0,
  2451. FALSE);
  2452. if (fd == -1) {
  2453. if (errno != ENOENT) {
  2454. msg_err ("cannot open collection id from %s: %s",
  2455. ctx->collection_id_file, strerror (errno));
  2456. }
  2457. ctx->collection_id = 0;
  2458. }
  2459. else {
  2460. if (read (fd, &ctx->collection_id,
  2461. sizeof (ctx->collection_id)) == -1) {
  2462. msg_err ("cannot read collection id from %s: %s",
  2463. ctx->collection_id_file, strerror (errno));
  2464. ctx->collection_id = 0;
  2465. }
  2466. close (fd);
  2467. }
  2468. }
  2469. /* Generate new cookie */
  2470. ottery_rand_bytes (ctx->cookie, sizeof (ctx->cookie));
  2471. /* Register paths */
  2472. rspamd_http_router_add_path (ctx->collection_rt,
  2473. "/cookie",
  2474. rspamd_fuzzy_collection_cookie);
  2475. rspamd_http_router_add_path (ctx->collection_rt,
  2476. "/data",
  2477. rspamd_fuzzy_collection_data);
  2478. }
  2479. }
  2480. if (ctx->mirrors && ctx->mirrors->len != 0) {
  2481. if (ctx->sync_keypair == NULL) {
  2482. GString *pk_str = NULL;
  2483. ctx->sync_keypair = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
  2484. RSPAMD_CRYPTOBOX_MODE_25519);
  2485. pk_str = rspamd_keypair_print (ctx->sync_keypair,
  2486. RSPAMD_KEYPAIR_COMPONENT_PK|RSPAMD_KEYPAIR_BASE32);
  2487. msg_warn_config ("generating new temporary keypair for communicating"
  2488. " with slave hosts, pk is %s", pk_str->str);
  2489. g_string_free (pk_str, TRUE);
  2490. }
  2491. }
  2492. /* Create radix trees */
  2493. if (ctx->update_map != NULL) {
  2494. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->update_map,
  2495. "Allow fuzzy updates from specified addresses",
  2496. &ctx->update_ips, NULL);
  2497. }
  2498. if (ctx->masters_map != NULL) {
  2499. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->masters_map,
  2500. "Allow fuzzy master/slave updates from specified addresses",
  2501. &ctx->master_ips, NULL);
  2502. }
  2503. if (ctx->skip_map != NULL) {
  2504. struct rspamd_map *m;
  2505. if ((m = rspamd_map_add_from_ucl (cfg, ctx->skip_map,
  2506. "Skip hashes",
  2507. rspamd_kv_list_read,
  2508. rspamd_kv_list_fin,
  2509. rspamd_kv_list_dtor,
  2510. (void **)&ctx->skip_hashes)) == NULL) {
  2511. msg_warn_config ("cannot load hashes list from %s",
  2512. ucl_object_tostring (ctx->skip_map));
  2513. }
  2514. else {
  2515. m->active_http = TRUE;
  2516. }
  2517. }
  2518. if (ctx->blocked_map != NULL) {
  2519. rspamd_config_radix_from_ucl (worker->srv->cfg, ctx->blocked_map,
  2520. "Block fuzzy requests from the specific IPs",
  2521. &ctx->blocked_ips, NULL);
  2522. }
  2523. /* Maps events */
  2524. ctx->resolver = dns_resolver_init (worker->srv->logger,
  2525. ctx->ev_base,
  2526. worker->srv->cfg);
  2527. rspamd_map_watch (worker->srv->cfg, ctx->ev_base, ctx->resolver, worker, 0);
  2528. /* Get peer pipe */
  2529. memset (&srv_cmd, 0, sizeof (srv_cmd));
  2530. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  2531. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  2532. srv_cmd.cmd.spair.pair_num = worker->index;
  2533. memset (srv_cmd.cmd.spair.pair_id, 0, sizeof (srv_cmd.cmd.spair.pair_id));
  2534. memcpy (srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof ("fuzzy"));
  2535. rspamd_srv_send_command (worker, ctx->ev_base, &srv_cmd, -1,
  2536. fuzzy_peer_rep, ctx);
  2537. event_base_loop (ctx->ev_base, 0);
  2538. rspamd_worker_block_signals ();
  2539. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  2540. if (!ctx->collection_mode) {
  2541. rspamd_fuzzy_process_updates_queue (ctx, local_db_name, FALSE);
  2542. event_base_loop (ctx->ev_base, 0);
  2543. }
  2544. }
  2545. if (!ctx->collection_mode) {
  2546. rspamd_fuzzy_backend_close (ctx->backend);
  2547. }
  2548. else if (worker->index == 0) {
  2549. gint fd;
  2550. /* Steal keypairs cache... */
  2551. ctx->collection_rt->cache = NULL;
  2552. rspamd_http_router_free (ctx->collection_rt);
  2553. /* Try to save collection id */
  2554. fd = rspamd_file_xopen (ctx->collection_id_file,
  2555. O_WRONLY | O_CREAT | O_TRUNC, 00644, 0);
  2556. if (fd == -1) {
  2557. msg_err ("cannot open collection id to store in %s: %s",
  2558. ctx->collection_id_file, strerror (errno));
  2559. }
  2560. else {
  2561. if (write (fd, &ctx->collection_id,
  2562. sizeof (ctx->collection_id)) == -1) {
  2563. msg_err ("cannot store collection id in %s: %s",
  2564. ctx->collection_id_file, strerror (errno));
  2565. }
  2566. close (fd);
  2567. }
  2568. }
  2569. if (worker->index == 0) {
  2570. g_array_free (ctx->updates_pending, TRUE);
  2571. }
  2572. if (ctx->peer_fd != -1) {
  2573. if (worker->index == 0) {
  2574. event_del (&ctx->peer_ev);
  2575. }
  2576. close (ctx->peer_fd);
  2577. }
  2578. if (ctx->keypair_cache) {
  2579. rspamd_keypair_cache_destroy (ctx->keypair_cache);
  2580. }
  2581. REF_RELEASE (ctx->cfg);
  2582. rspamd_log_close (worker->srv->logger, TRUE);
  2583. exit (EXIT_SUCCESS);
  2584. }