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

rspamd.c 40KB

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