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

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