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.

cfg_utils.c 71KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960
  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 "cfg_file.h"
  18. #include "rspamd.h"
  19. #include "cfg_file_private.h"
  20. #include "scan_result.h"
  21. #include "lua/lua_common.h"
  22. #include "lua/lua_thread_pool.h"
  23. #include "maps/map.h"
  24. #include "maps/map_helpers.h"
  25. #include "maps/map_private.h"
  26. #include "dynamic_cfg.h"
  27. #include "utlist.h"
  28. #include "stat_api.h"
  29. #include "unix-std.h"
  30. #include "libutil/multipattern.h"
  31. #include "monitored.h"
  32. #include "ref.h"
  33. #include "cryptobox.h"
  34. #include "ssl_util.h"
  35. #include "contrib/libottery/ottery.h"
  36. #include "contrib/fastutf8/fastutf8.h"
  37. #ifdef SYS_ZSTD
  38. # include "zstd.h"
  39. #else
  40. # define ZSTD_STATIC_LINKING_ONLY
  41. # include "contrib/zstd/zstd.h"
  42. #endif
  43. #ifdef HAVE_OPENSSL
  44. #include <openssl/rand.h>
  45. #include <openssl/err.h>
  46. #include <openssl/evp.h>
  47. #include <openssl/ssl.h>
  48. #include <openssl/conf.h>
  49. #endif
  50. #ifdef HAVE_LOCALE_H
  51. #include <locale.h>
  52. #endif
  53. #ifdef HAVE_SYS_RESOURCE_H
  54. #include <sys/resource.h>
  55. #endif
  56. #include <math.h>
  57. #include "libserver/composites/composites.h"
  58. #include "blas-config.h"
  59. #define DEFAULT_SCORE 10.0
  60. #define DEFAULT_RLIMIT_NOFILE 2048
  61. #define DEFAULT_RLIMIT_MAXCORE 0
  62. #define DEFAULT_MAP_TIMEOUT 60.0 * 5
  63. #define DEFAULT_MAP_FILE_WATCH_MULTIPLIER 1
  64. #define DEFAULT_MIN_WORD 0
  65. #define DEFAULT_MAX_WORD 40
  66. #define DEFAULT_WORDS_DECAY 600
  67. #define DEFAULT_MAX_MESSAGE (50 * 1024 * 1024)
  68. #define DEFAULT_MAX_PIC (1 * 1024 * 1024)
  69. #define DEFAULT_MAX_SHOTS 100
  70. #define DEFAULT_MAX_SESSIONS 100
  71. #define DEFAULT_MAX_WORKERS 4
  72. /* Timeout for task processing */
  73. #define DEFAULT_TASK_TIMEOUT 8.0
  74. #define DEFAULT_LUA_GC_STEP 200
  75. #define DEFAULT_LUA_GC_PAUSE 200
  76. #define DEFAULT_GC_MAXITERS 0
  77. struct rspamd_ucl_map_cbdata {
  78. struct rspamd_config *cfg;
  79. GString *buf;
  80. };
  81. static gchar * rspamd_ucl_read_cb (gchar * chunk,
  82. gint len,
  83. struct map_cb_data *data,
  84. gboolean final);
  85. static void rspamd_ucl_fin_cb (struct map_cb_data *data, void **target);
  86. static void rspamd_ucl_dtor_cb (struct map_cb_data *data);
  87. guint rspamd_config_log_id = (guint)-1;
  88. RSPAMD_CONSTRUCTOR(rspamd_config_log_init)
  89. {
  90. rspamd_config_log_id = rspamd_logger_add_debug_module("config");
  91. }
  92. gboolean
  93. rspamd_parse_bind_line (struct rspamd_config *cfg,
  94. struct rspamd_worker_conf *cf,
  95. const gchar *str)
  96. {
  97. struct rspamd_worker_bind_conf *cnf;
  98. const gchar *fdname;
  99. gboolean ret = TRUE;
  100. if (str == NULL) {
  101. return FALSE;
  102. }
  103. cnf = g_malloc0 (sizeof (struct rspamd_worker_bind_conf));
  104. cnf->cnt = 1024;
  105. cnf->bind_line = g_strdup (str);
  106. if (g_ascii_strncasecmp (str, "systemd:", sizeof ("systemd:") - 1) == 0) {
  107. /* The actual socket will be passed by systemd environment */
  108. fdname = str + sizeof ("systemd:") - 1;
  109. cnf->is_systemd = TRUE;
  110. cnf->addrs = g_ptr_array_new_full (1, g_free);
  111. if (fdname[0]) {
  112. g_ptr_array_add (cnf->addrs, g_strdup (fdname));
  113. cnf->cnt = cnf->addrs->len;
  114. cnf->name = g_strdup (str);
  115. LL_PREPEND (cf->bind_conf, cnf);
  116. }
  117. else {
  118. msg_err_config ("cannot parse bind line: %s", str);
  119. ret = FALSE;
  120. }
  121. }
  122. else {
  123. if (rspamd_parse_host_port_priority (str, &cnf->addrs,
  124. NULL, &cnf->name, DEFAULT_BIND_PORT, TRUE, NULL) == RSPAMD_PARSE_ADDR_FAIL) {
  125. msg_err_config ("cannot parse bind line: %s", str);
  126. ret = FALSE;
  127. }
  128. else {
  129. cnf->cnt = cnf->addrs->len;
  130. LL_PREPEND (cf->bind_conf, cnf);
  131. }
  132. }
  133. if (!ret) {
  134. if (cnf->addrs) {
  135. g_ptr_array_free (cnf->addrs, TRUE);
  136. }
  137. g_free (cnf->name);
  138. g_free (cnf);
  139. }
  140. return ret;
  141. }
  142. struct rspamd_config *
  143. rspamd_config_new (enum rspamd_config_init_flags flags)
  144. {
  145. struct rspamd_config *cfg;
  146. rspamd_mempool_t *pool;
  147. pool = rspamd_mempool_new (8 * 1024 * 1024, "cfg", 0);
  148. cfg = rspamd_mempool_alloc0_type(pool, struct rspamd_config);
  149. /* Allocate larger pool for cfg */
  150. cfg->cfg_pool = pool;
  151. cfg->dns_timeout = 1.0;
  152. cfg->dns_retransmits = 5;
  153. /* 16 sockets per DNS server */
  154. cfg->dns_io_per_server = 16;
  155. cfg->unknown_weight = NAN;
  156. /* Add all internal actions to keep compatibility */
  157. for (int i = METRIC_ACTION_REJECT; i < METRIC_ACTION_MAX; i ++) {
  158. struct rspamd_action *action;
  159. action = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*action));
  160. action->threshold = NAN;
  161. action->name = rspamd_mempool_strdup (cfg->cfg_pool,
  162. rspamd_action_to_str (i));
  163. action->action_type = i;
  164. if (i == METRIC_ACTION_SOFT_REJECT) {
  165. action->flags |= RSPAMD_ACTION_NO_THRESHOLD|RSPAMD_ACTION_HAM;
  166. }
  167. else if (i == METRIC_ACTION_GREYLIST) {
  168. action->flags |= RSPAMD_ACTION_THRESHOLD_ONLY|RSPAMD_ACTION_HAM;
  169. }
  170. else if (i == METRIC_ACTION_NOACTION) {
  171. action->flags |= RSPAMD_ACTION_HAM;
  172. }
  173. HASH_ADD_KEYPTR (hh, cfg->actions,
  174. action->name, strlen (action->name), action);
  175. }
  176. /* Disable timeout */
  177. cfg->task_timeout = DEFAULT_TASK_TIMEOUT;
  178. rspamd_config_init_metric (cfg);
  179. cfg->composites_manager = rspamd_composites_manager_create(cfg);
  180. cfg->classifiers_symbols = g_hash_table_new (rspamd_str_hash,
  181. rspamd_str_equal);
  182. cfg->cfg_params = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
  183. cfg->debug_modules = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
  184. cfg->explicit_modules = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
  185. cfg->wrk_parsers = g_hash_table_new (g_int_hash, g_int_equal);
  186. cfg->trusted_keys = g_hash_table_new (rspamd_str_hash,
  187. rspamd_str_equal);
  188. cfg->map_timeout = DEFAULT_MAP_TIMEOUT;
  189. cfg->map_file_watch_multiplier = DEFAULT_MAP_FILE_WATCH_MULTIPLIER;
  190. cfg->log_level = G_LOG_LEVEL_WARNING;
  191. cfg->log_flags = RSPAMD_LOG_FLAG_DEFAULT;
  192. cfg->check_text_attachements = TRUE;
  193. cfg->dns_max_requests = 64;
  194. cfg->history_rows = 200;
  195. cfg->log_error_elts = 10;
  196. cfg->log_error_elt_maxlen = 1000;
  197. cfg->cache_reload_time = 30.0;
  198. cfg->max_lua_urls = 1024;
  199. cfg->max_urls = cfg->max_lua_urls * 10;
  200. cfg->max_recipients = 1024;
  201. cfg->max_blas_threads = 1;
  202. cfg->max_opts_len = 4096;
  203. /* Default log line */
  204. cfg->log_format_str = "id: <$mid>,$if_qid{ qid: <$>,}$if_ip{ ip: $,}"
  205. "$if_user{ user: $,}$if_smtp_from{ from: <$>,} (default: $is_spam "
  206. "($action): [$scores] [$symbols_scores_params]), len: $len, time: $time_real, "
  207. "dns req: $dns_req, digest: <$digest>"
  208. "$if_smtp_rcpts{ rcpts: <$>, }$if_mime_rcpt{ mime_rcpt: <$>, }";
  209. /* Allow non-mime input by default */
  210. cfg->allow_raw_input = TRUE;
  211. /* Default maximum words processed */
  212. cfg->words_decay = DEFAULT_WORDS_DECAY;
  213. cfg->min_word_len = DEFAULT_MIN_WORD;
  214. cfg->max_word_len = DEFAULT_MAX_WORD;
  215. /* GC limits */
  216. cfg->lua_gc_pause = DEFAULT_LUA_GC_PAUSE;
  217. cfg->lua_gc_step = DEFAULT_LUA_GC_STEP;
  218. cfg->full_gc_iters = DEFAULT_GC_MAXITERS;
  219. /* Default hyperscan cache */
  220. cfg->hs_cache_dir = RSPAMD_DBDIR "/";
  221. if (!(flags & RSPAMD_CONFIG_INIT_SKIP_LUA)) {
  222. cfg->lua_state = rspamd_lua_init (flags & RSPAMD_CONFIG_INIT_WIPE_LUA_MEM);
  223. cfg->own_lua_state = TRUE;
  224. cfg->lua_thread_pool = lua_thread_pool_new (cfg->lua_state);
  225. }
  226. cfg->cache = rspamd_symcache_new (cfg);
  227. cfg->ups_ctx = rspamd_upstreams_library_init ();
  228. cfg->re_cache = rspamd_re_cache_new ();
  229. cfg->doc_strings = ucl_object_typed_new (UCL_OBJECT);
  230. /*
  231. * Unless exim is fixed
  232. */
  233. cfg->enable_shutdown_workaround = TRUE;
  234. cfg->ssl_ciphers = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
  235. cfg->max_message = DEFAULT_MAX_MESSAGE;
  236. cfg->max_pic_size = DEFAULT_MAX_PIC;
  237. cfg->images_cache_size = 256;
  238. cfg->monitored_ctx = rspamd_monitored_ctx_init ();
  239. cfg->neighbours = ucl_object_typed_new (UCL_OBJECT);
  240. cfg->redis_pool = rspamd_redis_pool_init ();
  241. cfg->default_max_shots = DEFAULT_MAX_SHOTS;
  242. cfg->max_sessions_cache = DEFAULT_MAX_SESSIONS;
  243. cfg->maps_cache_dir = rspamd_mempool_strdup (cfg->cfg_pool, RSPAMD_DBDIR);
  244. cfg->c_modules = g_ptr_array_new ();
  245. cfg->heartbeat_interval = 10.0;
  246. cfg->enable_css_parser = true;
  247. REF_INIT_RETAIN (cfg, rspamd_config_free);
  248. return cfg;
  249. }
  250. void
  251. rspamd_config_free (struct rspamd_config *cfg)
  252. {
  253. struct rspamd_config_cfg_lua_script *sc, *sctmp;
  254. struct rspamd_config_settings_elt *set, *stmp;
  255. struct rspamd_worker_log_pipe *lp, *ltmp;
  256. rspamd_lua_run_config_unload (cfg->lua_state, cfg);
  257. /* Scripts part */
  258. DL_FOREACH_SAFE (cfg->on_term_scripts, sc, sctmp) {
  259. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX, sc->cbref);
  260. }
  261. DL_FOREACH_SAFE (cfg->on_load_scripts, sc, sctmp) {
  262. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX, sc->cbref);
  263. }
  264. DL_FOREACH_SAFE (cfg->post_init_scripts, sc, sctmp) {
  265. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX, sc->cbref);
  266. }
  267. DL_FOREACH_SAFE (cfg->config_unload_scripts, sc, sctmp) {
  268. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX, sc->cbref);
  269. }
  270. DL_FOREACH_SAFE (cfg->setting_ids, set, stmp) {
  271. REF_RELEASE (set);
  272. }
  273. rspamd_map_remove_all (cfg);
  274. rspamd_mempool_destructors_enforce (cfg->cfg_pool);
  275. g_list_free (cfg->classifiers);
  276. g_list_free (cfg->workers);
  277. rspamd_symcache_destroy (cfg->cache);
  278. ucl_object_unref (cfg->rcl_obj);
  279. ucl_object_unref (cfg->config_comments);
  280. ucl_object_unref (cfg->doc_strings);
  281. ucl_object_unref (cfg->neighbours);
  282. g_hash_table_remove_all (cfg->cfg_params);
  283. g_hash_table_unref (cfg->cfg_params);
  284. g_hash_table_unref (cfg->classifiers_symbols);
  285. g_hash_table_unref (cfg->debug_modules);
  286. g_hash_table_unref (cfg->explicit_modules);
  287. g_hash_table_unref (cfg->wrk_parsers);
  288. g_hash_table_unref (cfg->trusted_keys);
  289. rspamd_re_cache_unref (cfg->re_cache);
  290. g_ptr_array_free (cfg->c_modules, TRUE);
  291. if (cfg->monitored_ctx) {
  292. rspamd_monitored_ctx_destroy (cfg->monitored_ctx);
  293. }
  294. if (cfg->lua_state && cfg->own_lua_state) {
  295. lua_thread_pool_free (cfg->lua_thread_pool);
  296. rspamd_lua_close (cfg->lua_state);
  297. }
  298. if (cfg->redis_pool) {
  299. rspamd_redis_pool_destroy (cfg->redis_pool);
  300. }
  301. rspamd_upstreams_library_unref (cfg->ups_ctx);
  302. HASH_CLEAR (hh, cfg->actions);
  303. rspamd_mempool_destructors_enforce (cfg->cfg_pool);
  304. if (cfg->checksum) {
  305. g_free (cfg->checksum);
  306. }
  307. REF_RELEASE (cfg->libs_ctx);
  308. DL_FOREACH_SAFE (cfg->log_pipes, lp, ltmp) {
  309. close (lp->fd);
  310. g_free (lp);
  311. }
  312. rspamd_mempool_delete (cfg->cfg_pool);
  313. }
  314. const ucl_object_t *
  315. rspamd_config_get_module_opt (struct rspamd_config *cfg,
  316. const gchar *module_name,
  317. const gchar *opt_name)
  318. {
  319. const ucl_object_t *res = NULL, *sec;
  320. sec = ucl_obj_get_key (cfg->rcl_obj, module_name);
  321. if (sec != NULL) {
  322. res = ucl_obj_get_key (sec, opt_name);
  323. }
  324. return res;
  325. }
  326. gchar
  327. rspamd_config_parse_flag (const gchar *str, guint len)
  328. {
  329. gchar c;
  330. if (!str || !*str) {
  331. return -1;
  332. }
  333. if (len == 0) {
  334. len = strlen (str);
  335. }
  336. switch (len) {
  337. case 1:
  338. c = g_ascii_tolower (*str);
  339. if (c == 'y' || c == '1') {
  340. return 1;
  341. }
  342. else if (c == 'n' || c == '0') {
  343. return 0;
  344. }
  345. break;
  346. case 2:
  347. if (g_ascii_strncasecmp (str, "no", len) == 0) {
  348. return 0;
  349. }
  350. else if (g_ascii_strncasecmp (str, "on", len) == 0) {
  351. return 1;
  352. }
  353. break;
  354. case 3:
  355. if (g_ascii_strncasecmp (str, "yes", len) == 0) {
  356. return 1;
  357. }
  358. else if (g_ascii_strncasecmp (str, "off", len) == 0) {
  359. return 0;
  360. }
  361. break;
  362. case 4:
  363. if (g_ascii_strncasecmp (str, "true", len) == 0) {
  364. return 1;
  365. }
  366. break;
  367. case 5:
  368. if (g_ascii_strncasecmp (str, "false", len) == 0) {
  369. return 0;
  370. }
  371. break;
  372. }
  373. return -1;
  374. }
  375. static gboolean
  376. rspamd_config_process_var (struct rspamd_config *cfg, const rspamd_ftok_t *var,
  377. const rspamd_ftok_t *content)
  378. {
  379. guint flags = RSPAMD_LOG_FLAG_DEFAULT;
  380. struct rspamd_log_format *lf;
  381. enum rspamd_log_format_type type;
  382. rspamd_ftok_t tok;
  383. gint id;
  384. g_assert (var != NULL);
  385. if (var->len > 3 && rspamd_lc_cmp (var->begin, "if_", 3) == 0) {
  386. flags |= RSPAMD_LOG_FMT_FLAG_CONDITION;
  387. tok.begin = var->begin + 3;
  388. tok.len = var->len - 3;
  389. }
  390. else {
  391. tok.begin = var->begin;
  392. tok.len = var->len;
  393. }
  394. /* Now compare variable and check what we have */
  395. if (rspamd_ftok_cstr_equal (&tok, "mid", TRUE)) {
  396. type = RSPAMD_LOG_MID;
  397. }
  398. else if (rspamd_ftok_cstr_equal (&tok, "qid", TRUE)) {
  399. type = RSPAMD_LOG_QID;
  400. }
  401. else if (rspamd_ftok_cstr_equal (&tok, "user", TRUE)) {
  402. type = RSPAMD_LOG_USER;
  403. }
  404. else if (rspamd_ftok_cstr_equal (&tok, "is_spam", TRUE)) {
  405. type = RSPAMD_LOG_ISSPAM;
  406. }
  407. else if (rspamd_ftok_cstr_equal (&tok, "action", TRUE)) {
  408. type = RSPAMD_LOG_ACTION;
  409. }
  410. else if (rspamd_ftok_cstr_equal (&tok, "scores", TRUE)) {
  411. type = RSPAMD_LOG_SCORES;
  412. }
  413. else if (rspamd_ftok_cstr_equal (&tok, "symbols", TRUE)) {
  414. type = RSPAMD_LOG_SYMBOLS;
  415. }
  416. else if (rspamd_ftok_cstr_equal (&tok, "symbols_scores", TRUE)) {
  417. type = RSPAMD_LOG_SYMBOLS;
  418. flags |= RSPAMD_LOG_FMT_FLAG_SYMBOLS_SCORES;
  419. }
  420. else if (rspamd_ftok_cstr_equal (&tok, "symbols_params", TRUE)) {
  421. type = RSPAMD_LOG_SYMBOLS;
  422. flags |= RSPAMD_LOG_FMT_FLAG_SYMBOLS_PARAMS;
  423. }
  424. else if (rspamd_ftok_cstr_equal (&tok, "symbols_scores_params", TRUE)) {
  425. type = RSPAMD_LOG_SYMBOLS;
  426. flags |= RSPAMD_LOG_FMT_FLAG_SYMBOLS_PARAMS|RSPAMD_LOG_FMT_FLAG_SYMBOLS_SCORES;
  427. }
  428. else if (rspamd_ftok_cstr_equal (&tok, "groups", TRUE)) {
  429. type = RSPAMD_LOG_GROUPS;
  430. }
  431. else if (rspamd_ftok_cstr_equal (&tok, "public_groups", TRUE)) {
  432. type = RSPAMD_LOG_PUBLIC_GROUPS;
  433. }
  434. else if (rspamd_ftok_cstr_equal (&tok, "ip", TRUE)) {
  435. type = RSPAMD_LOG_IP;
  436. }
  437. else if (rspamd_ftok_cstr_equal (&tok, "len", TRUE)) {
  438. type = RSPAMD_LOG_LEN;
  439. }
  440. else if (rspamd_ftok_cstr_equal (&tok, "dns_req", TRUE)) {
  441. type = RSPAMD_LOG_DNS_REQ;
  442. }
  443. else if (rspamd_ftok_cstr_equal (&tok, "smtp_from", TRUE)) {
  444. type = RSPAMD_LOG_SMTP_FROM;
  445. }
  446. else if (rspamd_ftok_cstr_equal (&tok, "mime_from", TRUE)) {
  447. type = RSPAMD_LOG_MIME_FROM;
  448. }
  449. else if (rspamd_ftok_cstr_equal (&tok, "smtp_rcpt", TRUE)) {
  450. type = RSPAMD_LOG_SMTP_RCPT;
  451. }
  452. else if (rspamd_ftok_cstr_equal (&tok, "mime_rcpt", TRUE)) {
  453. type = RSPAMD_LOG_MIME_RCPT;
  454. }
  455. else if (rspamd_ftok_cstr_equal (&tok, "smtp_rcpts", TRUE)) {
  456. type = RSPAMD_LOG_SMTP_RCPTS;
  457. }
  458. else if (rspamd_ftok_cstr_equal (&tok, "mime_rcpts", TRUE)) {
  459. type = RSPAMD_LOG_MIME_RCPTS;
  460. }
  461. else if (rspamd_ftok_cstr_equal (&tok, "time_real", TRUE)) {
  462. type = RSPAMD_LOG_TIME_REAL;
  463. }
  464. else if (rspamd_ftok_cstr_equal (&tok, "time_virtual", TRUE)) {
  465. type = RSPAMD_LOG_TIME_VIRTUAL;
  466. }
  467. else if (rspamd_ftok_cstr_equal (&tok, "lua", TRUE)) {
  468. type = RSPAMD_LOG_LUA;
  469. }
  470. else if (rspamd_ftok_cstr_equal (&tok, "digest", TRUE) ||
  471. rspamd_ftok_cstr_equal (&tok, "checksum", TRUE)) {
  472. type = RSPAMD_LOG_DIGEST;
  473. }
  474. else if (rspamd_ftok_cstr_equal (&tok, "filename", TRUE)) {
  475. type = RSPAMD_LOG_FILENAME;
  476. }
  477. else if (rspamd_ftok_cstr_equal (&tok, "forced_action", TRUE)) {
  478. type = RSPAMD_LOG_FORCED_ACTION;
  479. }
  480. else if (rspamd_ftok_cstr_equal (&tok, "settings_id", TRUE)) {
  481. type = RSPAMD_LOG_SETTINGS_ID;
  482. }
  483. else if (rspamd_ftok_cstr_equal (&tok, "mempool_size", TRUE)) {
  484. type = RSPAMD_LOG_MEMPOOL_SIZE;
  485. }
  486. else if (rspamd_ftok_cstr_equal (&tok, "mempool_waste", TRUE)) {
  487. type = RSPAMD_LOG_MEMPOOL_WASTE;
  488. }
  489. else {
  490. msg_err_config ("unknown log variable: %T", &tok);
  491. return FALSE;
  492. }
  493. lf = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*lf));
  494. lf->type = type;
  495. lf->flags = flags;
  496. if (type != RSPAMD_LOG_LUA) {
  497. if (content && content->len > 0) {
  498. lf->data = rspamd_mempool_alloc0 (cfg->cfg_pool,
  499. sizeof (rspamd_ftok_t));
  500. memcpy (lf->data, content, sizeof (*content));
  501. lf->len = sizeof (*content);
  502. }
  503. }
  504. else {
  505. /* Load lua code and ensure that we have function ref returned */
  506. if (!content || content->len == 0) {
  507. msg_err_config ("lua variable needs content: %T", &tok);
  508. return FALSE;
  509. }
  510. if (luaL_loadbuffer (cfg->lua_state, content->begin, content->len,
  511. "lua log variable") != 0) {
  512. msg_err_config ("error loading lua code: '%T': %s", content,
  513. lua_tostring (cfg->lua_state, -1));
  514. return FALSE;
  515. }
  516. if (lua_pcall (cfg->lua_state, 0, 1, 0) != 0) {
  517. msg_err_config ("error executing lua code: '%T': %s", content,
  518. lua_tostring (cfg->lua_state, -1));
  519. lua_pop (cfg->lua_state, 1);
  520. return FALSE;
  521. }
  522. if (lua_type (cfg->lua_state, -1) != LUA_TFUNCTION) {
  523. msg_err_config ("lua variable should return function: %T", content);
  524. lua_pop (cfg->lua_state, 1);
  525. return FALSE;
  526. }
  527. id = luaL_ref (cfg->lua_state, LUA_REGISTRYINDEX);
  528. lf->data = GINT_TO_POINTER (id);
  529. lf->len = 0;
  530. }
  531. DL_APPEND (cfg->log_format, lf);
  532. return TRUE;
  533. }
  534. static gboolean
  535. rspamd_config_parse_log_format (struct rspamd_config *cfg)
  536. {
  537. const gchar *p, *c, *end, *s;
  538. gchar *d;
  539. struct rspamd_log_format *lf = NULL;
  540. rspamd_ftok_t var, var_content;
  541. enum {
  542. parse_str,
  543. parse_dollar,
  544. parse_var_name,
  545. parse_var_content,
  546. } state = parse_str;
  547. gint braces = 0;
  548. g_assert (cfg != NULL);
  549. c = cfg->log_format_str;
  550. if (c == NULL) {
  551. return FALSE;
  552. }
  553. p = c;
  554. end = p + strlen (p);
  555. while (p < end) {
  556. switch (state) {
  557. case parse_str:
  558. if (*p == '$') {
  559. state = parse_dollar;
  560. }
  561. else {
  562. p ++;
  563. }
  564. break;
  565. case parse_dollar:
  566. if (p > c) {
  567. /* We have string element that we need to store */
  568. lf = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*lf));
  569. lf->type = RSPAMD_LOG_STRING;
  570. lf->data = rspamd_mempool_alloc (cfg->cfg_pool, p - c + 1);
  571. /* Filter \r\n from the destination */
  572. s = c;
  573. d = lf->data;
  574. while (s < p) {
  575. if (*s != '\r' && *s != '\n') {
  576. *d++ = *s++;
  577. }
  578. else {
  579. *d ++ = ' ';
  580. s++;
  581. }
  582. }
  583. *d = '\0';
  584. lf->len = d - (char *) lf->data;
  585. DL_APPEND (cfg->log_format, lf);
  586. lf = NULL;
  587. }
  588. p++;
  589. c = p;
  590. state = parse_var_name;
  591. break;
  592. case parse_var_name:
  593. if (*p == '{') {
  594. var.begin = c;
  595. var.len = p - c;
  596. p ++;
  597. c = p;
  598. state = parse_var_content;
  599. braces = 1;
  600. }
  601. else if (*p != '_' && *p != '-' && !g_ascii_isalnum (*p)) {
  602. /* Variable with no content */
  603. var.begin = c;
  604. var.len = p - c;
  605. c = p;
  606. if (!rspamd_config_process_var (cfg, &var, NULL)) {
  607. return FALSE;
  608. }
  609. state = parse_str;
  610. }
  611. else {
  612. p++;
  613. }
  614. break;
  615. case parse_var_content:
  616. if (*p == '}' && --braces == 0) {
  617. var_content.begin = c;
  618. var_content.len = p - c;
  619. p ++;
  620. c = p;
  621. if (!rspamd_config_process_var (cfg, &var, &var_content)) {
  622. return FALSE;
  623. }
  624. state = parse_str;
  625. }
  626. else if (*p == '{') {
  627. braces ++;
  628. p ++;
  629. }
  630. else {
  631. p++;
  632. }
  633. break;
  634. }
  635. }
  636. /* Last state */
  637. switch (state) {
  638. case parse_str:
  639. if (p > c) {
  640. /* We have string element that we need to store */
  641. lf = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*lf));
  642. lf->type = RSPAMD_LOG_STRING;
  643. lf->data = rspamd_mempool_alloc (cfg->cfg_pool, p - c + 1);
  644. /* Filter \r\n from the destination */
  645. s = c;
  646. d = lf->data;
  647. while (s < p) {
  648. if (*s != '\r' && *s != '\n') {
  649. *d++ = *s++;
  650. }
  651. else {
  652. *d++ = ' ';
  653. s++;
  654. }
  655. }
  656. *d = '\0';
  657. lf->len = d - (char *)lf->data;
  658. DL_APPEND (cfg->log_format, lf);
  659. lf = NULL;
  660. }
  661. break;
  662. case parse_var_name:
  663. var.begin = c;
  664. var.len = p - c;
  665. if (!rspamd_config_process_var (cfg, &var, NULL)) {
  666. return FALSE;
  667. }
  668. break;
  669. case parse_dollar:
  670. case parse_var_content:
  671. msg_err_config ("cannot parse log format %s: incomplete string",
  672. cfg->log_format_str);
  673. return FALSE;
  674. break;
  675. }
  676. return TRUE;
  677. }
  678. static void
  679. rspamd_urls_config_dtor (gpointer _unused)
  680. {
  681. rspamd_url_deinit ();
  682. }
  683. /*
  684. * Perform post load actions
  685. */
  686. gboolean
  687. rspamd_config_post_load (struct rspamd_config *cfg,
  688. enum rspamd_post_load_options opts)
  689. {
  690. #ifdef HAVE_CLOCK_GETTIME
  691. struct timespec ts;
  692. #endif
  693. gboolean ret = TRUE;
  694. #ifdef HAVE_CLOCK_GETTIME
  695. #ifdef HAVE_CLOCK_PROCESS_CPUTIME_ID
  696. clock_getres (CLOCK_PROCESS_CPUTIME_ID, &ts);
  697. # elif defined(HAVE_CLOCK_VIRTUAL)
  698. clock_getres (CLOCK_VIRTUAL, &ts);
  699. # else
  700. clock_getres (CLOCK_REALTIME, &ts);
  701. # endif
  702. rspamd_logger_configure_modules (cfg->debug_modules);
  703. cfg->clock_res = log10 (1000000. / ts.tv_nsec);
  704. if (cfg->clock_res < 0) {
  705. cfg->clock_res = 0;
  706. }
  707. if (cfg->clock_res > 3) {
  708. cfg->clock_res = 3;
  709. }
  710. #else
  711. /* For gettimeofday */
  712. cfg->clock_res = 1;
  713. #endif
  714. if (cfg->one_shot_mode) {
  715. msg_info_config ("enabling one shot mode (was %d max shots)",
  716. cfg->default_max_shots);
  717. cfg->default_max_shots = 1;
  718. }
  719. rspamd_regexp_library_init (cfg);
  720. rspamd_multipattern_library_init (cfg->hs_cache_dir);
  721. #if defined(WITH_HYPERSCAN) && !defined(__aarch64__) && !defined(__powerpc64__)
  722. if (!cfg->disable_hyperscan) {
  723. if (!(cfg->libs_ctx->crypto_ctx->cpu_config & CPUID_SSSE3)) {
  724. msg_warn_config ("CPU doesn't have SSSE3 instructions set "
  725. "required for hyperscan, disable it");
  726. cfg->disable_hyperscan = TRUE;
  727. }
  728. }
  729. #endif
  730. if (opts & RSPAMD_CONFIG_INIT_URL) {
  731. if (cfg->tld_file == NULL) {
  732. /* Try to guess tld file */
  733. GString *fpath = g_string_new (NULL);
  734. rspamd_printf_gstring (fpath, "%s%c%s", RSPAMD_SHAREDIR,
  735. G_DIR_SEPARATOR, "effective_tld_names.dat");
  736. if (access (fpath->str, R_OK) != -1) {
  737. msg_debug_config ("url_tld option is not specified but %s is available,"
  738. " therefore this file is assumed as TLD file for URL"
  739. " extraction", fpath->str);
  740. cfg->tld_file = rspamd_mempool_strdup (cfg->cfg_pool, fpath->str);
  741. }
  742. else {
  743. if (opts & RSPAMD_CONFIG_INIT_VALIDATE) {
  744. msg_err_config ("no url_tld option has been specified");
  745. ret = FALSE;
  746. }
  747. }
  748. g_string_free (fpath, TRUE);
  749. }
  750. else {
  751. if (access (cfg->tld_file, R_OK) == -1) {
  752. if (opts & RSPAMD_CONFIG_INIT_VALIDATE) {
  753. ret = FALSE;
  754. msg_err_config ("cannot access tld file %s: %s", cfg->tld_file,
  755. strerror (errno));
  756. }
  757. else {
  758. msg_debug_config ("cannot access tld file %s: %s", cfg->tld_file,
  759. strerror (errno));
  760. cfg->tld_file = NULL;
  761. }
  762. }
  763. }
  764. if (opts & RSPAMD_CONFIG_INIT_NO_TLD) {
  765. rspamd_url_init (NULL);
  766. }
  767. else {
  768. rspamd_url_init (cfg->tld_file);
  769. }
  770. rspamd_mempool_add_destructor (cfg->cfg_pool, rspamd_urls_config_dtor,
  771. NULL);
  772. }
  773. init_dynamic_config (cfg);
  774. /* Insert classifiers symbols */
  775. rspamd_config_insert_classify_symbols (cfg);
  776. /* Parse format string that we have */
  777. if (!rspamd_config_parse_log_format (cfg)) {
  778. msg_err_config ("cannot parse log format, task logging will not be available");
  779. }
  780. if (opts & RSPAMD_CONFIG_INIT_SYMCACHE) {
  781. /* Init config cache */
  782. rspamd_symcache_init (cfg->cache);
  783. /* Init re cache */
  784. rspamd_re_cache_init (cfg->re_cache, cfg);
  785. /* Try load Hypersan */
  786. rspamd_re_cache_load_hyperscan (cfg->re_cache,
  787. cfg->hs_cache_dir ? cfg->hs_cache_dir : RSPAMD_DBDIR "/",
  788. true);
  789. }
  790. if (opts & RSPAMD_CONFIG_INIT_LIBS) {
  791. /* Config other libraries */
  792. rspamd_config_libs (cfg->libs_ctx, cfg);
  793. }
  794. /* Validate cache */
  795. if (opts & RSPAMD_CONFIG_INIT_VALIDATE) {
  796. /* Check for actions sanity */
  797. gboolean seen_controller = FALSE;
  798. GList *cur;
  799. struct rspamd_worker_conf *wcf;
  800. cur = cfg->workers;
  801. while (cur) {
  802. wcf = cur->data;
  803. if (wcf->type == g_quark_from_static_string ("controller")) {
  804. seen_controller = TRUE;
  805. break;
  806. }
  807. cur = g_list_next (cur);
  808. }
  809. if (!seen_controller) {
  810. msg_warn_config ("controller worker is unconfigured: learning,"
  811. " periodic scripts, maps watching and many other"
  812. " Rspamd features will be broken");
  813. }
  814. ret = rspamd_symcache_validate (cfg->cache, cfg, FALSE) && ret;
  815. }
  816. if (opts & RSPAMD_CONFIG_INIT_POST_LOAD_LUA) {
  817. rspamd_lua_run_config_post_init (cfg->lua_state, cfg);
  818. }
  819. if (opts & RSPAMD_CONFIG_INIT_PRELOAD_MAPS) {
  820. rspamd_map_preload (cfg);
  821. }
  822. return ret;
  823. }
  824. struct rspamd_classifier_config *
  825. rspamd_config_new_classifier (struct rspamd_config *cfg,
  826. struct rspamd_classifier_config *c)
  827. {
  828. if (c == NULL) {
  829. c =
  830. rspamd_mempool_alloc0 (cfg->cfg_pool,
  831. sizeof (struct rspamd_classifier_config));
  832. c->min_prob_strength = 0.05;
  833. c->min_token_hits = 2;
  834. }
  835. if (c->labels == NULL) {
  836. c->labels = g_hash_table_new_full (rspamd_str_hash,
  837. rspamd_str_equal,
  838. NULL,
  839. (GDestroyNotify)g_list_free);
  840. rspamd_mempool_add_destructor (cfg->cfg_pool,
  841. (rspamd_mempool_destruct_t) g_hash_table_destroy,
  842. c->labels);
  843. }
  844. return c;
  845. }
  846. struct rspamd_statfile_config *
  847. rspamd_config_new_statfile (struct rspamd_config *cfg,
  848. struct rspamd_statfile_config *c)
  849. {
  850. if (c == NULL) {
  851. c =
  852. rspamd_mempool_alloc0 (cfg->cfg_pool,
  853. sizeof (struct rspamd_statfile_config));
  854. }
  855. return c;
  856. }
  857. void
  858. rspamd_config_init_metric (struct rspamd_config *cfg)
  859. {
  860. cfg->grow_factor = 1.0;
  861. cfg->symbols = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
  862. cfg->groups = g_hash_table_new (rspamd_strcase_hash, rspamd_strcase_equal);
  863. cfg->subject = SPAM_SUBJECT;
  864. rspamd_mempool_add_destructor (cfg->cfg_pool,
  865. (rspamd_mempool_destruct_t) g_hash_table_unref,
  866. cfg->symbols);
  867. rspamd_mempool_add_destructor (cfg->cfg_pool,
  868. (rspamd_mempool_destruct_t) g_hash_table_unref,
  869. cfg->groups);
  870. }
  871. struct rspamd_symbols_group *
  872. rspamd_config_new_group (struct rspamd_config *cfg, const gchar *name)
  873. {
  874. struct rspamd_symbols_group *gr;
  875. gr = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*gr));
  876. gr->symbols = g_hash_table_new (rspamd_strcase_hash,
  877. rspamd_strcase_equal);
  878. rspamd_mempool_add_destructor (cfg->cfg_pool,
  879. (rspamd_mempool_destruct_t)g_hash_table_unref, gr->symbols);
  880. gr->name = rspamd_mempool_strdup (cfg->cfg_pool, name);
  881. if (strcmp (gr->name, "ungrouped") == 0) {
  882. gr->flags |= RSPAMD_SYMBOL_GROUP_UNGROUPED;
  883. }
  884. g_hash_table_insert (cfg->groups, gr->name, gr);
  885. return gr;
  886. }
  887. static void
  888. rspamd_worker_conf_dtor (struct rspamd_worker_conf *wcf)
  889. {
  890. if (wcf) {
  891. struct rspamd_worker_bind_conf *cnf, *tmp;
  892. LL_FOREACH_SAFE (wcf->bind_conf, cnf, tmp) {
  893. g_free (cnf->name);
  894. g_free (cnf->bind_line);
  895. g_ptr_array_free (cnf->addrs, TRUE);
  896. g_free (cnf);
  897. }
  898. ucl_object_unref (wcf->options);
  899. g_queue_free (wcf->active_workers);
  900. g_hash_table_unref (wcf->params);
  901. g_free (wcf);
  902. }
  903. }
  904. static void
  905. rspamd_worker_conf_cfg_fin (gpointer d)
  906. {
  907. struct rspamd_worker_conf *wcf = d;
  908. REF_RELEASE (wcf);
  909. }
  910. struct rspamd_worker_conf *
  911. rspamd_config_new_worker (struct rspamd_config *cfg,
  912. struct rspamd_worker_conf *c)
  913. {
  914. if (c == NULL) {
  915. c = g_malloc0 (sizeof (struct rspamd_worker_conf));
  916. c->params = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
  917. c->active_workers = g_queue_new ();
  918. #ifdef HAVE_SC_NPROCESSORS_ONLN
  919. c->count = MIN (DEFAULT_MAX_WORKERS,
  920. MAX (1, sysconf (_SC_NPROCESSORS_ONLN) - 2));
  921. #else
  922. c->count = DEFAULT_MAX_WORKERS;
  923. #endif
  924. c->rlimit_nofile = 0;
  925. c->rlimit_maxcore = 0;
  926. c->enabled = TRUE;
  927. REF_INIT_RETAIN (c, rspamd_worker_conf_dtor);
  928. rspamd_mempool_add_destructor (cfg->cfg_pool,
  929. rspamd_worker_conf_cfg_fin, c);
  930. }
  931. return c;
  932. }
  933. static bool
  934. rspamd_include_map_handler (const guchar *data, gsize len,
  935. const ucl_object_t *args, void * ud)
  936. {
  937. struct rspamd_config *cfg = (struct rspamd_config *)ud;
  938. struct rspamd_ucl_map_cbdata *cbdata, **pcbdata;
  939. gchar *map_line;
  940. map_line = rspamd_mempool_alloc (cfg->cfg_pool, len + 1);
  941. rspamd_strlcpy (map_line, data, len + 1);
  942. cbdata = g_malloc (sizeof (struct rspamd_ucl_map_cbdata));
  943. pcbdata = g_malloc (sizeof (struct rspamd_ucl_map_cbdata *));
  944. cbdata->buf = NULL;
  945. cbdata->cfg = cfg;
  946. *pcbdata = cbdata;
  947. return rspamd_map_add (cfg,
  948. map_line,
  949. "ucl include",
  950. rspamd_ucl_read_cb,
  951. rspamd_ucl_fin_cb,
  952. rspamd_ucl_dtor_cb,
  953. (void **)pcbdata,
  954. NULL, RSPAMD_MAP_DEFAULT) != NULL;
  955. }
  956. /*
  957. * Variables:
  958. * $CONFDIR - configuration directory
  959. * $LOCAL_CONFDIR - local configuration directory
  960. * $RUNDIR - local states directory
  961. * $DBDIR - databases dir
  962. * $LOGDIR - logs dir
  963. * $PLUGINSDIR - plugins dir
  964. * $PREFIX - installation prefix
  965. * $VERSION - rspamd version
  966. */
  967. #define RSPAMD_CONFDIR_MACRO "CONFDIR"
  968. #define RSPAMD_LOCAL_CONFDIR_MACRO "LOCAL_CONFDIR"
  969. #define RSPAMD_RUNDIR_MACRO "RUNDIR"
  970. #define RSPAMD_DBDIR_MACRO "DBDIR"
  971. #define RSPAMD_LOGDIR_MACRO "LOGDIR"
  972. #define RSPAMD_PLUGINSDIR_MACRO "PLUGINSDIR"
  973. #define RSPAMD_SHAREDIR_MACRO "SHAREDIR"
  974. #define RSPAMD_RULESDIR_MACRO "RULESDIR"
  975. #define RSPAMD_WWWDIR_MACRO "WWWDIR"
  976. #define RSPAMD_PREFIX_MACRO "PREFIX"
  977. #define RSPAMD_VERSION_MACRO "VERSION"
  978. #define RSPAMD_VERSION_MAJOR_MACRO "VERSION_MAJOR"
  979. #define RSPAMD_VERSION_MINOR_MACRO "VERSION_MINOR"
  980. #define RSPAMD_BRANCH_VERSION_MACRO "BRANCH_VERSION"
  981. #define RSPAMD_HOSTNAME_MACRO "HOSTNAME"
  982. void
  983. rspamd_ucl_add_conf_variables (struct ucl_parser *parser, GHashTable *vars)
  984. {
  985. GHashTableIter it;
  986. gpointer k, v;
  987. gchar *hostbuf;
  988. gsize hostlen;
  989. ucl_parser_register_variable (parser,
  990. RSPAMD_CONFDIR_MACRO,
  991. RSPAMD_CONFDIR);
  992. ucl_parser_register_variable (parser,
  993. RSPAMD_LOCAL_CONFDIR_MACRO,
  994. RSPAMD_LOCAL_CONFDIR);
  995. ucl_parser_register_variable (parser, RSPAMD_RUNDIR_MACRO,
  996. RSPAMD_RUNDIR);
  997. ucl_parser_register_variable (parser, RSPAMD_DBDIR_MACRO,
  998. RSPAMD_DBDIR);
  999. ucl_parser_register_variable (parser, RSPAMD_LOGDIR_MACRO,
  1000. RSPAMD_LOGDIR);
  1001. ucl_parser_register_variable (parser,
  1002. RSPAMD_PLUGINSDIR_MACRO,
  1003. RSPAMD_PLUGINSDIR);
  1004. ucl_parser_register_variable (parser,
  1005. RSPAMD_SHAREDIR_MACRO,
  1006. RSPAMD_SHAREDIR);
  1007. ucl_parser_register_variable (parser,
  1008. RSPAMD_RULESDIR_MACRO,
  1009. RSPAMD_RULESDIR);
  1010. ucl_parser_register_variable (parser, RSPAMD_WWWDIR_MACRO,
  1011. RSPAMD_WWWDIR);
  1012. ucl_parser_register_variable (parser, RSPAMD_PREFIX_MACRO,
  1013. RSPAMD_PREFIX);
  1014. ucl_parser_register_variable (parser, RSPAMD_VERSION_MACRO, RVERSION);
  1015. ucl_parser_register_variable (parser, RSPAMD_VERSION_MAJOR_MACRO,
  1016. RSPAMD_VERSION_MAJOR);
  1017. ucl_parser_register_variable (parser, RSPAMD_VERSION_MINOR_MACRO,
  1018. RSPAMD_VERSION_MINOR);
  1019. ucl_parser_register_variable (parser, RSPAMD_BRANCH_VERSION_MACRO,
  1020. RSPAMD_VERSION_BRANCH);
  1021. hostlen = sysconf (_SC_HOST_NAME_MAX);
  1022. if (hostlen <= 0) {
  1023. hostlen = 256;
  1024. }
  1025. else {
  1026. hostlen ++;
  1027. }
  1028. hostbuf = g_alloca (hostlen);
  1029. memset (hostbuf, 0, hostlen);
  1030. gethostname (hostbuf, hostlen - 1);
  1031. /* UCL copies variables, so it is safe to pass an ephemeral buffer here */
  1032. ucl_parser_register_variable (parser, RSPAMD_HOSTNAME_MACRO,
  1033. hostbuf);
  1034. if (vars != NULL) {
  1035. g_hash_table_iter_init (&it, vars);
  1036. while (g_hash_table_iter_next (&it, &k, &v)) {
  1037. ucl_parser_register_variable (parser, k, v);
  1038. }
  1039. }
  1040. }
  1041. void
  1042. rspamd_ucl_add_conf_macros (struct ucl_parser *parser,
  1043. struct rspamd_config *cfg)
  1044. {
  1045. ucl_parser_register_macro (parser,
  1046. "include_map",
  1047. rspamd_include_map_handler,
  1048. cfg);
  1049. }
  1050. static void
  1051. symbols_classifiers_callback (gpointer key, gpointer value, gpointer ud)
  1052. {
  1053. struct rspamd_config *cfg = ud;
  1054. /* Actually, statistics should act like any ordinary symbol */
  1055. rspamd_symcache_add_symbol (cfg->cache, key, 0, NULL, NULL,
  1056. SYMBOL_TYPE_CLASSIFIER | SYMBOL_TYPE_NOSTAT, -1);
  1057. }
  1058. void
  1059. rspamd_config_insert_classify_symbols (struct rspamd_config *cfg)
  1060. {
  1061. g_hash_table_foreach (cfg->classifiers_symbols,
  1062. symbols_classifiers_callback,
  1063. cfg);
  1064. }
  1065. struct rspamd_classifier_config *
  1066. rspamd_config_find_classifier (struct rspamd_config *cfg, const gchar *name)
  1067. {
  1068. GList *cur;
  1069. struct rspamd_classifier_config *cf;
  1070. if (name == NULL) {
  1071. return NULL;
  1072. }
  1073. cur = cfg->classifiers;
  1074. while (cur) {
  1075. cf = cur->data;
  1076. if (g_ascii_strcasecmp (cf->name, name) == 0) {
  1077. return cf;
  1078. }
  1079. cur = g_list_next (cur);
  1080. }
  1081. return NULL;
  1082. }
  1083. gboolean
  1084. rspamd_config_check_statfiles (struct rspamd_classifier_config *cf)
  1085. {
  1086. struct rspamd_statfile_config *st;
  1087. gboolean has_other = FALSE, res = FALSE, cur_class = FALSE;
  1088. GList *cur;
  1089. /* First check classes directly */
  1090. cur = cf->statfiles;
  1091. while (cur) {
  1092. st = cur->data;
  1093. if (!has_other) {
  1094. cur_class = st->is_spam;
  1095. has_other = TRUE;
  1096. }
  1097. else {
  1098. if (cur_class != st->is_spam) {
  1099. return TRUE;
  1100. }
  1101. }
  1102. cur = g_list_next (cur);
  1103. }
  1104. if (!has_other) {
  1105. /* We have only one statfile */
  1106. return FALSE;
  1107. }
  1108. /* We have not detected any statfile that has different class, so turn on heuristic based on symbol's name */
  1109. has_other = FALSE;
  1110. cur = cf->statfiles;
  1111. while (cur) {
  1112. st = cur->data;
  1113. if (rspamd_substring_search_caseless (st->symbol,
  1114. strlen (st->symbol),"spam", 4) != -1) {
  1115. st->is_spam = TRUE;
  1116. }
  1117. else if (rspamd_substring_search_caseless (st->symbol,
  1118. strlen (st->symbol),"ham", 3) != -1) {
  1119. st->is_spam = FALSE;
  1120. }
  1121. if (!has_other) {
  1122. cur_class = st->is_spam;
  1123. has_other = TRUE;
  1124. }
  1125. else {
  1126. if (cur_class != st->is_spam) {
  1127. res = TRUE;
  1128. }
  1129. }
  1130. cur = g_list_next (cur);
  1131. }
  1132. return res;
  1133. }
  1134. static gchar *
  1135. rspamd_ucl_read_cb (gchar * chunk,
  1136. gint len,
  1137. struct map_cb_data *data,
  1138. gboolean final)
  1139. {
  1140. struct rspamd_ucl_map_cbdata *cbdata = data->cur_data, *prev;
  1141. if (cbdata == NULL) {
  1142. cbdata = g_malloc (sizeof (struct rspamd_ucl_map_cbdata));
  1143. prev = data->prev_data;
  1144. cbdata->buf = g_string_sized_new (BUFSIZ);
  1145. cbdata->cfg = prev->cfg;
  1146. data->cur_data = cbdata;
  1147. }
  1148. g_string_append_len (cbdata->buf, chunk, len);
  1149. /* Say not to copy any part of this buffer */
  1150. return NULL;
  1151. }
  1152. static void
  1153. rspamd_ucl_fin_cb (struct map_cb_data *data, void **target)
  1154. {
  1155. struct rspamd_ucl_map_cbdata *cbdata = data->cur_data, *prev =
  1156. data->prev_data;
  1157. ucl_object_t *obj;
  1158. struct ucl_parser *parser;
  1159. ucl_object_iter_t it = NULL;
  1160. const ucl_object_t *cur;
  1161. struct rspamd_config *cfg = data->map->cfg;
  1162. if (cbdata == NULL) {
  1163. msg_err_config ("map fin error: new data is NULL");
  1164. return;
  1165. }
  1166. /* New data available */
  1167. parser = ucl_parser_new (0);
  1168. if (!ucl_parser_add_chunk (parser, cbdata->buf->str,
  1169. cbdata->buf->len)) {
  1170. msg_err_config ("cannot parse map %s: %s",
  1171. data->map->name,
  1172. ucl_parser_get_error (parser));
  1173. ucl_parser_free (parser);
  1174. }
  1175. else {
  1176. obj = ucl_parser_get_object (parser);
  1177. ucl_parser_free (parser);
  1178. it = NULL;
  1179. while ((cur = ucl_object_iterate (obj, &it, true))) {
  1180. ucl_object_replace_key (cbdata->cfg->rcl_obj, (ucl_object_t *)cur,
  1181. cur->key, cur->keylen, false);
  1182. }
  1183. ucl_object_unref (obj);
  1184. }
  1185. if (target) {
  1186. *target = data->cur_data;
  1187. }
  1188. if (prev != NULL) {
  1189. if (prev->buf != NULL) {
  1190. g_string_free (prev->buf, TRUE);
  1191. }
  1192. g_free (prev);
  1193. }
  1194. }
  1195. static void
  1196. rspamd_ucl_dtor_cb (struct map_cb_data *data)
  1197. {
  1198. struct rspamd_ucl_map_cbdata *cbdata = data->cur_data;
  1199. if (cbdata != NULL) {
  1200. if (cbdata->buf != NULL) {
  1201. g_string_free (cbdata->buf, TRUE);
  1202. }
  1203. g_free (cbdata);
  1204. }
  1205. }
  1206. gboolean
  1207. rspamd_check_module (struct rspamd_config *cfg, module_t *mod)
  1208. {
  1209. gboolean ret = TRUE;
  1210. if (mod != NULL) {
  1211. if (mod->module_version != RSPAMD_CUR_MODULE_VERSION) {
  1212. msg_err_config ("module %s has incorrect version %xd (%xd expected)",
  1213. mod->name, (gint)mod->module_version, RSPAMD_CUR_MODULE_VERSION);
  1214. ret = FALSE;
  1215. }
  1216. if (ret && mod->rspamd_version != RSPAMD_VERSION_NUM) {
  1217. msg_err_config ("module %s has incorrect rspamd version %xL (%xL expected)",
  1218. mod->name, mod->rspamd_version, RSPAMD_VERSION_NUM);
  1219. ret = FALSE;
  1220. }
  1221. if (ret && strcmp (mod->rspamd_features, RSPAMD_FEATURES) != 0) {
  1222. msg_err_config ("module %s has incorrect rspamd features '%s' ('%s' expected)",
  1223. mod->name, mod->rspamd_features, RSPAMD_FEATURES);
  1224. ret = FALSE;
  1225. }
  1226. }
  1227. else {
  1228. ret = FALSE;
  1229. }
  1230. return ret;
  1231. }
  1232. gboolean
  1233. rspamd_check_worker (struct rspamd_config *cfg, worker_t *wrk)
  1234. {
  1235. gboolean ret = TRUE;
  1236. if (wrk != NULL) {
  1237. if (wrk->worker_version != RSPAMD_CUR_WORKER_VERSION) {
  1238. msg_err_config ("worker %s has incorrect version %xd (%xd expected)",
  1239. wrk->name, wrk->worker_version, RSPAMD_CUR_WORKER_VERSION);
  1240. ret = FALSE;
  1241. }
  1242. if (ret && wrk->rspamd_version != RSPAMD_VERSION_NUM) {
  1243. msg_err_config ("worker %s has incorrect rspamd version %xL (%xL expected)",
  1244. wrk->name, wrk->rspamd_version, RSPAMD_VERSION_NUM);
  1245. ret = FALSE;
  1246. }
  1247. if (ret && strcmp (wrk->rspamd_features, RSPAMD_FEATURES) != 0) {
  1248. msg_err_config ("worker %s has incorrect rspamd features '%s' ('%s' expected)",
  1249. wrk->name, wrk->rspamd_features, RSPAMD_FEATURES);
  1250. ret = FALSE;
  1251. }
  1252. }
  1253. else {
  1254. ret = FALSE;
  1255. }
  1256. return ret;
  1257. }
  1258. gboolean
  1259. rspamd_init_filters (struct rspamd_config *cfg, bool reconfig, bool strict)
  1260. {
  1261. GList *cur;
  1262. module_t *mod, **pmod;
  1263. guint i = 0;
  1264. struct module_ctx *mod_ctx, *cur_ctx;
  1265. gboolean ret = TRUE;
  1266. /* Init all compiled modules */
  1267. for (pmod = cfg->compiled_modules; pmod != NULL && *pmod != NULL; pmod ++) {
  1268. mod = *pmod;
  1269. if (rspamd_check_module (cfg, mod)) {
  1270. if (mod->module_init_func (cfg, &mod_ctx) == 0) {
  1271. g_assert (mod_ctx != NULL);
  1272. g_ptr_array_add (cfg->c_modules, mod_ctx);
  1273. mod_ctx->mod = mod;
  1274. mod->ctx_offset = i ++;
  1275. }
  1276. }
  1277. }
  1278. /* Now check what's enabled */
  1279. cur = g_list_first (cfg->filters);
  1280. while (cur) {
  1281. /* Perform modules configuring */
  1282. mod_ctx = NULL;
  1283. PTR_ARRAY_FOREACH (cfg->c_modules, i, cur_ctx) {
  1284. if (g_ascii_strcasecmp (cur_ctx->mod->name,
  1285. (const gchar *)cur->data) == 0) {
  1286. mod_ctx = cur_ctx;
  1287. break;
  1288. }
  1289. }
  1290. if (mod_ctx) {
  1291. mod = mod_ctx->mod;
  1292. mod_ctx->enabled = rspamd_config_is_module_enabled (cfg, mod->name);
  1293. if (reconfig) {
  1294. if (!mod->module_reconfig_func (cfg)) {
  1295. msg_err_config ("reconfig of %s failed!", mod->name);
  1296. }
  1297. else {
  1298. msg_info_config ("reconfig of %s", mod->name);
  1299. }
  1300. }
  1301. else {
  1302. if (!mod->module_config_func (cfg, strict)) {
  1303. msg_err_config ("config of %s failed", mod->name);
  1304. ret = FALSE;
  1305. if (strict) {
  1306. return FALSE;
  1307. }
  1308. }
  1309. }
  1310. }
  1311. if (mod_ctx == NULL) {
  1312. msg_warn_config ("requested unknown module %s", cur->data);
  1313. }
  1314. cur = g_list_next (cur);
  1315. }
  1316. ret = rspamd_init_lua_filters (cfg, 0, strict) && ret;
  1317. return ret;
  1318. }
  1319. static void
  1320. rspamd_config_new_symbol (struct rspamd_config *cfg, const gchar *symbol,
  1321. gdouble score, const gchar *description, const gchar *group,
  1322. guint flags, guint priority, gint nshots)
  1323. {
  1324. struct rspamd_symbols_group *sym_group;
  1325. struct rspamd_symbol *sym_def;
  1326. gdouble *score_ptr;
  1327. sym_def =
  1328. rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (struct rspamd_symbol));
  1329. score_ptr = rspamd_mempool_alloc (cfg->cfg_pool, sizeof (gdouble));
  1330. if (isnan (score)) {
  1331. /* In fact, it could be defined later */
  1332. msg_debug_config ("score is not defined for symbol %s, set it to zero",
  1333. symbol);
  1334. score = 0.0;
  1335. /* Also set priority to 0 to allow override by anything */
  1336. sym_def->priority = 0;
  1337. flags |= RSPAMD_SYMBOL_FLAG_UNSCORED;
  1338. }
  1339. else {
  1340. sym_def->priority = priority;
  1341. }
  1342. *score_ptr = score;
  1343. sym_def->score = score;
  1344. sym_def->weight_ptr = score_ptr;
  1345. sym_def->name = rspamd_mempool_strdup (cfg->cfg_pool, symbol);
  1346. sym_def->flags = flags;
  1347. sym_def->nshots = nshots != 0 ? nshots : cfg->default_max_shots;
  1348. sym_def->groups = g_ptr_array_sized_new (1);
  1349. rspamd_mempool_add_destructor (cfg->cfg_pool, rspamd_ptr_array_free_hard,
  1350. sym_def->groups);
  1351. if (description) {
  1352. sym_def->description = rspamd_mempool_strdup (cfg->cfg_pool, description);
  1353. }
  1354. msg_debug_config ("registered symbol %s with weight %.2f in and group %s",
  1355. sym_def->name, score, group);
  1356. g_hash_table_insert (cfg->symbols, sym_def->name, sym_def);
  1357. /* Search for symbol group */
  1358. if (group == NULL) {
  1359. group = "ungrouped";
  1360. sym_def->flags |= RSPAMD_SYMBOL_FLAG_UNGROUPED;
  1361. }
  1362. else {
  1363. if (strcmp (group, "ungrouped") == 0) {
  1364. sym_def->flags |= RSPAMD_SYMBOL_FLAG_UNGROUPED;
  1365. }
  1366. }
  1367. sym_group = g_hash_table_lookup (cfg->groups, group);
  1368. if (sym_group == NULL) {
  1369. /* Create new group */
  1370. sym_group = rspamd_config_new_group (cfg, group);
  1371. }
  1372. sym_def->gr = sym_group;
  1373. g_hash_table_insert (sym_group->symbols, sym_def->name, sym_def);
  1374. if (!(sym_def->flags & RSPAMD_SYMBOL_FLAG_UNGROUPED)) {
  1375. g_ptr_array_add (sym_def->groups, sym_group);
  1376. }
  1377. }
  1378. gboolean
  1379. rspamd_config_add_symbol (struct rspamd_config *cfg,
  1380. const gchar *symbol,
  1381. gdouble score,
  1382. const gchar *description,
  1383. const gchar *group,
  1384. guint flags,
  1385. guint priority,
  1386. gint nshots)
  1387. {
  1388. struct rspamd_symbol *sym_def;
  1389. struct rspamd_symbols_group *sym_group;
  1390. guint i;
  1391. g_assert (cfg != NULL);
  1392. g_assert (symbol != NULL);
  1393. sym_def = g_hash_table_lookup (cfg->symbols, symbol);
  1394. if (sym_def != NULL) {
  1395. if (group != NULL) {
  1396. gboolean has_group = FALSE;
  1397. PTR_ARRAY_FOREACH (sym_def->groups, i, sym_group) {
  1398. if (g_ascii_strcasecmp (sym_group->name, group) == 0) {
  1399. /* Group is already here */
  1400. has_group = TRUE;
  1401. break;
  1402. }
  1403. }
  1404. if (!has_group) {
  1405. /* Non-empty group has a priority over non-grouped one */
  1406. sym_group = g_hash_table_lookup (cfg->groups, group);
  1407. if (sym_group == NULL) {
  1408. /* Create new group */
  1409. sym_group = rspamd_config_new_group (cfg, group);
  1410. }
  1411. if ((!sym_def->gr) || (sym_def->flags & RSPAMD_SYMBOL_FLAG_UNGROUPED)) {
  1412. sym_def->gr = sym_group;
  1413. sym_def->flags &= ~RSPAMD_SYMBOL_FLAG_UNGROUPED;
  1414. }
  1415. g_hash_table_insert (sym_group->symbols, sym_def->name, sym_def);
  1416. sym_def->flags &= ~(RSPAMD_SYMBOL_FLAG_UNGROUPED);
  1417. g_ptr_array_add (sym_def->groups, sym_group);
  1418. }
  1419. }
  1420. if (sym_def->priority > priority &&
  1421. (isnan(score) || !(sym_def->flags & RSPAMD_SYMBOL_FLAG_UNSCORED))) {
  1422. msg_debug_config ("symbol %s has been already registered with "
  1423. "priority %ud, do not override (new priority: %ud)",
  1424. symbol,
  1425. sym_def->priority,
  1426. priority);
  1427. /* But we can still add description */
  1428. if (!sym_def->description && description) {
  1429. sym_def->description = rspamd_mempool_strdup (cfg->cfg_pool,
  1430. description);
  1431. }
  1432. /* Or nshots in case of non-default setting */
  1433. if (nshots != 0 && sym_def->nshots == cfg->default_max_shots) {
  1434. sym_def->nshots = nshots;
  1435. }
  1436. return FALSE;
  1437. }
  1438. else {
  1439. if (!isnan (score)) {
  1440. msg_debug_config ("symbol %s has been already registered with "
  1441. "priority %ud, override it with new priority: %ud, "
  1442. "old score: %.2f, new score: %.2f",
  1443. symbol,
  1444. sym_def->priority,
  1445. priority,
  1446. sym_def->score,
  1447. score);
  1448. *sym_def->weight_ptr = score;
  1449. sym_def->score = score;
  1450. sym_def->priority = priority;
  1451. sym_def->flags &= ~RSPAMD_SYMBOL_FLAG_UNSCORED;
  1452. }
  1453. sym_def->flags = flags;
  1454. if (nshots != 0) {
  1455. sym_def->nshots = nshots;
  1456. }
  1457. else {
  1458. /* Do not reset unless we have exactly lower priority */
  1459. if (sym_def->priority < priority) {
  1460. sym_def->nshots = cfg->default_max_shots;
  1461. }
  1462. }
  1463. if (description) {
  1464. sym_def->description = rspamd_mempool_strdup (cfg->cfg_pool,
  1465. description);
  1466. }
  1467. /* We also check group information in this case */
  1468. if (group != NULL && sym_def->gr != NULL &&
  1469. strcmp (group, sym_def->gr->name) != 0) {
  1470. sym_group = g_hash_table_lookup (cfg->groups, group);
  1471. if (sym_group == NULL) {
  1472. /* Create new group */
  1473. sym_group = rspamd_config_new_group (cfg, group);
  1474. }
  1475. if (!(sym_group->flags & RSPAMD_SYMBOL_GROUP_UNGROUPED)) {
  1476. msg_debug_config ("move symbol %s from group %s to %s",
  1477. sym_def->name, sym_def->gr->name, group);
  1478. g_hash_table_remove (sym_def->gr->symbols, sym_def->name);
  1479. sym_def->gr = sym_group;
  1480. g_hash_table_insert (sym_group->symbols, sym_def->name, sym_def);
  1481. }
  1482. }
  1483. return TRUE;
  1484. }
  1485. }
  1486. /* This is called merely when we have an undefined symbol */
  1487. rspamd_config_new_symbol (cfg, symbol, score, description,
  1488. group, flags, priority, nshots);
  1489. return TRUE;
  1490. }
  1491. gboolean
  1492. rspamd_config_add_symbol_group (struct rspamd_config *cfg,
  1493. const gchar *symbol,
  1494. const gchar *group)
  1495. {
  1496. struct rspamd_symbol *sym_def;
  1497. struct rspamd_symbols_group *sym_group;
  1498. guint i;
  1499. g_assert (cfg != NULL);
  1500. g_assert (symbol != NULL);
  1501. g_assert (group != NULL);
  1502. sym_def = g_hash_table_lookup (cfg->symbols, symbol);
  1503. if (sym_def != NULL) {
  1504. gboolean has_group = FALSE;
  1505. PTR_ARRAY_FOREACH (sym_def->groups, i, sym_group) {
  1506. if (g_ascii_strcasecmp (sym_group->name, group) == 0) {
  1507. /* Group is already here */
  1508. has_group = TRUE;
  1509. break;
  1510. }
  1511. }
  1512. if (!has_group) {
  1513. /* Non-empty group has a priority over non-grouped one */
  1514. sym_group = g_hash_table_lookup (cfg->groups, group);
  1515. if (sym_group == NULL) {
  1516. /* Create new group */
  1517. sym_group = rspamd_config_new_group (cfg, group);
  1518. }
  1519. if (!sym_def->gr) {
  1520. sym_def->gr = sym_group;
  1521. }
  1522. g_hash_table_insert (sym_group->symbols, sym_def->name, sym_def);
  1523. sym_def->flags &= ~(RSPAMD_SYMBOL_FLAG_UNGROUPED);
  1524. g_ptr_array_add (sym_def->groups, sym_group);
  1525. return TRUE;
  1526. }
  1527. }
  1528. return FALSE;
  1529. }
  1530. gboolean
  1531. rspamd_config_is_enabled_from_ucl (rspamd_mempool_t *pool,
  1532. const ucl_object_t *obj)
  1533. {
  1534. {
  1535. const ucl_object_t *enabled;
  1536. enabled = ucl_object_lookup(obj, "enabled");
  1537. if (enabled) {
  1538. if (ucl_object_type(enabled) == UCL_BOOLEAN) {
  1539. return ucl_object_toboolean(enabled);
  1540. }
  1541. else if (ucl_object_type(enabled) == UCL_STRING) {
  1542. gchar ret;
  1543. ret = rspamd_config_parse_flag(ucl_object_tostring(enabled), 0);
  1544. if (ret == 0) {
  1545. return FALSE;
  1546. }
  1547. else if (ret == -1) {
  1548. msg_info_pool_check ("wrong value for the `enabled` key");
  1549. return FALSE;
  1550. }
  1551. /* Default return is TRUE here */
  1552. }
  1553. }
  1554. }
  1555. {
  1556. const ucl_object_t *disabled;
  1557. disabled = ucl_object_lookup(obj, "disabled");
  1558. if (disabled) {
  1559. if (ucl_object_type(disabled) == UCL_BOOLEAN) {
  1560. return !ucl_object_toboolean(disabled);
  1561. }
  1562. else if (ucl_object_type(disabled) == UCL_STRING) {
  1563. gchar ret;
  1564. ret = rspamd_config_parse_flag(ucl_object_tostring(disabled), 0);
  1565. if (ret == 0) {
  1566. return TRUE;
  1567. }
  1568. else if (ret == -1) {
  1569. msg_info_pool_check ("wrong value for the `disabled` key");
  1570. return FALSE;
  1571. }
  1572. return FALSE;
  1573. }
  1574. }
  1575. }
  1576. return TRUE;
  1577. }
  1578. gboolean
  1579. rspamd_config_is_module_enabled (struct rspamd_config *cfg,
  1580. const gchar *module_name)
  1581. {
  1582. gboolean is_c = FALSE, enabled;
  1583. const ucl_object_t *conf;
  1584. GList *cur;
  1585. struct rspamd_symbols_group *gr;
  1586. lua_State *L = cfg->lua_state;
  1587. struct module_ctx *cur_ctx;
  1588. guint i;
  1589. PTR_ARRAY_FOREACH (cfg->c_modules, i, cur_ctx) {
  1590. if (g_ascii_strcasecmp (cur_ctx->mod->name, module_name) == 0) {
  1591. is_c = TRUE;
  1592. break;
  1593. }
  1594. }
  1595. if (g_hash_table_lookup (cfg->explicit_modules, module_name) != NULL) {
  1596. /* Always load module */
  1597. rspamd_plugins_table_push_elt (L, "enabled", module_name);
  1598. return TRUE;
  1599. }
  1600. if (is_c) {
  1601. gboolean found = FALSE;
  1602. cur = g_list_first (cfg->filters);
  1603. while (cur) {
  1604. if (strcmp (cur->data, module_name) == 0) {
  1605. found = TRUE;
  1606. break;
  1607. }
  1608. cur = g_list_next (cur);
  1609. }
  1610. if (!found) {
  1611. msg_info_config ("internal module %s is disable in `filters` line",
  1612. module_name);
  1613. rspamd_plugins_table_push_elt (L,
  1614. "disabled_explicitly", module_name);
  1615. return FALSE;
  1616. }
  1617. }
  1618. conf = ucl_object_lookup (cfg->rcl_obj, module_name);
  1619. if (conf == NULL) {
  1620. rspamd_plugins_table_push_elt (L, "disabled_unconfigured", module_name);
  1621. msg_info_config ("%s module %s is enabled but has not been configured",
  1622. is_c ? "internal" : "lua", module_name);
  1623. if (!is_c) {
  1624. msg_info_config ("%s disabling unconfigured lua module", module_name);
  1625. return FALSE;
  1626. }
  1627. }
  1628. else {
  1629. enabled = rspamd_config_is_enabled_from_ucl (cfg->cfg_pool, conf);
  1630. if (!enabled) {
  1631. rspamd_plugins_table_push_elt (L,
  1632. "disabled_explicitly", module_name);
  1633. msg_info_config (
  1634. "%s module %s is disabled in the configuration",
  1635. is_c ? "internal" : "lua", module_name);
  1636. return FALSE;
  1637. }
  1638. }
  1639. /* Now we check symbols group */
  1640. gr = g_hash_table_lookup (cfg->groups, module_name);
  1641. if (gr) {
  1642. if (gr->flags & RSPAMD_SYMBOL_GROUP_DISABLED) {
  1643. rspamd_plugins_table_push_elt (L,
  1644. "disabled_explicitly", module_name);
  1645. msg_info_config ("%s module %s is disabled in the configuration as "
  1646. "its group has been disabled",
  1647. is_c ? "internal" : "lua", module_name);
  1648. return FALSE;
  1649. }
  1650. }
  1651. rspamd_plugins_table_push_elt (L, "enabled", module_name);
  1652. return TRUE;
  1653. }
  1654. static gboolean
  1655. rspamd_config_action_from_ucl (struct rspamd_config *cfg,
  1656. struct rspamd_action *act,
  1657. const ucl_object_t *obj,
  1658. guint priority)
  1659. {
  1660. const ucl_object_t *elt;
  1661. gdouble threshold = NAN;
  1662. guint flags = 0, std_act, obj_type;
  1663. obj_type = ucl_object_type (obj);
  1664. if (obj_type == UCL_OBJECT) {
  1665. obj_type = ucl_object_type (obj);
  1666. elt = ucl_object_lookup_any (obj, "score", "threshold", NULL);
  1667. if (elt) {
  1668. threshold = ucl_object_todouble (elt);
  1669. }
  1670. elt = ucl_object_lookup (obj, "flags");
  1671. if (elt && ucl_object_type (elt) == UCL_ARRAY) {
  1672. const ucl_object_t *cur;
  1673. ucl_object_iter_t it = NULL;
  1674. while ((cur = ucl_object_iterate (elt, &it, true)) != NULL) {
  1675. if (ucl_object_type (cur) == UCL_STRING) {
  1676. const gchar *fl_str = ucl_object_tostring (cur);
  1677. if (g_ascii_strcasecmp (fl_str, "no_threshold") == 0) {
  1678. flags |= RSPAMD_ACTION_NO_THRESHOLD;
  1679. } else if (g_ascii_strcasecmp (fl_str, "threshold_only") == 0) {
  1680. flags |= RSPAMD_ACTION_THRESHOLD_ONLY;
  1681. } else if (g_ascii_strcasecmp (fl_str, "ham") == 0) {
  1682. flags |= RSPAMD_ACTION_HAM;
  1683. } else {
  1684. msg_warn_config ("unknown action flag: %s", fl_str);
  1685. }
  1686. }
  1687. }
  1688. }
  1689. elt = ucl_object_lookup (obj, "milter");
  1690. if (elt) {
  1691. const gchar *milter_action = ucl_object_tostring (elt);
  1692. if (strcmp (milter_action, "discard") == 0) {
  1693. flags |= RSPAMD_ACTION_MILTER;
  1694. act->action_type = METRIC_ACTION_DISCARD;
  1695. }
  1696. else if (strcmp (milter_action, "quarantine") == 0) {
  1697. flags |= RSPAMD_ACTION_MILTER;
  1698. act->action_type = METRIC_ACTION_QUARANTINE;
  1699. }
  1700. else {
  1701. msg_warn_config ("unknown milter action: %s", milter_action);
  1702. }
  1703. }
  1704. }
  1705. else if (obj_type == UCL_FLOAT || obj_type == UCL_INT) {
  1706. threshold = ucl_object_todouble (obj);
  1707. }
  1708. /* TODO: add lua references support */
  1709. if (isnan (threshold) && !(flags & RSPAMD_ACTION_NO_THRESHOLD)) {
  1710. msg_err_config ("action %s has no threshold being set and it is not"
  1711. " a no threshold action", act->name);
  1712. return FALSE;
  1713. }
  1714. act->threshold = threshold;
  1715. act->flags = flags;
  1716. if (!(flags & RSPAMD_ACTION_MILTER)) {
  1717. if (rspamd_action_from_str (act->name, &std_act)) {
  1718. act->action_type = std_act;
  1719. } else {
  1720. act->action_type = METRIC_ACTION_CUSTOM;
  1721. }
  1722. }
  1723. return TRUE;
  1724. }
  1725. gboolean
  1726. rspamd_config_set_action_score (struct rspamd_config *cfg,
  1727. const gchar *action_name,
  1728. const ucl_object_t *obj)
  1729. {
  1730. struct rspamd_action *act;
  1731. enum rspamd_action_type std_act;
  1732. const ucl_object_t *elt;
  1733. guint priority = ucl_object_get_priority (obj), obj_type;
  1734. g_assert (cfg != NULL);
  1735. g_assert (action_name != NULL);
  1736. obj_type = ucl_object_type (obj);
  1737. if (obj_type == UCL_OBJECT) {
  1738. elt = ucl_object_lookup (obj, "priority");
  1739. if (elt) {
  1740. priority = ucl_object_toint (elt);
  1741. }
  1742. }
  1743. /* Here are dragons:
  1744. * We have `canonical` name for actions, such as `soft reject` and
  1745. * configuration names for actions (used to be more convenient), such
  1746. * as `soft_reject`. Unfortunately, we must have heuristic for this
  1747. * variance of names.
  1748. */
  1749. if (rspamd_action_from_str (action_name, (gint *)&std_act)) {
  1750. action_name = rspamd_action_to_str (std_act);
  1751. }
  1752. HASH_FIND_STR (cfg->actions, action_name, act);
  1753. if (act) {
  1754. /* Existing element */
  1755. if (act->priority <= priority) {
  1756. /* We can replace data */
  1757. msg_info_config ("action %s has been already registered with "
  1758. "priority %ud, override it with new priority: %ud, "
  1759. "old score: %.2f",
  1760. action_name,
  1761. act->priority,
  1762. priority,
  1763. act->threshold);
  1764. if (rspamd_config_action_from_ucl (cfg, act, obj, priority)) {
  1765. rspamd_actions_sort (cfg);
  1766. }
  1767. else {
  1768. return FALSE;
  1769. }
  1770. }
  1771. else {
  1772. msg_info_config ("action %s has been already registered with "
  1773. "priority %ud, do not override (new priority: %ud)",
  1774. action_name,
  1775. act->priority,
  1776. priority);
  1777. }
  1778. }
  1779. else {
  1780. /* Add new element */
  1781. act = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*act));
  1782. act->name = rspamd_mempool_strdup (cfg->cfg_pool, action_name);
  1783. if (rspamd_config_action_from_ucl (cfg, act, obj, priority)) {
  1784. HASH_ADD_KEYPTR (hh, cfg->actions,
  1785. act->name, strlen (act->name), act);
  1786. rspamd_actions_sort (cfg);
  1787. }
  1788. else {
  1789. return FALSE;
  1790. }
  1791. }
  1792. return TRUE;
  1793. }
  1794. gboolean
  1795. rspamd_config_maybe_disable_action (struct rspamd_config *cfg,
  1796. const gchar *action_name,
  1797. guint priority)
  1798. {
  1799. struct rspamd_action *act;
  1800. HASH_FIND_STR (cfg->actions, action_name, act);
  1801. if (act) {
  1802. if (priority >= act->priority) {
  1803. msg_info_config ("disable action %s; old priority: %ud, new priority: %ud",
  1804. action_name,
  1805. act->priority,
  1806. priority);
  1807. act->threshold = NAN;
  1808. act->priority = priority;
  1809. act->flags |= RSPAMD_ACTION_NO_THRESHOLD;
  1810. return TRUE;
  1811. }
  1812. else {
  1813. msg_info_config ("action %s has been already registered with "
  1814. "priority %ud, cannot disable it with new priority: %ud",
  1815. action_name,
  1816. act->priority,
  1817. priority);
  1818. }
  1819. }
  1820. return FALSE;
  1821. }
  1822. struct rspamd_action *
  1823. rspamd_config_get_action (struct rspamd_config *cfg, const gchar *name)
  1824. {
  1825. struct rspamd_action *res = NULL;
  1826. HASH_FIND_STR (cfg->actions, name, res);
  1827. return res;
  1828. }
  1829. struct rspamd_action *
  1830. rspamd_config_get_action_by_type (struct rspamd_config *cfg,
  1831. enum rspamd_action_type type)
  1832. {
  1833. struct rspamd_action *cur, *tmp;
  1834. HASH_ITER (hh, cfg->actions, cur, tmp) {
  1835. if (cur->action_type == type) {
  1836. return cur;
  1837. }
  1838. }
  1839. return NULL;
  1840. }
  1841. gboolean
  1842. rspamd_config_radix_from_ucl (struct rspamd_config *cfg, const ucl_object_t *obj, const gchar *description,
  1843. struct rspamd_radix_map_helper **target, GError **err,
  1844. struct rspamd_worker *worker, const gchar *map_name)
  1845. {
  1846. ucl_type_t type;
  1847. ucl_object_iter_t it = NULL;
  1848. const ucl_object_t *cur, *cur_elt;
  1849. const gchar *str;
  1850. /* Cleanup */
  1851. *target = NULL;
  1852. LL_FOREACH (obj, cur_elt) {
  1853. type = ucl_object_type (cur_elt);
  1854. switch (type) {
  1855. case UCL_STRING:
  1856. /* Either map or a list of IPs */
  1857. str = ucl_object_tostring (cur_elt);
  1858. if (rspamd_map_is_map (str)) {
  1859. if (rspamd_map_add_from_ucl (cfg, cur_elt,
  1860. description,
  1861. rspamd_radix_read,
  1862. rspamd_radix_fin,
  1863. rspamd_radix_dtor,
  1864. (void **)target,
  1865. worker, RSPAMD_MAP_DEFAULT) == NULL) {
  1866. g_set_error (err,
  1867. g_quark_from_static_string ("rspamd-config"),
  1868. EINVAL, "bad map definition %s for %s", str,
  1869. ucl_object_key (obj));
  1870. return FALSE;
  1871. }
  1872. return TRUE;
  1873. }
  1874. else {
  1875. /* Just a list */
  1876. if (!*target) {
  1877. *target = rspamd_map_helper_new_radix (
  1878. rspamd_map_add_fake (cfg, description, map_name));
  1879. }
  1880. rspamd_map_helper_insert_radix_resolve (*target, str, "");
  1881. }
  1882. break;
  1883. case UCL_OBJECT:
  1884. /* Should be a map description */
  1885. if (rspamd_map_add_from_ucl (cfg, cur_elt,
  1886. description,
  1887. rspamd_radix_read,
  1888. rspamd_radix_fin,
  1889. rspamd_radix_dtor,
  1890. (void **)target,
  1891. worker, RSPAMD_MAP_DEFAULT) == NULL) {
  1892. g_set_error (err,
  1893. g_quark_from_static_string ("rspamd-config"),
  1894. EINVAL, "bad map object for %s", ucl_object_key (obj));
  1895. return FALSE;
  1896. }
  1897. return TRUE;
  1898. break;
  1899. case UCL_ARRAY:
  1900. /* List of IP addresses */
  1901. it = ucl_object_iterate_new (cur_elt);
  1902. while ((cur = ucl_object_iterate_safe (it, true)) != NULL) {
  1903. str = ucl_object_tostring (cur);
  1904. if (!*target) {
  1905. *target = rspamd_map_helper_new_radix (
  1906. rspamd_map_add_fake (cfg, description, map_name));
  1907. }
  1908. rspamd_map_helper_insert_radix_resolve (*target, str, "");
  1909. }
  1910. ucl_object_iterate_free (it);
  1911. break;
  1912. default:
  1913. g_set_error (err, g_quark_from_static_string ("rspamd-config"),
  1914. EINVAL, "bad map type %s for %s",
  1915. ucl_object_type_to_string (type),
  1916. ucl_object_key (obj));
  1917. return FALSE;
  1918. }
  1919. }
  1920. /* Destroy on cfg cleanup */
  1921. rspamd_mempool_add_destructor (cfg->cfg_pool,
  1922. (rspamd_mempool_destruct_t)rspamd_map_helper_destroy_radix,
  1923. *target);
  1924. return TRUE;
  1925. }
  1926. gboolean
  1927. rspamd_action_from_str (const gchar *data, gint *result)
  1928. {
  1929. guint64 h;
  1930. h = rspamd_cryptobox_fast_hash_specific (RSPAMD_CRYPTOBOX_XXHASH64,
  1931. data, strlen (data), 0xdeadbabe);
  1932. switch (h) {
  1933. case 0x9917BFDB46332B8CULL: /* reject */
  1934. *result = METRIC_ACTION_REJECT;
  1935. break;
  1936. case 0x7130EE37D07B3715ULL: /* greylist */
  1937. *result = METRIC_ACTION_GREYLIST;
  1938. break;
  1939. case 0xCA6087E05480C60CULL: /* add_header */
  1940. case 0x87A3D27783B16241ULL: /* add header */
  1941. *result = METRIC_ACTION_ADD_HEADER;
  1942. break;
  1943. case 0x4963374ED8B90449ULL: /* rewrite_subject */
  1944. case 0x5C9FC4679C025948ULL: /* rewrite subject */
  1945. *result = METRIC_ACTION_REWRITE_SUBJECT;
  1946. break;
  1947. case 0xFC7D6502EE71FDD9ULL: /* soft reject */
  1948. case 0x73576567C262A82DULL: /* soft_reject */
  1949. *result = METRIC_ACTION_SOFT_REJECT;
  1950. break;
  1951. case 0x207091B927D1EC0DULL: /* no action */
  1952. case 0xB7D92D002CD46325ULL: /* no_action */
  1953. case 0x167C0DF4BAA9BCECULL: /* accept */
  1954. *result = METRIC_ACTION_NOACTION;
  1955. break;
  1956. case 0x4E9666ECCD3FC314ULL: /* quarantine */
  1957. *result = METRIC_ACTION_QUARANTINE;
  1958. break;
  1959. case 0x93B346242F7F69B3ULL: /* discard */
  1960. *result = METRIC_ACTION_DISCARD;
  1961. break;
  1962. default:
  1963. return FALSE;
  1964. }
  1965. return TRUE;
  1966. }
  1967. const gchar *
  1968. rspamd_action_to_str (enum rspamd_action_type action)
  1969. {
  1970. switch (action) {
  1971. case METRIC_ACTION_REJECT:
  1972. return "reject";
  1973. case METRIC_ACTION_SOFT_REJECT:
  1974. return "soft reject";
  1975. case METRIC_ACTION_REWRITE_SUBJECT:
  1976. return "rewrite subject";
  1977. case METRIC_ACTION_ADD_HEADER:
  1978. return "add header";
  1979. case METRIC_ACTION_GREYLIST:
  1980. return "greylist";
  1981. case METRIC_ACTION_NOACTION:
  1982. return "no action";
  1983. case METRIC_ACTION_MAX:
  1984. return "invalid max action";
  1985. case METRIC_ACTION_CUSTOM:
  1986. return "custom";
  1987. case METRIC_ACTION_DISCARD:
  1988. return "discard";
  1989. case METRIC_ACTION_QUARANTINE:
  1990. return "quarantine";
  1991. }
  1992. return "unknown action";
  1993. }
  1994. const gchar *
  1995. rspamd_action_to_str_alt (enum rspamd_action_type action)
  1996. {
  1997. switch (action) {
  1998. case METRIC_ACTION_REJECT:
  1999. return "reject";
  2000. case METRIC_ACTION_SOFT_REJECT:
  2001. return "soft_reject";
  2002. case METRIC_ACTION_REWRITE_SUBJECT:
  2003. return "rewrite_subject";
  2004. case METRIC_ACTION_ADD_HEADER:
  2005. return "add_header";
  2006. case METRIC_ACTION_GREYLIST:
  2007. return "greylist";
  2008. case METRIC_ACTION_NOACTION:
  2009. return "no action";
  2010. case METRIC_ACTION_MAX:
  2011. return "invalid max action";
  2012. case METRIC_ACTION_CUSTOM:
  2013. return "custom";
  2014. case METRIC_ACTION_DISCARD:
  2015. return "discard";
  2016. case METRIC_ACTION_QUARANTINE:
  2017. return "quarantine";
  2018. }
  2019. return "unknown action";
  2020. }
  2021. static int
  2022. rspamd_actions_cmp (const struct rspamd_action *a1, const struct rspamd_action *a2)
  2023. {
  2024. if (!isnan (a1->threshold) && !isnan (a2->threshold)) {
  2025. if (a1->threshold < a2->threshold) {
  2026. return -1;
  2027. }
  2028. else if (a1->threshold > a2->threshold) {
  2029. return 1;
  2030. }
  2031. return 0;
  2032. }
  2033. if (isnan (a1->threshold) && isnan (a2->threshold)) {
  2034. return 0;
  2035. }
  2036. else if (isnan (a1->threshold)) {
  2037. return 1;
  2038. }
  2039. else {
  2040. return -1;
  2041. }
  2042. }
  2043. void
  2044. rspamd_actions_sort (struct rspamd_config *cfg)
  2045. {
  2046. HASH_SORT (cfg->actions, rspamd_actions_cmp);
  2047. }
  2048. static void
  2049. rspamd_config_settings_elt_dtor (struct rspamd_config_settings_elt *e)
  2050. {
  2051. if (e->symbols_enabled) {
  2052. ucl_object_unref (e->symbols_enabled);
  2053. }
  2054. if (e->symbols_disabled) {
  2055. ucl_object_unref (e->symbols_disabled);
  2056. }
  2057. }
  2058. guint32
  2059. rspamd_config_name_to_id (const gchar *name, gsize namelen)
  2060. {
  2061. guint64 h;
  2062. h = rspamd_cryptobox_fast_hash_specific (RSPAMD_CRYPTOBOX_XXHASH64,
  2063. name, namelen, 0x0);
  2064. /* Take the lower part of hash as LE number */
  2065. return ((guint32)GUINT64_TO_LE (h));
  2066. }
  2067. struct rspamd_config_settings_elt *
  2068. rspamd_config_find_settings_id_ref (struct rspamd_config *cfg,
  2069. guint32 id)
  2070. {
  2071. struct rspamd_config_settings_elt *cur;
  2072. DL_FOREACH (cfg->setting_ids, cur) {
  2073. if (cur->id == id) {
  2074. REF_RETAIN (cur);
  2075. return cur;
  2076. }
  2077. }
  2078. return NULL;
  2079. }
  2080. struct rspamd_config_settings_elt *rspamd_config_find_settings_name_ref (
  2081. struct rspamd_config *cfg,
  2082. const gchar *name, gsize namelen)
  2083. {
  2084. guint32 id;
  2085. id = rspamd_config_name_to_id (name, namelen);
  2086. return rspamd_config_find_settings_id_ref (cfg, id);
  2087. }
  2088. void
  2089. rspamd_config_register_settings_id (struct rspamd_config *cfg,
  2090. const gchar *name,
  2091. ucl_object_t *symbols_enabled,
  2092. ucl_object_t *symbols_disabled,
  2093. enum rspamd_config_settings_policy policy)
  2094. {
  2095. struct rspamd_config_settings_elt *elt;
  2096. guint32 id;
  2097. id = rspamd_config_name_to_id (name, strlen (name));
  2098. elt = rspamd_config_find_settings_id_ref (cfg, id);
  2099. if (elt) {
  2100. /* Need to replace */
  2101. struct rspamd_config_settings_elt *nelt;
  2102. DL_DELETE (cfg->setting_ids, elt);
  2103. nelt = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*nelt));
  2104. nelt->id = id;
  2105. nelt->name = rspamd_mempool_strdup (cfg->cfg_pool, name);
  2106. if (symbols_enabled) {
  2107. nelt->symbols_enabled = ucl_object_ref (symbols_enabled);
  2108. }
  2109. if (symbols_disabled) {
  2110. nelt->symbols_disabled = ucl_object_ref (symbols_disabled);
  2111. }
  2112. nelt->policy = policy;
  2113. REF_INIT_RETAIN (nelt, rspamd_config_settings_elt_dtor);
  2114. msg_warn_config ("replace settings id %ud (%s)", id, name);
  2115. rspamd_symcache_process_settings_elt (cfg->cache, elt);
  2116. DL_APPEND (cfg->setting_ids, nelt);
  2117. /*
  2118. * Need to unref old element twice as there are two reference holders:
  2119. * 1. Config structure as we call REF_INIT_RETAIN
  2120. * 2. rspamd_config_find_settings_id_ref also increases refcount
  2121. */
  2122. REF_RELEASE (elt);
  2123. REF_RELEASE (elt);
  2124. }
  2125. else {
  2126. elt = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*elt));
  2127. elt->id = id;
  2128. elt->name = rspamd_mempool_strdup (cfg->cfg_pool, name);
  2129. if (symbols_enabled) {
  2130. elt->symbols_enabled = ucl_object_ref (symbols_enabled);
  2131. }
  2132. if (symbols_disabled) {
  2133. elt->symbols_disabled = ucl_object_ref (symbols_disabled);
  2134. }
  2135. elt->policy = policy;
  2136. msg_info_config ("register new settings id %ud (%s)", id, name);
  2137. REF_INIT_RETAIN (elt, rspamd_config_settings_elt_dtor);
  2138. rspamd_symcache_process_settings_elt (cfg->cache, elt);
  2139. DL_APPEND (cfg->setting_ids, elt);
  2140. }
  2141. }
  2142. int
  2143. rspamd_config_ev_backend_get (struct rspamd_config *cfg)
  2144. {
  2145. #define AUTO_BACKEND (ev_supported_backends () & ~EVBACKEND_IOURING)
  2146. if (cfg == NULL || cfg->events_backend == NULL) {
  2147. return AUTO_BACKEND;
  2148. }
  2149. if (strcmp (cfg->events_backend, "auto") == 0) {
  2150. return AUTO_BACKEND;
  2151. }
  2152. else if (strcmp (cfg->events_backend, "epoll") == 0) {
  2153. if (ev_supported_backends () & EVBACKEND_EPOLL) {
  2154. return EVBACKEND_EPOLL;
  2155. }
  2156. else {
  2157. msg_warn_config ("unsupported events_backend: %s; defaulting to auto",
  2158. cfg->events_backend);
  2159. return AUTO_BACKEND;
  2160. }
  2161. }
  2162. else if (strcmp (cfg->events_backend, "iouring") == 0) {
  2163. if (ev_supported_backends () & EVBACKEND_IOURING) {
  2164. return EVBACKEND_IOURING;
  2165. }
  2166. else {
  2167. msg_warn_config ("unsupported events_backend: %s; defaulting to auto",
  2168. cfg->events_backend);
  2169. return AUTO_BACKEND;
  2170. }
  2171. }
  2172. else if (strcmp (cfg->events_backend, "kqueue") == 0) {
  2173. if (ev_supported_backends () & EVBACKEND_KQUEUE) {
  2174. return EVBACKEND_KQUEUE;
  2175. }
  2176. else {
  2177. msg_warn_config ("unsupported events_backend: %s; defaulting to auto",
  2178. cfg->events_backend);
  2179. return AUTO_BACKEND;
  2180. }
  2181. }
  2182. else if (strcmp (cfg->events_backend, "poll") == 0) {
  2183. return EVBACKEND_POLL;
  2184. }
  2185. else if (strcmp (cfg->events_backend, "select") == 0) {
  2186. return EVBACKEND_SELECT;
  2187. }
  2188. else {
  2189. msg_warn_config ("unknown events_backend: %s; defaulting to auto",
  2190. cfg->events_backend);
  2191. }
  2192. return AUTO_BACKEND;
  2193. }
  2194. const gchar *
  2195. rspamd_config_ev_backend_to_string (int ev_backend, gboolean *effective)
  2196. {
  2197. #define SET_EFFECTIVE(b) do { if ((effective) != NULL) *(effective) = b; } while(0)
  2198. if ((ev_backend & EVBACKEND_ALL) == EVBACKEND_ALL) {
  2199. SET_EFFECTIVE (TRUE);
  2200. return "auto";
  2201. }
  2202. if (ev_backend & EVBACKEND_IOURING) {
  2203. SET_EFFECTIVE (TRUE);
  2204. return "epoll+io_uring";
  2205. }
  2206. if (ev_backend & EVBACKEND_LINUXAIO) {
  2207. SET_EFFECTIVE (TRUE);
  2208. return "epoll+aio";
  2209. }if (ev_backend & EVBACKEND_IOURING) {
  2210. SET_EFFECTIVE (TRUE);
  2211. return "epoll+io_uring";
  2212. }
  2213. if (ev_backend & EVBACKEND_LINUXAIO) {
  2214. SET_EFFECTIVE (TRUE);
  2215. return "epoll+aio";
  2216. }
  2217. if (ev_backend & EVBACKEND_EPOLL) {
  2218. SET_EFFECTIVE (TRUE);
  2219. return "epoll";
  2220. }
  2221. if (ev_backend & EVBACKEND_KQUEUE) {
  2222. SET_EFFECTIVE (TRUE);
  2223. return "kqueue";
  2224. }
  2225. if (ev_backend & EVBACKEND_POLL) {
  2226. SET_EFFECTIVE (FALSE);
  2227. return "poll";
  2228. }
  2229. if (ev_backend & EVBACKEND_SELECT) {
  2230. SET_EFFECTIVE (FALSE);
  2231. return "select";
  2232. }
  2233. SET_EFFECTIVE (FALSE);
  2234. return "unknown";
  2235. #undef SET_EFFECTIVE
  2236. }
  2237. struct rspamd_external_libs_ctx *
  2238. rspamd_init_libs (void)
  2239. {
  2240. struct rlimit rlim;
  2241. struct rspamd_external_libs_ctx *ctx;
  2242. struct ottery_config *ottery_cfg;
  2243. ctx = g_malloc0 (sizeof (*ctx));
  2244. ctx->crypto_ctx = rspamd_cryptobox_init ();
  2245. ottery_cfg = g_malloc0 (ottery_get_sizeof_config ());
  2246. ottery_config_init (ottery_cfg);
  2247. ctx->ottery_cfg = ottery_cfg;
  2248. rspamd_openssl_maybe_init ();
  2249. /* Check if we have rdrand */
  2250. if ((ctx->crypto_ctx->cpu_config & CPUID_RDRAND) == 0) {
  2251. ottery_config_disable_entropy_sources (ottery_cfg,
  2252. OTTERY_ENTROPY_SRC_RDRAND);
  2253. #if OPENSSL_VERSION_NUMBER >= 0x1000104fL && OPENSSL_VERSION_NUMBER < 0x30000000L && !defined(LIBRESSL_VERSION_NUMBER)
  2254. RAND_set_rand_engine (NULL);
  2255. #endif
  2256. }
  2257. /* Configure utf8 library */
  2258. guint utf8_flags = 0;
  2259. if ((ctx->crypto_ctx->cpu_config & CPUID_SSE41)) {
  2260. utf8_flags |= RSPAMD_FAST_UTF8_FLAG_SSE41;
  2261. }
  2262. if ((ctx->crypto_ctx->cpu_config & CPUID_AVX2)) {
  2263. utf8_flags |= RSPAMD_FAST_UTF8_FLAG_AVX2;
  2264. }
  2265. rspamd_fast_utf8_library_init (utf8_flags);
  2266. g_assert (ottery_init (ottery_cfg) == 0);
  2267. #ifdef HAVE_LOCALE_H
  2268. if (getenv ("LANG") == NULL) {
  2269. setlocale (LC_ALL, "C");
  2270. setlocale (LC_CTYPE, "C");
  2271. setlocale (LC_MESSAGES, "C");
  2272. setlocale (LC_TIME, "C");
  2273. }
  2274. else {
  2275. /* Just set the default locale */
  2276. setlocale (LC_ALL, "");
  2277. /* But for some issues we still want C locale */
  2278. setlocale (LC_NUMERIC, "C");
  2279. }
  2280. #endif
  2281. ctx->ssl_ctx = rspamd_init_ssl_ctx ();
  2282. ctx->ssl_ctx_noverify = rspamd_init_ssl_ctx_noverify ();
  2283. rspamd_random_seed_fast ();
  2284. /* Set stack size for pcre */
  2285. getrlimit (RLIMIT_STACK, &rlim);
  2286. rlim.rlim_cur = 100 * 1024 * 1024;
  2287. rlim.rlim_max = rlim.rlim_cur;
  2288. setrlimit (RLIMIT_STACK, &rlim);
  2289. ctx->local_addrs = rspamd_inet_library_init ();
  2290. REF_INIT_RETAIN (ctx, rspamd_deinit_libs);
  2291. return ctx;
  2292. }
  2293. static struct zstd_dictionary *
  2294. rspamd_open_zstd_dictionary (const char *path)
  2295. {
  2296. struct zstd_dictionary *dict;
  2297. dict = g_malloc0 (sizeof (*dict));
  2298. dict->dict = rspamd_file_xmap (path, PROT_READ, &dict->size, TRUE);
  2299. if (dict->dict == NULL) {
  2300. g_free (dict);
  2301. return NULL;
  2302. }
  2303. dict->id = -1;
  2304. if (dict->id == 0) {
  2305. g_free (dict);
  2306. return NULL;
  2307. }
  2308. return dict;
  2309. }
  2310. static void
  2311. rspamd_free_zstd_dictionary (struct zstd_dictionary *dict)
  2312. {
  2313. if (dict) {
  2314. munmap (dict->dict, dict->size);
  2315. g_free (dict);
  2316. }
  2317. }
  2318. #ifdef HAVE_OPENBLAS_SET_NUM_THREADS
  2319. extern void openblas_set_num_threads(int num_threads);
  2320. #endif
  2321. #ifdef HAVE_BLI_THREAD_SET_NUM_THREADS
  2322. extern void bli_thread_set_num_threads(int num_threads);
  2323. #endif
  2324. gboolean
  2325. rspamd_config_libs (struct rspamd_external_libs_ctx *ctx,
  2326. struct rspamd_config *cfg)
  2327. {
  2328. size_t r;
  2329. gboolean ret = TRUE;
  2330. g_assert (cfg != NULL);
  2331. if (ctx != NULL) {
  2332. if (cfg->local_addrs) {
  2333. rspamd_config_radix_from_ucl (cfg, cfg->local_addrs,
  2334. "Local addresses",
  2335. (struct rspamd_radix_map_helper **) ctx->local_addrs,
  2336. NULL,
  2337. NULL, "local addresses");
  2338. }
  2339. rspamd_free_zstd_dictionary (ctx->in_dict);
  2340. rspamd_free_zstd_dictionary (ctx->out_dict);
  2341. if (ctx->out_zstream) {
  2342. ZSTD_freeCStream (ctx->out_zstream);
  2343. ctx->out_zstream = NULL;
  2344. }
  2345. if (ctx->in_zstream) {
  2346. ZSTD_freeDStream (ctx->in_zstream);
  2347. ctx->in_zstream = NULL;
  2348. }
  2349. if (cfg->zstd_input_dictionary) {
  2350. ctx->in_dict = rspamd_open_zstd_dictionary (
  2351. cfg->zstd_input_dictionary);
  2352. if (ctx->in_dict == NULL) {
  2353. msg_err_config ("cannot open zstd dictionary in %s",
  2354. cfg->zstd_input_dictionary);
  2355. }
  2356. }
  2357. if (cfg->zstd_output_dictionary) {
  2358. ctx->out_dict = rspamd_open_zstd_dictionary (
  2359. cfg->zstd_output_dictionary);
  2360. if (ctx->out_dict == NULL) {
  2361. msg_err_config ("cannot open zstd dictionary in %s",
  2362. cfg->zstd_output_dictionary);
  2363. }
  2364. }
  2365. if (cfg->fips_mode) {
  2366. #ifdef HAVE_FIPS_MODE
  2367. int mode = FIPS_mode ();
  2368. unsigned long err = (unsigned long)-1;
  2369. /* Toggle FIPS mode */
  2370. if (mode == 0) {
  2371. #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
  2372. if (EVP_set_default_properties (NULL, "fips=yes") != 1) {
  2373. #else
  2374. if (FIPS_mode_set (1) != 1) {
  2375. #endif
  2376. err = ERR_get_error ();
  2377. }
  2378. }
  2379. else {
  2380. msg_info_config ("OpenSSL FIPS mode is already enabled");
  2381. }
  2382. if (err != (unsigned long)-1) {
  2383. #if defined(OPENSSL_VERSION_MAJOR) && (OPENSSL_VERSION_MAJOR >= 3)
  2384. msg_err_config ("EVP_set_default_properties failed: %s",
  2385. #else
  2386. msg_err_config ("FIPS_mode_set failed: %s",
  2387. #endif
  2388. ERR_error_string (err, NULL));
  2389. ret = FALSE;
  2390. }
  2391. else {
  2392. msg_info_config ("OpenSSL FIPS mode is enabled");
  2393. }
  2394. #else
  2395. msg_warn_config ("SSL FIPS mode is enabled but not supported by OpenSSL library!");
  2396. #endif
  2397. }
  2398. rspamd_ssl_ctx_config (cfg, ctx->ssl_ctx);
  2399. rspamd_ssl_ctx_config (cfg, ctx->ssl_ctx_noverify);
  2400. /* Init decompression */
  2401. ctx->in_zstream = ZSTD_createDStream ();
  2402. r = ZSTD_initDStream (ctx->in_zstream);
  2403. if (ZSTD_isError (r)) {
  2404. msg_err ("cannot init decompression stream: %s",
  2405. ZSTD_getErrorName (r));
  2406. ZSTD_freeDStream (ctx->in_zstream);
  2407. ctx->in_zstream = NULL;
  2408. }
  2409. /* Init compression */
  2410. ctx->out_zstream = ZSTD_createCStream ();
  2411. r = ZSTD_initCStream (ctx->out_zstream, 1);
  2412. if (ZSTD_isError (r)) {
  2413. msg_err ("cannot init compression stream: %s",
  2414. ZSTD_getErrorName (r));
  2415. ZSTD_freeCStream (ctx->out_zstream);
  2416. ctx->out_zstream = NULL;
  2417. }
  2418. #ifdef HAVE_OPENBLAS_SET_NUM_THREADS
  2419. openblas_set_num_threads (cfg->max_blas_threads);
  2420. #endif
  2421. #ifdef HAVE_BLI_THREAD_SET_NUM_THREADS
  2422. bli_thread_set_num_threads (cfg->max_blas_threads);
  2423. #endif
  2424. }
  2425. return ret;
  2426. }
  2427. gboolean
  2428. rspamd_libs_reset_decompression (struct rspamd_external_libs_ctx *ctx)
  2429. {
  2430. gsize r;
  2431. if (ctx->in_zstream == NULL) {
  2432. return FALSE;
  2433. }
  2434. else {
  2435. r = ZSTD_DCtx_reset (ctx->in_zstream, ZSTD_reset_session_only);
  2436. if (ZSTD_isError (r)) {
  2437. msg_err ("cannot init decompression stream: %s",
  2438. ZSTD_getErrorName (r));
  2439. ZSTD_freeDStream (ctx->in_zstream);
  2440. ctx->in_zstream = NULL;
  2441. return FALSE;
  2442. }
  2443. }
  2444. return TRUE;
  2445. }
  2446. gboolean
  2447. rspamd_libs_reset_compression (struct rspamd_external_libs_ctx *ctx)
  2448. {
  2449. gsize r;
  2450. if (ctx->out_zstream == NULL) {
  2451. return FALSE;
  2452. }
  2453. else {
  2454. /* Dictionary will be reused automatically if specified */
  2455. r = ZSTD_CCtx_reset (ctx->out_zstream, ZSTD_reset_session_only);
  2456. if (!ZSTD_isError (r)) {
  2457. r = ZSTD_CCtx_setPledgedSrcSize (ctx->out_zstream, ZSTD_CONTENTSIZE_UNKNOWN);
  2458. }
  2459. if (ZSTD_isError (r)) {
  2460. msg_err ("cannot init compression stream: %s",
  2461. ZSTD_getErrorName (r));
  2462. ZSTD_freeCStream (ctx->out_zstream);
  2463. ctx->out_zstream = NULL;
  2464. return FALSE;
  2465. }
  2466. }
  2467. return TRUE;
  2468. }
  2469. void
  2470. rspamd_deinit_libs (struct rspamd_external_libs_ctx *ctx)
  2471. {
  2472. if (ctx != NULL) {
  2473. g_free (ctx->ottery_cfg);
  2474. #ifdef HAVE_OPENSSL
  2475. EVP_cleanup ();
  2476. ERR_free_strings ();
  2477. rspamd_ssl_ctx_free (ctx->ssl_ctx);
  2478. rspamd_ssl_ctx_free (ctx->ssl_ctx_noverify);
  2479. #endif
  2480. rspamd_inet_library_destroy ();
  2481. rspamd_free_zstd_dictionary (ctx->in_dict);
  2482. rspamd_free_zstd_dictionary (ctx->out_dict);
  2483. if (ctx->out_zstream) {
  2484. ZSTD_freeCStream (ctx->out_zstream);
  2485. }
  2486. if (ctx->in_zstream) {
  2487. ZSTD_freeDStream (ctx->in_zstream);
  2488. }
  2489. rspamd_cryptobox_deinit (ctx->crypto_ctx);
  2490. g_free (ctx);
  2491. }
  2492. }
  2493. gboolean
  2494. rspamd_ip_is_local_cfg (struct rspamd_config *cfg,
  2495. const rspamd_inet_addr_t *addr)
  2496. {
  2497. struct rspamd_radix_map_helper *local_addrs = NULL;
  2498. if (cfg && cfg->libs_ctx) {
  2499. local_addrs = *(struct rspamd_radix_map_helper**)cfg->libs_ctx->local_addrs;
  2500. }
  2501. if (rspamd_inet_address_is_local (addr)) {
  2502. return TRUE;
  2503. }
  2504. if (local_addrs) {
  2505. if (rspamd_match_radix_map_addr (local_addrs, addr) != NULL) {
  2506. return TRUE;
  2507. }
  2508. }
  2509. return FALSE;
  2510. }