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

rspamd.c 43KB

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