chksum_and_xwrite_tar_header.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. * Copyright (C) 2021 Denys Vlasenko <vda.linux@googlemail.com>
  3. *
  4. * Licensed under GPLv2, see file LICENSE in this source tree.
  5. */
  6. //kbuild:lib-$(CONFIG_FEATURE_TAR_CREATE) += chksum_and_xwrite_tar_header.o
  7. //kbuild:lib-$(CONFIG_SMEMCAP) += chksum_and_xwrite_tar_header.o
  8. #include "libbb.h"
  9. #include "bb_archive.h"
  10. void FAST_FUNC chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp)
  11. {
  12. /* POSIX says that checksum is done on unsigned bytes
  13. * (Sun and HP-UX gets it wrong... more details in
  14. * GNU tar source) */
  15. const unsigned char *cp;
  16. unsigned int chksum, size;
  17. strcpy(hp->magic, "ustar ");
  18. /* Calculate and store the checksum (the sum of all of the bytes of
  19. * the header). The checksum field must be filled with blanks for the
  20. * calculation. The checksum field is formatted differently from the
  21. * other fields: it has 6 digits, a NUL, then a space -- rather than
  22. * digits, followed by a NUL like the other fields... */
  23. memset(hp->chksum, ' ', sizeof(hp->chksum));
  24. cp = (const unsigned char *) hp;
  25. chksum = 0;
  26. size = sizeof(*hp);
  27. do { chksum += *cp++; } while (--size);
  28. sprintf(hp->chksum, "%06o", chksum);
  29. xwrite(fd, hp, sizeof(*hp));
  30. }