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.

16 yıl önce
9 yıl önce
9 yıl önce
16 yıl önce
9 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. * Copyright 2024 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. /*
  17. * Rspamd worker implementation
  18. */
  19. #include "config.h"
  20. #include "libutil/util.h"
  21. #include "libserver/maps/map.h"
  22. #include "libutil/upstream.h"
  23. #include "libserver/protocol.h"
  24. #include "libserver/cfg_file.h"
  25. #include "libserver/url.h"
  26. #include "libserver/dns.h"
  27. #include "libmime/message.h"
  28. #include "rspamd.h"
  29. #include "libstat/stat_api.h"
  30. #include "libserver/worker_util.h"
  31. #include "libserver/rspamd_control.h"
  32. #include "worker_private.h"
  33. #include "libserver/http/http_private.h"
  34. #include "libserver/cfg_file_private.h"
  35. #include <math.h>
  36. #include "unix-std.h"
  37. #include "lua/lua_common.h"
  38. /* 60 seconds for worker's IO */
  39. #define DEFAULT_WORKER_IO_TIMEOUT 60.0
  40. gpointer init_worker(struct rspamd_config *cfg);
  41. void start_worker(struct rspamd_worker *worker);
  42. worker_t normal_worker = {
  43. "normal", /* Name */
  44. init_worker, /* Init function */
  45. start_worker, /* Start function */
  46. RSPAMD_WORKER_HAS_SOCKET | RSPAMD_WORKER_KILLABLE | RSPAMD_WORKER_SCANNER,
  47. RSPAMD_WORKER_SOCKET_TCP, /* TCP socket */
  48. RSPAMD_WORKER_VER /* Version info */
  49. };
  50. #define msg_err_ctx(...) rspamd_default_log_function(G_LOG_LEVEL_CRITICAL, \
  51. "worker", ctx->cfg->cfg_pool->tag.uid, \
  52. RSPAMD_LOG_FUNC, \
  53. __VA_ARGS__)
  54. #define msg_warn_ctx(...) rspamd_default_log_function(G_LOG_LEVEL_WARNING, \
  55. "worker", ctx->cfg->cfg_pool->tag.uid, \
  56. RSPAMD_LOG_FUNC, \
  57. __VA_ARGS__)
  58. #define msg_info_ctx(...) rspamd_default_log_function(G_LOG_LEVEL_INFO, \
  59. "worker", ctx->cfg->cfg_pool->tag.uid, \
  60. RSPAMD_LOG_FUNC, \
  61. __VA_ARGS__)
  62. struct rspamd_worker_session {
  63. int64_t magic;
  64. struct rspamd_task *task;
  65. int fd;
  66. rspamd_inet_addr_t *addr;
  67. struct rspamd_worker_ctx *ctx;
  68. struct rspamd_http_connection *http_conn;
  69. struct rspamd_worker *worker;
  70. };
  71. /*
  72. * Reduce number of tasks proceeded
  73. */
  74. static void
  75. reduce_tasks_count(gpointer arg)
  76. {
  77. struct rspamd_worker *worker = arg;
  78. worker->nconns--;
  79. if (worker->state == rspamd_worker_wait_connections && worker->nconns == 0) {
  80. worker->state = rspamd_worker_wait_final_scripts;
  81. msg_info("performing finishing actions");
  82. if (rspamd_worker_call_finish_handlers(worker)) {
  83. worker->state = rspamd_worker_wait_final_scripts;
  84. }
  85. else {
  86. worker->state = rspamd_worker_wanna_die;
  87. }
  88. }
  89. else if (worker->state != rspamd_worker_state_running) {
  90. worker->state = rspamd_worker_wait_connections;
  91. }
  92. }
  93. static int
  94. rspamd_worker_body_handler(struct rspamd_http_connection *conn,
  95. struct rspamd_http_message *msg,
  96. const char *chunk, gsize len)
  97. {
  98. struct rspamd_worker_session *session = (struct rspamd_worker_session *) conn->ud;
  99. struct rspamd_task *task;
  100. struct rspamd_worker_ctx *ctx;
  101. const rspamd_ftok_t *hv_tok;
  102. gboolean debug_mempool = FALSE;
  103. ctx = session->ctx;
  104. /* Check debug */
  105. if ((hv_tok = rspamd_http_message_find_header(msg, "Memory")) != NULL) {
  106. rspamd_ftok_t cmp;
  107. RSPAMD_FTOK_ASSIGN(&cmp, "debug");
  108. if (rspamd_ftok_cmp(hv_tok, &cmp) == 0) {
  109. debug_mempool = TRUE;
  110. }
  111. }
  112. task = rspamd_task_new(session->worker,
  113. session->ctx->cfg, NULL, session->ctx->lang_det,
  114. session->ctx->event_loop,
  115. debug_mempool);
  116. session->task = task;
  117. msg_info_task("accepted connection from %s port %d, task ptr: %p",
  118. rspamd_inet_address_to_string(session->addr),
  119. rspamd_inet_address_get_port(session->addr),
  120. task);
  121. /* Copy some variables */
  122. if (ctx->is_mime) {
  123. task->flags |= RSPAMD_TASK_FLAG_MIME;
  124. }
  125. else {
  126. task->flags &= ~RSPAMD_TASK_FLAG_MIME;
  127. }
  128. /* We actually transfer ownership from session to task here */
  129. task->sock = session->fd;
  130. task->client_addr = session->addr;
  131. task->worker = session->worker;
  132. task->http_conn = session->http_conn;
  133. task->resolver = ctx->resolver;
  134. session->worker->nconns++;
  135. rspamd_mempool_add_destructor(task->task_pool,
  136. (rspamd_mempool_destruct_t) reduce_tasks_count,
  137. session->worker);
  138. /* Session memory is also now handled by task */
  139. rspamd_mempool_add_destructor(task->task_pool,
  140. (rspamd_mempool_destruct_t) g_free,
  141. session);
  142. /* Set up async session */
  143. task->s = rspamd_session_create(task->task_pool, rspamd_task_fin,
  144. NULL, (event_finalizer_t) rspamd_task_free, task);
  145. if (!rspamd_protocol_handle_request(task, msg)) {
  146. msg_err_task("cannot handle request: %e", task->err);
  147. task->flags |= RSPAMD_TASK_FLAG_SKIP;
  148. }
  149. else {
  150. if (task->cmd == CMD_PING) {
  151. task->flags |= RSPAMD_TASK_FLAG_SKIP;
  152. }
  153. else {
  154. if (!rspamd_task_load_message(task, msg, chunk, len)) {
  155. msg_err_task("cannot load message: %e", task->err);
  156. task->flags |= RSPAMD_TASK_FLAG_SKIP;
  157. }
  158. }
  159. }
  160. /* Set global timeout for the task */
  161. if (!isnan(ctx->task_timeout) && ctx->task_timeout > 0.0) {
  162. task->timeout_ev.data = task;
  163. ev_timer_init(&task->timeout_ev, rspamd_task_timeout,
  164. ctx->task_timeout,
  165. ctx->task_timeout);
  166. ev_set_priority(&task->timeout_ev, EV_MAXPRI);
  167. ev_timer_start(task->event_loop, &task->timeout_ev);
  168. }
  169. /* Set socket guard */
  170. task->guard_ev.data = task;
  171. ev_io_init(&task->guard_ev,
  172. rspamd_worker_guard_handler,
  173. task->sock, EV_READ);
  174. ev_io_start(task->event_loop, &task->guard_ev);
  175. rspamd_task_process(task, RSPAMD_TASK_PROCESS_ALL);
  176. return 0;
  177. }
  178. static void
  179. rspamd_worker_error_handler(struct rspamd_http_connection *conn, GError *err)
  180. {
  181. struct rspamd_worker_session *session = (struct rspamd_worker_session *) conn->ud;
  182. struct rspamd_task *task;
  183. struct rspamd_http_message *msg;
  184. rspamd_fstring_t *reply;
  185. /*
  186. * This function can be called with both struct rspamd_worker_session *
  187. * and struct rspamd_task *
  188. *
  189. * The first case is when we read message and it is controlled by this code;
  190. * the second case is when a reply is written and we do not control it normally,
  191. * as it is managed by `rspamd_protocol_reply` in protocol.c
  192. *
  193. * Hence, we need to distinguish our arguments...
  194. *
  195. * The approach here is simple:
  196. * - struct rspamd_worker_session starts with int64_t `magic` and we set it to
  197. * MAX_INT64
  198. * - struct rspamd_task starts with a pointer (or pointer + command on 32 bit system)
  199. *
  200. * The idea is simple: no sane pointer would reach MAX_INT64, so if this field
  201. * is MAX_INT64 then it is our session, and if it is not then it is a task.
  202. */
  203. if (session->magic == G_MAXINT64) {
  204. task = session->task;
  205. }
  206. else {
  207. task = (struct rspamd_task *) conn->ud;
  208. }
  209. if (task) {
  210. msg_info_task("abnormally closing connection from: %s, error: %e",
  211. rspamd_inet_address_to_string_pretty(task->client_addr), err);
  212. if (task->processed_stages & RSPAMD_TASK_STAGE_REPLIED) {
  213. /* Terminate session immediately */
  214. rspamd_session_destroy(task->s);
  215. }
  216. else {
  217. task->processed_stages |= RSPAMD_TASK_STAGE_REPLIED;
  218. msg = rspamd_http_new_message(HTTP_RESPONSE);
  219. if (err) {
  220. msg->status = rspamd_fstring_new_init(err->message,
  221. strlen(err->message));
  222. msg->code = err->code;
  223. }
  224. else {
  225. msg->status = rspamd_fstring_new_init("Internal error",
  226. strlen("Internal error"));
  227. msg->code = 500;
  228. }
  229. msg->date = time(NULL);
  230. reply = rspamd_fstring_sized_new(msg->status->len + 16);
  231. rspamd_printf_fstring(&reply, "{\"error\":\"%V\"}", msg->status);
  232. rspamd_http_message_set_body_from_fstring_steal(msg, reply);
  233. rspamd_http_connection_reset(task->http_conn);
  234. /* Use a shorter timeout for writing reply */
  235. rspamd_http_connection_write_message(task->http_conn,
  236. msg,
  237. NULL,
  238. "application/json",
  239. task,
  240. session->ctx->timeout / 10.0);
  241. }
  242. }
  243. else {
  244. /* If there was no task, then session is unmanaged */
  245. msg_info("no data received from: %s, error: %e",
  246. rspamd_inet_address_to_string_pretty(session->addr), err);
  247. rspamd_http_connection_reset(session->http_conn);
  248. rspamd_http_connection_unref(session->http_conn);
  249. rspamd_inet_address_free(session->addr);
  250. close(session->fd);
  251. g_free(session);
  252. }
  253. }
  254. static int
  255. rspamd_worker_finish_handler(struct rspamd_http_connection *conn,
  256. struct rspamd_http_message *msg)
  257. {
  258. struct rspamd_worker_session *session = (struct rspamd_worker_session *) conn->ud;
  259. struct rspamd_task *task;
  260. /* Read the comment to rspamd_worker_error_handler */
  261. if (session->magic == G_MAXINT64) {
  262. task = session->task;
  263. }
  264. else {
  265. task = (struct rspamd_task *) conn->ud;
  266. }
  267. if (task) {
  268. if (task->processed_stages & RSPAMD_TASK_STAGE_REPLIED) {
  269. /* We are done here */
  270. msg_debug_task("normally closing connection from: %s",
  271. rspamd_inet_address_to_string(task->client_addr));
  272. rspamd_session_destroy(task->s);
  273. }
  274. else if (task->processed_stages & RSPAMD_TASK_STAGE_DONE) {
  275. rspamd_session_pending(task->s);
  276. }
  277. }
  278. else {
  279. /* If there was no task, then session is unmanaged */
  280. msg_info("no data received from: %s, closing connection",
  281. rspamd_inet_address_to_string_pretty(session->addr));
  282. rspamd_inet_address_free(session->addr);
  283. rspamd_http_connection_reset(session->http_conn);
  284. rspamd_http_connection_unref(session->http_conn);
  285. close(session->fd);
  286. g_free(session);
  287. }
  288. return 0;
  289. }
  290. /*
  291. * Accept new connection and construct task
  292. */
  293. static void
  294. accept_socket(EV_P_ ev_io *w, int revents)
  295. {
  296. struct rspamd_worker *worker = (struct rspamd_worker *) w->data;
  297. struct rspamd_worker_ctx *ctx;
  298. struct rspamd_worker_session *session;
  299. rspamd_inet_addr_t *addr = NULL;
  300. int nfd, http_opts = 0;
  301. ctx = worker->ctx;
  302. if (ctx->max_tasks != 0 && worker->nconns > ctx->max_tasks) {
  303. msg_info_ctx("current tasks is now: %uD while maximum is: %uD",
  304. worker->nconns,
  305. ctx->max_tasks);
  306. return;
  307. }
  308. if ((nfd =
  309. rspamd_accept_from_socket(w->fd, &addr,
  310. rspamd_worker_throttle_accept_events, worker->accept_events)) == -1) {
  311. msg_warn_ctx("accept failed: %s", strerror(errno));
  312. return;
  313. }
  314. /* Check for EAGAIN */
  315. if (nfd == 0) {
  316. rspamd_inet_address_free(addr);
  317. return;
  318. }
  319. session = g_malloc0(sizeof(*session));
  320. session->magic = G_MAXINT64;
  321. session->addr = addr;
  322. session->fd = nfd;
  323. session->ctx = ctx;
  324. session->worker = worker;
  325. if (ctx->encrypted_only && !rspamd_inet_address_is_local(addr)) {
  326. http_opts = RSPAMD_HTTP_REQUIRE_ENCRYPTION;
  327. }
  328. session->http_conn = rspamd_http_connection_new_server(
  329. ctx->http_ctx,
  330. nfd,
  331. rspamd_worker_body_handler,
  332. rspamd_worker_error_handler,
  333. rspamd_worker_finish_handler,
  334. http_opts);
  335. worker->srv->stat->connections_count++;
  336. rspamd_http_connection_set_max_size(session->http_conn,
  337. ctx->cfg->max_message);
  338. if (ctx->key) {
  339. rspamd_http_connection_set_key(session->http_conn, ctx->key);
  340. }
  341. rspamd_http_connection_read_message(session->http_conn,
  342. session,
  343. ctx->timeout);
  344. }
  345. gpointer
  346. init_worker(struct rspamd_config *cfg)
  347. {
  348. struct rspamd_worker_ctx *ctx;
  349. GQuark type;
  350. type = g_quark_try_string("normal");
  351. ctx = rspamd_mempool_alloc0(cfg->cfg_pool,
  352. sizeof(struct rspamd_worker_ctx));
  353. ctx->magic = rspamd_worker_magic;
  354. ctx->is_mime = TRUE;
  355. ctx->timeout = DEFAULT_WORKER_IO_TIMEOUT;
  356. ctx->cfg = cfg;
  357. ctx->task_timeout = NAN;
  358. rspamd_rcl_register_worker_option(cfg,
  359. type,
  360. "mime",
  361. rspamd_rcl_parse_struct_boolean,
  362. ctx,
  363. G_STRUCT_OFFSET(struct rspamd_worker_ctx, is_mime),
  364. 0,
  365. "Set to `false` if this worker is intended to work with non-MIME messages");
  366. rspamd_rcl_register_worker_option(cfg,
  367. type,
  368. "encrypted_only",
  369. rspamd_rcl_parse_struct_boolean,
  370. ctx,
  371. G_STRUCT_OFFSET(struct rspamd_worker_ctx, encrypted_only),
  372. 0,
  373. "Allow only encrypted connections");
  374. rspamd_rcl_register_worker_option(cfg,
  375. type,
  376. "timeout",
  377. rspamd_rcl_parse_struct_time,
  378. ctx,
  379. G_STRUCT_OFFSET(struct rspamd_worker_ctx,
  380. timeout),
  381. RSPAMD_CL_FLAG_TIME_FLOAT,
  382. "Protocol IO timeout");
  383. rspamd_rcl_register_worker_option(cfg,
  384. type,
  385. "task_timeout",
  386. rspamd_rcl_parse_struct_time,
  387. ctx,
  388. G_STRUCT_OFFSET(struct rspamd_worker_ctx,
  389. task_timeout),
  390. RSPAMD_CL_FLAG_TIME_FLOAT,
  391. "Maximum task processing time, default: 8.0 seconds");
  392. rspamd_rcl_register_worker_option(cfg,
  393. type,
  394. "max_tasks",
  395. rspamd_rcl_parse_struct_integer,
  396. ctx,
  397. G_STRUCT_OFFSET(struct rspamd_worker_ctx,
  398. max_tasks),
  399. RSPAMD_CL_FLAG_INT_32,
  400. "Maximum count of parallel tasks processed by a single worker process");
  401. rspamd_rcl_register_worker_option(cfg,
  402. type,
  403. "keypair",
  404. rspamd_rcl_parse_struct_keypair,
  405. ctx,
  406. G_STRUCT_OFFSET(struct rspamd_worker_ctx,
  407. key),
  408. 0,
  409. "Encryption keypair");
  410. return ctx;
  411. }
  412. /*
  413. * Start worker process
  414. */
  415. __attribute__((noreturn)) void
  416. start_worker(struct rspamd_worker *worker)
  417. {
  418. struct rspamd_worker_ctx *ctx = worker->ctx;
  419. gboolean is_controller = FALSE;
  420. g_assert(rspamd_worker_check_context(worker->ctx, rspamd_worker_magic));
  421. ctx->cfg = worker->srv->cfg;
  422. ctx->event_loop = rspamd_prepare_worker(worker, "normal", accept_socket);
  423. rspamd_symcache_start_refresh(worker->srv->cfg->cache, ctx->event_loop,
  424. worker);
  425. ctx->task_timeout = rspamd_worker_check_and_adjust_timeout(ctx->cfg, ctx->task_timeout);
  426. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  427. ctx->event_loop,
  428. worker->srv->cfg);
  429. rspamd_upstreams_library_config(worker->srv->cfg, ctx->cfg->ups_ctx,
  430. ctx->event_loop, ctx->resolver->r);
  431. ctx->http_ctx = rspamd_http_context_create(ctx->cfg, ctx->event_loop,
  432. ctx->cfg->ups_ctx);
  433. rspamd_mempool_add_destructor(ctx->cfg->cfg_pool,
  434. (rspamd_mempool_destruct_t) rspamd_http_context_free,
  435. ctx->http_ctx);
  436. rspamd_worker_init_scanner(worker, ctx->event_loop, ctx->resolver,
  437. &ctx->lang_det);
  438. is_controller = rspamd_worker_check_controller_presence(worker);
  439. if (is_controller) {
  440. rspamd_worker_init_controller(worker, NULL);
  441. }
  442. else {
  443. rspamd_map_watch(worker->srv->cfg, ctx->event_loop, ctx->resolver,
  444. worker, RSPAMD_MAP_WATCH_SCANNER);
  445. }
  446. rspamd_lua_run_postloads(ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  447. worker);
  448. ev_loop(ctx->event_loop, 0);
  449. rspamd_worker_block_signals();
  450. if (is_controller) {
  451. rspamd_controller_on_terminate(worker, NULL);
  452. }
  453. rspamd_stat_close();
  454. REF_RELEASE(ctx->cfg);
  455. rspamd_log_close(worker->srv->logger);
  456. rspamd_unset_crash_handler(worker->srv);
  457. exit(EXIT_SUCCESS);
  458. }