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

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