cksum.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. //config:config CKSUM
  10. //config: bool "cksum"
  11. //config: default y
  12. //config: help
  13. //config: cksum is used to calculate the CRC32 checksum of a file.
  14. //applet:IF_CKSUM(APPLET_NOEXEC(cksum, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
  15. //kbuild:lib-$(CONFIG_CKSUM) += cksum.o
  16. //usage:#define cksum_trivial_usage
  17. //usage: "FILES..."
  18. //usage:#define cksum_full_usage "\n\n"
  19. //usage: "Calculate the CRC32 checksums of FILES"
  20. #include "libbb.h"
  21. #include "common_bufsiz.h"
  22. /* This is a NOEXEC applet. Be very careful! */
  23. int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  24. int cksum_main(int argc UNUSED_PARAM, char **argv)
  25. {
  26. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  27. uint32_t crc;
  28. off_t length, filesize;
  29. int bytes_read;
  30. int exit_code = EXIT_SUCCESS;
  31. #if ENABLE_DESKTOP
  32. getopt32(argv, ""); /* coreutils 6.9 compat */
  33. argv += optind;
  34. #else
  35. argv++;
  36. #endif
  37. setup_common_bufsiz();
  38. do {
  39. int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
  40. if (fd < 0) {
  41. exit_code = EXIT_FAILURE;
  42. continue;
  43. }
  44. crc = 0;
  45. length = 0;
  46. #define read_buf bb_common_bufsiz1
  47. while ((bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE)) > 0) {
  48. length += bytes_read;
  49. crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
  50. }
  51. close(fd);
  52. filesize = length;
  53. while (length) {
  54. crc = (crc << 8) ^ crc32_table[(uint8_t)(crc >> 24) ^ (uint8_t)length];
  55. /* must ensure that shift is unsigned! */
  56. if (sizeof(length) <= sizeof(unsigned))
  57. length = (unsigned)length >> 8;
  58. else if (sizeof(length) <= sizeof(unsigned long))
  59. length = (unsigned long)length >> 8;
  60. else
  61. length = (unsigned long long)length >> 8;
  62. }
  63. crc = ~crc;
  64. printf((*argv ? "%"PRIu32" %"OFF_FMT"i %s\n" : "%"PRIu32" %"OFF_FMT"i\n"),
  65. crc, filesize, *argv);
  66. } while (*argv && *++argv);
  67. fflush_stdout_and_exit(exit_code);
  68. }