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

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