Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

lua_repl.c 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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 "rspamadm.h"
  18. #include "libutil/http.h"
  19. #include "libutil/http_private.h"
  20. #include "printf.h"
  21. #include "lua/lua_common.h"
  22. #include "lua/lua_thread_pool.h"
  23. #include "message.h"
  24. #include "unix-std.h"
  25. #include "linenoise.h"
  26. #include "worker_util.h"
  27. #ifdef WITH_LUAJIT
  28. #include <luajit.h>
  29. #endif
  30. static gchar **paths = NULL;
  31. static gchar **scripts = NULL;
  32. static gchar **lua_args = NULL;
  33. static gchar *histfile = NULL;
  34. static guint max_history = 2000;
  35. static gchar *serve = NULL;
  36. static gchar *exec_line = NULL;
  37. static gint batch = -1;
  38. static gboolean per_line = FALSE;
  39. extern struct rspamd_async_session *rspamadm_session;
  40. static const char *default_history_file = ".rspamd_repl.hist";
  41. #ifdef WITH_LUAJIT
  42. #define MAIN_PROMPT LUAJIT_VERSION "> "
  43. #else
  44. #define MAIN_PROMPT LUA_VERSION "> "
  45. #endif
  46. #define MULTILINE_PROMPT "... "
  47. static void rspamadm_lua (gint argc, gchar **argv,
  48. const struct rspamadm_command *cmd);
  49. static const char *rspamadm_lua_help (gboolean full_help,
  50. const struct rspamadm_command *cmd);
  51. struct rspamadm_command lua_command = {
  52. .name = "lua",
  53. .flags = 0,
  54. .help = rspamadm_lua_help,
  55. .run = rspamadm_lua,
  56. .lua_subrs = NULL,
  57. };
  58. /*
  59. * Dot commands
  60. */
  61. typedef void (*rspamadm_lua_dot_handler)(lua_State *L, gint argc, gchar **argv);
  62. struct rspamadm_lua_dot_command {
  63. const gchar *name;
  64. const gchar *description;
  65. rspamadm_lua_dot_handler handler;
  66. };
  67. static void rspamadm_lua_help_handler (lua_State *L, gint argc, gchar **argv);
  68. static void rspamadm_lua_load_handler (lua_State *L, gint argc, gchar **argv);
  69. static void rspamadm_lua_exec_handler (lua_State *L, gint argc, gchar **argv);
  70. static void rspamadm_lua_message_handler (lua_State *L, gint argc, gchar **argv);
  71. static void lua_thread_error_cb (struct thread_entry *thread, int ret, const char *msg);
  72. static void lua_thread_finish_cb (struct thread_entry *thread, int ret);
  73. static struct rspamadm_lua_dot_command cmds[] = {
  74. {
  75. .name = "help",
  76. .description = "shows help for commands",
  77. .handler = rspamadm_lua_help_handler
  78. },
  79. {
  80. .name = "load",
  81. .description = "load lua file",
  82. .handler = rspamadm_lua_load_handler
  83. },
  84. {
  85. .name = "exec",
  86. .description = "exec lua file",
  87. .handler = rspamadm_lua_exec_handler
  88. },
  89. {
  90. .name = "message",
  91. .description = "scans message using specified callback: .message <callback_name> <file>...",
  92. .handler = rspamadm_lua_message_handler
  93. },
  94. };
  95. static GHashTable *cmds_hash = NULL;
  96. static GOptionEntry entries[] = {
  97. {"script", 's', 0, G_OPTION_ARG_STRING_ARRAY, &scripts,
  98. "Load specified scripts", NULL},
  99. {"path", 'P', 0, G_OPTION_ARG_STRING_ARRAY, &paths,
  100. "Add specified paths to lua paths", NULL},
  101. {"history-file", 'H', 0, G_OPTION_ARG_FILENAME, &histfile,
  102. "Load history from the specified file", NULL},
  103. {"max-history", 'm', 0, G_OPTION_ARG_INT, &max_history,
  104. "Store this number of history entries", NULL},
  105. {"serve", 'S', 0, G_OPTION_ARG_STRING, &serve,
  106. "Serve http lua server", NULL},
  107. {"batch", 'b', 0, G_OPTION_ARG_NONE, &batch,
  108. "Batch execution mode", NULL},
  109. {"per-line", 'p', 0, G_OPTION_ARG_NONE, &per_line,
  110. "Pass each line of input to the specified lua script", NULL},
  111. {"exec", 'e', 0, G_OPTION_ARG_STRING, &exec_line,
  112. "Execute specified script", NULL},
  113. {"args", 'a', 0, G_OPTION_ARG_STRING_ARRAY, &lua_args,
  114. "Arguments to pass to Lua", NULL},
  115. {NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL}
  116. };
  117. static const char *
  118. rspamadm_lua_help (gboolean full_help, const struct rspamadm_command *cmd)
  119. {
  120. const char *help_str;
  121. if (full_help) {
  122. help_str = "Run lua read/execute/print loop\n\n"
  123. "Usage: rspamadm lua [-P paths] [-s scripts]\n"
  124. "Where options are:\n\n"
  125. "-P: add additional lua paths (may be repeated)\n"
  126. "-p: split input to lines and feed each line to the script\n"
  127. "-s: load scripts on start from specified files (may be repeated)\n"
  128. "-S: listen on a specified address as HTTP server\n"
  129. "-a: pass argument to lua (may be repeated)\n"
  130. "-e: execute script specified in command line"
  131. "--help: shows available options and commands";
  132. }
  133. else {
  134. help_str = "Run LUA interpreter";
  135. }
  136. return help_str;
  137. }
  138. static void
  139. rspamadm_lua_add_path (lua_State *L, const gchar *path)
  140. {
  141. const gchar *old_path;
  142. gsize len;
  143. GString *new_path;
  144. lua_getglobal (L, "package");
  145. lua_getfield (L, -1, "path");
  146. old_path = luaL_checklstring (L, -1, &len);
  147. new_path = g_string_sized_new (len + strlen (path) + sizeof("/?.lua"));
  148. if (strstr (path, "?.lua") == NULL) {
  149. rspamd_printf_gstring (new_path, "%s/?.lua;%s", path, old_path);
  150. }
  151. else {
  152. rspamd_printf_gstring (new_path, "%s;%s", path, old_path);
  153. }
  154. lua_pushlstring (L, new_path->str, new_path->len);
  155. lua_setfield (L, -2, "path");
  156. lua_settop (L, 0);
  157. g_string_free (new_path, TRUE);
  158. }
  159. static void
  160. lua_thread_finish_cb (struct thread_entry *thread, int ret)
  161. {
  162. struct lua_call_data *cd = thread->cd;
  163. cd->ret = ret;
  164. }
  165. static void
  166. lua_thread_error_cb (struct thread_entry *thread, int ret, const char *msg)
  167. {
  168. struct lua_call_data *cd = thread->cd;
  169. rspamd_fprintf (stderr, "call failed: %s\n", msg);
  170. cd->ret = ret;
  171. }
  172. static void
  173. lua_thread_str_error_cb (struct thread_entry *thread, int ret, const char *msg)
  174. {
  175. struct lua_call_data *cd = thread->cd;
  176. const char *what = cd->ud;
  177. rspamd_fprintf (stderr, "call to %s failed: %s\n", what, msg);
  178. cd->ret = ret;
  179. }
  180. static gboolean
  181. rspamadm_lua_load_script (lua_State *L, const gchar *path)
  182. {
  183. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  184. L = thread->lua_state;
  185. if (luaL_loadfile (L, path) != 0) {
  186. rspamd_fprintf (stderr, "cannot load script %s: %s\n",
  187. path, lua_tostring (L, -1));
  188. lua_settop (L, 0);
  189. return FALSE;
  190. }
  191. if (!per_line) {
  192. if (lua_repl_thread_call (thread, 0, (void *)path, lua_thread_str_error_cb) != 0) {
  193. return FALSE;
  194. }
  195. lua_settop (L, 0);
  196. }
  197. return TRUE;
  198. }
  199. static void
  200. rspamadm_exec_input (lua_State *L, const gchar *input)
  201. {
  202. GString *tb;
  203. gint i, cbref;
  204. int top = 0;
  205. gchar outbuf[8192];
  206. struct lua_logger_trace tr;
  207. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  208. L = thread->lua_state;
  209. /* First try return + input */
  210. tb = g_string_sized_new (strlen (input) + sizeof ("return "));
  211. rspamd_printf_gstring (tb, "return %s", input);
  212. int r = luaL_loadstring (L, tb->str);
  213. if (r != 0) {
  214. /* Reset stack */
  215. lua_settop (L, 0);
  216. /* Try with no return */
  217. if (luaL_loadstring (L, input) != 0) {
  218. rspamd_fprintf (stderr, "cannot load string %s\n",
  219. input);
  220. g_string_free (tb, TRUE);
  221. lua_settop (L, 0);
  222. lua_thread_pool_return (rspamd_main->cfg->lua_thread_pool, thread);
  223. return;
  224. }
  225. }
  226. g_string_free (tb, TRUE);
  227. if (!per_line) {
  228. top = lua_gettop (L);
  229. if (lua_repl_thread_call (thread, 0, NULL, NULL) == 0) {
  230. /* Print output */
  231. for (i = top; i <= lua_gettop (L); i++) {
  232. if (lua_isfunction (L, i)) {
  233. lua_pushvalue (L, i);
  234. cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  235. rspamd_printf ("local function: %d\n", cbref);
  236. } else {
  237. memset (&tr, 0, sizeof (tr));
  238. lua_logger_out_type (L, i, outbuf, sizeof (outbuf), &tr);
  239. rspamd_printf ("%s\n", outbuf);
  240. }
  241. }
  242. }
  243. }
  244. }
  245. static void
  246. wait_session_events (void)
  247. {
  248. /* XXX: it's probably worth to add timeout here - not to wait forever */
  249. while (rspamd_session_events_pending (rspamadm_session) > 0) {
  250. event_base_loop (rspamd_main->ev_base, EVLOOP_ONCE);
  251. }
  252. }
  253. gint
  254. lua_repl_thread_call (struct thread_entry *thread, gint narg, gpointer ud, lua_thread_error_t error_func)
  255. {
  256. int ret;
  257. struct lua_call_data *cd = g_new0 (struct lua_call_data, 1);
  258. cd->top = lua_gettop (thread->lua_state);
  259. cd->ud = ud;
  260. thread->finish_callback = lua_thread_finish_cb;
  261. if (error_func) {
  262. thread->error_callback = error_func;
  263. }
  264. else {
  265. thread->error_callback = lua_thread_error_cb;
  266. }
  267. thread->cd = cd;
  268. lua_thread_call (thread, narg);
  269. wait_session_events ();
  270. ret = cd->ret;
  271. g_free (cd);
  272. return ret;
  273. }
  274. static void
  275. rspamadm_lua_help_handler (lua_State *L, gint argc, gchar **argv)
  276. {
  277. guint i;
  278. struct rspamadm_lua_dot_command *cmd;
  279. if (argv[1] == NULL) {
  280. /* Print all commands */
  281. for (i = 0; i < G_N_ELEMENTS (cmds); i ++) {
  282. rspamd_printf ("%s: %s\n", cmds[i].name, cmds[i].description);
  283. }
  284. rspamd_printf ("{{: start multiline input\n");
  285. rspamd_printf ("}}: end multiline input\n");
  286. }
  287. else {
  288. for (i = 1; argv[i] != NULL; i ++) {
  289. cmd = g_hash_table_lookup (cmds_hash, argv[i]);
  290. if (cmd) {
  291. rspamd_printf ("%s: %s\n", cmds->name, cmds->description);
  292. }
  293. else {
  294. rspamd_printf ("%s: no such command\n", argv[i]);
  295. }
  296. }
  297. }
  298. }
  299. static void
  300. rspamadm_lua_load_handler (lua_State *L, gint argc, gchar **argv)
  301. {
  302. guint i;
  303. gboolean ret;
  304. for (i = 1; argv[i] != NULL; i ++) {
  305. ret = rspamadm_lua_load_script (L, argv[i]);
  306. rspamd_printf ("%s: %sloaded\n", argv[i], ret ? "" : "NOT ");
  307. }
  308. }
  309. static void
  310. rspamadm_lua_exec_handler (lua_State *L, gint argc, gchar **argv)
  311. {
  312. gint i;
  313. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  314. L = thread->lua_state;
  315. for (i = 1; argv[i] != NULL; i ++) {
  316. if (luaL_loadfile (L, argv[i]) != 0) {
  317. rspamd_fprintf (stderr, "cannot load script %s: %s\n",
  318. argv[i], lua_tostring (L, -1));
  319. lua_settop (L, 0);
  320. return;
  321. }
  322. lua_repl_thread_call (thread, 0, argv[i], lua_thread_str_error_cb);
  323. }
  324. }
  325. static void
  326. rspamadm_lua_message_handler (lua_State *L, gint argc, gchar **argv)
  327. {
  328. gulong cbref;
  329. gint old_top, func_idx, i, j;
  330. struct rspamd_task *task, **ptask;
  331. gpointer map;
  332. gsize len;
  333. gchar outbuf[8192];
  334. struct lua_logger_trace tr;
  335. if (argv[1] == NULL) {
  336. rspamd_printf ("no callback is specified\n");
  337. return;
  338. }
  339. for (i = 2; argv[i] != NULL; i ++) {
  340. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  341. L = thread->lua_state;
  342. if (rspamd_strtoul (argv[1], strlen (argv[1]), &cbref)) {
  343. lua_rawgeti (L, LUA_REGISTRYINDEX, cbref);
  344. }
  345. else {
  346. lua_getglobal (L, argv[1]);
  347. }
  348. if (lua_type (L, -1) != LUA_TFUNCTION) {
  349. rspamd_printf ("bad callback type: %s\n", lua_typename (L, lua_type (L, -1)));
  350. lua_thread_pool_return (rspamd_main->cfg->lua_thread_pool, thread);
  351. return;
  352. }
  353. /* Save index to reuse */
  354. func_idx = lua_gettop (L);
  355. map = rspamd_file_xmap (argv[i], PROT_READ, &len, TRUE);
  356. if (map == NULL) {
  357. rspamd_printf ("cannot open %s: %s\n", argv[i], strerror (errno));
  358. }
  359. else {
  360. task = rspamd_task_new (NULL, rspamd_main->cfg, NULL, NULL, NULL);
  361. if (!rspamd_task_load_message (task, NULL, map, len)) {
  362. rspamd_printf ("cannot load %s\n", argv[i]);
  363. rspamd_task_free (task);
  364. munmap (map, len);
  365. continue;
  366. }
  367. if (!rspamd_message_parse (task)) {
  368. rspamd_printf ("cannot parse %s: %e\n", argv[i], task->err);
  369. rspamd_task_free (task);
  370. munmap (map, len);
  371. continue;
  372. }
  373. rspamd_message_process (task);
  374. old_top = lua_gettop (L);
  375. lua_pushvalue (L, func_idx);
  376. ptask = lua_newuserdata (L, sizeof (*ptask));
  377. *ptask = task;
  378. rspamd_lua_setclass (L, "rspamd{task}", -1);
  379. if (lua_repl_thread_call (thread, 1, argv[i], lua_thread_str_error_cb) == 0) {
  380. rspamd_printf ("lua callback for %s returned:\n", argv[i]);
  381. for (j = old_top + 1; j <= lua_gettop (L); j ++) {
  382. memset (&tr, 0, sizeof (tr));
  383. lua_logger_out_type (L, j, outbuf, sizeof (outbuf), &tr);
  384. rspamd_printf ("%s\n", outbuf);
  385. }
  386. }
  387. rspamd_task_free (task);
  388. munmap (map, len);
  389. /* Pop all but the original function */
  390. lua_settop (L, func_idx);
  391. }
  392. }
  393. lua_settop (L, 0);
  394. }
  395. static gboolean
  396. rspamadm_lua_try_dot_command (lua_State *L, const gchar *input)
  397. {
  398. struct rspamadm_lua_dot_command *cmd;
  399. gchar **argv;
  400. argv = g_strsplit_set (input + 1, " ", -1);
  401. if (argv == NULL || argv[0] == NULL) {
  402. if (argv) {
  403. g_strfreev (argv);
  404. }
  405. return FALSE;
  406. }
  407. cmd = g_hash_table_lookup (cmds_hash, argv[0]);
  408. if (cmd) {
  409. cmd->handler (L, g_strv_length (argv), argv);
  410. g_strfreev (argv);
  411. return TRUE;
  412. }
  413. g_strfreev (argv);
  414. return FALSE;
  415. }
  416. static void
  417. rspamadm_lua_run_repl (lua_State *L)
  418. {
  419. gchar *input;
  420. gboolean is_multiline = FALSE;
  421. GString *tb;
  422. guint i;
  423. for (;;) {
  424. if (!is_multiline) {
  425. input = linenoise (MAIN_PROMPT);
  426. if (input == NULL) {
  427. return;
  428. }
  429. if (input[0] == '.') {
  430. if (rspamadm_lua_try_dot_command (L, input)) {
  431. linenoiseHistoryAdd (input);
  432. linenoiseFree (input);
  433. continue;
  434. }
  435. }
  436. if (strcmp (input, "{{") == 0) {
  437. is_multiline = TRUE;
  438. linenoiseFree (input);
  439. tb = g_string_sized_new (8192);
  440. continue;
  441. }
  442. rspamadm_exec_input (L, input);
  443. linenoiseHistoryAdd (input);
  444. linenoiseFree (input);
  445. lua_settop (L, 0);
  446. }
  447. else {
  448. input = linenoise (MULTILINE_PROMPT);
  449. if (input == NULL) {
  450. g_string_free (tb, TRUE);
  451. return;
  452. }
  453. if (strcmp (input, "}}") == 0) {
  454. is_multiline = FALSE;
  455. linenoiseFree (input);
  456. rspamadm_exec_input (L, tb->str);
  457. /* Replace \n with ' ' for sanity */
  458. for (i = 0; i < tb->len; i ++) {
  459. if (tb->str[i] == '\n') {
  460. tb->str[i] = ' ';
  461. }
  462. }
  463. linenoiseHistoryAdd (tb->str);
  464. g_string_free (tb, TRUE);
  465. }
  466. else {
  467. g_string_append (tb, input);
  468. g_string_append (tb, " \n");
  469. linenoiseFree (input);
  470. }
  471. }
  472. }
  473. }
  474. struct rspamadm_lua_repl_context {
  475. struct rspamd_http_connection_router *rt;
  476. lua_State *L;
  477. };
  478. struct rspamadm_lua_repl_session {
  479. struct rspamd_http_connection_router *rt;
  480. rspamd_inet_addr_t *addr;
  481. struct rspamadm_lua_repl_context *ctx;
  482. gint sock;
  483. };
  484. static void
  485. rspamadm_lua_accept_cb (gint fd, short what, void *arg)
  486. {
  487. struct rspamadm_lua_repl_context *ctx = arg;
  488. rspamd_inet_addr_t *addr;
  489. struct rspamadm_lua_repl_session *session;
  490. gint nfd;
  491. if ((nfd =
  492. rspamd_accept_from_socket (fd, &addr, NULL)) == -1) {
  493. rspamd_fprintf (stderr, "accept failed: %s", strerror (errno));
  494. return;
  495. }
  496. /* Check for EAGAIN */
  497. if (nfd == 0) {
  498. return;
  499. }
  500. session = g_malloc0 (sizeof (*session));
  501. session->rt = ctx->rt;
  502. session->ctx = ctx;
  503. session->addr = addr;
  504. session->sock = nfd;
  505. rspamd_http_router_handle_socket (ctx->rt, nfd, session);
  506. }
  507. static void
  508. rspamadm_lua_error_handler (struct rspamd_http_connection_entry *conn_ent,
  509. GError *err)
  510. {
  511. struct rspamadm_lua_repl_session *session = conn_ent->ud;
  512. rspamd_fprintf (stderr, "http error occurred: %s\n", err->message);
  513. }
  514. static void
  515. rspamadm_lua_finish_handler (struct rspamd_http_connection_entry *conn_ent)
  516. {
  517. struct rspamadm_lua_repl_session *session = conn_ent->ud;
  518. g_free (session);
  519. }
  520. static void
  521. lua_thread_http_error_cb (struct thread_entry *thread, int ret, const char *msg)
  522. {
  523. struct lua_call_data *cd = thread->cd;
  524. struct rspamd_http_connection_entry *conn_ent = cd->ud;
  525. rspamd_controller_send_error (conn_ent, 500, "call failed: %s\n", msg);
  526. cd->ret = ret;
  527. }
  528. /*
  529. * Exec command handler:
  530. * request: /exec
  531. * body: lua script
  532. * reply: json {"status": "ok", "reply": {<lua json object>}}
  533. */
  534. static int
  535. rspamadm_lua_handle_exec (struct rspamd_http_connection_entry *conn_ent,
  536. struct rspamd_http_message *msg)
  537. {
  538. GString *tb;
  539. gint err_idx, i;
  540. lua_State *L;
  541. struct rspamadm_lua_repl_context *ctx;
  542. struct rspamadm_lua_repl_session *session = conn_ent->ud;
  543. ucl_object_t *obj, *elt;
  544. const gchar *body;
  545. gsize body_len;
  546. ctx = session->ctx;
  547. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  548. L = thread->lua_state;
  549. body = rspamd_http_message_get_body (msg, &body_len);
  550. if (body == NULL) {
  551. rspamd_controller_send_error (conn_ent, 400, "Empty lua script");
  552. return 0;
  553. }
  554. lua_pushcfunction (L, &rspamd_lua_traceback);
  555. err_idx = lua_gettop (L);
  556. /* First try return + input */
  557. tb = g_string_sized_new (body_len + sizeof ("return "));
  558. rspamd_printf_gstring (tb, "return %*s", (gint)body_len, body);
  559. if (luaL_loadstring (L, tb->str) != 0) {
  560. /* Reset stack */
  561. lua_settop (L, 0);
  562. lua_pushcfunction (L, &rspamd_lua_traceback);
  563. err_idx = lua_gettop (L);
  564. /* Try with no return */
  565. if (luaL_loadbuffer (L, body, body_len, "http input") != 0) {
  566. rspamd_controller_send_error (conn_ent, 400, "Invalid lua script");
  567. return 0;
  568. }
  569. }
  570. g_string_free (tb, TRUE);
  571. if (lua_repl_thread_call (thread, 0, conn_ent, lua_thread_http_error_cb) != 0) {
  572. return 0;
  573. }
  574. obj = ucl_object_typed_new (UCL_ARRAY);
  575. for (i = err_idx + 1; i <= lua_gettop (L); i ++) {
  576. if (lua_isfunction (L, i)) {
  577. /* XXX: think about API */
  578. }
  579. else {
  580. elt = ucl_object_lua_import (L, i);
  581. if (elt) {
  582. ucl_array_append (obj, elt);
  583. }
  584. }
  585. }
  586. rspamd_controller_send_ucl (conn_ent, obj);
  587. ucl_object_unref (obj);
  588. lua_settop (L, 0);
  589. return 0;
  590. }
  591. static void
  592. rspamadm_lua (gint argc, gchar **argv, const struct rspamadm_command *cmd)
  593. {
  594. GOptionContext *context;
  595. GError *error = NULL;
  596. gchar **elt;
  597. guint i;
  598. lua_State *L = rspamd_main->cfg->lua_state;
  599. context = g_option_context_new ("lua - run lua interpreter");
  600. g_option_context_set_summary (context,
  601. "Summary:\n Rspamd administration utility version "
  602. RVERSION
  603. "\n Release id: "
  604. RID);
  605. g_option_context_add_main_entries (context, entries, NULL);
  606. if (!g_option_context_parse (context, &argc, &argv, &error)) {
  607. fprintf (stderr, "option parsing failed: %s\n", error->message);
  608. g_error_free (error);
  609. exit (1);
  610. }
  611. if (batch == -1) {
  612. if (isatty (STDIN_FILENO)) {
  613. batch = 0;
  614. }
  615. else {
  616. batch = 1;
  617. }
  618. }
  619. if (paths) {
  620. for (elt = paths; *elt != NULL; elt ++) {
  621. rspamadm_lua_add_path (L, *elt);
  622. }
  623. }
  624. if (lua_args) {
  625. i = 1;
  626. lua_newtable (L);
  627. for (elt = lua_args; *elt != NULL; elt ++) {
  628. lua_pushinteger (L, i);
  629. lua_pushstring (L, *elt);
  630. lua_settable (L, -3);
  631. i++;
  632. }
  633. lua_setglobal (L, "arg");
  634. }
  635. if (scripts) {
  636. for (elt = scripts; *elt != NULL; elt ++) {
  637. if (!rspamadm_lua_load_script (L, *elt)) {
  638. exit (EXIT_FAILURE);
  639. }
  640. }
  641. }
  642. if (exec_line) {
  643. rspamadm_exec_input (L, exec_line);
  644. }
  645. if (serve) {
  646. /* HTTP Server mode */
  647. GPtrArray *addrs = NULL;
  648. gchar *name = NULL;
  649. struct event_base *ev_base;
  650. struct rspamd_http_connection_router *http;
  651. gint fd;
  652. struct rspamadm_lua_repl_context *ctx;
  653. if (!rspamd_parse_host_port_priority (serve, &addrs, NULL, &name,
  654. 10000, NULL)) {
  655. fprintf (stderr, "cannot listen on %s", serve);
  656. exit (EXIT_FAILURE);
  657. }
  658. ev_base = rspamd_main->ev_base;
  659. ctx = g_malloc0 (sizeof (*ctx));
  660. http = rspamd_http_router_new (rspamadm_lua_error_handler,
  661. rspamadm_lua_finish_handler,
  662. NULL, ev_base,
  663. NULL, NULL);
  664. ctx->L = L;
  665. ctx->rt = http;
  666. rspamd_http_router_add_path (http,
  667. "/exec",
  668. rspamadm_lua_handle_exec);
  669. for (i = 0; i < addrs->len; i ++) {
  670. rspamd_inet_addr_t *addr = g_ptr_array_index (addrs, i);
  671. fd = rspamd_inet_address_listen (addr, SOCK_STREAM, TRUE);
  672. if (fd != -1) {
  673. struct event *ev;
  674. ev = g_malloc0 (sizeof (*ev));
  675. event_set (ev, fd, EV_READ|EV_PERSIST, rspamadm_lua_accept_cb,
  676. ctx);
  677. event_base_set (ev_base, ev);
  678. event_add (ev, NULL);
  679. rspamd_printf ("listen on %s\n",
  680. rspamd_inet_address_to_string_pretty (addr));
  681. }
  682. }
  683. event_base_loop (ev_base, 0);
  684. exit (EXIT_SUCCESS);
  685. }
  686. if (histfile == NULL) {
  687. const gchar *homedir;
  688. GString *hist_path;
  689. homedir = getenv ("HOME");
  690. if (homedir) {
  691. hist_path = g_string_sized_new (strlen (homedir) +
  692. strlen (default_history_file) + 1);
  693. rspamd_printf_gstring (hist_path, "%s/%s", homedir,
  694. default_history_file);
  695. }
  696. else {
  697. hist_path = g_string_sized_new (strlen (default_history_file) + 2);
  698. rspamd_printf_gstring (hist_path, "./%s", default_history_file);
  699. }
  700. histfile = hist_path->str;
  701. g_string_free (hist_path, FALSE);
  702. }
  703. if (argc > 1) {
  704. for (i = 1; i < argc; i ++) {
  705. if (!rspamadm_lua_load_script (L, argv[i])) {
  706. exit (EXIT_FAILURE);
  707. }
  708. }
  709. exit (EXIT_SUCCESS);
  710. }
  711. /* Init dot commands */
  712. cmds_hash = g_hash_table_new (rspamd_strcase_hash, rspamd_strcase_equal);
  713. for (i = 0; i < G_N_ELEMENTS (cmds); i ++) {
  714. g_hash_table_insert (cmds_hash, (gpointer)cmds[i].name, &cmds[i]);
  715. }
  716. if (per_line) {
  717. GIOChannel *in;
  718. GString *buf;
  719. gsize end_pos;
  720. GIOStatus ret;
  721. gint old_top;
  722. GError *err = NULL;
  723. in = g_io_channel_unix_new (STDIN_FILENO);
  724. buf = g_string_sized_new (BUFSIZ);
  725. again:
  726. while ((ret = g_io_channel_read_line_string (in, buf, &end_pos, &err)) ==
  727. G_IO_STATUS_NORMAL) {
  728. old_top = lua_gettop (L);
  729. lua_pushvalue (L, -1);
  730. lua_pushlstring (L, buf->str, MIN (buf->len, end_pos));
  731. lua_setglobal (L, "input");
  732. struct thread_entry *thread = lua_thread_pool_get_for_config (rspamd_main->cfg);
  733. L = thread->lua_state;
  734. lua_repl_thread_call (thread, 0, NULL, NULL);
  735. lua_settop (L, old_top);
  736. }
  737. if (ret == G_IO_STATUS_AGAIN) {
  738. goto again;
  739. }
  740. g_string_free (buf, TRUE);
  741. g_io_channel_shutdown (in, FALSE, NULL);
  742. if (ret == G_IO_STATUS_EOF) {
  743. if (err) {
  744. g_error_free (err);
  745. }
  746. }
  747. else {
  748. rspamd_fprintf (stderr, "IO error: %e\n", err);
  749. if (err) {
  750. g_error_free (err);
  751. }
  752. exit (-errno);
  753. }
  754. }
  755. else {
  756. if (!batch) {
  757. linenoiseHistorySetMaxLen (max_history);
  758. linenoiseHistoryLoad (histfile);
  759. rspamadm_lua_run_repl (L);
  760. linenoiseHistorySave (histfile);
  761. } else {
  762. rspamadm_lua_run_repl (L);
  763. }
  764. }
  765. }