You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rspamc.c 53KB

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