3
0

cksum.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 (4.1 kb)"
  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. /* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
  16. //kbuild:lib-$(CONFIG_CKSUM) += cksum.o
  17. //usage:#define cksum_trivial_usage
  18. //usage: "FILE..."
  19. //usage:#define cksum_full_usage "\n\n"
  20. //usage: "Calculate the CRC32 checksums of FILEs"
  21. #include "libbb.h"
  22. #include "common_bufsiz.h"
  23. /* This is a NOEXEC applet. Be very careful! */
  24. int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  25. int cksum_main(int argc UNUSED_PARAM, char **argv)
  26. {
  27. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  28. int exit_code = EXIT_SUCCESS;
  29. #if ENABLE_DESKTOP
  30. getopt32(argv, ""); /* coreutils 6.9 compat */
  31. argv += optind;
  32. #else
  33. argv++;
  34. #endif
  35. setup_common_bufsiz();
  36. do {
  37. uint32_t crc;
  38. off_t filesize;
  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. filesize = 0;
  46. #define read_buf bb_common_bufsiz1
  47. for (;;) {
  48. uoff_t t;
  49. int bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE);
  50. if (bytes_read > 0) {
  51. filesize += bytes_read;
  52. } else {
  53. /* Checksum filesize bytes, LSB first, and exit */
  54. close(fd);
  55. fd = -1; /* break flag */
  56. t = filesize;
  57. bytes_read = 0;
  58. while (t != 0) {
  59. read_buf[bytes_read++] = (uint8_t)t;
  60. t >>= 8;
  61. }
  62. }
  63. crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
  64. if (fd < 0)
  65. break;
  66. }
  67. crc = ~crc;
  68. printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
  69. (unsigned)crc, filesize, *argv);
  70. } while (*argv && *++argv);
  71. fflush_stdout_and_exit(exit_code);
  72. }