brotli.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. /* Copyright 2014 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* Command line interface for Brotli library. */
  6. /* Mute strerror/strcpy warnings. */
  7. #if !defined(_CRT_SECURE_NO_WARNINGS)
  8. #define _CRT_SECURE_NO_WARNINGS
  9. #endif
  10. #include <errno.h>
  11. #include <fcntl.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <time.h>
  18. #include <brotli/decode.h>
  19. #include <brotli/encode.h>
  20. #include <brotli/types.h>
  21. #include "../common/constants.h"
  22. #include "../common/version.h"
  23. #if defined(_WIN32)
  24. #include <io.h>
  25. #include <share.h>
  26. #include <sys/utime.h>
  27. #define MAKE_BINARY(FILENO) (_setmode((FILENO), _O_BINARY), (FILENO))
  28. #if !defined(__MINGW32__)
  29. #define STDIN_FILENO _fileno(stdin)
  30. #define STDOUT_FILENO _fileno(stdout)
  31. #define S_IRUSR S_IREAD
  32. #define S_IWUSR S_IWRITE
  33. #endif
  34. #define fdopen _fdopen
  35. #define isatty _isatty
  36. #define unlink _unlink
  37. #define utimbuf _utimbuf
  38. #define utime _utime
  39. #define fopen ms_fopen
  40. #define open ms_open
  41. #define chmod(F, P) (0)
  42. #define chown(F, O, G) (0)
  43. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  44. #define fseek _fseeki64
  45. #define ftell _ftelli64
  46. #endif
  47. static FILE* ms_fopen(const char* filename, const char* mode) {
  48. FILE* result = 0;
  49. fopen_s(&result, filename, mode);
  50. return result;
  51. }
  52. static int ms_open(const char* filename, int oflag, int pmode) {
  53. int result = -1;
  54. _sopen_s(&result, filename, oflag | O_BINARY, _SH_DENYNO, pmode);
  55. return result;
  56. }
  57. #else /* !defined(_WIN32) */
  58. #include <unistd.h>
  59. #include <utime.h>
  60. #define MAKE_BINARY(FILENO) (FILENO)
  61. #endif /* defined(_WIN32) */
  62. #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L)
  63. #define HAVE_UTIMENSAT 1
  64. #elif defined(_ATFILE_SOURCE)
  65. #define HAVE_UTIMENSAT 1
  66. #else
  67. #define HAVE_UTIMENSAT 0
  68. #endif
  69. #if HAVE_UTIMENSAT
  70. #if defined(__APPLE__)
  71. #define ATIME_NSEC(S) ((S)->st_atimespec.tv_nsec)
  72. #define MTIME_NSEC(S) ((S)->st_mtimespec.tv_nsec)
  73. #else /* defined(__APPLE__) */
  74. #define ATIME_NSEC(S) ((S)->st_atim.tv_nsec)
  75. #define MTIME_NSEC(S) ((S)->st_mtim.tv_nsec)
  76. #endif
  77. #endif /* HAVE_UTIMENSAT */
  78. typedef enum {
  79. COMMAND_COMPRESS,
  80. COMMAND_DECOMPRESS,
  81. COMMAND_HELP,
  82. COMMAND_INVALID,
  83. COMMAND_TEST_INTEGRITY,
  84. COMMAND_NOOP,
  85. COMMAND_VERSION
  86. } Command;
  87. typedef enum {
  88. COMMENT_INIT,
  89. COMMENT_READ,
  90. COMMENT_OK,
  91. COMMENT_BAD,
  92. } CommentState;
  93. #define DEFAULT_LGWIN 24
  94. #define DEFAULT_SUFFIX ".br"
  95. #define MAX_OPTIONS 24
  96. #define MAX_COMMENT_LEN 80
  97. typedef struct {
  98. /* Parameters */
  99. int quality;
  100. int lgwin;
  101. int verbosity;
  102. BROTLI_BOOL force_overwrite;
  103. BROTLI_BOOL junk_source;
  104. BROTLI_BOOL reject_uncompressible;
  105. BROTLI_BOOL copy_stat;
  106. BROTLI_BOOL write_to_stdout;
  107. BROTLI_BOOL test_integrity;
  108. BROTLI_BOOL decompress;
  109. BROTLI_BOOL large_window;
  110. BROTLI_BOOL allow_concatenated;
  111. const char* output_path;
  112. const char* dictionary_path;
  113. const char* suffix;
  114. uint8_t comment[MAX_COMMENT_LEN];
  115. size_t comment_len;
  116. size_t comment_pos;
  117. CommentState comment_state;
  118. int not_input_indices[MAX_OPTIONS];
  119. size_t longest_path_len;
  120. size_t input_count;
  121. /* Inner state */
  122. int argc;
  123. char** argv;
  124. uint8_t* dictionary;
  125. size_t dictionary_size;
  126. BrotliEncoderPreparedDictionary* prepared_dictionary;
  127. BrotliDecoderState* decoder;
  128. char* modified_path; /* Storage for path with appended / cut suffix */
  129. int iterator;
  130. int ignore;
  131. BROTLI_BOOL iterator_error;
  132. uint8_t* buffer;
  133. uint8_t* input;
  134. uint8_t* output;
  135. const char* current_input_path;
  136. const char* current_output_path;
  137. int64_t input_file_length; /* -1, if impossible to calculate */
  138. FILE* fin;
  139. FILE* fout;
  140. /* I/O buffers */
  141. size_t available_in;
  142. const uint8_t* next_in;
  143. size_t available_out;
  144. uint8_t* next_out;
  145. /* Reporting */
  146. /* size_t would be large enough,
  147. until 4GiB+ files are compressed / decompressed on 32-bit CPUs. */
  148. size_t total_in;
  149. size_t total_out;
  150. clock_t start_time;
  151. clock_t end_time;
  152. } Context;
  153. /* Parse base 64 encoded string to buffer. Not performance-centric.
  154. |out_len| as input is buffer size; |out_len| as output is decoded length.
  155. Returns BROTLI_FALSE if either input is not (relaxed) base 64 conformant,
  156. or output does not fit buffer. */
  157. static BROTLI_BOOL ParseBase64(const char* str, uint8_t* out, size_t* out_len) {
  158. size_t in_len = strlen(str);
  159. size_t max_out_len = *out_len;
  160. size_t i;
  161. size_t bit_count = 0;
  162. uint32_t bits = 0;
  163. size_t padding_count = 0;
  164. size_t octet_count = 0;
  165. for (i = 0; i < in_len; ++i) {
  166. char c = str[i];
  167. int sextet = 0;
  168. if (c == 9 || c == 10 || c == 13 || c == ' ') {
  169. continue;
  170. }
  171. if (c == '=') {
  172. padding_count++;
  173. continue;
  174. }
  175. if (padding_count) return BROTLI_FALSE;
  176. if (c == '+' || c == '-') {
  177. sextet = 62;
  178. } else if (c == '/' || c == '_') {
  179. sextet = 63;
  180. } else if (c >= 'A' && c <= 'Z') {
  181. sextet = c - 'A';
  182. } else if (c >= 'a' && c <= 'z') {
  183. sextet = c - 'a' + 26;
  184. } else if (c >= '0' && c <= '9') {
  185. sextet = c - '0' + 52;
  186. } else {
  187. return BROTLI_FALSE;
  188. }
  189. bits = (bits << 6) | (uint32_t)sextet;
  190. bit_count += 6;
  191. if (bit_count >= 8) {
  192. if (octet_count == max_out_len) return BROTLI_FALSE;
  193. bit_count -= 8;
  194. out[octet_count++] = (bits >> bit_count) & 0xFF;
  195. }
  196. }
  197. if (padding_count > 2) return BROTLI_FALSE;
  198. *out_len = octet_count;
  199. return BROTLI_TRUE;
  200. }
  201. /* Parse up to 5 decimal digits. */
  202. static BROTLI_BOOL ParseInt(const char* s, int low, int high, int* result) {
  203. int value = 0;
  204. int i;
  205. for (i = 0; i < 5; ++i) {
  206. char c = s[i];
  207. if (c == 0) break;
  208. if (s[i] < '0' || s[i] > '9') return BROTLI_FALSE;
  209. value = (10 * value) + (c - '0');
  210. }
  211. if (i == 0) return BROTLI_FALSE;
  212. if (i > 1 && s[0] == '0') return BROTLI_FALSE;
  213. if (s[i] != 0) return BROTLI_FALSE;
  214. if (value < low || value > high) return BROTLI_FALSE;
  215. *result = value;
  216. return BROTLI_TRUE;
  217. }
  218. /* Returns "base file name" or its tail, if it contains '/' or '\'. */
  219. static const char* FileName(const char* path) {
  220. const char* separator_position = strrchr(path, '/');
  221. if (separator_position) path = separator_position + 1;
  222. separator_position = strrchr(path, '\\');
  223. if (separator_position) path = separator_position + 1;
  224. return path;
  225. }
  226. /* Detect if the program name is a special alias that infers a command type. */
  227. static BROTLI_BOOL CheckAlias(const char* name, const char* alias) {
  228. /* TODO: cast name to lower case? */
  229. size_t alias_len = strlen(alias);
  230. name = FileName(name);
  231. /* Partial comparison. On Windows there could be ".exe" suffix. */
  232. if (strncmp(name, alias, alias_len) == 0) {
  233. char terminator = name[alias_len];
  234. if (terminator == 0 || terminator == '.') return BROTLI_TRUE;
  235. }
  236. return BROTLI_FALSE;
  237. }
  238. static Command ParseParams(Context* params) {
  239. int argc = params->argc;
  240. char** argv = params->argv;
  241. int i;
  242. int next_option_index = 0;
  243. size_t input_count = 0;
  244. size_t longest_path_len = 1;
  245. BROTLI_BOOL command_set = BROTLI_FALSE;
  246. BROTLI_BOOL quality_set = BROTLI_FALSE;
  247. BROTLI_BOOL output_set = BROTLI_FALSE;
  248. BROTLI_BOOL keep_set = BROTLI_FALSE;
  249. BROTLI_BOOL squash_set = BROTLI_FALSE;
  250. BROTLI_BOOL lgwin_set = BROTLI_FALSE;
  251. BROTLI_BOOL suffix_set = BROTLI_FALSE;
  252. BROTLI_BOOL after_dash_dash = BROTLI_FALSE;
  253. BROTLI_BOOL comment_set = BROTLI_FALSE;
  254. BROTLI_BOOL concatenated_set = BROTLI_FALSE;
  255. Command command = COMMAND_COMPRESS;
  256. if (CheckAlias(argv[0], "brcat")) {
  257. command_set = BROTLI_TRUE;
  258. command = COMMAND_DECOMPRESS;
  259. concatenated_set = BROTLI_TRUE;
  260. params->allow_concatenated = BROTLI_TRUE;
  261. output_set = BROTLI_TRUE;
  262. params->write_to_stdout = BROTLI_TRUE;
  263. } else if (CheckAlias(argv[0], "unbrotli")) {
  264. command_set = BROTLI_TRUE;
  265. command = COMMAND_DECOMPRESS;
  266. }
  267. for (i = 1; i < argc; ++i) {
  268. const char* arg = argv[i];
  269. /* C99 5.1.2.2.1: "members argv[0] through argv[argc-1] inclusive shall
  270. contain pointers to strings"; NULL and 0-length are not forbidden. */
  271. size_t arg_len = arg ? strlen(arg) : 0;
  272. if (arg_len == 0) {
  273. params->not_input_indices[next_option_index++] = i;
  274. continue;
  275. }
  276. /* Too many options. The expected longest option list is:
  277. "-q 0 -w 10 -o f -D d -S b -d -f -k -n -v -K --", i.e. 17 items in total.
  278. This check is an additional guard that is never triggered, but provides
  279. a guard for future changes. */
  280. if (next_option_index > (MAX_OPTIONS - 2)) {
  281. fprintf(stderr, "too many options passed\n");
  282. return COMMAND_INVALID;
  283. }
  284. /* Input file entry. */
  285. if (after_dash_dash || arg[0] != '-' || arg_len == 1) {
  286. input_count++;
  287. if (longest_path_len < arg_len) longest_path_len = arg_len;
  288. continue;
  289. }
  290. /* Not a file entry. */
  291. params->not_input_indices[next_option_index++] = i;
  292. /* '--' entry stop parsing arguments. */
  293. if (arg_len == 2 && arg[1] == '-') {
  294. after_dash_dash = BROTLI_TRUE;
  295. continue;
  296. }
  297. /* Simple / coalesced options. */
  298. if (arg[1] != '-') {
  299. size_t j;
  300. for (j = 1; j < arg_len; ++j) {
  301. char c = arg[j];
  302. if (c >= '0' && c <= '9') {
  303. if (quality_set) {
  304. fprintf(stderr, "quality already set\n");
  305. return COMMAND_INVALID;
  306. }
  307. quality_set = BROTLI_TRUE;
  308. params->quality = c - '0';
  309. continue;
  310. } else if (c == 'c') {
  311. if (output_set) {
  312. fprintf(stderr, "write to standard output already set\n");
  313. return COMMAND_INVALID;
  314. }
  315. output_set = BROTLI_TRUE;
  316. params->write_to_stdout = BROTLI_TRUE;
  317. continue;
  318. } else if (c == 'd') {
  319. if (command_set) {
  320. fprintf(stderr, "command already set when parsing -d\n");
  321. return COMMAND_INVALID;
  322. }
  323. command_set = BROTLI_TRUE;
  324. command = COMMAND_DECOMPRESS;
  325. continue;
  326. } else if (c == 'f') {
  327. if (params->force_overwrite) {
  328. fprintf(stderr, "force output overwrite already set\n");
  329. return COMMAND_INVALID;
  330. }
  331. params->force_overwrite = BROTLI_TRUE;
  332. continue;
  333. } else if (c == 'h') {
  334. /* Don't parse further. */
  335. return COMMAND_HELP;
  336. } else if (c == 'j' || c == 'k') {
  337. if (keep_set) {
  338. fprintf(stderr, "argument --rm / -j or --keep / -k already set\n");
  339. return COMMAND_INVALID;
  340. }
  341. keep_set = BROTLI_TRUE;
  342. params->junk_source = TO_BROTLI_BOOL(c == 'j');
  343. continue;
  344. } else if (c == 'n') {
  345. if (!params->copy_stat) {
  346. fprintf(stderr, "argument --no-copy-stat / -n already set\n");
  347. return COMMAND_INVALID;
  348. }
  349. params->copy_stat = BROTLI_FALSE;
  350. continue;
  351. } else if (c == 's') {
  352. if (squash_set) {
  353. fprintf(stderr, "argument --squash / -s already set\n");
  354. return COMMAND_INVALID;
  355. }
  356. squash_set = BROTLI_TRUE;
  357. params->reject_uncompressible = BROTLI_TRUE;
  358. continue;
  359. } else if (c == 't') {
  360. if (command_set) {
  361. fprintf(stderr, "command already set when parsing -t\n");
  362. return COMMAND_INVALID;
  363. }
  364. command_set = BROTLI_TRUE;
  365. command = COMMAND_TEST_INTEGRITY;
  366. continue;
  367. } else if (c == 'v') {
  368. if (params->verbosity > 0) {
  369. fprintf(stderr, "argument --verbose / -v already set\n");
  370. return COMMAND_INVALID;
  371. }
  372. params->verbosity = 1;
  373. continue;
  374. } else if (c == 'K') {
  375. if (concatenated_set) {
  376. fprintf(stderr, "argument -K / --concatenated already set\n");
  377. return COMMAND_INVALID;
  378. }
  379. concatenated_set = BROTLI_TRUE;
  380. params->allow_concatenated = BROTLI_TRUE;
  381. continue;
  382. } else if (c == 'V') {
  383. /* Don't parse further. */
  384. return COMMAND_VERSION;
  385. } else if (c == 'Z') {
  386. if (quality_set) {
  387. fprintf(stderr, "quality already set\n");
  388. return COMMAND_INVALID;
  389. }
  390. quality_set = BROTLI_TRUE;
  391. params->quality = 11;
  392. continue;
  393. }
  394. /* o/q/w/C/D/S with parameter is expected */
  395. if (c != 'o' && c != 'q' && c != 'w' && c != 'C' && c != 'D' &&
  396. c != 'S') {
  397. fprintf(stderr, "invalid argument -%c\n", c);
  398. return COMMAND_INVALID;
  399. }
  400. if (j + 1 != arg_len) {
  401. fprintf(stderr, "expected parameter for argument -%c\n", c);
  402. return COMMAND_INVALID;
  403. }
  404. i++;
  405. if (i == argc || !argv[i] || argv[i][0] == 0) {
  406. fprintf(stderr, "expected parameter for argument -%c\n", c);
  407. return COMMAND_INVALID;
  408. }
  409. params->not_input_indices[next_option_index++] = i;
  410. if (c == 'o') {
  411. if (output_set) {
  412. fprintf(stderr, "write to standard output already set (-o)\n");
  413. return COMMAND_INVALID;
  414. }
  415. params->output_path = argv[i];
  416. } else if (c == 'q') {
  417. if (quality_set) {
  418. fprintf(stderr, "quality already set\n");
  419. return COMMAND_INVALID;
  420. }
  421. quality_set = ParseInt(argv[i], BROTLI_MIN_QUALITY,
  422. BROTLI_MAX_QUALITY, &params->quality);
  423. if (!quality_set) {
  424. fprintf(stderr, "error parsing quality value [%s]\n", argv[i]);
  425. return COMMAND_INVALID;
  426. }
  427. } else if (c == 'w') {
  428. if (lgwin_set) {
  429. fprintf(stderr, "lgwin parameter already set\n");
  430. return COMMAND_INVALID;
  431. }
  432. lgwin_set = ParseInt(argv[i], 0,
  433. BROTLI_MAX_WINDOW_BITS, &params->lgwin);
  434. if (!lgwin_set) {
  435. fprintf(stderr, "error parsing lgwin value [%s]\n", argv[i]);
  436. return COMMAND_INVALID;
  437. }
  438. if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) {
  439. fprintf(stderr,
  440. "lgwin parameter (%d) smaller than the minimum (%d)\n",
  441. params->lgwin, BROTLI_MIN_WINDOW_BITS);
  442. return COMMAND_INVALID;
  443. }
  444. } else if (c == 'C') {
  445. if (comment_set) {
  446. fprintf(stderr, "comment already set\n");
  447. return COMMAND_INVALID;
  448. }
  449. params->comment_len = MAX_COMMENT_LEN;
  450. if (!ParseBase64(argv[i], params->comment, &params->comment_len)) {
  451. fprintf(stderr, "invalid base64-encoded comment\n");
  452. return COMMAND_INVALID;
  453. }
  454. comment_set = BROTLI_TRUE;
  455. } else if (c == 'D') {
  456. if (params->dictionary_path) {
  457. fprintf(stderr, "dictionary path already set\n");
  458. return COMMAND_INVALID;
  459. }
  460. params->dictionary_path = argv[i];
  461. } else if (c == 'S') {
  462. if (suffix_set) {
  463. fprintf(stderr, "suffix already set\n");
  464. return COMMAND_INVALID;
  465. }
  466. suffix_set = BROTLI_TRUE;
  467. params->suffix = argv[i];
  468. }
  469. }
  470. } else { /* Double-dash. */
  471. arg = &arg[2];
  472. if (strcmp("best", arg) == 0) {
  473. if (quality_set) {
  474. fprintf(stderr, "quality already set\n");
  475. return COMMAND_INVALID;
  476. }
  477. quality_set = BROTLI_TRUE;
  478. params->quality = 11;
  479. } else if (strcmp("concatenated", arg) == 0) {
  480. if (concatenated_set) {
  481. fprintf(stderr, "argument -K / --concatenated already set\n");
  482. return COMMAND_INVALID;
  483. }
  484. concatenated_set = BROTLI_TRUE;
  485. params->allow_concatenated = BROTLI_TRUE;
  486. continue;
  487. } else if (strcmp("decompress", arg) == 0) {
  488. if (command_set) {
  489. fprintf(stderr, "command already set when parsing --decompress\n");
  490. return COMMAND_INVALID;
  491. }
  492. command_set = BROTLI_TRUE;
  493. command = COMMAND_DECOMPRESS;
  494. } else if (strcmp("force", arg) == 0) {
  495. if (params->force_overwrite) {
  496. fprintf(stderr, "force output overwrite already set\n");
  497. return COMMAND_INVALID;
  498. }
  499. params->force_overwrite = BROTLI_TRUE;
  500. } else if (strcmp("help", arg) == 0) {
  501. /* Don't parse further. */
  502. return COMMAND_HELP;
  503. } else if (strcmp("keep", arg) == 0) {
  504. if (keep_set) {
  505. fprintf(stderr, "argument --rm / -j or --keep / -k already set\n");
  506. return COMMAND_INVALID;
  507. }
  508. keep_set = BROTLI_TRUE;
  509. params->junk_source = BROTLI_FALSE;
  510. } else if (strcmp("no-copy-stat", arg) == 0) {
  511. if (!params->copy_stat) {
  512. fprintf(stderr, "argument --no-copy-stat / -n already set\n");
  513. return COMMAND_INVALID;
  514. }
  515. params->copy_stat = BROTLI_FALSE;
  516. } else if (strcmp("rm", arg) == 0) {
  517. if (keep_set) {
  518. fprintf(stderr, "argument --rm / -j or --keep / -k already set\n");
  519. return COMMAND_INVALID;
  520. }
  521. keep_set = BROTLI_TRUE;
  522. params->junk_source = BROTLI_TRUE;
  523. } else if (strcmp("squash", arg) == 0) {
  524. if (squash_set) {
  525. fprintf(stderr, "argument --squash / -s already set\n");
  526. return COMMAND_INVALID;
  527. }
  528. squash_set = BROTLI_TRUE;
  529. params->reject_uncompressible = BROTLI_TRUE;
  530. continue;
  531. } else if (strcmp("stdout", arg) == 0) {
  532. if (output_set) {
  533. fprintf(stderr, "write to standard output already set\n");
  534. return COMMAND_INVALID;
  535. }
  536. output_set = BROTLI_TRUE;
  537. params->write_to_stdout = BROTLI_TRUE;
  538. } else if (strcmp("test", arg) == 0) {
  539. if (command_set) {
  540. fprintf(stderr, "command already set when parsing --test\n");
  541. return COMMAND_INVALID;
  542. }
  543. command_set = BROTLI_TRUE;
  544. command = COMMAND_TEST_INTEGRITY;
  545. } else if (strcmp("verbose", arg) == 0) {
  546. if (params->verbosity > 0) {
  547. fprintf(stderr, "argument --verbose / -v already set\n");
  548. return COMMAND_INVALID;
  549. }
  550. params->verbosity = 1;
  551. } else if (strcmp("version", arg) == 0) {
  552. /* Don't parse further. */
  553. return COMMAND_VERSION;
  554. } else {
  555. /* key=value */
  556. const char* value = strchr(arg, '=');
  557. size_t key_len;
  558. if (!value || value[1] == 0) {
  559. fprintf(stderr, "must pass the parameter as --%s=value\n", arg);
  560. return COMMAND_INVALID;
  561. }
  562. key_len = (size_t)(value - arg);
  563. value++;
  564. if (strncmp("comment", arg, key_len) == 0) {
  565. if (comment_set) {
  566. fprintf(stderr, "comment already set\n");
  567. return COMMAND_INVALID;
  568. }
  569. params->comment_len = MAX_COMMENT_LEN;
  570. if (!ParseBase64(value, params->comment, &params->comment_len)) {
  571. fprintf(stderr, "invalid base64-encoded comment\n");
  572. return COMMAND_INVALID;
  573. }
  574. comment_set = BROTLI_TRUE;
  575. } else if (strncmp("dictionary", arg, key_len) == 0) {
  576. if (params->dictionary_path) {
  577. fprintf(stderr, "dictionary path already set\n");
  578. return COMMAND_INVALID;
  579. }
  580. params->dictionary_path = value;
  581. } else if (strncmp("lgwin", arg, key_len) == 0) {
  582. if (lgwin_set) {
  583. fprintf(stderr, "lgwin parameter already set\n");
  584. return COMMAND_INVALID;
  585. }
  586. lgwin_set = ParseInt(value, 0,
  587. BROTLI_MAX_WINDOW_BITS, &params->lgwin);
  588. if (!lgwin_set) {
  589. fprintf(stderr, "error parsing lgwin value [%s]\n", value);
  590. return COMMAND_INVALID;
  591. }
  592. if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) {
  593. fprintf(stderr,
  594. "lgwin parameter (%d) smaller than the minimum (%d)\n",
  595. params->lgwin, BROTLI_MIN_WINDOW_BITS);
  596. return COMMAND_INVALID;
  597. }
  598. } else if (strncmp("large_window", arg, key_len) == 0) {
  599. /* This option is intentionally not mentioned in help. */
  600. if (lgwin_set) {
  601. fprintf(stderr, "lgwin parameter already set\n");
  602. return COMMAND_INVALID;
  603. }
  604. lgwin_set = ParseInt(value, 0,
  605. BROTLI_LARGE_MAX_WINDOW_BITS, &params->lgwin);
  606. if (!lgwin_set) {
  607. fprintf(stderr, "error parsing lgwin value [%s]\n", value);
  608. return COMMAND_INVALID;
  609. }
  610. if (params->lgwin != 0 && params->lgwin < BROTLI_MIN_WINDOW_BITS) {
  611. fprintf(stderr,
  612. "lgwin parameter (%d) smaller than the minimum (%d)\n",
  613. params->lgwin, BROTLI_MIN_WINDOW_BITS);
  614. return COMMAND_INVALID;
  615. }
  616. } else if (strncmp("output", arg, key_len) == 0) {
  617. if (output_set) {
  618. fprintf(stderr,
  619. "write to standard output already set (--output)\n");
  620. return COMMAND_INVALID;
  621. }
  622. params->output_path = value;
  623. } else if (strncmp("quality", arg, key_len) == 0) {
  624. if (quality_set) {
  625. fprintf(stderr, "quality already set\n");
  626. return COMMAND_INVALID;
  627. }
  628. quality_set = ParseInt(value, BROTLI_MIN_QUALITY,
  629. BROTLI_MAX_QUALITY, &params->quality);
  630. if (!quality_set) {
  631. fprintf(stderr, "error parsing quality value [%s]\n", value);
  632. return COMMAND_INVALID;
  633. }
  634. } else if (strncmp("suffix", arg, key_len) == 0) {
  635. if (suffix_set) {
  636. fprintf(stderr, "suffix already set\n");
  637. return COMMAND_INVALID;
  638. }
  639. suffix_set = BROTLI_TRUE;
  640. params->suffix = value;
  641. } else {
  642. fprintf(stderr, "invalid parameter: [%s]\n", arg);
  643. return COMMAND_INVALID;
  644. }
  645. }
  646. }
  647. }
  648. params->input_count = input_count;
  649. params->longest_path_len = longest_path_len;
  650. params->decompress = (command == COMMAND_DECOMPRESS);
  651. params->test_integrity = (command == COMMAND_TEST_INTEGRITY);
  652. if (input_count > 1 && output_set) return COMMAND_INVALID;
  653. if (params->test_integrity) {
  654. if (params->output_path) return COMMAND_INVALID;
  655. if (params->write_to_stdout) return COMMAND_INVALID;
  656. }
  657. if (params->reject_uncompressible && params->write_to_stdout) {
  658. return COMMAND_INVALID;
  659. }
  660. if (strchr(params->suffix, '/') || strchr(params->suffix, '\\')) {
  661. return COMMAND_INVALID;
  662. }
  663. if (!params->decompress && params->allow_concatenated) {
  664. return COMMAND_INVALID;
  665. }
  666. if (params->allow_concatenated && params->comment_len) {
  667. return COMMAND_INVALID;
  668. }
  669. return command;
  670. }
  671. static void PrintVersion(void) {
  672. int major = BROTLI_VERSION_MAJOR;
  673. int minor = BROTLI_VERSION_MINOR;
  674. int patch = BROTLI_VERSION_PATCH;
  675. fprintf(stdout, "brotli %d.%d.%d\n", major, minor, patch);
  676. }
  677. static void PrintHelp(const char* name, BROTLI_BOOL error) {
  678. FILE* media = error ? stderr : stdout;
  679. /* String is cut to pieces with length less than 509, to conform C90 spec. */
  680. fprintf(media,
  681. "Usage: %s [OPTION]... [FILE]...\n",
  682. name);
  683. fprintf(media,
  684. "Options:\n"
  685. " -# compression level (0-9)\n"
  686. " -c, --stdout write on standard output\n"
  687. " -d, --decompress decompress\n"
  688. " -f, --force force output file overwrite\n"
  689. " -h, --help display this help and exit\n");
  690. fprintf(media,
  691. " -j, --rm remove source file(s)\n"
  692. " -s, --squash remove destination file if larger than source\n"
  693. " -k, --keep keep source file(s) (default)\n"
  694. " -n, --no-copy-stat do not copy source file(s) attributes\n"
  695. " -o FILE, --output=FILE output file (only if 1 input file)\n");
  696. fprintf(media,
  697. " -q NUM, --quality=NUM compression level (%d-%d)\n",
  698. BROTLI_MIN_QUALITY, BROTLI_MAX_QUALITY);
  699. fprintf(media,
  700. " -t, --test test compressed file integrity\n"
  701. " -v, --verbose verbose mode\n");
  702. fprintf(media,
  703. " -w NUM, --lgwin=NUM set LZ77 window size (0, %d-%d)\n"
  704. " window size = 2**NUM - 16\n"
  705. " 0 lets compressor choose the optimal value\n",
  706. BROTLI_MIN_WINDOW_BITS, BROTLI_MAX_WINDOW_BITS);
  707. fprintf(media,
  708. " --large_window=NUM use incompatible large-window brotli\n"
  709. " bitstream with window size (0, %d-%d)\n"
  710. " WARNING: this format is not compatible\n"
  711. " with brotli RFC 7932 and may not be\n"
  712. " decodable with regular brotli decoders\n",
  713. BROTLI_MIN_WINDOW_BITS, BROTLI_LARGE_MAX_WINDOW_BITS);
  714. fprintf(media,
  715. " -C B64, --comment=B64 set comment; argument is base64-decoded first;\n"
  716. " (maximal decoded length: %d)\n"
  717. " when decoding: check stream comment;\n"
  718. " when encoding: embed comment (fingerprint)\n",
  719. MAX_COMMENT_LEN);
  720. fprintf(media,
  721. " -D FILE, --dictionary=FILE use FILE as raw (LZ77) dictionary\n"
  722. " -K, --concatenated allows concatenated brotli streams as input\n");
  723. fprintf(media,
  724. " -S SUF, --suffix=SUF output file suffix (default:'%s')\n",
  725. DEFAULT_SUFFIX);
  726. fprintf(media,
  727. " -V, --version display version and exit\n"
  728. " -Z, --best use best compression level (11) (default)\n"
  729. "Simple options could be coalesced, i.e. '-9kf' is equivalent to '-9 -k -f'.\n"
  730. "With no FILE, or when FILE is -, read standard input.\n"
  731. "All arguments after '--' are treated as files.\n");
  732. }
  733. static const char* PrintablePath(const char* path) {
  734. return path ? path : "con";
  735. }
  736. static BROTLI_BOOL OpenInputFile(const char* input_path, FILE** f) {
  737. *f = NULL;
  738. if (!input_path) {
  739. *f = fdopen(MAKE_BINARY(STDIN_FILENO), "rb");
  740. return BROTLI_TRUE;
  741. }
  742. *f = fopen(input_path, "rb");
  743. if (!*f) {
  744. fprintf(stderr, "failed to open input file [%s]: %s\n",
  745. PrintablePath(input_path), strerror(errno));
  746. return BROTLI_FALSE;
  747. }
  748. return BROTLI_TRUE;
  749. }
  750. static BROTLI_BOOL OpenOutputFile(const char* output_path, FILE** f,
  751. BROTLI_BOOL force) {
  752. int fd;
  753. *f = NULL;
  754. if (!output_path) {
  755. *f = fdopen(MAKE_BINARY(STDOUT_FILENO), "wb");
  756. return BROTLI_TRUE;
  757. }
  758. fd = open(output_path, O_CREAT | (force ? 0 : O_EXCL) | O_WRONLY | O_TRUNC,
  759. S_IRUSR | S_IWUSR);
  760. if (fd < 0) {
  761. fprintf(stderr, "failed to open output file [%s]: %s\n",
  762. PrintablePath(output_path), strerror(errno));
  763. return BROTLI_FALSE;
  764. }
  765. *f = fdopen(fd, "wb");
  766. if (!*f) {
  767. fprintf(stderr, "failed to open output file [%s]: %s\n",
  768. PrintablePath(output_path), strerror(errno));
  769. return BROTLI_FALSE;
  770. }
  771. return BROTLI_TRUE;
  772. }
  773. static int64_t FileSize(const char* path) {
  774. FILE* f = fopen(path, "rb");
  775. int64_t retval;
  776. if (f == NULL) {
  777. return -1;
  778. }
  779. if (fseek(f, 0L, SEEK_END) != 0) {
  780. fclose(f);
  781. return -1;
  782. }
  783. retval = ftell(f);
  784. if (fclose(f) != 0) {
  785. return -1;
  786. }
  787. return retval;
  788. }
  789. static int CopyTimeStat(const struct stat* statbuf, const char* output_path) {
  790. #if HAVE_UTIMENSAT
  791. struct timespec times[2];
  792. times[0].tv_sec = statbuf->st_atime;
  793. times[0].tv_nsec = ATIME_NSEC(statbuf);
  794. times[1].tv_sec = statbuf->st_mtime;
  795. times[1].tv_nsec = MTIME_NSEC(statbuf);
  796. return utimensat(AT_FDCWD, output_path, times, AT_SYMLINK_NOFOLLOW);
  797. #else
  798. struct utimbuf times;
  799. times.actime = statbuf->st_atime;
  800. times.modtime = statbuf->st_mtime;
  801. return utime(output_path, &times);
  802. #endif
  803. }
  804. /* Copy file times and permissions.
  805. TODO(eustas): this is a "best effort" implementation; honest cross-platform
  806. fully featured implementation is way too hacky; add more hacks by request. */
  807. static void CopyStat(const char* input_path, const char* output_path) {
  808. struct stat statbuf;
  809. int res;
  810. if (input_path == 0 || output_path == 0) {
  811. return;
  812. }
  813. if (stat(input_path, &statbuf) != 0) {
  814. return;
  815. }
  816. res = CopyTimeStat(&statbuf, output_path);
  817. res = chmod(output_path, statbuf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO));
  818. if (res != 0) {
  819. fprintf(stderr, "setting access bits failed for [%s]: %s\n",
  820. PrintablePath(output_path), strerror(errno));
  821. }
  822. res = chown(output_path, (uid_t)-1, statbuf.st_gid);
  823. if (res != 0) {
  824. fprintf(stderr, "setting group failed for [%s]: %s\n",
  825. PrintablePath(output_path), strerror(errno));
  826. }
  827. res = chown(output_path, statbuf.st_uid, (gid_t)-1);
  828. if (res != 0) {
  829. fprintf(stderr, "setting user failed for [%s]: %s\n",
  830. PrintablePath(output_path), strerror(errno));
  831. }
  832. }
  833. /* Result ownership is passed to caller.
  834. |*dictionary_size| is set to resulting buffer size. */
  835. static BROTLI_BOOL ReadDictionary(Context* context, Command command) {
  836. static const int kMaxDictionarySize =
  837. BROTLI_MAX_DISTANCE - BROTLI_MAX_BACKWARD_LIMIT(24);
  838. FILE* f;
  839. int64_t file_size_64;
  840. uint8_t* buffer;
  841. size_t bytes_read;
  842. if (context->dictionary_path == NULL) return BROTLI_TRUE;
  843. f = fopen(context->dictionary_path, "rb");
  844. if (f == NULL) {
  845. fprintf(stderr, "failed to open dictionary file [%s]: %s\n",
  846. PrintablePath(context->dictionary_path), strerror(errno));
  847. return BROTLI_FALSE;
  848. }
  849. file_size_64 = FileSize(context->dictionary_path);
  850. if (file_size_64 == -1) {
  851. fprintf(stderr, "could not get size of dictionary file [%s]",
  852. PrintablePath(context->dictionary_path));
  853. fclose(f);
  854. return BROTLI_FALSE;
  855. }
  856. if (file_size_64 > kMaxDictionarySize) {
  857. fprintf(stderr, "dictionary [%s] is larger than maximum allowed: %d\n",
  858. PrintablePath(context->dictionary_path), kMaxDictionarySize);
  859. fclose(f);
  860. return BROTLI_FALSE;
  861. }
  862. context->dictionary_size = (size_t)file_size_64;
  863. buffer = (uint8_t*)malloc(context->dictionary_size);
  864. if (!buffer) {
  865. fprintf(stderr, "could not read dictionary: out of memory\n");
  866. fclose(f);
  867. return BROTLI_FALSE;
  868. }
  869. bytes_read = fread(buffer, sizeof(uint8_t), context->dictionary_size, f);
  870. if (bytes_read != context->dictionary_size) {
  871. free(buffer);
  872. fprintf(stderr, "failed to read dictionary [%s]: %s\n",
  873. PrintablePath(context->dictionary_path), strerror(errno));
  874. fclose(f);
  875. return BROTLI_FALSE;
  876. }
  877. fclose(f);
  878. context->dictionary = buffer;
  879. if (command == COMMAND_COMPRESS) {
  880. context->prepared_dictionary = BrotliEncoderPrepareDictionary(
  881. BROTLI_SHARED_DICTIONARY_RAW, context->dictionary_size,
  882. context->dictionary, BROTLI_MAX_QUALITY, NULL, NULL, NULL);
  883. if (context->prepared_dictionary == NULL) {
  884. fprintf(stderr, "failed to prepare dictionary [%s]\n",
  885. PrintablePath(context->dictionary_path));
  886. return BROTLI_FALSE;
  887. }
  888. }
  889. return BROTLI_TRUE;
  890. }
  891. static BROTLI_BOOL NextFile(Context* context) {
  892. const char* arg;
  893. size_t arg_len;
  894. /* Iterator points to last used arg; increment to search for the next one. */
  895. context->iterator++;
  896. context->input_file_length = -1;
  897. /* No input path; read from console. */
  898. if (context->input_count == 0) {
  899. if (context->iterator > 1) return BROTLI_FALSE;
  900. context->current_input_path = NULL;
  901. /* Either write to the specified path, or to console. */
  902. context->current_output_path = context->output_path;
  903. return BROTLI_TRUE;
  904. }
  905. /* Skip option arguments. */
  906. while (context->iterator == context->not_input_indices[context->ignore]) {
  907. context->iterator++;
  908. context->ignore++;
  909. }
  910. /* All args are scanned already. */
  911. if (context->iterator >= context->argc) return BROTLI_FALSE;
  912. /* Iterator now points to the input file name. */
  913. arg = context->argv[context->iterator];
  914. arg_len = strlen(arg);
  915. /* Read from console. */
  916. if (arg_len == 1 && arg[0] == '-') {
  917. context->current_input_path = NULL;
  918. context->current_output_path = context->output_path;
  919. return BROTLI_TRUE;
  920. }
  921. context->current_input_path = arg;
  922. context->input_file_length = FileSize(arg);
  923. context->current_output_path = context->output_path;
  924. if (context->output_path) return BROTLI_TRUE;
  925. if (context->write_to_stdout) return BROTLI_TRUE;
  926. strcpy(context->modified_path, arg);
  927. context->current_output_path = context->modified_path;
  928. /* If output is not specified, input path suffix should match. */
  929. if (context->decompress) {
  930. size_t suffix_len = strlen(context->suffix);
  931. char* name = (char*)FileName(context->modified_path);
  932. char* name_suffix;
  933. size_t name_len = strlen(name);
  934. if (name_len < suffix_len + 1) {
  935. fprintf(stderr, "empty output file name for [%s] input file\n",
  936. PrintablePath(arg));
  937. context->iterator_error = BROTLI_TRUE;
  938. return BROTLI_FALSE;
  939. }
  940. name_suffix = name + name_len - suffix_len;
  941. if (strcmp(context->suffix, name_suffix) != 0) {
  942. fprintf(stderr, "input file [%s] suffix mismatch\n",
  943. PrintablePath(arg));
  944. context->iterator_error = BROTLI_TRUE;
  945. return BROTLI_FALSE;
  946. }
  947. name_suffix[0] = 0;
  948. return BROTLI_TRUE;
  949. } else {
  950. strcpy(context->modified_path + arg_len, context->suffix);
  951. return BROTLI_TRUE;
  952. }
  953. }
  954. static BROTLI_BOOL OpenFiles(Context* context) {
  955. BROTLI_BOOL is_ok = OpenInputFile(context->current_input_path, &context->fin);
  956. if (!context->test_integrity && is_ok) {
  957. is_ok = OpenOutputFile(
  958. context->current_output_path, &context->fout, context->force_overwrite);
  959. }
  960. return is_ok;
  961. }
  962. static BROTLI_BOOL CloseFiles(Context* context, BROTLI_BOOL rm_input,
  963. BROTLI_BOOL rm_output) {
  964. BROTLI_BOOL is_ok = BROTLI_TRUE;
  965. if (!context->test_integrity && context->fout) {
  966. if (fclose(context->fout) != 0) {
  967. if (is_ok) {
  968. fprintf(stderr, "fclose failed [%s]: %s\n",
  969. PrintablePath(context->current_output_path), strerror(errno));
  970. }
  971. is_ok = BROTLI_FALSE;
  972. }
  973. if (rm_output && context->current_output_path) {
  974. unlink(context->current_output_path);
  975. }
  976. /* TOCTOU violation, but otherwise it is impossible to set file times. */
  977. if (!rm_output && is_ok && context->copy_stat) {
  978. CopyStat(context->current_input_path, context->current_output_path);
  979. }
  980. }
  981. if (context->fin) {
  982. if (fclose(context->fin) != 0) {
  983. if (is_ok) {
  984. fprintf(stderr, "fclose failed [%s]: %s\n",
  985. PrintablePath(context->current_input_path), strerror(errno));
  986. }
  987. is_ok = BROTLI_FALSE;
  988. }
  989. }
  990. if (rm_input && context->current_input_path) {
  991. unlink(context->current_input_path);
  992. }
  993. context->fin = NULL;
  994. context->fout = NULL;
  995. return is_ok;
  996. }
  997. static const size_t kFileBufferSize = 1 << 19;
  998. static void InitializeBuffers(Context* context) {
  999. context->available_in = 0;
  1000. context->next_in = NULL;
  1001. context->available_out = kFileBufferSize;
  1002. context->next_out = context->output;
  1003. context->total_in = 0;
  1004. context->total_out = 0;
  1005. if (context->verbosity > 0) {
  1006. context->start_time = clock();
  1007. }
  1008. }
  1009. /* This method might give the false-negative result.
  1010. However, after an empty / incomplete read it should tell the truth. */
  1011. static BROTLI_BOOL HasMoreInput(Context* context) {
  1012. return feof(context->fin) ? BROTLI_FALSE : BROTLI_TRUE;
  1013. }
  1014. static BROTLI_BOOL ProvideInput(Context* context) {
  1015. context->available_in =
  1016. fread(context->input, 1, kFileBufferSize, context->fin);
  1017. context->total_in += context->available_in;
  1018. context->next_in = context->input;
  1019. if (ferror(context->fin)) {
  1020. fprintf(stderr, "failed to read input [%s]: %s\n",
  1021. PrintablePath(context->current_input_path), strerror(errno));
  1022. return BROTLI_FALSE;
  1023. }
  1024. return BROTLI_TRUE;
  1025. }
  1026. /* Internal: should be used only in Provide-/Flush-Output. */
  1027. static BROTLI_BOOL WriteOutput(Context* context) {
  1028. size_t out_size = (size_t)(context->next_out - context->output);
  1029. context->total_out += out_size;
  1030. if (out_size == 0) return BROTLI_TRUE;
  1031. if (context->test_integrity) return BROTLI_TRUE;
  1032. fwrite(context->output, 1, out_size, context->fout);
  1033. if (ferror(context->fout)) {
  1034. fprintf(stderr, "failed to write output [%s]: %s\n",
  1035. PrintablePath(context->current_output_path), strerror(errno));
  1036. return BROTLI_FALSE;
  1037. }
  1038. return BROTLI_TRUE;
  1039. }
  1040. static BROTLI_BOOL ProvideOutput(Context* context) {
  1041. if (!WriteOutput(context)) return BROTLI_FALSE;
  1042. context->available_out = kFileBufferSize;
  1043. context->next_out = context->output;
  1044. return BROTLI_TRUE;
  1045. }
  1046. static BROTLI_BOOL FlushOutput(Context* context) {
  1047. if (!WriteOutput(context)) return BROTLI_FALSE;
  1048. context->available_out = 0;
  1049. context->next_out = context->output;
  1050. return BROTLI_TRUE;
  1051. }
  1052. static void PrintBytes(size_t value) {
  1053. if (value < 1024) {
  1054. fprintf(stderr, "%d B", (int)value);
  1055. } else if (value < 1048576) {
  1056. fprintf(stderr, "%0.3f KiB", (double)value / 1024.0);
  1057. } else if (value < 1073741824) {
  1058. fprintf(stderr, "%0.3f MiB", (double)value / 1048576.0);
  1059. } else {
  1060. fprintf(stderr, "%0.3f GiB", (double)value / 1073741824.0);
  1061. }
  1062. }
  1063. static void PrintFileProcessingProgress(Context* context) {
  1064. fprintf(stderr, "[%s]: ", PrintablePath(context->current_input_path));
  1065. PrintBytes(context->total_in);
  1066. fprintf(stderr, " -> ");
  1067. PrintBytes(context->total_out);
  1068. fprintf(stderr, " in %1.2f sec", (double)(context->end_time - context->start_time) / CLOCKS_PER_SEC);
  1069. }
  1070. static const char* PrettyDecoderErrorString(BrotliDecoderErrorCode code) {
  1071. /* "_ERROR_domain_" is in only added in newer versions. If CLI is linked
  1072. against older shared library, return error string as is; result might be
  1073. a bit confusing, e.g. "RESERVED" instead of "FORMAT_RESERVED" */
  1074. const char* prefix = "_ERROR_";
  1075. size_t prefix_len = strlen(prefix);
  1076. const char* error_str = BrotliDecoderErrorString(code);
  1077. size_t error_len = strlen(error_str);
  1078. if (error_len > prefix_len) {
  1079. if (strncmp(error_str, prefix, prefix_len) == 0) {
  1080. error_str += prefix_len;
  1081. }
  1082. }
  1083. return error_str;
  1084. }
  1085. static void OnMetadataStart(void* opaque, size_t size) {
  1086. Context* context = (Context*) opaque;
  1087. if (context->comment_state == COMMENT_INIT) {
  1088. if (context->comment_len != size) {
  1089. context->comment_state = COMMENT_BAD;
  1090. return;
  1091. }
  1092. context->comment_pos = 0;
  1093. context->comment_state = COMMENT_READ;
  1094. }
  1095. }
  1096. static void OnMetadataChunk(void* opaque, const uint8_t* data, size_t size) {
  1097. Context* context = (Context*) opaque;
  1098. if (context->comment_state == COMMENT_READ) {
  1099. size_t i;
  1100. for (i = 0; i < size; ++i) {
  1101. if (context->comment_pos >= context->comment_len) {
  1102. context->comment_state = COMMENT_BAD;
  1103. return;
  1104. }
  1105. if (context->comment[context->comment_pos++] != data[i]) {
  1106. context->comment_state = COMMENT_BAD;
  1107. return;
  1108. }
  1109. }
  1110. if (context->comment_pos == context->comment_len) {
  1111. context->comment_state = COMMENT_OK;
  1112. }
  1113. }
  1114. }
  1115. static BROTLI_BOOL InitDecoder(Context* context) {
  1116. context->decoder = BrotliDecoderCreateInstance(NULL, NULL, NULL);
  1117. if (!context->decoder) {
  1118. fprintf(stderr, "out of memory\n");
  1119. return BROTLI_FALSE;
  1120. }
  1121. /* This allows decoding "large-window" streams. Though it creates
  1122. fragmentation (new builds decode streams that old builds don't),
  1123. it is better from used experience perspective. */
  1124. BrotliDecoderSetParameter(
  1125. context->decoder, BROTLI_DECODER_PARAM_LARGE_WINDOW, 1u);
  1126. if (context->dictionary) {
  1127. BrotliDecoderAttachDictionary(context->decoder,
  1128. BROTLI_SHARED_DICTIONARY_RAW, context->dictionary_size,
  1129. context->dictionary);
  1130. }
  1131. return BROTLI_TRUE;
  1132. }
  1133. static BROTLI_BOOL DecompressFile(Context* context) {
  1134. BrotliDecoderState* s = context->decoder;
  1135. BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  1136. if (context->comment_len) {
  1137. context->comment_state = COMMENT_INIT;
  1138. BrotliDecoderSetMetadataCallbacks(s, &OnMetadataStart, &OnMetadataChunk,
  1139. (void*)context);
  1140. } else {
  1141. context->comment_state = COMMENT_OK;
  1142. }
  1143. InitializeBuffers(context);
  1144. for (;;) {
  1145. /* Early check */
  1146. if (context->comment_state == COMMENT_BAD) {
  1147. fprintf(stderr, "corrupt input [%s]\n",
  1148. PrintablePath(context->current_input_path));
  1149. if (context->verbosity > 0) {
  1150. fprintf(stderr, "reason: comment mismatch\n");
  1151. }
  1152. return BROTLI_FALSE;
  1153. }
  1154. if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) {
  1155. if (!HasMoreInput(context)) {
  1156. fprintf(stderr, "corrupt input [%s]\n",
  1157. PrintablePath(context->current_input_path));
  1158. if (context->verbosity > 0) {
  1159. fprintf(stderr, "reason: truncated input\n");
  1160. }
  1161. return BROTLI_FALSE;
  1162. }
  1163. if (!ProvideInput(context)) return BROTLI_FALSE;
  1164. } else if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  1165. if (!ProvideOutput(context)) return BROTLI_FALSE;
  1166. } else if (result == BROTLI_DECODER_RESULT_SUCCESS) {
  1167. if (!FlushOutput(context)) return BROTLI_FALSE;
  1168. BROTLI_BOOL has_more_input = (context->available_in != 0);
  1169. int extra_char = EOF;
  1170. if (!has_more_input) {
  1171. extra_char = fgetc(context->fin);
  1172. if (extra_char != EOF) {
  1173. has_more_input = BROTLI_TRUE;
  1174. context->input[0] = (uint8_t)extra_char;
  1175. context->next_in = context->input;
  1176. context->available_in = 1;
  1177. }
  1178. }
  1179. if (has_more_input) {
  1180. if (context->allow_concatenated) {
  1181. if (context->verbosity > 0) {
  1182. fprintf(stderr, "extra input\n");
  1183. }
  1184. if (!ProvideOutput(context)) return BROTLI_FALSE;
  1185. BrotliDecoderDestroyInstance(context->decoder);
  1186. context->decoder = NULL;
  1187. if (!InitDecoder(context)) return BROTLI_FALSE;
  1188. s = context->decoder;
  1189. } else {
  1190. fprintf(stderr, "corrupt input [%s]\n",
  1191. PrintablePath(context->current_input_path));
  1192. if (context->verbosity > 0) {
  1193. fprintf(stderr, "reason: extra input\n");
  1194. }
  1195. return BROTLI_FALSE;
  1196. }
  1197. } else {
  1198. if (context->verbosity > 0) {
  1199. context->end_time = clock();
  1200. fprintf(stderr, "Decompressed ");
  1201. PrintFileProcessingProgress(context);
  1202. fprintf(stderr, "\n");
  1203. }
  1204. /* Final check */
  1205. if (context->comment_state != COMMENT_OK) {
  1206. fprintf(stderr, "corrupt input [%s]\n",
  1207. PrintablePath(context->current_input_path));
  1208. if (context->verbosity > 0) {
  1209. fprintf(stderr, "reason: comment mismatch\n");
  1210. }
  1211. }
  1212. return BROTLI_TRUE;
  1213. }
  1214. } else { /* result == BROTLI_DECODER_RESULT_ERROR */
  1215. fprintf(stderr, "corrupt input [%s]\n",
  1216. PrintablePath(context->current_input_path));
  1217. if (context->verbosity > 0) {
  1218. BrotliDecoderErrorCode error = BrotliDecoderGetErrorCode(s);
  1219. const char* error_str = PrettyDecoderErrorString(error);
  1220. fprintf(stderr, "reason: %s (%d)\n", error_str, error);
  1221. }
  1222. return BROTLI_FALSE;
  1223. }
  1224. result = BrotliDecoderDecompressStream(s, &context->available_in,
  1225. &context->next_in, &context->available_out, &context->next_out, 0);
  1226. }
  1227. }
  1228. static BROTLI_BOOL DecompressFiles(Context* context) {
  1229. while (NextFile(context)) {
  1230. BROTLI_BOOL is_ok = BROTLI_TRUE;
  1231. BROTLI_BOOL rm_input = BROTLI_FALSE;
  1232. BROTLI_BOOL rm_output = BROTLI_TRUE;
  1233. if (!InitDecoder(context)) return BROTLI_FALSE;
  1234. is_ok = OpenFiles(context);
  1235. if (is_ok && !context->current_input_path &&
  1236. !context->force_overwrite && isatty(STDIN_FILENO)) {
  1237. fprintf(stderr, "Use -h help. Use -f to force input from a terminal.\n");
  1238. is_ok = BROTLI_FALSE;
  1239. }
  1240. if (is_ok) is_ok = DecompressFile(context);
  1241. if (context->decoder) BrotliDecoderDestroyInstance(context->decoder);
  1242. context->decoder = NULL;
  1243. rm_output = !is_ok;
  1244. rm_input = !rm_output && context->junk_source;
  1245. if (!CloseFiles(context, rm_input, rm_output)) is_ok = BROTLI_FALSE;
  1246. if (!is_ok) return BROTLI_FALSE;
  1247. }
  1248. return BROTLI_TRUE;
  1249. }
  1250. static BROTLI_BOOL CompressFile(Context* context, BrotliEncoderState* s) {
  1251. BROTLI_BOOL is_eof = BROTLI_FALSE;
  1252. BROTLI_BOOL prologue = !!context->comment_len;
  1253. InitializeBuffers(context);
  1254. for (;;) {
  1255. if (context->available_in == 0 && !is_eof) {
  1256. if (!ProvideInput(context)) return BROTLI_FALSE;
  1257. is_eof = !HasMoreInput(context);
  1258. }
  1259. if (prologue) {
  1260. prologue = BROTLI_FALSE;
  1261. const uint8_t* next_meta = context->comment;
  1262. size_t available_meta = context->comment_len;
  1263. if (!BrotliEncoderCompressStream(s,
  1264. BROTLI_OPERATION_EMIT_METADATA,
  1265. &available_meta, &next_meta,
  1266. &context->available_out, &context->next_out, NULL)) {
  1267. /* Should detect OOM? */
  1268. fprintf(stderr, "failed to emit metadata [%s]\n",
  1269. PrintablePath(context->current_input_path));
  1270. return BROTLI_FALSE;
  1271. }
  1272. if (available_meta != 0) {
  1273. fprintf(stderr, "failed to emit metadata [%s]\n",
  1274. PrintablePath(context->current_input_path));
  1275. return BROTLI_FALSE;
  1276. }
  1277. } else {
  1278. if (!BrotliEncoderCompressStream(s,
  1279. is_eof ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS,
  1280. &context->available_in, &context->next_in,
  1281. &context->available_out, &context->next_out, NULL)) {
  1282. /* Should detect OOM? */
  1283. fprintf(stderr, "failed to compress data [%s]\n",
  1284. PrintablePath(context->current_input_path));
  1285. return BROTLI_FALSE;
  1286. }
  1287. }
  1288. if (context->available_out == 0) {
  1289. if (!ProvideOutput(context)) return BROTLI_FALSE;
  1290. }
  1291. if (BrotliEncoderIsFinished(s)) {
  1292. if (!FlushOutput(context)) return BROTLI_FALSE;
  1293. if (context->verbosity > 0) {
  1294. context->end_time = clock();
  1295. fprintf(stderr, "Compressed ");
  1296. PrintFileProcessingProgress(context);
  1297. fprintf(stderr, "\n");
  1298. }
  1299. return BROTLI_TRUE;
  1300. }
  1301. }
  1302. }
  1303. static BROTLI_BOOL CompressFiles(Context* context) {
  1304. while (NextFile(context)) {
  1305. BROTLI_BOOL is_ok = BROTLI_TRUE;
  1306. BROTLI_BOOL rm_input = BROTLI_FALSE;
  1307. BROTLI_BOOL rm_output = BROTLI_TRUE;
  1308. BrotliEncoderState* s = BrotliEncoderCreateInstance(NULL, NULL, NULL);
  1309. if (!s) {
  1310. fprintf(stderr, "out of memory\n");
  1311. return BROTLI_FALSE;
  1312. }
  1313. BrotliEncoderSetParameter(s,
  1314. BROTLI_PARAM_QUALITY, (uint32_t)context->quality);
  1315. if (context->lgwin > 0) {
  1316. /* Specified by user. */
  1317. /* Do not enable "large-window" extension, if not required. */
  1318. if (context->lgwin > BROTLI_MAX_WINDOW_BITS) {
  1319. BrotliEncoderSetParameter(s, BROTLI_PARAM_LARGE_WINDOW, 1u);
  1320. }
  1321. BrotliEncoderSetParameter(s,
  1322. BROTLI_PARAM_LGWIN, (uint32_t)context->lgwin);
  1323. } else {
  1324. /* 0, or not specified by user; could be chosen by compressor. */
  1325. uint32_t lgwin = DEFAULT_LGWIN;
  1326. /* Use file size to limit lgwin. */
  1327. if (context->input_file_length >= 0) {
  1328. lgwin = BROTLI_MIN_WINDOW_BITS;
  1329. while (BROTLI_MAX_BACKWARD_LIMIT(lgwin) <
  1330. (uint64_t)context->input_file_length) {
  1331. lgwin++;
  1332. if (lgwin == BROTLI_MAX_WINDOW_BITS) break;
  1333. }
  1334. }
  1335. BrotliEncoderSetParameter(s, BROTLI_PARAM_LGWIN, lgwin);
  1336. }
  1337. if (context->input_file_length > 0) {
  1338. uint32_t size_hint = context->input_file_length < (1 << 30) ?
  1339. (uint32_t)context->input_file_length : (1u << 30);
  1340. BrotliEncoderSetParameter(s, BROTLI_PARAM_SIZE_HINT, size_hint);
  1341. }
  1342. if (context->dictionary) {
  1343. BrotliEncoderAttachPreparedDictionary(s, context->prepared_dictionary);
  1344. }
  1345. is_ok = OpenFiles(context);
  1346. if (is_ok && !context->current_output_path &&
  1347. !context->force_overwrite && isatty(STDOUT_FILENO)) {
  1348. fprintf(stderr, "Use -h help. Use -f to force output to a terminal.\n");
  1349. is_ok = BROTLI_FALSE;
  1350. }
  1351. if (is_ok) is_ok = CompressFile(context, s);
  1352. BrotliEncoderDestroyInstance(s);
  1353. rm_output = !is_ok;
  1354. if (is_ok && context->reject_uncompressible) {
  1355. if (context->total_out >= context->total_in) {
  1356. rm_output = BROTLI_TRUE;
  1357. if (context->verbosity > 0) {
  1358. fprintf(stderr, "Output is larger than input\n");
  1359. }
  1360. }
  1361. }
  1362. rm_input = !rm_output && context->junk_source;
  1363. if (!CloseFiles(context, rm_input, rm_output)) is_ok = BROTLI_FALSE;
  1364. if (!is_ok) return BROTLI_FALSE;
  1365. }
  1366. return BROTLI_TRUE;
  1367. }
  1368. int main(int argc, char** argv) {
  1369. Command command;
  1370. Context context;
  1371. BROTLI_BOOL is_ok = BROTLI_TRUE;
  1372. int i;
  1373. context.quality = 11;
  1374. context.lgwin = -1;
  1375. context.verbosity = 0;
  1376. context.comment_len = 0;
  1377. context.force_overwrite = BROTLI_FALSE;
  1378. context.junk_source = BROTLI_FALSE;
  1379. context.reject_uncompressible = BROTLI_FALSE;
  1380. context.copy_stat = BROTLI_TRUE;
  1381. context.test_integrity = BROTLI_FALSE;
  1382. context.write_to_stdout = BROTLI_FALSE;
  1383. context.decompress = BROTLI_FALSE;
  1384. context.large_window = BROTLI_FALSE;
  1385. context.allow_concatenated = BROTLI_FALSE;
  1386. context.output_path = NULL;
  1387. context.dictionary_path = NULL;
  1388. context.suffix = DEFAULT_SUFFIX;
  1389. for (i = 0; i < MAX_OPTIONS; ++i) context.not_input_indices[i] = 0;
  1390. context.longest_path_len = 1;
  1391. context.input_count = 0;
  1392. context.argc = argc;
  1393. context.argv = argv;
  1394. context.dictionary = NULL;
  1395. context.dictionary_size = 0;
  1396. context.decoder = NULL;
  1397. context.prepared_dictionary = NULL;
  1398. context.modified_path = NULL;
  1399. context.iterator = 0;
  1400. context.ignore = 0;
  1401. context.iterator_error = BROTLI_FALSE;
  1402. context.buffer = NULL;
  1403. context.current_input_path = NULL;
  1404. context.current_output_path = NULL;
  1405. context.fin = NULL;
  1406. context.fout = NULL;
  1407. command = ParseParams(&context);
  1408. if (command == COMMAND_COMPRESS || command == COMMAND_DECOMPRESS ||
  1409. command == COMMAND_TEST_INTEGRITY) {
  1410. if (!ReadDictionary(&context, command)) is_ok = BROTLI_FALSE;
  1411. if (is_ok) {
  1412. size_t modified_path_len =
  1413. context.longest_path_len + strlen(context.suffix) + 1;
  1414. context.modified_path = (char*)malloc(modified_path_len);
  1415. context.buffer = (uint8_t*)malloc(kFileBufferSize * 2);
  1416. if (!context.modified_path || !context.buffer) {
  1417. fprintf(stderr, "out of memory\n");
  1418. is_ok = BROTLI_FALSE;
  1419. } else {
  1420. context.input = context.buffer;
  1421. context.output = context.buffer + kFileBufferSize;
  1422. }
  1423. }
  1424. }
  1425. if (!is_ok) command = COMMAND_NOOP;
  1426. switch (command) {
  1427. case COMMAND_NOOP:
  1428. break;
  1429. case COMMAND_VERSION:
  1430. PrintVersion();
  1431. break;
  1432. case COMMAND_COMPRESS:
  1433. is_ok = CompressFiles(&context);
  1434. break;
  1435. case COMMAND_DECOMPRESS:
  1436. case COMMAND_TEST_INTEGRITY:
  1437. is_ok = DecompressFiles(&context);
  1438. break;
  1439. case COMMAND_HELP:
  1440. case COMMAND_INVALID:
  1441. default:
  1442. is_ok = (command == COMMAND_HELP);
  1443. PrintHelp(FileName(argv[0]), is_ok);
  1444. break;
  1445. }
  1446. if (context.iterator_error) is_ok = BROTLI_FALSE;
  1447. BrotliEncoderDestroyPreparedDictionary(context.prepared_dictionary);
  1448. free(context.dictionary);
  1449. free(context.modified_path);
  1450. free(context.buffer);
  1451. if (!is_ok) exit(1);
  1452. return 0;
  1453. }