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

rspamd.c 40KB

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