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 51KB

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