Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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