sum.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * sum -- checksum and count the blocks in a file
  4. * Like BSD sum or SysV sum -r, except like SysV sum if -s option is given.
  5. *
  6. * Copyright (C) 86, 89, 91, 1995-2002, 2004 Free Software Foundation, Inc.
  7. * Copyright (C) 2005 by Erik Andersen <andersen@codepoet.org>
  8. * Copyright (C) 2005 by Mike Frysinger <vapier@gentoo.org>
  9. *
  10. * Written by Kayvan Aghaiepour and David MacKenzie
  11. * Taken from coreutils and turned into a busybox applet by Mike Frysinger
  12. *
  13. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  14. */
  15. #include "busybox.h"
  16. enum { sysv_sum, bsd_sum };
  17. /* BSD: calculate and print the rotated checksum and the size in 1K blocks
  18. The checksum varies depending on sizeof (int). */
  19. /* SYSV: calculate and print the checksum and the size in 512-byte blocks */
  20. /* Return 1 if successful. */
  21. static int sum_file(const char *file, int type, int print_name)
  22. {
  23. #define buf bb_common_bufsiz1
  24. int r, fd;
  25. uintmax_t total_bytes = 0;
  26. /* The sum of all the input bytes, modulo (UINT_MAX + 1). */
  27. unsigned s = 0;
  28. fd = 0;
  29. if (NOT_LONE_DASH(file)) {
  30. fd = open(file, O_RDONLY);
  31. if (fd == -1)
  32. goto ret_bad;
  33. }
  34. while (1) {
  35. size_t bytes_read = safe_read(fd, buf, BUFSIZ);
  36. if ((ssize_t)bytes_read <= 0) {
  37. r = (fd && close(fd) != 0);
  38. if (!bytes_read && !r)
  39. /* no error */
  40. break;
  41. ret_bad:
  42. bb_perror_msg(file);
  43. return 0;
  44. }
  45. total_bytes += bytes_read;
  46. if (type == sysv_sum) {
  47. do s += buf[--bytes_read]; while (bytes_read);
  48. } else {
  49. r = 0;
  50. do {
  51. s = (s >> 1) + ((s & 1) << 15);
  52. s += buf[r++];
  53. s &= 0xffff; /* Keep it within bounds. */
  54. } while (--bytes_read);
  55. }
  56. }
  57. if (!print_name) file = "";
  58. if (type == sysv_sum) {
  59. r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
  60. s = (r & 0xffff) + (r >> 16);
  61. printf("%d %ju %s\n", s, (total_bytes+511)/512, file);
  62. } else
  63. printf("%05d %5ju %s\n", s, (total_bytes+1023)/1024, file);
  64. return 1;
  65. #undef buf
  66. }
  67. int sum_main(int argc, char **argv)
  68. {
  69. int n;
  70. int type = bsd_sum;
  71. n = getopt32(argc, argv, "sr");
  72. if (n & 1) type = sysv_sum;
  73. /* give the bsd priority over sysv func */
  74. if (n & 2) type = bsd_sum;
  75. if (argc == optind)
  76. n = sum_file("-", type, 0);
  77. else
  78. for (n = 1; optind < argc; optind++)
  79. n &= sum_file(argv[optind], type, 1);
  80. return !n;
  81. }