Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

rspamd_symcache.c 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  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. #include "config.h"
  17. #include "util.h"
  18. #include "rspamd.h"
  19. #include "message.h"
  20. #include "rspamd_symcache.h"
  21. #include "cfg_file.h"
  22. #include "lua/lua_common.h"
  23. #include "unix-std.h"
  24. #include "contrib/t1ha/t1ha.h"
  25. #include "libserver/worker_util.h"
  26. #include <math.h>
  27. #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  28. # include <stdalign.h>
  29. #endif
  30. #define msg_err_cache(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \
  31. cache->static_pool->tag.tagname, cache->cfg->checksum, \
  32. G_STRFUNC, \
  33. __VA_ARGS__)
  34. #define msg_warn_cache(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  35. cache->static_pool->tag.tagname, cache->cfg->checksum, \
  36. G_STRFUNC, \
  37. __VA_ARGS__)
  38. #define msg_info_cache(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  39. cache->static_pool->tag.tagname, cache->cfg->checksum, \
  40. G_STRFUNC, \
  41. __VA_ARGS__)
  42. #define msg_debug_cache(...) rspamd_conditional_debug_fast (NULL, NULL, \
  43. rspamd_symcache_log_id, "symcache", cache->cfg->checksum, \
  44. G_STRFUNC, \
  45. __VA_ARGS__)
  46. #define msg_debug_cache_task(...) rspamd_conditional_debug_fast (NULL, NULL, \
  47. rspamd_symcache_log_id, "symcache", task->task_pool->tag.uid, \
  48. G_STRFUNC, \
  49. __VA_ARGS__)
  50. INIT_LOG_MODULE(symcache)
  51. #define CHECK_START_BIT(checkpoint, dyn_item) \
  52. ((dyn_item)->started)
  53. #define SET_START_BIT(checkpoint, dyn_item) \
  54. (dyn_item)->started = 1
  55. #define CHECK_FINISH_BIT(checkpoint, dyn_item) \
  56. ((dyn_item)->finished)
  57. #define SET_FINISH_BIT(checkpoint, dyn_item) \
  58. (dyn_item)->finished = 1
  59. static const guchar rspamd_symcache_magic[8] = {'r', 's', 'c', 2, 0, 0, 0, 0 };
  60. struct rspamd_symcache_header {
  61. guchar magic[8];
  62. guint nitems;
  63. guchar checksum[64];
  64. guchar unused[128];
  65. };
  66. struct symcache_order {
  67. GPtrArray *d;
  68. guint id;
  69. ref_entry_t ref;
  70. };
  71. struct rspamd_symcache {
  72. /* Hash table for fast access */
  73. GHashTable *items_by_symbol;
  74. GPtrArray *items_by_id;
  75. struct symcache_order *items_by_order;
  76. GPtrArray *filters;
  77. GPtrArray *prefilters;
  78. GPtrArray *postfilters;
  79. GPtrArray *composites;
  80. GPtrArray *idempotent;
  81. GPtrArray *virtual;
  82. GPtrArray *squeezed;
  83. GList *delayed_deps;
  84. GList *delayed_conditions;
  85. rspamd_mempool_t *static_pool;
  86. guint64 cksum;
  87. gdouble total_weight;
  88. guint used_items;
  89. guint stats_symbols_count;
  90. guint64 total_hits;
  91. guint id;
  92. struct rspamd_config *cfg;
  93. gdouble reload_time;
  94. gint peak_cb;
  95. };
  96. struct item_stat {
  97. struct rspamd_counter_data time_counter;
  98. gdouble avg_time;
  99. gdouble weight;
  100. guint hits;
  101. guint64 total_hits;
  102. struct rspamd_counter_data frequency_counter;
  103. gdouble avg_frequency;
  104. gdouble stddev_frequency;
  105. };
  106. struct rspamd_symcache_dynamic_item {
  107. guint16 start_msec; /* Relative to task time */
  108. unsigned started:1;
  109. unsigned finished:1;
  110. /* unsigned pad:14; */
  111. guint32 async_events;
  112. };
  113. struct rspamd_symcache_item {
  114. /* This block is likely shared */
  115. struct item_stat *st;
  116. guint64 last_count;
  117. struct rspamd_counter_data *cd;
  118. gchar *symbol;
  119. enum rspamd_symbol_type type;
  120. /* Callback data */
  121. union {
  122. struct {
  123. symbol_func_t func;
  124. gpointer user_data;
  125. gint condition_cb;
  126. } normal;
  127. struct {
  128. gint parent;
  129. } virtual;
  130. } specific;
  131. /* Condition of execution */
  132. gboolean enabled;
  133. /* Used for async stuff checks */
  134. gboolean is_filter;
  135. gboolean is_virtual;
  136. /* Priority */
  137. gint priority;
  138. /* Topological order */
  139. guint order;
  140. gint id;
  141. gint frequency_peaks;
  142. /* Dependencies */
  143. GPtrArray *deps;
  144. GPtrArray *rdeps;
  145. };
  146. struct cache_dependency {
  147. struct rspamd_symcache_item *item;
  148. gchar *sym;
  149. gint id;
  150. };
  151. struct delayed_cache_dependency {
  152. gchar *from;
  153. gchar *to;
  154. };
  155. struct delayed_cache_condition {
  156. gchar *sym;
  157. gint cbref;
  158. lua_State *L;
  159. };
  160. enum rspamd_cache_savepoint_stage {
  161. RSPAMD_CACHE_PASS_INIT = 0,
  162. RSPAMD_CACHE_PASS_PREFILTERS,
  163. RSPAMD_CACHE_PASS_FILTERS,
  164. RSPAMD_CACHE_PASS_POSTFILTERS,
  165. RSPAMD_CACHE_PASS_IDEMPOTENT,
  166. RSPAMD_CACHE_PASS_WAIT_IDEMPOTENT,
  167. RSPAMD_CACHE_PASS_DONE,
  168. };
  169. struct cache_savepoint {
  170. enum rspamd_cache_savepoint_stage pass;
  171. guint version;
  172. guint items_inflight;
  173. struct rspamd_metric_result *rs;
  174. gdouble lim;
  175. struct rspamd_symcache_item *cur_item;
  176. struct symcache_order *order;
  177. struct rspamd_symcache_dynamic_item dynamic_items[];
  178. };
  179. struct rspamd_cache_refresh_cbdata {
  180. gdouble last_resort;
  181. struct event resort_ev;
  182. struct rspamd_symcache *cache;
  183. struct rspamd_worker *w;
  184. struct event_base *ev_base;
  185. };
  186. /* weight, frequency, time */
  187. #define TIME_ALPHA (1.0)
  188. #define WEIGHT_ALPHA (0.1)
  189. #define FREQ_ALPHA (0.01)
  190. #define SCORE_FUN(w, f, t) (((w) > 0 ? (w) : WEIGHT_ALPHA) \
  191. * ((f) > 0 ? (f) : FREQ_ALPHA) \
  192. / (t > TIME_ALPHA ? t : TIME_ALPHA))
  193. static gboolean rspamd_symcache_check_symbol (struct rspamd_task *task,
  194. struct rspamd_symcache *cache,
  195. struct rspamd_symcache_item *item,
  196. struct cache_savepoint *checkpoint);
  197. static gboolean rspamd_symcache_check_deps (struct rspamd_task *task,
  198. struct rspamd_symcache *cache,
  199. struct rspamd_symcache_item *item,
  200. struct cache_savepoint *checkpoint,
  201. guint recursion,
  202. gboolean check_only);
  203. static void rspamd_symcache_disable_symbol_checkpoint (struct rspamd_task *task,
  204. struct rspamd_symcache *cache, const gchar *symbol);
  205. static void rspamd_symcache_enable_symbol_checkpoint (struct rspamd_task *task,
  206. struct rspamd_symcache *cache, const gchar *symbol);
  207. static void rspamd_symcache_disable_all_symbols (struct rspamd_task *task,
  208. struct rspamd_symcache *cache);
  209. static void
  210. rspamd_symcache_order_dtor (gpointer p)
  211. {
  212. struct symcache_order *ord = p;
  213. g_ptr_array_free (ord->d, TRUE);
  214. g_free (ord);
  215. }
  216. static void
  217. rspamd_symcache_order_unref (gpointer p)
  218. {
  219. struct symcache_order *ord = p;
  220. REF_RELEASE (ord);
  221. }
  222. static struct symcache_order *
  223. rspamd_symcache_order_new (struct rspamd_symcache *cache,
  224. gsize nelts)
  225. {
  226. struct symcache_order *ord;
  227. ord = g_malloc0 (sizeof (*ord));
  228. ord->d = g_ptr_array_sized_new (nelts);
  229. ord->id = cache->id;
  230. REF_INIT_RETAIN (ord, rspamd_symcache_order_dtor);
  231. return ord;
  232. }
  233. static inline struct rspamd_symcache_dynamic_item*
  234. rspamd_symcache_get_dynamic (struct cache_savepoint *checkpoint,
  235. struct rspamd_symcache_item *item)
  236. {
  237. return &checkpoint->dynamic_items[item->id];
  238. }
  239. static inline struct rspamd_symcache_item *
  240. rspamd_symcache_find_filter (struct rspamd_symcache *cache,
  241. const gchar *name)
  242. {
  243. struct rspamd_symcache_item *item;
  244. g_assert (cache != NULL);
  245. if (name == NULL) {
  246. return NULL;
  247. }
  248. item = g_hash_table_lookup (cache->items_by_symbol, name);
  249. if (item != NULL) {
  250. if (item->is_virtual) {
  251. item = g_ptr_array_index (cache->items_by_id,
  252. item->specific.virtual.parent);
  253. }
  254. return item;
  255. }
  256. return NULL;
  257. }
  258. static gint
  259. postfilters_cmp (const void *p1, const void *p2, gpointer ud)
  260. {
  261. const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1,
  262. *i2 = *(struct rspamd_symcache_item **)p2;
  263. double w1, w2;
  264. w1 = i1->priority;
  265. w2 = i2->priority;
  266. if (w1 > w2) {
  267. return 1;
  268. }
  269. else if (w1 < w2) {
  270. return -1;
  271. }
  272. return 0;
  273. }
  274. static gint
  275. prefilters_cmp (const void *p1, const void *p2, gpointer ud)
  276. {
  277. const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1,
  278. *i2 = *(struct rspamd_symcache_item **)p2;
  279. double w1, w2;
  280. w1 = i1->priority;
  281. w2 = i2->priority;
  282. if (w1 < w2) {
  283. return 1;
  284. }
  285. else if (w1 > w2) {
  286. return -1;
  287. }
  288. return 0;
  289. }
  290. #define TSORT_MARK_PERM(it) (it)->order |= (1u << 31)
  291. #define TSORT_MARK_TEMP(it) (it)->order |= (1u << 30)
  292. #define TSORT_IS_MARKED_PERM(it) ((it)->order & (1u << 31))
  293. #define TSORT_IS_MARKED_TEMP(it) ((it)->order & (1u << 30))
  294. #define TSORT_UNMASK(it) ((it)->order & ~((1u << 31) | (1u << 30)))
  295. static gint
  296. cache_logic_cmp (const void *p1, const void *p2, gpointer ud)
  297. {
  298. const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1,
  299. *i2 = *(struct rspamd_symcache_item **)p2;
  300. struct rspamd_symcache *cache = ud;
  301. double w1, w2;
  302. double weight1, weight2;
  303. double f1 = 0, f2 = 0, t1, t2, avg_freq, avg_weight;
  304. guint o1 = TSORT_UNMASK (i1), o2 = TSORT_UNMASK (i2);
  305. if (o1 == o2) {
  306. /* Heurstic */
  307. if (i1->priority == i2->priority) {
  308. avg_freq = ((gdouble) cache->total_hits / cache->used_items);
  309. avg_weight = (cache->total_weight / cache->used_items);
  310. f1 = (double) i1->st->total_hits / avg_freq;
  311. f2 = (double) i2->st->total_hits / avg_freq;
  312. weight1 = fabs (i1->st->weight) / avg_weight;
  313. weight2 = fabs (i2->st->weight) / avg_weight;
  314. t1 = i1->st->avg_time;
  315. t2 = i2->st->avg_time;
  316. w1 = SCORE_FUN (weight1, f1, t1);
  317. w2 = SCORE_FUN (weight2, f2, t2);
  318. } else {
  319. /* Strict sorting */
  320. w1 = abs (i1->priority);
  321. w2 = abs (i2->priority);
  322. }
  323. }
  324. else {
  325. w1 = o1;
  326. w2 = o2;
  327. }
  328. if (w2 > w1) {
  329. return 1;
  330. }
  331. else if (w2 < w1) {
  332. return -1;
  333. }
  334. return 0;
  335. }
  336. static void
  337. rspamd_symcache_tsort_visit (struct rspamd_symcache *cache,
  338. struct rspamd_symcache_item *it,
  339. guint cur_order)
  340. {
  341. struct cache_dependency *dep;
  342. guint i;
  343. if (TSORT_IS_MARKED_PERM (it)) {
  344. if (cur_order > TSORT_UNMASK (it)) {
  345. /* Need to recalculate the whole chain */
  346. it->order = cur_order; /* That also removes all masking */
  347. }
  348. else {
  349. /* We are fine, stop DFS */
  350. return;
  351. }
  352. }
  353. else if (TSORT_IS_MARKED_TEMP (it)) {
  354. msg_err_cache ("cyclic dependencies found when checking '%s'!",
  355. it->symbol);
  356. return;
  357. }
  358. TSORT_MARK_TEMP (it);
  359. msg_debug_cache ("visiting node: %s (%d)", it->symbol, cur_order);
  360. PTR_ARRAY_FOREACH (it->deps, i, dep) {
  361. msg_debug_cache ("visiting dep: %s (%d)", dep->item->symbol, cur_order + 1);
  362. rspamd_symcache_tsort_visit (cache, dep->item, cur_order + 1);
  363. }
  364. it->order = cur_order;
  365. TSORT_MARK_PERM (it);
  366. }
  367. static void
  368. rspamd_symcache_resort (struct rspamd_symcache *cache)
  369. {
  370. struct symcache_order *ord;
  371. guint i;
  372. guint64 total_hits = 0;
  373. struct rspamd_symcache_item *it;
  374. ord = rspamd_symcache_order_new (cache, cache->filters->len);
  375. for (i = 0; i < cache->filters->len; i ++) {
  376. it = g_ptr_array_index (cache->filters, i);
  377. total_hits += it->st->total_hits;
  378. it->order = 0;
  379. g_ptr_array_add (ord->d, it);
  380. }
  381. /* Topological sort, intended to be O(N) but my implementation
  382. * is not linear (semi-linear usually) as I want to make it as
  383. * simple as possible.
  384. * On each stage it does DFS for unseen nodes. In theory, that
  385. * can be more complicated than linear - O(N^2) for specially
  386. * crafted data. But I don't care.
  387. */
  388. PTR_ARRAY_FOREACH (ord->d, i, it) {
  389. if (it->order == 0) {
  390. rspamd_symcache_tsort_visit (cache, it, 1);
  391. }
  392. }
  393. /*
  394. * Now we have all sorted and can do some heuristical sort, keeping
  395. * topological order invariant
  396. */
  397. g_ptr_array_sort_with_data (ord->d, cache_logic_cmp, cache);
  398. cache->total_hits = total_hits;
  399. if (cache->items_by_order) {
  400. REF_RELEASE (cache->items_by_order);
  401. }
  402. cache->items_by_order = ord;
  403. }
  404. /* Sort items in logical order */
  405. static void
  406. rspamd_symcache_post_init (struct rspamd_symcache *cache)
  407. {
  408. struct rspamd_symcache_item *it, *dit;
  409. struct cache_dependency *dep, *rdep;
  410. struct delayed_cache_dependency *ddep;
  411. struct delayed_cache_condition *dcond;
  412. GList *cur;
  413. gint i, j;
  414. cur = cache->delayed_deps;
  415. while (cur) {
  416. ddep = cur->data;
  417. it = rspamd_symcache_find_filter (cache, ddep->from);
  418. if (it == NULL) {
  419. msg_err_cache ("cannot register delayed dependency between %s and %s, "
  420. "%s is missing", ddep->from, ddep->to, ddep->from);
  421. }
  422. else {
  423. msg_debug_cache ("delayed between %s(%d) -> %s", ddep->from,
  424. it->id, ddep->to);
  425. rspamd_symcache_add_dependency (cache, it->id, ddep->to);
  426. }
  427. cur = g_list_next (cur);
  428. }
  429. cur = cache->delayed_conditions;
  430. while (cur) {
  431. dcond = cur->data;
  432. it = rspamd_symcache_find_filter (cache, dcond->sym);
  433. if (it == NULL) {
  434. msg_err_cache (
  435. "cannot register delayed condition for %s",
  436. dcond->sym);
  437. luaL_unref (dcond->L, LUA_REGISTRYINDEX, dcond->cbref);
  438. }
  439. else {
  440. it->specific.normal.condition_cb = dcond->cbref;
  441. }
  442. cur = g_list_next (cur);
  443. }
  444. PTR_ARRAY_FOREACH (cache->items_by_id, i, it) {
  445. PTR_ARRAY_FOREACH (it->deps, j, dep) {
  446. dit = rspamd_symcache_find_filter (cache, dep->sym);
  447. if (dit != NULL) {
  448. if (dit->id == i) {
  449. msg_err_cache ("cannot add dependency on self: %s -> %s "
  450. "(resolved to %s)",
  451. it->symbol, dep->sym, dit->symbol);
  452. }
  453. else {
  454. rdep = rspamd_mempool_alloc (cache->static_pool,
  455. sizeof (*rdep));
  456. rdep->sym = dep->sym;
  457. rdep->item = it;
  458. rdep->id = i;
  459. g_ptr_array_add (dit->rdeps, rdep);
  460. dep->item = dit;
  461. dep->id = dit->id;
  462. msg_debug_cache ("add dependency from %d on %d", it->id,
  463. dit->id);
  464. }
  465. }
  466. else {
  467. msg_err_cache ("cannot find dependency on symbol %s", dep->sym);
  468. }
  469. }
  470. if (it->deps) {
  471. /* Reversed loop to make removal safe */
  472. for (j = it->deps->len - 1; j >= 0; j--) {
  473. dep = g_ptr_array_index (it->deps, j);
  474. if (dep->item == NULL) {
  475. /* Remove useless dep */
  476. g_ptr_array_remove_index (it->deps, j);
  477. }
  478. }
  479. }
  480. }
  481. g_ptr_array_sort_with_data (cache->prefilters, prefilters_cmp, cache);
  482. g_ptr_array_sort_with_data (cache->postfilters, postfilters_cmp, cache);
  483. g_ptr_array_sort_with_data (cache->idempotent, postfilters_cmp, cache);
  484. rspamd_symcache_resort (cache);
  485. }
  486. static gboolean
  487. rspamd_symcache_load_items (struct rspamd_symcache *cache, const gchar *name)
  488. {
  489. struct rspamd_symcache_header *hdr;
  490. struct stat st;
  491. struct ucl_parser *parser;
  492. ucl_object_t *top;
  493. const ucl_object_t *cur, *elt;
  494. ucl_object_iter_t it;
  495. struct rspamd_symcache_item *item, *parent;
  496. const guchar *p;
  497. gint fd;
  498. gpointer map;
  499. fd = open (name, O_RDONLY);
  500. if (fd == -1) {
  501. msg_info_cache ("cannot open file %s, error %d, %s", name,
  502. errno, strerror (errno));
  503. return FALSE;
  504. }
  505. rspamd_file_lock (fd, FALSE);
  506. if (fstat (fd, &st) == -1) {
  507. rspamd_file_unlock (fd, FALSE);
  508. close (fd);
  509. msg_info_cache ("cannot stat file %s, error %d, %s", name,
  510. errno, strerror (errno));
  511. return FALSE;
  512. }
  513. if (st.st_size < (gint)sizeof (*hdr)) {
  514. rspamd_file_unlock (fd, FALSE);
  515. close (fd);
  516. errno = EINVAL;
  517. msg_info_cache ("cannot use file %s, error %d, %s", name,
  518. errno, strerror (errno));
  519. return FALSE;
  520. }
  521. map = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
  522. if (map == MAP_FAILED) {
  523. rspamd_file_unlock (fd, FALSE);
  524. close (fd);
  525. msg_info_cache ("cannot mmap file %s, error %d, %s", name,
  526. errno, strerror (errno));
  527. return FALSE;
  528. }
  529. hdr = map;
  530. if (memcmp (hdr->magic, rspamd_symcache_magic,
  531. sizeof (rspamd_symcache_magic)) != 0) {
  532. msg_info_cache ("cannot use file %s, bad magic", name);
  533. munmap (map, st.st_size);
  534. rspamd_file_unlock (fd, FALSE);
  535. close (fd);
  536. return FALSE;
  537. }
  538. parser = ucl_parser_new (0);
  539. p = (const guchar *)(hdr + 1);
  540. if (!ucl_parser_add_chunk (parser, p, st.st_size - sizeof (*hdr))) {
  541. msg_info_cache ("cannot use file %s, cannot parse: %s", name,
  542. ucl_parser_get_error (parser));
  543. munmap (map, st.st_size);
  544. ucl_parser_free (parser);
  545. rspamd_file_unlock (fd, FALSE);
  546. close (fd);
  547. return FALSE;
  548. }
  549. top = ucl_parser_get_object (parser);
  550. munmap (map, st.st_size);
  551. rspamd_file_unlock (fd, FALSE);
  552. close (fd);
  553. ucl_parser_free (parser);
  554. if (top == NULL || ucl_object_type (top) != UCL_OBJECT) {
  555. msg_info_cache ("cannot use file %s, bad object", name);
  556. ucl_object_unref (top);
  557. return FALSE;
  558. }
  559. it = ucl_object_iterate_new (top);
  560. while ((cur = ucl_object_iterate_safe (it, true))) {
  561. item = g_hash_table_lookup (cache->items_by_symbol, ucl_object_key (cur));
  562. if (item) {
  563. /* Copy saved info */
  564. /*
  565. * XXX: don't save or load weight, it should be obtained from the
  566. * metric
  567. */
  568. #if 0
  569. elt = ucl_object_lookup (cur, "weight");
  570. if (elt) {
  571. w = ucl_object_todouble (elt);
  572. if (w != 0) {
  573. item->weight = w;
  574. }
  575. }
  576. #endif
  577. elt = ucl_object_lookup (cur, "time");
  578. if (elt) {
  579. item->st->avg_time = ucl_object_todouble (elt);
  580. }
  581. elt = ucl_object_lookup (cur, "count");
  582. if (elt) {
  583. item->st->total_hits = ucl_object_toint (elt);
  584. item->last_count = item->st->total_hits;
  585. }
  586. elt = ucl_object_lookup (cur, "frequency");
  587. if (elt && ucl_object_type (elt) == UCL_OBJECT) {
  588. const ucl_object_t *cur;
  589. cur = ucl_object_lookup (elt, "avg");
  590. if (cur) {
  591. item->st->avg_frequency = ucl_object_todouble (cur);
  592. }
  593. cur = ucl_object_lookup (elt, "stddev");
  594. if (cur) {
  595. item->st->stddev_frequency = ucl_object_todouble (cur);
  596. }
  597. }
  598. if (item->is_virtual) {
  599. g_assert (item->specific.virtual.parent < (gint)cache->items_by_id->len);
  600. parent = g_ptr_array_index (cache->items_by_id,
  601. item->specific.virtual.parent);
  602. if (parent->st->weight < item->st->weight) {
  603. parent->st->weight = item->st->weight;
  604. }
  605. /*
  606. * We maintain avg_time for virtual symbols equal to the
  607. * parent item avg_time
  608. */
  609. item->st->avg_time = parent->st->avg_time;
  610. }
  611. cache->total_weight += fabs (item->st->weight);
  612. cache->total_hits += item->st->total_hits;
  613. }
  614. }
  615. ucl_object_iterate_free (it);
  616. ucl_object_unref (top);
  617. return TRUE;
  618. }
  619. #define ROUND_DOUBLE(x) (floor((x) * 100.0) / 100.0)
  620. static gboolean
  621. rspamd_symcache_save_items (struct rspamd_symcache *cache, const gchar *name)
  622. {
  623. struct rspamd_symcache_header hdr;
  624. ucl_object_t *top, *elt, *freq;
  625. GHashTableIter it;
  626. struct rspamd_symcache_item *item;
  627. struct ucl_emitter_functions *efunc;
  628. gpointer k, v;
  629. gint fd;
  630. bool ret;
  631. gchar path[PATH_MAX];
  632. rspamd_snprintf (path, sizeof (path), "%s.new", name);
  633. for (;;) {
  634. fd = open (path, O_CREAT | O_WRONLY | O_EXCL, 00644);
  635. if (fd == -1) {
  636. if (errno == EEXIST) {
  637. /* Some other process is already writing data, give up silently */
  638. return TRUE;
  639. }
  640. msg_info_cache ("cannot open file %s, error %d, %s", path,
  641. errno, strerror (errno));
  642. return FALSE;
  643. }
  644. break;
  645. }
  646. rspamd_file_lock (fd, FALSE);
  647. memset (&hdr, 0, sizeof (hdr));
  648. memcpy (hdr.magic, rspamd_symcache_magic,
  649. sizeof (rspamd_symcache_magic));
  650. if (write (fd, &hdr, sizeof (hdr)) == -1) {
  651. msg_info_cache ("cannot write to file %s, error %d, %s", path,
  652. errno, strerror (errno));
  653. rspamd_file_unlock (fd, FALSE);
  654. close (fd);
  655. return FALSE;
  656. }
  657. top = ucl_object_typed_new (UCL_OBJECT);
  658. g_hash_table_iter_init (&it, cache->items_by_symbol);
  659. while (g_hash_table_iter_next (&it, &k, &v)) {
  660. item = v;
  661. elt = ucl_object_typed_new (UCL_OBJECT);
  662. ucl_object_insert_key (elt,
  663. ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)),
  664. "weight", 0, false);
  665. ucl_object_insert_key (elt,
  666. ucl_object_fromdouble (ROUND_DOUBLE (item->st->time_counter.mean)),
  667. "time", 0, false);
  668. ucl_object_insert_key (elt, ucl_object_fromint (item->st->total_hits),
  669. "count", 0, false);
  670. freq = ucl_object_typed_new (UCL_OBJECT);
  671. ucl_object_insert_key (freq,
  672. ucl_object_fromdouble (ROUND_DOUBLE (item->st->frequency_counter.mean)),
  673. "avg", 0, false);
  674. ucl_object_insert_key (freq,
  675. ucl_object_fromdouble (ROUND_DOUBLE (item->st->frequency_counter.stddev)),
  676. "stddev", 0, false);
  677. ucl_object_insert_key (elt, freq, "frequency", 0, false);
  678. ucl_object_insert_key (top, elt, k, 0, false);
  679. }
  680. efunc = ucl_object_emit_fd_funcs (fd);
  681. ret = ucl_object_emit_full (top, UCL_EMIT_JSON_COMPACT, efunc, NULL);
  682. ucl_object_emit_funcs_free (efunc);
  683. ucl_object_unref (top);
  684. rspamd_file_unlock (fd, FALSE);
  685. close (fd);
  686. if (rename (path, name) == -1) {
  687. msg_info_cache ("cannot rename %s -> %s, error %d, %s", path, name,
  688. errno, strerror (errno));
  689. (void)unlink (path);
  690. ret = FALSE;
  691. }
  692. return ret;
  693. }
  694. #undef ROUND_DOUBLE
  695. gint
  696. rspamd_symcache_add_symbol (struct rspamd_symcache *cache,
  697. const gchar *name,
  698. gint priority,
  699. symbol_func_t func,
  700. gpointer user_data,
  701. enum rspamd_symbol_type type,
  702. gint parent)
  703. {
  704. struct rspamd_symcache_item *item = NULL;
  705. g_assert (cache != NULL);
  706. if (name == NULL && !(type & SYMBOL_TYPE_CALLBACK)) {
  707. msg_warn_cache ("no name for non-callback symbol!");
  708. }
  709. else if ((type & SYMBOL_TYPE_VIRTUAL) && parent == -1) {
  710. msg_warn_cache ("no parent symbol is associated with virtual symbol %s",
  711. name);
  712. }
  713. if (name != NULL && !(type & SYMBOL_TYPE_CALLBACK)) {
  714. if (g_hash_table_lookup (cache->items_by_symbol, name) != NULL) {
  715. msg_err_cache ("skip duplicate symbol registration for %s", name);
  716. return -1;
  717. }
  718. }
  719. if (type & (SYMBOL_TYPE_CLASSIFIER|SYMBOL_TYPE_CALLBACK|
  720. SYMBOL_TYPE_PREFILTER|SYMBOL_TYPE_POSTFILTER|
  721. SYMBOL_TYPE_IDEMPOTENT)) {
  722. type |= SYMBOL_TYPE_NOSTAT;
  723. }
  724. item = rspamd_mempool_alloc0 (cache->static_pool,
  725. sizeof (struct rspamd_symcache_item));
  726. item->st = rspamd_mempool_alloc0_shared (cache->static_pool,
  727. sizeof (*item->st));
  728. item->enabled = TRUE;
  729. /*
  730. * We do not share cd to skip locking, instead we'll just calculate it on
  731. * save or accumulate
  732. */
  733. item->cd = rspamd_mempool_alloc0 (cache->static_pool,
  734. sizeof (struct rspamd_counter_data));
  735. item->priority = priority;
  736. item->type = type;
  737. if ((type & SYMBOL_TYPE_FINE) && item->priority == 0) {
  738. /* Make priority for negative weighted symbols */
  739. item->priority = 1;
  740. }
  741. if (func) {
  742. /* Non-virtual symbol */
  743. g_assert (parent == -1);
  744. if (item->type & SYMBOL_TYPE_PREFILTER) {
  745. g_ptr_array_add (cache->prefilters, item);
  746. }
  747. else if (item->type & SYMBOL_TYPE_IDEMPOTENT) {
  748. g_ptr_array_add (cache->idempotent, item);
  749. }
  750. else if (item->type & SYMBOL_TYPE_POSTFILTER) {
  751. g_ptr_array_add (cache->postfilters, item);
  752. }
  753. else {
  754. item->is_filter = TRUE;
  755. g_ptr_array_add (cache->filters, item);
  756. }
  757. item->id = cache->items_by_id->len;
  758. g_ptr_array_add (cache->items_by_id, item);
  759. item->specific.normal.func = func;
  760. item->specific.normal.user_data = user_data;
  761. item->specific.normal.condition_cb = -1;
  762. }
  763. else {
  764. /*
  765. * Three possibilities here when no function is specified:
  766. * - virtual symbol
  767. * - classifier symbol
  768. * - composite symbol
  769. */
  770. if (item->type & SYMBOL_TYPE_COMPOSITE) {
  771. item->specific.normal.condition_cb = -1;
  772. g_ptr_array_add (cache->composites, item);
  773. item->id = cache->items_by_id->len;
  774. g_ptr_array_add (cache->items_by_id, item);
  775. }
  776. else if (item->type & SYMBOL_TYPE_CLASSIFIER) {
  777. /* Treat it as normal symbol to allow enable/disable */
  778. item->id = cache->items_by_id->len;
  779. g_ptr_array_add (cache->items_by_id, item);
  780. item->is_filter = TRUE;
  781. item->specific.normal.func = NULL;
  782. item->specific.normal.user_data = NULL;
  783. item->specific.normal.condition_cb = -1;
  784. }
  785. else {
  786. /* Require parent */
  787. g_assert (parent != -1);
  788. item->is_virtual = TRUE;
  789. item->specific.virtual.parent = parent;
  790. item->id = cache->virtual->len;
  791. g_ptr_array_add (cache->virtual, item);
  792. /* Not added to items_by_id, handled by parent */
  793. }
  794. }
  795. if (item->type & SYMBOL_TYPE_SQUEEZED) {
  796. g_ptr_array_add (cache->squeezed, item);
  797. }
  798. cache->used_items ++;
  799. cache->id ++;
  800. if (!(item->type &
  801. (SYMBOL_TYPE_IDEMPOTENT|SYMBOL_TYPE_NOSTAT|SYMBOL_TYPE_CLASSIFIER))) {
  802. if (name != NULL) {
  803. cache->cksum = t1ha (name, strlen (name),
  804. cache->cksum);
  805. } else {
  806. cache->cksum = t1ha (&item->id, sizeof (item->id),
  807. cache->cksum);
  808. }
  809. cache->stats_symbols_count ++;
  810. }
  811. if (name != NULL) {
  812. item->symbol = rspamd_mempool_strdup (cache->static_pool, name);
  813. msg_debug_cache ("used items: %d, added symbol: %s, %d",
  814. cache->used_items, name, item->id);
  815. } else {
  816. g_assert (func != NULL);
  817. msg_debug_cache ("used items: %d, added unnamed symbol: %d",
  818. cache->used_items, item->id);
  819. }
  820. if (item->is_filter) {
  821. /* Only plain filters can have deps and rdeps */
  822. item->deps = g_ptr_array_new ();
  823. item->rdeps = g_ptr_array_new ();
  824. rspamd_mempool_add_destructor (cache->static_pool,
  825. rspamd_ptr_array_free_hard, item->deps);
  826. rspamd_mempool_add_destructor (cache->static_pool,
  827. rspamd_ptr_array_free_hard, item->rdeps);
  828. }
  829. if (name != NULL) {
  830. g_hash_table_insert (cache->items_by_symbol, item->symbol, item);
  831. }
  832. return item->id;
  833. }
  834. void
  835. rspamd_symcache_set_peak_callback (struct rspamd_symcache *cache,
  836. gint cbref)
  837. {
  838. g_assert (cache != NULL);
  839. if (cache->peak_cb != -1) {
  840. luaL_unref (cache->cfg->lua_state, LUA_REGISTRYINDEX,
  841. cache->peak_cb);
  842. }
  843. cache->peak_cb = cbref;
  844. msg_info_cache ("registered peak callback");
  845. }
  846. gboolean
  847. rspamd_symcache_add_condition_delayed (struct rspamd_symcache *cache,
  848. const gchar *sym, lua_State *L, gint cbref)
  849. {
  850. struct delayed_cache_condition *ncond;
  851. g_assert (cache != NULL);
  852. g_assert (sym != NULL);
  853. ncond = g_malloc0 (sizeof (*ncond));
  854. ncond->sym = g_strdup (sym);
  855. ncond->cbref = cbref;
  856. ncond->L = L;
  857. cache->id ++;
  858. cache->delayed_conditions = g_list_prepend (cache->delayed_conditions, ncond);
  859. return TRUE;
  860. }
  861. void
  862. rspamd_symcache_save (struct rspamd_symcache *cache)
  863. {
  864. if (cache != NULL) {
  865. if (cache->cfg->cache_filename) {
  866. /* Try to sync values to the disk */
  867. if (!rspamd_symcache_save_items (cache,
  868. cache->cfg->cache_filename)) {
  869. msg_err_cache ("cannot save cache data to %s",
  870. cache->cfg->cache_filename);
  871. }
  872. }
  873. }
  874. }
  875. void
  876. rspamd_symcache_destroy (struct rspamd_symcache *cache)
  877. {
  878. GList *cur;
  879. struct delayed_cache_dependency *ddep;
  880. struct delayed_cache_condition *dcond;
  881. if (cache != NULL) {
  882. rspamd_symcache_save (cache);
  883. if (cache->delayed_deps) {
  884. cur = cache->delayed_deps;
  885. while (cur) {
  886. ddep = cur->data;
  887. g_free (ddep->from);
  888. g_free (ddep->to);
  889. g_free (ddep);
  890. cur = g_list_next (cur);
  891. }
  892. g_list_free (cache->delayed_deps);
  893. }
  894. if (cache->delayed_conditions) {
  895. cur = cache->delayed_conditions;
  896. while (cur) {
  897. dcond = cur->data;
  898. g_free (dcond->sym);
  899. g_free (dcond);
  900. cur = g_list_next (cur);
  901. }
  902. g_list_free (cache->delayed_conditions);
  903. }
  904. g_hash_table_destroy (cache->items_by_symbol);
  905. g_ptr_array_free (cache->items_by_id, TRUE);
  906. rspamd_mempool_delete (cache->static_pool);
  907. g_ptr_array_free (cache->filters, TRUE);
  908. g_ptr_array_free (cache->prefilters, TRUE);
  909. g_ptr_array_free (cache->postfilters, TRUE);
  910. g_ptr_array_free (cache->idempotent, TRUE);
  911. g_ptr_array_free (cache->composites, TRUE);
  912. g_ptr_array_free (cache->squeezed, TRUE);
  913. REF_RELEASE (cache->items_by_order);
  914. if (cache->peak_cb != -1) {
  915. luaL_unref (cache->cfg->lua_state, LUA_REGISTRYINDEX, cache->peak_cb);
  916. }
  917. g_free (cache);
  918. }
  919. }
  920. struct rspamd_symcache*
  921. rspamd_symcache_new (struct rspamd_config *cfg)
  922. {
  923. struct rspamd_symcache *cache;
  924. cache = g_malloc0 (sizeof (struct rspamd_symcache));
  925. cache->static_pool =
  926. rspamd_mempool_new (rspamd_mempool_suggest_size (), "symcache");
  927. cache->items_by_symbol = g_hash_table_new (rspamd_str_hash,
  928. rspamd_str_equal);
  929. cache->items_by_id = g_ptr_array_new ();
  930. cache->filters = g_ptr_array_new ();
  931. cache->prefilters = g_ptr_array_new ();
  932. cache->postfilters = g_ptr_array_new ();
  933. cache->idempotent = g_ptr_array_new ();
  934. cache->composites = g_ptr_array_new ();
  935. cache->virtual = g_ptr_array_new ();
  936. cache->squeezed = g_ptr_array_new ();
  937. cache->reload_time = cfg->cache_reload_time;
  938. cache->total_hits = 1;
  939. cache->total_weight = 1.0;
  940. cache->cfg = cfg;
  941. cache->cksum = 0xdeadbabe;
  942. cache->peak_cb = -1;
  943. cache->id = rspamd_random_uint64_fast ();
  944. return cache;
  945. }
  946. gboolean
  947. rspamd_symcache_init (struct rspamd_symcache *cache)
  948. {
  949. gboolean res;
  950. g_assert (cache != NULL);
  951. cache->reload_time = cache->cfg->cache_reload_time;
  952. /* Just in-memory cache */
  953. if (cache->cfg->cache_filename == NULL) {
  954. rspamd_symcache_post_init (cache);
  955. return TRUE;
  956. }
  957. /* Copy saved cache entries */
  958. res = rspamd_symcache_load_items (cache, cache->cfg->cache_filename);
  959. rspamd_symcache_post_init (cache);
  960. return res;
  961. }
  962. static void
  963. rspamd_symcache_validate_cb (gpointer k, gpointer v, gpointer ud)
  964. {
  965. struct rspamd_symcache_item *item = v, *parent;
  966. struct rspamd_config *cfg;
  967. struct rspamd_symcache *cache = (struct rspamd_symcache *)ud;
  968. struct rspamd_symbol *s;
  969. gboolean skipped, ghost;
  970. gint p1, p2;
  971. ghost = item->st->weight == 0 ? TRUE : FALSE;
  972. cfg = cache->cfg;
  973. /* Check whether this item is skipped */
  974. skipped = !ghost;
  975. g_assert (cfg != NULL);
  976. if ((item->type &
  977. (SYMBOL_TYPE_NORMAL|SYMBOL_TYPE_VIRTUAL|SYMBOL_TYPE_COMPOSITE|SYMBOL_TYPE_CLASSIFIER))
  978. && g_hash_table_lookup (cfg->symbols, item->symbol) == NULL) {
  979. if (cfg->unknown_weight != 0) {
  980. skipped = FALSE;
  981. item->st->weight = cfg->unknown_weight;
  982. s = rspamd_mempool_alloc0 (cache->static_pool,
  983. sizeof (*s));
  984. s->name = item->symbol;
  985. s->weight_ptr = &item->st->weight;
  986. g_hash_table_insert (cfg->symbols, item->symbol, s);
  987. msg_info_cache ("adding unknown symbol %s", item->symbol);
  988. ghost = FALSE;
  989. }
  990. else {
  991. skipped = TRUE;
  992. }
  993. }
  994. else {
  995. skipped = FALSE;
  996. }
  997. if (!ghost && skipped) {
  998. item->type |= SYMBOL_TYPE_SKIPPED;
  999. msg_warn_cache ("symbol %s has no score registered, skip its check",
  1000. item->symbol);
  1001. }
  1002. if (ghost) {
  1003. msg_debug_cache ("symbol %s is registered as ghost symbol, it won't be inserted "
  1004. "to any metric", item->symbol);
  1005. }
  1006. if (item->st->weight < 0 && item->priority == 0) {
  1007. item->priority ++;
  1008. }
  1009. if (item->is_virtual) {
  1010. g_assert (item->specific.virtual.parent < (gint)cache->items_by_id->len);
  1011. parent = g_ptr_array_index (cache->items_by_id,
  1012. item->specific.virtual.parent);
  1013. if (fabs (parent->st->weight) < fabs (item->st->weight)) {
  1014. parent->st->weight = item->st->weight;
  1015. }
  1016. p1 = abs (item->priority);
  1017. p2 = abs (parent->priority);
  1018. if (p1 != p2) {
  1019. parent->priority = MAX (p1, p2);
  1020. item->priority = parent->priority;
  1021. }
  1022. }
  1023. cache->total_weight += fabs (item->st->weight);
  1024. }
  1025. static void
  1026. rspamd_symcache_metric_validate_cb (gpointer k, gpointer v, gpointer ud)
  1027. {
  1028. struct rspamd_symcache *cache = (struct rspamd_symcache *)ud;
  1029. const gchar *sym = k;
  1030. struct rspamd_symbol *s = (struct rspamd_symbol *)v;
  1031. gdouble weight;
  1032. struct rspamd_symcache_item *item;
  1033. weight = *s->weight_ptr;
  1034. item = g_hash_table_lookup (cache->items_by_symbol, sym);
  1035. if (item) {
  1036. item->st->weight = weight;
  1037. }
  1038. }
  1039. gboolean
  1040. rspamd_symcache_validate (struct rspamd_symcache *cache,
  1041. struct rspamd_config *cfg,
  1042. gboolean strict)
  1043. {
  1044. struct rspamd_symcache_item *item;
  1045. GHashTableIter it;
  1046. gpointer k, v;
  1047. struct rspamd_symbol *sym_def;
  1048. gboolean ignore_symbol = FALSE, ret = TRUE;
  1049. if (cache == NULL) {
  1050. msg_err ("empty cache is invalid");
  1051. return FALSE;
  1052. }
  1053. /* Now adjust symbol weights according to default metric */
  1054. g_hash_table_foreach (cfg->symbols,
  1055. rspamd_symcache_metric_validate_cb,
  1056. cache);
  1057. g_hash_table_foreach (cache->items_by_symbol,
  1058. rspamd_symcache_validate_cb,
  1059. cache);
  1060. /* Now check each metric item and find corresponding symbol in a cache */
  1061. g_hash_table_iter_init (&it, cfg->symbols);
  1062. while (g_hash_table_iter_next (&it, &k, &v)) {
  1063. ignore_symbol = FALSE;
  1064. sym_def = v;
  1065. if (sym_def && (sym_def->flags & RSPAMD_SYMBOL_FLAG_IGNORE)) {
  1066. ignore_symbol = TRUE;
  1067. }
  1068. if (!ignore_symbol) {
  1069. item = g_hash_table_lookup (cache->items_by_symbol, k);
  1070. if (item == NULL) {
  1071. msg_warn_cache (
  1072. "symbol '%s' has its score defined but there is no "
  1073. "corresponding rule registered",
  1074. k);
  1075. if (strict) {
  1076. ret = FALSE;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. return ret;
  1082. }
  1083. /* Return true if metric has score that is more than spam score for it */
  1084. static gboolean
  1085. rspamd_symcache_metric_limit (struct rspamd_task *task,
  1086. struct cache_savepoint *cp)
  1087. {
  1088. struct rspamd_metric_result *res;
  1089. double ms;
  1090. if (task->flags & RSPAMD_TASK_FLAG_PASS_ALL) {
  1091. return FALSE;
  1092. }
  1093. if (cp->lim == 0.0) {
  1094. res = task->result;
  1095. if (res) {
  1096. ms = rspamd_task_get_required_score (task, res);
  1097. if (!isnan (ms) && cp->lim < ms) {
  1098. cp->rs = res;
  1099. cp->lim = ms;
  1100. }
  1101. }
  1102. }
  1103. if (cp->rs) {
  1104. if (cp->rs->score > cp->lim) {
  1105. return TRUE;
  1106. }
  1107. }
  1108. else {
  1109. /* No reject score define, always check all rules */
  1110. cp->lim = -1;
  1111. }
  1112. return FALSE;
  1113. }
  1114. static gboolean
  1115. rspamd_symcache_check_symbol (struct rspamd_task *task,
  1116. struct rspamd_symcache *cache,
  1117. struct rspamd_symcache_item *item,
  1118. struct cache_savepoint *checkpoint)
  1119. {
  1120. double t1 = 0;
  1121. struct rspamd_task **ptask;
  1122. lua_State *L;
  1123. gboolean check = TRUE;
  1124. struct rspamd_symcache_dynamic_item *dyn_item =
  1125. rspamd_symcache_get_dynamic (checkpoint, item);
  1126. if (item->type & (SYMBOL_TYPE_CLASSIFIER|SYMBOL_TYPE_COMPOSITE)) {
  1127. /* Classifiers are special :( */
  1128. return TRUE;
  1129. }
  1130. if (rspamd_session_blocked (task->s)) {
  1131. /*
  1132. * We cannot add new events as session is either destroyed or
  1133. * being cleaned up.
  1134. */
  1135. return TRUE;
  1136. }
  1137. g_assert (!item->is_virtual);
  1138. g_assert (item->specific.normal.func != NULL);
  1139. if (CHECK_START_BIT (checkpoint, dyn_item)) {
  1140. /*
  1141. * This can actually happen when deps span over different layers
  1142. */
  1143. return CHECK_FINISH_BIT (checkpoint, dyn_item);
  1144. }
  1145. /* Check has been started */
  1146. SET_START_BIT (checkpoint, dyn_item);
  1147. if (!item->enabled ||
  1148. (RSPAMD_TASK_IS_EMPTY (task) && !(item->type & SYMBOL_TYPE_EMPTY))) {
  1149. check = FALSE;
  1150. }
  1151. else if (item->specific.normal.condition_cb != -1) {
  1152. /* We also executes condition callback to check if we need this symbol */
  1153. L = task->cfg->lua_state;
  1154. lua_rawgeti (L, LUA_REGISTRYINDEX, item->specific.normal.condition_cb);
  1155. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  1156. rspamd_lua_setclass (L, "rspamd{task}", -1);
  1157. *ptask = task;
  1158. if (lua_pcall (L, 1, 1, 0) != 0) {
  1159. msg_info_task ("call to condition for %s failed: %s",
  1160. item->symbol, lua_tostring (L, -1));
  1161. lua_pop (L, 1);
  1162. }
  1163. else {
  1164. check = lua_toboolean (L, -1);
  1165. lua_pop (L, 1);
  1166. }
  1167. }
  1168. if (check) {
  1169. msg_debug_cache_task ("execute %s, %d", item->symbol, item->id);
  1170. #ifdef HAVE_EVENT_NO_CACHE_TIME_FUNC
  1171. struct timeval tv;
  1172. event_base_update_cache_time (task->ev_base);
  1173. event_base_gettimeofday_cached (task->ev_base, &tv);
  1174. t1 = tv_to_double (&tv);
  1175. #else
  1176. t1 = rspamd_get_ticks (FALSE);
  1177. #endif
  1178. dyn_item->start_msec = (t1 - task->time_real) * 1e3;
  1179. dyn_item->async_events = 0;
  1180. checkpoint->cur_item = item;
  1181. checkpoint->items_inflight ++;
  1182. /* Callback now must finalize itself */
  1183. item->specific.normal.func (task, item, item->specific.normal.user_data);
  1184. checkpoint->cur_item = NULL;
  1185. if (checkpoint->items_inflight == 0) {
  1186. return TRUE;
  1187. }
  1188. if (dyn_item->async_events == 0 && !CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1189. msg_err_cache ("critical error: item %s has no async events pending, "
  1190. "but it is not finalised", item->symbol);
  1191. g_assert_not_reached ();
  1192. }
  1193. return FALSE;
  1194. }
  1195. else {
  1196. msg_debug_cache_task ("skipping check of %s as its start condition is false",
  1197. item->symbol);
  1198. SET_FINISH_BIT (checkpoint, dyn_item);
  1199. }
  1200. return TRUE;
  1201. }
  1202. static gboolean
  1203. rspamd_symcache_check_deps (struct rspamd_task *task,
  1204. struct rspamd_symcache *cache,
  1205. struct rspamd_symcache_item *item,
  1206. struct cache_savepoint *checkpoint,
  1207. guint recursion,
  1208. gboolean check_only)
  1209. {
  1210. struct cache_dependency *dep;
  1211. guint i;
  1212. gboolean ret = TRUE;
  1213. static const guint max_recursion = 20;
  1214. struct rspamd_symcache_dynamic_item *dyn_item;
  1215. if (recursion > max_recursion) {
  1216. msg_err_task ("cyclic dependencies: maximum check level %ud exceed when "
  1217. "checking dependencies for %s", max_recursion, item->symbol);
  1218. return TRUE;
  1219. }
  1220. if (item->deps != NULL && item->deps->len > 0) {
  1221. for (i = 0; i < item->deps->len; i ++) {
  1222. dep = g_ptr_array_index (item->deps, i);
  1223. if (dep->item == NULL) {
  1224. /* Assume invalid deps as done */
  1225. msg_debug_cache_task ("symbol %d(%s) has invalid dependencies on %d(%s)",
  1226. item->id, item->symbol, dep->id, dep->sym);
  1227. continue;
  1228. }
  1229. dyn_item = rspamd_symcache_get_dynamic (checkpoint, dep->item);
  1230. if (!CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1231. if (!CHECK_START_BIT (checkpoint, dyn_item)) {
  1232. /* Not started */
  1233. if (!check_only) {
  1234. if (!rspamd_symcache_check_deps (task, cache,
  1235. dep->item,
  1236. checkpoint,
  1237. recursion + 1,
  1238. check_only)) {
  1239. ret = FALSE;
  1240. msg_debug_cache_task ("delayed dependency %d(%s) for "
  1241. "symbol %d(%s)",
  1242. dep->id, dep->sym, item->id, item->symbol);
  1243. }
  1244. else if (!rspamd_symcache_check_symbol (task, cache,
  1245. dep->item,
  1246. checkpoint)) {
  1247. /* Now started, but has events pending */
  1248. ret = FALSE;
  1249. msg_debug_cache_task ("started check of %d(%s) symbol "
  1250. "as dep for "
  1251. "%d(%s)",
  1252. dep->id, dep->sym, item->id, item->symbol);
  1253. }
  1254. else {
  1255. msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is "
  1256. "already processed",
  1257. dep->id, dep->sym, item->id, item->symbol);
  1258. }
  1259. }
  1260. else {
  1261. msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) "
  1262. "cannot be started now",
  1263. dep->id, dep->sym,
  1264. item->id, item->symbol);
  1265. ret = FALSE;
  1266. }
  1267. }
  1268. else {
  1269. /* Started but not finished */
  1270. msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is "
  1271. "still executing",
  1272. dep->id, dep->sym,
  1273. item->id, item->symbol);
  1274. ret = FALSE;
  1275. }
  1276. }
  1277. else {
  1278. msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is already "
  1279. "checked",
  1280. dep->id, dep->sym,
  1281. item->id, item->symbol);
  1282. }
  1283. }
  1284. }
  1285. return ret;
  1286. }
  1287. static struct cache_savepoint *
  1288. rspamd_symcache_make_checkpoint (struct rspamd_task *task,
  1289. struct rspamd_symcache *cache)
  1290. {
  1291. struct cache_savepoint *checkpoint;
  1292. if (cache->items_by_order->id != cache->id) {
  1293. /*
  1294. * Cache has been modified, need to resort it
  1295. */
  1296. msg_info_cache ("symbols cache has been modified since last check:"
  1297. " old id: %ud, new id: %ud",
  1298. cache->items_by_order->id, cache->id);
  1299. rspamd_symcache_resort (cache);
  1300. }
  1301. checkpoint = rspamd_mempool_alloc0 (task->task_pool,
  1302. sizeof (*checkpoint) +
  1303. sizeof (struct rspamd_symcache_dynamic_item) * cache->items_by_id->len);
  1304. g_assert (cache->items_by_order != NULL);
  1305. checkpoint->version = cache->items_by_order->d->len;
  1306. checkpoint->order = cache->items_by_order;
  1307. REF_RETAIN (checkpoint->order);
  1308. rspamd_mempool_add_destructor (task->task_pool,
  1309. rspamd_symcache_order_unref, checkpoint->order);
  1310. checkpoint->pass = RSPAMD_CACHE_PASS_INIT;
  1311. task->checkpoint = checkpoint;
  1312. task->result = task->result;
  1313. return checkpoint;
  1314. }
  1315. gboolean
  1316. rspamd_symcache_process_settings (struct rspamd_task *task,
  1317. struct rspamd_symcache *cache)
  1318. {
  1319. const ucl_object_t *wl, *cur, *disabled, *enabled;
  1320. struct rspamd_symbols_group *gr;
  1321. GHashTableIter gr_it;
  1322. ucl_object_iter_t it = NULL;
  1323. gboolean already_disabled = FALSE;
  1324. gpointer k, v;
  1325. wl = ucl_object_lookup (task->settings, "whitelist");
  1326. if (wl != NULL) {
  1327. msg_info_task ("<%s> is whitelisted", task->message_id);
  1328. task->flags |= RSPAMD_TASK_FLAG_SKIP;
  1329. return TRUE;
  1330. }
  1331. enabled = ucl_object_lookup (task->settings, "symbols_enabled");
  1332. if (enabled) {
  1333. /* Disable all symbols but selected */
  1334. rspamd_symcache_disable_all_symbols (task, cache);
  1335. already_disabled = TRUE;
  1336. it = NULL;
  1337. while ((cur = ucl_iterate_object (enabled, &it, true)) != NULL) {
  1338. rspamd_symcache_enable_symbol_checkpoint (task, cache,
  1339. ucl_object_tostring (cur));
  1340. }
  1341. }
  1342. /* Enable groups of symbols */
  1343. enabled = ucl_object_lookup (task->settings, "groups_enabled");
  1344. if (enabled) {
  1345. it = NULL;
  1346. if (!already_disabled) {
  1347. rspamd_symcache_disable_all_symbols (task, cache);
  1348. }
  1349. while ((cur = ucl_iterate_object (enabled, &it, true)) != NULL) {
  1350. if (ucl_object_type (cur) == UCL_STRING) {
  1351. gr = g_hash_table_lookup (task->cfg->groups,
  1352. ucl_object_tostring (cur));
  1353. if (gr) {
  1354. g_hash_table_iter_init (&gr_it, gr->symbols);
  1355. while (g_hash_table_iter_next (&gr_it, &k, &v)) {
  1356. rspamd_symcache_enable_symbol_checkpoint (task, cache, k);
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. disabled = ucl_object_lookup (task->settings, "symbols_disabled");
  1363. if (disabled) {
  1364. it = NULL;
  1365. while ((cur = ucl_iterate_object (disabled, &it, true)) != NULL) {
  1366. rspamd_symcache_disable_symbol_checkpoint (task, cache,
  1367. ucl_object_tostring (cur));
  1368. }
  1369. }
  1370. /* Disable groups of symbols */
  1371. disabled = ucl_object_lookup (task->settings, "groups_disabled");
  1372. if (disabled) {
  1373. it = NULL;
  1374. while ((cur = ucl_iterate_object (disabled, &it, true)) != NULL) {
  1375. if (ucl_object_type (cur) == UCL_STRING) {
  1376. gr = g_hash_table_lookup (task->cfg->groups,
  1377. ucl_object_tostring (cur));
  1378. if (gr) {
  1379. g_hash_table_iter_init (&gr_it, gr->symbols);
  1380. while (g_hash_table_iter_next (&gr_it, &k, &v)) {
  1381. rspamd_symcache_disable_symbol_checkpoint (task, cache, k);
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. return FALSE;
  1388. }
  1389. gboolean
  1390. rspamd_symcache_process_symbols (struct rspamd_task *task,
  1391. struct rspamd_symcache *cache, gint stage)
  1392. {
  1393. struct rspamd_symcache_item *item = NULL;
  1394. struct rspamd_symcache_dynamic_item *dyn_item;
  1395. struct cache_savepoint *checkpoint;
  1396. gint i;
  1397. gboolean all_done;
  1398. gint saved_priority;
  1399. guint start_events_pending;
  1400. g_assert (cache != NULL);
  1401. if (task->checkpoint == NULL) {
  1402. checkpoint = rspamd_symcache_make_checkpoint (task, cache);
  1403. task->checkpoint = checkpoint;
  1404. }
  1405. else {
  1406. checkpoint = task->checkpoint;
  1407. }
  1408. if (stage == RSPAMD_TASK_STAGE_POST_FILTERS && checkpoint->pass <
  1409. RSPAMD_CACHE_PASS_POSTFILTERS) {
  1410. checkpoint->pass = RSPAMD_CACHE_PASS_POSTFILTERS;
  1411. }
  1412. if (stage == RSPAMD_TASK_STAGE_IDEMPOTENT && checkpoint->pass <
  1413. RSPAMD_CACHE_PASS_IDEMPOTENT) {
  1414. checkpoint->pass = RSPAMD_CACHE_PASS_IDEMPOTENT;
  1415. }
  1416. msg_debug_cache_task ("symbols processing stage at pass: %d", checkpoint->pass);
  1417. start_events_pending = rspamd_session_events_pending (task->s);
  1418. switch (checkpoint->pass) {
  1419. case RSPAMD_CACHE_PASS_INIT:
  1420. case RSPAMD_CACHE_PASS_PREFILTERS:
  1421. /* Check for prefilters */
  1422. saved_priority = G_MININT;
  1423. all_done = TRUE;
  1424. for (i = 0; i < (gint)cache->prefilters->len; i ++) {
  1425. item = g_ptr_array_index (cache->prefilters, i);
  1426. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1427. if (RSPAMD_TASK_IS_SKIPPED (task)) {
  1428. return TRUE;
  1429. }
  1430. if (!CHECK_START_BIT (checkpoint, dyn_item) &&
  1431. !CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1432. /* Check priorities */
  1433. if (saved_priority == G_MININT) {
  1434. saved_priority = item->priority;
  1435. }
  1436. else {
  1437. if (item->priority < saved_priority &&
  1438. rspamd_session_events_pending (task->s) > start_events_pending) {
  1439. /*
  1440. * Delay further checks as we have higher
  1441. * priority filters to be processed
  1442. */
  1443. checkpoint->pass = RSPAMD_CACHE_PASS_PREFILTERS;
  1444. return TRUE;
  1445. }
  1446. }
  1447. rspamd_symcache_check_symbol (task, cache, item,
  1448. checkpoint);
  1449. all_done = FALSE;
  1450. }
  1451. }
  1452. if (all_done || stage == RSPAMD_TASK_STAGE_FILTERS) {
  1453. checkpoint->pass = RSPAMD_CACHE_PASS_FILTERS;
  1454. }
  1455. if (stage == RSPAMD_TASK_STAGE_FILTERS) {
  1456. return rspamd_symcache_process_symbols (task, cache, stage);
  1457. }
  1458. break;
  1459. case RSPAMD_CACHE_PASS_FILTERS:
  1460. /*
  1461. * On the first pass we check symbols that do not have dependencies
  1462. * If we figure out symbol that has no dependencies satisfied, then
  1463. * we just save it for another pass
  1464. */
  1465. all_done = TRUE;
  1466. for (i = 0; i < (gint)checkpoint->version; i ++) {
  1467. if (RSPAMD_TASK_IS_SKIPPED (task)) {
  1468. return TRUE;
  1469. }
  1470. item = g_ptr_array_index (checkpoint->order->d, i);
  1471. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1472. if (item->type & SYMBOL_TYPE_CLASSIFIER) {
  1473. continue;
  1474. }
  1475. if (!CHECK_START_BIT (checkpoint, dyn_item)) {
  1476. all_done = FALSE;
  1477. if (!rspamd_symcache_check_deps (task, cache, item,
  1478. checkpoint, 0, FALSE)) {
  1479. msg_debug_cache_task ("blocked execution of %d(%s) unless deps are "
  1480. "resolved",
  1481. item->id, item->symbol);
  1482. continue;
  1483. }
  1484. rspamd_symcache_check_symbol (task, cache, item,
  1485. checkpoint);
  1486. }
  1487. if (!(item->type & SYMBOL_TYPE_FINE)) {
  1488. if (rspamd_symcache_metric_limit (task, checkpoint)) {
  1489. msg_info_task ("<%s> has already scored more than %.2f, so do "
  1490. "not "
  1491. "plan more checks", task->message_id,
  1492. checkpoint->rs->score);
  1493. all_done = TRUE;
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. if (all_done || stage == RSPAMD_TASK_STAGE_POST_FILTERS) {
  1499. checkpoint->pass = RSPAMD_CACHE_PASS_POSTFILTERS;
  1500. }
  1501. if (stage == RSPAMD_TASK_STAGE_POST_FILTERS) {
  1502. return rspamd_symcache_process_symbols (task, cache, stage);
  1503. }
  1504. break;
  1505. case RSPAMD_CACHE_PASS_POSTFILTERS:
  1506. /* Check for postfilters */
  1507. saved_priority = G_MININT;
  1508. all_done = TRUE;
  1509. for (i = 0; i < (gint)cache->postfilters->len; i ++) {
  1510. if (RSPAMD_TASK_IS_SKIPPED (task)) {
  1511. return TRUE;
  1512. }
  1513. item = g_ptr_array_index (cache->postfilters, i);
  1514. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1515. if (!CHECK_START_BIT (checkpoint, dyn_item) &&
  1516. !CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1517. /* Check priorities */
  1518. all_done = FALSE;
  1519. if (saved_priority == G_MININT) {
  1520. saved_priority = item->priority;
  1521. }
  1522. else {
  1523. if (item->priority > saved_priority &&
  1524. rspamd_session_events_pending (task->s) > start_events_pending) {
  1525. /*
  1526. * Delay further checks as we have higher
  1527. * priority filters to be processed
  1528. */
  1529. checkpoint->pass = RSPAMD_CACHE_PASS_POSTFILTERS;
  1530. return TRUE;
  1531. }
  1532. }
  1533. rspamd_symcache_check_symbol (task, cache, item,
  1534. checkpoint);
  1535. }
  1536. }
  1537. if (all_done) {
  1538. checkpoint->pass = RSPAMD_CACHE_PASS_IDEMPOTENT;
  1539. }
  1540. if (checkpoint->items_inflight == 0 ||
  1541. stage == RSPAMD_TASK_STAGE_IDEMPOTENT) {
  1542. checkpoint->pass = RSPAMD_CACHE_PASS_IDEMPOTENT;
  1543. }
  1544. if (stage == RSPAMD_TASK_STAGE_IDEMPOTENT) {
  1545. return rspamd_symcache_process_symbols (task, cache, stage);
  1546. }
  1547. break;
  1548. case RSPAMD_CACHE_PASS_IDEMPOTENT:
  1549. /* Check for postfilters */
  1550. saved_priority = G_MININT;
  1551. for (i = 0; i < (gint)cache->idempotent->len; i ++) {
  1552. item = g_ptr_array_index (cache->idempotent, i);
  1553. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1554. if (!CHECK_START_BIT (checkpoint, dyn_item) &&
  1555. !CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1556. /* Check priorities */
  1557. if (saved_priority == G_MININT) {
  1558. saved_priority = item->priority;
  1559. }
  1560. else {
  1561. if (item->priority > saved_priority &&
  1562. rspamd_session_events_pending (task->s) > start_events_pending) {
  1563. /*
  1564. * Delay further checks as we have higher
  1565. * priority filters to be processed
  1566. */
  1567. checkpoint->pass = RSPAMD_CACHE_PASS_IDEMPOTENT;
  1568. return TRUE;
  1569. }
  1570. }
  1571. rspamd_symcache_check_symbol (task, cache, item,
  1572. checkpoint);
  1573. }
  1574. }
  1575. checkpoint->pass = RSPAMD_CACHE_PASS_WAIT_IDEMPOTENT;
  1576. break;
  1577. case RSPAMD_CACHE_PASS_WAIT_IDEMPOTENT:
  1578. all_done = TRUE;
  1579. for (i = 0; i < (gint)cache->idempotent->len; i ++) {
  1580. item = g_ptr_array_index (cache->idempotent, i);
  1581. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1582. if (!CHECK_FINISH_BIT (checkpoint, dyn_item)) {
  1583. all_done = FALSE;
  1584. break;
  1585. }
  1586. }
  1587. if (all_done) {
  1588. checkpoint->pass = RSPAMD_CACHE_PASS_DONE;
  1589. return TRUE;
  1590. }
  1591. break;
  1592. case RSPAMD_CACHE_PASS_DONE:
  1593. return TRUE;
  1594. break;
  1595. }
  1596. return FALSE;
  1597. }
  1598. struct counters_cbdata {
  1599. ucl_object_t *top;
  1600. struct rspamd_symcache *cache;
  1601. };
  1602. #define ROUND_DOUBLE(x) (floor((x) * 100.0) / 100.0)
  1603. static void
  1604. rspamd_symcache_counters_cb (gpointer k, gpointer v, gpointer ud)
  1605. {
  1606. struct counters_cbdata *cbd = ud;
  1607. ucl_object_t *obj, *top;
  1608. struct rspamd_symcache_item *item = v, *parent;
  1609. const gchar *symbol = k;
  1610. top = cbd->top;
  1611. obj = ucl_object_typed_new (UCL_OBJECT);
  1612. ucl_object_insert_key (obj, ucl_object_fromstring (symbol ? symbol : "unknown"),
  1613. "symbol", 0, false);
  1614. if (item->is_virtual) {
  1615. parent = g_ptr_array_index (cbd->cache->items_by_id,
  1616. item->specific.virtual.parent);
  1617. ucl_object_insert_key (obj,
  1618. ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)),
  1619. "weight", 0, false);
  1620. ucl_object_insert_key (obj,
  1621. ucl_object_fromdouble (ROUND_DOUBLE (parent->st->avg_frequency)),
  1622. "frequency", 0, false);
  1623. ucl_object_insert_key (obj,
  1624. ucl_object_fromint (parent->st->total_hits),
  1625. "hits", 0, false);
  1626. ucl_object_insert_key (obj,
  1627. ucl_object_fromdouble (ROUND_DOUBLE (parent->st->avg_time)),
  1628. "time", 0, false);
  1629. }
  1630. else {
  1631. ucl_object_insert_key (obj,
  1632. ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)),
  1633. "weight", 0, false);
  1634. ucl_object_insert_key (obj,
  1635. ucl_object_fromdouble (ROUND_DOUBLE (item->st->avg_frequency)),
  1636. "frequency", 0, false);
  1637. ucl_object_insert_key (obj,
  1638. ucl_object_fromint (item->st->total_hits),
  1639. "hits", 0, false);
  1640. ucl_object_insert_key (obj,
  1641. ucl_object_fromdouble (ROUND_DOUBLE (item->st->avg_time)),
  1642. "time", 0, false);
  1643. }
  1644. ucl_array_append (top, obj);
  1645. }
  1646. #undef ROUND_DOUBLE
  1647. ucl_object_t *
  1648. rspamd_symcache_counters (struct rspamd_symcache *cache)
  1649. {
  1650. ucl_object_t *top;
  1651. struct counters_cbdata cbd;
  1652. g_assert (cache != NULL);
  1653. top = ucl_object_typed_new (UCL_ARRAY);
  1654. cbd.top = top;
  1655. cbd.cache = cache;
  1656. g_hash_table_foreach (cache->items_by_symbol,
  1657. rspamd_symcache_counters_cb, &cbd);
  1658. return top;
  1659. }
  1660. static void
  1661. rspamd_symcache_call_peak_cb (struct event_base *ev_base,
  1662. struct rspamd_symcache *cache,
  1663. struct rspamd_symcache_item *item,
  1664. gdouble cur_value,
  1665. gdouble cur_err)
  1666. {
  1667. lua_State *L = cache->cfg->lua_state;
  1668. struct event_base **pbase;
  1669. lua_rawgeti (L, LUA_REGISTRYINDEX, cache->peak_cb);
  1670. pbase = lua_newuserdata (L, sizeof (*pbase));
  1671. *pbase = ev_base;
  1672. rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
  1673. lua_pushstring (L, item->symbol);
  1674. lua_pushnumber (L, item->st->avg_frequency);
  1675. lua_pushnumber (L, sqrt (item->st->stddev_frequency));
  1676. lua_pushnumber (L, cur_value);
  1677. lua_pushnumber (L, cur_err);
  1678. if (lua_pcall (L, 6, 0, 0) != 0) {
  1679. msg_info_cache ("call to peak function for %s failed: %s",
  1680. item->symbol, lua_tostring (L, -1));
  1681. lua_pop (L, 1);
  1682. }
  1683. }
  1684. static void
  1685. rspamd_symcache_resort_cb (gint fd, short what, gpointer ud)
  1686. {
  1687. struct timeval tv;
  1688. gdouble tm;
  1689. struct rspamd_cache_refresh_cbdata *cbdata = ud;
  1690. struct rspamd_symcache *cache;
  1691. struct rspamd_symcache_item *item;
  1692. guint i;
  1693. gdouble cur_ticks;
  1694. static const double decay_rate = 0.7;
  1695. cache = cbdata->cache;
  1696. /* Plan new event */
  1697. tm = rspamd_time_jitter (cache->reload_time, 0);
  1698. cur_ticks = rspamd_get_ticks (FALSE);
  1699. msg_debug_cache ("resort symbols cache, next reload in %.2f seconds", tm);
  1700. g_assert (cache != NULL);
  1701. evtimer_set (&cbdata->resort_ev, rspamd_symcache_resort_cb, cbdata);
  1702. event_base_set (cbdata->ev_base, &cbdata->resort_ev);
  1703. double_to_tv (tm, &tv);
  1704. event_add (&cbdata->resort_ev, &tv);
  1705. if (rspamd_worker_is_primary_controller (cbdata->w)) {
  1706. /* Gather stats from shared execution times */
  1707. for (i = 0; i < cache->filters->len; i ++) {
  1708. item = g_ptr_array_index (cache->filters, i);
  1709. item->st->total_hits += item->st->hits;
  1710. g_atomic_int_set (&item->st->hits, 0);
  1711. if (item->last_count > 0 && cbdata->w->index == 0) {
  1712. /* Calculate frequency */
  1713. gdouble cur_err, cur_value;
  1714. cur_value = (item->st->total_hits - item->last_count) /
  1715. (cur_ticks - cbdata->last_resort);
  1716. rspamd_set_counter_ema (&item->st->frequency_counter,
  1717. cur_value, decay_rate);
  1718. item->st->avg_frequency = item->st->frequency_counter.mean;
  1719. item->st->stddev_frequency = item->st->frequency_counter.stddev;
  1720. if (cur_value > 0) {
  1721. msg_debug_cache ("frequency for %s is %.2f, avg: %.2f",
  1722. item->symbol, cur_value, item->st->avg_frequency);
  1723. }
  1724. cur_err = (item->st->avg_frequency - cur_value);
  1725. cur_err *= cur_err;
  1726. /*
  1727. * TODO: replace magic number
  1728. */
  1729. if (item->st->frequency_counter.number > 10 &&
  1730. cur_err > sqrt (item->st->stddev_frequency) * 3) {
  1731. item->frequency_peaks ++;
  1732. msg_debug_cache ("peak found for %s is %.2f, avg: %.2f, "
  1733. "stddev: %.2f, error: %.2f, peaks: %d",
  1734. item->symbol, cur_value,
  1735. item->st->avg_frequency,
  1736. item->st->stddev_frequency,
  1737. cur_err,
  1738. item->frequency_peaks);
  1739. if (cache->peak_cb != -1) {
  1740. rspamd_symcache_call_peak_cb (cbdata->ev_base,
  1741. cache, item,
  1742. cur_value, cur_err);
  1743. }
  1744. }
  1745. }
  1746. item->last_count = item->st->total_hits;
  1747. if (item->cd->number > 0) {
  1748. if (item->type & (SYMBOL_TYPE_CALLBACK|SYMBOL_TYPE_NORMAL)) {
  1749. item->st->avg_time = item->cd->mean;
  1750. rspamd_set_counter_ema (&item->st->time_counter,
  1751. item->st->avg_time, decay_rate);
  1752. item->st->avg_time = item->st->time_counter.mean;
  1753. memset (item->cd, 0, sizeof (*item->cd));
  1754. }
  1755. }
  1756. }
  1757. cbdata->last_resort = cur_ticks;
  1758. /* We don't do actual sorting due to topological guarantees */
  1759. }
  1760. }
  1761. void
  1762. rspamd_symcache_start_refresh (struct rspamd_symcache *cache,
  1763. struct event_base *ev_base, struct rspamd_worker *w)
  1764. {
  1765. struct timeval tv;
  1766. gdouble tm;
  1767. struct rspamd_cache_refresh_cbdata *cbdata;
  1768. cbdata = rspamd_mempool_alloc0 (cache->static_pool, sizeof (*cbdata));
  1769. cbdata->last_resort = rspamd_get_ticks (TRUE);
  1770. cbdata->ev_base = ev_base;
  1771. cbdata->w = w;
  1772. cbdata->cache = cache;
  1773. tm = rspamd_time_jitter (cache->reload_time, 0);
  1774. msg_debug_cache ("next reload in %.2f seconds", tm);
  1775. g_assert (cache != NULL);
  1776. evtimer_set (&cbdata->resort_ev, rspamd_symcache_resort_cb,
  1777. cbdata);
  1778. event_base_set (ev_base, &cbdata->resort_ev);
  1779. double_to_tv (tm, &tv);
  1780. event_add (&cbdata->resort_ev, &tv);
  1781. rspamd_mempool_add_destructor (cache->static_pool,
  1782. (rspamd_mempool_destruct_t) event_del,
  1783. &cbdata->resort_ev);
  1784. }
  1785. void
  1786. rspamd_symcache_inc_frequency (struct rspamd_symcache *cache,
  1787. const gchar *symbol)
  1788. {
  1789. struct rspamd_symcache_item *item;
  1790. g_assert (cache != NULL);
  1791. item = g_hash_table_lookup (cache->items_by_symbol, symbol);
  1792. if (item != NULL) {
  1793. g_atomic_int_inc (&item->st->hits);
  1794. }
  1795. }
  1796. void
  1797. rspamd_symcache_add_dependency (struct rspamd_symcache *cache,
  1798. gint id_from, const gchar *to)
  1799. {
  1800. struct rspamd_symcache_item *source;
  1801. struct cache_dependency *dep;
  1802. g_assert (id_from >= 0 && id_from < (gint)cache->items_by_id->len);
  1803. source = g_ptr_array_index (cache->items_by_id, id_from);
  1804. dep = rspamd_mempool_alloc (cache->static_pool, sizeof (*dep));
  1805. dep->id = id_from;
  1806. dep->sym = rspamd_mempool_strdup (cache->static_pool, to);
  1807. /* Will be filled later */
  1808. dep->item = NULL;
  1809. g_ptr_array_add (source->deps, dep);
  1810. }
  1811. void
  1812. rspamd_symcache_add_delayed_dependency (struct rspamd_symcache *cache,
  1813. const gchar *from, const gchar *to)
  1814. {
  1815. struct delayed_cache_dependency *ddep;
  1816. g_assert (from != NULL);
  1817. g_assert (to != NULL);
  1818. ddep = g_malloc0 (sizeof (*ddep));
  1819. ddep->from = g_strdup (from);
  1820. ddep->to = g_strdup (to);
  1821. cache->delayed_deps = g_list_prepend (cache->delayed_deps, ddep);
  1822. }
  1823. gint
  1824. rspamd_symcache_find_symbol (struct rspamd_symcache *cache, const gchar *name)
  1825. {
  1826. struct rspamd_symcache_item *item;
  1827. g_assert (cache != NULL);
  1828. if (name == NULL) {
  1829. return -1;
  1830. }
  1831. item = g_hash_table_lookup (cache->items_by_symbol, name);
  1832. if (item != NULL) {
  1833. return item->id;
  1834. }
  1835. return -1;
  1836. }
  1837. gboolean
  1838. rspamd_symcache_stat_symbol (struct rspamd_symcache *cache,
  1839. const gchar *name,
  1840. gdouble *frequency,
  1841. gdouble *freq_stddev,
  1842. gdouble *tm,
  1843. guint *nhits)
  1844. {
  1845. struct rspamd_symcache_item *item;
  1846. g_assert (cache != NULL);
  1847. if (name == NULL) {
  1848. return FALSE;
  1849. }
  1850. item = g_hash_table_lookup (cache->items_by_symbol, name);
  1851. if (item != NULL) {
  1852. *frequency = item->st->avg_frequency;
  1853. *freq_stddev = sqrt (item->st->stddev_frequency);
  1854. *tm = item->st->time_counter.mean;
  1855. if (nhits) {
  1856. *nhits = item->st->hits;
  1857. }
  1858. return TRUE;
  1859. }
  1860. return FALSE;
  1861. }
  1862. const gchar *
  1863. rspamd_symcache_symbol_by_id (struct rspamd_symcache *cache,
  1864. gint id)
  1865. {
  1866. struct rspamd_symcache_item *item;
  1867. g_assert (cache != NULL);
  1868. if (id < 0 || id >= (gint)cache->items_by_id->len) {
  1869. return NULL;
  1870. }
  1871. item = g_ptr_array_index (cache->items_by_id, id);
  1872. return item->symbol;
  1873. }
  1874. guint
  1875. rspamd_symcache_stats_symbols_count (struct rspamd_symcache *cache)
  1876. {
  1877. g_assert (cache != NULL);
  1878. return cache->stats_symbols_count;
  1879. }
  1880. static void
  1881. rspamd_symcache_disable_all_symbols (struct rspamd_task *task,
  1882. struct rspamd_symcache *cache)
  1883. {
  1884. struct cache_savepoint *checkpoint;
  1885. guint i;
  1886. struct rspamd_symcache_item *item;
  1887. struct rspamd_symcache_dynamic_item *dyn_item;
  1888. if (task->checkpoint == NULL) {
  1889. checkpoint = rspamd_symcache_make_checkpoint (task, cache);
  1890. task->checkpoint = checkpoint;
  1891. }
  1892. else {
  1893. checkpoint = task->checkpoint;
  1894. }
  1895. /* Enable for squeezed symbols */
  1896. PTR_ARRAY_FOREACH (cache->items_by_id, i, item) {
  1897. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1898. if (!(item->type & SYMBOL_TYPE_SQUEEZED)) {
  1899. SET_FINISH_BIT (checkpoint, dyn_item);
  1900. SET_START_BIT (checkpoint, dyn_item);
  1901. }
  1902. }
  1903. }
  1904. static void
  1905. rspamd_symcache_disable_symbol_checkpoint (struct rspamd_task *task,
  1906. struct rspamd_symcache *cache, const gchar *symbol)
  1907. {
  1908. struct cache_savepoint *checkpoint;
  1909. struct rspamd_symcache_item *item;
  1910. struct rspamd_symcache_dynamic_item *dyn_item;
  1911. if (task->checkpoint == NULL) {
  1912. checkpoint = rspamd_symcache_make_checkpoint (task, cache);
  1913. task->checkpoint = checkpoint;
  1914. }
  1915. else {
  1916. checkpoint = task->checkpoint;
  1917. }
  1918. item = rspamd_symcache_find_filter (cache, symbol);
  1919. if (item) {
  1920. if (!(item->type & SYMBOL_TYPE_SQUEEZED)) {
  1921. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1922. SET_FINISH_BIT (checkpoint, dyn_item);
  1923. SET_START_BIT (checkpoint, dyn_item);
  1924. msg_debug_cache_task ("disable execution of %s", symbol);
  1925. }
  1926. else {
  1927. msg_debug_cache_task ("skip disabling squeezed symbol %s", symbol);
  1928. }
  1929. }
  1930. else {
  1931. msg_info_task ("cannot disable %s: not found", symbol);
  1932. }
  1933. }
  1934. static void
  1935. rspamd_symcache_enable_symbol_checkpoint (struct rspamd_task *task,
  1936. struct rspamd_symcache *cache, const gchar *symbol)
  1937. {
  1938. struct cache_savepoint *checkpoint;
  1939. struct rspamd_symcache_item *item;
  1940. struct rspamd_symcache_dynamic_item *dyn_item;
  1941. if (task->checkpoint == NULL) {
  1942. checkpoint = rspamd_symcache_make_checkpoint (task, cache);
  1943. task->checkpoint = checkpoint;
  1944. }
  1945. else {
  1946. checkpoint = task->checkpoint;
  1947. }
  1948. item = rspamd_symcache_find_filter (cache, symbol);
  1949. if (item) {
  1950. if (!(item->type & SYMBOL_TYPE_SQUEEZED)) {
  1951. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1952. dyn_item->finished = 0;
  1953. dyn_item->started = 0;
  1954. msg_debug_cache_task ("enable execution of %s", symbol);
  1955. }
  1956. else {
  1957. msg_debug_cache_task ("skip enabling squeezed symbol %s", symbol);
  1958. }
  1959. }
  1960. else {
  1961. msg_info_task ("cannot enable %s: not found", symbol);
  1962. }
  1963. }
  1964. struct rspamd_abstract_callback_data*
  1965. rspamd_symcache_get_cbdata (struct rspamd_symcache *cache,
  1966. const gchar *symbol)
  1967. {
  1968. struct rspamd_symcache_item *item;
  1969. g_assert (cache != NULL);
  1970. g_assert (symbol != NULL);
  1971. item = rspamd_symcache_find_filter (cache, symbol);
  1972. if (item) {
  1973. return item->specific.normal.user_data;
  1974. }
  1975. return NULL;
  1976. }
  1977. gboolean
  1978. rspamd_symcache_is_checked (struct rspamd_task *task,
  1979. struct rspamd_symcache *cache, const gchar *symbol)
  1980. {
  1981. struct cache_savepoint *checkpoint;
  1982. struct rspamd_symcache_item *item;
  1983. struct rspamd_symcache_dynamic_item *dyn_item;
  1984. g_assert (cache != NULL);
  1985. g_assert (symbol != NULL);
  1986. if (task->checkpoint == NULL) {
  1987. checkpoint = rspamd_symcache_make_checkpoint (task, cache);
  1988. task->checkpoint = checkpoint;
  1989. }
  1990. else {
  1991. checkpoint = task->checkpoint;
  1992. }
  1993. item = rspamd_symcache_find_filter (cache, symbol);
  1994. if (item) {
  1995. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  1996. return dyn_item->started;
  1997. }
  1998. return FALSE;
  1999. }
  2000. void
  2001. rspamd_symcache_disable_symbol (struct rspamd_symcache *cache,
  2002. const gchar *symbol)
  2003. {
  2004. struct rspamd_symcache_item *item;
  2005. g_assert (cache != NULL);
  2006. g_assert (symbol != NULL);
  2007. item = g_hash_table_lookup (cache->items_by_symbol, symbol);
  2008. if (item) {
  2009. item->enabled = FALSE;
  2010. }
  2011. }
  2012. void
  2013. rspamd_symcache_enable_symbol (struct rspamd_symcache *cache,
  2014. const gchar *symbol)
  2015. {
  2016. struct rspamd_symcache_item *item;
  2017. g_assert (cache != NULL);
  2018. g_assert (symbol != NULL);
  2019. item = g_hash_table_lookup (cache->items_by_symbol, symbol);
  2020. if (item) {
  2021. item->enabled = TRUE;
  2022. }
  2023. }
  2024. guint64
  2025. rspamd_symcache_get_cksum (struct rspamd_symcache *cache)
  2026. {
  2027. g_assert (cache != NULL);
  2028. return cache->cksum;
  2029. }
  2030. gboolean
  2031. rspamd_symcache_is_symbol_enabled (struct rspamd_task *task,
  2032. struct rspamd_symcache *cache,
  2033. const gchar *symbol)
  2034. {
  2035. struct cache_savepoint *checkpoint;
  2036. struct rspamd_symcache_item *item;
  2037. struct rspamd_symcache_dynamic_item *dyn_item;
  2038. lua_State *L;
  2039. struct rspamd_task **ptask;
  2040. gboolean ret = TRUE;
  2041. g_assert (cache != NULL);
  2042. g_assert (symbol != NULL);
  2043. checkpoint = task->checkpoint;
  2044. if (checkpoint) {
  2045. item = rspamd_symcache_find_filter (cache, symbol);
  2046. if (item) {
  2047. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  2048. if (CHECK_START_BIT (checkpoint, dyn_item)) {
  2049. ret = FALSE;
  2050. }
  2051. else {
  2052. if (item->specific.normal.condition_cb != -1) {
  2053. /* We also executes condition callback to check if we need this symbol */
  2054. L = task->cfg->lua_state;
  2055. lua_rawgeti (L, LUA_REGISTRYINDEX,
  2056. item->specific.normal.condition_cb);
  2057. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  2058. rspamd_lua_setclass (L, "rspamd{task}", -1);
  2059. *ptask = task;
  2060. if (lua_pcall (L, 1, 1, 0) != 0) {
  2061. msg_info_task ("call to condition for %s failed: %s",
  2062. item->symbol, lua_tostring (L, -1));
  2063. lua_pop (L, 1);
  2064. }
  2065. else {
  2066. ret = lua_toboolean (L, -1);
  2067. lua_pop (L, 1);
  2068. }
  2069. }
  2070. }
  2071. }
  2072. }
  2073. return ret;
  2074. }
  2075. void
  2076. rspamd_symcache_foreach (struct rspamd_symcache *cache,
  2077. void (*func) (gint, const gchar *, gint, gpointer),
  2078. gpointer ud)
  2079. {
  2080. struct rspamd_symcache_item *item;
  2081. GHashTableIter it;
  2082. gpointer k, v;
  2083. g_hash_table_iter_init (&it, cache->items_by_symbol);
  2084. while (g_hash_table_iter_next (&it, &k, &v)) {
  2085. item = (struct rspamd_symcache_item *)v;
  2086. func (item->id, item->symbol, item->type, ud);
  2087. }
  2088. }
  2089. struct rspamd_symcache_item *
  2090. rspamd_symcache_get_cur_item (struct rspamd_task *task)
  2091. {
  2092. struct cache_savepoint *checkpoint = task->checkpoint;
  2093. if (checkpoint == NULL) {
  2094. return NULL;
  2095. }
  2096. return checkpoint->cur_item;
  2097. }
  2098. /**
  2099. * Replaces the current item being processed.
  2100. * Returns the current item being processed (if any)
  2101. * @param task
  2102. * @param item
  2103. * @return
  2104. */
  2105. struct rspamd_symcache_item *
  2106. rspamd_symcache_set_cur_item (struct rspamd_task *task,
  2107. struct rspamd_symcache_item *item)
  2108. {
  2109. struct cache_savepoint *checkpoint = task->checkpoint;
  2110. struct rspamd_symcache_item *ex;
  2111. ex = checkpoint->cur_item;
  2112. checkpoint->cur_item = item;
  2113. return ex;
  2114. }
  2115. /**
  2116. * Finalize the current async element potentially calling its deps
  2117. */
  2118. void
  2119. rspamd_symcache_finalize_item (struct rspamd_task *task,
  2120. struct rspamd_symcache_item *item)
  2121. {
  2122. struct cache_savepoint *checkpoint = task->checkpoint;
  2123. struct cache_dependency *rdep;
  2124. struct rspamd_symcache_dynamic_item *dyn_item;
  2125. gdouble t2, diff;
  2126. guint i;
  2127. struct timeval tv;
  2128. const gdouble slow_diff_limit = 300;
  2129. /* Sanity checks */
  2130. g_assert (checkpoint->items_inflight > 0);
  2131. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  2132. if (dyn_item->async_events > 0) {
  2133. /*
  2134. * XXX: Race condition
  2135. *
  2136. * It is possible that some async event is still in flight, but we
  2137. * already know its result, however, it is the responsibility of that
  2138. * event to decrease async events count and call this function
  2139. * one more time
  2140. */
  2141. msg_debug_cache_task ("postpone finalisation of %s(%d) as there are %d "
  2142. "async events pendning",
  2143. item->symbol, item->id, dyn_item->async_events);
  2144. return;
  2145. }
  2146. msg_debug_cache_task ("process finalize for item %s(%d)", item->symbol, item->id);
  2147. SET_FINISH_BIT (checkpoint, dyn_item);
  2148. checkpoint->items_inflight --;
  2149. checkpoint->cur_item = NULL;
  2150. #ifdef HAVE_EVENT_NO_CACHE_TIME_FUNC
  2151. event_base_update_cache_time (task->ev_base);
  2152. event_base_gettimeofday_cached (task->ev_base, &tv);
  2153. t2 = tv_to_double (&tv);
  2154. #else
  2155. t2 = rspamd_get_ticks (FALSE);
  2156. #endif
  2157. diff = ((t2 - task->time_real) * 1e3 - dyn_item->start_msec);
  2158. if (G_UNLIKELY (RSPAMD_TASK_IS_PROFILING (task))) {
  2159. rspamd_task_profile_set (task, item->symbol, diff);
  2160. }
  2161. if (!(item->type & SYMBOL_TYPE_SQUEEZED)) {
  2162. if (diff > slow_diff_limit) {
  2163. msg_info_task ("slow rule: %s(%d): %.2f ms", item->symbol, item->id,
  2164. diff);
  2165. }
  2166. if (rspamd_worker_is_scanner (task->worker)) {
  2167. rspamd_set_counter (item->cd, diff);
  2168. }
  2169. }
  2170. /* Process all reverse dependencies */
  2171. PTR_ARRAY_FOREACH (item->rdeps, i, rdep) {
  2172. if (rdep->item) {
  2173. dyn_item = rspamd_symcache_get_dynamic (checkpoint, rdep->item);
  2174. if (!CHECK_START_BIT (checkpoint, dyn_item)) {
  2175. msg_debug_cache_task ("check item %d(%s) rdep of %s ",
  2176. rdep->item->id, rdep->item->symbol, item->symbol);
  2177. if (!rspamd_symcache_check_deps (task, task->cfg->cache,
  2178. rdep->item,
  2179. checkpoint, 0, FALSE)) {
  2180. msg_debug_cache_task ("blocked execution of %d(%s) rdep of %s "
  2181. "unless deps are resolved",
  2182. rdep->item->id, rdep->item->symbol, item->symbol);
  2183. }
  2184. else {
  2185. rspamd_symcache_check_symbol (task, task->cfg->cache,
  2186. rdep->item,
  2187. checkpoint);
  2188. }
  2189. }
  2190. }
  2191. }
  2192. }
  2193. guint
  2194. rspamd_symcache_item_async_inc_full (struct rspamd_task *task,
  2195. struct rspamd_symcache_item *item,
  2196. const gchar *subsystem,
  2197. const gchar *loc)
  2198. {
  2199. struct rspamd_symcache_dynamic_item *dyn_item;
  2200. struct cache_savepoint *checkpoint = task->checkpoint;
  2201. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  2202. msg_debug_cache_task ("increase async events counter for %s(%d) = %d + 1; "
  2203. "subsystem %s (%s)",
  2204. item->symbol, item->id, dyn_item->async_events, subsystem, loc);
  2205. return ++dyn_item->async_events;
  2206. }
  2207. guint
  2208. rspamd_symcache_item_async_dec_full (struct rspamd_task *task,
  2209. struct rspamd_symcache_item *item,
  2210. const gchar *subsystem,
  2211. const gchar *loc)
  2212. {
  2213. struct rspamd_symcache_dynamic_item *dyn_item;
  2214. struct cache_savepoint *checkpoint = task->checkpoint;
  2215. dyn_item = rspamd_symcache_get_dynamic (checkpoint, item);
  2216. msg_debug_cache_task ("decrease async events counter for %s(%d) = %d - 1; "
  2217. "subsystem %s (%s)",
  2218. item->symbol, item->id, dyn_item->async_events, subsystem, loc);
  2219. g_assert (dyn_item->async_events > 0);
  2220. return --dyn_item->async_events;
  2221. }
  2222. gboolean
  2223. rspamd_symcache_item_async_dec_check_full (struct rspamd_task *task,
  2224. struct rspamd_symcache_item *item,
  2225. const gchar *subsystem,
  2226. const gchar *loc)
  2227. {
  2228. if (rspamd_symcache_item_async_dec_full (task, item, subsystem, loc) == 0) {
  2229. rspamd_symcache_finalize_item (task, item);
  2230. return TRUE;
  2231. }
  2232. return FALSE;
  2233. }