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.

hs_helper.c 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 "libutil/util.h"
  18. #include "libserver/cfg_file.h"
  19. #include "libserver/cfg_rcl.h"
  20. #include "libserver/worker_util.h"
  21. #include "libserver/rspamd_control.h"
  22. #include "unix-std.h"
  23. #ifdef HAVE_GLOB_H
  24. #include <glob.h>
  25. #endif
  26. static gpointer init_hs_helper (struct rspamd_config *cfg);
  27. __attribute__((noreturn)) static void start_hs_helper (struct rspamd_worker *worker);
  28. worker_t hs_helper_worker = {
  29. "hs_helper", /* Name */
  30. init_hs_helper, /* Init function */
  31. start_hs_helper, /* Start function */
  32. RSPAMD_WORKER_UNIQUE|RSPAMD_WORKER_KILLABLE|RSPAMD_WORKER_ALWAYS_START|RSPAMD_WORKER_NO_TERMINATE_DELAY,
  33. RSPAMD_WORKER_SOCKET_NONE,
  34. RSPAMD_WORKER_VER /* Version info */
  35. };
  36. static const gdouble default_max_time = 1.0;
  37. static const gdouble default_recompile_time = 60.0;
  38. static const guint64 rspamd_hs_helper_magic = 0x22d310157a2288a0ULL;
  39. /*
  40. * Worker's context
  41. */
  42. struct hs_helper_ctx {
  43. guint64 magic;
  44. /* Events base */
  45. struct ev_loop *event_loop;
  46. /* DNS resolver */
  47. struct rspamd_dns_resolver *resolver;
  48. /* Config */
  49. struct rspamd_config *cfg;
  50. /* END OF COMMON PART */
  51. gchar *hs_dir;
  52. gboolean loaded;
  53. gdouble max_time;
  54. gdouble recompile_time;
  55. ev_timer recompile_timer;
  56. };
  57. static gpointer
  58. init_hs_helper (struct rspamd_config *cfg)
  59. {
  60. struct hs_helper_ctx *ctx;
  61. GQuark type;
  62. type = g_quark_try_string ("hs_helper");
  63. ctx = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*ctx));
  64. ctx->magic = rspamd_hs_helper_magic;
  65. ctx->cfg = cfg;
  66. ctx->hs_dir = NULL;
  67. ctx->max_time = default_max_time;
  68. ctx->recompile_time = default_recompile_time;
  69. rspamd_rcl_register_worker_option (cfg,
  70. type,
  71. "cache_dir",
  72. rspamd_rcl_parse_struct_string,
  73. ctx,
  74. G_STRUCT_OFFSET (struct hs_helper_ctx, hs_dir),
  75. 0,
  76. "Directory where to save hyperscan compiled expressions");
  77. rspamd_rcl_register_worker_option (cfg,
  78. type,
  79. "max_time",
  80. rspamd_rcl_parse_struct_time,
  81. ctx,
  82. G_STRUCT_OFFSET (struct hs_helper_ctx, max_time),
  83. RSPAMD_CL_FLAG_TIME_FLOAT,
  84. "Maximum time to wait for compilation of a single expression");
  85. rspamd_rcl_register_worker_option (cfg,
  86. type,
  87. "recompile",
  88. rspamd_rcl_parse_struct_time,
  89. ctx,
  90. G_STRUCT_OFFSET (struct hs_helper_ctx, recompile_time),
  91. RSPAMD_CL_FLAG_TIME_FLOAT,
  92. "Time between recompilation checks");
  93. rspamd_rcl_register_worker_option (cfg,
  94. type,
  95. "timeout",
  96. rspamd_rcl_parse_struct_time,
  97. ctx,
  98. G_STRUCT_OFFSET (struct hs_helper_ctx, max_time),
  99. RSPAMD_CL_FLAG_TIME_FLOAT,
  100. "Maximum time to wait for compilation of a single expression");
  101. return ctx;
  102. }
  103. /**
  104. * Clean
  105. */
  106. static gboolean
  107. rspamd_hs_helper_cleanup_dir (struct hs_helper_ctx *ctx, gboolean forced)
  108. {
  109. struct stat st;
  110. glob_t globbuf;
  111. guint len, i;
  112. gint rc;
  113. gchar *pattern;
  114. gboolean ret = TRUE;
  115. pid_t our_pid = getpid ();
  116. if (stat (ctx->hs_dir, &st) == -1) {
  117. msg_err ("cannot stat path %s, %s",
  118. ctx->hs_dir,
  119. strerror (errno));
  120. return FALSE;
  121. }
  122. globbuf.gl_offs = 0;
  123. /*
  124. * We reuse this buffer for .new patterns as well, so allocate with some
  125. * margin
  126. */
  127. len = strlen (ctx->hs_dir) + 1 + sizeof ("*.hs.new") + 2;
  128. pattern = g_malloc (len);
  129. rspamd_snprintf (pattern, len, "%s%c%s", ctx->hs_dir, G_DIR_SEPARATOR, "*.hs");
  130. if ((rc = glob (pattern, 0, NULL, &globbuf)) == 0) {
  131. for (i = 0; i < globbuf.gl_pathc; i++) {
  132. GError *err = NULL;
  133. if (forced) {
  134. g_set_error(&err, g_quark_from_static_string ("re_cache"),
  135. 0, "forced removal");
  136. }
  137. if (forced ||
  138. !rspamd_re_cache_is_valid_hyperscan_file (ctx->cfg->re_cache,
  139. globbuf.gl_pathv[i], TRUE, TRUE, &err)) {
  140. if (unlink (globbuf.gl_pathv[i]) == -1) {
  141. msg_err ("cannot unlink %s: %s; reason for expiration: %e", globbuf.gl_pathv[i],
  142. strerror(errno), err);
  143. ret = FALSE;
  144. }
  145. else {
  146. msg_notice ("successfully removed outdated hyperscan file: %s; reason for expiration: %e",
  147. globbuf.gl_pathv[i], err);
  148. }
  149. }
  150. if (err) {
  151. g_error_free(err);
  152. }
  153. }
  154. }
  155. else if (rc != GLOB_NOMATCH) {
  156. msg_err ("glob %s failed: %s", pattern, strerror (errno));
  157. ret = FALSE;
  158. }
  159. globfree (&globbuf);
  160. memset (&globbuf, 0, sizeof (globbuf));
  161. rspamd_snprintf (pattern, len, "%s%c%s", ctx->hs_dir, G_DIR_SEPARATOR, "*.hs.new");
  162. if ((rc = glob (pattern, 0, NULL, &globbuf)) == 0) {
  163. for (i = 0; i < globbuf.gl_pathc; i++) {
  164. /* Check if we have a pid in the filename */
  165. const gchar *end_num = globbuf.gl_pathv[i] +
  166. strlen (globbuf.gl_pathv[i]) - (sizeof (".hs.new") - 1);
  167. const gchar *p = end_num - 1;
  168. pid_t foreign_pid = -1;
  169. while (p > globbuf.gl_pathv[i]) {
  170. if (g_ascii_isdigit (*p)) {
  171. p --;
  172. }
  173. else {
  174. p ++;
  175. break;
  176. }
  177. }
  178. gulong ul;
  179. if (p < end_num && rspamd_strtoul (p, end_num - p, &ul)) {
  180. foreign_pid = ul;
  181. }
  182. /*
  183. * Remove only files that was left by us or some non-existing process
  184. * There could be another race condition but it would just leave
  185. * extra files which is relatively innocent?
  186. */
  187. if (foreign_pid == -1 || foreign_pid == our_pid || kill (foreign_pid, 0) == -1) {
  188. if (unlink(globbuf.gl_pathv[i]) == -1) {
  189. msg_err ("cannot unlink %s: %s", globbuf.gl_pathv[i],
  190. strerror(errno));
  191. ret = FALSE;
  192. }
  193. else {
  194. msg_notice ("successfully removed outdated hyperscan temporary file: %s; "
  195. "pid of the file creator process: %P",
  196. globbuf.gl_pathv[i],
  197. foreign_pid);
  198. }
  199. }
  200. else {
  201. msg_notice ("skip removal of the hyperscan temporary file: %s; "
  202. "pid of the file creator process: %P",
  203. globbuf.gl_pathv[i],
  204. foreign_pid);
  205. }
  206. }
  207. }
  208. else if (rc != GLOB_NOMATCH) {
  209. msg_err ("glob %s failed: %s", pattern, strerror (errno));
  210. ret = FALSE;
  211. }
  212. globfree (&globbuf);
  213. g_free (pattern);
  214. return ret;
  215. }
  216. /* Bad hack, but who cares */
  217. static gboolean hack_global_forced;
  218. static void
  219. rspamd_rs_delayed_cb (EV_P_ ev_timer *w, int revents)
  220. {
  221. struct rspamd_worker *worker = (struct rspamd_worker *)w->data;
  222. static struct rspamd_srv_command srv_cmd;
  223. struct hs_helper_ctx *ctx;
  224. ctx = (struct hs_helper_ctx *)worker->ctx;
  225. memset (&srv_cmd, 0, sizeof (srv_cmd));
  226. srv_cmd.type = RSPAMD_SRV_HYPERSCAN_LOADED;
  227. rspamd_strlcpy (srv_cmd.cmd.hs_loaded.cache_dir, ctx->hs_dir,
  228. sizeof (srv_cmd.cmd.hs_loaded.cache_dir));
  229. srv_cmd.cmd.hs_loaded.forced = hack_global_forced;
  230. hack_global_forced = FALSE;
  231. rspamd_srv_send_command (worker,
  232. ctx->event_loop, &srv_cmd, -1, NULL, NULL);
  233. ev_timer_stop (EV_A_ w);
  234. g_free (w);
  235. ev_timer_again (EV_A_ &ctx->recompile_timer);
  236. }
  237. static void
  238. rspamd_rs_compile_cb (guint ncompiled, GError *err, void *cbd)
  239. {
  240. struct rspamd_worker *worker = (struct rspamd_worker *)cbd;
  241. ev_timer *tm;
  242. ev_tstamp when = 0.0;
  243. struct hs_helper_ctx *ctx;
  244. ctx = (struct hs_helper_ctx *)worker->ctx;
  245. if (err != NULL) {
  246. /* Failed to compile: log and go out */
  247. msg_err ("cannot compile Hyperscan database: %e", err);
  248. return;
  249. }
  250. if (ncompiled > 0) {
  251. /* Enforce update for other workers */
  252. hack_global_forced = TRUE;
  253. }
  254. /*
  255. * Do not send notification unless all other workers are started
  256. * XXX: now we just sleep for 1 seconds to ensure that
  257. */
  258. if (!ctx->loaded) {
  259. when = 1.0; /* Postpone */
  260. ctx->loaded = TRUE;
  261. msg_info ("compiled %d regular expressions to the hyperscan tree, "
  262. "postpone loaded notification for %.0f seconds to avoid races",
  263. ncompiled,
  264. when);
  265. }
  266. else {
  267. msg_info ("compiled %d regular expressions to the hyperscan tree, "
  268. "send loaded notification",
  269. ncompiled);
  270. }
  271. tm = g_malloc0 (sizeof (*tm));
  272. tm->data = (void *)worker;
  273. ev_timer_init (tm, rspamd_rs_delayed_cb, when, 0);
  274. ev_timer_start (ctx->event_loop, tm);
  275. }
  276. static gboolean
  277. rspamd_rs_compile (struct hs_helper_ctx *ctx, struct rspamd_worker *worker,
  278. gboolean forced)
  279. {
  280. #if !defined(__aarch64__) && !defined(__powerpc64__)
  281. if (!(ctx->cfg->libs_ctx->crypto_ctx->cpu_config & CPUID_SSSE3)) {
  282. msg_warn ("CPU doesn't have SSSE3 instructions set "
  283. "required for hyperscan, disable hyperscan compilation");
  284. return FALSE;
  285. }
  286. #endif
  287. if (!rspamd_hs_helper_cleanup_dir (ctx, forced)) {
  288. msg_warn ("cannot cleanup cache dir '%s'", ctx->hs_dir);
  289. }
  290. hack_global_forced = forced; /* killmeplease */
  291. rspamd_re_cache_compile_hyperscan (ctx->cfg->re_cache,
  292. ctx->hs_dir, ctx->max_time, !forced,
  293. ctx->event_loop,
  294. rspamd_rs_compile_cb,
  295. (void *)worker);
  296. return TRUE;
  297. }
  298. static gboolean
  299. rspamd_hs_helper_reload (struct rspamd_main *rspamd_main,
  300. struct rspamd_worker *worker, gint fd,
  301. gint attached_fd,
  302. struct rspamd_control_command *cmd,
  303. gpointer ud)
  304. {
  305. struct rspamd_control_reply rep;
  306. struct hs_helper_ctx *ctx = ud;
  307. msg_info ("recompiling hyperscan expressions after receiving reload command");
  308. memset (&rep, 0, sizeof (rep));
  309. rep.type = RSPAMD_CONTROL_RECOMPILE;
  310. rep.reply.recompile.status = 0;
  311. /* We write reply before actual recompilation as it takes a lot of time */
  312. if (write (fd, &rep, sizeof (rep)) != sizeof (rep)) {
  313. msg_err ("cannot write reply to the control socket: %s",
  314. strerror (errno));
  315. }
  316. /* Stop recompile */
  317. ev_timer_stop (ctx->event_loop, &ctx->recompile_timer);
  318. rspamd_rs_compile (ctx, worker, TRUE);
  319. return TRUE;
  320. }
  321. static void
  322. rspamd_hs_helper_timer (EV_P_ ev_timer *w, int revents)
  323. {
  324. struct rspamd_worker *worker = (struct rspamd_worker *)w->data;
  325. struct hs_helper_ctx *ctx;
  326. double tim;
  327. ctx = worker->ctx;
  328. tim = rspamd_time_jitter (ctx->recompile_time, 0);
  329. w->repeat = tim;
  330. rspamd_rs_compile (ctx, worker, FALSE);
  331. }
  332. static void
  333. start_hs_helper (struct rspamd_worker *worker)
  334. {
  335. struct hs_helper_ctx *ctx = worker->ctx;
  336. double tim;
  337. g_assert (rspamd_worker_check_context (worker->ctx, rspamd_hs_helper_magic));
  338. ctx->cfg = worker->srv->cfg;
  339. if (ctx->hs_dir == NULL) {
  340. ctx->hs_dir = ctx->cfg->hs_cache_dir;
  341. }
  342. if (ctx->hs_dir == NULL) {
  343. ctx->hs_dir = RSPAMD_DBDIR "/";
  344. }
  345. ctx->event_loop = rspamd_prepare_worker (worker,
  346. "hs_helper",
  347. NULL);
  348. if (!rspamd_rs_compile (ctx, worker, FALSE)) {
  349. /* Tell main not to respawn more workers */
  350. exit (EXIT_SUCCESS);
  351. }
  352. rspamd_control_worker_add_cmd_handler (worker, RSPAMD_CONTROL_RECOMPILE,
  353. rspamd_hs_helper_reload, ctx);
  354. ctx->recompile_timer.data = worker;
  355. tim = rspamd_time_jitter (ctx->recompile_time, 0);
  356. ev_timer_init (&ctx->recompile_timer, rspamd_hs_helper_timer, tim, 0.0);
  357. ev_timer_start (ctx->event_loop, &ctx->recompile_timer);
  358. ev_loop (ctx->event_loop, 0);
  359. rspamd_worker_block_signals ();
  360. rspamd_log_close (worker->srv->logger);
  361. REF_RELEASE (ctx->cfg);
  362. rspamd_unset_crash_handler (worker->srv);
  363. exit (EXIT_SUCCESS);
  364. }