cksum.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * cksum - calculate the CRC32 checksum of a file
  4. *
  5. * Copyright (C) 2006 by Rob Sullivan, with ideas from code by Walter Harms
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. //usage:#define cksum_trivial_usage
  10. //usage: "FILES..."
  11. //usage:#define cksum_full_usage "\n\n"
  12. //usage: "Calculate the CRC32 checksums of FILES"
  13. #include "libbb.h"
  14. #include "common_bufsiz.h"
  15. /* This is a NOEXEC applet. Be very careful! */
  16. int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  17. int cksum_main(int argc UNUSED_PARAM, char **argv)
  18. {
  19. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  20. uint32_t crc;
  21. off_t length, filesize;
  22. int bytes_read;
  23. int exit_code = EXIT_SUCCESS;
  24. #if ENABLE_DESKTOP
  25. getopt32(argv, ""); /* coreutils 6.9 compat */
  26. argv += optind;
  27. #else
  28. argv++;
  29. #endif
  30. setup_common_bufsiz();
  31. do {
  32. int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
  33. if (fd < 0) {
  34. exit_code = EXIT_FAILURE;
  35. continue;
  36. }
  37. crc = 0;
  38. length = 0;
  39. #define read_buf bb_common_bufsiz1
  40. while ((bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE)) > 0) {
  41. length += bytes_read;
  42. crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
  43. }
  44. close(fd);
  45. filesize = length;
  46. while (length) {
  47. crc = (crc << 8) ^ crc32_table[(uint8_t)(crc >> 24) ^ (uint8_t)length];
  48. /* must ensure that shift is unsigned! */
  49. if (sizeof(length) <= sizeof(unsigned))
  50. length = (unsigned)length >> 8;
  51. else if (sizeof(length) <= sizeof(unsigned long))
  52. length = (unsigned long)length >> 8;
  53. else
  54. length = (unsigned long long)length >> 8;
  55. }
  56. crc = ~crc;
  57. printf((*argv ? "%"PRIu32" %"OFF_FMT"i %s\n" : "%"PRIu32" %"OFF_FMT"i\n"),
  58. crc, filesize, *argv);
  59. } while (*argv && *++argv);
  60. fflush_stdout_and_exit(exit_code);
  61. }