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

rspamc.c 52KB

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