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

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