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.cxx 65KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380
  1. /*
  2. * Copyright 2024 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "libutil/util.h"
  18. #include "libserver/http/http_connection.h"
  19. #include "libserver/http/http_private.h"
  20. #include "libserver/cfg_file.h"
  21. #include "rspamdclient.h"
  22. #include "unix-std.h"
  23. #include <vector>
  24. #include <string>
  25. #include <optional>
  26. #include <algorithm>
  27. #include <functional>
  28. #include <cstdint>
  29. #include <cstdio>
  30. #include <cmath>
  31. #include "frozen/string.h"
  32. #include "frozen/unordered_map.h"
  33. #include "fmt/format.h"
  34. #include "fmt/color.h"
  35. #include "libutil/cxx/file_util.hxx"
  36. #include "libutil/cxx/util.hxx"
  37. #ifdef HAVE_SYS_WAIT_H
  38. #include <sys/wait.h>
  39. #endif
  40. #define DEFAULT_PORT 11333
  41. #define DEFAULT_CONTROL_PORT 11334
  42. static const char *connect_str = "localhost";
  43. static const char *password = nullptr;
  44. static const char *ip = nullptr;
  45. static const char *from = nullptr;
  46. static const char *deliver_to = nullptr;
  47. static const char **rcpts = nullptr;
  48. static const char *user = nullptr;
  49. static const char *helo = nullptr;
  50. static const char *hostname = nullptr;
  51. static const char *classifier = nullptr;
  52. static const char *local_addr = nullptr;
  53. static const char *execute = nullptr;
  54. static const char *sort = nullptr;
  55. static const char **http_headers = nullptr;
  56. static const char **exclude_patterns = nullptr;
  57. static int weight = 0;
  58. static int flag = 0;
  59. static const char *fuzzy_symbol = nullptr;
  60. static const char *dictionary = nullptr;
  61. static int max_requests = 8;
  62. static double timeout = 10.0;
  63. static gboolean pass_all;
  64. static gboolean tty = FALSE;
  65. static gboolean verbose = FALSE;
  66. static gboolean print_commands = FALSE;
  67. static gboolean humanreport = FALSE;
  68. static gboolean json = FALSE;
  69. static gboolean compact = FALSE;
  70. static gboolean headers = FALSE;
  71. static gboolean raw = FALSE;
  72. static gboolean ucl_reply = FALSE;
  73. static gboolean extended_urls = FALSE;
  74. static gboolean mime_output = FALSE;
  75. static gboolean empty_input = FALSE;
  76. static gboolean compressed = TRUE;
  77. static gboolean profile = FALSE;
  78. static gboolean skip_images = FALSE;
  79. static gboolean skip_attachments = FALSE;
  80. static const char *pubkey = nullptr;
  81. static const char *user_agent = "rspamc";
  82. std::vector<GPid> children;
  83. static GPatternSpec **exclude_compiled = nullptr;
  84. static struct rspamd_http_context *http_ctx;
  85. static int retcode = EXIT_SUCCESS;
  86. static gboolean rspamc_password_callback(const char *option_name,
  87. const char *value,
  88. gpointer data,
  89. GError **error);
  90. static GOptionEntry entries[] =
  91. {
  92. {"connect", 'h', 0, G_OPTION_ARG_STRING, &connect_str,
  93. "Specify host and port", nullptr},
  94. {"password", 'P', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK,
  95. (void *) &rspamc_password_callback, "Specify control password", nullptr},
  96. {"classifier", 'c', 0, G_OPTION_ARG_STRING, &classifier,
  97. "Classifier to learn spam or ham", nullptr},
  98. {"weight", 'w', 0, G_OPTION_ARG_INT, &weight,
  99. "Weight for fuzzy operations", nullptr},
  100. {"flag", 'f', 0, G_OPTION_ARG_INT, &flag, "Flag for fuzzy operations",
  101. nullptr},
  102. {"pass-all", 'p', 0, G_OPTION_ARG_NONE, &pass_all, "Pass all filters",
  103. nullptr},
  104. {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "More verbose output",
  105. nullptr},
  106. {"ip", 'i', 0, G_OPTION_ARG_STRING, &ip,
  107. "Emulate that message was received from specified ip address",
  108. nullptr},
  109. {"user", 'u', 0, G_OPTION_ARG_STRING, &user,
  110. "Emulate that message was received from specified authenticated user", nullptr},
  111. {"deliver", 'd', 0, G_OPTION_ARG_STRING, &deliver_to,
  112. "Emulate that message is delivered to specified user (for LDA/statistics)", nullptr},
  113. {"from", 'F', 0, G_OPTION_ARG_STRING, &from,
  114. "Emulate that message has specified SMTP FROM address", nullptr},
  115. {"rcpt", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &rcpts,
  116. "Emulate that message has specified SMTP RCPT address", nullptr},
  117. {"helo", 0, 0, G_OPTION_ARG_STRING, &helo,
  118. "Imitate SMTP HELO passing from MTA", nullptr},
  119. {"hostname", 0, 0, G_OPTION_ARG_STRING, &hostname,
  120. "Imitate hostname passing from MTA", nullptr},
  121. {"timeout", 't', 0, G_OPTION_ARG_DOUBLE, &timeout,
  122. "Time in seconds to wait for a reply", nullptr},
  123. {"bind", 'b', 0, G_OPTION_ARG_STRING, &local_addr,
  124. "Bind to specified ip address", nullptr},
  125. {"commands", 0, 0, G_OPTION_ARG_NONE, &print_commands,
  126. "List available commands", nullptr},
  127. {"human", 'R', 0, G_OPTION_ARG_NONE, &humanreport, "Output human readable report", nullptr},
  128. {"json", 'j', 0, G_OPTION_ARG_NONE, &json, "Output json reply", nullptr},
  129. {"compact", '\0', 0, G_OPTION_ARG_NONE, &compact, "Output compact json reply", nullptr},
  130. {"headers", 0, 0, G_OPTION_ARG_NONE, &headers, "Output HTTP headers",
  131. nullptr},
  132. {"raw", 0, 0, G_OPTION_ARG_NONE, &raw, "Input is a raw file, not an email file",
  133. nullptr},
  134. {"ucl", 0, 0, G_OPTION_ARG_NONE, &ucl_reply, "Output ucl reply from rspamd",
  135. nullptr},
  136. {"max-requests", 'n', 0, G_OPTION_ARG_INT, &max_requests,
  137. "Maximum count of parallel requests to rspamd", nullptr},
  138. {"extended-urls", 0, 0, G_OPTION_ARG_NONE, &extended_urls,
  139. "Output urls in extended format", nullptr},
  140. {"key", 0, 0, G_OPTION_ARG_STRING, &pubkey,
  141. "Use specified pubkey to encrypt request", nullptr},
  142. {"exec", 'e', 0, G_OPTION_ARG_STRING, &execute,
  143. "Execute the specified command and pass output to it", nullptr},
  144. {"mime", 'm', 0, G_OPTION_ARG_NONE, &mime_output,
  145. "Write mime body of message with headers instead of just a scan's result", nullptr},
  146. {"header", 0, 0, G_OPTION_ARG_STRING_ARRAY, &http_headers,
  147. "Add custom HTTP header to query (can be repeated)", nullptr},
  148. {"exclude", 0, 0, G_OPTION_ARG_STRING_ARRAY, &exclude_patterns,
  149. "Exclude specific glob patterns in file names (can be repeated)", nullptr},
  150. {"sort", 0, 0, G_OPTION_ARG_STRING, &sort,
  151. "Sort output in a specific order (name, weight, frequency, hits)", nullptr},
  152. {"empty", 'E', 0, G_OPTION_ARG_NONE, &empty_input,
  153. "Allow empty input instead of reading from stdin", nullptr},
  154. {"fuzzy-symbol", 'S', 0, G_OPTION_ARG_STRING, &fuzzy_symbol,
  155. "Learn the specified fuzzy symbol", nullptr},
  156. {"compressed", 'z', 0, G_OPTION_ARG_NONE, &compressed,
  157. "Enable zstd compression", nullptr},
  158. {"profile", '\0', 0, G_OPTION_ARG_NONE, &profile,
  159. "Profile symbols execution time", nullptr},
  160. {"dictionary", 'D', 0, G_OPTION_ARG_FILENAME, &dictionary,
  161. "Use dictionary to compress data", nullptr},
  162. {"skip-images", '\0', 0, G_OPTION_ARG_NONE, &skip_images,
  163. "Skip images when learning/unlearning fuzzy", nullptr},
  164. {"skip-attachments", '\0', 0, G_OPTION_ARG_NONE, &skip_attachments,
  165. "Skip attachments when learning/unlearning fuzzy", nullptr},
  166. {"user-agent", 'U', 0, G_OPTION_ARG_STRING, &user_agent,
  167. "Use specific User-Agent instead of \"rspamc\"", nullptr},
  168. {nullptr, 0, 0, G_OPTION_ARG_NONE, nullptr, nullptr, nullptr}};
  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 *path;
  193. const char *description;
  194. gboolean is_controller;
  195. gboolean is_privileged;
  196. gboolean need_input;
  197. void (*command_output_func)(FILE *, ucl_object_t *obj);
  198. };
  199. static const constexpr auto rspamc_commands = rspamd::array_of(
  200. rspamc_command{
  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. rspamc_command{
  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 = nullptr},
  218. rspamc_command{
  219. .cmd = RSPAMC_COMMAND_LEARN_HAM,
  220. .name = "learn_ham",
  221. .path = "learnham",
  222. .description = "learn message as ham",
  223. .is_controller = TRUE,
  224. .is_privileged = TRUE,
  225. .need_input = TRUE,
  226. .command_output_func = nullptr},
  227. rspamc_command{
  228. .cmd = RSPAMC_COMMAND_FUZZY_ADD,
  229. .name = "fuzzy_add",
  230. .path = "fuzzyadd",
  231. .description =
  232. "add hashes from a message to the fuzzy storage (check -f and -w options for this command)",
  233. .is_controller = TRUE,
  234. .is_privileged = TRUE,
  235. .need_input = TRUE,
  236. .command_output_func = nullptr},
  237. rspamc_command{
  238. .cmd = RSPAMC_COMMAND_FUZZY_DEL,
  239. .name = "fuzzy_del",
  240. .path = "fuzzydel",
  241. .description =
  242. "delete hashes from a message from the fuzzy storage (check -f option for this command)",
  243. .is_controller = TRUE,
  244. .is_privileged = TRUE,
  245. .need_input = TRUE,
  246. .command_output_func = nullptr},
  247. rspamc_command{
  248. .cmd = RSPAMC_COMMAND_FUZZY_DELHASH,
  249. .name = "fuzzy_delhash",
  250. .path = "fuzzydelhash",
  251. .description =
  252. "delete a hash from fuzzy storage (check -f option for this command)",
  253. .is_controller = TRUE,
  254. .is_privileged = TRUE,
  255. .need_input = FALSE,
  256. .command_output_func = nullptr},
  257. rspamc_command{
  258. .cmd = RSPAMC_COMMAND_STAT,
  259. .name = "stat",
  260. .path = "stat",
  261. .description = "show rspamd statistics",
  262. .is_controller = TRUE,
  263. .is_privileged = FALSE,
  264. .need_input = FALSE,
  265. .command_output_func = rspamc_stat_output,
  266. },
  267. rspamc_command{
  268. .cmd = RSPAMC_COMMAND_STAT_RESET,
  269. .name = "stat_reset",
  270. .path = "statreset",
  271. .description = "show and reset rspamd statistics (useful for graphs)",
  272. .is_controller = TRUE,
  273. .is_privileged = TRUE,
  274. .need_input = FALSE,
  275. .command_output_func = rspamc_stat_output},
  276. rspamc_command{
  277. .cmd = RSPAMC_COMMAND_COUNTERS,
  278. .name = "counters",
  279. .path = "counters",
  280. .description = "display rspamd symbols statistics",
  281. .is_controller = TRUE,
  282. .is_privileged = FALSE,
  283. .need_input = FALSE,
  284. .command_output_func = rspamc_counters_output},
  285. rspamc_command{
  286. .cmd = RSPAMC_COMMAND_UPTIME,
  287. .name = "uptime",
  288. .path = "auth",
  289. .description = "show rspamd uptime",
  290. .is_controller = TRUE,
  291. .is_privileged = FALSE,
  292. .need_input = FALSE,
  293. .command_output_func = rspamc_uptime_output},
  294. rspamc_command{
  295. .cmd = RSPAMC_COMMAND_ADD_SYMBOL,
  296. .name = "add_symbol",
  297. .path = "addsymbol",
  298. .description = "add or modify symbol settings in rspamd",
  299. .is_controller = TRUE,
  300. .is_privileged = TRUE,
  301. .need_input = FALSE,
  302. .command_output_func = nullptr},
  303. rspamc_command{
  304. .cmd = RSPAMC_COMMAND_ADD_ACTION,
  305. .name = "add_action",
  306. .path = "addaction",
  307. .description = "add or modify action settings",
  308. .is_controller = TRUE,
  309. .is_privileged = TRUE,
  310. .need_input = FALSE,
  311. .command_output_func = nullptr});
  312. struct rspamc_callback_data {
  313. struct rspamc_command cmd;
  314. std::string filename;
  315. };
  316. template<typename T>
  317. static constexpr auto emphasis_argument(const T &arg) -> auto
  318. {
  319. if (tty) {
  320. return fmt::format(fmt::emphasis::bold, "{}", arg);
  321. }
  322. return fmt::format("{}", arg);
  323. }
  324. template<typename T, typename std::enable_if_t<std::is_floating_point_v<T>, bool> = false>
  325. static constexpr auto emphasis_argument(const T &arg, int precision) -> auto
  326. {
  327. if (tty) {
  328. return fmt::format(fmt::emphasis::bold, "{:.{}f}", arg, precision);
  329. }
  330. return fmt::format("{:.{}f}", arg, precision);
  331. }
  332. template<>
  333. struct fmt::formatter<rspamd_action_type> : fmt::formatter<string_view> {
  334. auto format(rspamd_action_type c, format_context &ctx) const
  335. {
  336. return formatter<string_view>::format(std::string_view{rspamd_action_to_str(c)}, ctx);
  337. }
  338. };
  339. template<typename... T>
  340. static inline void rspamc_print(std::FILE *f, fmt::format_string<T...> fmt, T &&...args)
  341. {
  342. static auto try_print_exception = true;
  343. auto wanna_die = false;
  344. try {
  345. fmt::print(f, fmt, std::forward<T>(args)...);
  346. } catch (const fmt::format_error &err) {
  347. if (try_print_exception) {
  348. if (fprintf(stderr, "Format error: %s\n", err.what()) < 0) {
  349. try_print_exception = false;
  350. }
  351. }
  352. } catch (std::system_error &err) {
  353. wanna_die = true;
  354. if (try_print_exception) {
  355. if (fprintf(stderr, "System error: %s\n", err.what()) < 0) {
  356. try_print_exception = false;
  357. }
  358. }
  359. } catch (...) {
  360. wanna_die = true;
  361. if (try_print_exception) {
  362. if (fprintf(stderr, "Unknown format error\n") < 0) {
  363. try_print_exception = false;
  364. }
  365. }
  366. }
  367. if (wanna_die) {
  368. exit(EXIT_FAILURE);
  369. }
  370. }
  371. using sort_lambda = std::function<int(const ucl_object_t *, const ucl_object_t *)>;
  372. static const auto sort_map = frozen::make_unordered_map<frozen::string, sort_lambda>({
  373. {"name", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  374. const auto *elt1 = ucl_object_lookup(o1, "symbol");
  375. const auto *elt2 = ucl_object_lookup(o2, "symbol");
  376. if (elt1 && elt2) {
  377. return strcmp(ucl_object_tostring(elt1),
  378. ucl_object_tostring(elt2));
  379. }
  380. else if (ucl_object_key(o1) != nullptr && ucl_object_key(o2) != nullptr) {
  381. return strcmp(ucl_object_key(o1),
  382. ucl_object_key(o2));
  383. }
  384. return 0;
  385. }},
  386. {"weight", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  387. const auto *elt1 = ucl_object_lookup(o1, "weight");
  388. const auto *elt2 = ucl_object_lookup(o2, "weight");
  389. if (elt1 && elt2) {
  390. return ucl_object_todouble(elt2) * 1000.0 - ucl_object_todouble(elt1) * 1000.0;
  391. }
  392. return 0;
  393. }},
  394. {"score", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  395. const auto *elt1 = ucl_object_lookup(o1, "score");
  396. const auto *elt2 = ucl_object_lookup(o2, "score");
  397. if (elt1 && elt2) {
  398. return std::fabs(ucl_object_todouble(elt2)) * 1000.0 -
  399. std::fabs(ucl_object_todouble(elt1)) * 1000.0;
  400. }
  401. return 0;
  402. }},
  403. {"time", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  404. const auto *elt1 = ucl_object_lookup(o1, "time");
  405. const auto *elt2 = ucl_object_lookup(o2, "time");
  406. if (elt1 && elt2) {
  407. return ucl_object_todouble(elt2) * 1000.0 - ucl_object_todouble(elt1) * 1000.0;
  408. }
  409. return 0;
  410. }},
  411. {"frequency", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  412. const auto *elt1 = ucl_object_lookup(o1, "frequency");
  413. const auto *elt2 = ucl_object_lookup(o2, "frequency");
  414. if (elt1 && elt2) {
  415. return ucl_object_todouble(elt2) * 1000.0 - ucl_object_todouble(elt1) * 1000.0;
  416. }
  417. return 0;
  418. }},
  419. {"hits", [](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  420. const auto *elt1 = ucl_object_lookup(o1, "hits");
  421. const auto *elt2 = ucl_object_lookup(o2, "hits");
  422. if (elt1 && elt2) {
  423. return ucl_object_toint(elt2) - ucl_object_toint(elt1);
  424. }
  425. return 0;
  426. }},
  427. });
  428. /* TODO: remove once migrate to C++20 standard */
  429. static constexpr auto
  430. sv_ends_with(std::string_view inp, std::string_view suffix) -> bool
  431. {
  432. return inp.size() >= suffix.size() && inp.compare(inp.size() - suffix.size(), std::string_view::npos, suffix) == 0;
  433. }
  434. template<typename T>
  435. auto sort_ucl_container_with_default(T &cont, const char *default_sort,
  436. typename std::enable_if<std::is_same_v<typename T::value_type, const ucl_object_t *>>::type * = 0) -> void
  437. {
  438. auto real_sort = sort ? sort : default_sort;
  439. if (real_sort) {
  440. auto sort_view = std::string_view{real_sort};
  441. auto inverse = false;
  442. if (sv_ends_with(sort_view, ":asc")) {
  443. inverse = true;
  444. sort_view = std::string_view{sort, strlen(sort) - sizeof(":asc") + 1};
  445. }
  446. const auto sort_functor = sort_map.find(sort_view);
  447. if (sort_functor != sort_map.end()) {
  448. std::stable_sort(std::begin(cont), std::end(cont),
  449. [&](const ucl_object_t *o1, const ucl_object_t *o2) -> int {
  450. auto order = sort_functor->second(o1, o2);
  451. return inverse ? order > 0 : order < 0;
  452. });
  453. }
  454. }
  455. }
  456. static gboolean
  457. rspamc_password_callback(const char *option_name,
  458. const char *value,
  459. gpointer data,
  460. GError **error)
  461. {
  462. // Some efforts to keep password erased
  463. static std::vector<char, rspamd::secure_mem_allocator<char>> processed_passwd;
  464. processed_passwd.clear();
  465. if (value != nullptr) {
  466. std::string_view value_view{value};
  467. if (value_view[0] == '/' || value_view[0] == '.') {
  468. /* Try to open file */
  469. auto locked_mmap = rspamd::util::raii_mmaped_file::mmap_shared(value, O_RDONLY, PROT_READ);
  470. if (!locked_mmap.has_value() || locked_mmap.value().get_size() == 0) {
  471. /* Just use it as a string */
  472. processed_passwd.assign(std::begin(value_view), std::end(value_view));
  473. processed_passwd.push_back('\0');
  474. }
  475. else {
  476. /* Strip trailing spaces */
  477. auto *map = (char *) locked_mmap.value().get_map();
  478. auto *end = map + locked_mmap.value().get_size() - 1;
  479. while (g_ascii_isspace(*end) && end > map) {
  480. end--;
  481. }
  482. end++;
  483. value_view = std::string_view{map, static_cast<std::size_t>(end - map + 1)};
  484. processed_passwd.assign(std::begin(value_view), std::end(value_view));
  485. processed_passwd.push_back('\0');
  486. }
  487. }
  488. else {
  489. processed_passwd.assign(std::begin(value_view), std::end(value_view));
  490. processed_passwd.push_back('\0');
  491. }
  492. }
  493. else {
  494. /* Read password from console */
  495. auto plen = 8192;
  496. processed_passwd.resize(plen, '\0');
  497. plen = rspamd_read_passphrase(processed_passwd.data(), plen, 0, nullptr);
  498. if (plen == 0) {
  499. rspamc_print(stderr, "Invalid password\n");
  500. exit(EXIT_FAILURE);
  501. }
  502. processed_passwd.resize(plen);
  503. processed_passwd.push_back('\0');
  504. }
  505. password = processed_passwd.data();
  506. return TRUE;
  507. }
  508. /*
  509. * Parse command line
  510. */
  511. static void
  512. read_cmd_line(int *argc, char ***argv)
  513. {
  514. GError *error = nullptr;
  515. GOptionContext *context;
  516. /* Prepare parser */
  517. context = g_option_context_new("- run rspamc client");
  518. g_option_context_set_summary(context,
  519. "Summary:\n Rspamd client version " RVERSION "\n Release id: " RID);
  520. g_option_context_add_main_entries(context, entries, nullptr);
  521. /* Parse options */
  522. if (!g_option_context_parse(context, argc, argv, &error)) {
  523. rspamc_print(stderr, "option parsing failed: {}\n", error->message);
  524. g_option_context_free(context);
  525. exit(EXIT_FAILURE);
  526. }
  527. if (json || compact) {
  528. ucl_reply = TRUE;
  529. }
  530. /* Argc and argv are shifted after this function */
  531. g_option_context_free(context);
  532. }
  533. static auto
  534. add_client_header(GQueue *opts, const char *hn, const char *hv) -> void
  535. {
  536. g_assert(hn != nullptr);
  537. g_assert(hv != nullptr);
  538. auto *nhdr = g_new(rspamd_http_client_header, 1);
  539. nhdr->name = g_strdup(hn);
  540. nhdr->value = g_strdup(hv);
  541. g_queue_push_tail(opts, (void *) nhdr);
  542. }
  543. static auto
  544. add_client_header(GQueue *opts, std::string_view hn, std::string_view hv) -> void
  545. {
  546. auto *nhdr = g_new(rspamd_http_client_header, 1);
  547. nhdr->name = g_new(char, hn.size() + 1);
  548. rspamd_strlcpy(nhdr->name, hn.data(), hn.size() + 1);
  549. nhdr->value = g_new(char, hv.size() + 1);
  550. rspamd_strlcpy(nhdr->value, hv.data(), hv.size() + 1);
  551. g_queue_push_tail(opts, (void *) nhdr);
  552. }
  553. static auto
  554. rspamd_string_tolower(const char *inp) -> std::string
  555. {
  556. std::string s{inp};
  557. std::transform(std::begin(s), std::end(s), std::begin(s),
  558. [](unsigned char c) { return std::tolower(c); });
  559. return s;
  560. }
  561. static auto
  562. rspamd_action_from_str_rspamc(const char *data) -> std::optional<int>
  563. {
  564. static constexpr const auto str_map = frozen::make_unordered_map<frozen::string, int>({
  565. {"reject", METRIC_ACTION_REJECT},
  566. {"greylist", METRIC_ACTION_GREYLIST},
  567. {"add_header", METRIC_ACTION_ADD_HEADER},
  568. {"add header", METRIC_ACTION_ADD_HEADER},
  569. {"rewrite_subject", METRIC_ACTION_REWRITE_SUBJECT},
  570. {"rewrite subject", METRIC_ACTION_REWRITE_SUBJECT},
  571. {"soft_reject", METRIC_ACTION_SOFT_REJECT},
  572. {"soft reject", METRIC_ACTION_SOFT_REJECT},
  573. {"no_action", METRIC_ACTION_NOACTION},
  574. {"no action", METRIC_ACTION_NOACTION},
  575. });
  576. auto st_lower = rspamd_string_tolower(data);
  577. return rspamd::find_map(str_map, std::string_view{st_lower});
  578. }
  579. /*
  580. * Check rspamc command from string (used for arguments parsing)
  581. */
  582. static auto
  583. check_rspamc_command(const char *cmd) -> std::optional<rspamc_command>
  584. {
  585. static constexpr const auto str_map = frozen::make_unordered_map<frozen::string, int>({
  586. {"symbols", RSPAMC_COMMAND_SYMBOLS},
  587. {"check", RSPAMC_COMMAND_SYMBOLS},
  588. {"report", RSPAMC_COMMAND_SYMBOLS},
  589. {"learn_spam", RSPAMC_COMMAND_LEARN_SPAM},
  590. {"learn_ham", RSPAMC_COMMAND_LEARN_HAM},
  591. {"fuzzy_add", RSPAMC_COMMAND_FUZZY_ADD},
  592. {"fuzzy_del", RSPAMC_COMMAND_FUZZY_DEL},
  593. {"fuzzy_delhash", RSPAMC_COMMAND_FUZZY_DELHASH},
  594. {"stat", RSPAMC_COMMAND_STAT},
  595. {"stat_reset", RSPAMC_COMMAND_STAT_RESET},
  596. {"counters", RSPAMC_COMMAND_COUNTERS},
  597. {"uptime", RSPAMC_COMMAND_UPTIME},
  598. });
  599. std::string cmd_lc = rspamd_string_tolower(cmd);
  600. auto ct = rspamd::find_map(str_map, std::string_view{cmd_lc});
  601. auto elt_it = std::find_if(rspamc_commands.begin(), rspamc_commands.end(), [&](const auto &item) {
  602. return item.cmd == ct;
  603. });
  604. if (elt_it != std::end(rspamc_commands)) {
  605. return *elt_it;
  606. }
  607. return std::nullopt;
  608. }
  609. static void
  610. print_commands_list()
  611. {
  612. unsigned int cmd_len = 0;
  613. rspamc_print(stdout, "Rspamc commands summary:\n");
  614. for (const auto &cmd: rspamc_commands) {
  615. auto clen = strlen(cmd.name);
  616. if (clen > cmd_len) {
  617. cmd_len = clen;
  618. }
  619. }
  620. for (const auto &cmd: rspamc_commands) {
  621. rspamc_print(stdout,
  622. " {:>{}} ({:7}{:1})\t{}\n",
  623. cmd.name,
  624. cmd_len,
  625. cmd.is_controller ? "control" : "normal",
  626. cmd.is_privileged ? "*" : "",
  627. cmd.description);
  628. }
  629. rspamc_print(stdout,
  630. "\n* is for privileged commands that may need password (see -P option)\n");
  631. rspamc_print(stdout,
  632. "control commands use port 11334 while normal use 11333 by default (see -h option)\n");
  633. }
  634. static void
  635. add_options(GQueue *opts)
  636. {
  637. std::string flagbuf;
  638. if (ip != nullptr) {
  639. rspamd_inet_addr_t *addr = nullptr;
  640. if (!rspamd_parse_inet_address(&addr, ip, strlen(ip),
  641. RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
  642. /* Try to resolve */
  643. struct addrinfo hints, *res, *cur;
  644. int r;
  645. memset(&hints, 0, sizeof(hints));
  646. hints.ai_socktype = SOCK_STREAM; /* Type of the socket */
  647. #ifdef AI_IDN
  648. hints.ai_flags = AI_NUMERICSERV | AI_IDN;
  649. #else
  650. hints.ai_flags = AI_NUMERICSERV;
  651. #endif
  652. hints.ai_family = AF_UNSPEC;
  653. if ((r = getaddrinfo(ip, "25", &hints, &res)) == 0) {
  654. cur = res;
  655. while (cur) {
  656. addr = rspamd_inet_address_from_sa(cur->ai_addr,
  657. cur->ai_addrlen);
  658. if (addr != nullptr) {
  659. ip = g_strdup(rspamd_inet_address_to_string(addr));
  660. rspamd_inet_address_free(addr);
  661. break;
  662. }
  663. cur = cur->ai_next;
  664. }
  665. freeaddrinfo(res);
  666. }
  667. else {
  668. rspamc_print(stderr, "address resolution for {} failed: {}\n",
  669. ip,
  670. gai_strerror(r));
  671. }
  672. }
  673. else {
  674. rspamd_inet_address_free(addr);
  675. }
  676. add_client_header(opts, "Ip", ip);
  677. }
  678. if (from != nullptr) {
  679. add_client_header(opts, "From", from);
  680. }
  681. if (user != nullptr) {
  682. add_client_header(opts, "User", user);
  683. }
  684. if (rcpts != nullptr) {
  685. for (auto *rcpt = rcpts; *rcpt != nullptr; rcpt++) {
  686. add_client_header(opts, "Rcpt", *rcpt);
  687. }
  688. }
  689. if (deliver_to != nullptr) {
  690. add_client_header(opts, "Deliver-To", deliver_to);
  691. }
  692. if (helo != nullptr) {
  693. add_client_header(opts, "Helo", helo);
  694. }
  695. if (hostname != nullptr) {
  696. add_client_header(opts, "Hostname", hostname);
  697. }
  698. if (password != nullptr) {
  699. add_client_header(opts, "Password", password);
  700. }
  701. if (pass_all) {
  702. flagbuf += "pass_all,";
  703. }
  704. if (raw) {
  705. add_client_header(opts, "Raw", "yes");
  706. }
  707. if (classifier) {
  708. add_client_header(opts, "Classifier", classifier);
  709. }
  710. if (weight != 0) {
  711. auto nstr = fmt::format("{}", weight);
  712. add_client_header(opts, "Weight", nstr.c_str());
  713. }
  714. if (fuzzy_symbol != nullptr) {
  715. add_client_header(opts, "Symbol", fuzzy_symbol);
  716. }
  717. if (flag != 0) {
  718. auto nstr = fmt::format("{}", flag);
  719. add_client_header(opts, "Flag", nstr.c_str());
  720. }
  721. if (extended_urls) {
  722. add_client_header(opts, "URL-Format", "extended");
  723. }
  724. if (profile) {
  725. flagbuf += "profile,";
  726. }
  727. flagbuf += "body_block,";
  728. if (skip_images) {
  729. add_client_header(opts, "Skip-Images", "true");
  730. }
  731. if (skip_attachments) {
  732. add_client_header(opts, "Skip-Attachments", "true");
  733. }
  734. auto hdr = http_headers;
  735. while (hdr != nullptr && *hdr != nullptr) {
  736. std::string_view hdr_view{*hdr};
  737. auto delim_pos = std::find_if(std::begin(hdr_view), std::end(hdr_view), [](auto c) {
  738. return c == ':' || c == '=';
  739. });
  740. if (delim_pos == std::end(hdr_view)) {
  741. /* Just a header name with no value */
  742. add_client_header(opts, *hdr, "");
  743. }
  744. else {
  745. add_client_header(opts,
  746. hdr_view.substr(0, std::distance(std::begin(hdr_view), delim_pos)),
  747. hdr_view.substr(std::distance(std::begin(hdr_view), delim_pos) + 1));
  748. }
  749. hdr++;
  750. }
  751. if (!flagbuf.empty()) {
  752. if (flagbuf.back() == ',') {
  753. flagbuf.pop_back();
  754. }
  755. add_client_header(opts, "Flags", flagbuf.c_str());
  756. }
  757. }
  758. template<std::size_t maxlen, std::size_t indent>
  759. static auto
  760. rspamc_print_indented_line(FILE *out, std::string_view line) -> void
  761. {
  762. static_assert(maxlen > 0, "maxlen must be > 0");
  763. static_assert(maxlen > indent, "maxlen must be more than indent");
  764. using namespace std::literals;
  765. constexpr const auto whitespace = " \f\n\r\t\v"sv;
  766. constexpr const auto break_begin = " \f\n\r\t\v?,;<({[~!#$%^&*+:=/\\|"sv;
  767. constexpr const auto break_end = " \f\n\r\t\v?,;]})>~!#$%^&*+:_=/\\|"sv;
  768. for (size_t pos = 0; pos < line.size();) {
  769. auto len = pos ? (maxlen - indent) : maxlen;
  770. auto s = line.substr(pos, len);
  771. if ((pos + s.size()) < line.size() && // reached EOL?
  772. break_begin.find_first_of(line.at(pos + s.size())) == std::string_view::npos// new word next?
  773. ) {
  774. auto wrap_at = s.find_last_of(break_end);
  775. if (wrap_at != std::string_view::npos) {
  776. s = line.substr(pos, wrap_at + 1);
  777. }
  778. }
  779. if (indent && pos) {
  780. rspamc_print(out, "{:>{}}", " ", indent);
  781. }
  782. rspamc_print(out, "{}\n", s);
  783. pos = line.find_first_not_of(whitespace, pos + s.size());//skip leading whitespace
  784. }
  785. }
  786. static void
  787. rspamc_symbol_human_output(FILE *out, const ucl_object_t *obj)
  788. {
  789. auto first = true;
  790. auto score = 0.0;
  791. const char *desc = nullptr;
  792. const auto *key = ucl_object_key(obj);
  793. const auto *val = ucl_object_lookup(obj, "score");
  794. if (val != nullptr) {
  795. score = ucl_object_todouble(val);
  796. }
  797. val = ucl_object_lookup(obj, "description");
  798. if (val != nullptr) {
  799. desc = ucl_object_tostring(val);
  800. }
  801. auto line = fmt::format("{:>4.1f} {:<22} ", score, key);
  802. if (desc != nullptr) {
  803. line += desc;
  804. }
  805. val = ucl_object_lookup(obj, "options");
  806. if (val != nullptr && ucl_object_type(val) == UCL_ARRAY) {
  807. ucl_object_iter_t it = nullptr;
  808. const ucl_object_t *cur;
  809. line += fmt::format("{}[", desc == nullptr ? "" : " ");
  810. while ((cur = ucl_object_iterate(val, &it, true)) != nullptr) {
  811. if (first) {
  812. line += fmt::format("{}", ucl_object_tostring(cur));
  813. first = false;
  814. }
  815. else {
  816. line += fmt::format(",{}", ucl_object_tostring(cur));
  817. }
  818. }
  819. line += ']';
  820. }
  821. rspamc_print_indented_line<78, 28>(out, line);
  822. }
  823. static void
  824. rspamc_symbol_output(FILE *out, const ucl_object_t *obj)
  825. {
  826. auto first = true;
  827. rspamc_print(out, "Symbol: {} ", ucl_object_key(obj));
  828. const auto *val = ucl_object_lookup(obj, "score");
  829. if (val != nullptr) {
  830. rspamc_print(out, "({:.2f})", ucl_object_todouble(val));
  831. }
  832. val = ucl_object_lookup(obj, "options");
  833. if (val != nullptr && ucl_object_type(val) == UCL_ARRAY) {
  834. ucl_object_iter_t it = nullptr;
  835. const ucl_object_t *cur;
  836. rspamc_print(out, "[");
  837. while ((cur = ucl_object_iterate(val, &it, true)) != nullptr) {
  838. if (first) {
  839. rspamc_print(out, "{}", ucl_object_tostring(cur));
  840. first = false;
  841. }
  842. else {
  843. rspamc_print(out, ", {}", ucl_object_tostring(cur));
  844. }
  845. }
  846. rspamc_print(out, "]");
  847. }
  848. rspamc_print(out, "\n");
  849. }
  850. static void
  851. rspamc_metric_output(FILE *out, const ucl_object_t *obj)
  852. {
  853. int got_scores = 0;
  854. bool is_spam = false;
  855. double score = 0, required_score = 0, greylist_score = 0, addheader_score = 0;
  856. auto print_protocol_string = [&](const char *ucl_name, const char *output_message) {
  857. auto *elt = ucl_object_lookup(obj, ucl_name);
  858. if (elt) {
  859. if (humanreport) {
  860. rspamc_print(out, ",{}={}", output_message, emphasis_argument(ucl_object_tostring(elt)));
  861. }
  862. else {
  863. rspamc_print(out, "{}: {}\n", output_message, emphasis_argument(ucl_object_tostring(elt)));
  864. }
  865. }
  866. };
  867. if (!humanreport) {
  868. rspamc_print(out, "[Metric: default]\n");
  869. }
  870. const auto *elt = ucl_object_lookup(obj, "required_score");
  871. if (elt) {
  872. required_score = ucl_object_todouble(elt);
  873. got_scores++;
  874. }
  875. elt = ucl_object_lookup(obj, "score");
  876. if (elt) {
  877. score = ucl_object_todouble(elt);
  878. got_scores++;
  879. }
  880. const auto *thresholds_obj = ucl_object_lookup(obj, "thresholds");
  881. if (thresholds_obj && ucl_object_type(thresholds_obj) == UCL_OBJECT) {
  882. const auto *action_obj = ucl_object_lookup(thresholds_obj, "greylist");
  883. if (action_obj) {
  884. greylist_score = ucl_object_todouble(action_obj);
  885. }
  886. action_obj = ucl_object_lookup(thresholds_obj, "add header");
  887. if (action_obj) {
  888. addheader_score = ucl_object_todouble(action_obj);
  889. }
  890. action_obj = ucl_object_lookup(thresholds_obj, "reject");
  891. if (action_obj) {
  892. required_score = ucl_object_todouble(action_obj);
  893. }
  894. }
  895. if (humanreport) {
  896. rspamc_print(out,
  897. "{}/{}/{}/{}",
  898. emphasis_argument(score, 2),
  899. emphasis_argument(greylist_score, 2),
  900. emphasis_argument(addheader_score, 2),
  901. emphasis_argument(required_score, 2));
  902. }
  903. elt = ucl_object_lookup(obj, "action");
  904. if (elt) {
  905. auto act = rspamd_action_from_str_rspamc(ucl_object_tostring(elt));
  906. if (act.has_value()) {
  907. if (!tty) {
  908. if (humanreport) {
  909. rspamc_print(out, ",action={}:{}", act.value(), ucl_object_tostring(elt));
  910. }
  911. else {
  912. print_protocol_string("action", "Action");
  913. }
  914. }
  915. else {
  916. /* Colorize action type */
  917. std::string colorized_action;
  918. switch (act.value()) {
  919. case METRIC_ACTION_REJECT:
  920. colorized_action = fmt::format(fmt::fg(fmt::color::red), "reject");
  921. break;
  922. case METRIC_ACTION_NOACTION:
  923. colorized_action = fmt::format(fmt::fg(fmt::color::green), "no action");
  924. break;
  925. case METRIC_ACTION_ADD_HEADER:
  926. case METRIC_ACTION_REWRITE_SUBJECT:
  927. colorized_action = fmt::format(fmt::fg(fmt::color::orange), ucl_object_tostring(elt));
  928. break;
  929. case METRIC_ACTION_GREYLIST:
  930. case METRIC_ACTION_SOFT_REJECT:
  931. colorized_action = fmt::format(fmt::fg(fmt::color::gray), ucl_object_tostring(elt));
  932. break;
  933. default:
  934. colorized_action = fmt::format(fmt::emphasis::bold, ucl_object_tostring(elt));
  935. break;
  936. }
  937. if (humanreport) {
  938. rspamc_print(out, ",action={}:{}", act.value(), colorized_action);
  939. }
  940. else {
  941. rspamc_print(out, "Action: {}\n", colorized_action);
  942. }
  943. }
  944. is_spam = act.value() < METRIC_ACTION_GREYLIST ? true : false;
  945. if (!humanreport) {
  946. rspamc_print(out, "Spam: {}\n", is_spam ? "true" : "false");
  947. }
  948. }
  949. else {
  950. if (humanreport) {
  951. rspamc_print(out, ",action={}:{}", METRIC_ACTION_NOACTION, ucl_object_tostring(elt));
  952. }
  953. else {
  954. print_protocol_string("action", "Action");
  955. }
  956. }
  957. }
  958. if (!humanreport) {
  959. print_protocol_string("subject", "Subject");
  960. }
  961. if (humanreport) {
  962. auto is_skipped = 0;
  963. elt = ucl_object_lookup(obj, "is_skipped");
  964. if (elt && ucl_object_toboolean(elt)) {
  965. is_skipped = 1;
  966. }
  967. rspamc_print(out, ",spam={},skipped={}\n", is_spam ? 1 : 0, is_skipped);
  968. }
  969. else if (got_scores == 2) {
  970. rspamc_print(out,
  971. "Score: {} / {}\n",
  972. emphasis_argument(score, 2),
  973. emphasis_argument(required_score, 2));
  974. }
  975. if (humanreport) {
  976. rspamc_print(out, "Content analysis details: ({} points, {} required)\n\n",
  977. emphasis_argument(score, 2),
  978. emphasis_argument(addheader_score, 2));
  979. rspamc_print(out, " pts rule name description\n");
  980. rspamc_print(out, "---- ---------------------- --------------------------------------------------\n");
  981. }
  982. elt = ucl_object_lookup(obj, "symbols");
  983. if (elt) {
  984. std::vector<const ucl_object_t *> symbols;
  985. ucl_object_iter_t it = nullptr;
  986. const ucl_object_t *cur;
  987. while ((cur = ucl_object_iterate(elt, &it, true)) != nullptr) {
  988. symbols.push_back(cur);
  989. }
  990. sort_ucl_container_with_default(symbols, "name");
  991. for (const auto *sym_obj: symbols) {
  992. humanreport ? rspamc_symbol_human_output(out, sym_obj) : rspamc_symbol_output(out, sym_obj);
  993. }
  994. }
  995. if (humanreport) {
  996. rspamc_print(out, "\n");
  997. }
  998. }
  999. static void
  1000. rspamc_profile_output(FILE *out, const ucl_object_t *obj)
  1001. {
  1002. ucl_object_iter_t it = nullptr;
  1003. const ucl_object_t *cur;
  1004. std::vector<const ucl_object_t *> ar;
  1005. while ((cur = ucl_object_iterate(obj, &it, true)) != nullptr) {
  1006. ar.push_back(cur);
  1007. }
  1008. std::stable_sort(std::begin(ar), std::end(ar),
  1009. [](const ucl_object_t *u1, const ucl_object_t *u2) -> int {
  1010. return ucl_object_compare(u1, u2);
  1011. });
  1012. for (const auto *cur_elt: ar) {
  1013. rspamc_print(out, "\t{}: {:3} usec\n",
  1014. ucl_object_key(cur_elt), ucl_object_todouble(cur_elt));
  1015. }
  1016. }
  1017. static void
  1018. rspamc_symbols_output(FILE *out, ucl_object_t *obj)
  1019. {
  1020. rspamc_metric_output(out, obj);
  1021. auto print_protocol_string = [&](const char *ucl_name, const char *output_message) {
  1022. auto *elt = ucl_object_lookup(obj, ucl_name);
  1023. if (elt) {
  1024. rspamc_print(out, "{}: {}\n", output_message, ucl_object_tostring(elt));
  1025. }
  1026. };
  1027. if (!humanreport) {
  1028. print_protocol_string("message-id", "Message-ID");
  1029. print_protocol_string("queue-id", "Queue-ID");
  1030. }
  1031. const auto *elt = ucl_object_lookup(obj, "urls");
  1032. if (elt) {
  1033. char *emitted;
  1034. if (!extended_urls || compact) {
  1035. emitted = (char *) ucl_object_emit(elt, UCL_EMIT_JSON_COMPACT);
  1036. }
  1037. else {
  1038. emitted = (char *) ucl_object_emit(elt, UCL_EMIT_JSON);
  1039. }
  1040. if (humanreport) {
  1041. if (emitted && strcmp(emitted, "[]") != 0) {
  1042. rspamc_print_indented_line<78, 4>(out, fmt::format("Domains found: {}", emitted));
  1043. }
  1044. }
  1045. else {
  1046. rspamc_print(out, "Urls: {}\n", emitted);
  1047. }
  1048. free(emitted);
  1049. }
  1050. elt = ucl_object_lookup(obj, "emails");
  1051. if (elt) {
  1052. char *emitted;
  1053. if (!extended_urls || compact) {
  1054. emitted = (char *) ucl_object_emit(elt, UCL_EMIT_JSON_COMPACT);
  1055. }
  1056. else {
  1057. emitted = (char *) ucl_object_emit(elt, UCL_EMIT_JSON);
  1058. }
  1059. if (humanreport) {
  1060. if (emitted && strcmp(emitted, "[]") != 0) {
  1061. rspamc_print_indented_line<78, 4>(out, fmt::format("Emails found: {}", emitted));
  1062. }
  1063. }
  1064. else {
  1065. rspamc_print(out, "Emails: {}\n", emitted);
  1066. }
  1067. free(emitted);
  1068. }
  1069. print_protocol_string("error", "Scan error");
  1070. if (humanreport) {
  1071. return;
  1072. }
  1073. elt = ucl_object_lookup(obj, "messages");
  1074. if (elt && elt->type == UCL_OBJECT) {
  1075. ucl_object_iter_t mit = nullptr;
  1076. const ucl_object_t *cmesg;
  1077. while ((cmesg = ucl_object_iterate(elt, &mit, true)) != nullptr) {
  1078. if (ucl_object_type(cmesg) == UCL_STRING) {
  1079. rspamc_print(out, "Message - {}: {}\n",
  1080. ucl_object_key(cmesg), ucl_object_tostring(cmesg));
  1081. }
  1082. else {
  1083. char *rendered_message;
  1084. rendered_message = (char *) ucl_object_emit(cmesg, UCL_EMIT_JSON_COMPACT);
  1085. rspamc_print(out, "Message - {}: {:.60}\n",
  1086. ucl_object_key(cmesg), rendered_message);
  1087. free(rendered_message);
  1088. }
  1089. }
  1090. }
  1091. elt = ucl_object_lookup(obj, "dkim-signature");
  1092. if (elt && elt->type == UCL_STRING) {
  1093. rspamc_print(out, "DKIM-Signature: {}\n", ucl_object_tostring(elt));
  1094. }
  1095. else if (elt && elt->type == UCL_ARRAY) {
  1096. ucl_object_iter_t it = nullptr;
  1097. const ucl_object_t *cur;
  1098. while ((cur = ucl_object_iterate(elt, &it, true)) != nullptr) {
  1099. rspamc_print(out, "DKIM-Signature: {}\n", ucl_object_tostring(cur));
  1100. }
  1101. }
  1102. elt = ucl_object_lookup(obj, "profile");
  1103. if (elt) {
  1104. rspamc_print(out, "Profile data:\n");
  1105. rspamc_profile_output(out, elt);
  1106. }
  1107. }
  1108. static void
  1109. rspamc_uptime_output(FILE *out, ucl_object_t *obj)
  1110. {
  1111. int64_t seconds, days, hours, minutes;
  1112. const auto *elt = ucl_object_lookup(obj, "version");
  1113. if (elt != nullptr) {
  1114. rspamc_print(out, "Rspamd version: {}\n", ucl_object_tostring(elt));
  1115. }
  1116. elt = ucl_object_lookup(obj, "uptime");
  1117. if (elt != nullptr) {
  1118. rspamc_print(out, "Uptime: ");
  1119. seconds = ucl_object_toint(elt);
  1120. if (seconds >= 2 * 3600) {
  1121. days = seconds / 86400;
  1122. hours = seconds / 3600 - days * 24;
  1123. minutes = seconds / 60 - hours * 60 - days * 1440;
  1124. rspamc_print(out, "{} day{} {} hour{} {} minute{}\n", days,
  1125. days > 1 ? "s" : "", hours, hours > 1 ? "s" : "",
  1126. minutes, minutes > 1 ? "s" : "");
  1127. }
  1128. /* If uptime is less than 1 minute print only seconds */
  1129. else if (seconds / 60 == 0) {
  1130. rspamc_print(out, "{} second{}\n", seconds,
  1131. seconds > 1 ? "s" : "");
  1132. }
  1133. /* Else print the minutes and seconds. */
  1134. else {
  1135. hours = seconds / 3600;
  1136. minutes = seconds / 60 - hours * 60;
  1137. seconds -= hours * 3600 + minutes * 60;
  1138. rspamc_print(out, "{} hour {} minute{} {} second{}\n", hours,
  1139. minutes, minutes > 1 ? "s" : "",
  1140. seconds, seconds > 1 ? "s" : "");
  1141. }
  1142. }
  1143. }
  1144. static void
  1145. rspamc_counters_output(FILE *out, ucl_object_t *obj)
  1146. {
  1147. if (obj->type != UCL_ARRAY) {
  1148. rspamc_print(out, "Bad output\n");
  1149. return;
  1150. }
  1151. std::vector<const ucl_object_t *> counters_vec;
  1152. auto max_len = sizeof("Symbol") - 1;
  1153. {
  1154. ucl_object_iter_t iter = nullptr;
  1155. const ucl_object_t *cur;
  1156. while ((cur = ucl_object_iterate(obj, &iter, true)) != nullptr) {
  1157. const auto *sym = ucl_object_lookup(cur, "symbol");
  1158. if (sym != nullptr) {
  1159. if (sym->len > max_len) {
  1160. max_len = sym->len;
  1161. }
  1162. }
  1163. counters_vec.push_back(cur);
  1164. }
  1165. }
  1166. sort_ucl_container_with_default(counters_vec, "name");
  1167. char dash_buf[82], sym_buf[82];
  1168. const int dashes = 44;
  1169. max_len = MIN(sizeof(dash_buf) - dashes - 1, max_len);
  1170. memset(dash_buf, '-', dashes + max_len);
  1171. dash_buf[dashes + max_len] = '\0';
  1172. rspamc_print(out, "Symbols cache\n");
  1173. rspamc_print(out, " {} \n", emphasis_argument(dash_buf));
  1174. rspamc_print(out,
  1175. "| {:<4} | {:<{}} | {:^7} | {:^13} | {:^7} |\n",
  1176. "Pri",
  1177. "Symbol",
  1178. max_len,
  1179. "Weight",
  1180. "Frequency",
  1181. "Hits");
  1182. rspamc_print(out, " {} \n", emphasis_argument(dash_buf));
  1183. rspamc_print(out, "| {:<4} | {:<{}} | {:^7} | {:^13} | {:^7} |\n", "",
  1184. "", max_len,
  1185. "", "hits/min", "");
  1186. for (const auto [i, cur]: rspamd::enumerate(counters_vec)) {
  1187. rspamc_print(out, " {} \n", dash_buf);
  1188. const auto *sym = ucl_object_lookup(cur, "symbol");
  1189. const auto *weight = ucl_object_lookup(cur, "weight");
  1190. const auto *freq = ucl_object_lookup(cur, "frequency");
  1191. const auto *freq_dev = ucl_object_lookup(cur, "frequency_stddev");
  1192. const auto *nhits = ucl_object_lookup(cur, "hits");
  1193. if (sym && weight && freq && nhits) {
  1194. const char *sym_name;
  1195. if (sym->len > max_len) {
  1196. rspamd_snprintf(sym_buf, sizeof(sym_buf), "%*s...",
  1197. (max_len - 3), ucl_object_tostring(sym));
  1198. sym_name = sym_buf;
  1199. }
  1200. else {
  1201. sym_name = ucl_object_tostring(sym);
  1202. }
  1203. rspamc_print(out, "| {:<4} | {:<{}} | {:^7.1f} | {:^6.3f}({:^5.3f}) | {:^7} |\n", i,
  1204. sym_name,
  1205. max_len,
  1206. ucl_object_todouble(weight),
  1207. ucl_object_todouble(freq) * 60.0,
  1208. ucl_object_todouble(freq_dev) * 60.0,
  1209. (std::uintmax_t) ucl_object_toint(nhits));
  1210. }
  1211. }
  1212. rspamc_print(out, " {} \n", dash_buf);
  1213. }
  1214. static void
  1215. rspamc_stat_actions(ucl_object_t *obj, std::string &out, std::int64_t scanned)
  1216. {
  1217. const ucl_object_t *actions = ucl_object_lookup(obj, "actions"), *cur;
  1218. ucl_object_iter_t iter = nullptr;
  1219. if (scanned > 0) {
  1220. if (actions && ucl_object_type(actions) == UCL_OBJECT) {
  1221. while ((cur = ucl_object_iterate(actions, &iter, true)) != nullptr) {
  1222. auto cnt = ucl_object_toint(cur);
  1223. fmt::format_to(std::back_inserter(out), "Messages with action {}: {}, {:.2f}%\n",
  1224. ucl_object_key(cur), emphasis_argument(cnt),
  1225. ((double) cnt / (double) scanned) * 100.);
  1226. }
  1227. }
  1228. auto spam = ucl_object_toint(ucl_object_lookup(obj, "spam_count"));
  1229. auto ham = ucl_object_toint(ucl_object_lookup(obj, "ham_count"));
  1230. fmt::format_to(std::back_inserter(out), "Messages treated as spam: {}, {:.2f}%\n",
  1231. emphasis_argument(spam),
  1232. ((double) spam / (double) scanned) * 100.);
  1233. fmt::format_to(std::back_inserter(out), "Messages treated as ham: {}, {:.2f}%\n",
  1234. emphasis_argument(ham),
  1235. ((double) ham / (double) scanned) * 100.);
  1236. }
  1237. }
  1238. static void
  1239. rspamc_stat_statfile(const ucl_object_t *obj, std::string &out)
  1240. {
  1241. auto version = ucl_object_toint(ucl_object_lookup(obj, "revision"));
  1242. auto size = ucl_object_toint(ucl_object_lookup(obj, "size"));
  1243. auto blocks = ucl_object_toint(ucl_object_lookup(obj, "total"));
  1244. auto used_blocks = ucl_object_toint(ucl_object_lookup(obj, "used"));
  1245. auto label = ucl_object_tostring(ucl_object_lookup(obj, "label"));
  1246. auto symbol = ucl_object_tostring(ucl_object_lookup(obj, "symbol"));
  1247. auto type = ucl_object_tostring(ucl_object_lookup(obj, "type"));
  1248. auto nlanguages = ucl_object_toint(ucl_object_lookup(obj, "languages"));
  1249. auto nusers = ucl_object_toint(ucl_object_lookup(obj, "users"));
  1250. if (label) {
  1251. fmt::format_to(std::back_inserter(out), "Statfile: {} <{}> type: {}; ", symbol,
  1252. label, type);
  1253. }
  1254. else {
  1255. fmt::format_to(std::back_inserter(out), "Statfile: {} type: {}; ", symbol, type);
  1256. }
  1257. fmt::format_to(std::back_inserter(out), "length: {}; free blocks: {}; total blocks: {}; "
  1258. "free: {:.2f}%; learned: {}; users: {}; languages: {}\n",
  1259. size,
  1260. blocks - used_blocks, blocks,
  1261. blocks > 0 ? (blocks - used_blocks) * 100.0 / (double) blocks : 0,
  1262. version,
  1263. nusers, nlanguages);
  1264. }
  1265. static void
  1266. rspamc_stat_output(FILE *out, ucl_object_t *obj)
  1267. {
  1268. std::string out_str;
  1269. out_str.reserve(8192);
  1270. auto scanned = ucl_object_toint(ucl_object_lookup(obj, "scanned"));
  1271. fmt::format_to(std::back_inserter(out_str), "Messages scanned: {}\n",
  1272. emphasis_argument(scanned));
  1273. rspamc_stat_actions(obj, out_str, scanned);
  1274. fmt::format_to(std::back_inserter(out_str), "Messages learned: {}\n",
  1275. emphasis_argument(ucl_object_toint(ucl_object_lookup(obj, "learned"))));
  1276. fmt::format_to(std::back_inserter(out_str), "Connections count: {}\n",
  1277. emphasis_argument(ucl_object_toint(ucl_object_lookup(obj, "connections"))));
  1278. fmt::format_to(std::back_inserter(out_str), "Control connections count: {}\n",
  1279. emphasis_argument(ucl_object_toint(ucl_object_lookup(obj, "control_connections"))));
  1280. const auto *avg_time_obj = ucl_object_lookup(obj, "scan_times");
  1281. if (avg_time_obj && ucl_object_type(avg_time_obj) == UCL_ARRAY) {
  1282. ucl_object_iter_t iter = nullptr;
  1283. const ucl_object_t *cur;
  1284. std::vector<float> nums;
  1285. while ((cur = ucl_object_iterate(avg_time_obj, &iter, true)) != nullptr) {
  1286. if (ucl_object_type(cur) == UCL_FLOAT || ucl_object_type(cur) == UCL_INT) {
  1287. nums.push_back(ucl_object_todouble(cur));
  1288. }
  1289. }
  1290. auto cnt = nums.size();
  1291. if (cnt > 0) {
  1292. auto sum = rspamd_sum_floats(nums.data(), &cnt);
  1293. fmt::format_to(std::back_inserter(out_str),
  1294. "Average scan time: {} sec\n",
  1295. emphasis_argument(sum / cnt, 3));
  1296. }
  1297. }
  1298. /* Pools */
  1299. fmt::format_to(std::back_inserter(out_str), "Pools allocated: {}\n",
  1300. ucl_object_toint(ucl_object_lookup(obj, "pools_allocated")));
  1301. fmt::format_to(std::back_inserter(out_str), "Pools freed: {}\n",
  1302. ucl_object_toint(ucl_object_lookup(obj, "pools_freed")));
  1303. fmt::format_to(std::back_inserter(out_str), "Bytes allocated: {}\n",
  1304. ucl_object_toint(ucl_object_lookup(obj, "bytes_allocated")));
  1305. fmt::format_to(std::back_inserter(out_str), "Memory chunks allocated: {}\n",
  1306. ucl_object_toint(ucl_object_lookup(obj, "chunks_allocated")));
  1307. fmt::format_to(std::back_inserter(out_str), "Shared chunks allocated: {}\n",
  1308. ucl_object_toint(ucl_object_lookup(obj, "shared_chunks_allocated")));
  1309. fmt::format_to(std::back_inserter(out_str), "Chunks freed: {}\n",
  1310. ucl_object_toint(ucl_object_lookup(obj, "chunks_freed")));
  1311. fmt::format_to(std::back_inserter(out_str), "Oversized chunks: {}\n",
  1312. ucl_object_toint(ucl_object_lookup(obj, "chunks_oversized")));
  1313. /* Fuzzy */
  1314. const auto *st = ucl_object_lookup(obj, "fuzzy_hashes");
  1315. if (st) {
  1316. ucl_object_iter_t it = nullptr;
  1317. const ucl_object_t *cur;
  1318. std::uint64_t stored = 0;
  1319. while ((cur = ucl_iterate_object(st, &it, true)) != nullptr) {
  1320. auto num = ucl_object_toint(cur);
  1321. fmt::format_to(std::back_inserter(out_str), "Fuzzy hashes in storage \"{}\": {}\n",
  1322. ucl_object_key(cur),
  1323. num);
  1324. stored += num;
  1325. }
  1326. fmt::format_to(std::back_inserter(out_str), "Fuzzy hashes stored: {}\n",
  1327. stored);
  1328. }
  1329. st = ucl_object_lookup(obj, "fuzzy_checked");
  1330. if (st != nullptr && ucl_object_type(st) == UCL_ARRAY) {
  1331. ucl_object_iter_t iter = nullptr;
  1332. const ucl_object_t *cur;
  1333. out_str += "Fuzzy hashes checked: ";
  1334. while ((cur = ucl_object_iterate(st, &iter, true)) != nullptr) {
  1335. fmt::format_to(std::back_inserter(out_str), "{} ", ucl_object_toint(cur));
  1336. }
  1337. out_str.push_back('\n');
  1338. }
  1339. st = ucl_object_lookup(obj, "fuzzy_found");
  1340. if (st != nullptr && ucl_object_type(st) == UCL_ARRAY) {
  1341. ucl_object_iter_t iter = nullptr;
  1342. const ucl_object_t *cur;
  1343. out_str += "Fuzzy hashes found: ";
  1344. while ((cur = ucl_object_iterate(st, &iter, true)) != nullptr) {
  1345. fmt::format_to(std::back_inserter(out_str), "{} ", ucl_object_toint(cur));
  1346. }
  1347. out_str.push_back('\n');
  1348. }
  1349. st = ucl_object_lookup(obj, "statfiles");
  1350. if (st != nullptr && ucl_object_type(st) == UCL_ARRAY) {
  1351. ucl_object_iter_t iter = nullptr;
  1352. const ucl_object_t *cur;
  1353. while ((cur = ucl_object_iterate(st, &iter, true)) != nullptr) {
  1354. rspamc_stat_statfile(cur, out_str);
  1355. }
  1356. }
  1357. fmt::format_to(std::back_inserter(out_str), "Total learns: {}\n",
  1358. ucl_object_toint(ucl_object_lookup(obj, "total_learns")));
  1359. rspamc_print(out, "{}", out_str.c_str());
  1360. }
  1361. static void
  1362. rspamc_output_headers(FILE *out, struct rspamd_http_message *msg)
  1363. {
  1364. struct rspamd_http_header *h;
  1365. kh_foreach_value(msg->headers, h, {
  1366. rspamc_print(out, "{}: {}\n", std::string_view{h->name.begin, h->name.len},
  1367. std::string_view{h->value.begin, h->value.len});
  1368. });
  1369. rspamc_print(out, "\n");
  1370. }
  1371. static void
  1372. rspamc_mime_output(FILE *out, ucl_object_t *result, GString *input,
  1373. double time, GError *err)
  1374. {
  1375. const char *action = "no action", *line_end = "\r\n", *p;
  1376. double score = 0.0, required_score = 0.0;
  1377. gboolean is_spam = FALSE;
  1378. auto nl_type = RSPAMD_TASK_NEWLINES_CRLF;
  1379. auto headers_pos = rspamd_string_find_eoh(input, nullptr);
  1380. if (headers_pos == -1) {
  1381. rspamc_print(stderr, "cannot find end of headers position");
  1382. return;
  1383. }
  1384. p = input->str + headers_pos;
  1385. if (headers_pos > 1 && *(p - 1) == '\n') {
  1386. if (headers_pos > 2 && *(p - 2) == '\r') {
  1387. line_end = "\r\n";
  1388. nl_type = RSPAMD_TASK_NEWLINES_CRLF;
  1389. }
  1390. else {
  1391. line_end = "\n";
  1392. nl_type = RSPAMD_TASK_NEWLINES_LF;
  1393. }
  1394. }
  1395. else if (headers_pos > 1 && *(p - 1) == '\r') {
  1396. line_end = "\r";
  1397. nl_type = RSPAMD_TASK_NEWLINES_CR;
  1398. }
  1399. std::string added_headers;
  1400. if (result) {
  1401. const auto *res = ucl_object_lookup(result, "action");
  1402. if (res) {
  1403. action = ucl_object_tostring(res);
  1404. }
  1405. res = ucl_object_lookup(result, "score");
  1406. if (res) {
  1407. score = ucl_object_todouble(res);
  1408. }
  1409. res = ucl_object_lookup(result, "required_score");
  1410. if (res) {
  1411. required_score = ucl_object_todouble(res);
  1412. }
  1413. auto act = rspamd_action_from_str_rspamc(action);
  1414. if (act.has_value() && act.value() < METRIC_ACTION_GREYLIST) {
  1415. is_spam = TRUE;
  1416. }
  1417. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Scanner: {}{}",
  1418. "rspamc " RVERSION, line_end);
  1419. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Scan-Time: {:.3}{}",
  1420. time, line_end);
  1421. /*
  1422. * TODO: add milter_headers support here
  1423. */
  1424. if (is_spam) {
  1425. fmt::format_to(std::back_inserter(added_headers), "X-Spam: yes{}", line_end);
  1426. }
  1427. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Action: {}{}",
  1428. action, line_end);
  1429. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Score: {:.2f} / {:.2f}{}",
  1430. score, required_score, line_end);
  1431. /* SA style stars header */
  1432. std::string scorebuf;
  1433. auto adjusted_score = std::min(score, 32.0);
  1434. while (adjusted_score > 0) {
  1435. scorebuf.push_back('*');
  1436. adjusted_score -= 1.0;
  1437. }
  1438. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Level: {}{}",
  1439. scorebuf, line_end);
  1440. /* Short description of all symbols */
  1441. std::string symbuf;
  1442. const ucl_object_t *cur;
  1443. ucl_object_iter_t it = nullptr;
  1444. const auto *syms = ucl_object_lookup(result, "symbols");
  1445. while (syms && (cur = ucl_object_iterate(syms, &it, true)) != nullptr) {
  1446. if (ucl_object_type(cur) == UCL_OBJECT) {
  1447. fmt::format_to(std::back_inserter(symbuf), "{},", ucl_object_key(cur));
  1448. }
  1449. }
  1450. /* Trim the last comma */
  1451. if (symbuf.back() == ',') {
  1452. symbuf.pop_back();
  1453. }
  1454. auto *folded_symbuf = rspamd_header_value_fold("X-Spam-Symbols", strlen("X-Spam-Symbols"),
  1455. symbuf.data(), symbuf.size(),
  1456. 0, nl_type, ",");
  1457. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Symbols: {}{}",
  1458. folded_symbuf->str, line_end);
  1459. g_string_free(folded_symbuf, TRUE);
  1460. res = ucl_object_lookup(result, "dkim-signature");
  1461. if (res && res->type == UCL_STRING) {
  1462. fmt::format_to(std::back_inserter(added_headers), "DKIM-Signature: {}{}",
  1463. ucl_object_tostring(res), line_end);
  1464. }
  1465. else if (res && res->type == UCL_ARRAY) {
  1466. it = nullptr;
  1467. while ((cur = ucl_object_iterate(res, &it, true)) != nullptr) {
  1468. fmt::format_to(std::back_inserter(added_headers), "DKIM-Signature: {}{}",
  1469. ucl_object_tostring(cur), line_end);
  1470. }
  1471. }
  1472. if (json || ucl_reply || compact) {
  1473. unsigned char *json_header;
  1474. /* We also append json data as a specific header */
  1475. if (json) {
  1476. json_header = ucl_object_emit(result,
  1477. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1478. }
  1479. else {
  1480. json_header = ucl_object_emit(result,
  1481. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1482. }
  1483. auto *json_header_encoded = rspamd_encode_base64_fold(json_header,
  1484. strlen((char *) json_header), 60, nullptr, nl_type);
  1485. free(json_header);
  1486. fmt::format_to(std::back_inserter(added_headers),
  1487. "X-Spam-Result: {}{}",
  1488. json_header_encoded, line_end);
  1489. g_free(json_header_encoded);
  1490. }
  1491. ucl_object_unref(result);
  1492. }
  1493. else {
  1494. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Scanner: {}{}",
  1495. "rspamc " RVERSION, line_end);
  1496. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Scan-Time: {:.3f}{}",
  1497. time, line_end);
  1498. fmt::format_to(std::back_inserter(added_headers), "X-Spam-Error: {}{}",
  1499. err->message, line_end);
  1500. }
  1501. /* Write message */
  1502. /* Original headers */
  1503. rspamc_print(out, "{}", std::string_view{input->str, (std::size_t) headers_pos});
  1504. /* Added headers */
  1505. rspamc_print(out, "{}", added_headers);
  1506. /* Message body */
  1507. rspamc_print(out, "{}", input->str + headers_pos);
  1508. }
  1509. static void
  1510. rspamc_client_execute_cmd(const struct rspamc_command &cmd, ucl_object_t *result,
  1511. GString *input, double time, GError *err)
  1512. {
  1513. char **eargv;
  1514. int eargc, infd, outfd, errfd;
  1515. GError *exec_err = nullptr;
  1516. GPid cld;
  1517. if (!g_shell_parse_argv(execute, &eargc, &eargv, &err)) {
  1518. rspamc_print(stderr, "Cannot execute {}: {}", execute, err->message);
  1519. g_error_free(err);
  1520. return;
  1521. }
  1522. if (!g_spawn_async_with_pipes(nullptr, eargv, nullptr,
  1523. static_cast<GSpawnFlags>(G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD), nullptr, nullptr, &cld,
  1524. &infd, &outfd, &errfd, &exec_err)) {
  1525. rspamc_print(stderr, "Cannot execute {}: {}", execute, exec_err->message);
  1526. g_error_free(exec_err);
  1527. exit(EXIT_FAILURE);
  1528. }
  1529. else {
  1530. children.push_back(cld);
  1531. auto *out = fdopen(infd, "w");
  1532. if (cmd.cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
  1533. rspamc_mime_output(out, result, input, time, err);
  1534. }
  1535. else if (result) {
  1536. if (ucl_reply || cmd.command_output_func == nullptr) {
  1537. char *ucl_out;
  1538. if (json) {
  1539. ucl_out = (char *) ucl_object_emit(result,
  1540. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1541. }
  1542. else {
  1543. ucl_out = (char *) ucl_object_emit(result,
  1544. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1545. }
  1546. rspamc_print(out, "{}", ucl_out);
  1547. free(ucl_out);
  1548. }
  1549. else {
  1550. cmd.command_output_func(out, result);
  1551. }
  1552. ucl_object_unref(result);
  1553. }
  1554. else {
  1555. rspamc_print(out, "{}\n", err->message);
  1556. }
  1557. fflush(out);
  1558. fclose(out);
  1559. }
  1560. g_strfreev(eargv);
  1561. }
  1562. static void
  1563. rspamc_client_cb(struct rspamd_client_connection *conn,
  1564. struct rspamd_http_message *msg,
  1565. const char *name, ucl_object_t *result, GString *input,
  1566. gpointer ud, double start_time, double send_time,
  1567. const char *body, gsize bodylen,
  1568. GError *err)
  1569. {
  1570. struct rspamc_callback_data *cbdata = (struct rspamc_callback_data *) ud;
  1571. FILE *out = stdout;
  1572. double finish = rspamd_get_ticks(FALSE), diff;
  1573. auto &cmd = cbdata->cmd;
  1574. if (send_time > 0) {
  1575. diff = finish - send_time;
  1576. }
  1577. else {
  1578. diff = finish - start_time;
  1579. }
  1580. if (execute) {
  1581. /* Pass all to the external command */
  1582. rspamc_client_execute_cmd(cmd, result, input, diff, err);
  1583. }
  1584. else {
  1585. if (cmd.cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) {
  1586. if (body) {
  1587. GString tmp;
  1588. tmp.str = (char *) body;
  1589. tmp.len = bodylen;
  1590. rspamc_mime_output(out, result, &tmp, diff, err);
  1591. }
  1592. else {
  1593. rspamc_mime_output(out, result, input, diff, err);
  1594. }
  1595. }
  1596. else {
  1597. if (cmd.need_input && !json) {
  1598. if (!compact && !humanreport) {
  1599. rspamc_print(out, "Results for file: {} ({:.3} seconds)\n",
  1600. emphasis_argument(cbdata->filename), diff);
  1601. }
  1602. }
  1603. else {
  1604. if (!compact && !json && !humanreport) {
  1605. rspamc_print(out, "Results for command: {} ({:.3} seconds)\n",
  1606. emphasis_argument(cmd.name), diff);
  1607. }
  1608. }
  1609. if (result != nullptr) {
  1610. if (headers && msg != nullptr) {
  1611. rspamc_output_headers(out, msg);
  1612. }
  1613. if (ucl_reply || cmd.command_output_func == nullptr) {
  1614. if (cmd.need_input) {
  1615. ucl_object_insert_key(result,
  1616. ucl_object_fromstring(cbdata->filename.c_str()),
  1617. "filename", 0,
  1618. false);
  1619. }
  1620. ucl_object_insert_key(result,
  1621. ucl_object_fromdouble(diff),
  1622. "scan_time", 0,
  1623. false);
  1624. char *ucl_out;
  1625. if (json) {
  1626. ucl_out = (char *) ucl_object_emit(result,
  1627. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON);
  1628. }
  1629. else {
  1630. ucl_out = (char *) ucl_object_emit(result,
  1631. compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG);
  1632. }
  1633. rspamc_print(out, "{}", ucl_out);
  1634. free(ucl_out);
  1635. }
  1636. else {
  1637. cmd.command_output_func(out, result);
  1638. }
  1639. if (body) {
  1640. rspamc_print(out, "\nNew body:\n{}\n",
  1641. std::string_view{body, bodylen});
  1642. }
  1643. ucl_object_unref(result);
  1644. }
  1645. else if (err != nullptr) {
  1646. rspamc_print(out, "{}\n", err->message);
  1647. if (json && msg != nullptr) {
  1648. gsize rawlen;
  1649. auto *raw_body = rspamd_http_message_get_body(msg, &rawlen);
  1650. if (raw_body) {
  1651. /* We can also output the resulting json */
  1652. rspamc_print(out, "{}\n", std::string_view{raw_body, (std::size_t)(rawlen - bodylen)});
  1653. }
  1654. }
  1655. }
  1656. rspamc_print(out, "\n");
  1657. }
  1658. fflush(out);
  1659. }
  1660. rspamd_client_destroy(conn);
  1661. delete cbdata;
  1662. if (err) {
  1663. retcode = EXIT_FAILURE;
  1664. }
  1665. }
  1666. static void
  1667. rspamc_process_input(struct ev_loop *ev_base, const struct rspamc_command &cmd,
  1668. FILE *in, const std::string &name, GQueue *attrs)
  1669. {
  1670. struct rspamd_client_connection *conn;
  1671. const char *p;
  1672. uint16_t port;
  1673. GError *err = nullptr;
  1674. std::string hostbuf;
  1675. if (connect_str[0] == '[') {
  1676. p = strrchr(connect_str, ']');
  1677. if (p != nullptr) {
  1678. hostbuf.assign(connect_str + 1, (std::size_t)(p - connect_str - 1));
  1679. p++;
  1680. }
  1681. else {
  1682. p = connect_str;
  1683. }
  1684. }
  1685. else {
  1686. p = connect_str;
  1687. }
  1688. p = strrchr(p, ':');
  1689. if (hostbuf.empty()) {
  1690. if (p != nullptr) {
  1691. hostbuf.assign(connect_str, (std::size_t)(p - connect_str));
  1692. }
  1693. else {
  1694. hostbuf.assign(connect_str);
  1695. }
  1696. }
  1697. if (p != nullptr) {
  1698. port = strtoul(p + 1, nullptr, 10);
  1699. }
  1700. else {
  1701. /*
  1702. * If we connect to localhost, 127.0.0.1 or ::1, then try controller
  1703. * port first
  1704. */
  1705. if (hostbuf == "localhost" ||
  1706. hostbuf == "127.0.0.1" ||
  1707. hostbuf == "::1" ||
  1708. hostbuf == "[::1]") {
  1709. port = DEFAULT_CONTROL_PORT;
  1710. }
  1711. else {
  1712. port = cmd.is_controller ? DEFAULT_CONTROL_PORT : DEFAULT_PORT;
  1713. }
  1714. }
  1715. conn = rspamd_client_init(http_ctx, ev_base, hostbuf.c_str(), port, timeout, pubkey);
  1716. if (conn != nullptr) {
  1717. auto *cbdata = new rspamc_callback_data;
  1718. cbdata->cmd = cmd;
  1719. cbdata->filename = name;
  1720. if (cmd.need_input) {
  1721. rspamd_client_command(conn, cmd.path, attrs, in, rspamc_client_cb,
  1722. cbdata, compressed, dictionary, cbdata->filename.c_str(), &err);
  1723. }
  1724. else {
  1725. rspamd_client_command(conn,
  1726. cmd.path,
  1727. attrs,
  1728. nullptr,
  1729. rspamc_client_cb,
  1730. cbdata,
  1731. compressed,
  1732. dictionary,
  1733. cbdata->filename.c_str(),
  1734. &err);
  1735. }
  1736. }
  1737. else {
  1738. rspamc_print(stderr, "cannot connect to {}: {}\n", connect_str,
  1739. strerror(errno));
  1740. exit(EXIT_FAILURE);
  1741. }
  1742. }
  1743. static gsize
  1744. rspamd_dirent_size(DIR *dirp)
  1745. {
  1746. goffset name_max;
  1747. gsize name_end;
  1748. #if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) && defined(_PC_NAME_MAX)
  1749. name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
  1750. #if defined(NAME_MAX)
  1751. if (name_max == -1) {
  1752. name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
  1753. }
  1754. #else
  1755. if (name_max == -1) {
  1756. return (size_t) (-1);
  1757. }
  1758. #endif
  1759. #else
  1760. #if defined(NAME_MAX)
  1761. name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
  1762. #else
  1763. #error "buffer size for readdir_r cannot be determined"
  1764. #endif
  1765. #endif
  1766. name_end = G_STRUCT_OFFSET(struct dirent, d_name) + name_max + 1;
  1767. return (name_end > sizeof(struct dirent) ? name_end : sizeof(struct dirent));
  1768. }
  1769. static void
  1770. rspamc_process_dir(struct ev_loop *ev_base, const struct rspamc_command &cmd,
  1771. const std::string &name, GQueue *attrs)
  1772. {
  1773. static auto cur_req = 0;
  1774. auto *d = opendir(name.c_str());
  1775. if (d != nullptr) {
  1776. struct dirent *pentry;
  1777. std::string fpath;
  1778. fpath.reserve(PATH_MAX);
  1779. while ((pentry = readdir(d)) != nullptr) {
  1780. if (pentry->d_name[0] == '.') {
  1781. continue;
  1782. }
  1783. fpath.clear();
  1784. fmt::format_to(std::back_inserter(fpath), "{}{}{}",
  1785. name, G_DIR_SEPARATOR,
  1786. pentry->d_name);
  1787. /* Check exclude */
  1788. auto **ex = exclude_compiled;
  1789. auto skip = false;
  1790. while (ex != nullptr && *ex != nullptr) {
  1791. #if GLIB_MAJOR_VERSION >= 2 && GLIB_MINOR_VERSION >= 70
  1792. if (g_pattern_spec_match(*ex, fpath.size(), fpath.c_str(), nullptr)) {
  1793. #else
  1794. if (g_pattern_match(*ex, fpath.size(), fpath.c_str(), nullptr)) {
  1795. #endif
  1796. skip = true;
  1797. break;
  1798. }
  1799. ex++;
  1800. }
  1801. if (skip) {
  1802. continue;
  1803. }
  1804. auto is_reg = false;
  1805. auto is_dir = false;
  1806. struct stat st;
  1807. #if (defined(_DIRENT_HAVE_D_TYPE) || defined(__APPLE__)) && defined(DT_UNKNOWN)
  1808. if (pentry->d_type == DT_UNKNOWN) {
  1809. /* Fallback to lstat */
  1810. if (lstat(fpath.c_str(), &st) == -1) {
  1811. rspamc_print(stderr, "cannot stat file {}: {}\n",
  1812. fpath, strerror(errno));
  1813. continue;
  1814. }
  1815. is_dir = S_ISDIR(st.st_mode);
  1816. is_reg = S_ISREG(st.st_mode);
  1817. }
  1818. else {
  1819. if (pentry->d_type == DT_REG) {
  1820. is_reg = true;
  1821. }
  1822. else if (pentry->d_type == DT_DIR) {
  1823. is_dir = true;
  1824. }
  1825. }
  1826. #else
  1827. if (lstat(fpath.c_str(), &st) == -1) {
  1828. rspamc_print(stderr, "cannot stat file {}: {}\n",
  1829. fpath, strerror(errno));
  1830. continue;
  1831. }
  1832. is_dir = S_ISDIR(st.st_mode);
  1833. is_reg = S_ISREG(st.st_mode);
  1834. #endif
  1835. if (is_dir) {
  1836. rspamc_process_dir(ev_base, cmd, fpath, attrs);
  1837. continue;
  1838. }
  1839. else if (is_reg) {
  1840. auto *in = fopen(fpath.c_str(), "r");
  1841. if (in == nullptr) {
  1842. rspamc_print(stderr, "cannot open file {}: {}\n",
  1843. fpath, strerror(errno));
  1844. continue;
  1845. }
  1846. rspamc_process_input(ev_base, cmd, in, fpath, attrs);
  1847. cur_req++;
  1848. fclose(in);
  1849. if (cur_req >= max_requests) {
  1850. cur_req = 0;
  1851. /* Wait for completion */
  1852. ev_loop(ev_base, 0);
  1853. }
  1854. }
  1855. }
  1856. }
  1857. else {
  1858. rspamc_print(stderr, "cannot open directory {}: {}\n", name, strerror(errno));
  1859. exit(EXIT_FAILURE);
  1860. }
  1861. closedir(d);
  1862. ev_loop(ev_base, 0);
  1863. }
  1864. static void
  1865. rspamc_kwattr_free(gpointer p)
  1866. {
  1867. struct rspamd_http_client_header *h = (struct rspamd_http_client_header *) p;
  1868. g_free(h->value);
  1869. g_free(h->name);
  1870. g_free(h);
  1871. }
  1872. int main(int argc, char **argv, char **env)
  1873. {
  1874. auto *kwattrs = g_queue_new();
  1875. read_cmd_line(&argc, &argv);
  1876. tty = isatty(STDOUT_FILENO);
  1877. if (print_commands) {
  1878. print_commands_list();
  1879. exit(EXIT_SUCCESS);
  1880. }
  1881. /* Deal with exclude patterns */
  1882. auto **exclude_pattern = exclude_patterns;
  1883. auto npatterns = 0;
  1884. while (exclude_pattern && *exclude_pattern) {
  1885. exclude_pattern++;
  1886. npatterns++;
  1887. }
  1888. if (npatterns > 0) {
  1889. exclude_compiled = g_new0(GPatternSpec *, (npatterns + 1));
  1890. for (auto i = 0; i < npatterns; i++) {
  1891. exclude_compiled[i] = g_pattern_spec_new(exclude_patterns[i]);
  1892. if (exclude_compiled[i] == nullptr) {
  1893. rspamc_print(stderr, "Invalid glob pattern: {}\n",
  1894. exclude_patterns[i]);
  1895. exit(EXIT_FAILURE);
  1896. }
  1897. }
  1898. }
  1899. auto *libs = rspamd_init_libs();
  1900. auto *event_loop = ev_loop_new(EVBACKEND_ALL);
  1901. struct rspamd_http_context_cfg http_config;
  1902. memset(&http_config, 0, sizeof(http_config));
  1903. http_config.kp_cache_size_client = 32;
  1904. http_config.kp_cache_size_server = 0;
  1905. http_config.user_agent = user_agent;
  1906. http_ctx = rspamd_http_context_create_config(&http_config,
  1907. event_loop, nullptr);
  1908. /* Ignore sigpipe */
  1909. struct sigaction sigpipe_act;
  1910. sigemptyset(&sigpipe_act.sa_mask);
  1911. sigaddset(&sigpipe_act.sa_mask, SIGPIPE);
  1912. sigpipe_act.sa_handler = SIG_IGN;
  1913. sigpipe_act.sa_flags = 0;
  1914. sigaction(SIGPIPE, &sigpipe_act, nullptr);
  1915. /* Now read other args from argc and argv */
  1916. FILE *in = nullptr;
  1917. std::optional<rspamc_command> maybe_cmd;
  1918. auto start_argc = 0;
  1919. if (argc == 1) {
  1920. start_argc = argc;
  1921. in = stdin;
  1922. maybe_cmd = check_rspamc_command("symbols");
  1923. }
  1924. else if (argc == 2) {
  1925. /* One argument is whether command or filename */
  1926. maybe_cmd = check_rspamc_command(argv[1]);
  1927. if (maybe_cmd.has_value()) {
  1928. start_argc = argc;
  1929. in = stdin;
  1930. }
  1931. else {
  1932. maybe_cmd = check_rspamc_command("symbols"); /* Symbols command */
  1933. start_argc = 1;
  1934. }
  1935. }
  1936. else {
  1937. maybe_cmd = check_rspamc_command(argv[1]);
  1938. if (maybe_cmd.has_value()) {
  1939. auto &cmd = maybe_cmd.value();
  1940. /* In case of command read arguments starting from 2 */
  1941. if (cmd.cmd == RSPAMC_COMMAND_ADD_SYMBOL || cmd.cmd == RSPAMC_COMMAND_ADD_ACTION) {
  1942. if (argc < 4 || argc > 5) {
  1943. rspamc_print(stderr, "invalid arguments\n");
  1944. exit(EXIT_FAILURE);
  1945. }
  1946. if (argc == 5) {
  1947. add_client_header(kwattrs, "metric", argv[2]);
  1948. add_client_header(kwattrs, "name", argv[3]);
  1949. add_client_header(kwattrs, "value", argv[4]);
  1950. }
  1951. else {
  1952. add_client_header(kwattrs, "name", argv[2]);
  1953. add_client_header(kwattrs, "value", argv[3]);
  1954. }
  1955. start_argc = argc;
  1956. }
  1957. else {
  1958. start_argc = 2;
  1959. }
  1960. }
  1961. else {
  1962. maybe_cmd = check_rspamc_command("symbols");
  1963. start_argc = 1;
  1964. }
  1965. }
  1966. if (!maybe_cmd.has_value()) {
  1967. rspamc_print(stderr, "invalid command\n");
  1968. exit(EXIT_FAILURE);
  1969. }
  1970. add_options(kwattrs);
  1971. auto cmd = maybe_cmd.value();
  1972. if (start_argc == argc) {
  1973. /* Do command without input or with stdin */
  1974. if (empty_input) {
  1975. rspamc_process_input(event_loop, cmd, nullptr, "empty", kwattrs);
  1976. }
  1977. else {
  1978. rspamc_process_input(event_loop, cmd, in, "stdin", kwattrs);
  1979. }
  1980. }
  1981. else {
  1982. auto cur_req = 0;
  1983. for (auto i = start_argc; i < argc; i++) {
  1984. if (cmd.cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
  1985. add_client_header(kwattrs, "Hash", argv[i]);
  1986. }
  1987. else {
  1988. struct stat st;
  1989. if (stat(argv[i], &st) == -1) {
  1990. rspamc_print(stderr, "cannot stat file {}\n", argv[i]);
  1991. exit(EXIT_FAILURE);
  1992. }
  1993. if (S_ISDIR(st.st_mode)) {
  1994. /* Directories are processed with a separate limit */
  1995. rspamc_process_dir(event_loop, cmd, argv[i], kwattrs);
  1996. cur_req = 0;
  1997. }
  1998. else {
  1999. in = fopen(argv[i], "r");
  2000. if (in == nullptr) {
  2001. rspamc_print(stderr, "cannot open file {}\n", argv[i]);
  2002. exit(EXIT_FAILURE);
  2003. }
  2004. rspamc_process_input(event_loop, cmd, in, argv[i], kwattrs);
  2005. cur_req++;
  2006. fclose(in);
  2007. }
  2008. if (cur_req >= max_requests) {
  2009. cur_req = 0;
  2010. /* Wait for completion */
  2011. ev_loop(event_loop, 0);
  2012. }
  2013. }
  2014. }
  2015. if (cmd.cmd == RSPAMC_COMMAND_FUZZY_DELHASH) {
  2016. rspamc_process_input(event_loop, cmd, nullptr, "hashes", kwattrs);
  2017. }
  2018. }
  2019. ev_loop(event_loop, 0);
  2020. g_queue_free_full(kwattrs, rspamc_kwattr_free);
  2021. /* Wait for children processes */
  2022. auto ret = 0;
  2023. for (auto cld: children) {
  2024. auto res = 0;
  2025. if (waitpid(cld, &res, 0) == -1) {
  2026. rspamc_print(stderr, "Cannot wait for {}: {}", cld,
  2027. strerror(errno));
  2028. ret = errno;
  2029. }
  2030. if (ret == 0) {
  2031. /* Check return code */
  2032. if (WIFSIGNALED(res)) {
  2033. ret = WTERMSIG(res);
  2034. }
  2035. else if (WIFEXITED(res)) {
  2036. ret = WEXITSTATUS(res);
  2037. }
  2038. }
  2039. }
  2040. for (auto i = 0; i < npatterns; i++) {
  2041. g_pattern_spec_free(exclude_compiled[i]);
  2042. }
  2043. g_free(exclude_compiled);
  2044. rspamd_deinit_libs(libs);
  2045. /* Mix retcode (return from Rspamd side) and ret (return from subprocess) */
  2046. return ret | retcode;
  2047. }