is_tar.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * is_tar() -- figure out whether file is a tar archive.
  3. *
  4. * Stolen (by the author!) from the public domain tar program:
  5. * Pubic Domain version written 26 Aug 1985 John Gilmore (ihnp4!hoptoad!gnu).
  6. *
  7. * @(#)list.c 1.18 9/23/86 Public Domain - gnu
  8. * $Id: is_tar.c,v 1.9 1997/01/15 17:23:24 christos Exp $
  9. *
  10. * Comments changed and some code/comments reformatted
  11. * for file command by Ian Darwin.
  12. */
  13. #include <string.h>
  14. #include <ctype.h>
  15. #include <sys/types.h>
  16. #include "tar.h"
  17. #define isodigit(c) ( ((c) >= '0') && ((c) <= '7') )
  18. #if defined(__STDC__) || defined(__cplusplus)
  19. static int from_oct(int, char*); /* Decode octal number */
  20. #else
  21. static int from_oct();
  22. #endif
  23. /*
  24. * Return
  25. * 0 if the checksum is bad (i.e., probably not a tar archive),
  26. * 1 for old UNIX tar file,
  27. * 2 for Unix Std (POSIX) tar file.
  28. */
  29. int
  30. is_tar(buf, nbytes)
  31. unsigned char *buf;
  32. int nbytes;
  33. {
  34. register union record *header = (union record *)buf;
  35. register int i;
  36. register int sum, recsum;
  37. register char *p;
  38. if (nbytes < sizeof(union record))
  39. return 0;
  40. recsum = from_oct(8, header->header.chksum);
  41. sum = 0;
  42. p = header->charptr;
  43. for (i = sizeof(union record); --i >= 0;) {
  44. /*
  45. * We can't use unsigned char here because of old compilers,
  46. * e.g. V7.
  47. */
  48. sum += 0xFF & *p++;
  49. }
  50. /* Adjust checksum to count the "chksum" field as blanks. */
  51. for (i = sizeof(header->header.chksum); --i >= 0;)
  52. sum -= 0xFF & header->header.chksum[i];
  53. sum += ' '* sizeof header->header.chksum;
  54. if (sum != recsum)
  55. return 0; /* Not a tar archive */
  56. if (0==strcmp(header->header.magic, TMAGIC))
  57. return 2; /* Unix Standard tar archive */
  58. return 1; /* Old fashioned tar archive */
  59. }
  60. /*
  61. * Quick and dirty octal conversion.
  62. *
  63. * Result is -1 if the field is invalid (all blank, or nonoctal).
  64. */
  65. static int
  66. from_oct(digs, where)
  67. register int digs;
  68. register char *where;
  69. {
  70. register int value;
  71. while (isspace(*where)) { /* Skip spaces */
  72. where++;
  73. if (--digs <= 0)
  74. return -1; /* All blank field */
  75. }
  76. value = 0;
  77. while (digs > 0 && isodigit(*where)) { /* Scan til nonoctal */
  78. value = (value << 3) | (*where++ - '0');
  79. --digs;
  80. }
  81. if (digs > 0 && *where && !isspace(*where))
  82. return -1; /* Ended on non-space/nul */
  83. return value;
  84. }