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.

rspamd_symcache.c 69KB

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