is_tar.c 2.3 KB

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