Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

483 řádky
12 KiB

  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/base.h>
  15. #include <memory>
  16. #include <string>
  17. #include <vector>
  18. #include <errno.h>
  19. #include <fcntl.h>
  20. #include <limits.h>
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include <sys/stat.h>
  24. #include <sys/types.h>
  25. #if !defined(OPENSSL_WINDOWS)
  26. #include <unistd.h>
  27. #if !defined(O_BINARY)
  28. #define O_BINARY 0
  29. #endif
  30. #else
  31. #define NOMINMAX
  32. #pragma warning(push, 3)
  33. #include <windows.h>
  34. #pragma warning(pop)
  35. #include <io.h>
  36. #define PATH_MAX MAX_PATH
  37. typedef int ssize_t;
  38. #endif
  39. #include <openssl/digest.h>
  40. struct close_delete {
  41. void operator()(int *fd) {
  42. close(*fd);
  43. }
  44. };
  45. template<typename T, typename R, R (*func) (T*)>
  46. struct func_delete {
  47. void operator()(T* obj) {
  48. func(obj);
  49. }
  50. };
  51. // Source is an awkward expression of a union type in C++: Stdin | File filename.
  52. struct Source {
  53. enum Type {
  54. STDIN,
  55. };
  56. Source() : is_stdin_(false) {}
  57. Source(Type) : is_stdin_(true) {}
  58. Source(const std::string &name) : is_stdin_(false), filename_(name) {}
  59. bool is_stdin() const { return is_stdin_; }
  60. const std::string &filename() const { return filename_; }
  61. private:
  62. bool is_stdin_;
  63. std::string filename_;
  64. };
  65. static const char kStdinName[] = "standard input";
  66. // OpenFile opens the regular file named |filename| and sets |*out_fd| to be a
  67. // file descriptor to it. Returns true on sucess or prints an error to stderr
  68. // and returns false on error.
  69. static bool OpenFile(int *out_fd, const std::string &filename) {
  70. *out_fd = -1;
  71. int fd = open(filename.c_str(), O_RDONLY | O_BINARY);
  72. if (fd < 0) {
  73. fprintf(stderr, "Failed to open input file '%s': %s\n", filename.c_str(),
  74. strerror(errno));
  75. return false;
  76. }
  77. #if !defined(OPENSSL_WINDOWS)
  78. struct stat st;
  79. if (fstat(fd, &st)) {
  80. fprintf(stderr, "Failed to stat input file '%s': %s\n", filename.c_str(),
  81. strerror(errno));
  82. goto err;
  83. }
  84. if (!S_ISREG(st.st_mode)) {
  85. fprintf(stderr, "%s: not a regular file\n", filename.c_str());
  86. goto err;
  87. }
  88. #endif
  89. *out_fd = fd;
  90. return true;
  91. #if !defined(OPENSSL_WINDOWS)
  92. err:
  93. close(fd);
  94. return false;
  95. #endif
  96. }
  97. // SumFile hashes the contents of |source| with |md| and sets |*out_hex| to the
  98. // hex-encoded result.
  99. //
  100. // It returns true on success or prints an error to stderr and returns false on
  101. // error.
  102. static bool SumFile(std::string *out_hex, const EVP_MD *md,
  103. const Source &source) {
  104. std::unique_ptr<int, close_delete> scoped_fd;
  105. int fd;
  106. if (source.is_stdin()) {
  107. fd = 0;
  108. } else {
  109. if (!OpenFile(&fd, source.filename())) {
  110. return false;
  111. }
  112. scoped_fd.reset(&fd);
  113. }
  114. static const size_t kBufSize = 8192;
  115. std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufSize]);
  116. EVP_MD_CTX ctx;
  117. EVP_MD_CTX_init(&ctx);
  118. std::unique_ptr<EVP_MD_CTX, func_delete<EVP_MD_CTX, int, EVP_MD_CTX_cleanup>>
  119. scoped_ctx(&ctx);
  120. if (!EVP_DigestInit_ex(&ctx, md, NULL)) {
  121. fprintf(stderr, "Failed to initialize EVP_MD_CTX.\n");
  122. return false;
  123. }
  124. for (;;) {
  125. ssize_t n;
  126. do {
  127. n = read(fd, buf.get(), kBufSize);
  128. } while (n == -1 && errno == EINTR);
  129. if (n == 0) {
  130. break;
  131. } else if (n < 0) {
  132. fprintf(stderr, "Failed to read from %s: %s\n",
  133. source.is_stdin() ? kStdinName : source.filename().c_str(),
  134. strerror(errno));
  135. return false;
  136. }
  137. if (!EVP_DigestUpdate(&ctx, buf.get(), n)) {
  138. fprintf(stderr, "Failed to update hash.\n");
  139. return false;
  140. }
  141. }
  142. uint8_t digest[EVP_MAX_MD_SIZE];
  143. unsigned digest_len;
  144. if (!EVP_DigestFinal_ex(&ctx, digest, &digest_len)) {
  145. fprintf(stderr, "Failed to finish hash.\n");
  146. return false;
  147. }
  148. char hex_digest[EVP_MAX_MD_SIZE * 2];
  149. static const char kHextable[] = "0123456789abcdef";
  150. for (unsigned i = 0; i < digest_len; i++) {
  151. const uint8_t b = digest[i];
  152. hex_digest[i * 2] = kHextable[b >> 4];
  153. hex_digest[i * 2 + 1] = kHextable[b & 0xf];
  154. }
  155. *out_hex = std::string(hex_digest, digest_len * 2);
  156. return true;
  157. }
  158. // PrintFileSum hashes |source| with |md| and prints a line to stdout in the
  159. // format of the coreutils *sum utilities. It returns true on success or prints
  160. // an error to stderr and returns false on error.
  161. static bool PrintFileSum(const EVP_MD *md, const Source &source) {
  162. std::string hex_digest;
  163. if (!SumFile(&hex_digest, md, source)) {
  164. return false;
  165. }
  166. // TODO: When given "--binary" or "-b", we should print " *" instead of " "
  167. // between the digest and the filename.
  168. //
  169. // MSYS and Cygwin md5sum default to binary mode by default, whereas other
  170. // platforms' tools default to text mode by default. We default to text mode
  171. // by default and consider text mode equivalent to binary mode (i.e. we
  172. // always use Unix semantics, even on Windows), which means that our default
  173. // output will differ from the MSYS and Cygwin tools' default output.
  174. printf("%s %s\n", hex_digest.c_str(),
  175. source.is_stdin() ? "-" : source.filename().c_str());
  176. return true;
  177. }
  178. // CheckModeArguments contains arguments for the check mode. See the
  179. // sha256sum(1) man page for details.
  180. struct CheckModeArguments {
  181. bool quiet = false;
  182. bool status = false;
  183. bool warn = false;
  184. bool strict = false;
  185. };
  186. // Check reads lines from |source| where each line is in the format of the
  187. // coreutils *sum utilities. It attempts to verify each hash by reading the
  188. // file named in the line.
  189. //
  190. // It returns true if all files were verified and, if |args.strict|, no input
  191. // lines had formatting errors. Otherwise it prints errors to stderr and
  192. // returns false.
  193. static bool Check(const CheckModeArguments &args, const EVP_MD *md,
  194. const Source &source) {
  195. std::unique_ptr<FILE, func_delete<FILE, int, fclose>> scoped_file;
  196. FILE *file;
  197. if (source.is_stdin()) {
  198. file = stdin;
  199. } else {
  200. int fd;
  201. if (!OpenFile(&fd, source.filename())) {
  202. return false;
  203. }
  204. file = fdopen(fd, "rb");
  205. if (!file) {
  206. perror("fdopen");
  207. close(fd);
  208. return false;
  209. }
  210. scoped_file = std::unique_ptr<FILE, func_delete<FILE, int, fclose>>(file);
  211. }
  212. const size_t hex_size = EVP_MD_size(md) * 2;
  213. char line[EVP_MAX_MD_SIZE * 2 + 2 /* spaces */ + PATH_MAX + 1 /* newline */ +
  214. 1 /* NUL */];
  215. unsigned bad_lines = 0;
  216. unsigned parsed_lines = 0;
  217. unsigned error_lines = 0;
  218. unsigned bad_hash_lines = 0;
  219. unsigned line_no = 0;
  220. bool ok = true;
  221. bool draining_overlong_line = false;
  222. for (;;) {
  223. line_no++;
  224. if (fgets(line, sizeof(line), file) == nullptr) {
  225. if (feof(file)) {
  226. break;
  227. }
  228. fprintf(stderr, "Error reading from input.\n");
  229. return false;
  230. }
  231. size_t len = strlen(line);
  232. if (draining_overlong_line) {
  233. if (line[len - 1] == '\n') {
  234. draining_overlong_line = false;
  235. }
  236. continue;
  237. }
  238. const bool overlong = line[len - 1] != '\n' && !feof(file);
  239. if (len < hex_size + 2 /* spaces */ + 1 /* filename */ ||
  240. line[hex_size] != ' ' ||
  241. line[hex_size + 1] != ' ' ||
  242. overlong) {
  243. bad_lines++;
  244. if (args.warn) {
  245. fprintf(stderr, "%s: %u: improperly formatted line\n",
  246. source.is_stdin() ? kStdinName : source.filename().c_str(), line_no);
  247. }
  248. if (args.strict) {
  249. ok = false;
  250. }
  251. if (overlong) {
  252. draining_overlong_line = true;
  253. }
  254. continue;
  255. }
  256. if (line[len - 1] == '\n') {
  257. line[len - 1] = 0;
  258. len--;
  259. }
  260. parsed_lines++;
  261. // coreutils does not attempt to restrict relative or absolute paths in the
  262. // input so nor does this code.
  263. std::string calculated_hex_digest;
  264. const std::string target_filename(&line[hex_size + 2]);
  265. Source target_source;
  266. if (target_filename == "-") {
  267. // coreutils reads from stdin if the filename is "-".
  268. target_source = Source(Source::STDIN);
  269. } else {
  270. target_source = Source(target_filename);
  271. }
  272. if (!SumFile(&calculated_hex_digest, md, target_source)) {
  273. error_lines++;
  274. ok = false;
  275. continue;
  276. }
  277. if (calculated_hex_digest != std::string(line, hex_size)) {
  278. bad_hash_lines++;
  279. if (!args.status) {
  280. printf("%s: FAILED\n", target_filename.c_str());
  281. }
  282. ok = false;
  283. continue;
  284. }
  285. if (!args.quiet) {
  286. printf("%s: OK\n", target_filename.c_str());
  287. }
  288. }
  289. if (!args.status) {
  290. if (bad_lines > 0 && parsed_lines > 0) {
  291. fprintf(stderr, "WARNING: %u line%s improperly formatted\n", bad_lines,
  292. bad_lines == 1 ? " is" : "s are");
  293. }
  294. if (error_lines > 0) {
  295. fprintf(stderr, "WARNING: %u computed checksum(s) did NOT match\n",
  296. error_lines);
  297. }
  298. }
  299. if (parsed_lines == 0) {
  300. fprintf(stderr, "%s: no properly formatted checksum lines found.\n",
  301. source.is_stdin() ? kStdinName : source.filename().c_str());
  302. ok = false;
  303. }
  304. return ok;
  305. }
  306. // DigestSum acts like the coreutils *sum utilites, with the given hash
  307. // function.
  308. static bool DigestSum(const EVP_MD *md,
  309. const std::vector<std::string> &args) {
  310. bool check_mode = false;
  311. CheckModeArguments check_args;
  312. bool check_mode_args_given = false;
  313. std::vector<Source> sources;
  314. auto it = args.begin();
  315. while (it != args.end()) {
  316. const std::string &arg = *it;
  317. if (!arg.empty() && arg[0] != '-') {
  318. break;
  319. }
  320. it++;
  321. if (arg == "--") {
  322. break;
  323. }
  324. if (arg == "-") {
  325. // "-" ends the argument list and indicates that stdin should be used.
  326. sources.push_back(Source(Source::STDIN));
  327. break;
  328. }
  329. if (arg.size() >= 2 && arg[0] == '-' && arg[1] != '-') {
  330. for (size_t i = 1; i < arg.size(); i++) {
  331. switch (arg[i]) {
  332. case 'b':
  333. case 't':
  334. // Binary/text mode – irrelevent, even on Windows.
  335. break;
  336. case 'c':
  337. check_mode = true;
  338. break;
  339. case 'w':
  340. check_mode_args_given = true;
  341. check_args.warn = true;
  342. break;
  343. default:
  344. fprintf(stderr, "Unknown option '%c'.\n", arg[i]);
  345. return false;
  346. }
  347. }
  348. } else if (arg == "--binary" || arg == "--text") {
  349. // Binary/text mode – irrelevent, even on Windows.
  350. } else if (arg == "--check") {
  351. check_mode = true;
  352. } else if (arg == "--quiet") {
  353. check_mode_args_given = true;
  354. check_args.quiet = true;
  355. } else if (arg == "--status") {
  356. check_mode_args_given = true;
  357. check_args.status = true;
  358. } else if (arg == "--warn") {
  359. check_mode_args_given = true;
  360. check_args.warn = true;
  361. } else if (arg == "--strict") {
  362. check_mode_args_given = true;
  363. check_args.strict = true;
  364. } else {
  365. fprintf(stderr, "Unknown option '%s'.\n", arg.c_str());
  366. return false;
  367. }
  368. }
  369. if (check_mode_args_given && !check_mode) {
  370. fprintf(
  371. stderr,
  372. "Check mode arguments are only meaningful when verifying checksums.\n");
  373. return false;
  374. }
  375. for (; it != args.end(); it++) {
  376. sources.push_back(Source(*it));
  377. }
  378. if (sources.empty()) {
  379. sources.push_back(Source(Source::STDIN));
  380. }
  381. bool ok = true;
  382. if (check_mode) {
  383. for (auto &source : sources) {
  384. ok &= Check(check_args, md, source);
  385. }
  386. } else {
  387. for (auto &source : sources) {
  388. ok &= PrintFileSum(md, source);
  389. }
  390. }
  391. return ok;
  392. }
  393. bool MD5Sum(const std::vector<std::string> &args) {
  394. return DigestSum(EVP_md5(), args);
  395. }
  396. bool SHA1Sum(const std::vector<std::string> &args) {
  397. return DigestSum(EVP_sha1(), args);
  398. }
  399. bool SHA224Sum(const std::vector<std::string> &args) {
  400. return DigestSum(EVP_sha224(), args);
  401. }
  402. bool SHA256Sum(const std::vector<std::string> &args) {
  403. return DigestSum(EVP_sha256(), args);
  404. }
  405. bool SHA384Sum(const std::vector<std::string> &args) {
  406. return DigestSum(EVP_sha384(), args);
  407. }
  408. bool SHA512Sum(const std::vector<std::string> &args) {
  409. return DigestSum(EVP_sha512(), args);
  410. }