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

rspamd.c 41KB

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