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

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