3
0

cksum.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #include "libbb.h"
  10. /* This is a NOEXEC applet. Be very careful! */
  11. int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12. int cksum_main(int argc UNUSED_PARAM, char **argv)
  13. {
  14. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  15. uint32_t crc;
  16. off_t length, filesize;
  17. int bytes_read;
  18. int exit_code = EXIT_SUCCESS;
  19. #if ENABLE_DESKTOP
  20. getopt32(argv, ""); /* coreutils 6.9 compat */
  21. argv += optind;
  22. #else
  23. argv++;
  24. #endif
  25. do {
  26. int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
  27. if (fd < 0) {
  28. exit_code = EXIT_FAILURE;
  29. continue;
  30. }
  31. crc = 0;
  32. length = 0;
  33. #define read_buf bb_common_bufsiz1
  34. while ((bytes_read = safe_read(fd, read_buf, sizeof(read_buf))) > 0) {
  35. length += bytes_read;
  36. crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
  37. }
  38. close(fd);
  39. filesize = length;
  40. while (length) {
  41. crc = (crc << 8) ^ crc32_table[(uint8_t)(crc >> 24) ^ (uint8_t)length];
  42. /* must ensure that shift is unsigned! */
  43. if (sizeof(length) <= sizeof(unsigned))
  44. length = (unsigned)length >> 8;
  45. else if (sizeof(length) <= sizeof(unsigned long))
  46. length = (unsigned long)length >> 8;
  47. else
  48. length = (unsigned long long)length >> 8;
  49. }
  50. crc = ~crc;
  51. printf((*argv ? "%"PRIu32" %"OFF_FMT"i %s\n" : "%"PRIu32" %"OFF_FMT"i\n"),
  52. crc, filesize, *argv);
  53. } while (*argv && *++argv);
  54. fflush_stdout_and_exit(exit_code);
  55. }