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 52KB

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