您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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