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

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