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

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