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

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