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.

rspamc.c 51KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  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 "libutil/http.h"
  19. #include "libutil/http_private.h"
  20. #include "rspamdclient.h"
  21. #include "utlist.h"
  22. #include "unix-std.h"
  23. #ifdef HAVE_SYS_WAIT_H
  24. #include <sys/wait.h>
  25. #endif
  26. #define DEFAULT_PORT 11333
  27. #define DEFAULT_CONTROL_PORT 11334
  28. static gchar *connect_str = "localhost";
  29. static gchar *password = NULL;
  30. static gchar *ip = NULL;
  31. static gchar *from = NULL;
  32. static gchar *deliver_to = NULL;
  33. static gchar **rcpts = NULL;
  34. static gchar *user = NULL;
  35. static gchar *helo = NULL;
  36. static gchar *hostname = NULL;
  37. static gchar *classifier = NULL;
  38. static gchar *local_addr = NULL;
  39. static gchar *execute = NULL;
  40. static gchar *sort = NULL;
  41. static gchar **http_headers = NULL;
  42. static gchar **exclude_patterns = NULL;
  43. static gint weight = 0;
  44. static gint flag = 0;
  45. static gchar *fuzzy_symbol = NULL;
  46. static gchar *dictionary = NULL;
  47. static gint max_requests = 8;
  48. static gdouble timeout = 10.0;
  49. static gboolean pass_all;
  50. static gboolean tty = FALSE;
  51. static gboolean verbose = FALSE;
  52. static gboolean print_commands = FALSE;
  53. static gboolean json = FALSE;
  54. static gboolean compact = FALSE;
  55. static gboolean headers = FALSE;
  56. static gboolean raw = FALSE;
  57. static gboolean extended_urls = FALSE;
  58. static gboolean mime_output = FALSE;
  59. static gboolean empty_input = FALSE;
  60. static gboolean compressed = FALSE;
  61. static gboolean profile = FALSE;
  62. static gboolean skip_images = FALSE;
  63. static gboolean skip_attachments = FALSE;
  64. static gchar *key = NULL;
  65. static gchar *user_agent = "rspamc";
  66. static GList *children;
  67. static GPatternSpec **exclude_compiled = NULL;
  68. static gint retcode = EXIT_SUCCESS;
  69. #define ADD_CLIENT_HEADER(o, n, v) do { \
  70. struct rspamd_http_client_header *nh; \
  71. nh = g_malloc (sizeof (*nh)); \
  72. nh->name = (n); \
  73. nh->value = (v); \
  74. g_queue_push_tail ((o), nh); \
  75. } while (0)
  76. static gboolean rspamc_password_callback (const gchar *option_name,
  77. const gchar *value,
  78. gpointer data,
  79. GError **error);
  80. static GOptionEntry entries[] =
  81. {
  82. { "connect", 'h', 0, G_OPTION_ARG_STRING, &connect_str,
  83. "Specify host and port", NULL },
  84. { "password", 'P', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK,
  85. &rspamc_password_callback, "Specify control password", NULL },
  86. { "classifier", 'c', 0, G_OPTION_ARG_STRING, &classifier,
  87. "Classifier to learn spam or ham", NULL },
  88. { "weight", 'w', 0, G_OPTION_ARG_INT, &weight,
  89. "Weight for fuzzy operations", NULL },
  90. { "flag", 'f', 0, G_OPTION_ARG_INT, &flag, "Flag for fuzzy operations",
  91. NULL },
  92. { "pass-all", 'p', 0, G_OPTION_ARG_NONE, &pass_all, "Pass all filters",
  93. NULL },
  94. { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "More verbose output",
  95. NULL },
  96. { "ip", 'i', 0, G_OPTION_ARG_STRING, &ip,
  97. "Emulate that message was received from specified ip address",
  98. NULL },
  99. { "user", 'u', 0, G_OPTION_ARG_STRING, &user,
  100. "Emulate that message was received from specified authenticated user", NULL },
  101. { "deliver", 'd', 0, G_OPTION_ARG_STRING, &deliver_to,
  102. "Emulate that message is delivered to specified user (for LDA/statistics)", NULL },
  103. { "from", 'F', 0, G_OPTION_ARG_STRING, &from,
  104. "Emulate that message has specified SMTP FROM address", NULL },
  105. { "rcpt", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &rcpts,
  106. "Emulate that message has specified SMTP RCPT address", NULL },
  107. { "helo", 0, 0, G_OPTION_ARG_STRING, &helo,
  108. "Imitate SMTP HELO passing from MTA", NULL },
  109. { "hostname", 0, 0, G_OPTION_ARG_STRING, &hostname,
  110. "Imitate hostname passing from MTA", NULL },
  111. { "timeout", 't', 0, G_OPTION_ARG_DOUBLE, &timeout,
  112. "Time in seconds to wait for a reply", NULL },
  113. { "bind", 'b', 0, G_OPTION_ARG_STRING, &local_addr,
  114. "Bind to specified ip address", NULL },
  115. { "commands", 0, 0, G_OPTION_ARG_NONE, &print_commands,
  116. "List available commands", NULL },
  117. { "json", 'j', 0, G_OPTION_ARG_NONE, &json, "Output json reply", NULL },
  118. { "compact", '\0', 0, G_OPTION_ARG_NONE, &compact, "Output compact json reply", NULL},
  119. { "headers", 0, 0, G_OPTION_ARG_NONE, &headers, "Output HTTP headers",
  120. NULL },
  121. { "raw", 0, 0, G_OPTION_ARG_NONE, &raw, "Output raw reply from rspamd",
  122. NULL },
  123. { "ucl", 0, 0, G_OPTION_ARG_NONE, &raw, "Output ucl reply from rspamd",
  124. NULL },
  125. { "max-requests", 'n', 0, G_OPTION_ARG_INT, &max_requests,
  126. "Maximum count of parallel requests to rspamd", NULL },
  127. { "extended-urls", 0, 0, G_OPTION_ARG_NONE, &extended_urls,
  128. "Output urls in extended format", NULL },
  129. { "key", 0, 0, G_OPTION_ARG_STRING, &key,
  130. "Use specified pubkey to encrypt request", NULL },
  131. { "exec", 'e', 0, G_OPTION_ARG_STRING, &execute,
  132. "Execute the specified command and pass output to it", NULL },
  133. { "mime", 'm', 0, G_OPTION_ARG_NONE, &mime_output,
  134. "Write mime body of message with headers instead of just a scan's result", NULL },
  135. {"header", 0, 0, G_OPTION_ARG_STRING_ARRAY, &http_headers,
  136. "Add custom HTTP header to query (can be repeated)", NULL},
  137. {"exclude", 0, 0, G_OPTION_ARG_STRING_ARRAY, &exclude_patterns,
  138. "Exclude specific glob patterns in file names (can be repeated)", NULL},
  139. {"sort", 0, 0, G_OPTION_ARG_STRING, &sort,
  140. "Sort output in a specific order (name, weight, frequency, hits)", NULL},
  141. { "empty", 'E', 0, G_OPTION_ARG_NONE, &empty_input,
  142. "Allow empty input instead of reading from stdin", NULL },
  143. { "fuzzy-symbol", 'S', 0, G_OPTION_ARG_STRING, &fuzzy_symbol,
  144. "Learn the specified fuzzy symbol", NULL },
  145. { "compressed", 'z', 0, G_OPTION_ARG_NONE, &compressed,
  146. "Enable zstd compression", NULL },
  147. { "profile", '\0', 0, G_OPTION_ARG_NONE, &profile,
  148. "Profile symbols execution time", NULL },
  149. { "dictionary", 'D', 0, G_OPTION_ARG_FILENAME, &dictionary,
  150. "Use dictionary to compress data", NULL },
  151. { "skip-images", '\0', 0, G_OPTION_ARG_NONE, &skip_images,
  152. "Skip images when learning/unlearning fuzzy", NULL },
  153. { "skip-attachments", '\0', 0, G_OPTION_ARG_NONE, &skip_attachments,
  154. "Skip attachments when learning/unlearning fuzzy", NULL },
  155. { "user-agent", 'U', 0, G_OPTION_ARG_STRING, &user_agent,
  156. "Use specific User-Agent instead of \"rspamc\"", NULL },
  157. { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL }
  158. };
  159. /* Copy to avoid linking with librspamdserver */
  160. enum rspamd_action_type {
  161. METRIC_ACTION_REJECT = 0,
  162. METRIC_ACTION_SOFT_REJECT,
  163. METRIC_ACTION_REWRITE_SUBJECT,
  164. METRIC_ACTION_ADD_HEADER,
  165. METRIC_ACTION_GREYLIST,
  166. METRIC_ACTION_NOACTION,
  167. METRIC_ACTION_MAX
  168. };
  169. static void rspamc_symbols_output (FILE *out, ucl_object_t *obj);
  170. static void rspamc_uptime_output (FILE *out, ucl_object_t *obj);
  171. static void rspamc_counters_output (FILE *out, ucl_object_t *obj);
  172. static void rspamc_stat_output (FILE *out, ucl_object_t *obj);
  173. enum rspamc_command_type {
  174. RSPAMC_COMMAND_UNKNOWN = 0,
  175. RSPAMC_COMMAND_CHECK,
  176. RSPAMC_COMMAND_SYMBOLS,
  177. RSPAMC_COMMAND_LEARN_SPAM,
  178. RSPAMC_COMMAND_LEARN_HAM,
  179. RSPAMC_COMMAND_FUZZY_ADD,
  180. RSPAMC_COMMAND_FUZZY_DEL,
  181. RSPAMC_COMMAND_FUZZY_DELHASH,
  182. RSPAMC_COMMAND_STAT,
  183. RSPAMC_COMMAND_STAT_RESET,
  184. RSPAMC_COMMAND_COUNTERS,
  185. RSPAMC_COMMAND_UPTIME,
  186. RSPAMC_COMMAND_ADD_SYMBOL,
  187. RSPAMC_COMMAND_ADD_ACTION
  188. };
  189. struct rspamc_command {
  190. enum rspamc_command_type cmd;
  191. const char *name;
  192. const char *description;
  193. const char *path;
  194. gboolean is_controller;
  195. gboolean is_privileged;
  196. gboolean need_input;
  197. void (*command_output_func)(FILE *, ucl_object_t *obj);
  198. } rspamc_commands[] = {
  199. {
  200. .cmd = RSPAMC_COMMAND_SYMBOLS,
  201. .name = "symbols",
  202. .path = "checkv2",
  203. .description = "scan message and show symbols (default command)",
  204. .is_controller = FALSE,
  205. .is_privileged = FALSE,
  206. .need_input = TRUE,
  207. .command_output_func = rspamc_symbols_output
  208. },
  209. {
  210. .cmd = RSPAMC_COMMAND_LEARN_SPAM,
  211. .name = "learn_spam",
  212. .path = "learnspam",
  213. .description = "learn message as spam",
  214. .is_controller = TRUE,
  215. .is_privileged = TRUE,
  216. .need_input = TRUE,
  217. .command_output_func = NULL
  218. },
  219. {
  220. .cmd = RSPAMC_COMMAND_LEARN_HAM,
  221. .name = "learn_ham",
  222. .path = "learnham",
  223. .description = "learn message as ham",
  224. .is_controller = TRUE,
  225. .is_privileged = TRUE,
  226. .need_input = TRUE,
  227. .command_output_func = NULL
  228. },
  229. {
  230. .cmd = RSPAMC_COMMAND_FUZZY_ADD,
  231. .name = "fuzzy_add",
  232. .path = "fuzzyadd",
  233. .description =
  234. "add hashes from a message to the fuzzy storage (check -f and -w options for this command)",
  235. .is_controller = TRUE,
  236. .is_privileged = TRUE,
  237. .need_input = TRUE,
  238. .command_output_func = NULL
  239. },
  240. {
  241. .cmd = RSPAMC_COMMAND_FUZZY_DEL,
  242. .name = "fuzzy_del",
  243. .path = "fuzzydel",
  244. .description =
  245. "delete hashes from a message from the fuzzy storage (check -f option for this command)",
  246. .is_controller = TRUE,
  247. .is_privileged = TRUE,
  248. .need_input = TRUE,
  249. .command_output_func = NULL
  250. },
  251. {
  252. .cmd = RSPAMC_COMMAND_FUZZY_DELHASH,
  253. .name = "fuzzy_delhash",
  254. .path = "fuzzydelhash",
  255. .description =
  256. "delete a hash from fuzzy storage (check -f option for this command)",
  257. .is_controller = TRUE,
  258. .is_privileged = TRUE,
  259. .need_input = FALSE,
  260. .command_output_func = NULL
  261. },
  262. {
  263. .cmd = RSPAMC_COMMAND_STAT,
  264. .name = "stat",
  265. .path = "stat",
  266. .description = "show rspamd statistics",
  267. .is_controller = TRUE,
  268. .is_privileged = FALSE,
  269. .need_input = FALSE,
  270. .command_output_func = rspamc_stat_output,
  271. },
  272. {
  273. .cmd = RSPAMC_COMMAND_STAT_RESET,
  274. .name = "stat_reset",
  275. .path = "statreset",
  276. .description = "show and reset rspamd statistics (useful for graphs)",
  277. .is_controller = TRUE,
  278. .is_privileged = TRUE,
  279. .need_input = FALSE,
  280. .command_output_func = rspamc_stat_output
  281. },
  282. {
  283. .cmd = RSPAMC_COMMAND_COUNTERS,
  284. .name = "counters",
  285. .path = "counters",
  286. .description = "display rspamd symbols statistics",
  287. .is_controller = TRUE,
  288. .is_privileged = FALSE,
  289. .need_input = FALSE,
  290. .command_output_func = rspamc_counters_output
  291. },
  292. {
  293. .cmd = RSPAMC_COMMAND_UPTIME,
  294. .name = "uptime",
  295. .path = "auth",
  296. .description = "show rspamd uptime",
  297. .is_controller = TRUE,
  298. .is_privileged = FALSE,
  299. .need_input = FALSE,
  300. .command_output_func = rspamc_uptime_output
  301. },
  302. {
  303. .cmd = RSPAMC_COMMAND_ADD_SYMBOL,
  304. .name = "add_symbol",
  305. .path = "addsymbol",
  306. .description = "add or modify symbol settings in rspamd",
  307. .is_controller = TRUE,
  308. .is_privileged = TRUE,
  309. .need_input = FALSE,
  310. .command_output_func = NULL
  311. },
  312. {
  313. .cmd = RSPAMC_COMMAND_ADD_ACTION,
  314. .name = "add_action",
  315. .path = "addaction",
  316. .description = "add or modify action settings",
  317. .is_controller = TRUE,
  318. .is_privileged = TRUE,
  319. .need_input = FALSE,
  320. .command_output_func = NULL
  321. }
  322. };
  323. struct rspamc_callback_data {
  324. struct rspamc_command *cmd;
  325. gchar *filename;
  326. };
  327. gboolean
  328. rspamc_password_callback (const gchar *option_name,
  329. const gchar *value,
  330. gpointer data,
  331. GError **error)
  332. {
  333. guint plen = 8192;
  334. guint8 *map, *end;
  335. gsize sz;
  336. if (value != NULL) {
  337. if (value[0] == '/' || value[0] == '.') {
  338. /* Try to open file */
  339. map = rspamd_file_xmap (value, PROT_READ, &sz, 0);
  340. if (map == NULL) {
  341. /* Just use it as a string */
  342. password = g_strdup (value);
  343. }
  344. else {
  345. /* Strip trailing spaces */
  346. g_assert (sz > 0);
  347. end = map + sz - 1;
  348. while (g_ascii_isspace (*end) && end > map) {
  349. end --;
  350. }
  351. end ++;
  352. password = g_malloc (end - map + 1);
  353. rspamd_strlcpy (password, map, end - map + 1);
  354. munmap (map, sz);
  355. }
  356. }
  357. else {
  358. password = g_strdup (value);
  359. }
  360. }
  361. else {
  362. /* Read password from console */
  363. password = g_malloc0 (plen);
  364. plen = rspamd_read_passphrase (password, plen, 0, NULL);
  365. }
  366. if (plen == 0) {
  367. rspamd_fprintf (stderr, "Invalid password\n");
  368. exit (EXIT_FAILURE);
  369. }
  370. return TRUE;
  371. }
  372. /*
  373. * Parse command line
  374. */
  375. static void
  376. read_cmd_line (gint *argc, gchar ***argv)
  377. {
  378. GError *error = NULL;
  379. GOptionContext *context;
  380. /* Prepare parser */
  381. context = g_option_context_new ("- run rspamc client");
  382. g_option_context_set_summary (context,
  383. "Summary:\n Rspamd client version " RVERSION "\n Release id: " RID);
  384. g_option_context_add_main_entries (context, entries, NULL);
  385. /* Parse options */
  386. if (!g_option_context_parse (context, argc, argv, &error)) {
  387. fprintf (stderr, "option parsing failed: %s\n", error->message);
  388. exit (EXIT_FAILURE);
  389. }
  390. if (json || compact) {
  391. raw = TRUE;
  392. }
  393. /* Argc and argv are shifted after this function */
  394. }
  395. static gboolean
  396. rspamd_action_from_str_rspamc (const gchar *data, gint *result)
  397. {
  398. if (strcmp (data, "reject") == 0) {
  399. *result = METRIC_ACTION_REJECT;
  400. }
  401. else if (strcmp (data, "greylist") == 0) {
  402. *result = METRIC_ACTION_GREYLIST;
  403. }
  404. else if (strcmp (data, "add_header") == 0) {
  405. *result = METRIC_ACTION_ADD_HEADER;
  406. }
  407. else if (strcmp (data, "rewrite_subject") == 0) {
  408. *result = METRIC_ACTION_REWRITE_SUBJECT;
  409. }
  410. else if (strcmp (data, "add header") == 0) {
  411. *result = METRIC_ACTION_ADD_HEADER;
  412. }
  413. else if (strcmp (data, "rewrite subject") == 0) {
  414. *result = METRIC_ACTION_REWRITE_SUBJECT;
  415. }
  416. else if (strcmp (data, "soft_reject") == 0) {
  417. *result = METRIC_ACTION_SOFT_REJECT;
  418. }
  419. else if (strcmp (data, "soft reject") == 0) {
  420. *result = METRIC_ACTION_SOFT_REJECT;
  421. }
  422. else if (strcmp (data, "no_action") == 0) {
  423. *result = METRIC_ACTION_NOACTION;
  424. }
  425. else if (strcmp (data, "no action") == 0) {
  426. *result = METRIC_ACTION_NOACTION;
  427. }
  428. else {
  429. return FALSE;
  430. }
  431. return TRUE;
  432. }
  433. /*
  434. * Check rspamc command from string (used for arguments parsing)
  435. */
  436. static struct rspamc_command *
  437. check_rspamc_command (const gchar *cmd)
  438. {
  439. enum rspamc_command_type ct = 0;
  440. guint i;
  441. if (g_ascii_strcasecmp (cmd, "SYMBOLS") == 0 ||
  442. g_ascii_strcasecmp (cmd, "CHECK") == 0 ||
  443. g_ascii_strcasecmp (cmd, "REPORT") == 0) {
  444. /* These all are symbols, don't use other commands */
  445. ct = RSPAMC_COMMAND_SYMBOLS;
  446. }
  447. else if (g_ascii_strcasecmp (cmd, "LEARN_SPAM") == 0) {
  448. ct = RSPAMC_COMMAND_LEARN_SPAM;
  449. }
  450. else if (g_ascii_strcasecmp (cmd, "LEARN_HAM") == 0) {
  451. ct = RSPAMC_COMMAND_LEARN_HAM;
  452. }
  453. else if (g_ascii_strcasecmp (cmd, "FUZZY_ADD") == 0) {
  454. ct = RSPAMC_COMMAND_FUZZY_ADD;
  455. }
  456. else if (g_ascii_strcasecmp (cmd, "FUZZY_DEL") == 0) {
  457. ct = RSPAMC_COMMAND_FUZZY_DEL;
  458. }
  459. else if (g_ascii_strcasecmp (cmd, "FUZZY_DELHASH") == 0) {
  460. ct = RSPAMC_COMMAND_FUZZY_DELHASH;
  461. }
  462. else if (g_ascii_strcasecmp (cmd, "STAT") == 0) {
  463. ct = RSPAMC_COMMAND_STAT;
  464. }
  465. else if (g_ascii_strcasecmp (cmd, "STAT_RESET") == 0) {
  466. ct = RSPAMC_COMMAND_STAT_RESET;
  467. }
  468. else if (g_ascii_strcasecmp (cmd, "COUNTERS") == 0) {
  469. ct = RSPAMC_COMMAND_COUNTERS;
  470. }
  471. else if (g_ascii_strcasecmp (cmd, "UPTIME") == 0) {
  472. ct = RSPAMC_COMMAND_UPTIME;
  473. }
  474. else if (g_ascii_strcasecmp (cmd, "ADD_SYMBOL") == 0) {
  475. ct = RSPAMC_COMMAND_ADD_SYMBOL;
  476. }
  477. else if (g_ascii_strcasecmp (cmd, "ADD_ACTION") == 0) {
  478. ct = RSPAMC_COMMAND_ADD_ACTION;
  479. }
  480. for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
  481. if (rspamc_commands[i].cmd == ct) {
  482. return &rspamc_commands[i];
  483. }
  484. }
  485. return NULL;
  486. }
  487. static void
  488. print_commands_list (void)
  489. {
  490. guint i;
  491. guint cmd_len = 0;
  492. gchar fmt_str[32];
  493. rspamd_fprintf (stdout, "Rspamc commands summary:\n");
  494. for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
  495. gsize clen = strlen (rspamc_commands[i].name);
  496. if (clen > cmd_len) {
  497. cmd_len = clen;
  498. }
  499. }
  500. rspamd_snprintf (fmt_str, sizeof (fmt_str), " %%%ds (%%7s%%1s)\t%%s\n",
  501. cmd_len);
  502. for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) {
  503. fprintf (stdout,
  504. fmt_str,
  505. rspamc_commands[i].name,
  506. rspamc_commands[i].is_controller ? "control" : "normal",
  507. rspamc_commands[i].is_privileged ? "*" : "",
  508. rspamc_commands[i].description);
  509. }
  510. rspamd_fprintf (stdout,
  511. "\n* is for privileged commands that may need password (see -P option)\n");
  512. rspamd_fprintf (stdout,
  513. "control commands use port 11334 while normal use 11333 by default (see -h option)\n");
  514. }
  515. static void
  516. add_options (GQueue *opts)
  517. {
  518. GString *numbuf;
  519. gchar **hdr, **rcpt;
  520. if (user_agent) {
  521. ADD_CLIENT_HEADER (opts, "User-Agent", user_agent);
  522. }
  523. if (ip != NULL) {
  524. rspamd_inet_addr_t *addr = NULL;
  525. if (!rspamd_parse_inet_address (&addr, ip, strlen (ip))) {
  526. /* Try to resolve */
  527. struct addrinfo hints, *res, *cur;
  528. gint r;
  529. memset (&hints, 0, sizeof (hints));
  530. hints.ai_socktype = SOCK_STREAM; /* Type of the socket */
  531. #ifdef AI_IDN
  532. hints.ai_flags = AI_NUMERICSERV|AI_IDN;
  533. #else
  534. hints.ai_flags = AI_NUMERICSERV;
  535. #endif
  536. hints.ai_family = AF_UNSPEC;
  537. if ((r = getaddrinfo (ip, "25", &hints, &res)) == 0) {
  538. cur = res;
  539. while (cur) {
  540. addr = rspamd_inet_address_from_sa (cur->ai_addr,
  541. cur->ai_addrlen);
  542. if (addr != NULL) {
  543. ip = g_strdup (rspamd_inet_address_to_string (addr));
  544. rspamd_inet_address_free (addr);
  545. break;
  546. }
  547. cur = cur->ai_next;
  548. }
  549. freeaddrinfo (res);
  550. }
  551. else {
  552. rspamd_fprintf (stderr, "address resolution for %s failed: %s\n",
  553. ip,
  554. gai_strerror (r));
  555. }
  556. }
  557. else {
  558. rspamd_inet_address_free (addr);
  559. }
  560. ADD_CLIENT_HEADER (opts, "Ip", ip);
  561. }
  562. if (from != NULL) {
  563. ADD_CLIENT_HEADER (opts, "From", from);
  564. }
  565. if (user != NULL) {
  566. ADD_CLIENT_HEADER (opts, "User", user);
  567. }
  568. if (rcpts != NULL) {
  569. for (rcpt = rcpts; *rcpt != NULL; rcpt ++) {
  570. ADD_CLIENT_HEADER (opts, "Rcpt", *rcpt);
  571. }
  572. }
  573. if (deliver_to != NULL) {
  574. ADD_CLIENT_HEADER (opts, "Deliver-To", deliver_to);
  575. }
  576. if (helo != NULL) {
  577. ADD_CLIENT_HEADER (opts, "Helo", helo);
  578. }
  579. if (hostname != NULL) {
  580. ADD_CLIENT_HEADER (opts, "Hostname", hostname);
  581. }
  582. if (password != NULL) {
  583. ADD_CLIENT_HEADER (opts, "Password", password);
  584. }
  585. if (pass_all) {
  586. ADD_CLIENT_HEADER (opts, "Pass", "all");
  587. }
  588. if (classifier) {
  589. ADD_CLIENT_HEADER (opts, "Classifier", classifier);
  590. }
  591. if (weight != 0) {
  592. numbuf = g_string_sized_new (8);
  593. rspamd_printf_gstring (numbuf, "%d", weight);
  594. ADD_CLIENT_HEADER (opts, "Weight", numbuf->str);
  595. }
  596. if (fuzzy_symbol != NULL) {
  597. ADD_CLIENT_HEADER (opts, "Symbol", fuzzy_symbol);
  598. }
  599. if (flag != 0) {
  600. numbuf = g_string_sized_new (8);
  601. rspamd_printf_gstring (numbuf, "%d", flag);
  602. ADD_CLIENT_HEADER (opts, "Flag", numbuf->str);
  603. }
  604. if (extended_urls) {
  605. ADD_CLIENT_HEADER (opts, "URL-Format", "extended");
  606. }
  607. if (profile) {
  608. ADD_CLIENT_HEADER (opts, "Profile", "true");
  609. }
  610. if (skip_images) {
  611. ADD_CLIENT_HEADER (opts, "Skip-Images", "true");
  612. }
  613. if (skip_attachments) {
  614. ADD_CLIENT_HEADER (opts, "Skip-Attachments", "true");
  615. }
  616. hdr = http_headers;
  617. while (hdr != NULL && *hdr != NULL) {
  618. gchar **kv = g_strsplit_set (*hdr, ":=", 2);
  619. if (kv == NULL || kv[1] == NULL) {
  620. ADD_CLIENT_HEADER (opts, *hdr, "");
  621. if (kv) {
  622. g_strfreev (kv);
  623. }
  624. }
  625. else {
  626. ADD_CLIENT_HEADER (opts, kv[0], kv[1]);
  627. }
  628. hdr ++;
  629. }
  630. }
  631. static void
  632. rspamc_symbol_output (FILE *out, const ucl_object_t *obj)
  633. {
  634. const ucl_object_t *val, *cur;
  635. ucl_object_iter_t it = NULL;
  636. gboolean first = TRUE;
  637. rspamd_fprintf (out, "Symbol: %s ", ucl_object_key (obj));
  638. val = ucl_object_lookup (obj, "score");
  639. if (val != NULL) {
  640. rspamd_fprintf (out, "(%.2f)", ucl_object_todouble (val));
  641. }
  642. val = ucl_object_lookup (obj, "options");
  643. if (val != NULL && val->type == UCL_ARRAY) {
  644. rspamd_fprintf (out, "[");
  645. while ((cur = ucl_object_iterate (val, &it, TRUE)) != NULL) {
  646. if (first) {
  647. rspamd_fprintf (out, "%s", ucl_object_tostring (cur));
  648. first = FALSE;
  649. }
  650. else {
  651. rspamd_fprintf (out, ", %s", ucl_object_tostring (cur));
  652. }
  653. }
  654. rspamd_fprintf (out, "]");
  655. }
  656. rspamd_fprintf (out, "\n");
  657. }
  658. static gint
  659. rspamc_symbols_sort_func (gconstpointer a, gconstpointer b)
  660. {
  661. ucl_object_t * const *ua = a, * const *ub = b;
  662. return strcmp (ucl_object_key (*ua), ucl_object_key (*ub));
  663. }
  664. #define PRINT_PROTOCOL_STRING(ucl_name, output_message) do { \
  665. elt = ucl_object_lookup (obj, (ucl_name)); \
  666. if (elt) { \
  667. rspamd_fprintf (out, output_message ": %s\n", ucl_object_tostring (elt)); \
  668. } \
  669. } while (0)
  670. static void
  671. rspamc_metric_output (FILE *out, const ucl_object_t *obj)
  672. {
  673. ucl_object_iter_t it = NULL;
  674. const ucl_object_t *cur, *elt;
  675. gdouble score = 0, required_score = 0;
  676. gint got_scores = 0, action = METRIC_ACTION_MAX;
  677. GPtrArray *sym_ptr;
  678. guint i;
  679. sym_ptr = g_ptr_array_new ();
  680. rspamd_fprintf (out, "[Metric: default]\n");
  681. elt = ucl_object_lookup (obj, "required_score");
  682. if (elt) {
  683. required_score = ucl_object_todouble (elt);
  684. got_scores++;
  685. }
  686. elt = ucl_object_lookup (obj, "score");
  687. if (elt) {
  688. score = ucl_object_todouble (elt);
  689. got_scores++;
  690. }
  691. PRINT_PROTOCOL_STRING ("action", "Action");
  692. /* Defined by previous macro */
  693. if (elt && rspamd_action_from_str_rspamc (ucl_object_tostring (elt), &action)) {
  694. rspamd_fprintf (out, "Spam: %s\n", action < METRIC_ACTION_GREYLIST ?
  695. "true" : "false");
  696. }
  697. PRINT_PROTOCOL_STRING ("subject", "Subject");
  698. if (got_scores == 2) {
  699. rspamd_fprintf (out,
  700. "Score: %.2f / %.2f\n",
  701. score,
  702. required_score);
  703. }
  704. elt = ucl_object_lookup (obj, "symbols");
  705. while (elt && (cur = ucl_object_iterate (elt, &it, true)) != NULL) {
  706. if (cur->type == UCL_OBJECT) {
  707. g_ptr_array_add (sym_ptr, (void *)cur);
  708. }
  709. }
  710. g_ptr_array_sort (sym_ptr, rspamc_symbols_sort_func);
  711. for (i = 0; i < sym_ptr->len; i ++) {
  712. cur = (const ucl_object_t *)g_ptr_array_index (sym_ptr, i);
  713. rspamc_symbol_output (out, cur);
  714. }
  715. g_ptr_array_free (sym_ptr, TRUE);
  716. }
  717. static gint
  718. rspamc_profile_sort_func (gconstpointer a, gconstpointer b)
  719. {
  720. ucl_object_t * const *ua = a, * const *ub = b;
  721. return ucl_object_compare (*ua, *ub);
  722. }
  723. static void
  724. rspamc_profile_output (FILE *out, const ucl_object_t *obj)
  725. {
  726. ucl_object_iter_t it = NULL;
  727. const ucl_object_t *cur;
  728. guint i;
  729. GPtrArray *ar;
  730. ar = g_ptr_array_sized_new (obj->len);
  731. while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
  732. g_ptr_array_add (ar, (void *)cur);
  733. }
  734. g_ptr_array_sort (ar, rspamc_profile_sort_func);
  735. for (i = 0; i < ar->len; i ++) {
  736. cur = (const ucl_object_t *)g_ptr_array_index (ar, i);
  737. rspamd_fprintf (out, "\t%s: %.3f usec\n",
  738. ucl_object_key (cur), ucl_object_todouble (cur));
  739. }
  740. g_ptr_array_free (ar, TRUE);
  741. }
  742. static void
  743. rspamc_symbols_output (FILE *out, ucl_object_t *obj)
  744. {
  745. ucl_object_iter_t mit = NULL;
  746. const ucl_object_t *cmesg, *elt;
  747. gchar *emitted;
  748. rspamc_metric_output (out, obj);
  749. PRINT_PROTOCOL_STRING ("message-id", "Message-ID");
  750. PRINT_PROTOCOL_STRING ("queue-id", "Queue-ID");
  751. elt = ucl_object_lookup (obj, "urls");
  752. if (elt) {
  753. if (!extended_urls || compact) {
  754. emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT);
  755. }
  756. else {
  757. emitted = ucl_object_emit (elt, UCL_EMIT_JSON);
  758. }
  759. rspamd_fprintf (out, "Urls: %s\n", emitted);
  760. free (emitted);
  761. }
  762. elt = ucl_object_lookup (obj, "emails");
  763. if (elt) {
  764. if (!extended_urls || compact) {
  765. emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT);
  766. }
  767. else {
  768. emitted = ucl_object_emit (elt, UCL_EMIT_JSON);
  769. }
  770. rspamd_fprintf (out, "Emails: %s\n", emitted);
  771. free (emitted);
  772. }
  773. PRINT_PROTOCOL_STRING ("error", "Scan error");
  774. elt = ucl_object_lookup (obj, "messages");
  775. if (elt && elt->type == UCL_OBJECT) {
  776. mit = NULL;
  777. while ((cmesg = ucl_object_iterate (elt, &mit, true)) != NULL) {
  778. rspamd_fprintf (out, "Message - %s: %s\n",
  779. ucl_object_key (cmesg), ucl_object_tostring (cmesg));
  780. }
  781. }
  782. PRINT_PROTOCOL_STRING ("dkim-signature", "DKIM-Signature");
  783. elt = ucl_object_lookup (obj, "profile");
  784. if (elt) {
  785. rspamd_fprintf (out, "Profile data:\n");
  786. rspamc_profile_output (out, elt);
  787. }
  788. }
  789. static void
  790. rspamc_uptime_output (FILE *out, ucl_object_t *obj)
  791. {
  792. const ucl_object_t *elt;
  793. int64_t seconds, days, hours, minutes;
  794. elt = ucl_object_lookup (obj, "version");
  795. if (elt != NULL) {
  796. rspamd_fprintf (out, "Rspamd version: %s\n", ucl_object_tostring (
  797. elt));
  798. }
  799. elt = ucl_object_lookup (obj, "uptime");
  800. if (elt != NULL) {
  801. rspamd_printf ("Uptime: ");
  802. seconds = ucl_object_toint (elt);
  803. if (seconds >= 2 * 3600) {
  804. days = seconds / 86400;
  805. hours = seconds / 3600 - days * 24;
  806. minutes = seconds / 60 - hours * 60 - days * 1440;
  807. rspamd_printf ("%L day%s %L hour%s %L minute%s\n", days,
  808. days > 1 ? "s" : "", hours, hours > 1 ? "s" : "",
  809. minutes, minutes > 1 ? "s" : "");
  810. }
  811. /* If uptime is less than 1 minute print only seconds */
  812. else if (seconds / 60 == 0) {
  813. rspamd_printf ("%L second%s\n", seconds,
  814. (gint)seconds > 1 ? "s" : "");
  815. }
  816. /* Else print the minutes and seconds. */
  817. else {
  818. hours = seconds / 3600;
  819. minutes = seconds / 60 - hours * 60;
  820. seconds -= hours * 3600 + minutes * 60;
  821. rspamd_printf ("%L hour %L minute%s %L second%s\n", hours,
  822. minutes, minutes > 1 ? "s" : "",
  823. seconds, seconds > 1 ? "s" : "");
  824. }
  825. }
  826. }
  827. static gint
  828. rspamc_counters_sort (const ucl_object_t **o1, const ucl_object_t **o2)
  829. {
  830. gint order1 = 0, order2 = 0, c;
  831. const ucl_object_t *elt1, *elt2;
  832. gboolean inverse = FALSE;
  833. gchar **args;
  834. if (sort != NULL) {
  835. args = g_strsplit_set (sort, ":", 2);
  836. if (args && args[0]) {
  837. if (args[1] && g_ascii_strcasecmp (args[1], "desc") == 0) {
  838. inverse = TRUE;
  839. }
  840. if (g_ascii_strcasecmp (args[0], "name") == 0) {
  841. elt1 = ucl_object_lookup (*o1, "symbol");
  842. elt2 = ucl_object_lookup (*o2, "symbol");
  843. if (elt1 && elt2) {
  844. c = strcmp (ucl_object_tostring (elt1),
  845. ucl_object_tostring (elt2));
  846. order1 = c > 0 ? 1 : 0;
  847. order2 = c < 0 ? 1 : 0;
  848. }
  849. }
  850. else if (g_ascii_strcasecmp (args[0], "weight") == 0) {
  851. elt1 = ucl_object_lookup (*o1, "weight");
  852. elt2 = ucl_object_lookup (*o2, "weight");
  853. if (elt1 && elt2) {
  854. order1 = ucl_object_todouble (elt1) * 1000.0;
  855. order2 = ucl_object_todouble (elt2) * 1000.0;
  856. }
  857. }
  858. else if (g_ascii_strcasecmp (args[0], "frequency") == 0) {
  859. elt1 = ucl_object_lookup (*o1, "frequency");
  860. elt2 = ucl_object_lookup (*o2, "frequency");
  861. if (elt1 && elt2) {
  862. order1 = ucl_object_todouble (elt1) * 100000;
  863. order2 = ucl_object_todouble (elt2) * 100000;
  864. }
  865. }
  866. else if (g_ascii_strcasecmp (args[0], "time") == 0) {
  867. elt1 = ucl_object_lookup (*o1, "time");
  868. elt2 = ucl_object_lookup (*o2, "time");
  869. if (elt1 && elt2) {
  870. order1 = ucl_object_todouble (elt1) * 1000000;
  871. order2 = ucl_object_todouble (elt2) * 1000000;
  872. }
  873. }
  874. else if (g_ascii_strcasecmp (args[0], "hits") == 0) {
  875. elt1 = ucl_object_lookup (*o1, "hits");
  876. elt2 = ucl_object_lookup (*o2, "hits");
  877. if (elt1 && elt2) {
  878. order1 = ucl_object_toint (elt1);
  879. order2 = ucl_object_toint (elt2);
  880. }
  881. }
  882. g_strfreev (args);
  883. }
  884. }
  885. return (inverse ? (order2 - order1) : (order1 - order2));
  886. }
  887. static void
  888. rspamc_counters_output (FILE *out, ucl_object_t *obj)
  889. {
  890. const ucl_object_t *cur, *sym, *weight, *freq, *freq_dev, *nhits;
  891. ucl_object_iter_t iter = NULL;
  892. gchar fmt_buf[64], dash_buf[82], sym_buf[82];
  893. gint l, max_len = INT_MIN, i;
  894. static const gint dashes = 44;
  895. if (obj->type != UCL_ARRAY) {
  896. rspamd_printf ("Bad output\n");
  897. return;
  898. }
  899. /* Sort symbols by their order */
  900. if (sort != NULL) {
  901. ucl_object_array_sort (obj, rspamc_counters_sort);
  902. }
  903. /* Find maximum width of symbol's name */
  904. while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) {
  905. sym = ucl_object_lookup (cur, "symbol");
  906. if (sym != NULL) {
  907. l = sym->len;
  908. if (l > max_len) {
  909. max_len = MIN (sizeof (dash_buf) - dashes - 1, l);
  910. }
  911. }
  912. }
  913. rspamd_snprintf (fmt_buf, sizeof (fmt_buf),
  914. "| %%3s | %%%ds | %%7s | %%13s | %%7s |\n", max_len);
  915. memset (dash_buf, '-', dashes + max_len);
  916. dash_buf[dashes + max_len] = '\0';
  917. printf ("Symbols cache\n");
  918. printf (" %s \n", dash_buf);
  919. if (tty) {
  920. printf ("\033[1m");
  921. }
  922. printf (fmt_buf, "Pri", "Symbol", "Weight", "Frequency", "Hits");
  923. printf (" %s \n", dash_buf);
  924. printf (fmt_buf, "", "", "", "hits/min", "");
  925. if (tty) {
  926. printf ("\033[0m");
  927. }
  928. rspamd_snprintf (fmt_buf, sizeof (fmt_buf),
  929. "| %%3d | %%%ds | %%7.1f | %%6.3f(%%5.3f) | %%7ju |\n", max_len);
  930. iter = NULL;
  931. i = 0;
  932. while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) {
  933. printf (" %s \n", dash_buf);
  934. sym = ucl_object_lookup (cur, "symbol");
  935. weight = ucl_object_lookup (cur, "weight");
  936. freq = ucl_object_lookup (cur, "frequency");
  937. freq_dev = ucl_object_lookup (cur, "frequency_stddev");
  938. nhits = ucl_object_lookup (cur, "hits");
  939. if (sym && weight && freq && nhits) {
  940. const gchar *sym_name;
  941. if (sym->len > max_len) {
  942. rspamd_snprintf (sym_buf, sizeof (sym_buf), "%*s...",
  943. (max_len - 3), ucl_object_tostring (sym));
  944. sym_name = sym_buf;
  945. }
  946. else {
  947. sym_name = ucl_object_tostring (sym);
  948. }
  949. printf (fmt_buf, i,
  950. sym_name,
  951. ucl_object_todouble (weight),
  952. ucl_object_todouble (freq) * 60.0,
  953. ucl_object_todouble (freq_dev) * 60.0,
  954. (uintmax_t)ucl_object_toint (nhits));
  955. }
  956. i++;
  957. }
  958. printf (" %s \n", dash_buf);
  959. }
  960. static void
  961. rspamc_stat_actions (ucl_object_t *obj, GString *out, gint64 scanned)
  962. {
  963. const ucl_object_t *actions = ucl_object_lookup (obj, "actions"), *cur;
  964. ucl_object_iter_t iter = NULL;
  965. gint64 spam, ham;
  966. if (actions && ucl_object_type (actions) == UCL_OBJECT) {
  967. while ((cur = ucl_object_iterate (actions, &iter, true)) != NULL) {
  968. gint64 cnt = ucl_object_toint (cur);
  969. rspamd_printf_gstring (out, "Messages with action %s: %L"
  970. ", %.2f%%\n", ucl_object_key (cur), cnt,
  971. ((gdouble)cnt / (gdouble)scanned) * 100.);
  972. }
  973. }
  974. spam = ucl_object_toint (ucl_object_lookup (obj, "spam_count"));
  975. ham = ucl_object_toint (ucl_object_lookup (obj, "ham_count"));
  976. rspamd_printf_gstring (out, "Messages treated as spam: %L, %.2f%%\n", spam,
  977. ((gdouble)spam / (gdouble)scanned) * 100.);
  978. rspamd_printf_gstring (out, "Messages treated as ham: %L, %.2f%%\n", ham,
  979. ((gdouble)ham / (gdouble)scanned) * 100.);
  980. }
  981. static void
  982. rspamc_stat_statfile (const ucl_object_t *obj, GString *out)
  983. {
  984. gint64 version, size, blocks, used_blocks, nlanguages, nusers;
  985. const gchar *label, *symbol, *type;
  986. version = ucl_object_toint (ucl_object_lookup (obj, "revision"));
  987. size = ucl_object_toint (ucl_object_lookup (obj, "size"));
  988. blocks = ucl_object_toint (ucl_object_lookup (obj, "total"));
  989. used_blocks = ucl_object_toint (ucl_object_lookup (obj, "used"));
  990. label = ucl_object_tostring (ucl_object_lookup (obj, "label"));
  991. symbol = ucl_object_tostring (ucl_object_lookup (obj, "symbol"));
  992. type = ucl_object_tostring (ucl_object_lookup (obj, "type"));
  993. nlanguages = ucl_object_toint (ucl_object_lookup (obj, "languages"));
  994. nusers = ucl_object_toint (ucl_object_lookup (obj, "users"));
  995. if (label) {
  996. rspamd_printf_gstring (out, "Statfile: %s <%s> type: %s; ", symbol,
  997. label, type);
  998. }
  999. else {
  1000. rspamd_printf_gstring (out, "Statfile: %s type: %s; ", symbol, type);
  1001. }
  1002. rspamd_printf_gstring (out, "length: %hL; free blocks: %hL; total blocks: %hL; "
  1003. "free: %.2f%%; learned: %L; users: %L; languages: %L\n",
  1004. size,
  1005. blocks - used_blocks, blocks,
  1006. blocks > 0 ? (blocks - used_blocks) * 100.0 / (gdouble)blocks : 0,
  1007. version,
  1008. nusers, nlanguages);
  1009. }
  1010. static void
  1011. rspamc_stat_output (FILE *out, ucl_object_t *obj)
  1012. {
  1013. GString *out_str;
  1014. ucl_object_iter_t iter = NULL;
  1015. const ucl_object_t *st, *cur;
  1016. gint64 scanned;
  1017. out_str = g_string_sized_new (BUFSIZ);
  1018. scanned = ucl_object_toint (ucl_object_lookup (obj, "scanned"));
  1019. rspamd_printf_gstring (out_str, "Messages scanned: %L\n",
  1020. scanned);
  1021. if (scanned > 0) {
  1022. rspamc_stat_actions (obj, out_str, scanned);
  1023. }
  1024. rspamd_printf_gstring (out_str, "Messages learned: %L\n",
  1025. ucl_object_toint (ucl_object_lookup (obj, "learned")));
  1026. rspamd_printf_gstring (out_str, "Connections count: %L\n",
  1027. ucl_object_toint (ucl_object_lookup (obj, "connections")));
  1028. rspamd_printf_gstring (out_str, "Control connections count: %L\n",
  1029. ucl_object_toint (ucl_object_lookup (obj, "control_connections")));
  1030. /* Pools */
  1031. rspamd_printf_gstring (out_str, "Pools allocated: %L\n",
  1032. ucl_object_toint (ucl_object_lookup (obj, "pools_allocated")));
  1033. rspamd_printf_gstring (out_str, "Pools freed: %L\n",
  1034. ucl_object_toint (ucl_object_lookup (obj, "pools_freed")));
  1035. rspamd_printf_gstring (out_str, "Bytes allocated: %HL\n",
  1036. ucl_object_toint (ucl_object_lookup (obj, "bytes_allocated")));
  1037. rspamd_printf_gstring (out_str, "Memory chunks allocated: %L\n",
  1038. ucl_object_toint (ucl_object_lookup (obj, "chunks_allocated")));
  1039. rspamd_printf_gstring (out_str, "Shared chunks allocated: %L\n",
  1040. ucl_object_toint (ucl_object_lookup (obj, "shared_chunks_allocated")));
  1041. rspamd_printf_gstring (out_str, "Chunks freed: %L\n",
  1042. ucl_object_toint (ucl_object_lookup (obj, "chunks_freed")));
  1043. rspamd_printf_gstring (out_str, "Oversized chunks: %L\n",
  1044. ucl_object_toint (ucl_object_lookup (obj, "chunks_oversized")));
  1045. /* Fuzzy */
  1046. st = ucl_object_lookup (obj, "fuzzy_hashes");
  1047. if (st) {
  1048. ucl_object_iter_t it = NULL;
  1049. const ucl_object_t *cur;
  1050. gint64 stored = 0;
  1051. while ((cur = ucl_iterate_object (st, &it, true)) != NULL) {
  1052. rspamd_printf_gstring (out_str, "Fuzzy hashes in storage \"%s\": %L\n",
  1053. ucl_object_key (cur),
  1054. ucl_object_toint (cur));
  1055. stored += ucl_object_toint (cur);
  1056. }
  1057. rspamd_printf_gstring (out_str, "Fuzzy hashes stored: %L\n",
  1058. stored);
  1059. }
  1060. st = ucl_object_lookup (obj, "fuzzy_checked");
  1061. if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
  1062. rspamd_printf_gstring (out_str, "Fuzzy hashes checked: ");
  1063. iter = NULL;
  1064. while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
  1065. rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur));
  1066. }
  1067. rspamd_printf_gstring (out_str, "\n");
  1068. }
  1069. st = ucl_object_lookup (obj, "fuzzy_found");
  1070. if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
  1071. rspamd_printf_gstring (out_str, "Fuzzy hashes found: ");
  1072. iter = NULL;
  1073. while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
  1074. rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur));
  1075. }
  1076. rspamd_printf_gstring (out_str, "\n");
  1077. }
  1078. st = ucl_object_lookup (obj, "statfiles");
  1079. if (st != NULL && ucl_object_type (st) == UCL_ARRAY) {
  1080. iter = NULL;
  1081. while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) {
  1082. rspamc_stat_statfile (cur, out_str);
  1083. }
  1084. }
  1085. rspamd_printf_gstring (out_str, "Total learns: %L\n",
  1086. ucl_object_toint (ucl_object_lookup (obj, "total_learns")));
  1087. rspamd_fprintf (out, "%v", out_str);
  1088. }
  1089. static void
  1090. rspamc_output_headers (FILE *out, struct rspamd_http_message *msg)
  1091. {
  1092. struct rspamd_http_header *h, *htmp;
  1093. HASH_ITER (hh, msg->headers, h, htmp) {
  1094. rspamd_fprintf (out, "%T: %T\n", &h->name, &h->value);
  1095. }
  1096. rspamd_fprintf (out, "\n");
  1097. }
  1098. static void
  1099. rspamc_mime_output (FILE *out, ucl_object_t *result, GString *input,
  1100. gdouble time, GError *err)
  1101. {
  1102. const ucl_object_t *cur, *res, *syms;
  1103. ucl_object_iter_t it = NULL;
  1104. const gchar *action = "no action", *line_end = "\r\n", *p;
  1105. gchar scorebuf[32];
  1106. GString *symbuf, *folded_symbuf, *added_headers;
  1107. gint act = 0;
  1108. goffset headers_pos;
  1109. gdouble score = 0.0, required_score = 0.0;
  1110. gboolean is_spam = FALSE;
  1111. gchar *json_header, *json_header_encoded, *sc;
  1112. enum rspamd_newlines_type nl_type = RSPAMD_TASK_NEWLINES_CRLF;
  1113. headers_pos = rspamd_string_find_eoh (input, NULL);
  1114. if (headers_pos == -1) {
  1115. rspamd_fprintf (stderr,"cannot find end of headers position");
  1116. return;
  1117. }
  1118. p = input->str + headers_pos;
  1119. if (headers_pos > 1 && *(p - 1) == '\n') {
  1120. if (headers_pos > 2 && *(p - 2) == '\r') {
  1121. line_end = "\r\n";
  1122. nl_type = RSPAMD_TASK_NEWLINES_CRLF;
  1123. }
  1124. else {
  1125. line_end = "\n";
  1126. nl_type = RSPAMD_TASK_NEWLINES_LF;
  1127. }
  1128. }
  1129. else if (headers_pos > 1 && *(p - 1) == '\r') {
  1130. line_end = "\r";
  1131. nl_type = RSPAMD_TASK_NEWLINES_CR;
  1132. }
  1133. added_headers = g_string_sized_new (127);
  1134. if (result) {
  1135. res = ucl_object_lookup (result, "action");
  1136. if (res) {
  1137. action = ucl_object_tostring (res);
  1138. }
  1139. res = ucl_object_lookup (result, "score");
  1140. if (res) {
  1141. score = ucl_object_todouble (res);
  1142. }
  1143. res = ucl_object_lookup (result, "required_score");
  1144. if (res) {
  1145. required_score = ucl_object_todouble (res);
  1146. }
  1147. rspamd_action_from_str_rspamc (action, &act);
  1148. if (act < METRIC_ACTION_GREYLIST) {
  1149. is_spam = TRUE;
  1150. }
  1151. rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s",
  1152. "rspamc " RVERSION, line_end);
  1153. rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s",
  1154. time, line_end);
  1155. /*
  1156. * TODO: add rmilter_headers support here
  1157. */
  1158. if (is_spam) {
  1159. rspamd_printf_gstring (added_headers, "X-Spam: yes%s", line_end);
  1160. }
  1161. rspamd_printf_gstring (added_headers, "X-Spam-Action: %s%s",
  1162. action, line_end);
  1163. rspamd_printf_gstring (added_headers, "X-Spam-Score: %.2f / %.2f%s",
  1164. score, required_score, line_end);
  1165. /* SA style stars header */
  1166. for (sc = scorebuf; sc < scorebuf + sizeof (scorebuf) - 1 && score > 0;
  1167. sc ++, score -= 1.0) {
  1168. *sc = '*';
  1169. }
  1170. *sc = '\0';
  1171. rspamd_printf_gstring (added_headers, "X-Spam-Level: %s%s",
  1172. scorebuf, line_end);
  1173. /* Short description of all symbols */
  1174. symbuf = g_string_sized_new (64);
  1175. syms = ucl_object_lookup (result, "symbols");
  1176. while (syms && (cur = ucl_object_iterate (syms, &it, true)) != NULL) {
  1177. if (ucl_object_type (cur) == UCL_OBJECT) {
  1178. rspamd_printf_gstring (symbuf, "%s,", ucl_object_key (cur));
  1179. }
  1180. }
  1181. /* Trim the last comma */
  1182. if (symbuf->str[symbuf->len - 1] == ',') {
  1183. g_string_erase (symbuf, symbuf->len - 1, 1);
  1184. }
  1185. folded_symbuf = rspamd_header_value_fold ("X-Spam-Symbols",
  1186. symbuf->str,
  1187. 0, nl_type, ",");
  1188. rspamd_printf_gstring (added_headers, "X-Spam-Symbols: %v%s",
  1189. folded_symbuf, line_end);
  1190. g_string_free (folded_symbuf, TRUE);
  1191. g_string_free (symbuf, TRUE);
  1192. if (ucl_object_lookup (result, "dkim-signature")) {
  1193. rspamd_printf_gstring (added_headers, "DKIM-Signature: %s%s",
  1194. ucl_object_tostring (
  1195. ucl_object_lookup (result, "dkim-signature")),
  1196. line_end);
  1197. }
  1198. if (json || raw || compact) {
  1199. /* We also append json data as a specific header */
  1200. if (json) {
  1201. json_header = ucl_object_emit (result,
  1202. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1203. }
  1204. else {
  1205. json_header = ucl_object_emit (result,
  1206. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1207. }
  1208. json_header_encoded = rspamd_encode_base64_fold (json_header,
  1209. strlen (json_header), 60, NULL, nl_type);
  1210. free (json_header);
  1211. rspamd_printf_gstring (added_headers,
  1212. "X-Spam-Result: %s%s",
  1213. json_header_encoded, line_end);
  1214. g_free (json_header_encoded);
  1215. }
  1216. ucl_object_unref (result);
  1217. }
  1218. else {
  1219. rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s",
  1220. "rspamc " RVERSION, line_end);
  1221. rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s",
  1222. time, line_end);
  1223. rspamd_printf_gstring (added_headers, "X-Spam-Error: %e%s",
  1224. err, line_end);
  1225. }
  1226. /* Write message */
  1227. if (rspamd_fprintf (out, "%*s", (gint)headers_pos, input->str)
  1228. == headers_pos) {
  1229. if (rspamd_fprintf (out, "%v", added_headers)
  1230. == (gint)added_headers->len) {
  1231. rspamd_fprintf (out, "%s", input->str + headers_pos);
  1232. }
  1233. }
  1234. g_string_free (added_headers, TRUE);
  1235. }
  1236. static void
  1237. rspamc_client_execute_cmd (struct rspamc_command *cmd, ucl_object_t *result,
  1238. GString *input, gdouble time, GError *err)
  1239. {
  1240. gchar **eargv;
  1241. gint eargc, infd, outfd, errfd;
  1242. GError *exec_err = NULL;
  1243. GPid cld;
  1244. FILE *out;
  1245. gchar *ucl_out;
  1246. if (!g_shell_parse_argv (execute, &eargc, &eargv, &err)) {
  1247. rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, err);
  1248. g_error_free (err);
  1249. return;
  1250. }
  1251. if (!g_spawn_async_with_pipes (NULL, eargv, NULL,
  1252. G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &cld,
  1253. &infd, &outfd, &errfd, &exec_err)) {
  1254. rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, exec_err);
  1255. g_error_free (exec_err);
  1256. exit (EXIT_FAILURE);
  1257. }
  1258. else {
  1259. children = g_list_prepend (children, GSIZE_TO_POINTER (cld));
  1260. out = fdopen (infd, "w");
  1261. if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
  1262. rspamc_mime_output (out, result, input, time, err);
  1263. }
  1264. else if (result) {
  1265. if (raw || cmd->command_output_func == NULL) {
  1266. if (json) {
  1267. ucl_out = ucl_object_emit (result,
  1268. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1269. }
  1270. else {
  1271. ucl_out = ucl_object_emit (result,
  1272. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1273. }
  1274. rspamd_fprintf (out, "%s", ucl_out);
  1275. free (ucl_out);
  1276. }
  1277. else {
  1278. cmd->command_output_func (out, result);
  1279. }
  1280. ucl_object_unref (result);
  1281. }
  1282. else {
  1283. rspamd_fprintf (out, "%e\n", err);
  1284. }
  1285. fflush (out);
  1286. fclose (out);
  1287. }
  1288. g_strfreev (eargv);
  1289. }
  1290. static void
  1291. rspamc_client_cb (struct rspamd_client_connection *conn,
  1292. struct rspamd_http_message *msg,
  1293. const gchar *name, ucl_object_t *result, GString *input,
  1294. gpointer ud, gdouble start_time, gdouble send_time,
  1295. GError *err)
  1296. {
  1297. gchar *ucl_out;
  1298. struct rspamc_callback_data *cbdata = (struct rspamc_callback_data *)ud;
  1299. struct rspamc_command *cmd;
  1300. FILE *out = stdout;
  1301. gdouble finish = rspamd_get_ticks (FALSE), diff;
  1302. const gchar *body;
  1303. gsize body_len;
  1304. cmd = cbdata->cmd;
  1305. if (send_time > 0) {
  1306. diff = finish - send_time;
  1307. }
  1308. else {
  1309. diff = finish - start_time;
  1310. }
  1311. if (execute) {
  1312. /* Pass all to the external command */
  1313. rspamc_client_execute_cmd (cmd, result, input, diff, err);
  1314. }
  1315. else {
  1316. if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
  1317. rspamc_mime_output (out, result, input, diff, err);
  1318. }
  1319. else {
  1320. if (cmd->need_input) {
  1321. if (!compact) {
  1322. rspamd_fprintf (out, "Results for file: %s (%.3f seconds)\n",
  1323. cbdata->filename, diff);
  1324. }
  1325. }
  1326. else {
  1327. if (!compact) {
  1328. rspamd_fprintf (out, "Results for command: %s (%.3f seconds)\n",
  1329. cmd->name, diff);
  1330. }
  1331. }
  1332. if (result != NULL) {
  1333. if (headers && msg != NULL) {
  1334. rspamc_output_headers (out, msg);
  1335. }
  1336. if (raw || cmd->command_output_func == NULL) {
  1337. if (cmd->need_input) {
  1338. ucl_object_insert_key (result,
  1339. ucl_object_fromstring (cbdata->filename),
  1340. "filename", 0,
  1341. false);
  1342. }
  1343. ucl_object_insert_key (result,
  1344. ucl_object_fromdouble (diff),
  1345. "scan_time", 0,
  1346. false);
  1347. if (json) {
  1348. ucl_out = ucl_object_emit (result,
  1349. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1350. }
  1351. else {
  1352. ucl_out = ucl_object_emit (result,
  1353. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1354. }
  1355. rspamd_fprintf (out, "%s", ucl_out);
  1356. free (ucl_out);
  1357. }
  1358. else {
  1359. cmd->command_output_func (out, result);
  1360. }
  1361. ucl_object_unref (result);
  1362. }
  1363. else if (err != NULL) {
  1364. rspamd_fprintf (out, "%s\n", err->message);
  1365. if (json && msg != NULL) {
  1366. body = rspamd_http_message_get_body (msg, &body_len);
  1367. if (body) {
  1368. /* We can also output the resulting json */
  1369. rspamd_fprintf (out, "%*s\n", (gint)body_len, body);
  1370. }
  1371. }
  1372. }
  1373. rspamd_fprintf (out, "\n");
  1374. }
  1375. fflush (out);
  1376. }
  1377. rspamd_client_destroy (conn);
  1378. g_free (cbdata->filename);
  1379. g_free (cbdata);
  1380. if (err) {
  1381. retcode = EXIT_FAILURE;
  1382. }
  1383. }
  1384. static void
  1385. rspamc_process_input (struct event_base *ev_base, struct rspamc_command *cmd,
  1386. FILE *in, const gchar *name, GQueue *attrs)
  1387. {
  1388. struct rspamd_client_connection *conn;
  1389. gchar *hostbuf = NULL, *p;
  1390. guint16 port;
  1391. GError *err = NULL;
  1392. struct rspamc_callback_data *cbdata;
  1393. if (connect_str[0] == '[') {
  1394. p = strrchr (connect_str, ']');
  1395. if (p != NULL) {
  1396. hostbuf = g_malloc (p - connect_str);
  1397. rspamd_strlcpy (hostbuf, connect_str + 1, p - connect_str);
  1398. p ++;
  1399. }
  1400. else {
  1401. p = connect_str;
  1402. }
  1403. }
  1404. else {
  1405. p = connect_str;
  1406. }
  1407. p = strrchr (p, ':');
  1408. if (!hostbuf) {
  1409. if (p != NULL) {
  1410. hostbuf = g_malloc (p - connect_str + 1);
  1411. rspamd_strlcpy (hostbuf, connect_str, p - connect_str + 1);
  1412. }
  1413. else {
  1414. hostbuf = g_strdup (connect_str);
  1415. }
  1416. }
  1417. if (p != NULL) {
  1418. port = strtoul (p + 1, NULL, 10);
  1419. }
  1420. else {
  1421. /*
  1422. * If we connect to localhost, 127.0.0.1 or ::1, then try controller
  1423. * port first
  1424. */
  1425. if (strcmp (hostbuf, "localhost") == 0 ||
  1426. strcmp (hostbuf, "127.0.0.1") == 0 ||
  1427. strcmp (hostbuf, "::1") == 0 ||
  1428. strcmp (hostbuf, "[::1]") == 0) {
  1429. port = DEFAULT_CONTROL_PORT;
  1430. }
  1431. else {
  1432. port = cmd->is_controller ? DEFAULT_CONTROL_PORT : DEFAULT_PORT;
  1433. }
  1434. }
  1435. conn = rspamd_client_init (ev_base, hostbuf, port, timeout, key);
  1436. if (conn != NULL) {
  1437. cbdata = g_malloc0 (sizeof (struct rspamc_callback_data));
  1438. cbdata->cmd = cmd;
  1439. if (name) {
  1440. cbdata->filename = g_strdup (name);
  1441. }
  1442. if (cmd->need_input) {
  1443. rspamd_client_command (conn, cmd->path, attrs, in, rspamc_client_cb,
  1444. cbdata, compressed, dictionary, cbdata->filename, &err);
  1445. }
  1446. else {
  1447. rspamd_client_command (conn,
  1448. cmd->path,
  1449. attrs,
  1450. NULL,
  1451. rspamc_client_cb,
  1452. cbdata,
  1453. compressed,
  1454. dictionary,
  1455. cbdata->filename,
  1456. &err);
  1457. }
  1458. }
  1459. else {
  1460. rspamd_fprintf (stderr, "cannot connect to %s\n", connect_str);
  1461. exit (EXIT_FAILURE);
  1462. }
  1463. g_free (hostbuf);
  1464. }
  1465. static gsize
  1466. rspamd_dirent_size (DIR * dirp)
  1467. {
  1468. goffset name_max;
  1469. gsize name_end;
  1470. #if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \
  1471. && defined(_PC_NAME_MAX)
  1472. name_max = fpathconf (dirfd (dirp), _PC_NAME_MAX);
  1473. # if defined(NAME_MAX)
  1474. if (name_max == -1) {
  1475. name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
  1476. }
  1477. # else
  1478. if (name_max == -1) {
  1479. return (size_t)(-1);
  1480. }
  1481. # endif
  1482. #else
  1483. # if defined(NAME_MAX)
  1484. name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
  1485. # else
  1486. # error "buffer size for readdir_r cannot be determined"
  1487. # endif
  1488. #endif
  1489. name_end = G_STRUCT_OFFSET (struct dirent, d_name) + name_max + 1;
  1490. return (name_end > sizeof (struct dirent) ? name_end : sizeof(struct dirent));
  1491. }
  1492. static void
  1493. rspamc_process_dir (struct event_base *ev_base, struct rspamc_command *cmd,
  1494. const gchar *name, GQueue *attrs)
  1495. {
  1496. DIR *d;
  1497. GPatternSpec **ex;
  1498. struct dirent *pentry;
  1499. gint cur_req = 0, r;
  1500. gchar fpath[PATH_MAX];
  1501. FILE *in;
  1502. struct stat st;
  1503. gboolean is_reg, is_dir, skip;
  1504. d = opendir (name);
  1505. if (d != NULL) {
  1506. while ((pentry = readdir (d))!= NULL) {
  1507. if (pentry->d_name[0] == '.') {
  1508. continue;
  1509. }
  1510. r = rspamd_snprintf (fpath, sizeof (fpath), "%s%c%s",
  1511. name, G_DIR_SEPARATOR,
  1512. pentry->d_name);
  1513. /* Check exclude */
  1514. ex = exclude_compiled;
  1515. skip = FALSE;
  1516. while (ex != NULL && *ex != NULL) {
  1517. if (g_pattern_match (*ex, r, fpath, NULL)) {
  1518. skip = TRUE;
  1519. break;
  1520. }
  1521. ex ++;
  1522. }
  1523. if (skip) {
  1524. continue;
  1525. }
  1526. is_reg = FALSE;
  1527. is_dir = FALSE;
  1528. #if (defined(_DIRENT_HAVE_D_TYPE) || defined(__APPLE__)) && defined(DT_UNKNOWN)
  1529. if (pentry->d_type == DT_UNKNOWN) {
  1530. /* Fallback to lstat */
  1531. if (lstat (fpath, &st) == -1) {
  1532. rspamd_fprintf (stderr, "cannot stat file %s: %s\n",
  1533. fpath, strerror (errno));
  1534. continue;
  1535. }
  1536. is_dir = S_ISDIR (st.st_mode);
  1537. is_reg = S_ISREG (st.st_mode);
  1538. }
  1539. else {
  1540. if (pentry->d_type == DT_REG) {
  1541. is_reg = TRUE;
  1542. }
  1543. else if (pentry->d_type == DT_DIR) {
  1544. is_dir = TRUE;
  1545. }
  1546. }
  1547. #else
  1548. if (lstat (fpath, &st) == -1) {
  1549. rspamd_fprintf (stderr, "cannot stat file %s: %s\n",
  1550. fpath, strerror (errno));
  1551. continue;
  1552. }
  1553. is_dir = S_ISDIR (st.st_mode);
  1554. is_reg = S_ISREG (st.st_mode);
  1555. #endif
  1556. if (is_dir) {
  1557. rspamc_process_dir (ev_base, cmd, fpath, attrs);
  1558. continue;
  1559. }
  1560. else if (is_reg) {
  1561. in = fopen (fpath, "r");
  1562. if (in == NULL) {
  1563. rspamd_fprintf (stderr, "cannot open file %s: %s\n",
  1564. fpath, strerror (errno));
  1565. continue;
  1566. }
  1567. rspamc_process_input (ev_base, cmd, in, fpath, attrs);
  1568. cur_req++;
  1569. fclose (in);
  1570. if (cur_req >= max_requests) {
  1571. cur_req = 0;
  1572. /* Wait for completion */
  1573. event_base_loop (ev_base, 0);
  1574. }
  1575. }
  1576. }
  1577. }
  1578. else {
  1579. fprintf (stderr, "cannot open directory %s: %s\n", name, strerror (errno));
  1580. exit (EXIT_FAILURE);
  1581. }
  1582. closedir (d);
  1583. event_base_loop (ev_base, 0);
  1584. }
  1585. gint
  1586. main (gint argc, gchar **argv, gchar **env)
  1587. {
  1588. gint i, start_argc, cur_req = 0, res, ret, npatterns;
  1589. GQueue *kwattrs;
  1590. GList *cur;
  1591. GPid cld;
  1592. struct rspamc_command *cmd;
  1593. FILE *in = NULL;
  1594. struct event_base *ev_base;
  1595. struct stat st;
  1596. struct sigaction sigpipe_act;
  1597. gchar **exclude_pattern;
  1598. kwattrs = g_queue_new ();
  1599. read_cmd_line (&argc, &argv);
  1600. tty = isatty (STDOUT_FILENO);
  1601. if (print_commands) {
  1602. print_commands_list ();
  1603. exit (EXIT_SUCCESS);
  1604. }
  1605. /* Deal with exclude patterns */
  1606. exclude_pattern = exclude_patterns;
  1607. npatterns = 0;
  1608. while (exclude_pattern && *exclude_pattern) {
  1609. npatterns ++;
  1610. }
  1611. if (npatterns > 0) {
  1612. exclude_compiled = g_malloc0 (sizeof (*exclude_compiled) * (npatterns + 1));
  1613. for (i = 0; i < npatterns; i ++) {
  1614. exclude_compiled[i] = g_pattern_spec_new (exclude_patterns[i]);
  1615. if (exclude_compiled[i] == NULL) {
  1616. rspamd_fprintf (stderr, "Invalid glob pattern: %s\n",
  1617. exclude_patterns[i]);
  1618. exit (EXIT_FAILURE);
  1619. }
  1620. }
  1621. }
  1622. rspamd_init_libs ();
  1623. ev_base = event_base_new ();
  1624. /* Ignore sigpipe */
  1625. sigemptyset (&sigpipe_act.sa_mask);
  1626. sigaddset (&sigpipe_act.sa_mask, SIGPIPE);
  1627. sigpipe_act.sa_handler = SIG_IGN;
  1628. sigpipe_act.sa_flags = 0;
  1629. sigaction (SIGPIPE, &sigpipe_act, NULL);
  1630. /* Now read other args from argc and argv */
  1631. if (argc == 1) {
  1632. start_argc = argc;
  1633. in = stdin;
  1634. cmd = check_rspamc_command ("symbols");
  1635. }
  1636. else if (argc == 2) {
  1637. /* One argument is whether command or filename */
  1638. if ((cmd = check_rspamc_command (argv[1])) != NULL) {
  1639. start_argc = argc;
  1640. in = stdin;
  1641. }
  1642. else {
  1643. cmd = check_rspamc_command ("symbols"); /* Symbols command */
  1644. start_argc = 1;
  1645. }
  1646. }
  1647. else {
  1648. if ((cmd = check_rspamc_command (argv[1])) != NULL) {
  1649. /* In case of command read arguments starting from 2 */
  1650. if (cmd->cmd == RSPAMC_COMMAND_ADD_SYMBOL || cmd->cmd ==
  1651. RSPAMC_COMMAND_ADD_ACTION) {
  1652. if (argc < 4 || argc > 5) {
  1653. fprintf (stderr, "invalid arguments\n");
  1654. exit (EXIT_FAILURE);
  1655. }
  1656. if (argc == 5) {
  1657. ADD_CLIENT_HEADER (kwattrs, "metric", argv[2]);
  1658. ADD_CLIENT_HEADER (kwattrs, "name", argv[3]);
  1659. ADD_CLIENT_HEADER (kwattrs, "value", argv[4]);
  1660. }
  1661. else {
  1662. ADD_CLIENT_HEADER (kwattrs, "name", argv[2]);
  1663. ADD_CLIENT_HEADER (kwattrs, "value", argv[3]);
  1664. }
  1665. start_argc = argc;
  1666. }
  1667. else {
  1668. start_argc = 2;
  1669. }
  1670. }
  1671. else {
  1672. cmd = check_rspamc_command ("symbols");
  1673. start_argc = 1;
  1674. }
  1675. }
  1676. add_options (kwattrs);
  1677. if (start_argc == argc) {
  1678. /* Do command without input or with stdin */
  1679. if (empty_input) {
  1680. rspamc_process_input (ev_base, cmd, NULL, "empty", kwattrs);
  1681. }
  1682. else {
  1683. rspamc_process_input (ev_base, cmd, in, "stdin", kwattrs);
  1684. }
  1685. }
  1686. else {
  1687. for (i = start_argc; i < argc; i++) {
  1688. if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
  1689. ADD_CLIENT_HEADER (kwattrs, "Hash", argv[i]);
  1690. }
  1691. else {
  1692. if (stat (argv[i], &st) == -1) {
  1693. fprintf (stderr, "cannot stat file %s\n", argv[i]);
  1694. exit (EXIT_FAILURE);
  1695. }
  1696. if (S_ISDIR (st.st_mode)) {
  1697. /* Directories are processed with a separate limit */
  1698. rspamc_process_dir (ev_base, cmd, argv[i], kwattrs);
  1699. cur_req = 0;
  1700. }
  1701. else {
  1702. in = fopen (argv[i], "r");
  1703. if (in == NULL) {
  1704. fprintf (stderr, "cannot open file %s\n", argv[i]);
  1705. exit (EXIT_FAILURE);
  1706. }
  1707. rspamc_process_input (ev_base, cmd, in, argv[i], kwattrs);
  1708. cur_req++;
  1709. fclose (in);
  1710. }
  1711. if (cur_req >= max_requests) {
  1712. cur_req = 0;
  1713. /* Wait for completion */
  1714. event_base_loop (ev_base, 0);
  1715. }
  1716. }
  1717. }
  1718. if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
  1719. rspamc_process_input (ev_base, cmd, NULL, "hashes", kwattrs);
  1720. }
  1721. }
  1722. event_base_loop (ev_base, 0);
  1723. g_queue_free_full (kwattrs, g_free);
  1724. /* Wait for children processes */
  1725. cur = g_list_first (children);
  1726. ret = 0;
  1727. while (cur) {
  1728. cld = GPOINTER_TO_SIZE (cur->data);
  1729. if (waitpid (cld, &res, 0) == -1) {
  1730. fprintf (stderr, "Cannot wait for %d: %s", (gint)cld,
  1731. strerror (errno));
  1732. ret = errno;
  1733. }
  1734. if (ret == 0) {
  1735. /* Check return code */
  1736. if (WIFSIGNALED (res)) {
  1737. ret = WTERMSIG (res);
  1738. }
  1739. else if (WIFEXITED (res)) {
  1740. ret = WEXITSTATUS (res);
  1741. }
  1742. }
  1743. cur = g_list_next (cur);
  1744. }
  1745. if (children != NULL) {
  1746. g_list_free (children);
  1747. }
  1748. for (i = 0; i < npatterns; i ++) {
  1749. g_pattern_spec_free (exclude_compiled[i]);
  1750. }
  1751. /* Mix retcode (return from Rspamd side) and ret (return from subprocess) */
  1752. return ret | retcode;
  1753. }