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.

rspamadm.c 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /*
  2. * Copyright 2023 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 "rspamd.h"
  19. #include "ottery.h"
  20. #include "lua/lua_common.h"
  21. #include "lua/lua_thread_pool.h"
  22. #include "lua_ucl.h"
  23. #include "unix-std.h"
  24. #include "contrib/libev/ev.h"
  25. #ifdef HAVE_LIBUTIL_H
  26. #include <libutil.h>
  27. #endif
  28. static gboolean verbose = FALSE;
  29. static gboolean list_commands = FALSE;
  30. static gboolean show_help = FALSE;
  31. static gboolean show_version = FALSE;
  32. GHashTable *ucl_vars = NULL;
  33. char **lua_env = NULL;
  34. struct rspamd_main *rspamd_main = NULL;
  35. struct rspamd_async_session *rspamadm_session = NULL;
  36. lua_State *L = NULL;
  37. /* Defined in modules.c */
  38. extern module_t *modules[];
  39. extern worker_t *workers[];
  40. static void rspamadm_help(int argc, char **argv, const struct rspamadm_command *);
  41. static const char *rspamadm_help_help(gboolean full_help, const struct rspamadm_command *);
  42. struct rspamadm_command help_command = {
  43. .name = "help",
  44. .flags = RSPAMADM_FLAG_NOHELP,
  45. .help = rspamadm_help_help,
  46. .run = rspamadm_help};
  47. static gboolean rspamadm_parse_ucl_var(const char *option_name,
  48. const char *value, gpointer data,
  49. GError **error);
  50. static GOptionEntry entries[] = {
  51. {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
  52. "Enable verbose logging", NULL},
  53. {"list-commands", 'l', 0, G_OPTION_ARG_NONE, &list_commands,
  54. "List available commands", NULL},
  55. {"var", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &rspamadm_parse_ucl_var,
  56. "Redefine/define environment variable", NULL},
  57. {"help", 'h', 0, G_OPTION_ARG_NONE, &show_help,
  58. "Show help", NULL},
  59. {"version", 'V', 0, G_OPTION_ARG_NONE, &show_version,
  60. "Show version", NULL},
  61. {"lua-env", '\0', 0, G_OPTION_ARG_FILENAME_ARRAY, &lua_env,
  62. "Load lua environment from the specified files", NULL},
  63. {NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL}};
  64. GQuark
  65. rspamadm_error(void)
  66. {
  67. return g_quark_from_static_string("rspamadm");
  68. }
  69. static void
  70. rspamadm_version(void)
  71. {
  72. rspamd_printf("Rspamadm %s\n", RVERSION);
  73. }
  74. static void
  75. rspamadm_usage(GOptionContext *context)
  76. {
  77. char *help_str;
  78. help_str = g_option_context_get_help(context, TRUE, NULL);
  79. rspamd_printf("%s", help_str);
  80. }
  81. static void
  82. rspamadm_commands(GPtrArray *all_commands)
  83. {
  84. const struct rspamadm_command *cmd;
  85. unsigned int i;
  86. rspamd_printf("Rspamadm %s\n", RVERSION);
  87. rspamd_printf("Usage: rspamadm [global_options] command [command_options]\n");
  88. rspamd_printf("\nAvailable commands:\n");
  89. PTR_ARRAY_FOREACH(all_commands, i, cmd)
  90. {
  91. if (!(cmd->flags & RSPAMADM_FLAG_NOHELP)) {
  92. if (cmd->flags & RSPAMADM_FLAG_LUA) {
  93. (void) cmd->help(FALSE, cmd);
  94. }
  95. else {
  96. printf(" %-18s %-60s\n", cmd->name, cmd->help(FALSE, cmd));
  97. }
  98. }
  99. }
  100. }
  101. static const char *
  102. rspamadm_help_help(gboolean full_help, const struct rspamadm_command *cmd)
  103. {
  104. const char *help_str;
  105. if (full_help) {
  106. help_str = "Shows help for a specified command\n"
  107. "Usage: rspamadm help <command>";
  108. }
  109. else {
  110. help_str = "Shows help for a specified command";
  111. }
  112. return help_str;
  113. }
  114. static void
  115. rspamadm_help(int argc, char **argv, const struct rspamadm_command *command)
  116. {
  117. const char *cmd_name;
  118. const struct rspamadm_command *cmd;
  119. GPtrArray *all_commands = (GPtrArray *) command->command_data;
  120. rspamd_printf("Rspamadm %s\n", RVERSION);
  121. rspamd_printf("Usage: rspamadm [global_options] command [command_options]\n\n");
  122. if (argc <= 1) {
  123. cmd_name = "help";
  124. }
  125. else {
  126. cmd_name = argv[1];
  127. rspamd_printf("Showing help for %s command\n\n", cmd_name);
  128. }
  129. cmd = rspamadm_search_command(cmd_name, all_commands);
  130. if (cmd == NULL) {
  131. fprintf(stderr, "Invalid command name: %s\n", cmd_name);
  132. exit(EXIT_FAILURE);
  133. }
  134. if (strcmp(cmd_name, "help") == 0) {
  135. unsigned int i;
  136. rspamd_printf("Available commands:\n");
  137. PTR_ARRAY_FOREACH(all_commands, i, cmd)
  138. {
  139. if (!(cmd->flags & RSPAMADM_FLAG_NOHELP)) {
  140. if (!(cmd->flags & RSPAMADM_FLAG_LUA)) {
  141. printf(" %-18s %-60s\n", cmd->name,
  142. cmd->help(FALSE, cmd));
  143. }
  144. else {
  145. /* Just call lua subr */
  146. (void) cmd->help(FALSE, cmd);
  147. }
  148. }
  149. }
  150. }
  151. else {
  152. if (!(cmd->flags & RSPAMADM_FLAG_LUA)) {
  153. rspamd_printf("%s\n", cmd->help(TRUE, cmd));
  154. }
  155. else {
  156. /* Just call lua subr */
  157. (void) cmd->help(TRUE, cmd);
  158. }
  159. }
  160. }
  161. static gboolean
  162. rspamadm_parse_ucl_var(const char *option_name,
  163. const char *value, gpointer data,
  164. GError **error)
  165. {
  166. char *k, *v, *t;
  167. t = strchr(value, '=');
  168. if (t != NULL) {
  169. k = g_strdup(value);
  170. t = k + (t - value);
  171. v = g_strdup(t + 1);
  172. *t = '\0';
  173. g_hash_table_insert(ucl_vars, k, v);
  174. }
  175. else {
  176. g_set_error(error, rspamadm_error(), EINVAL,
  177. "Bad variable format: %s", value);
  178. return FALSE;
  179. }
  180. return TRUE;
  181. }
  182. static void
  183. lua_thread_str_error_cb(struct thread_entry *thread, int ret, const char *msg)
  184. {
  185. struct lua_call_data *cd = thread->cd;
  186. msg_err("call to rspamadm lua script failed (%d): %s", ret, msg);
  187. cd->ret = ret;
  188. }
  189. gboolean
  190. rspamadm_execute_lua_ucl_subr(int argc, char **argv,
  191. const ucl_object_t *res,
  192. const char *script_name,
  193. gboolean rspamadm_subcommand)
  194. {
  195. struct thread_entry *thread = lua_thread_pool_get_for_config(rspamd_main->cfg);
  196. lua_State *L = thread->lua_state;
  197. int i;
  198. char str[PATH_MAX];
  199. g_assert(script_name != NULL);
  200. g_assert(res != NULL);
  201. g_assert(L != NULL);
  202. /* Init internal rspamadm routines */
  203. if (rspamadm_subcommand) {
  204. rspamd_snprintf(str, sizeof(str), "return require \"%s.%s\"", "rspamadm",
  205. script_name);
  206. }
  207. else {
  208. rspamd_snprintf(str, sizeof(str), "return require \"%s\"",
  209. script_name);
  210. }
  211. if (luaL_dostring(L, str) != 0) {
  212. msg_err("cannot execute lua script %s: %s",
  213. str, lua_tostring(L, -1));
  214. return FALSE;
  215. }
  216. else {
  217. if (lua_type(L, -1) == LUA_TTABLE) {
  218. lua_pushstring(L, "handler");
  219. lua_gettable(L, -2);
  220. }
  221. if (lua_type(L, -1) != LUA_TFUNCTION) {
  222. msg_err("lua script must return "
  223. "function and not %s",
  224. lua_typename(L, lua_type(L, -1)));
  225. return FALSE;
  226. }
  227. }
  228. /* Push function */
  229. lua_pushvalue(L, -1);
  230. /* Push argv */
  231. lua_newtable(L);
  232. for (i = 1; i < argc; i++) {
  233. lua_pushstring(L, argv[i]);
  234. lua_rawseti(L, -2, i);
  235. }
  236. /* Push results */
  237. ucl_object_push_lua(L, res, TRUE);
  238. if (lua_repl_thread_call(thread, 2, NULL, lua_thread_str_error_cb) != 0) {
  239. return FALSE;
  240. }
  241. /* error function */
  242. lua_settop(L, 0);
  243. return TRUE;
  244. }
  245. static int
  246. rspamdadm_commands_sort_func(gconstpointer a, gconstpointer b)
  247. {
  248. const struct rspamadm_command *cmda = *((struct rspamadm_command const **) a),
  249. *cmdb = *((struct rspamadm_command const **) b);
  250. return strcmp(cmda->name, cmdb->name);
  251. }
  252. static gboolean
  253. rspamadm_command_maybe_match_name(const char *cmd, const char *input)
  254. {
  255. gsize clen, inplen;
  256. clen = strlen(cmd);
  257. inplen = strlen(input);
  258. if (rspamd_strings_levenshtein_distance(cmd, clen,
  259. input, inplen, 1) == 1) {
  260. return TRUE;
  261. }
  262. else if ((clen > inplen &&
  263. rspamd_substring_search(cmd, clen, input, inplen) != -1) ||
  264. (inplen > clen &&
  265. rspamd_substring_search(input, inplen, cmd, clen) != -1)) {
  266. return TRUE;
  267. }
  268. return FALSE;
  269. }
  270. static void
  271. rspamadm_add_lua_globals(struct rspamd_dns_resolver *resolver)
  272. {
  273. struct rspamd_async_session **psession;
  274. struct ev_loop **pev_base;
  275. struct rspamd_dns_resolver **presolver;
  276. rspamadm_session = rspamd_session_create(rspamd_main->cfg->cfg_pool, NULL,
  277. NULL, (event_finalizer_t) NULL, NULL);
  278. psession = lua_newuserdata(L, sizeof(struct rspamd_async_session *));
  279. rspamd_lua_setclass(L, rspamd_session_classname, -1);
  280. *psession = rspamadm_session;
  281. lua_setglobal(L, "rspamadm_session");
  282. pev_base = lua_newuserdata(L, sizeof(struct ev_loop *));
  283. rspamd_lua_setclass(L, rspamd_ev_base_classname, -1);
  284. *pev_base = rspamd_main->event_loop;
  285. lua_setglobal(L, "rspamadm_ev_base");
  286. presolver = lua_newuserdata(L, sizeof(struct rspamd_dns_resolver *));
  287. rspamd_lua_setclass(L, rspamd_resolver_classname, -1);
  288. *presolver = resolver;
  289. lua_setglobal(L, "rspamadm_dns_resolver");
  290. }
  291. static void
  292. rspamadm_cmd_dtor(gpointer p)
  293. {
  294. struct rspamadm_command *cmd = (struct rspamadm_command *) p;
  295. if (cmd->flags & RSPAMADM_FLAG_DYNAMIC) {
  296. if (cmd->aliases) {
  297. g_ptr_array_free(cmd->aliases, TRUE);
  298. }
  299. g_free((gpointer) cmd->name);
  300. g_free(cmd);
  301. }
  302. }
  303. int main(int argc, char **argv, char **env)
  304. {
  305. GError *error = NULL;
  306. GOptionContext *context;
  307. GOptionGroup *og;
  308. struct rspamd_config *cfg;
  309. GQuark process_quark;
  310. char **nargv, **targv;
  311. const char *cmd_name;
  312. const struct rspamadm_command *cmd;
  313. struct rspamd_dns_resolver *resolver;
  314. GPtrArray *all_commands = g_ptr_array_new_full(32,
  315. rspamadm_cmd_dtor); /* Discovered during check */
  316. int i, nargc, targc;
  317. worker_t **pworker;
  318. gboolean lua_file = FALSE;
  319. int retcode = 0;
  320. ucl_vars = g_hash_table_new_full(rspamd_strcase_hash,
  321. rspamd_strcase_equal, g_free, g_free);
  322. process_quark = g_quark_from_static_string("rspamadm");
  323. cfg = rspamd_config_new(RSPAMD_CONFIG_INIT_DEFAULT | RSPAMD_CONFIG_INIT_WIPE_LUA_MEM);
  324. cfg->libs_ctx = rspamd_init_libs();
  325. rspamd_main = g_malloc0(sizeof(*rspamd_main));
  326. rspamd_main->cfg = cfg;
  327. rspamd_main->pid = getpid();
  328. rspamd_main->type = process_quark;
  329. rspamd_main->server_pool = rspamd_mempool_new(rspamd_mempool_suggest_size(),
  330. "rspamadm", 0);
  331. rspamadm_fill_internal_commands(all_commands);
  332. help_command.command_data = all_commands;
  333. /* Now read options and store everything till the first non-dash argument */
  334. nargv = g_malloc0(sizeof(char *) * (argc + 1));
  335. nargv[0] = g_strdup(argv[0]);
  336. for (i = 1, nargc = 1; i < argc; i++) {
  337. if (argv[i] && argv[i][0] == '-') {
  338. /* Copy to nargv */
  339. nargv[nargc] = g_strdup(argv[i]);
  340. nargc++;
  341. }
  342. else {
  343. break;
  344. }
  345. }
  346. context = g_option_context_new("command - rspamd administration utility");
  347. og = g_option_group_new("global", "global options", "global options",
  348. NULL, NULL);
  349. g_option_context_set_help_enabled(context, FALSE);
  350. g_option_group_add_entries(og, entries);
  351. g_option_context_set_summary(context,
  352. "Summary:\n Rspamd administration utility version " RVERSION
  353. "\n Release id: " RID);
  354. g_option_context_set_main_group(context, og);
  355. targv = nargv;
  356. targc = nargc;
  357. if (!g_option_context_parse(context, &targc, &targv, &error)) {
  358. fprintf(stderr, "option parsing failed: %s\n", error->message);
  359. g_error_free(error);
  360. g_option_context_free(context);
  361. exit(EXIT_FAILURE);
  362. }
  363. /* Setup logger */
  364. if (verbose) {
  365. rspamd_main->logger = rspamd_log_open_emergency(rspamd_main->server_pool,
  366. RSPAMD_LOG_FLAG_USEC | RSPAMD_LOG_FLAG_ENFORCED | RSPAMD_LOG_FLAG_RSPAMADM);
  367. rspamd_log_set_log_level(rspamd_main->logger, G_LOG_LEVEL_DEBUG);
  368. }
  369. else {
  370. rspamd_main->logger = rspamd_log_open_emergency(rspamd_main->server_pool,
  371. RSPAMD_LOG_FLAG_RSPAMADM);
  372. rspamd_log_set_log_level(rspamd_main->logger, G_LOG_LEVEL_MESSAGE);
  373. }
  374. rspamd_main->event_loop = ev_default_loop(rspamd_config_ev_backend_get(cfg));
  375. resolver = rspamd_dns_resolver_init(rspamd_main->logger,
  376. rspamd_main->event_loop,
  377. cfg);
  378. rspamd_main->http_ctx = rspamd_http_context_create(cfg, rspamd_main->event_loop,
  379. NULL);
  380. g_log_set_default_handler(rspamd_glib_log_function, rspamd_main->logger);
  381. g_set_printerr_handler(rspamd_glib_printerr_function);
  382. rspamd_config_post_load(cfg,
  383. RSPAMD_CONFIG_INIT_LIBS | RSPAMD_CONFIG_INIT_URL | RSPAMD_CONFIG_INIT_NO_TLD);
  384. pworker = &workers[0];
  385. while (*pworker) {
  386. /* Init string quarks */
  387. (void) g_quark_from_static_string((*pworker)->name);
  388. pworker++;
  389. }
  390. cfg->compiled_modules = modules;
  391. cfg->compiled_workers = workers;
  392. rspamd_setproctitle("rspamdadm");
  393. L = cfg->lua_state;
  394. rspamd_lua_set_path(L, NULL, ucl_vars);
  395. if (!rspamd_lua_set_env(L, ucl_vars, lua_env, &error)) {
  396. rspamd_fprintf(stderr, "Cannot load lua environment: %e", error);
  397. g_error_free(error);
  398. goto end;
  399. }
  400. rspamd_lua_set_globals(cfg, L);
  401. rspamadm_add_lua_globals(resolver);
  402. rspamd_redis_pool_config(cfg->redis_pool, cfg, rspamd_main->event_loop);
  403. /* Init rspamadm global */
  404. lua_newtable(L);
  405. PTR_ARRAY_FOREACH(all_commands, i, cmd)
  406. {
  407. if (cmd->lua_subrs != NULL) {
  408. cmd->lua_subrs(L);
  409. }
  410. cmd++;
  411. }
  412. lua_setglobal(L, "rspamadm");
  413. rspamadm_fill_lua_commands(L, all_commands);
  414. rspamd_lua_start_gc(cfg);
  415. g_ptr_array_sort(all_commands, rspamdadm_commands_sort_func);
  416. g_strfreev(nargv);
  417. if (show_version) {
  418. rspamadm_version();
  419. goto end;
  420. }
  421. if (show_help) {
  422. rspamadm_usage(context);
  423. goto end;
  424. }
  425. if (list_commands) {
  426. rspamadm_commands(all_commands);
  427. goto end;
  428. }
  429. cmd_name = argv[nargc];
  430. if (cmd_name == NULL) {
  431. cmd_name = "help";
  432. }
  433. gsize cmdlen = strlen(cmd_name);
  434. if (cmdlen > 4 && memcmp(cmd_name + (cmdlen - 4), ".lua", 4) == 0) {
  435. cmd_name = "lua";
  436. lua_file = TRUE;
  437. }
  438. cmd = rspamadm_search_command(cmd_name, all_commands);
  439. if (cmd == NULL) {
  440. rspamd_fprintf(stderr, "Invalid command name: %s\n", cmd_name);
  441. /* Try fuzz search */
  442. rspamd_fprintf(stderr, "Suggested commands:\n");
  443. PTR_ARRAY_FOREACH(all_commands, i, cmd)
  444. {
  445. unsigned int j;
  446. const char *alias;
  447. if (rspamadm_command_maybe_match_name(cmd->name, cmd_name)) {
  448. rspamd_fprintf(stderr, "%s\n", cmd->name);
  449. }
  450. else {
  451. PTR_ARRAY_FOREACH(cmd->aliases, j, alias)
  452. {
  453. if (rspamadm_command_maybe_match_name(alias, cmd_name)) {
  454. rspamd_fprintf(stderr, "%s\n", alias);
  455. }
  456. }
  457. }
  458. }
  459. retcode = EXIT_FAILURE;
  460. goto end;
  461. }
  462. if (nargc < argc) {
  463. if (lua_file) {
  464. nargv = g_malloc0(sizeof(char *) * (argc - nargc + 2));
  465. nargv[1] = g_strdup(argv[nargc]);
  466. i = 2;
  467. argc++;
  468. }
  469. else {
  470. nargv = g_malloc0(sizeof(char *) * (argc - nargc + 1));
  471. i = 1;
  472. }
  473. nargv[0] = g_strdup_printf("%s %s", argv[0], cmd_name);
  474. for (; i < argc - nargc; i++) {
  475. if (lua_file) {
  476. /*
  477. * We append prefix '--arg=' to each argument and shift argv index
  478. */
  479. gsize arglen = strlen(argv[i + nargc - 1]);
  480. arglen += sizeof("--args="); /* Including \0 */
  481. nargv[i] = g_malloc(arglen);
  482. rspamd_snprintf(nargv[i], arglen, "--args=%s", argv[i + nargc - 1]);
  483. }
  484. else {
  485. nargv[i] = g_strdup(argv[i + nargc]);
  486. }
  487. }
  488. targc = argc - nargc;
  489. targv = nargv;
  490. cmd->run(targc, targv, cmd);
  491. g_strfreev(nargv);
  492. }
  493. else {
  494. cmd->run(0, NULL, cmd);
  495. }
  496. ev_break(rspamd_main->event_loop, EVBREAK_ALL);
  497. end:
  498. rspamd_session_destroy(rspamadm_session);
  499. g_option_context_free(context);
  500. rspamd_dns_resolver_deinit(resolver);
  501. REF_RELEASE(rspamd_main->cfg);
  502. rspamd_http_context_free(rspamd_main->http_ctx);
  503. rspamd_log_close(rspamd_main->logger);
  504. rspamd_url_deinit();
  505. g_ptr_array_free(all_commands, TRUE);
  506. ev_loop_destroy(rspamd_main->event_loop);
  507. g_hash_table_unref(ucl_vars);
  508. rspamd_mempool_delete(rspamd_main->server_pool);
  509. g_free(rspamd_main);
  510. return retcode;
  511. }