cksum.c 1.6 KB

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