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