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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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_LIBUTIL_H
  45. #include <libutil.h>
  46. #endif
  47. #ifdef WITH_GPERF_TOOLS
  48. #include <gperftools/profiler.h>
  49. #endif
  50. #ifdef HAVE_STROPS_H
  51. #include <stropts.h>
  52. #endif
  53. #ifdef HAVE_OPENSSL
  54. #include <openssl/err.h>
  55. #include <openssl/evp.h>
  56. #endif
  57. /* 2 seconds to fork new process in place of dead one */
  58. #define SOFT_FORK_TIME 2
  59. /* 10 seconds after getting termination signal to terminate all workers with SIGKILL */
  60. #define TERMINATION_ATTEMPTS 50
  61. static gboolean load_rspamd_config (struct rspamd_main *rspamd_main,
  62. struct rspamd_config *cfg,
  63. gboolean init_modules,
  64. enum rspamd_post_load_options opts,
  65. gboolean reload,
  66. GHashTable *vars);
  67. /* Control socket */
  68. static gint control_fd;
  69. /* Cmdline options */
  70. static gboolean config_test = FALSE;
  71. static gboolean no_fork = FALSE;
  72. static gboolean show_version = FALSE;
  73. static gchar **cfg_names = NULL;
  74. static gchar **lua_tests = NULL;
  75. static gchar **sign_configs = NULL;
  76. static gchar *privkey = NULL;
  77. static gchar *rspamd_user = NULL;
  78. static gchar *rspamd_group = NULL;
  79. static gchar *rspamd_pidfile = NULL;
  80. static gboolean dump_cache = FALSE;
  81. static gboolean is_debug = FALSE;
  82. static gboolean is_insecure = FALSE;
  83. static gboolean gen_keypair = FALSE;
  84. static gboolean encrypt_password = FALSE;
  85. static GHashTable *ucl_vars = NULL;
  86. static gint term_attempts = 0;
  87. /* List of unrelated forked processes */
  88. static GArray *other_workers = NULL;
  89. /* List of active listen sockets indexed by worker type */
  90. static GHashTable *listen_sockets = NULL;
  91. /* Defined in modules.c */
  92. extern module_t *modules[];
  93. extern worker_t *workers[];
  94. /* Commandline options */
  95. static GOptionEntry entries[] =
  96. {
  97. { "config-test", 't', 0, G_OPTION_ARG_NONE, &config_test,
  98. "Do config test and exit", NULL },
  99. { "no-fork", 'f', 0, G_OPTION_ARG_NONE, &no_fork,
  100. "Do not daemonize main process", NULL },
  101. { "config", 'c', 0, G_OPTION_ARG_FILENAME_ARRAY, &cfg_names,
  102. "Specify config file(s)", NULL },
  103. { "user", 'u', 0, G_OPTION_ARG_STRING, &rspamd_user,
  104. "User to run rspamd as", NULL },
  105. { "group", 'g', 0, G_OPTION_ARG_STRING, &rspamd_group,
  106. "Group to run rspamd as", NULL },
  107. { "pid", 'p', 0, G_OPTION_ARG_STRING, &rspamd_pidfile, "Path to pidfile",
  108. NULL },
  109. { "dump-cache", 'C', 0, G_OPTION_ARG_NONE, &dump_cache,
  110. "Dump symbols cache stats and exit", NULL },
  111. { "debug", 'd', 0, G_OPTION_ARG_NONE, &is_debug, "Force debug output",
  112. NULL },
  113. { "insecure", 'i', 0, G_OPTION_ARG_NONE, &is_insecure,
  114. "Ignore running workers as privileged users (insecure)", NULL },
  115. { "test-lua", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &lua_tests,
  116. "Specify lua file(s) to test", NULL },
  117. { "sign-config", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sign_configs,
  118. "Specify config file(s) to sign", NULL },
  119. { "private-key", 0, 0, G_OPTION_ARG_FILENAME, &privkey,
  120. "Specify private key to sign", NULL },
  121. { "gen-keypair", 0, 0, G_OPTION_ARG_NONE, &gen_keypair, "Generate new encryption "
  122. "keypair", NULL},
  123. { "encrypt-password", 0, 0, G_OPTION_ARG_NONE, &encrypt_password, "Encrypt "
  124. "controller password to store in the configuration file", NULL },
  125. { "version", 'v', 0, G_OPTION_ARG_NONE, &show_version,
  126. "Show version and exit", NULL },
  127. { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
  128. };
  129. static void
  130. read_cmd_line (gint *argc, gchar ***argv, struct rspamd_config *cfg)
  131. {
  132. GError *error = NULL;
  133. GOptionContext *context;
  134. guint i, cfg_num;
  135. pid_t r;
  136. context = g_option_context_new ("- run rspamd daemon");
  137. #if defined(GIT_VERSION) && GIT_VERSION == 1
  138. g_option_context_set_summary (context,
  139. "Summary:\n Rspamd daemon version " RVERSION "-git\n Git id: " RID);
  140. #else
  141. g_option_context_set_summary (context,
  142. "Summary:\n Rspamd daemon version " RVERSION);
  143. #endif
  144. g_option_context_add_main_entries (context, entries, NULL);
  145. if (!g_option_context_parse (context, argc, argv, &error)) {
  146. fprintf (stderr, "option parsing failed: %s\n", error->message);
  147. g_option_context_free (context);
  148. exit (1);
  149. }
  150. cfg->rspamd_user = rspamd_user;
  151. cfg->rspamd_group = rspamd_group;
  152. cfg_num = cfg_names != NULL ? g_strv_length (cfg_names) : 0;
  153. if (cfg_num == 0) {
  154. cfg->cfg_name = FIXED_CONFIG_FILE;
  155. }
  156. else {
  157. cfg->cfg_name = cfg_names[0];
  158. }
  159. for (i = 1; i < cfg_num; i++) {
  160. r = fork ();
  161. if (r == 0) {
  162. /* Spawning new main process */
  163. cfg->cfg_name = cfg_names[i];
  164. (void)setsid ();
  165. }
  166. else if (r == -1) {
  167. fprintf (stderr,
  168. "fork failed while spawning process for %s configuration file: %s\n",
  169. cfg_names[i],
  170. strerror (errno));
  171. }
  172. else {
  173. /* Save pid to the list of other main processes, we need it to ignore SIGCHLD from them */
  174. g_array_append_val (other_workers, r);
  175. }
  176. }
  177. cfg->pid_file = rspamd_pidfile;
  178. g_option_context_free (context);
  179. }
  180. /* Detect privilleged mode */
  181. static void
  182. detect_priv (struct rspamd_main *rspamd_main)
  183. {
  184. struct passwd *pwd;
  185. struct group *grp;
  186. uid_t euid;
  187. euid = geteuid ();
  188. if (euid == 0) {
  189. if (!rspamd_main->cfg->rspamd_user && !is_insecure) {
  190. msg_err_main (
  191. "cannot run rspamd workers as root user, please add -u and -g options to select a proper unprivilleged user or specify --insecure flag");
  192. exit (EXIT_FAILURE);
  193. }
  194. else if (is_insecure) {
  195. rspamd_main->is_privilleged = TRUE;
  196. rspamd_main->workers_uid = 0;
  197. rspamd_main->workers_gid = 0;
  198. }
  199. else {
  200. rspamd_main->is_privilleged = TRUE;
  201. pwd = getpwnam (rspamd_main->cfg->rspamd_user);
  202. if (pwd == NULL) {
  203. msg_err_main ("user specified does not exists (%s), aborting",
  204. strerror (errno));
  205. exit (-errno);
  206. }
  207. if (rspamd_main->cfg->rspamd_group) {
  208. grp = getgrnam (rspamd_main->cfg->rspamd_group);
  209. if (grp == NULL) {
  210. msg_err_main ("group specified does not exists (%s), aborting",
  211. strerror (errno));
  212. exit (-errno);
  213. }
  214. rspamd_main->workers_gid = grp->gr_gid;
  215. }
  216. else {
  217. rspamd_main->workers_gid = (gid_t)-1;
  218. }
  219. rspamd_main->workers_uid = pwd->pw_uid;
  220. }
  221. }
  222. else {
  223. rspamd_main->is_privilleged = FALSE;
  224. rspamd_main->workers_uid = (uid_t)-1;
  225. rspamd_main->workers_gid = (gid_t)-1;
  226. }
  227. }
  228. static void
  229. config_logger (rspamd_mempool_t *pool, gpointer ud)
  230. {
  231. struct rspamd_main *rspamd_main = ud;
  232. if (config_test) {
  233. /* Explicitly set logger type to console in case of config testing */
  234. rspamd_main->cfg->log_type = RSPAMD_LOG_CONSOLE;
  235. }
  236. rspamd_set_logger (rspamd_main->cfg, g_quark_try_string ("main"),
  237. &rspamd_main->logger, rspamd_main->server_pool);
  238. if (rspamd_log_open_priv (rspamd_main->logger,
  239. rspamd_main->workers_uid, rspamd_main->workers_gid) == -1) {
  240. fprintf (stderr, "Fatal error, cannot open logfile, exiting\n");
  241. exit (EXIT_FAILURE);
  242. }
  243. }
  244. static void
  245. reread_config (struct rspamd_main *rspamd_main)
  246. {
  247. struct rspamd_config *tmp_cfg, *old_cfg;
  248. gchar *cfg_file;
  249. rspamd_symbols_cache_save (rspamd_main->cfg->cache);
  250. tmp_cfg = rspamd_config_new ();
  251. g_hash_table_unref (tmp_cfg->c_modules);
  252. tmp_cfg->c_modules = g_hash_table_ref (rspamd_main->cfg->c_modules);
  253. tmp_cfg->libs_ctx = rspamd_main->cfg->libs_ctx;
  254. REF_RETAIN (tmp_cfg->libs_ctx);
  255. cfg_file = rspamd_mempool_strdup (tmp_cfg->cfg_pool,
  256. rspamd_main->cfg->cfg_name);
  257. /* Save some variables */
  258. tmp_cfg->cfg_name = cfg_file;
  259. old_cfg = rspamd_main->cfg;
  260. rspamd_main->cfg = tmp_cfg;
  261. if (!load_rspamd_config (rspamd_main, tmp_cfg, TRUE,
  262. RSPAMD_CONFIG_INIT_VALIDATE|RSPAMD_CONFIG_INIT_SYMCACHE,
  263. TRUE, ucl_vars)) {
  264. rspamd_main->cfg = old_cfg;
  265. rspamd_log_close_priv (rspamd_main->logger,
  266. rspamd_main->workers_uid,
  267. rspamd_main->workers_gid);
  268. rspamd_set_logger (rspamd_main->cfg, g_quark_try_string ("main"),
  269. &rspamd_main->logger, rspamd_main->server_pool);
  270. rspamd_log_open_priv (rspamd_main->logger,
  271. rspamd_main->workers_uid,
  272. rspamd_main->workers_gid);
  273. msg_err_main ("cannot parse new config file, revert to old one");
  274. REF_RELEASE (tmp_cfg);
  275. }
  276. else {
  277. msg_debug_main ("replacing config");
  278. REF_RELEASE (old_cfg);
  279. msg_info_main ("config has been reread successfully");
  280. }
  281. }
  282. struct waiting_worker {
  283. struct rspamd_main *rspamd_main;
  284. struct event wait_ev;
  285. struct rspamd_worker_conf *cf;
  286. guint oldindex;
  287. };
  288. static void
  289. rspamd_fork_delayed_cb (gint signo, short what, gpointer arg)
  290. {
  291. struct waiting_worker *w = arg;
  292. event_del (&w->wait_ev);
  293. rspamd_fork_worker (w->rspamd_main, w->cf, w->oldindex,
  294. w->rspamd_main->ev_base);
  295. REF_RELEASE (w->cf);
  296. g_slice_free1 (sizeof (*w), w);
  297. }
  298. static void
  299. rspamd_fork_delayed (struct rspamd_worker_conf *cf,
  300. guint index,
  301. struct rspamd_main *rspamd_main)
  302. {
  303. struct waiting_worker *nw;
  304. struct timeval tv;
  305. nw = g_slice_alloc0 (sizeof (*nw));
  306. nw->cf = cf;
  307. nw->oldindex = index;
  308. nw->rspamd_main = rspamd_main;
  309. tv.tv_sec = SOFT_FORK_TIME;
  310. tv.tv_usec = 0;
  311. REF_RETAIN (cf);
  312. event_set (&nw->wait_ev, -1, EV_TIMEOUT, rspamd_fork_delayed_cb, nw);
  313. event_base_set (rspamd_main->ev_base, &nw->wait_ev);
  314. event_add (&nw->wait_ev, &tv);
  315. }
  316. static GList *
  317. create_listen_socket (GPtrArray *addrs, guint cnt,
  318. enum rspamd_worker_socket_type listen_type)
  319. {
  320. GList *result = NULL;
  321. gint fd;
  322. guint i;
  323. struct rspamd_worker_listen_socket *ls;
  324. g_ptr_array_sort (addrs, rspamd_inet_address_compare_ptr);
  325. for (i = 0; i < cnt; i ++) {
  326. if (listen_type & RSPAMD_WORKER_SOCKET_TCP) {
  327. fd = rspamd_inet_address_listen (g_ptr_array_index (addrs, i),
  328. SOCK_STREAM, TRUE);
  329. if (fd != -1) {
  330. ls = g_slice_alloc0 (sizeof (*ls));
  331. ls->addr = g_ptr_array_index (addrs, i);
  332. ls->fd = fd;
  333. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  334. result = g_list_prepend (result, ls);
  335. }
  336. }
  337. if (listen_type & RSPAMD_WORKER_SOCKET_UDP) {
  338. fd = rspamd_inet_address_listen (g_ptr_array_index (addrs, i),
  339. SOCK_DGRAM, TRUE);
  340. if (fd != -1) {
  341. ls = g_slice_alloc0 (sizeof (*ls));
  342. ls->addr = g_ptr_array_index (addrs, i);
  343. ls->fd = fd;
  344. ls->type = RSPAMD_WORKER_SOCKET_UDP;
  345. result = g_list_prepend (result, ls);
  346. }
  347. }
  348. }
  349. return result;
  350. }
  351. static GList *
  352. systemd_get_socket (struct rspamd_main *rspamd_main, gint number)
  353. {
  354. int sock, num_passed, flags;
  355. GList *result = NULL;
  356. const gchar *e;
  357. gchar *err;
  358. struct stat st;
  359. /* XXX: can we trust the current choice ? */
  360. static const int sd_listen_fds_start = 3;
  361. struct rspamd_worker_listen_socket *ls;
  362. union {
  363. struct sockaddr_storage ss;
  364. struct sockaddr sa;
  365. } addr_storage;
  366. socklen_t slen = sizeof (addr_storage);
  367. gint stype;
  368. e = getenv ("LISTEN_FDS");
  369. if (e != NULL) {
  370. errno = 0;
  371. num_passed = strtoul (e, &err, 10);
  372. if ((err == NULL || *err == '\0') && num_passed > number) {
  373. sock = number + sd_listen_fds_start;
  374. if (fstat (sock, &st) == -1) {
  375. msg_warn_main ("cannot stat systemd descriptor %d", sock);
  376. return NULL;
  377. }
  378. if (!S_ISSOCK (st.st_mode)) {
  379. msg_warn_main ("systemd descriptor %d is not a socket", sock);
  380. errno = EINVAL;
  381. return NULL;
  382. }
  383. flags = fcntl (sock, F_GETFD);
  384. if (flags != -1) {
  385. (void)fcntl (sock, F_SETFD, flags | FD_CLOEXEC);
  386. }
  387. rspamd_socket_nonblocking (sock);
  388. if (getsockname (sock, &addr_storage.sa, &slen) == -1) {
  389. msg_warn_main ("cannot get name for systemd descriptor %d: %s",
  390. sock, strerror (errno));
  391. errno = EINVAL;
  392. return NULL;
  393. }
  394. ls = g_slice_alloc0 (sizeof (*ls));
  395. ls->addr = rspamd_inet_address_from_sa (&addr_storage.sa, slen);
  396. ls->fd = sock;
  397. slen = sizeof (stype);
  398. if (getsockopt (sock, SOL_SOCKET, SO_TYPE, &stype, &slen) != -1) {
  399. if (stype == SOCK_STREAM) {
  400. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  401. }
  402. else {
  403. ls->type = RSPAMD_WORKER_SOCKET_UDP;
  404. }
  405. }
  406. else {
  407. msg_warn_main ("cannot get type for systemd descriptor %d: %s",
  408. sock, strerror (errno));
  409. ls->type = RSPAMD_WORKER_SOCKET_TCP;
  410. }
  411. result = g_list_prepend (result, ls);
  412. }
  413. else if (num_passed <= number) {
  414. msg_err_main ("systemd LISTEN_FDS does not contain the expected fd: %d",
  415. num_passed);
  416. errno = EOVERFLOW;
  417. }
  418. }
  419. else {
  420. msg_err_main ("cannot get systemd variable 'LISTEN_FDS'");
  421. errno = ENOENT;
  422. }
  423. return result;
  424. }
  425. static inline uintptr_t
  426. make_listen_key (struct rspamd_worker_bind_conf *cf)
  427. {
  428. rspamd_cryptobox_fast_hash_state_t st;
  429. guint i, keylen = 0;
  430. guint8 *key;
  431. rspamd_inet_addr_t *addr;
  432. guint16 port;
  433. rspamd_cryptobox_fast_hash_init (&st, rspamd_hash_seed ());
  434. if (cf->is_systemd) {
  435. rspamd_cryptobox_fast_hash_update (&st, "systemd", sizeof ("systemd"));
  436. rspamd_cryptobox_fast_hash_update (&st, &cf->cnt, sizeof (cf->cnt));
  437. }
  438. else {
  439. rspamd_cryptobox_fast_hash_update (&st, cf->name, strlen (cf->name));
  440. for (i = 0; i < cf->cnt; i ++) {
  441. addr = g_ptr_array_index (cf->addrs, i);
  442. key = rspamd_inet_address_get_hash_key (
  443. addr, &keylen);
  444. rspamd_cryptobox_fast_hash_update (&st, key, keylen);
  445. port = rspamd_inet_address_get_port (addr);
  446. rspamd_cryptobox_fast_hash_update (&st, &port, sizeof (port));
  447. }
  448. }
  449. return rspamd_cryptobox_fast_hash_final (&st);
  450. }
  451. static void
  452. spawn_worker_type (struct rspamd_main *rspamd_main, struct event_base *ev_base,
  453. struct rspamd_worker_conf *cf)
  454. {
  455. gint i;
  456. if (cf->worker->flags & RSPAMD_WORKER_UNIQUE) {
  457. if (cf->count > 1) {
  458. msg_warn_main (
  459. "cannot spawn more than 1 %s worker, so spawn one",
  460. cf->worker->name);
  461. }
  462. rspamd_fork_worker (rspamd_main, cf, 0, ev_base);
  463. }
  464. else if (cf->worker->flags & RSPAMD_WORKER_THREADED) {
  465. rspamd_fork_worker (rspamd_main, cf, 0, ev_base);
  466. }
  467. else {
  468. for (i = 0; i < cf->count; i++) {
  469. rspamd_fork_worker (rspamd_main, cf, i, ev_base);
  470. }
  471. }
  472. }
  473. static void
  474. spawn_workers (struct rspamd_main *rspamd_main, struct event_base *ev_base)
  475. {
  476. GList *cur, *ls;
  477. struct rspamd_worker_conf *cf;
  478. gpointer p;
  479. guintptr key;
  480. struct rspamd_worker_bind_conf *bcf;
  481. gboolean listen_ok = FALSE;
  482. GPtrArray *seen_mandatory_workers;
  483. worker_t **cw, *wrk;
  484. guint i;
  485. /* Special hack for hs_helper if it's not defined in a config */
  486. seen_mandatory_workers = g_ptr_array_new ();
  487. cur = rspamd_main->cfg->workers;
  488. while (cur) {
  489. cf = cur->data;
  490. listen_ok = FALSE;
  491. if (cf->worker == NULL) {
  492. msg_err_main ("type of worker is unspecified, skip spawning");
  493. }
  494. else {
  495. if (!cf->enabled) {
  496. msg_info_main ("worker of type %s is disabled in the config, "
  497. "skip spawning", g_quark_to_string (cf->type));
  498. cur = g_list_next (cur);
  499. continue;
  500. }
  501. if (cf->worker->flags & RSPAMD_WORKER_ALWAYS_START) {
  502. g_ptr_array_add (seen_mandatory_workers, cf->worker);
  503. }
  504. if (cf->worker->flags & RSPAMD_WORKER_HAS_SOCKET) {
  505. LL_FOREACH (cf->bind_conf, bcf) {
  506. key = make_listen_key (bcf);
  507. if ((p =
  508. g_hash_table_lookup (listen_sockets,
  509. GINT_TO_POINTER (key))) == NULL) {
  510. if (!bcf->is_systemd) {
  511. /* Create listen socket */
  512. ls = create_listen_socket (bcf->addrs, bcf->cnt,
  513. cf->worker->listen_type);
  514. }
  515. else {
  516. ls = systemd_get_socket (rspamd_main, bcf->cnt);
  517. }
  518. if (ls == NULL) {
  519. msg_err_main ("cannot listen on %s socket %s: %s",
  520. bcf->is_systemd ? "systemd" : "normal",
  521. bcf->name,
  522. strerror (errno));
  523. }
  524. else {
  525. g_hash_table_insert (listen_sockets, (gpointer)key, ls);
  526. listen_ok = TRUE;
  527. }
  528. }
  529. else {
  530. /* We had socket for this type of worker */
  531. ls = p;
  532. listen_ok = TRUE;
  533. }
  534. /* Do not add existing lists as it causes loops */
  535. if (g_list_position (cf->listen_socks, ls) == -1) {
  536. cf->listen_socks = g_list_concat (cf->listen_socks, ls);
  537. }
  538. }
  539. if (listen_ok) {
  540. spawn_worker_type (rspamd_main, ev_base, cf);
  541. }
  542. else {
  543. msg_err_main ("cannot create listen socket for %s at %s",
  544. g_quark_to_string (cf->type), cf->bind_conf->name);
  545. rspamd_hard_terminate (rspamd_main);
  546. g_assert_not_reached ();
  547. }
  548. }
  549. else {
  550. spawn_worker_type (rspamd_main, ev_base, cf);
  551. }
  552. }
  553. cur = g_list_next (cur);
  554. }
  555. for (cw = workers; *cw != NULL; cw ++) {
  556. gboolean seen = FALSE;
  557. wrk = *cw;
  558. if (wrk->flags & RSPAMD_WORKER_ALWAYS_START) {
  559. for (i = 0; i < seen_mandatory_workers->len; i ++) {
  560. if (wrk == g_ptr_array_index (seen_mandatory_workers, i)) {
  561. seen = TRUE;
  562. break;
  563. }
  564. }
  565. if (!seen) {
  566. cf = rspamd_mempool_alloc0 (rspamd_main->cfg->cfg_pool,
  567. sizeof (struct rspamd_worker_conf));
  568. cf->params = g_hash_table_new (rspamd_str_hash,
  569. rspamd_str_equal);
  570. cf->active_workers = g_queue_new ();
  571. rspamd_mempool_add_destructor (rspamd_main->cfg->cfg_pool,
  572. (rspamd_mempool_destruct_t) g_hash_table_destroy,
  573. cf->params);
  574. rspamd_mempool_add_destructor (rspamd_main->cfg->cfg_pool,
  575. (rspamd_mempool_destruct_t) g_queue_free,
  576. cf->active_workers);
  577. cf->count = 1;
  578. cf->worker = wrk;
  579. cf->type = g_quark_from_static_string (wrk->name);
  580. if (cf->worker->worker_init_func) {
  581. cf->ctx = cf->worker->worker_init_func (rspamd_main->cfg);
  582. }
  583. spawn_worker_type (rspamd_main, ev_base, cf);
  584. }
  585. }
  586. }
  587. g_ptr_array_free (seen_mandatory_workers, TRUE);
  588. }
  589. static void
  590. kill_old_workers (gpointer key, gpointer value, gpointer unused)
  591. {
  592. struct rspamd_worker *w = value;
  593. struct rspamd_main *rspamd_main;
  594. rspamd_main = w->srv;
  595. if (!w->wanna_die) {
  596. w->wanna_die = TRUE;
  597. kill (w->pid, SIGUSR2);
  598. msg_info_main ("send signal to worker %P", w->pid);
  599. }
  600. else {
  601. msg_info_main ("do not send signal to worker %P, already sent", w->pid);
  602. }
  603. }
  604. static gboolean
  605. wait_for_workers (gpointer key, gpointer value, gpointer unused)
  606. {
  607. struct rspamd_worker *w = value;
  608. struct rspamd_main *rspamd_main;
  609. gint res = 0;
  610. rspamd_main = w->srv;
  611. if (waitpid (w->pid, &res, WNOHANG) <= 0) {
  612. if (term_attempts < 0) {
  613. if (w->cf->worker->flags & RSPAMD_WORKER_KILLABLE) {
  614. msg_warn_main ("terminate worker %s(%P) with SIGKILL",
  615. g_quark_to_string (w->type), w->pid);
  616. kill (w->pid, SIGKILL);
  617. }
  618. else {
  619. if (term_attempts > -(TERMINATION_ATTEMPTS * 2)) {
  620. if (term_attempts % 10 == 0) {
  621. msg_info_main ("waiting for worker %s(%P) to sync, "
  622. "%d seconds remain",
  623. g_quark_to_string (w->type), w->pid,
  624. (TERMINATION_ATTEMPTS * 2 + term_attempts) / 5);
  625. kill (w->pid, SIGTERM);
  626. }
  627. }
  628. else {
  629. msg_err_main ("data corruption warning: terminating "
  630. "special worker %s(%P) with SIGKILL",
  631. g_quark_to_string (w->type), w->pid);
  632. kill (w->pid, SIGKILL);
  633. }
  634. }
  635. }
  636. return FALSE;
  637. }
  638. msg_info_main ("%s process %P terminated %s",
  639. g_quark_to_string (w->type), w->pid,
  640. WTERMSIG (res) == SIGKILL ? "hardly" : "softly");
  641. event_del (&w->srv_ev);
  642. g_ptr_array_free (w->finish_actions, TRUE);
  643. REF_RELEASE (w->cf);
  644. g_free (w);
  645. return TRUE;
  646. }
  647. struct core_check_cbdata {
  648. struct rspamd_config *cfg;
  649. gsize total_count;
  650. gsize total_size;
  651. };
  652. #ifdef HAVE_NFTW
  653. static struct core_check_cbdata cores_cbdata;
  654. static gint
  655. rspamd_check_core_cb (const gchar *path, const struct stat *st,
  656. gint flag, struct FTW *ft)
  657. {
  658. if (S_ISREG (st->st_mode)) {
  659. cores_cbdata.total_count ++;
  660. /* Use physical size instead of displayed one */
  661. cores_cbdata.total_size += st->st_blocks * 512;
  662. }
  663. return 0;
  664. }
  665. #endif
  666. static void
  667. rspamd_check_core_limits (struct rspamd_main *rspamd_main)
  668. {
  669. #ifdef HAVE_NFTW
  670. struct rspamd_config *cfg = rspamd_main->cfg;
  671. cores_cbdata.cfg = cfg;
  672. cores_cbdata.total_count = 0;
  673. cores_cbdata.total_size = 0;
  674. if (cfg->cores_dir && (cfg->max_cores_count || cfg->max_cores_size)) {
  675. if (nftw (cfg->cores_dir, rspamd_check_core_cb, 1, FTW_MOUNT|FTW_PHYS)
  676. == -1) {
  677. msg_err_main ("nftw failed for path %s: %s", cfg->cores_dir,
  678. strerror (errno));
  679. }
  680. else {
  681. if (!rspamd_main->cores_throttling) {
  682. if (cfg->max_cores_size &&
  683. cores_cbdata.total_size > cfg->max_cores_size) {
  684. msg_warn_main (
  685. "enable cores throttling as size of cores in"
  686. " %s is %Hz, limit is %Hz",
  687. cfg->cores_dir,
  688. cores_cbdata.total_size,
  689. cfg->max_cores_size);
  690. rspamd_main->cores_throttling = TRUE;
  691. }
  692. if (cfg->max_cores_count &&
  693. cores_cbdata.total_count > cfg->max_cores_count) {
  694. msg_warn_main (
  695. "enable cores throttling as count of cores in"
  696. " %s is %z, limit is %z",
  697. cfg->cores_dir,
  698. cores_cbdata.total_count,
  699. cfg->max_cores_count);
  700. rspamd_main->cores_throttling = TRUE;
  701. }
  702. }
  703. else {
  704. if (cfg->max_cores_size &&
  705. cores_cbdata.total_size < cfg->max_cores_size) {
  706. msg_info_main (
  707. "disable cores throttling as size of cores in"
  708. " %s is now %Hz, limit is %Hz",
  709. cfg->cores_dir,
  710. cores_cbdata.total_size,
  711. cfg->max_cores_size);
  712. rspamd_main->cores_throttling = FALSE;
  713. }
  714. if (cfg->max_cores_count &&
  715. cores_cbdata.total_count < cfg->max_cores_count) {
  716. msg_info_main (
  717. "disable cores throttling as count of cores in"
  718. " %s is %z, limit is %z",
  719. cfg->cores_dir,
  720. cores_cbdata.total_count,
  721. cfg->max_cores_count);
  722. rspamd_main->cores_throttling = FALSE;
  723. }
  724. }
  725. }
  726. }
  727. #endif
  728. }
  729. static void
  730. reopen_log_handler (gpointer key, gpointer value, gpointer unused)
  731. {
  732. struct rspamd_worker *w = value;
  733. struct rspamd_main *rspamd_main;
  734. rspamd_main = w->srv;
  735. if (kill (w->pid, SIGUSR1) == -1) {
  736. msg_err_main ("kill failed for pid %P: %s", w->pid, strerror (errno));
  737. }
  738. }
  739. static gboolean
  740. load_rspamd_config (struct rspamd_main *rspamd_main,
  741. struct rspamd_config *cfg, gboolean init_modules,
  742. enum rspamd_post_load_options opts,
  743. gboolean reload,
  744. GHashTable *vars)
  745. {
  746. cfg->compiled_modules = modules;
  747. cfg->compiled_workers = workers;
  748. if (!rspamd_config_read (cfg, cfg->cfg_name, NULL,
  749. config_logger, rspamd_main, ucl_vars)) {
  750. return FALSE;
  751. }
  752. /* Strictly set temp dir */
  753. if (!cfg->temp_dir) {
  754. msg_warn_main ("tempdir is not set, trying to use $TMPDIR");
  755. cfg->temp_dir =
  756. rspamd_mempool_strdup (cfg->cfg_pool, getenv ("TMPDIR"));
  757. if (!cfg->temp_dir) {
  758. msg_warn_main ("$TMPDIR is empty too, using /tmp as default");
  759. cfg->temp_dir = rspamd_mempool_strdup (cfg->cfg_pool, "/tmp");
  760. }
  761. }
  762. /*
  763. * As some rules are defined in lua, we need to process them, then init
  764. * modules and merely afterwards to init modules
  765. */
  766. rspamd_lua_post_load_config (cfg);
  767. if (init_modules) {
  768. rspamd_init_filters (cfg, reload, vars);
  769. }
  770. /* Do post-load actions */
  771. rspamd_config_post_load (cfg, opts);
  772. return TRUE;
  773. }
  774. static gint
  775. perform_lua_tests (struct rspamd_config *cfg)
  776. {
  777. rspamd_fprintf (stderr, "no longer supported\n");
  778. return EXIT_FAILURE;
  779. }
  780. static gint
  781. perform_configs_sign (void)
  782. {
  783. rspamd_fprintf (stderr, "use rspamadm signtool for this operation\n");
  784. return EXIT_FAILURE;
  785. }
  786. static void
  787. do_encrypt_password (void)
  788. {
  789. rspamd_fprintf (stderr, "use rspamadm pw for this operation\n");
  790. }
  791. /* Signal handlers */
  792. static void
  793. rspamd_term_handler (gint signo, short what, gpointer arg)
  794. {
  795. struct rspamd_main *rspamd_main = arg;
  796. msg_info_main ("catch termination signal, waiting for children");
  797. rspamd_log_nolock (rspamd_main->logger);
  798. rspamd_pass_signal (rspamd_main->workers, signo);
  799. event_base_loopexit (rspamd_main->ev_base, NULL);
  800. }
  801. static void
  802. rspamd_usr1_handler (gint signo, short what, gpointer arg)
  803. {
  804. struct rspamd_main *rspamd_main = arg;
  805. rspamd_log_reopen_priv (rspamd_main->logger,
  806. rspamd_main->workers_uid,
  807. rspamd_main->workers_gid);
  808. g_hash_table_foreach (rspamd_main->workers, reopen_log_handler,
  809. NULL);
  810. }
  811. static void
  812. rspamd_hup_handler (gint signo, short what, gpointer arg)
  813. {
  814. struct rspamd_main *rspamd_main = arg;
  815. msg_info_main ("rspamd "
  816. RVERSION
  817. " is restarting");
  818. g_hash_table_foreach (rspamd_main->workers, kill_old_workers, NULL);
  819. rspamd_map_remove_all (rspamd_main->cfg);
  820. rspamd_log_close_priv (rspamd_main->logger,
  821. rspamd_main->workers_uid,
  822. rspamd_main->workers_gid);
  823. reread_config (rspamd_main);
  824. rspamd_check_core_limits (rspamd_main);
  825. spawn_workers (rspamd_main, rspamd_main->ev_base);
  826. }
  827. static void
  828. rspamd_cld_handler (gint signo, short what, gpointer arg)
  829. {
  830. struct rspamd_main *rspamd_main = arg;
  831. guint i;
  832. gint res = 0;
  833. struct rspamd_worker *cur;
  834. pid_t wrk;
  835. gboolean need_refork = TRUE;
  836. /* Turn off locking for logger */
  837. rspamd_log_nolock (rspamd_main->logger);
  838. msg_debug_main ("catch SIGCHLD signal, finding terminated workers");
  839. /* Remove dead child form children list */
  840. while ((wrk = waitpid (0, &res, WNOHANG)) > 0) {
  841. if ((cur =
  842. g_hash_table_lookup (rspamd_main->workers,
  843. GSIZE_TO_POINTER (wrk))) != NULL) {
  844. /* Unlink dead process from queue and hash table */
  845. g_hash_table_remove (rspamd_main->workers, GSIZE_TO_POINTER (
  846. wrk));
  847. if (cur->wanna_die) {
  848. /* Do not refork workers that are intended to be terminated */
  849. need_refork = FALSE;
  850. }
  851. if (WIFEXITED (res) && WEXITSTATUS (res) == 0) {
  852. /* Normal worker termination, do not fork one more */
  853. msg_info_main ("%s process %P terminated normally",
  854. g_quark_to_string (cur->type),
  855. cur->pid);
  856. }
  857. else {
  858. if (WIFSIGNALED (res)) {
  859. #ifdef WCOREDUMP
  860. if (WCOREDUMP (res)) {
  861. msg_warn_main (
  862. "%s process %P terminated abnormally by signal: %s"
  863. " and created core file",
  864. g_quark_to_string (cur->type),
  865. cur->pid,
  866. g_strsignal (WTERMSIG (res)));
  867. }
  868. else {
  869. msg_warn_main (
  870. "%s process %P terminated abnormally by signal: %s"
  871. " but NOT created core file",
  872. g_quark_to_string (cur->type),
  873. cur->pid,
  874. g_strsignal (WTERMSIG (res)));
  875. }
  876. #else
  877. msg_warn_main (
  878. "%s process %P terminated abnormally by signal: %s",
  879. g_quark_to_string (cur->type),
  880. cur->pid,
  881. g_strsignal (WTERMSIG (res)));
  882. #endif
  883. if (WTERMSIG (res) == SIGUSR2) {
  884. /*
  885. * It is actually race condition when not started process
  886. * has been requested to be reloaded.
  887. *
  888. * We shouldn't refork on this
  889. */
  890. need_refork = FALSE;
  891. }
  892. }
  893. else {
  894. msg_warn_main ("%s process %P terminated abnormally "
  895. "with exit code %d",
  896. g_quark_to_string (cur->type),
  897. cur->pid,
  898. WEXITSTATUS (res));
  899. }
  900. if (need_refork) {
  901. /* Fork another worker in replace of dead one */
  902. rspamd_check_core_limits (rspamd_main);
  903. rspamd_fork_delayed (cur->cf, cur->index, rspamd_main);
  904. }
  905. }
  906. event_del (&cur->srv_ev);
  907. /* We also need to clean descriptors left */
  908. close (cur->control_pipe[0]);
  909. close (cur->srv_pipe[0]);
  910. REF_RELEASE (cur->cf);
  911. g_ptr_array_free (cur->finish_actions, TRUE);
  912. g_free (cur);
  913. }
  914. else {
  915. for (i = 0; i < other_workers->len; i++) {
  916. if (g_array_index (other_workers, pid_t, i) == wrk) {
  917. g_array_remove_index_fast (other_workers, i);
  918. msg_info_main ("related process %P terminated", wrk);
  919. }
  920. }
  921. }
  922. }
  923. rspamd_log_lock (rspamd_main->logger);
  924. }
  925. static void
  926. rspamd_final_term_handler (gint signo, short what, gpointer arg)
  927. {
  928. struct rspamd_main *rspamd_main = arg;
  929. term_attempts--;
  930. g_hash_table_foreach_remove (rspamd_main->workers, wait_for_workers, NULL);
  931. if (g_hash_table_size (rspamd_main->workers) == 0) {
  932. event_base_loopexit (rspamd_main->ev_base, NULL);
  933. }
  934. }
  935. /* Control socket handler */
  936. static void
  937. rspamd_control_handler (gint fd, short what, gpointer arg)
  938. {
  939. struct rspamd_main *rspamd_main = arg;
  940. rspamd_inet_addr_t *addr;
  941. gint nfd;
  942. if ((nfd =
  943. rspamd_accept_from_socket (fd, &addr, NULL)) == -1) {
  944. msg_warn_main ("accept failed: %s", strerror (errno));
  945. return;
  946. }
  947. /* Check for EAGAIN */
  948. if (nfd == 0) {
  949. return;
  950. }
  951. msg_info_main ("accepted control connection from %s",
  952. rspamd_inet_address_to_string (addr));
  953. rspamd_control_process_client_socket (rspamd_main, nfd);
  954. }
  955. static guint
  956. rspamd_spair_hash (gconstpointer p)
  957. {
  958. return rspamd_cryptobox_fast_hash (p, PAIR_ID_LEN, rspamd_hash_seed ());
  959. }
  960. static gboolean
  961. rspamd_spair_equal (gconstpointer a, gconstpointer b)
  962. {
  963. return memcmp (a, b, PAIR_ID_LEN) == 0;
  964. }
  965. static void
  966. rspamd_spair_close (gpointer p)
  967. {
  968. gint *fds = p;
  969. close (fds[0]);
  970. close (fds[1]);
  971. g_free (p);
  972. }
  973. static void
  974. version (void)
  975. {
  976. #if defined(GIT_VERSION) && GIT_VERSION == 1
  977. rspamd_printf ("Rspamd daemon version " RVERSION "-git." RID "\n");
  978. #else
  979. rspamd_printf ("Rspamd daemon version " RVERSION "\n");
  980. #endif
  981. }
  982. gint
  983. main (gint argc, gchar **argv, gchar **env)
  984. {
  985. gint i, res = 0;
  986. struct sigaction signals, sigpipe_act;
  987. worker_t **pworker;
  988. GQuark type;
  989. rspamd_inet_addr_t *control_addr = NULL;
  990. struct event_base *ev_base;
  991. struct event term_ev, int_ev, cld_ev, hup_ev, usr1_ev, control_ev;
  992. struct timeval term_tv;
  993. struct rspamd_main *rspamd_main;
  994. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION <= 30))
  995. g_thread_init (NULL);
  996. #endif
  997. rspamd_main = (struct rspamd_main *) g_malloc0 (sizeof (struct rspamd_main));
  998. rspamd_main->server_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
  999. "main");
  1000. rspamd_main->stat = rspamd_mempool_alloc0_shared (rspamd_main->server_pool,
  1001. sizeof (struct rspamd_stat));
  1002. rspamd_main->cfg = rspamd_config_new ();
  1003. rspamd_main->spairs = g_hash_table_new_full (rspamd_spair_hash,
  1004. rspamd_spair_equal, g_free, rspamd_spair_close);
  1005. rspamd_main->start_mtx = rspamd_mempool_get_mutex (rspamd_main->server_pool);
  1006. #ifndef HAVE_SETPROCTITLE
  1007. init_title (argc, argv, env);
  1008. #endif
  1009. rspamd_main->cfg->libs_ctx = rspamd_init_libs ();
  1010. memset (&signals, 0, sizeof (struct sigaction));
  1011. other_workers = g_array_new (FALSE, TRUE, sizeof (pid_t));
  1012. read_cmd_line (&argc, &argv, rspamd_main->cfg);
  1013. if (show_version) {
  1014. version ();
  1015. exit (EXIT_SUCCESS);
  1016. }
  1017. if (argc > 0) {
  1018. /* Parse variables */
  1019. for (i = 0; i < argc; i++) {
  1020. if (strchr (argv[i], '=') != NULL) {
  1021. gchar *k, *v, *t;
  1022. k = g_strdup (argv[i]);
  1023. t = strchr (k, '=');
  1024. v = g_strdup (t + 1);
  1025. *t = '\0';
  1026. if (ucl_vars == NULL) {
  1027. ucl_vars = g_hash_table_new_full (rspamd_strcase_hash,
  1028. rspamd_strcase_equal, g_free, g_free);
  1029. }
  1030. g_hash_table_insert (ucl_vars, k, v);
  1031. }
  1032. }
  1033. }
  1034. if (config_test || is_debug) {
  1035. rspamd_main->cfg->log_level = G_LOG_LEVEL_DEBUG;
  1036. }
  1037. else {
  1038. rspamd_main->cfg->log_level = G_LOG_LEVEL_WARNING;
  1039. }
  1040. type = g_quark_from_static_string ("main");
  1041. /* First set logger to console logger */
  1042. rspamd_main->cfg->log_type = RSPAMD_LOG_CONSOLE;
  1043. rspamd_set_logger (rspamd_main->cfg, type,
  1044. &rspamd_main->logger, rspamd_main->server_pool);
  1045. (void) rspamd_log_open (rspamd_main->logger);
  1046. g_log_set_default_handler (rspamd_glib_log_function, rspamd_main->logger);
  1047. g_set_printerr_handler (rspamd_glib_printerr_function);
  1048. detect_priv (rspamd_main);
  1049. pworker = &workers[0];
  1050. while (*pworker) {
  1051. /* Init string quarks */
  1052. (void) g_quark_from_static_string ((*pworker)->name);
  1053. pworker++;
  1054. }
  1055. /* Init listen sockets hash */
  1056. listen_sockets = g_hash_table_new (g_direct_hash, g_direct_equal);
  1057. /* If we want to test lua skip everything except it */
  1058. if (lua_tests != NULL && lua_tests[0] != NULL) {
  1059. exit (perform_lua_tests (rspamd_main->cfg));
  1060. }
  1061. /* If we want to sign configs, just do it */
  1062. if (sign_configs != NULL && privkey != NULL) {
  1063. exit (perform_configs_sign ());
  1064. }
  1065. /* Same for keypair creation */
  1066. if (gen_keypair) {
  1067. rspamd_fprintf (stderr, "use rspamadm keypair for this operation\n");
  1068. exit (EXIT_FAILURE);
  1069. }
  1070. if (encrypt_password) {
  1071. do_encrypt_password ();
  1072. exit (EXIT_SUCCESS);
  1073. }
  1074. rspamd_log_close_priv (rspamd_main->logger, rspamd_main->workers_uid,
  1075. rspamd_main->workers_gid);
  1076. if (config_test || dump_cache) {
  1077. if (!load_rspamd_config (rspamd_main, rspamd_main->cfg, FALSE, 0,
  1078. FALSE, ucl_vars)) {
  1079. exit (EXIT_FAILURE);
  1080. }
  1081. res = TRUE;
  1082. if (!rspamd_symbols_cache_validate (rspamd_main->cfg->cache,
  1083. rspamd_main->cfg,
  1084. FALSE)) {
  1085. res = FALSE;
  1086. }
  1087. if (dump_cache) {
  1088. msg_err_main ("Use rspamc counters for dumping cache");
  1089. exit (EXIT_FAILURE);
  1090. }
  1091. fprintf (stderr, "syntax %s\n", res ? "OK" : "BAD");
  1092. return res ? EXIT_SUCCESS : EXIT_FAILURE;
  1093. }
  1094. /* Load config */
  1095. if (!load_rspamd_config (rspamd_main, rspamd_main->cfg, TRUE,
  1096. RSPAMD_CONFIG_LOAD_ALL, FALSE, ucl_vars)) {
  1097. exit (EXIT_FAILURE);
  1098. }
  1099. /* Override pidfile from configuration by command line argument */
  1100. if (rspamd_pidfile != NULL) {
  1101. rspamd_main->cfg->pid_file = rspamd_pidfile;
  1102. }
  1103. /* Force debug log */
  1104. if (is_debug) {
  1105. rspamd_main->cfg->log_level = G_LOG_LEVEL_DEBUG;
  1106. }
  1107. /* Create rolling history */
  1108. rspamd_main->history = rspamd_roll_history_new (rspamd_main->server_pool,
  1109. rspamd_main->cfg->history_rows, rspamd_main->cfg);
  1110. gperf_profiler_init (rspamd_main->cfg, "main");
  1111. msg_info_main ("rspamd "
  1112. RVERSION
  1113. " is starting, build id: "
  1114. RID);
  1115. rspamd_main->cfg->cfg_name = rspamd_mempool_strdup (
  1116. rspamd_main->cfg->cfg_pool,
  1117. rspamd_main->cfg->cfg_name);
  1118. msg_info_main ("cpu features: %s",
  1119. rspamd_main->cfg->libs_ctx->crypto_ctx->cpu_extensions);
  1120. msg_info_main ("cryptobox configuration: curve25519(%s), "
  1121. "chacha20(%s), poly1305(%s), siphash(%s), blake2(%s), base64(%s)",
  1122. rspamd_main->cfg->libs_ctx->crypto_ctx->curve25519_impl,
  1123. rspamd_main->cfg->libs_ctx->crypto_ctx->chacha20_impl,
  1124. rspamd_main->cfg->libs_ctx->crypto_ctx->poly1305_impl,
  1125. rspamd_main->cfg->libs_ctx->crypto_ctx->siphash_impl,
  1126. rspamd_main->cfg->libs_ctx->crypto_ctx->blake2_impl,
  1127. rspamd_main->cfg->libs_ctx->crypto_ctx->base64_impl);
  1128. /* Daemonize */
  1129. if (!no_fork && daemon (0, 0) == -1) {
  1130. rspamd_fprintf (stderr, "Cannot daemonize\n");
  1131. exit (-errno);
  1132. }
  1133. /* Write info */
  1134. rspamd_main->pid = getpid ();
  1135. rspamd_main->type = type;
  1136. /* Ignore SIGPIPE as we handle write errors manually */
  1137. sigemptyset (&sigpipe_act.sa_mask);
  1138. sigaddset (&sigpipe_act.sa_mask, SIGPIPE);
  1139. sigpipe_act.sa_handler = SIG_IGN;
  1140. sigpipe_act.sa_flags = 0;
  1141. sigaction (SIGPIPE, &sigpipe_act, NULL);
  1142. if (rspamd_main->cfg->pid_file == NULL) {
  1143. msg_info("pid file is not specified, skipping writing it");
  1144. }
  1145. else if (rspamd_write_pid (rspamd_main) == -1) {
  1146. msg_err_main ("cannot write pid file %s", rspamd_main->cfg->pid_file);
  1147. exit (-errno);
  1148. }
  1149. /* Block signals to use sigsuspend in future */
  1150. sigprocmask (SIG_BLOCK, &signals.sa_mask, NULL);
  1151. /* Set title */
  1152. setproctitle ("main process");
  1153. /* Flush log */
  1154. rspamd_log_flush (rspamd_main->logger);
  1155. /* Open control socket if needed */
  1156. control_fd = -1;
  1157. if (rspamd_main->cfg->control_socket_path) {
  1158. if (!rspamd_parse_inet_address (&control_addr,
  1159. rspamd_main->cfg->control_socket_path,
  1160. 0)) {
  1161. msg_err_main ("cannot parse inet address %s",
  1162. rspamd_main->cfg->control_socket_path);
  1163. }
  1164. else {
  1165. control_fd = rspamd_inet_address_listen (control_addr, SOCK_STREAM,
  1166. TRUE);
  1167. if (control_fd == -1) {
  1168. msg_err_main ("cannot open control socket at path: %s",
  1169. rspamd_main->cfg->control_socket_path);
  1170. }
  1171. }
  1172. }
  1173. /* Maybe read roll history */
  1174. if (rspamd_main->cfg->history_file) {
  1175. rspamd_roll_history_load (rspamd_main->history,
  1176. rspamd_main->cfg->history_file);
  1177. }
  1178. #if defined(WITH_GPERF_TOOLS)
  1179. ProfilerStop ();
  1180. #endif
  1181. /* Spawn workers */
  1182. rspamd_main->workers = g_hash_table_new (g_direct_hash, g_direct_equal);
  1183. /* Init event base */
  1184. ev_base = event_init ();
  1185. rspamd_main->ev_base = ev_base;
  1186. /* Unblock signals */
  1187. sigemptyset (&signals.sa_mask);
  1188. sigprocmask (SIG_SETMASK, &signals.sa_mask, NULL);
  1189. /* Set events for signals */
  1190. evsignal_set (&term_ev, SIGTERM, rspamd_term_handler, rspamd_main);
  1191. event_base_set (ev_base, &term_ev);
  1192. event_add (&term_ev, NULL);
  1193. evsignal_set (&int_ev, SIGINT, rspamd_term_handler, rspamd_main);
  1194. event_base_set (ev_base, &int_ev);
  1195. event_add (&int_ev, NULL);
  1196. evsignal_set (&hup_ev, SIGHUP, rspamd_hup_handler, rspamd_main);
  1197. event_base_set (ev_base, &hup_ev);
  1198. event_add (&hup_ev, NULL);
  1199. evsignal_set (&cld_ev, SIGCHLD, rspamd_cld_handler, rspamd_main);
  1200. event_base_set (ev_base, &cld_ev);
  1201. event_add (&cld_ev, NULL);
  1202. evsignal_set (&usr1_ev, SIGUSR1, rspamd_usr1_handler, rspamd_main);
  1203. event_base_set (ev_base, &usr1_ev);
  1204. event_add (&usr1_ev, NULL);
  1205. rspamd_check_core_limits (rspamd_main);
  1206. rspamd_mempool_lock_mutex (rspamd_main->start_mtx);
  1207. spawn_workers (rspamd_main, ev_base);
  1208. rspamd_mempool_unlock_mutex (rspamd_main->start_mtx);
  1209. if (control_fd != -1) {
  1210. msg_info_main ("listening for control commands on %s",
  1211. rspamd_inet_address_to_string (control_addr));
  1212. event_set (&control_ev, control_fd, EV_READ|EV_PERSIST,
  1213. rspamd_control_handler, rspamd_main);
  1214. event_base_set (ev_base, &control_ev);
  1215. event_add (&control_ev, NULL);
  1216. }
  1217. event_base_loop (ev_base, 0);
  1218. /* We need to block signals unless children are waited for */
  1219. rspamd_worker_block_signals ();
  1220. event_del (&term_ev);
  1221. event_del (&int_ev);
  1222. event_del (&hup_ev);
  1223. event_del (&cld_ev);
  1224. event_del (&usr1_ev);
  1225. if (control_fd != -1) {
  1226. event_del (&control_ev);
  1227. close (control_fd);
  1228. }
  1229. if (getenv ("VALGRIND") != NULL) {
  1230. /* Special case if we are likely running with valgrind */
  1231. term_attempts = TERMINATION_ATTEMPTS * 10;
  1232. }
  1233. else {
  1234. term_attempts = TERMINATION_ATTEMPTS;
  1235. }
  1236. /* Check each 200 ms */
  1237. term_tv.tv_sec = 0;
  1238. term_tv.tv_usec = 200000;
  1239. /* Wait for workers termination */
  1240. g_hash_table_foreach_remove (rspamd_main->workers, wait_for_workers, NULL);
  1241. event_set (&term_ev, -1, EV_TIMEOUT|EV_PERSIST,
  1242. rspamd_final_term_handler, rspamd_main);
  1243. event_base_set (ev_base, &term_ev);
  1244. event_add (&term_ev, &term_tv);
  1245. event_base_loop (ev_base, 0);
  1246. event_del (&term_ev);
  1247. /* Maybe save roll history */
  1248. if (rspamd_main->cfg->history_file) {
  1249. rspamd_roll_history_save (rspamd_main->history,
  1250. rspamd_main->cfg->history_file);
  1251. }
  1252. msg_info_main ("terminating...");
  1253. rspamd_log_close (rspamd_main->logger);
  1254. REF_RELEASE (rspamd_main->cfg);
  1255. g_hash_table_unref (rspamd_main->spairs);
  1256. rspamd_mempool_delete (rspamd_main->server_pool);
  1257. rspamd_pidfile_close (rspamd_main->pfh);
  1258. g_free (rspamd_main);
  1259. event_base_free (ev_base);
  1260. return (res);
  1261. }