You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rspamd.c 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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 "rspamd.h"
  18. #include "libserver/maps/map.h"
  19. #include "lua/lua_common.h"
  20. #include "libserver/worker_util.h"
  21. #include "libserver/rspamd_control.h"
  22. #include "ottery.h"
  23. #include "cryptobox.h"
  24. #include "utlist.h"
  25. #include "unix-std.h"
  26. /* pwd and grp */
  27. #ifdef HAVE_PWD_H
  28. #include <pwd.h>
  29. #endif
  30. #ifdef HAVE_GRP_H
  31. #include <grp.h>
  32. #endif
  33. #ifdef HAVE_NFTW
  34. #include <ftw.h>
  35. #endif
  36. #include <signal.h>
  37. #ifdef HAVE_SYS_RESOURCE_H
  38. #include <sys/resource.h>
  39. #endif
  40. #ifdef HAVE_LIBUTIL_H
  41. #include <libutil.h>
  42. #endif
  43. #ifdef HAVE_OPENSSL
  44. #include <openssl/err.h>
  45. #include <openssl/evp.h>
  46. #include <math.h>
  47. #endif
  48. #include "sqlite3.h"
  49. #include "contrib/libev/ev.h"
  50. /* 2 seconds to fork new process in place of dead one */
  51. #define SOFT_FORK_TIME 2
  52. /* 10 seconds after getting termination signal to terminate all workers with SIGKILL */
  53. #define TERMINATION_INTERVAL (0.2)
  54. static gboolean load_rspamd_config (struct rspamd_main *rspamd_main,
  55. struct rspamd_config *cfg,
  56. gboolean init_modules,
  57. enum rspamd_post_load_options opts,
  58. gboolean reload);
  59. static void rspamd_cld_handler (EV_P_ ev_child *w,
  60. struct rspamd_main *rspamd_main,
  61. struct rspamd_worker *wrk);
  62. /* Control socket */
  63. static gint control_fd;
  64. static ev_io control_ev;
  65. static struct rspamd_stat old_stat;
  66. static ev_timer stat_ev;
  67. static gboolean valgrind_mode = FALSE;
  68. /* Cmdline options */
  69. static gboolean no_fork = FALSE;
  70. static gboolean show_version = FALSE;
  71. static gchar **cfg_names = NULL;
  72. static gchar *rspamd_user = NULL;
  73. static gchar *rspamd_group = NULL;
  74. static gchar *rspamd_pidfile = NULL;
  75. static gboolean is_debug = FALSE;
  76. static gboolean is_insecure = FALSE;
  77. static GHashTable *ucl_vars = NULL;
  78. static gchar **lua_env = NULL;
  79. static gboolean skip_template = FALSE;
  80. static gint term_attempts = 0;
  81. /* List of active listen sockets indexed by worker type */
  82. static GHashTable *listen_sockets = NULL;
  83. /* Defined in modules.c */
  84. extern module_t *modules[];
  85. extern worker_t *workers[];
  86. /* Command line options */
  87. static gboolean rspamd_parse_var (const gchar *option_name,
  88. const gchar *value, gpointer data,
  89. GError **error);
  90. static GOptionEntry entries[] =
  91. {
  92. { "no-fork", 'f', 0, G_OPTION_ARG_NONE, &no_fork,
  93. "Do not daemonize main process", NULL },
  94. { "config", 'c', 0, G_OPTION_ARG_FILENAME_ARRAY, &cfg_names,
  95. "Specify config file(s)", NULL },
  96. { "user", 'u', 0, G_OPTION_ARG_STRING, &rspamd_user,
  97. "User to run rspamd as", NULL },
  98. { "group", 'g', 0, G_OPTION_ARG_STRING, &rspamd_group,
  99. "Group to run rspamd as", NULL },
  100. { "pid", 'p', 0, G_OPTION_ARG_STRING, &rspamd_pidfile, "Path to pidfile",
  101. NULL },
  102. { "debug", 'd', 0, G_OPTION_ARG_NONE, &is_debug, "Force debug output",
  103. NULL },
  104. { "insecure", 'i', 0, G_OPTION_ARG_NONE, &is_insecure,
  105. "Ignore running workers as privileged users (insecure)", NULL },
  106. { "version", 'v', 0, G_OPTION_ARG_NONE, &show_version,
  107. "Show version and exit", NULL },
  108. {"var", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer)&rspamd_parse_var,
  109. "Redefine/define environment variable", NULL},
  110. {"skip-template", 'T', 0, G_OPTION_ARG_NONE, &skip_template,
  111. "Do not apply Jinja templates", NULL},
  112. {"lua-env", '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &lua_env,
  113. "Load lua environment from the specified files", NULL},
  114. { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
  115. };
  116. static gboolean
  117. rspamd_parse_var (const gchar *option_name,
  118. const gchar *value, gpointer data,
  119. GError **error)
  120. {
  121. gchar *k, *v, *t;
  122. t = strchr (value, '=');
  123. if (t != NULL) {
  124. k = g_strdup (value);
  125. t = k + (t - value);
  126. v = g_strdup (t + 1);
  127. *t = '\0';
  128. if (ucl_vars == NULL) {
  129. ucl_vars = g_hash_table_new_full (rspamd_strcase_hash,
  130. rspamd_strcase_equal, g_free, g_free);
  131. }
  132. g_hash_table_insert (ucl_vars, k, v);
  133. }
  134. else {
  135. g_set_error (error, g_quark_try_string ("main"), EINVAL,
  136. "Bad variable format: %s", value);
  137. return FALSE;
  138. }
  139. return TRUE;
  140. }
  141. static void
  142. read_cmd_line (gint *argc, gchar ***argv, struct rspamd_config *cfg)
  143. {
  144. GError *error = NULL;
  145. GOptionContext *context;
  146. guint cfg_num;
  147. context = g_option_context_new ("- run rspamd daemon");
  148. #if defined(GIT_VERSION) && GIT_VERSION == 1
  149. g_option_context_set_summary (context,
  150. "Summary:\n Rspamd daemon version " RVERSION "-git\n Git id: " RID);
  151. #else
  152. g_option_context_set_summary (context,
  153. "Summary:\n Rspamd daemon version " RVERSION);
  154. #endif
  155. g_option_context_add_main_entries (context, entries, NULL);
  156. if (!g_option_context_parse (context, argc, argv, &error)) {
  157. fprintf (stderr, "option parsing failed: %s\n", error->message);
  158. g_option_context_free (context);
  159. exit (EXIT_FAILURE);
  160. }
  161. cfg->rspamd_user = rspamd_user;
  162. cfg->rspamd_group = rspamd_group;
  163. cfg_num = cfg_names != NULL ? g_strv_length (cfg_names) : 0;
  164. if (cfg_num == 0) {
  165. cfg->cfg_name = FIXED_CONFIG_FILE;
  166. }
  167. else {
  168. cfg->cfg_name = cfg_names[0];
  169. g_assert (cfg_num == 1);
  170. }
  171. cfg->pid_file = rspamd_pidfile;
  172. g_option_context_free (context);
  173. }
  174. static int
  175. rspamd_write_pid (struct rspamd_main *main)
  176. {
  177. pid_t pid;
  178. if (main->cfg->pid_file == NULL) {
  179. return -1;
  180. }
  181. main->pfh = rspamd_pidfile_open (main->cfg->pid_file, 0644, &pid);
  182. if (main->pfh == NULL) {
  183. return -1;
  184. }
  185. if (main->is_privileged) {
  186. /* Force root user as owner of pid file */
  187. #ifdef HAVE_PIDFILE_FILENO
  188. if (fchown (pidfile_fileno (main->pfh), 0, 0) == -1) {
  189. #else
  190. if (fchown (main->pfh->pf_fd, 0, 0) == -1) {
  191. #endif
  192. }
  193. }
  194. rspamd_pidfile_write (main->pfh);
  195. return 0;
  196. }
  197. /* Detect privileged mode */
  198. static void
  199. detect_priv (struct rspamd_main *rspamd_main)
  200. {
  201. struct passwd *pwd;
  202. struct group *grp;
  203. uid_t euid;
  204. euid = geteuid ();
  205. if (euid == 0) {
  206. if (!rspamd_main->cfg->rspamd_user && !is_insecure) {
  207. msg_err_main (
  208. "cannot run rspamd workers as root user, please add -u and -g options to select a proper unprivileged user or specify --insecure flag");
  209. exit (EXIT_FAILURE);
  210. }
  211. else if (is_insecure) {
  212. rspamd_main->is_privileged = TRUE;
  213. rspamd_main->workers_uid = 0;
  214. rspamd_main->workers_gid = 0;
  215. }
  216. else {
  217. rspamd_main->is_privileged = TRUE;
  218. pwd = getpwnam (rspamd_main->cfg->rspamd_user);
  219. if (pwd == NULL) {
  220. msg_err_main ("user specified does not exists (%s), aborting",
  221. strerror (errno));
  222. exit (-errno);
  223. }
  224. if (rspamd_main->cfg->rspamd_group) {
  225. grp = getgrnam (rspamd_main->cfg->rspamd_group);
  226. if (grp == NULL) {
  227. msg_err_main ("group specified does not exists (%s), aborting",
  228. strerror (errno));
  229. exit (-errno);
  230. }
  231. rspamd_main->workers_gid = grp->gr_gid;
  232. }
  233. else {
  234. rspamd_main->workers_gid = (gid_t)-1;
  235. }
  236. rspamd_main->workers_uid = pwd->pw_uid;
  237. }
  238. }
  239. else {
  240. rspamd_main->is_privileged = FALSE;
  241. rspamd_main->workers_uid = (uid_t)-1;
  242. rspamd_main->workers_gid = (gid_t)-1;
  243. }
  244. }
  245. static void
  246. config_logger (rspamd_mempool_t *pool, gpointer ud)
  247. {
  248. struct rspamd_main *rspamd_main = ud;
  249. rspamd_main->logger = rspamd_log_open_specific (rspamd_main->server_pool,
  250. rspamd_main->cfg,
  251. "main",
  252. rspamd_main->workers_uid,
  253. rspamd_main->workers_gid);
  254. if (rspamd_main->logger == NULL) {
  255. /*
  256. * XXX:
  257. * Error has been already logged (in fact,
  258. * we might fall back to console logger here)
  259. */
  260. exit (EXIT_FAILURE);
  261. }
  262. rspamd_logger_configure_modules (rspamd_main->cfg->debug_modules);
  263. }
  264. static gboolean
  265. reread_config (struct rspamd_main *rspamd_main)
  266. {
  267. struct rspamd_config *tmp_cfg, *old_cfg;
  268. gchar *cfg_file;
  269. int load_opts = RSPAMD_CONFIG_INIT_VALIDATE|RSPAMD_CONFIG_INIT_SYMCACHE|
  270. RSPAMD_CONFIG_INIT_LIBS|RSPAMD_CONFIG_INIT_URL;
  271. rspamd_symcache_save (rspamd_main->cfg->cache);
  272. tmp_cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_DEFAULT);
  273. tmp_cfg->libs_ctx = rspamd_main->cfg->libs_ctx;
  274. REF_RETAIN (tmp_cfg->libs_ctx);
  275. cfg_file = rspamd_mempool_strdup (tmp_cfg->cfg_pool,
  276. rspamd_main->cfg->cfg_name);
  277. /* Save some variables */
  278. tmp_cfg->cfg_name = cfg_file;
  279. old_cfg = rspamd_main->cfg;
  280. rspamd_main->cfg = tmp_cfg;
  281. rspamd_logger_t *old_logger = rspamd_main->logger;
  282. if (!load_rspamd_config (rspamd_main, tmp_cfg, TRUE, load_opts, TRUE)) {
  283. rspamd_main->cfg = old_cfg;
  284. rspamd_main->logger = old_logger;
  285. msg_err_main ("cannot parse new config file, revert to old one");
  286. REF_RELEASE (tmp_cfg);
  287. return FALSE;
  288. }
  289. else {
  290. rspamd_log_close (old_logger);
  291. msg_info_main ("replacing config");
  292. REF_RELEASE (old_cfg);
  293. rspamd_main->cfg->rspamd_user = rspamd_user;
  294. rspamd_main->cfg->rspamd_group = rspamd_group;
  295. /* Here, we can do post actions with the existing config */
  296. /*
  297. * As some rules are defined in lua, we need to process them, then init
  298. * modules and merely afterwards to init modules
  299. */
  300. rspamd_lua_post_load_config (tmp_cfg);
  301. rspamd_init_filters (tmp_cfg, true, false);
  302. /* Do post-load actions */
  303. rspamd_config_post_load (tmp_cfg,
  304. load_opts|RSPAMD_CONFIG_INIT_POST_LOAD_LUA|RSPAMD_CONFIG_INIT_PRELOAD_MAPS);
  305. msg_info_main ("config has been reread successfully");
  306. }
  307. return TRUE;
  308. }
  309. struct waiting_worker {
  310. struct rspamd_main *rspamd_main;
  311. struct ev_timer wait_ev;
  312. struct rspamd_worker_conf *cf;
  313. guint oldindex;
  314. };
  315. static void
  316. rspamd_fork_delayed_cb (EV_P_ ev_timer *w, int revents)
  317. {
  318. struct waiting_worker *waiting_worker = (struct waiting_worker *)w->data;
  319. ev_timer_stop (EV_A_ &waiting_worker->wait_ev);
  320. rspamd_fork_worker (waiting_worker->rspamd_main, waiting_worker->cf,
  321. waiting_worker->oldindex,
  322. waiting_worker->rspamd_main->event_loop,
  323. rspamd_cld_handler, listen_sockets);
  324. REF_RELEASE (waiting_worker->cf);
  325. g_free (waiting_worker);
  326. }
  327. static void
  328. rspamd_fork_delayed (struct rspamd_worker_conf *cf,
  329. guint index,
  330. struct rspamd_main *rspamd_main)
  331. {
  332. struct waiting_worker *nw;
  333. nw = g_malloc0 (sizeof (*nw));
  334. nw->cf = cf;
  335. nw->oldindex = index;
  336. nw->rspamd_main = rspamd_main;
  337. REF_RETAIN (cf);
  338. nw->wait_ev.data = nw;
  339. ev_timer_init (&nw->wait_ev, rspamd_fork_delayed_cb, SOFT_FORK_TIME, 0.0);
  340. ev_timer_start (rspamd_main->event_loop, &nw->wait_ev);
  341. }
  342. static GList *
  343. create_listen_socket (GPtrArray *addrs, guint cnt,
  344. enum rspamd_worker_socket_type listen_type)
  345. {
  346. GList *result = NULL;
  347. gint fd;
  348. guint i;
  349. static const int listen_opts = RSPAMD_INET_ADDRESS_LISTEN_ASYNC;
  350. struct rspamd_worker_listen_socket *ls;
  351. g_ptr_array_sort (addrs, rspamd_inet_address_compare_ptr);
  352. for (i = 0; i < cnt; i ++) {
  353. /*
  354. * Copy address to avoid reload issues
  355. */
  356. if (listen_type & RSPAMD_WORKER_SOCKET_TCP) {
  357. fd = rspamd_inet_address_listen (g_ptr_array_index (addrs, i),
  358. SOCK_STREAM,
  359. listen_opts, -1);
  360. if (fd != -1) {
  361. ls = g_malloc0 (sizeof (*ls));
  362. ls->addr = rspamd_inet_address_copy(g_ptr_array_index (addrs, i), NULL);
  363. ls->fd = fd;
  364. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  365. result = g_list_prepend (result, ls);
  366. }
  367. }
  368. if (listen_type & RSPAMD_WORKER_SOCKET_UDP) {
  369. fd = rspamd_inet_address_listen (g_ptr_array_index (addrs, i),
  370. SOCK_DGRAM,
  371. listen_opts | RSPAMD_INET_ADDRESS_LISTEN_REUSEPORT, -1);
  372. if (fd != -1) {
  373. ls = g_malloc0 (sizeof (*ls));
  374. ls->addr = rspamd_inet_address_copy(g_ptr_array_index (addrs, i), NULL);
  375. ls->fd = fd;
  376. ls->type = RSPAMD_WORKER_SOCKET_UDP;
  377. result = g_list_prepend (result, ls);
  378. }
  379. }
  380. }
  381. return result;
  382. }
  383. static GList *
  384. systemd_get_socket (struct rspamd_main *rspamd_main, const gchar *fdname)
  385. {
  386. int number, sock, num_passed, flags;
  387. GList *result = NULL;
  388. const gchar *e;
  389. gchar **fdnames;
  390. gchar *end;
  391. struct stat st;
  392. static const int sd_listen_fds_start = 3; /* SD_LISTEN_FDS_START */
  393. struct rspamd_worker_listen_socket *ls;
  394. union {
  395. struct sockaddr_storage ss;
  396. struct sockaddr sa;
  397. } addr_storage;
  398. socklen_t slen = sizeof (addr_storage);
  399. gint stype;
  400. number = strtoul (fdname, &end, 10);
  401. if (end != NULL && *end != '\0') {
  402. /* Cannot parse as number, assume a name in LISTEN_FDNAMES. */
  403. e = getenv ("LISTEN_FDNAMES");
  404. if (!e) {
  405. msg_err_main ("cannot get systemd variable 'LISTEN_FDNAMES'");
  406. errno = ENOENT;
  407. return NULL;
  408. }
  409. fdnames = g_strsplit (e, ":", -1);
  410. for (number = 0; fdnames[number]; number++) {
  411. if (!strcmp (fdnames[number], fdname)) {
  412. break;
  413. }
  414. }
  415. if (!fdnames[number]) {
  416. number = -1;
  417. }
  418. g_strfreev (fdnames);
  419. }
  420. if (number < 0) {
  421. msg_warn_main ("cannot find systemd socket: %s", fdname);
  422. errno = ENOENT;
  423. return NULL;
  424. }
  425. e = getenv ("LISTEN_FDS");
  426. if (e != NULL) {
  427. errno = 0;
  428. num_passed = strtoul (e, &end, 10);
  429. if ((end == NULL || *end == '\0') && num_passed > number) {
  430. sock = number + sd_listen_fds_start;
  431. if (fstat (sock, &st) == -1) {
  432. msg_warn_main ("cannot stat systemd descriptor %d", sock);
  433. return NULL;
  434. }
  435. if (!S_ISSOCK (st.st_mode)) {
  436. msg_warn_main ("systemd descriptor %d is not a socket", sock);
  437. errno = EINVAL;
  438. return NULL;
  439. }
  440. flags = fcntl (sock, F_GETFD);
  441. if (flags != -1) {
  442. (void)fcntl (sock, F_SETFD, flags | FD_CLOEXEC);
  443. }
  444. rspamd_socket_nonblocking (sock);
  445. if (getsockname (sock, &addr_storage.sa, &slen) == -1) {
  446. msg_warn_main ("cannot get name for systemd descriptor %d: %s",
  447. sock, strerror (errno));
  448. errno = EINVAL;
  449. return NULL;
  450. }
  451. ls = g_malloc0 (sizeof (*ls));
  452. ls->addr = rspamd_inet_address_from_sa (&addr_storage.sa, slen);
  453. ls->fd = sock;
  454. ls->is_systemd = true;
  455. slen = sizeof (stype);
  456. if (getsockopt (sock, SOL_SOCKET, SO_TYPE, &stype, &slen) != -1) {
  457. if (stype == SOCK_STREAM) {
  458. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  459. }
  460. else {
  461. ls->type = RSPAMD_WORKER_SOCKET_UDP;
  462. }
  463. }
  464. else {
  465. msg_warn_main ("cannot get type for systemd descriptor %d: %s",
  466. sock, strerror (errno));
  467. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  468. }
  469. result = g_list_prepend (result, ls);
  470. }
  471. else if (num_passed <= number) {
  472. msg_err_main ("systemd LISTEN_FDS does not contain the expected fd: %d",
  473. num_passed);
  474. errno = EINVAL;
  475. }
  476. }
  477. else {
  478. msg_err_main ("cannot get systemd variable 'LISTEN_FDS'");
  479. errno = ENOENT;
  480. }
  481. return result;
  482. }
  483. static void
  484. pass_signal_cb (gpointer key, gpointer value, gpointer ud)
  485. {
  486. struct rspamd_worker *cur = value;
  487. gint signo = GPOINTER_TO_INT (ud);
  488. kill (cur->pid, signo);
  489. }
  490. static void
  491. rspamd_pass_signal (GHashTable * workers, gint signo)
  492. {
  493. g_hash_table_foreach (workers, pass_signal_cb, GINT_TO_POINTER (signo));
  494. }
  495. static inline uintptr_t
  496. make_listen_key (struct rspamd_worker_bind_conf *cf)
  497. {
  498. rspamd_cryptobox_fast_hash_state_t st;
  499. guint i, keylen = 0;
  500. guint8 *key;
  501. rspamd_inet_addr_t *addr;
  502. guint16 port;
  503. rspamd_cryptobox_fast_hash_init (&st, rspamd_hash_seed ());
  504. if (cf->is_systemd) {
  505. /* Something like 'systemd:0' or 'systemd:controller'. */
  506. rspamd_cryptobox_fast_hash_update (&st, cf->name, strlen (cf->name));
  507. }
  508. else {
  509. rspamd_cryptobox_fast_hash_update (&st, cf->name, strlen (cf->name));
  510. for (i = 0; i < cf->cnt; i ++) {
  511. addr = g_ptr_array_index (cf->addrs, i);
  512. key = rspamd_inet_address_get_hash_key (
  513. addr, &keylen);
  514. rspamd_cryptobox_fast_hash_update (&st, key, keylen);
  515. port = rspamd_inet_address_get_port (addr);
  516. rspamd_cryptobox_fast_hash_update (&st, &port, sizeof (port));
  517. }
  518. }
  519. return rspamd_cryptobox_fast_hash_final (&st);
  520. }
  521. static void
  522. spawn_worker_type (struct rspamd_main *rspamd_main, struct ev_loop *event_loop,
  523. struct rspamd_worker_conf *cf)
  524. {
  525. gint i;
  526. if (cf->count < 0) {
  527. msg_info_main ("skip spawning of worker %s: disabled in configuration",
  528. cf->worker->name);
  529. return;
  530. }
  531. if (cf->worker->flags & RSPAMD_WORKER_UNIQUE) {
  532. if (cf->count > 1) {
  533. msg_warn_main (
  534. "cannot spawn more than 1 %s worker, so spawn one",
  535. cf->worker->name);
  536. }
  537. rspamd_fork_worker (rspamd_main, cf, 0, event_loop, rspamd_cld_handler,
  538. listen_sockets);
  539. }
  540. else if (cf->worker->flags & RSPAMD_WORKER_THREADED) {
  541. rspamd_fork_worker (rspamd_main, cf, 0, event_loop, rspamd_cld_handler,
  542. listen_sockets);
  543. }
  544. else {
  545. for (i = 0; i < cf->count; i++) {
  546. rspamd_fork_worker (rspamd_main, cf, i, event_loop,
  547. rspamd_cld_handler, listen_sockets);
  548. }
  549. }
  550. }
  551. static void
  552. spawn_workers (struct rspamd_main *rspamd_main, struct ev_loop *ev_base)
  553. {
  554. GList *cur, *ls;
  555. struct rspamd_worker_conf *cf;
  556. gpointer p;
  557. guintptr key;
  558. struct rspamd_worker_bind_conf *bcf;
  559. gboolean listen_ok = FALSE;
  560. GPtrArray *seen_mandatory_workers;
  561. worker_t **cw, *wrk;
  562. guint i;
  563. /* Special hack for hs_helper if it's not defined in a config */
  564. seen_mandatory_workers = g_ptr_array_new ();
  565. cur = rspamd_main->cfg->workers;
  566. while (cur) {
  567. cf = cur->data;
  568. listen_ok = FALSE;
  569. if (cf->worker == NULL) {
  570. msg_err_main ("type of worker is unspecified, skip spawning");
  571. }
  572. else {
  573. if (!cf->enabled || cf->count <= 0) {
  574. msg_info_main ("worker of type %s(%s) is disabled in the config, "
  575. "skip spawning", g_quark_to_string (cf->type),
  576. cf->bind_conf ? cf->bind_conf->name : "none");
  577. cur = g_list_next (cur);
  578. continue;
  579. }
  580. if (cf->worker->flags & RSPAMD_WORKER_ALWAYS_START) {
  581. g_ptr_array_add (seen_mandatory_workers, cf->worker);
  582. }
  583. if (cf->worker->flags & RSPAMD_WORKER_HAS_SOCKET) {
  584. LL_FOREACH (cf->bind_conf, bcf) {
  585. key = make_listen_key (bcf);
  586. if ((p =
  587. g_hash_table_lookup (listen_sockets,
  588. GINT_TO_POINTER (key))) == NULL) {
  589. if (!bcf->is_systemd) {
  590. /* Create listen socket */
  591. ls = create_listen_socket (bcf->addrs, bcf->cnt,
  592. cf->worker->listen_type);
  593. }
  594. else {
  595. ls = systemd_get_socket (rspamd_main,
  596. g_ptr_array_index (bcf->addrs, 0));
  597. }
  598. if (ls == NULL) {
  599. msg_err_main ("cannot listen on %s socket %s: %s",
  600. bcf->is_systemd ? "systemd" : "normal",
  601. bcf->name,
  602. strerror (errno));
  603. }
  604. else {
  605. g_hash_table_insert (listen_sockets, (gpointer)key, ls);
  606. listen_ok = TRUE;
  607. }
  608. }
  609. else {
  610. /* We had socket for this type of worker */
  611. ls = p;
  612. listen_ok = TRUE;
  613. }
  614. /* Do not add existing lists as it causes loops */
  615. if (g_list_position (cf->listen_socks, ls) == -1) {
  616. cf->listen_socks = g_list_concat (cf->listen_socks, ls);
  617. }
  618. }
  619. if (listen_ok) {
  620. spawn_worker_type (rspamd_main, ev_base, cf);
  621. }
  622. else {
  623. if (cf->bind_conf == NULL) {
  624. msg_err_main ("cannot create listen socket for %s",
  625. g_quark_to_string (cf->type));
  626. } else {
  627. msg_err_main ("cannot create listen socket for %s at %s",
  628. g_quark_to_string (cf->type), cf->bind_conf->name);
  629. }
  630. rspamd_hard_terminate (rspamd_main);
  631. g_assert_not_reached ();
  632. }
  633. }
  634. else {
  635. spawn_worker_type (rspamd_main, ev_base, cf);
  636. }
  637. }
  638. cur = g_list_next (cur);
  639. }
  640. for (cw = workers; *cw != NULL; cw ++) {
  641. gboolean seen = FALSE;
  642. wrk = *cw;
  643. if (wrk->flags & RSPAMD_WORKER_ALWAYS_START) {
  644. for (i = 0; i < seen_mandatory_workers->len; i ++) {
  645. if (wrk == g_ptr_array_index (seen_mandatory_workers, i)) {
  646. seen = TRUE;
  647. break;
  648. }
  649. }
  650. if (!seen) {
  651. cf = rspamd_config_new_worker (rspamd_main->cfg, NULL);
  652. cf->count = 1;
  653. cf->worker = wrk;
  654. cf->type = g_quark_from_static_string (wrk->name);
  655. if (cf->worker->worker_init_func) {
  656. cf->ctx = cf->worker->worker_init_func (rspamd_main->cfg);
  657. }
  658. spawn_worker_type (rspamd_main, ev_base, cf);
  659. }
  660. }
  661. }
  662. g_ptr_array_free (seen_mandatory_workers, TRUE);
  663. }
  664. static void
  665. kill_old_workers (gpointer key, gpointer value, gpointer unused)
  666. {
  667. struct rspamd_worker *w = value;
  668. struct rspamd_main *rspamd_main;
  669. rspamd_main = w->srv;
  670. if (w->state == rspamd_worker_state_wanna_die) {
  671. w->state = rspamd_worker_state_terminating;
  672. kill (w->pid, SIGUSR2);
  673. ev_io_stop (rspamd_main->event_loop, &w->srv_ev);
  674. g_hash_table_remove_all (w->control_events_pending);
  675. msg_info_main ("send signal to worker %P", w->pid);
  676. }
  677. else if (w->state != rspamd_worker_state_running) {
  678. msg_info_main ("do not send signal to worker %P, already sent", w->pid);
  679. }
  680. }
  681. static void
  682. mark_old_workers (gpointer key, gpointer value, gpointer unused)
  683. {
  684. struct rspamd_worker *w = value;
  685. if (w->state == rspamd_worker_state_running) {
  686. w->state = rspamd_worker_state_wanna_die;
  687. }
  688. w->flags |= RSPAMD_WORKER_OLD_CONFIG;
  689. }
  690. static void
  691. rspamd_worker_wait (struct rspamd_worker *w)
  692. {
  693. struct rspamd_main *rspamd_main;
  694. rspamd_main = w->srv;
  695. if (term_attempts < 0) {
  696. if (w->cf->worker->flags & RSPAMD_WORKER_KILLABLE) {
  697. if (kill (w->pid, SIGKILL) == -1) {
  698. if (errno == ESRCH) {
  699. /* We have actually killed the process */
  700. return;
  701. }
  702. }
  703. else {
  704. msg_warn_main ("terminate worker %s(%P) with SIGKILL",
  705. g_quark_to_string (w->type), w->pid);
  706. }
  707. }
  708. else {
  709. kill (w->pid, SIGKILL);
  710. if (errno == ESRCH) {
  711. /* We have actually killed the process */
  712. return;
  713. }
  714. else {
  715. msg_err_main ("data corruption warning: terminating "
  716. "special worker %s(%P) with SIGKILL",
  717. g_quark_to_string (w->type), w->pid);
  718. }
  719. }
  720. }
  721. }
  722. static void
  723. hash_worker_wait_callback (gpointer key, gpointer value, gpointer unused)
  724. {
  725. rspamd_worker_wait ((struct rspamd_worker *)value);
  726. }
  727. struct core_check_cbdata {
  728. struct rspamd_config *cfg;
  729. gsize total_count;
  730. gsize total_size;
  731. };
  732. #ifdef HAVE_NFTW
  733. static struct core_check_cbdata cores_cbdata;
  734. static gint
  735. rspamd_check_core_cb (const gchar *path, const struct stat *st,
  736. gint flag, struct FTW *ft)
  737. {
  738. if (S_ISREG (st->st_mode)) {
  739. cores_cbdata.total_count ++;
  740. /* Use physical size instead of displayed one */
  741. cores_cbdata.total_size += st->st_blocks * 512;
  742. }
  743. return 0;
  744. }
  745. #endif
  746. static void
  747. rspamd_check_core_limits (struct rspamd_main *rspamd_main)
  748. {
  749. #ifdef HAVE_NFTW
  750. struct rspamd_config *cfg = rspamd_main->cfg;
  751. cores_cbdata.cfg = cfg;
  752. cores_cbdata.total_count = 0;
  753. cores_cbdata.total_size = 0;
  754. if (cfg->cores_dir && (cfg->max_cores_count || cfg->max_cores_size)) {
  755. if (nftw (cfg->cores_dir, rspamd_check_core_cb, 1, FTW_MOUNT|FTW_PHYS)
  756. == -1) {
  757. msg_err_main ("nftw failed for path %s: %s", cfg->cores_dir,
  758. strerror (errno));
  759. }
  760. else {
  761. if (!rspamd_main->cores_throttling) {
  762. if (cfg->max_cores_size &&
  763. cores_cbdata.total_size > cfg->max_cores_size) {
  764. msg_warn_main (
  765. "enable cores throttling as size of cores in"
  766. " %s is %Hz, limit is %Hz",
  767. cfg->cores_dir,
  768. cores_cbdata.total_size,
  769. cfg->max_cores_size);
  770. rspamd_main->cores_throttling = TRUE;
  771. }
  772. if (cfg->max_cores_count &&
  773. cores_cbdata.total_count > cfg->max_cores_count) {
  774. msg_warn_main (
  775. "enable cores throttling as count of cores in"
  776. " %s is %z, limit is %z",
  777. cfg->cores_dir,
  778. cores_cbdata.total_count,
  779. cfg->max_cores_count);
  780. rspamd_main->cores_throttling = TRUE;
  781. }
  782. }
  783. else {
  784. if (cfg->max_cores_size &&
  785. cores_cbdata.total_size < cfg->max_cores_size) {
  786. msg_info_main (
  787. "disable cores throttling as size of cores in"
  788. " %s is now %Hz, limit is %Hz",
  789. cfg->cores_dir,
  790. cores_cbdata.total_size,
  791. cfg->max_cores_size);
  792. rspamd_main->cores_throttling = FALSE;
  793. }
  794. if (cfg->max_cores_count &&
  795. cores_cbdata.total_count < cfg->max_cores_count) {
  796. msg_info_main (
  797. "disable cores throttling as count of cores in"
  798. " %s is %z, limit is %z",
  799. cfg->cores_dir,
  800. cores_cbdata.total_count,
  801. cfg->max_cores_count);
  802. rspamd_main->cores_throttling = FALSE;
  803. }
  804. }
  805. }
  806. }
  807. #endif
  808. }
  809. static void
  810. reopen_log_handler (gpointer key, gpointer value, gpointer unused)
  811. {
  812. struct rspamd_worker *w = value;
  813. struct rspamd_main *rspamd_main;
  814. rspamd_main = w->srv;
  815. if (kill (w->pid, SIGUSR1) == -1) {
  816. msg_err_main ("kill failed for pid %P: %s", w->pid, strerror (errno));
  817. }
  818. }
  819. static gboolean
  820. load_rspamd_config (struct rspamd_main *rspamd_main,
  821. struct rspamd_config *cfg, gboolean init_modules,
  822. enum rspamd_post_load_options opts,
  823. gboolean reload)
  824. {
  825. cfg->compiled_modules = modules;
  826. cfg->compiled_workers = workers;
  827. if (!rspamd_config_read (cfg, cfg->cfg_name, config_logger, rspamd_main,
  828. ucl_vars, skip_template, lua_env)) {
  829. return FALSE;
  830. }
  831. /* Strictly set temp dir */
  832. if (!cfg->temp_dir) {
  833. msg_warn_main ("tempdir is not set, trying to use $TMPDIR");
  834. cfg->temp_dir =
  835. rspamd_mempool_strdup (cfg->cfg_pool, getenv ("TMPDIR"));
  836. if (!cfg->temp_dir) {
  837. msg_warn_main ("$TMPDIR is empty too, using /tmp as default");
  838. cfg->temp_dir = rspamd_mempool_strdup (cfg->cfg_pool, "/tmp");
  839. }
  840. }
  841. if (!reload) {
  842. /*
  843. * As some rules are defined in lua, we need to process them, then init
  844. * modules and merely afterwards to init modules
  845. */
  846. rspamd_lua_post_load_config (cfg);
  847. if (init_modules) {
  848. if (!rspamd_init_filters (cfg, reload, false)) {
  849. return FALSE;
  850. }
  851. }
  852. /* Do post-load actions */
  853. if (!rspamd_config_post_load (cfg, opts)) {
  854. return FALSE;
  855. }
  856. }
  857. return TRUE;
  858. }
  859. static void
  860. rspamd_detach_worker (struct rspamd_main *rspamd_main, struct rspamd_worker *wrk)
  861. {
  862. ev_io_stop (rspamd_main->event_loop, &wrk->srv_ev);
  863. ev_timer_stop (rspamd_main->event_loop, &wrk->hb.heartbeat_ev);
  864. }
  865. static void
  866. rspamd_attach_worker (struct rspamd_main *rspamd_main, struct rspamd_worker *wrk)
  867. {
  868. ev_io_start (rspamd_main->event_loop, &wrk->srv_ev);
  869. ev_timer_start (rspamd_main->event_loop, &wrk->hb.heartbeat_ev);
  870. }
  871. static void
  872. stop_srv_ev (gpointer key, gpointer value, gpointer ud)
  873. {
  874. struct rspamd_worker *cur = (struct rspamd_worker *)value;
  875. struct rspamd_main *rspamd_main = (struct rspamd_main *)ud;
  876. rspamd_detach_worker (rspamd_main, cur);
  877. }
  878. static void
  879. start_srv_ev (gpointer key, gpointer value, gpointer ud)
  880. {
  881. struct rspamd_worker *cur = (struct rspamd_worker *)value;
  882. struct rspamd_main *rspamd_main = (struct rspamd_main *)ud;
  883. rspamd_attach_worker (rspamd_main, cur);
  884. }
  885. static void
  886. rspamd_final_timer_handler (EV_P_ ev_timer *w, int revents)
  887. {
  888. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  889. term_attempts--;
  890. g_hash_table_foreach (rspamd_main->workers, hash_worker_wait_callback,
  891. NULL);
  892. if (g_hash_table_size (rspamd_main->workers) == 0) {
  893. ev_break (rspamd_main->event_loop, EVBREAK_ALL);
  894. }
  895. }
  896. /* Signal handlers */
  897. static void
  898. rspamd_term_handler (struct ev_loop *loop, ev_signal *w, int revents)
  899. {
  900. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  901. static ev_timer ev_finale;
  902. ev_tstamp shutdown_ts;
  903. if (!rspamd_main->wanna_die) {
  904. rspamd_main->wanna_die = TRUE;
  905. shutdown_ts = MAX (SOFT_SHUTDOWN_TIME,
  906. rspamd_main->cfg->task_timeout * 2.0);
  907. msg_info_main ("catch termination signal, waiting for %d children for %.2f seconds",
  908. (gint)g_hash_table_size (rspamd_main->workers),
  909. valgrind_mode ? shutdown_ts * 10 : shutdown_ts);
  910. /* Stop srv events to avoid false notifications */
  911. g_hash_table_foreach (rspamd_main->workers, stop_srv_ev, rspamd_main);
  912. rspamd_pass_signal (rspamd_main->workers, SIGTERM);
  913. if (control_fd != -1) {
  914. ev_io_stop (rspamd_main->event_loop, &control_ev);
  915. close (control_fd);
  916. }
  917. if (valgrind_mode) {
  918. /* Special case if we are likely running with valgrind */
  919. term_attempts = shutdown_ts / TERMINATION_INTERVAL * 10;
  920. }
  921. else {
  922. term_attempts = shutdown_ts / TERMINATION_INTERVAL;
  923. }
  924. ev_finale.data = rspamd_main;
  925. ev_timer_init (&ev_finale, rspamd_final_timer_handler,
  926. TERMINATION_INTERVAL, TERMINATION_INTERVAL);
  927. ev_timer_start (rspamd_main->event_loop, &ev_finale);
  928. }
  929. }
  930. static void
  931. rspamd_usr1_handler (struct ev_loop *loop, ev_signal *w, int revents)
  932. {
  933. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  934. if (!rspamd_main->wanna_die) {
  935. rspamd_log_reopen (rspamd_main->logger,
  936. rspamd_main->cfg,
  937. rspamd_main->workers_uid,
  938. rspamd_main->workers_gid);
  939. msg_info_main ("logging reinitialised");
  940. g_hash_table_foreach (rspamd_main->workers, reopen_log_handler,
  941. NULL);
  942. }
  943. }
  944. static void
  945. rspamd_stat_update_handler (struct ev_loop *loop, ev_timer *w, int revents)
  946. {
  947. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  948. struct rspamd_stat cur_stat;
  949. gchar proctitle[128];
  950. memcpy (&cur_stat, rspamd_main->stat, sizeof (cur_stat));
  951. if (old_stat.messages_scanned > 0 &&
  952. cur_stat.messages_scanned > old_stat.messages_scanned) {
  953. gdouble rate = (double)(cur_stat.messages_scanned - old_stat.messages_scanned) /
  954. w->repeat;
  955. gdouble old_spam = old_stat.actions_stat[METRIC_ACTION_REJECT] +
  956. old_stat.actions_stat[METRIC_ACTION_ADD_HEADER] +
  957. old_stat.actions_stat[METRIC_ACTION_REWRITE_SUBJECT];
  958. gdouble old_ham = old_stat.actions_stat[METRIC_ACTION_NOACTION];
  959. gdouble new_spam = cur_stat.actions_stat[METRIC_ACTION_REJECT] +
  960. cur_stat.actions_stat[METRIC_ACTION_ADD_HEADER] +
  961. cur_stat.actions_stat[METRIC_ACTION_REWRITE_SUBJECT];
  962. gdouble new_ham = cur_stat.actions_stat[METRIC_ACTION_NOACTION];
  963. gsize cnt = MAX_AVG_TIME_SLOTS;
  964. float sum = rspamd_sum_floats (cur_stat.avg_time.avg_time, &cnt);
  965. rspamd_snprintf (proctitle, sizeof (proctitle),
  966. "main process; %.1f msg/sec, %.1f msg/sec spam, %.1f msg/sec ham; %.2fs avg processing time",
  967. rate,
  968. (new_spam - old_spam) / w->repeat,
  969. (new_ham - old_ham) / w->repeat,
  970. cnt > 0 ? sum / cnt : 0);
  971. setproctitle (proctitle);
  972. }
  973. memcpy (&old_stat, &cur_stat, sizeof (cur_stat));
  974. }
  975. static void
  976. rspamd_hup_handler (struct ev_loop *loop, ev_signal *w, int revents)
  977. {
  978. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  979. if (!rspamd_main->wanna_die) {
  980. msg_info_main ("rspamd "
  981. RVERSION
  982. " is requested to reload configuration");
  983. /* Detach existing workers and stop their heartbeats */
  984. g_hash_table_foreach (rspamd_main->workers, stop_srv_ev, rspamd_main);
  985. if (reread_config (rspamd_main)) {
  986. rspamd_check_core_limits (rspamd_main);
  987. /* Mark old workers */
  988. g_hash_table_foreach (rspamd_main->workers, mark_old_workers, NULL);
  989. msg_info_main ("spawn workers with a new config");
  990. spawn_workers (rspamd_main, rspamd_main->event_loop);
  991. msg_info_main ("workers spawning has been finished");
  992. /* Kill marked */
  993. msg_info_main ("kill old workers");
  994. g_hash_table_foreach (rspamd_main->workers, kill_old_workers, NULL);
  995. }
  996. else {
  997. /* Reattach old workers */
  998. msg_info_main ("restore old workers with a old config");
  999. g_hash_table_foreach (rspamd_main->workers, start_srv_ev, rspamd_main);
  1000. }
  1001. }
  1002. }
  1003. /* Called when a dead child has been found */
  1004. static void
  1005. rspamd_cld_handler (EV_P_ ev_child *w, struct rspamd_main *rspamd_main,
  1006. struct rspamd_worker *wrk)
  1007. {
  1008. gboolean need_refork;
  1009. static struct rspamd_control_command cmd;
  1010. /* Turn off locking for logger */
  1011. ev_child_stop (EV_A_ w);
  1012. /* Remove dead child form children list */
  1013. g_hash_table_remove (rspamd_main->workers, GSIZE_TO_POINTER (wrk->pid));
  1014. g_hash_table_remove_all (wrk->control_events_pending);
  1015. if (wrk->srv_pipe[0] != -1) {
  1016. /* Ugly workaround */
  1017. if (wrk->tmp_data) {
  1018. g_free (wrk->tmp_data);
  1019. }
  1020. rspamd_detach_worker (rspamd_main, wrk);
  1021. }
  1022. if (wrk->control_pipe[0] != -1) {
  1023. /* We also need to clean descriptors left */
  1024. close (wrk->control_pipe[0]);
  1025. close (wrk->srv_pipe[0]);
  1026. }
  1027. if (!rspamd_main->wanna_die) {
  1028. cmd.type = RSPAMD_CONTROL_CHILD_CHANGE;
  1029. cmd.cmd.child_change.what = rspamd_child_terminated;
  1030. cmd.cmd.child_change.pid = wrk->pid;
  1031. cmd.cmd.child_change.additional = w->rstatus;
  1032. rspamd_control_broadcast_srv_cmd (rspamd_main, &cmd, wrk->pid);
  1033. }
  1034. need_refork = rspamd_check_termination_clause (wrk->srv, wrk, w->rstatus);
  1035. if (need_refork) {
  1036. /* Fork another worker in replace of dead one */
  1037. msg_info_main ("respawn process %s in lieu of terminated process with pid %P",
  1038. g_quark_to_string (wrk->type),
  1039. wrk->pid);
  1040. rspamd_check_core_limits (rspamd_main);
  1041. rspamd_fork_delayed (wrk->cf, wrk->index, rspamd_main);
  1042. }
  1043. else {
  1044. msg_info_main ("do not respawn process %s after found terminated process with pid %P",
  1045. g_quark_to_string (wrk->type),
  1046. wrk->pid);
  1047. }
  1048. REF_RELEASE (wrk->cf);
  1049. g_hash_table_unref (wrk->control_events_pending);
  1050. g_free (wrk);
  1051. }
  1052. /* Control socket handler */
  1053. static void
  1054. rspamd_control_handler (EV_P_ ev_io *w, int revents)
  1055. {
  1056. struct rspamd_main *rspamd_main = (struct rspamd_main *)w->data;
  1057. rspamd_inet_addr_t *addr = NULL;
  1058. gint nfd;
  1059. if ((nfd =
  1060. rspamd_accept_from_socket (w->fd, &addr, NULL, NULL)) == -1) {
  1061. msg_warn_main ("accept failed: %s", strerror (errno));
  1062. return;
  1063. }
  1064. /* Check for EAGAIN */
  1065. if (nfd == 0) {
  1066. rspamd_inet_address_free (addr);
  1067. return;
  1068. }
  1069. msg_info_main ("accepted control connection from %s",
  1070. rspamd_inet_address_to_string (addr));
  1071. rspamd_control_process_client_socket (rspamd_main, nfd, addr);
  1072. }
  1073. static guint
  1074. rspamd_spair_hash (gconstpointer p)
  1075. {
  1076. return rspamd_cryptobox_fast_hash (p, PAIR_ID_LEN, rspamd_hash_seed ());
  1077. }
  1078. static gboolean
  1079. rspamd_spair_equal (gconstpointer a, gconstpointer b)
  1080. {
  1081. return memcmp (a, b, PAIR_ID_LEN) == 0;
  1082. }
  1083. static void
  1084. rspamd_spair_close (gpointer p)
  1085. {
  1086. gint *fds = p;
  1087. close (fds[0]);
  1088. close (fds[1]);
  1089. g_free (p);
  1090. }
  1091. static void
  1092. version (void)
  1093. {
  1094. #if defined(GIT_VERSION) && GIT_VERSION == 1
  1095. rspamd_printf ("Rspamd daemon version " RVERSION "-git." RID "\n");
  1096. #else
  1097. rspamd_printf ("Rspamd daemon version " RVERSION "\n");
  1098. #endif
  1099. }
  1100. static gboolean
  1101. rspamd_main_daemon (struct rspamd_main *rspamd_main)
  1102. {
  1103. int fd;
  1104. pid_t old_pid = getpid ();
  1105. switch (fork ()) {
  1106. case -1:
  1107. msg_err_main ("fork() failed: %s", strerror (errno));
  1108. return FALSE;
  1109. case 0:
  1110. break;
  1111. default:
  1112. /* Old process */
  1113. exit (0);
  1114. }
  1115. rspamd_log_on_fork (g_quark_from_static_string ("main"),
  1116. rspamd_main->cfg,
  1117. rspamd_main->logger);
  1118. if (setsid () == -1) {
  1119. msg_err_main ("setsid () failed: %s", strerror (errno));
  1120. return FALSE;
  1121. }
  1122. umask (0);
  1123. fd = open ("/dev/null", O_RDWR);
  1124. if (fd == -1) {
  1125. msg_err_main ("open(\"/dev/null\") failed: %s", strerror (errno));
  1126. return FALSE;
  1127. }
  1128. if (dup2 (fd, STDIN_FILENO) == -1) {
  1129. msg_err_main ("dup2(STDIN) failed: %s", strerror (errno));
  1130. return FALSE;
  1131. }
  1132. if (dup2 (fd, STDOUT_FILENO) == -1) {
  1133. msg_err_main ("dup2(STDOUT) failed: %s", strerror (errno));
  1134. return FALSE;
  1135. }
  1136. if (fd > STDERR_FILENO) {
  1137. if (close(fd) == -1) {
  1138. msg_err_main ("close() failed: %s", strerror (errno));
  1139. return FALSE;
  1140. }
  1141. }
  1142. msg_info_main ("daemonized successfully; old pid %P, new pid %P; pid file: %s",
  1143. old_pid, getpid (),
  1144. rspamd_main->cfg->pid_file);
  1145. return TRUE;
  1146. }
  1147. gint
  1148. main (gint argc, gchar **argv, gchar **env)
  1149. {
  1150. gint i, res = 0;
  1151. struct sigaction signals, sigpipe_act;
  1152. worker_t **pworker;
  1153. GQuark type;
  1154. rspamd_inet_addr_t *control_addr = NULL;
  1155. struct ev_loop *event_loop;
  1156. struct rspamd_main *rspamd_main;
  1157. gboolean skip_pid = FALSE;
  1158. sigset_t control_signals;
  1159. /* Block special signals on loading */
  1160. sigemptyset (&control_signals);
  1161. sigaddset (&control_signals, SIGHUP);
  1162. sigaddset (&control_signals, SIGUSR1);
  1163. sigaddset (&control_signals, SIGUSR2);
  1164. sigprocmask (SIG_BLOCK, &control_signals, NULL);
  1165. rspamd_main = (struct rspamd_main *) g_malloc0 (sizeof (struct rspamd_main));
  1166. rspamd_main->server_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
  1167. "main", 0);
  1168. rspamd_main->stat = rspamd_mempool_alloc0_shared_ (rspamd_main->server_pool,
  1169. sizeof (struct rspamd_stat),
  1170. RSPAMD_ALIGNOF(struct rspamd_stat),
  1171. G_STRLOC);
  1172. /* Set all time slots to nan */
  1173. for (i = 0; i < MAX_AVG_TIME_SLOTS; i ++) {
  1174. rspamd_main->stat->avg_time.avg_time[i] = NAN;
  1175. }
  1176. rspamd_main->cfg = rspamd_config_new (RSPAMD_CONFIG_INIT_DEFAULT);
  1177. rspamd_main->spairs = g_hash_table_new_full (rspamd_spair_hash,
  1178. rspamd_spair_equal, g_free, rspamd_spair_close);
  1179. rspamd_main->start_mtx = rspamd_mempool_get_mutex (rspamd_main->server_pool);
  1180. if (getenv ("VALGRIND") != NULL) {
  1181. valgrind_mode = TRUE;
  1182. }
  1183. #ifndef HAVE_SETPROCTITLE
  1184. init_title (rspamd_main->server_pool, argc, argv, env);
  1185. #endif
  1186. rspamd_main->cfg->libs_ctx = rspamd_init_libs ();
  1187. memset (&signals, 0, sizeof (struct sigaction));
  1188. read_cmd_line (&argc, &argv, rspamd_main->cfg);
  1189. if (show_version) {
  1190. version ();
  1191. exit (EXIT_SUCCESS);
  1192. }
  1193. if (argc > 0) {
  1194. /* Parse variables */
  1195. for (i = 0; i < argc; i++) {
  1196. if (strchr (argv[i], '=') != NULL) {
  1197. gchar *k, *v, *t;
  1198. k = g_strdup (argv[i]);
  1199. t = strchr (k, '=');
  1200. v = g_strdup (t + 1);
  1201. *t = '\0';
  1202. if (ucl_vars == NULL) {
  1203. ucl_vars = g_hash_table_new_full (rspamd_strcase_hash,
  1204. rspamd_strcase_equal, g_free, g_free);
  1205. }
  1206. g_hash_table_insert (ucl_vars, k, v);
  1207. }
  1208. }
  1209. }
  1210. if (is_debug) {
  1211. rspamd_main->cfg->log_level = G_LOG_LEVEL_DEBUG;
  1212. }
  1213. else {
  1214. rspamd_main->cfg->log_level = G_LOG_LEVEL_MESSAGE;
  1215. }
  1216. type = g_quark_from_static_string ("main");
  1217. /* First set logger to console logger */
  1218. rspamd_main->logger = rspamd_log_open_emergency (rspamd_main->server_pool, 0);
  1219. g_assert (rspamd_main->logger != NULL);
  1220. if (is_debug) {
  1221. rspamd_log_set_log_level (rspamd_main->logger, G_LOG_LEVEL_DEBUG);
  1222. }
  1223. else {
  1224. rspamd_log_set_log_level (rspamd_main->logger, G_LOG_LEVEL_MESSAGE);
  1225. }
  1226. g_log_set_default_handler (rspamd_glib_log_function, rspamd_main->logger);
  1227. g_set_printerr_handler (rspamd_glib_printerr_function);
  1228. detect_priv (rspamd_main);
  1229. msg_notice_main ("rspamd "
  1230. RVERSION
  1231. " is loading configuration, build id: "
  1232. RID);
  1233. pworker = &workers[0];
  1234. while (*pworker) {
  1235. /* Init string quarks */
  1236. (void) g_quark_from_static_string ((*pworker)->name);
  1237. pworker++;
  1238. }
  1239. /* Init listen sockets hash */
  1240. listen_sockets = g_hash_table_new (g_direct_hash, g_direct_equal);
  1241. sqlite3_initialize ();
  1242. /* Load config */
  1243. if (!load_rspamd_config (rspamd_main, rspamd_main->cfg, TRUE,
  1244. RSPAMD_CONFIG_LOAD_ALL, FALSE)) {
  1245. exit (EXIT_FAILURE);
  1246. }
  1247. /* Override pidfile from configuration by command line argument */
  1248. if (rspamd_pidfile != NULL) {
  1249. rspamd_main->cfg->pid_file = rspamd_pidfile;
  1250. }
  1251. /* Force debug log */
  1252. if (is_debug) {
  1253. rspamd_log_set_log_level (rspamd_main->logger, G_LOG_LEVEL_DEBUG);
  1254. }
  1255. /* Create rolling history */
  1256. rspamd_main->history = rspamd_roll_history_new (rspamd_main->server_pool,
  1257. rspamd_main->cfg->history_rows, rspamd_main->cfg);
  1258. msg_info_main ("rspamd "
  1259. RVERSION
  1260. " is starting, build id: "
  1261. RID);
  1262. rspamd_main->cfg->cfg_name = rspamd_mempool_strdup (
  1263. rspamd_main->cfg->cfg_pool,
  1264. rspamd_main->cfg->cfg_name);
  1265. msg_info_main ("cpu features: %s",
  1266. rspamd_main->cfg->libs_ctx->crypto_ctx->cpu_extensions);
  1267. msg_info_main ("cryptobox configuration: curve25519(libsodium), "
  1268. "chacha20(%s), poly1305(libsodium), siphash(libsodium), blake2(libsodium), base64(%s)",
  1269. rspamd_main->cfg->libs_ctx->crypto_ctx->chacha20_impl,
  1270. rspamd_main->cfg->libs_ctx->crypto_ctx->base64_impl);
  1271. msg_info_main ("libottery prf: %s", ottery_get_impl_name ());
  1272. /* Daemonize */
  1273. if (!no_fork) {
  1274. if (!rspamd_main_daemon (rspamd_main)) {
  1275. exit (EXIT_FAILURE);
  1276. }
  1277. /* Close emergency logger */
  1278. rspamd_log_close (rspamd_log_emergency_logger ());
  1279. }
  1280. /* Write info */
  1281. rspamd_main->pid = getpid ();
  1282. rspamd_main->type = type;
  1283. if (!valgrind_mode) {
  1284. rspamd_set_crash_handler (rspamd_main);
  1285. }
  1286. /* Ignore SIGPIPE as we handle write errors manually */
  1287. sigemptyset (&sigpipe_act.sa_mask);
  1288. sigaddset (&sigpipe_act.sa_mask, SIGPIPE);
  1289. sigpipe_act.sa_handler = SIG_IGN;
  1290. sigpipe_act.sa_flags = 0;
  1291. sigaction (SIGPIPE, &sigpipe_act, NULL);
  1292. if (rspamd_main->cfg->pid_file == NULL) {
  1293. msg_info_main ("pid file is not specified, skipping writing it");
  1294. skip_pid = TRUE;
  1295. }
  1296. else if (no_fork) {
  1297. msg_info_main ("skip writing pid in no-fork mode");
  1298. skip_pid = TRUE;
  1299. }
  1300. else if (rspamd_write_pid (rspamd_main) == -1) {
  1301. msg_err_main ("cannot write pid file %s", rspamd_main->cfg->pid_file);
  1302. exit (-errno);
  1303. }
  1304. sigprocmask (SIG_BLOCK, &signals.sa_mask, NULL);
  1305. /* Set title */
  1306. setproctitle ("main process");
  1307. /* Open control socket if needed */
  1308. control_fd = -1;
  1309. if (rspamd_main->cfg->control_socket_path) {
  1310. if (!rspamd_parse_inet_address (&control_addr,
  1311. rspamd_main->cfg->control_socket_path,
  1312. strlen (rspamd_main->cfg->control_socket_path),
  1313. RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
  1314. msg_err_main ("cannot parse inet address %s",
  1315. rspamd_main->cfg->control_socket_path);
  1316. }
  1317. else {
  1318. control_fd = rspamd_inet_address_listen (control_addr, SOCK_STREAM,
  1319. RSPAMD_INET_ADDRESS_LISTEN_ASYNC, -1);
  1320. if (control_fd == -1) {
  1321. msg_err_main ("cannot open control socket at path: %s",
  1322. rspamd_main->cfg->control_socket_path);
  1323. }
  1324. }
  1325. }
  1326. /* Maybe read roll history */
  1327. if (rspamd_main->cfg->history_file) {
  1328. rspamd_roll_history_load (rspamd_main->history,
  1329. rspamd_main->cfg->history_file);
  1330. }
  1331. /* Init workers hash */
  1332. rspamd_main->workers = g_hash_table_new (g_direct_hash, g_direct_equal);
  1333. /* Unblock control signals */
  1334. sigprocmask (SIG_UNBLOCK, &control_signals, NULL);
  1335. /* Init event base */
  1336. event_loop = ev_default_loop (rspamd_config_ev_backend_get (rspamd_main->cfg));
  1337. rspamd_main->event_loop = event_loop;
  1338. if (event_loop) {
  1339. int loop_type = ev_backend (event_loop);
  1340. gboolean effective_backend;
  1341. const gchar *loop_str;
  1342. loop_str =
  1343. rspamd_config_ev_backend_to_string (loop_type, &effective_backend);
  1344. if (!effective_backend) {
  1345. msg_warn_main ("event loop uses non-optimal backend: %s", loop_str);
  1346. }
  1347. else {
  1348. msg_info_main ("event loop initialised with backend: %s", loop_str);
  1349. }
  1350. }
  1351. else {
  1352. msg_err ("cannot init event loop! exiting");
  1353. exit (EXIT_FAILURE);
  1354. }
  1355. /* Unblock signals */
  1356. sigemptyset (&signals.sa_mask);
  1357. sigprocmask (SIG_SETMASK, &signals.sa_mask, NULL);
  1358. /* Set events for signals */
  1359. ev_signal_init (&rspamd_main->term_ev, rspamd_term_handler, SIGTERM);
  1360. rspamd_main->term_ev.data = rspamd_main;
  1361. ev_signal_start (event_loop, &rspamd_main->term_ev);
  1362. ev_signal_init (&rspamd_main->int_ev, rspamd_term_handler, SIGINT);
  1363. rspamd_main->int_ev.data = rspamd_main;
  1364. ev_signal_start (event_loop, &rspamd_main->int_ev);
  1365. ev_signal_init (&rspamd_main->hup_ev, rspamd_hup_handler, SIGHUP);
  1366. rspamd_main->hup_ev.data = rspamd_main;
  1367. ev_signal_start (event_loop, &rspamd_main->hup_ev);
  1368. ev_signal_init (&rspamd_main->usr1_ev, rspamd_usr1_handler, SIGUSR1);
  1369. rspamd_main->usr1_ev.data = rspamd_main;
  1370. ev_signal_start (event_loop, &rspamd_main->usr1_ev);
  1371. /* Update proctitle according to number of messages processed */
  1372. static const ev_tstamp stat_update_time = 10.0;
  1373. memset (&old_stat, 0, sizeof (old_stat));
  1374. stat_ev.data = rspamd_main;
  1375. ev_timer_init (&stat_ev, rspamd_stat_update_handler,
  1376. stat_update_time, stat_update_time);
  1377. ev_timer_start (event_loop, &stat_ev);
  1378. rspamd_check_core_limits (rspamd_main);
  1379. rspamd_mempool_lock_mutex (rspamd_main->start_mtx);
  1380. spawn_workers (rspamd_main, event_loop);
  1381. rspamd_mempool_unlock_mutex (rspamd_main->start_mtx);
  1382. rspamd_main->http_ctx = rspamd_http_context_create (rspamd_main->cfg,
  1383. event_loop, rspamd_main->cfg->ups_ctx);
  1384. if (control_fd != -1) {
  1385. msg_info_main ("listening for control commands on %s",
  1386. rspamd_inet_address_to_string (control_addr));
  1387. ev_io_init (&control_ev, rspamd_control_handler, control_fd, EV_READ);
  1388. control_ev.data = rspamd_main;
  1389. ev_io_start (event_loop, &control_ev);
  1390. }
  1391. ev_loop (event_loop, 0);
  1392. /* Maybe save roll history */
  1393. if (rspamd_main->cfg->history_file) {
  1394. rspamd_roll_history_save (rspamd_main->history,
  1395. rspamd_main->cfg->history_file);
  1396. }
  1397. if (rspamd_main->cfg->cache) {
  1398. rspamd_symcache_save(rspamd_main->cfg->cache);
  1399. }
  1400. msg_info_main ("terminating...");
  1401. REF_RELEASE (rspamd_main->cfg);
  1402. rspamd_log_close (rspamd_main->logger);
  1403. g_hash_table_unref (rspamd_main->spairs);
  1404. g_hash_table_unref (rspamd_main->workers);
  1405. rspamd_mempool_delete (rspamd_main->server_pool);
  1406. if (!skip_pid) {
  1407. rspamd_pidfile_close (rspamd_main->pfh);
  1408. }
  1409. g_free (rspamd_main);
  1410. ev_unref (event_loop);
  1411. sqlite3_shutdown ();
  1412. if (control_addr) {
  1413. rspamd_inet_address_free (control_addr);
  1414. }
  1415. return (res);
  1416. }