Index: head/usr.bin/file/Magdir/pgp =================================================================== --- head/usr.bin/file/Magdir/pgp (revision 13586) +++ head/usr.bin/file/Magdir/pgp (revision 13587) @@ -1,11 +1,12 @@ + +#------------------------------------------------------------------------------ +# pgp: file(1) magic for Pretty Good Privacy # -# PGP (Pretty Good Privacy) -# 0 beshort 0x9900 PGP key public ring 0 beshort 0x9501 PGP key security ring 0 beshort 0x9500 PGP key security ring 0 string -----BEGIN\040PGP PGP armored data ->15 string PUBLIC\040KEY\040BLOCK- (public key block) ->15 string MESSAGE- (message) ->15 string SIGNED\040MESSAGE- (signed message) ->15 string PGP\040SIGNATURE- (signature) +>15 string PUBLIC\040KEY\040BLOCK- public key block +>15 string MESSAGE- message +>15 string SIGNED\040MESSAGE- signed message +>15 string PGP\040SIGNATURE- signature Index: head/usr.bin/file/Magdir/zyxel =================================================================== --- head/usr.bin/file/Magdir/zyxel (revision 13586) +++ head/usr.bin/file/Magdir/zyxel (revision 13587) @@ -1,11 +1,16 @@ + +#------------------------------------------------------------------------------ +# zyxel: file(1) magic for ZyXEL modems +# # From # These are the /etc/magic entries to decode datafiles as used for the # ZyXEL U-1496E DATA/FAX/VOICE modems. (This header conforms to a # ZyXEL-defined standard) -0 string ZyXEL\002 ZyXEL voice data ->10 byte 0 - CELP encoding ->10 byte 1 - ADPCM2 encoding ->10 byte 2 - ADPCM3 encoding ->10 byte 3 - ADPCM4 encoding - +0 string ZyXEL\002 ZyXEL voice data +>10 byte 0 - CELP encoding +>10 byte&0x0B 1 - ADPCM2 encoding +>10 byte&0x0B 2 - ADPCM3 encoding +>10 byte&0x0B 3 - ADPCM4 encoding +>10 byte&0x0B 8 - New ADPCM3 encoding +>10 byte&0x04 4 with resync Index: head/usr.bin/file/apprentice.c =================================================================== --- head/usr.bin/file/apprentice.c (revision 13586) +++ head/usr.bin/file/apprentice.c (revision 13587) @@ -1,551 +1,622 @@ /* * apprentice - make one pass through /etc/magic, learning its secrets. * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #include #include #include #include +#include #include "file.h" #ifndef lint static char *moduleid = - "@(#)$Id: apprentice.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $"; + "@(#)$Id: apprentice.c,v 1.2 1995/05/30 06:29:58 rgrimes Exp $"; #endif /* lint */ #define EATAB {while (isascii((unsigned char) *l) && \ isspace((unsigned char) *l)) ++l;} +#define LOWCASE(l) (isupper((unsigned char) (l)) ? \ + tolower((unsigned char) (l)) : (l)) static int getvalue __P((struct magic *, char **)); static int hextoint __P((int)); static char *getstr __P((char *, char *, int, int *)); static int parse __P((char *, int *, int)); +static void eatsize __P((char **)); static int maxmagic = 0; +static int apprentice_1 __P((char *, int)); + int apprentice(fn, check) -char *fn; /* name of magic file */ +char *fn; /* list of magic files */ int check; /* non-zero? checking-only run. */ { - FILE *f; - char line[BUFSIZ+1]; - int errs = 0; + char *p, *mfn; + int file_err, errs = -1; - f = fopen(fn, "r"); - if (f==NULL) { - (void) fprintf(stderr, "%s: can't read magic file %s\n", - progname, fn); - if (check) - return -1; - else - exit(1); - } - maxmagic = MAXMAGIS; - if ((magic = (struct magic *) calloc(sizeof(struct magic), maxmagic)) - == NULL) { + magic = (struct magic *) calloc(sizeof(struct magic), maxmagic); + mfn = malloc(strlen(fn)+1); + if (magic == NULL || mfn == NULL) { (void) fprintf(stderr, "%s: Out of memory.\n", progname); if (check) return -1; else exit(1); } + fn = strcpy(mfn, fn); + + while (fn) { + p = strchr(fn, ':'); + if (p) + *p++ = '\0'; + file_err = apprentice_1(fn, check); + if (file_err > errs) + errs = file_err; + fn = p; + } + if (errs == -1) + (void) fprintf(stderr, "%s: couldn't find any magic files!\n", + progname); + if (!check && errs) + exit(1); + free(mfn); + return errs; +} + +static int +apprentice_1(fn, check) +char *fn; /* name of magic file */ +int check; /* non-zero? checking-only run. */ +{ + static const char hdr[] = + "cont\toffset\ttype\topcode\tmask\tvalue\tdesc"; + FILE *f; + char line[BUFSIZ+1]; + int errs = 0; + + f = fopen(fn, "r"); + if (f==NULL) { + if (errno != ENOENT) + (void) fprintf(stderr, + "%s: can't read magic file %s (%s)\n", + progname, fn, strerror(errno)); + return -1; + } + /* parse it */ if (check) /* print silly verbose header for USG compat. */ - (void) printf("cont\toffset\ttype\topcode\tmask\tvalue\tdesc\n"); + (void) printf("%s\n", hdr); for (lineno = 1;fgets(line, BUFSIZ, f) != NULL; lineno++) { if (line[0]=='#') /* comment, do not parse */ continue; if (strlen(line) <= (unsigned)1) /* null line, garbage, etc */ continue; line[strlen(line)-1] = '\0'; /* delete newline */ if (parse(line, &nmagic, check) != 0) - ++errs; + errs = 1; } (void) fclose(f); - return errs ? -1 : 0; + return errs; } /* * extend the sign bit if the comparison is to be signed */ unsigned long signextend(m, v) struct magic *m; unsigned long v; { if (!(m->flag & UNSIGNED)) switch(m->type) { /* * Do not remove the casts below. They are * vital. When later compared with the data, * the sign extension must have happened. */ case BYTE: v = (char) v; break; case SHORT: case BESHORT: case LESHORT: v = (short) v; break; case DATE: case BEDATE: case LEDATE: case LONG: case BELONG: case LELONG: v = (long) v; break; case STRING: break; default: magwarn("can't happen: m->type=%d\n", m->type); return -1; } return v; } /* * parse one line from magic file, put into magic[index++] if valid */ static int parse(l, ndx, check) char *l; int *ndx, check; { int i = 0, nd = *ndx; struct magic *m; char *t, *s; +#define ALLOC_INCR 20 if (nd+1 >= maxmagic){ - maxmagic += 20; - if ((magic = (struct magic *) realloc(magic, - sizeof(struct magic) * + maxmagic += ALLOC_INCR; + if ((magic = (struct magic *) realloc(magic, + sizeof(struct magic) * maxmagic)) == NULL) { (void) fprintf(stderr, "%s: Out of memory.\n", progname); if (check) return -1; else exit(1); } + memset(&magic[*ndx], 0, sizeof(struct magic) * ALLOC_INCR); } m = &magic[*ndx]; m->flag = 0; m->cont_level = 0; while (*l == '>') { ++l; /* step over */ m->cont_level++; } if (m->cont_level != 0 && *l == '(') { ++l; /* step over */ m->flag |= INDIR; } /* get offset, then skip over it */ - m->offset = (int) strtol(l,&t,0); + m->offset = (int) strtoul(l,&t,0); if (l == t) magwarn("offset %s invalid", l); l = t; if (m->flag & INDIR) { m->in.type = LONG; m->in.offset = 0; /* * read [.lbs][+-]nnnnn) */ if (*l == '.') { - switch (*++l) { + l++; + switch (LOWCASE(*l)) { case 'l': m->in.type = LONG; break; + case 'h': case 's': m->in.type = SHORT; break; + case 'c': case 'b': m->in.type = BYTE; break; default: magwarn("indirect offset type %c invalid", *l); break; } l++; } s = l; if (*l == '+' || *l == '-') l++; if (isdigit((unsigned char)*l)) { - m->in.offset = strtol(l, &t, 0); + m->in.offset = strtoul(l, &t, 0); if (*s == '-') m->in.offset = - m->in.offset; } else t = l; if (*t++ != ')') magwarn("missing ')' in indirect offset"); l = t; } while (isascii((unsigned char)*l) && isdigit((unsigned char)*l)) ++l; EATAB; #define NBYTE 4 #define NSHORT 5 #define NLONG 4 #define NSTRING 6 #define NDATE 4 #define NBESHORT 7 #define NBELONG 6 #define NBEDATE 6 #define NLESHORT 7 #define NLELONG 6 #define NLEDATE 6 if (*l == 'u') { ++l; m->flag |= UNSIGNED; } /* get type, skip it */ if (strncmp(l, "byte", NBYTE)==0) { m->type = BYTE; l += NBYTE; } else if (strncmp(l, "short", NSHORT)==0) { m->type = SHORT; l += NSHORT; } else if (strncmp(l, "long", NLONG)==0) { m->type = LONG; l += NLONG; } else if (strncmp(l, "string", NSTRING)==0) { m->type = STRING; l += NSTRING; } else if (strncmp(l, "date", NDATE)==0) { m->type = DATE; l += NDATE; } else if (strncmp(l, "beshort", NBESHORT)==0) { m->type = BESHORT; l += NBESHORT; } else if (strncmp(l, "belong", NBELONG)==0) { m->type = BELONG; l += NBELONG; } else if (strncmp(l, "bedate", NBEDATE)==0) { m->type = BEDATE; l += NBEDATE; } else if (strncmp(l, "leshort", NLESHORT)==0) { m->type = LESHORT; l += NLESHORT; } else if (strncmp(l, "lelong", NLELONG)==0) { m->type = LELONG; l += NLELONG; } else if (strncmp(l, "ledate", NLEDATE)==0) { m->type = LEDATE; l += NLEDATE; } else { magwarn("type %s invalid", l); return -1; } /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */ if (*l == '&') { ++l; - m->mask = signextend(m, strtol(l, &l, 0)); + m->mask = signextend(m, strtoul(l, &l, 0)); + eatsize(&l); } else m->mask = ~0L; EATAB; switch (*l) { case '>': case '<': /* Old-style anding: "0 byte &0x80 dynamically linked" */ case '&': case '^': case '=': m->reln = *l; ++l; break; case '!': if (m->type != STRING) { m->reln = *l; ++l; break; } /* FALL THROUGH */ default: if (*l == 'x' && isascii((unsigned char)l[1]) && isspace((unsigned char)l[1])) { m->reln = *l; ++l; goto GetDesc; /* Bill The Cat */ } m->reln = '='; break; } EATAB; if (getvalue(m, &l)) return -1; /* * TODO finish this macro and start using it! * #define offsetcheck {if (offset > HOWMANY-1) * magwarn("offset too big"); } */ /* * now get last part - the description */ GetDesc: EATAB; if (l[0] == '\b') { ++l; m->nospflag = 1; } else if ((l[0] == '\\') && (l[1] == 'b')) { ++l; ++l; m->nospflag = 1; } else m->nospflag = 0; while ((m->desc[i++] = *l++) != '\0' && itype == STRING) { *p = getstr(*p, m->value.s, sizeof(m->value.s), &slen); m->vallen = slen; } else - if (m->reln != 'x') - m->value.l = signextend(m, strtol(*p, p, 0)); + if (m->reln != 'x') { + m->value.l = signextend(m, strtoul(*p, p, 0)); + eatsize(p); + } return 0; } /* * Convert a string containing C character escapes. Stop at an unescaped * space or tab. * Copy the converted version to "p", returning its length in *slen. * Return updated scan pointer as function result. */ static char * getstr(s, p, plen, slen) register char *s; register char *p; int plen, *slen; { char *origs = s, *origp = p; char *pmax = p + plen - 1; register int c; register int val; while ((c = *s++) != '\0') { if (isspace((unsigned char) c)) break; if (p >= pmax) { fprintf(stderr, "String too long: %s\n", origs); break; } if(c == '\\') { switch(c = *s++) { case '\0': goto out; default: *p++ = (char) c; break; case 'n': *p++ = '\n'; break; case 'r': *p++ = '\r'; break; case 'b': *p++ = '\b'; break; case 't': *p++ = '\t'; break; case 'f': *p++ = '\f'; break; case 'v': *p++ = '\v'; break; /* \ and up to 3 octal digits */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': val = c - '0'; c = *s++; /* try for 2 */ if(c >= '0' && c <= '7') { val = (val<<3) | (c - '0'); c = *s++; /* try for 3 */ if(c >= '0' && c <= '7') val = (val<<3) | (c-'0'); else --s; } else --s; *p++ = (char)val; break; /* \x and up to 3 hex digits */ case 'x': val = 'x'; /* Default if no digits */ c = hextoint(*s++); /* Get next char */ if (c >= 0) { val = c; c = hextoint(*s++); if (c >= 0) { val = (val << 4) + c; c = hextoint(*s++); if (c >= 0) { val = (val << 4) + c; } else --s; } else --s; } else --s; *p++ = (char)val; break; } } else *p++ = (char)c; } out: *p = '\0'; *slen = p - origp; return s; } /* Single hex char to int; -1 if not a hex char. */ static int hextoint(c) int c; { if (!isascii((unsigned char) c)) return -1; if (isdigit((unsigned char) c)) return c - '0'; if ((c>='a')&&(c<='f')) return c + 10 - 'a'; if ((c>='A')&&(c<='F')) return c + 10 - 'A'; return -1; } /* * Print a string containing C character escapes. */ void showstr(fp, s, len) FILE *fp; const char *s; int len; { register char c; for (;;) { c = *s++; if (len == -1) { if (c == '\0') break; } else { if (len-- == 0) break; } if(c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */ (void) fputc(c, fp); else { (void) fputc('\\', fp); switch (c) { case '\n': (void) fputc('n', fp); break; case '\r': (void) fputc('r', fp); break; case '\b': (void) fputc('b', fp); break; case '\t': (void) fputc('t', fp); break; case '\f': (void) fputc('f', fp); break; case '\v': (void) fputc('v', fp); break; default: (void) fprintf(fp, "%.3o", c & 0377); break; } } } +} + +/* + * eatsize(): Eat the size spec from a number [eg. 10UL] + */ +static void +eatsize(p) +char **p; +{ + char *l = *p; + + if (LOWCASE(*l) == 'u') + l++; + + switch (LOWCASE(*l)) { + case 'l': /* long */ + case 's': /* short */ + case 'h': /* short */ + case 'b': /* char/byte */ + case 'c': /* char/byte */ + l++; + /*FALLTHROUGH*/ + default: + break; + } + + *p = l; } Index: head/usr.bin/file/ascmagic.c =================================================================== --- head/usr.bin/file/ascmagic.c (revision 13586) +++ head/usr.bin/file/ascmagic.c (revision 13587) @@ -1,120 +1,123 @@ /* - * Ascii magic -- file types that we know based on keywords + * ASCII magic -- file types that we know based on keywords * that can appear anywhere in the file. * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #include #include #include #include #include #include "file.h" #include "names.h" #ifndef lint static char *moduleid = - "@(#)$Id: ascmagic.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $"; + "@(#)$Id: ascmagic.c,v 1.2 1995/05/30 06:29:59 rgrimes Exp $"; #endif /* lint */ /* an optimisation over plain strcmp() */ #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0) int ascmagic(buf, nbytes) unsigned char *buf; int nbytes; /* size actually read */ { - int i, isblock, has_escapes = 0; + int i, has_escapes = 0; unsigned char *s; char nbuf[HOWMANY+1]; /* one extra for terminating '\0' */ char *token; register struct names *p; - /* these are easy, do them first */ + /* + * Do the tar test first, because if the first file in the tar + * archive starts with a dot, we can confuse it with an nroff file. + */ + switch (is_tar(buf, nbytes)) { + case 1: + ckfputs("tar archive", stdout); + return 1; + case 2: + ckfputs("POSIX tar archive", stdout); + return 1; + } /* * for troff, look for . + letter + letter or .\"; * this must be done to disambiguate tar archives' ./file * and other trash from real troff input. */ if (*buf == '.') { unsigned char *tp = buf + 1; while (isascii(*tp) && isspace(*tp)) ++tp; /* skip leading whitespace */ if ((isascii(*tp) && (isalnum(*tp) || *tp=='\\') && - isascii(*(tp+1)) && (isalnum(*(tp+1)) || *tp=='"'))) { + isascii(tp[1]) && (isalnum(tp[1]) || tp[1] == '"'))) { ckfputs("troff or preprocessor input text", stdout); return 1; } } - if ((*buf == 'c' || *buf == 'C') && - isascii(*(buf + 1)) && isspace(*(buf + 1))) { + if ((*buf == 'c' || *buf == 'C') && + isascii(buf[1]) && isspace(buf[1])) { ckfputs("fortran program text", stdout); return 1; } /* look for tokens from names.h - this is expensive! */ /* make a copy of the buffer here because strtok() will destroy it */ s = (unsigned char*) memcpy(nbuf, buf, nbytes); s[nbytes] = '\0'; has_escapes = (memchr(s, '\033', nbytes) != NULL); - while ((token = strtok((char*)s, " \t\n\r\f")) != NULL) { + while ((token = strtok((char *) s, " \t\n\r\f")) != NULL) { s = NULL; /* make strtok() keep on tokin' */ for (p = names; p < names + NNAMES; p++) { if (STREQ(p->name, token)) { ckfputs(types[p->type], stdout); if (has_escapes) ckfputs(" (with escape sequences)", stdout); return 1; } } } - switch (is_tar(buf, nbytes)) { - case 1: - ckfputs("tar archive", stdout); - return 1; - case 2: - ckfputs("POSIX tar archive", stdout); - return 1; - } for (i = 0; i < nbytes; i++) { - if (!isascii(*(buf+i))) - return 0; /* not all ascii */ + if (!isascii(buf[i])) + return 0; /* not all ASCII */ } - /* all else fails, but it is ascii... */ - ckfputs("ascii text", stdout); + /* all else fails, but it is ASCII... */ + ckfputs("ASCII text", stdout); if (has_escapes) { ckfputs(" (with escape sequences)", stdout); } return 1; } Index: head/usr.bin/file/compress.c =================================================================== --- head/usr.bin/file/compress.c (revision 13586) +++ head/usr.bin/file/compress.c (revision 13587) @@ -1,125 +1,122 @@ /* * compress routines: * zmagic() - returns 0 if not recognized, uncompresses and prints * information if recognized * uncompress(method, old, n, newch) - uncompress old into new, * using method, return sizeof new - * $Id: compress.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $ + * $Id: compress.c,v 1.2 1995/05/30 06:30:00 rgrimes Exp $ */ #include #include #include #include #include #include "file.h" static struct { char *magic; int maglen; char *argv[3]; int silent; } compr[] = { - { "\037\235", 2, { "uncompress", "-c", NULL }, 0 }, - { "\037\213", 2, { "gzip", "-dq", NULL }, 1 }, - /* - * XXX pcat does not work, cause I don't know how to make it read stdin, - * so we use gzip - */ - { "\037\036", 2, { "gzip", "-dq", NULL }, 0 }, + { "\037\235", 2, { "uncompress", "-c", NULL }, 0 }, /* compressed */ + { "\037\213", 2, { "gzip", "-cdq", NULL }, 1 }, /* gzipped */ + { "\037\236", 2, { "gzip", "-cdq", NULL }, 1 }, /* frozen */ + { "\037\240", 2, { "gzip", "-cdq", NULL }, 1 }, /* SCO LZH */ + /* the standard pack utilities do not accept standard input */ + { "\037\036", 2, { "gzip", "-cdq", NULL }, 0 }, /* packed */ }; static int ncompr = sizeof(compr) / sizeof(compr[0]); static int uncompress __P((int, const unsigned char *, unsigned char **, int)); int zmagic(buf, nbytes) unsigned char *buf; int nbytes; { unsigned char *newbuf; int newsize; int i; for (i = 0; i < ncompr; i++) { if (nbytes < compr[i].maglen) continue; if (memcmp(buf, compr[i].magic, compr[i].maglen) == 0) break; } if (i == ncompr) return 0; if ((newsize = uncompress(i, buf, &newbuf, nbytes)) != 0) { tryit(newbuf, newsize, 1); free(newbuf); printf(" ("); tryit(buf, nbytes, 0); printf(")"); } return 1; } static int uncompress(method, old, newch, n) int method; const unsigned char *old; unsigned char **newch; int n; { int fdin[2], fdout[2]; if (pipe(fdin) == -1 || pipe(fdout) == -1) { error("cannot create pipe (%s).\n", strerror(errno)); /*NOTREACHED*/ } switch (fork()) { case 0: /* child */ (void) close(0); (void) dup(fdin[0]); (void) close(fdin[0]); (void) close(fdin[1]); (void) close(1); (void) dup(fdout[1]); (void) close(fdout[0]); (void) close(fdout[1]); if (compr[method].silent) (void) close(2); execvp(compr[method].argv[0], compr[method].argv); error("could not execute `%s' (%s).\n", compr[method].argv[0], strerror(errno)); /*NOTREACHED*/ case -1: error("could not fork (%s).\n", strerror(errno)); /*NOTREACHED*/ default: /* parent */ (void) close(fdin[0]); (void) close(fdout[1]); if (write(fdin[1], old, n) != n) { error("write failed (%s).\n", strerror(errno)); /*NOTREACHED*/ } (void) close(fdin[1]); if ((*newch = (unsigned char *) malloc(n)) == NULL) { error("out of memory.\n"); /*NOTREACHED*/ } if ((n = read(fdout[0], *newch, n)) <= 0) { free(*newch); error("read failed (%s).\n", strerror(errno)); /*NOTREACHED*/ } (void) close(fdout[0]); (void) wait(NULL); return n; } } - - Index: head/usr.bin/file/file.1 =================================================================== --- head/usr.bin/file/file.1 (revision 13586) +++ head/usr.bin/file/file.1 (revision 13587) @@ -1,351 +1,348 @@ .TH FILE 1 "Copyright but distributable" -.\# $Id: file.man,v 1.23 1993/09/24 18:50:48 christos Exp $ +.\# $Id: file.1,v 1.2 1994/09/03 19:31:15 csgr Exp $ .SH NAME -.I file +file \- determine file type .SH SYNOPSIS .B file [ -.B \-c +.B \-vczL ] [ -.B \-z -] -[ -.B \-L -] -[ .B \-f namefile ] [ .B \-m -magicfile ] +magicfiles ] file ... .SH DESCRIPTION .I File tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The .I first test that succeeds causes the file type to be printed. .PP The type printed will usually contain one of the words .B text (the file contains only ASCII characters and is probably safe to read on an ASCII terminal), .B executable (the file contains the result of compiling a program in a form understandable to some \s-1UNIX\s0 kernel or another), or .B data meaning anything else (data is usually `binary' or non-printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When modifying the file .I /etc/magic or the program itself, .B "preserve these keywords" . People depend on knowing that all the readable files in a directory have the word ``text'' printed. Don't do as Berkeley did \- change ``shell commands text'' to ``shell script''. .PP The filesystem tests are based on examining the return from a .IR stat (2) system call. The program checks to see if the file is empty, or if it's some sort of special file. Any known file types appropriate to the system you are running on (sockets, symbolic links, or named pipes (FIFOs) on those systems that implement them) are intuited if they are defined in the system header file .BR sys/stat.h . .PP The magic number tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) .B a.out file, whose format is defined in .B a.out.h and possibly .B exec.h in the standard include directory. These files have a `magic number' stored in a particular place near the beginning of the file that tells the \s-1UNIX\s0 operating system that the file is a binary executable, and which of several types thereof. The concept of `magic number' has been applied by extension to data files. Any file with some invariant identifier at a small fixed offset into the file can usually be described in this way. The information in these files is read from the magic file .I /etc/magic. .PP If an argument appears to be an .SM ASCII file, .I file attempts to guess its language. The language tests look for particular strings (cf \fInames.h\fP) that can appear anywhere in the first few blocks of a file. For example, the keyword .B .br indicates that the file is most likely a troff input file, just as the keyword .B struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last. The language test routines also test for some miscellany (such as .I tar archives) and determine whether an unknown file should be labelled as `ascii text' or `data'. -.PP -Use -.B \-m -.I file -to specify an alternate file of magic numbers. -.PP -The +.SH OPTIONS +.TP 8 +.B \-v +Print the version of the program and exit. +.TP 8 +.B \-m list +Specify an alternate list of files containing magic numbers. +This can be a single file, or a colon-separated list of files. +.TP 8 .B \-z -tries to look inside compressed files. -.PP -The +Try to look inside compressed files. +.TP 8 .B \-c -option causes a checking printout of the parsed form of the magic file. +Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction with .B \-m to debug a new magic file before installing it. -.PP -The -.B \-f +.TP 8 +.B \-f namefile +Read the names of the files to be examined from .I namefile -option specifies that the names of the files to be examined -are to be read (one per line) from -.I namefile +(one per line) before the argument list. Either .I namefile or at least one filename argument must be present; to test the standard input, use ``-'' as a filename argument. -.PP -The +.TP 8 .B \-L option causes symlinks to be followed, as the like-named option in .IR ls (1). +(on systems that support symbolic links). .SH FILES .I /etc/magic \- default list of magic numbers +.SH ENVIRONMENT +The environment variable +.B MAGIC +can be used to set the default magic number files. .SH SEE ALSO .IR magic (5) \- description of magic file format. .br .IR Strings (1), " od" (1) \- tools for examining non-textfiles. .SH STANDARDS CONFORMANCE This program is believed to exceed the System V Interface Definition of FILE(CMD), as near as one can determine from the vague language contained therein. Its behaviour is mostly compatible with the System V program of the same name. This version knows more magic, however, so it will produce different (albeit more accurate) output in many cases. .PP The one significant difference between this version and System V is that this version treats any white space as a delimiter, so that spaces in pattern strings must be escaped. For example, .br >10 string language impress\ (imPRESS data) .br in an existing magic file would have to be changed to .br >10 string language\e impress (imPRESS data) .br In addition, in this version, if a pattern string contains a backslash, it must be escaped. For example .br 0 string \ebegindata Andrew Toolkit document .br in an existing magic file would have to be changed to .br 0 string \e\ebegindata Andrew Toolkit document .br .PP SunOS releases 3.2 and later from Sun Microsystems include a .IR file (1) command derived from the System V one, but with some extensions. My version differs from Sun's only in minor ways. It includes the extension of the `&' operator, used as, for example, .br >16 long&0x7fffffff >0 not stripped .SH MAGIC DIRECTORY The magic file entries have been collected from various sources, mainly USENET, and contributed by various authors. Christos Zoulas (address below) will collect additional or corrected magic file entries. A consolidation of magic file entries will be distributed periodically. .PP The order of entries in the magic file is significant. Depending on what system you are using, the order that they are put together may be incorrect. If your old .I file command uses a magic file, keep the old magic file around for comparison purposes (rename it to .IR /etc/magic.orig ). .SH HISTORY There has been a .I file command in every UNIX since at least Research Version 6 (man page dated January, 1975). The System V version introduced one significant major change: the external list of magic number types. This slowed the program down slightly but made it a lot more flexible. .PP This program, based on the System V version, was written by Ian Darwin without looking at anybody else's source code. .PP John Gilmore revised the code extensively, making it better than the first version. Geoff Collyer found several inadequacies and provided some magic file entries. The program has undergone continued evolution since. .SH AUTHOR Written by Ian F. Darwin, UUCP address {utzoo | ihnp4}!darwin!ian, Internet address ian@sq.com, postal address: P.O. Box 603, Station F, Toronto, Ontario, CANADA M4Y 2L8. .PP Altered by Rob McMahon, cudcv@warwick.ac.uk, 1989, to extend the `&' operator from simple `x&y != 0' to `x&y op z'. .PP Altered by Guy Harris, guy@auspex.com, 1993, to: .RS .PP put the ``old-style'' `&' operator back the way it was, because 1) Rob McMahon's change broke the previous style of usage, 2) the SunOS ``new-style'' `&' operator, which this version of .I file supports, also handles `x&y op z', and 3) Rob's change wasn't documented in any case; .PP put in multiple levels of `>'; .PP put in ``beshort'', ``leshort'', etc. keywords to look at numbers in the file in a specific byte order, rather than in the native byte order of the process running .IR file . .RE .PP Changes by Ian Darwin and various authors including Christos Zoulas (christos@ee.cornell.edu), 1990-1992. .SH LEGAL NOTICE Copyright (c) Ian F. Darwin, Toronto, Canada, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993. .PP This software is not subject to and may not be made subject to any license of the American Telephone and Telegraph Company, Sun Microsystems Inc., Digital Equipment Inc., Lotus Development Inc., the Regents of the University of California, The X Consortium or MIT, or The Free Software Foundation. .PP This software is not subject to any export provision of the United States Department of Commerce, and may be exported to any country or planet. .PP Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it freely, subject to the following restrictions: .PP 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. .PP 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. .PP 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. .PP 4. This notice may not be removed or altered. .PP A few support files (\fIgetopt\fP, \fIstrtok\fP) distributed with this package are by Henry Spencer and are subject to the same terms as above. .PP A few simple support files (\fIstrtol\fP, \fIstrchr\fP) distributed with this package are in the public domain; they are so marked. .PP The files .I tar.h and .I is_tar.c were written by John Gilmore from his public-domain .I tar program, and are not covered by the above restrictions. .SH BUGS There must be a better way to automate the construction of the Magic file from all the glop in Magdir. What is it? Better yet, the magic file should be compiled into binary (say, .IR ndbm (3) or, better yet, fixed-length ASCII strings for use in heterogenous network environments) for faster startup. Then the program would run as fast as the Version 7 program of the same name, with the flexibility of the System V version. .PP .I File uses several algorithms that favor speed over accuracy, thus it can be misled about the contents of ASCII files. .PP The support for ASCII files (primarily for programming languages) is simplistic, inefficient and requires recompilation to update. .PP There should be an ``else'' clause to follow a series of continuation lines. .PP The magic file and keywords should have regular expression support. Their use of ASCII TAB as a field delimiter is ugly and makes it hard to edit the files, but is entrenched. .PP It might be advisable to allow upper-case letters in keywords for e.g., troff commands vs man page macros. Regular expression support would make this easy. .PP The program doesn't grok \s-2FORTRAN\s0. It should be able to figure \s-2FORTRAN\s0 by seeing some keywords which appear indented at the start of line. Regular expression support would make this easy. .PP The list of keywords in .I ascmagic probably belongs in the Magic file. This could be done by using some keyword like `*' for the offset value. .PP Another optimisation would be to sort the magic file so that we can just run down all the tests for the first byte, first word, first long, etc, once we have fetched it. Complain about conflicts in the magic file entries. Make a rule that the magic entries sort based on file offset rather than position within the magic file? .PP The program should provide a way to give an estimate of ``how good'' a guess is. We end up removing guesses (e.g. ``From '' as first 5 chars of file) because they are not as good as other guesses (e.g. ``Newsgroups:'' versus "Return-Path:"). Still, if the others don't pan out, it should be possible to use the first guess. .PP This program is slower than some vendors' file commands. .PP This manual page, and particularly this section, is too long. .SH AVAILABILITY You can obtain the original author's latest version by anonymous FTP on .B tesla.ee.cornell.edu in the directory .BR /pub/file-X.YY.tar.gz Index: head/usr.bin/file/file.c =================================================================== --- head/usr.bin/file/file.c (revision 13586) +++ head/usr.bin/file/file.c (revision 13587) @@ -1,276 +1,349 @@ /* * file - find type of a file or files - main program. * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #ifndef lint static char *moduleid = - "@(#)$Id: file.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $"; + "@(#)$Id: file.c,v 1.2 1995/05/30 06:30:01 rgrimes Exp $"; #endif /* lint */ #include #include #include #include #include /* for MAXPATHLEN */ #include #include /* for open() */ +#if (__COHERENT__ >= 0x420) +#include +#else #include +#endif #include /* for read() */ +#ifdef __ELF__ +#include +#endif + +#include "patchlevel.h" #include "file.h" #ifdef S_IFLNK -# define USAGE "Usage: %s [-czL] [-f namefile] [-m magicfile] file...\n" +# define USAGE "Usage: %s [-vczL] [-f namefile] [-m magicfiles] file...\n" #else -# define USAGE "Usage: %s [-cz] [-f namefile] [-m magicfile] file...\n" +# define USAGE "Usage: %s [-vcz] [-f namefile] [-m magicfiles] file...\n" #endif #ifndef MAGIC # define MAGIC "/etc/magic" #endif int /* Global command-line options */ debug = 0, /* debugging */ lflag = 0, /* follow Symlinks (BSD only) */ zflag = 0; /* follow (uncompress) compressed files */ int /* Misc globals */ nmagic = 0; /* number of valid magic[]s */ struct magic *magic; /* array of magic entries */ -char *magicfile = MAGIC;/* where magic be found */ +char *magicfile; /* where magic be found */ char *progname; /* used throughout */ int lineno; /* line number in the magic file */ static void unwrap __P((char *fn)); /* * main - parse arguments and handle options */ int main(argc, argv) int argc; char *argv[]; { int c; - int check = 0, didsomefiles = 0, errflg = 0, ret = 0; + int check = 0, didsomefiles = 0, errflg = 0, ret = 0, app = 0; if ((progname = strrchr(argv[0], '/')) != NULL) progname++; else progname = argv[0]; - while ((c = getopt(argc, argv, "cdf:Lm:z")) != EOF) + if (!(magicfile = getenv("MAGIC"))) + magicfile = MAGIC; + + while ((c = getopt(argc, argv, "vcdf:Lm:z")) != EOF) switch (c) { + case 'v': + (void) fprintf(stdout, "%s-%d.%d\n", progname, + FILE_VERSION_MAJOR, patchlevel); + return 1; case 'c': ++check; break; case 'd': ++debug; break; case 'f': + if (!app) { + ret = apprentice(magicfile, check); + if (check) + exit(ret); + app = 1; + } unwrap(optarg); ++didsomefiles; break; #ifdef S_IFLNK case 'L': ++lflag; break; #endif case 'm': magicfile = optarg; break; case 'z': zflag++; break; case '?': default: errflg++; break; } + if (errflg) { (void) fprintf(stderr, USAGE, progname); exit(2); } - ret = apprentice(magicfile, check); - if (check) - exit(ret); + if (!app) { + ret = apprentice(magicfile, check); + if (check) + exit(ret); + app = 1; + } if (optind == argc) { if (!didsomefiles) { (void)fprintf(stderr, USAGE, progname); exit(2); } } else { int i, wid, nw; for (wid = 0, i = optind; i < argc; i++) { nw = strlen(argv[i]); if (nw > wid) wid = nw; } for (; optind < argc; optind++) process(argv[optind], wid); } return 0; } /* * unwrap -- read a file of filenames, do each one. */ static void unwrap(fn) char *fn; { char buf[MAXPATHLEN]; FILE *f; int wid = 0, cwid; if ((f = fopen(fn, "r")) == NULL) { error("Cannot open `%s' (%s).\n", fn, strerror(errno)); /*NOTREACHED*/ } while (fgets(buf, MAXPATHLEN, f) != NULL) { cwid = strlen(buf) - 1; if (cwid > wid) wid = cwid; } rewind(f); while (fgets(buf, MAXPATHLEN, f) != NULL) { buf[strlen(buf)-1] = '\0'; process(buf, wid); } (void) fclose(f); } /* * process - process input file */ void process(inname, wid) const char *inname; int wid; { int fd = 0; static const char stdname[] = "standard input"; unsigned char buf[HOWMANY+1]; /* one extra for terminating '\0' */ struct utimbuf utbuf; struct stat sb; int nbytes = 0; /* number of bytes read from a datafile */ + char match = '\0'; if (strcmp("-", inname) == 0) { if (fstat(0, &sb)<0) { error("cannot fstat `%s' (%s).\n", stdname, strerror(errno)); /*NOTREACHED*/ } inname = stdname; } if (wid > 0) (void) printf("%s:%*s ", inname, (int) (wid - strlen(inname)), ""); if (inname != stdname) { /* * first try judging the file based on its filesystem status */ if (fsmagic(inname, &sb) != 0) { putchar('\n'); return; } if ((fd = open(inname, O_RDONLY)) < 0) { /* We can't open it, but we were able to stat it. */ if (sb.st_mode & 0002) ckfputs("writeable, ", stdout); if (sb.st_mode & 0111) ckfputs("executable, ", stdout); ckfprintf(stdout, "can't read `%s' (%s).\n", inname, strerror(errno)); return; } } /* * try looking at the first HOWMANY bytes */ if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) { error("read failed (%s).\n", strerror(errno)); /*NOTREACHED*/ } if (nbytes == 0) ckfputs("empty", stdout); else { buf[nbytes++] = '\0'; /* null-terminate it */ - tryit(buf, nbytes, zflag); + match = tryit(buf, nbytes, zflag); } +#ifdef __ELF__ + /* + * ELF executables have multiple section headers in arbitrary + * file locations and thus file(1) cannot determine it from easily. + * Instead we traverse thru all section headers until a symbol table + * one is found or else the binary is stripped. + * XXX: This will not work for binaries of a different byteorder. + * Should come up with a better fix. + */ + if (match == 's' && nbytes > sizeof (Elf32_Ehdr) && + buf[EI_MAG0] == ELFMAG0 && + buf[EI_MAG1] == ELFMAG1 && + buf[EI_MAG2] == ELFMAG2 && + buf[EI_MAG3] == ELFMAG3) { + + union { + long l; + char c[sizeof (long)]; + } u; + Elf32_Ehdr elfhdr; + int stripped = 1; + + u.l = 1; + (void) memcpy(&elfhdr, buf, sizeof elfhdr); + + /* + * If the system byteorder does not equal the object byteorder + * then don't test. + */ + if ((u.c[sizeof(long) - 1] + 1) == elfhdr.e_ident[5]) { + if (lseek(fd, elfhdr.e_shoff, SEEK_SET)<0) + error("lseek failed (%s).\n", strerror(errno)); + + for ( ; elfhdr.e_shnum ; elfhdr.e_shnum--) { + if (read(fd, buf, elfhdr.e_shentsize)<0) + error("read failed (%s).\n", strerror(errno)); + if (((Elf32_Shdr *)&buf)->sh_type == SHT_SYMTAB) { + stripped = 0; + break; + } + } + if (stripped) + (void) printf (", stripped"); + } + } +#endif + if (inname != stdname) { /* * Try to restore access, modification times if read it. */ utbuf.actime = sb.st_atime; utbuf.modtime = sb.st_mtime; (void) utime(inname, &utbuf); /* don't care if loses */ (void) close(fd); } (void) putchar('\n'); } -void +int tryit(buf, nb, zflag) unsigned char *buf; int nb, zflag; { - /* - * Try compression stuff - */ - if (!zflag || zmagic(buf, nb) != 1) - /* - * try tests in /etc/magic (or surrogate magic file) - */ - if (softmagic(buf, nb) != 1) - /* - * try known keywords, check for ascii-ness too. - */ - if (ascmagic(buf, nb) != 1) - /* - * abandon hope, all ye who remain here - */ - ckfputs("data", stdout); + /* try compression stuff */ + if (zflag && zmagic(buf, nb)) + return 'z'; + + /* try tests in /etc/magic (or surrogate magic file) */ + if (softmagic(buf, nb)) + return 's'; + + /* try known keywords, check whether it is ASCII */ + if (ascmagic(buf, nb)) + return 'a'; + + /* abandon hope, all ye who remain here */ + ckfputs("data", stdout); + return '\0'; } Index: head/usr.bin/file/file.h =================================================================== --- head/usr.bin/file/file.h (revision 13586) +++ head/usr.bin/file/file.h (revision 13587) @@ -1,128 +1,131 @@ /* * file.h - definitions for file(1) program - * @(#)$Id: file.h,v 1.1.1.1 1994/09/03 19:16:23 csgr Exp $ + * @(#)$Id: file.h,v 1.2 1995/05/30 06:30:02 rgrimes Exp $ * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ -#define HOWMANY 8192 /* how much of the file to look at */ +#ifndef HOWMANY +# define HOWMANY 8192 /* how much of the file to look at */ +#endif #define MAXMAGIS 1000 /* max entries in /etc/magic */ #define MAXDESC 50 /* max leng of text description */ #define MAXstring 32 /* max leng of "string" types */ struct magic { short flag; #define INDIR 1 /* if '>(...)' appears, */ #define UNSIGNED 2 /* comparison is unsigned */ short cont_level; /* level of ">" */ struct { char type; /* byte short long */ long offset; /* offset from indirection */ } in; long offset; /* offset to magic number */ unsigned char reln; /* relation (0=eq, '>'=gt, etc) */ char type; /* int, short, long or string. */ char vallen; /* length of string value, if any */ #define BYTE 1 #define SHORT 2 #define LONG 4 #define STRING 5 #define DATE 6 #define BESHORT 7 #define BELONG 8 #define BEDATE 9 #define LESHORT 10 #define LELONG 11 #define LEDATE 12 union VALUETYPE { unsigned char b; unsigned short h; unsigned long l; char s[MAXstring]; unsigned char hs[2]; /* 2 bytes of a fixed-endian "short" */ unsigned char hl[4]; /* 2 bytes of a fixed-endian "long" */ } value; /* either number or string */ unsigned long mask; /* mask before comparison with value */ char nospflag; /* supress space character */ char desc[MAXDESC]; /* description */ }; #include /* Include that here, to make sure __P gets defined */ #ifndef __P # if __STDC__ || __cplusplus # define __P(a) a # else # define __P(a) () # define const # endif #endif extern int apprentice __P((char *, int)); extern int ascmagic __P((unsigned char *, int)); extern void error __P((const char *, ...)); extern void ckfputs __P((const char *, FILE *)); struct stat; extern int fsmagic __P((const char *, struct stat *)); extern int is_compress __P((const unsigned char *, int *)); extern int is_tar __P((unsigned char *, int)); extern void magwarn __P((const char *, ...)); extern void mdump __P((struct magic *)); extern void process __P((const char *, int)); extern void showstr __P((FILE *, const char *, int)); extern int softmagic __P((unsigned char *, int)); -extern void tryit __P((unsigned char *, int, int)); +extern int tryit __P((unsigned char *, int, int)); extern int zmagic __P((unsigned char *, int)); extern void ckfprintf __P((FILE *, const char *, ...)); extern unsigned long signextend __P((struct magic *, unsigned long)); extern int errno; /* Some unixes don't define this.. */ extern char *progname; /* the program name */ extern char *magicfile; /* name of the magic file */ extern int lineno; /* current line number in magic file */ extern struct magic *magic; /* array of magic entries */ extern int nmagic; /* number of valid magic[]s */ extern int debug; /* enable debugging? */ extern int zflag; /* process compressed files? */ extern int lflag; /* follow symbolic links? */ extern int optind; /* From getopt(3) */ extern char *optarg; #if !defined(__STDC__) || defined(sun) || defined(__sun__) || defined(__convex__) extern int sys_nerr; extern char *sys_errlist[]; #define strerror(e) \ (((e) >= 0 && (e) < sys_nerr) ? sys_errlist[(e)] : "Unknown error") +#define strtoul(a, b, c) strtol(a, b, c) #endif #ifndef MAXPATHLEN #define MAXPATHLEN 512 #endif Index: head/usr.bin/file/fsmagic.c =================================================================== --- head/usr.bin/file/fsmagic.c (revision 13586) +++ head/usr.bin/file/fsmagic.c (revision 13587) @@ -1,174 +1,176 @@ /* * fsmagic - magic based on filesystem info - directory, special files, etc. * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #include #include #include #include #include #include #ifndef major /* if `major' not defined in types.h, */ #include /* try this one. */ #endif #ifndef major /* still not defined? give up, manual intervention needed */ /* If cc tries to compile this, read and act on it. */ /* On most systems cpp will discard it automatically */ Congratulations, you have found a portability bug. Please grep /usr/include/sys and edit the above #include to point at the file that defines the "major" macro. #endif /*major*/ #include "file.h" #ifndef lint static char *moduleid = - "@(#)$Id: fsmagic.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $"; + "@(#)$Id: fsmagic.c,v 1.2 1995/05/30 06:30:03 rgrimes Exp $"; #endif /* lint */ int fsmagic(fn, sb) const char *fn; struct stat *sb; { int ret = 0; /* * Fstat is cheaper but fails for files you don't have read perms on. * On 4.2BSD and similar systems, use lstat() to identify symlinks. */ #ifdef S_IFLNK if (!lflag) ret = lstat(fn, sb); else #endif ret = stat(fn, sb); /* don't merge into if; see "ret =" above */ if (ret) { ckfprintf(stdout, /* Yes, I do mean stdout. */ /* No \n, caller will provide. */ "can't stat `%s' (%s).", fn, strerror(errno)); return 1; } if (sb->st_mode & S_ISUID) ckfputs("setuid ", stdout); if (sb->st_mode & S_ISGID) ckfputs("setgid ", stdout); if (sb->st_mode & S_ISVTX) ckfputs("sticky ", stdout); switch (sb->st_mode & S_IFMT) { case S_IFDIR: ckfputs("directory", stdout); return 1; case S_IFCHR: (void) printf("character special (%d/%d)", major(sb->st_rdev), minor(sb->st_rdev)); return 1; case S_IFBLK: (void) printf("block special (%d/%d)", major(sb->st_rdev), minor(sb->st_rdev)); return 1; /* TODO add code to handle V7 MUX and Blit MUX files */ #ifdef S_IFIFO case S_IFIFO: ckfputs("fifo (named pipe)", stdout); return 1; #endif #ifdef S_IFLNK case S_IFLNK: { char buf[BUFSIZ+4]; register int nch; struct stat tstatbuf; if ((nch = readlink(fn, buf, BUFSIZ-1)) <= 0) { ckfprintf(stdout, "unreadable symlink (%s).", strerror(errno)); return 1; } buf[nch] = '\0'; /* readlink(2) forgets this */ /* If broken symlink, say so and quit early. */ if (*buf == '/') { if (stat(buf, &tstatbuf) < 0) { ckfprintf(stdout, "broken symbolic link to %s", buf); return 1; } } else { char *tmp; char buf2[BUFSIZ+BUFSIZ+4]; if ((tmp = strrchr(fn, '/')) == NULL) { tmp = buf; /* in current directory anyway */ } else { strcpy (buf2, fn); /* take directory part */ buf2[tmp-fn+1] = '\0'; strcat (buf2, buf); /* plus (relative) symlink */ tmp = buf2; } if (stat(tmp, &tstatbuf) < 0) { ckfprintf(stdout, "broken symbolic link to %s", buf); return 1; } } /* Otherwise, handle it. */ if (lflag) { process(buf, strlen(buf)); return 1; } else { /* just print what it points to */ ckfputs("symbolic link to ", stdout); ckfputs(buf, stdout); } } return 1; #endif #ifdef S_IFSOCK +#ifndef __COHERENT__ case S_IFSOCK: ckfputs("socket", stdout); return 1; +#endif #endif case S_IFREG: break; default: error("invalid mode 0%o.\n", sb->st_mode); /*NOTREACHED*/ } /* * regular file, check next possibility */ if (sb->st_size == 0) { ckfputs("empty", stdout); return 1; } return 0; } Index: head/usr.bin/file/magic.5 =================================================================== --- head/usr.bin/file/magic.5 (revision 13586) +++ head/usr.bin/file/magic.5 (revision 13587) @@ -1,194 +1,194 @@ .TH MAGIC 5 "Public Domain" .\" install as magic.4 on USG, magic.5 on V7 or Berkeley systems. .SH NAME magic \- file command's magic number file .SH DESCRIPTION The .IR file (1) command identifies the type of a file using, among other tests, a test for whether the file begins with a certain .IR "magic number" . The file .B /etc/magic specifies what magic numbers are to be tested for, what message to print if a particular magic number is found, and additional information to extract from the file. .PP Each line of the file specifies a test to be performed. A test compares the data starting at a particular offset in the file with a 1-byte, 2-byte, or 4-byte numeric value or a string. If the test succeeds, a message is printed. The line consists of the following fields: .IP offset \w'message'u+2n A number specifying the offset, in bytes, into the file of the data which is to be tested. .IP type The type of the data to be tested. The possible values are: .RS .IP byte \w'message'u+2n A one-byte value. .IP short A two-byte value (on most systems) in this machine's native byte order. .IP long A four-byte value (on most systems) in this machine's native byte order. .IP string A string of bytes. .IP date A four-byte value interpreted as a unix date. .IP beshort A two-byte value (on most systems) in big-endian byte order. .IP belong A four-byte value (on most systems) in big-endian byte order. .IP bedate A four-byte value (on most systems) in big-endian byte order, interpreted as a unix date. .IP leshort A two-byte value (on most systems) in little-endian byte order. .IP lelong A four-byte value (on most systems) in little-endian byte order. .IP ledate A four-byte value (on most systems) in little-endian byte order, interpreted as a unix date. .RE .PP The numeric types may optionally be followed by .B & and a numeric value, to specify that the value is to be AND'ed with the numeric value before any comparisons are done. Prepending a .B u to the type indicates that ordered comparisons should be unsigned. .IP test The value to be compared with the value from the file. If the type is numeric, this value is specified in C form; if it is a string, it is specified as a C string with the usual escapes permitted (e.g. \en for new-line). .IP Numeric values may be preceded by a character indicating the operation to be performed. It may be .BR = , to specify that the value from the file must equal the specified value, .BR < , to specify that the value from the file must be less than the specified value, .BR > , to specify that the value from the file must be greater than the specified value, .BR & , to specify that the value from the file must have set all of the bits that are set in the specified value, -or .BR ^ , to specify that the value from the file must have clear any of the bits -that are set in the specified value. +that are set in the specified value, or +.BR x , +to specify that any value will match. If the character is omitted, +it is assumed to be +.BR = . .IP Numeric values are specified in C form; e.g. .B 13 is decimal, .B 013 is octal, and .B 0x13 is hexadecimal. -to specify that any value will match. If the character -is omitted, it is assumed to be -.BR = . .IP For string values, the byte string from the file must match the specified byte string. The operators .BR = , .B < and .B > (but not .BR & ) can be applied to strings. The length used for matching is that of the string argument in the magic file. This means that a line can match any string, and then presumably print that string, by doing .B >\e0 (because all strings are greater than the null string). .IP message The message to be printed if the comparison succeeds. If the string contains a .IR printf (3S) format specification, the value from the file (with any specified masking performed) is printed using the message as the format string. .PP Some file formats contain additional information which is to be printed along with the file type. A line which begins with the character .B > indicates additional tests and messages to be printed. The number of .B > on the line indicates the level of the test; a line with no .B > at the beginning is considered to be at level 0. Each line at level .IB n \(pl1 is under the control of the line at level .IB n most closely preceding it in the magic file. If the test on a line at level .I n succeeds, the tests specified in all the subsequent lines at level .IB n \(pl1 are performed, and the messages printed if the tests succeed. The next line at level .I n terminates this. If the first character following the last .B > is a .B ( then the string after the parenthesis is interpreted as an indirect offset. -That means that the number after the parenthesis is used as a offset in +That means that the number after the parenthesis is used as an offset in the file. The value at that offset is read, and is used again as an offset in the file. Indirect offsets are of the form: .BI (( x [.[bsl]][+-][ y ]). The value of .I x is used as an offset in the file. A byte, short or long is read at that offset depending on the .B [bsl] type specifier. To that number the value of .I y is added and the result is used as an offset in the file. The default type if one is not specified is long. .SH BUGS The formats .IR long , .IR belong , .IR lelong , .IR short , .IR beshort , .IR leshort , .IR date , .IR bedate , and .I ledate -are system-dependant; perhaps they should be specified as a number +are system-dependent; perhaps they should be specified as a number of bytes (2B, 4B, etc), since the files being recognized typically come from a system on which the lengths are invariant. .PP There is (currently) no support for specified-endian data to be used in indirect offsets. .SH SEE ALSO .IR file (1) \- the command that reads this file. .\" .\" From: guy@sun.uucp (Guy Harris) .\" Newsgroups: net.bugs.usg .\" Subject: /etc/magic's format isn't well documented .\" Message-ID: <2752@sun.uucp> .\" Date: 3 Sep 85 08:19:07 GMT .\" Organization: Sun Microsystems, Inc. .\" Lines: 136 .\" .\" Here's a manual page for the format accepted by the "file" made by adding .\" the changes I posted to the S5R2 version. .\" .\" Modified for Ian Darwin's version of the file command. -.\" @(#)$Id: magic.man,v 1.11 1994/05/03 17:58:23 christos Exp $ +.\" @(#)$Id: magic.5,v 1.2 1994/09/03 19:31:16 csgr Exp $ Index: head/usr.bin/file/names.h =================================================================== --- head/usr.bin/file/names.h (revision 13586) +++ head/usr.bin/file/names.h (revision 13587) @@ -1,91 +1,91 @@ /* * Names.h - names and types used by ascmagic in file(1). * These tokens are here because they can appear anywhere in * the first HOWMANY bytes, while tokens in /etc/magic must * appear at fixed offsets into the file. Don't make HOWMANY * too high unless you have a very fast CPU. * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * See LEGAL.NOTICE * - * $Id: names.h,v 1.12 1995/04/28 17:29:13 christos Exp $ + * $Id: names.h,v 1.1.1.2 1996/01/22 22:31:42 mpp Exp $ */ /* these types are used to index the table 'types': keep em in sync! */ #define L_C 0 /* first and foremost on UNIX */ #define L_FORT 1 /* the oldest one */ #define L_MAKE 2 /* Makefiles */ #define L_PLI 3 /* PL/1 */ #define L_MACH 4 /* some kinda assembler */ #define L_ENG 5 /* English */ #define L_PAS 6 /* Pascal */ #define L_MAIL 7 /* Electronic mail */ #define L_NEWS 8 /* Usenet Netnews */ static char *types[] = { "C program text", "FORTRAN program text", "make commands text" , "PL/1 program text", "assembler program text", "English text", "Pascal program text", "mail text", "news text", "can't happen error on names.h/types", 0}; static struct names { char *name; short type; } names[] = { /* These must be sorted by eye for optimal hit rate */ /* Add to this list only after substantial meditation */ {"/*", L_C}, /* must precede "The", "the", etc. */ {"#include", L_C}, {"char", L_C}, {"The", L_ENG}, {"the", L_ENG}, {"double", L_C}, {"extern", L_C}, {"float", L_C}, {"real", L_C}, {"struct", L_C}, {"union", L_C}, {"CFLAGS", L_MAKE}, {"LDFLAGS", L_MAKE}, {"all:", L_MAKE}, {".PRECIOUS", L_MAKE}, /* Too many files of text have these words in them. Find another way * to recognize Fortrash. */ #ifdef NOTDEF {"subroutine", L_FORT}, {"function", L_FORT}, {"block", L_FORT}, {"common", L_FORT}, {"dimension", L_FORT}, {"integer", L_FORT}, {"data", L_FORT}, #endif /*NOTDEF*/ {".ascii", L_MACH}, {".asciiz", L_MACH}, {".byte", L_MACH}, {".even", L_MACH}, {".globl", L_MACH}, {".text", L_MACH}, {"clr", L_MACH}, {"(input,", L_PAS}, {"dcl", L_PLI}, {"Received:", L_MAIL}, {">From", L_MAIL}, {"Return-Path:",L_MAIL}, {"Cc:", L_MAIL}, {"Newsgroups:", L_NEWS}, {"Path:", L_NEWS}, {"Organization:",L_NEWS}, {NULL, 0} }; #define NNAMES ((sizeof(names)/sizeof(struct names)) - 1) Index: head/usr.bin/file/patchlevel.h =================================================================== --- head/usr.bin/file/patchlevel.h (revision 13586) +++ head/usr.bin/file/patchlevel.h (revision 13587) @@ -1,63 +1,101 @@ #define FILE_VERSION_MAJOR 3 -#define patchlevel 14 +#define patchlevel 19 /* * Patchlevel file for Ian Darwin's MAGIC command. - * $Id: patchlevel.h,v 1.1.1.1 1994/09/03 19:16:23 csgr Exp $ + * $Id: patchlevel.h,v 1.2 1995/05/30 06:30:06 rgrimes Exp $ * * $Log: patchlevel.h,v $ + * Revision 1.2 1995/05/30 06:30:06 rgrimes + * Remove trailing whitespace. + * + * Revision 1.1.1.2 1996/01/22 22:31:44 mpp + * Upgrade to file version 3.19. + * * Revision 1.1.1.1 1994/09/03 19:16:23 csgr * Bring in file 3.14 by Ian Darwin (and Christos Zoulas) * * The following files were moved to different names: * - file.man -> file.1 * - magic.man -> magic.5 * * The following file was removed: * - Magdir/Makefile + * + * Revision 1.19 1995/10/27 23:14:46 christos + * Ability to parse colon separated list of magic files + * New LEGAL.NOTICE + * Various magic file changes + * + * Revision 1.18 1995/05/20 22:09:21 christos + * Passed incorrect argument to eatsize(). + * Use %ld and %lx where appropriate. + * Remove unused variables + * ELF support for both big and little endian + * Fixes for small files again. + * + * Revision 1.17 1995/04/28 17:29:13 christos + * - Incorrect nroff detection fix from der Mouse + * - Lost and incorrect magic entries. + * - Added ELF stripped binary detection [in C; ugh] + * - Look for $MAGIC to find the magic file. + * - Eat trailing size specifications from numbers i.e. ignore 10L + * - More fixes for very short files + * + * Revision 1.16 1995/03/25 22:06:45 christos + * - use strtoul() where it exists. + * - fix sign-extend bug + * - try to detect tar archives before nroff files, otherwise + * tar files where the first file starts with a . will not work + * + * Revision 1.15 1995/01/21 21:03:35 christos + * Added CSECTION for the file man page + * Added version flag -v + * Fixed bug with -f input flag (from iorio@violet.berkeley.edu) + * Lots of magic fixes and reorganization... * * Revision 1.14 1994/05/03 17:58:23 christos * changes from mycroft@gnu.ai.mit.edu (Charles Hannum) for unsigned * * Revision 1.13 1994/01/21 01:27:01 christos * Fixed null termination bug from Don Seeley at BSDI in ascmagic.c * * Revision 1.12 1993/10/27 20:59:05 christos * Changed -z flag to understand gzip format too. * Moved builtin compression detection to a table, and move * the compress magic entry out of the source. * Made printing of numbers unsigned, and added the mask to it. * Changed the buffer size to 8k, because gzip will refuse to * unzip just a few bytes. * * Revision 1.11 1993/09/24 18:49:06 christos * Fixed small bug in softmagic.c introduced by * copying the data to be examined out of the input * buffer. Changed the Makefile to use sed to create * the correct man pages. * * Revision 1.10 1993/09/23 21:56:23 christos * Passed purify. Fixed indirections. Fixed byte order printing. * Fixed segmentation faults caused by referencing past the end * of the magic buffer. Fixed bus errors caused by referencing * unaligned shorts or longs. * * Revision 1.9 1993/03/24 14:23:40 ian * Batch of minor changes from several contributors. * * Revision 1.8 93/02/19 15:01:26 ian * Numerous changes from Guy Harris too numerous to mention but including * byte-order independance, fixing "old-style masking", etc. etc. A bugfix * for broken symlinks from martin@@d255s004.zfe.siemens.de. * * Revision 1.7 93/01/05 14:57:27 ian * Couple of nits picked by Christos (again, thanks). * * Revision 1.6 93/01/05 13:51:09 ian * Lotsa work on the Magic directory. * * Revision 1.5 92/09/14 14:54:51 ian * Fix a tiny null-pointer bug in previous fix for tar archive + uncompress. * */ Index: head/usr.bin/file/print.c =================================================================== --- head/usr.bin/file/print.c (revision 13586) +++ head/usr.bin/file/print.c (revision 13587) @@ -1,204 +1,204 @@ /* * print.c - debugging printout routines * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #include #include #include #if __STDC__ # include #else # include #endif #include #include #include #include "file.h" #ifndef lint static char *moduleid = - "@(#)$Id: print.c,v 1.1.1.1 1994/09/03 19:16:22 csgr Exp $"; + "@(#)$Id: print.c,v 1.2 1995/05/30 06:30:08 rgrimes Exp $"; #endif /* lint */ #define SZOF(a) (sizeof(a) / sizeof(a[0])) void mdump(m) struct magic *m; { static char *typ[] = { "invalid", "byte", "short", "invalid", "long", "string", "date", "beshort", "belong", "bedate", "leshort", "lelong", "ledate" }; (void) fputc('[', stderr); (void) fprintf(stderr, ">>>>>>>> %d" + 8 - (m->cont_level & 7), m->offset); if (m->flag & INDIR) - (void) fprintf(stderr, "(%s,%d),", - (m->in.type >= 0 && m->in.type < SZOF(typ)) ? + (void) fprintf(stderr, "(%s,%ld),", + (m->in.type >= 0 && m->in.type < SZOF(typ)) ? typ[(unsigned char) m->in.type] : "*bad*", m->in.offset); (void) fprintf(stderr, " %s%s", (m->flag & UNSIGNED) ? "u" : "", (m->type >= 0 && m->type < SZOF(typ)) ? typ[(unsigned char) m->type] : "*bad*"); if (m->mask != ~0L) - (void) fprintf(stderr, " & %.8x", m->mask); + (void) fprintf(stderr, " & %.8lx", m->mask); (void) fprintf(stderr, ",%c", m->reln); if (m->reln != 'x') { switch (m->type) { case BYTE: case SHORT: case LONG: case LESHORT: case LELONG: case BESHORT: case BELONG: - (void) fprintf(stderr, "%d", m->value.l); + (void) fprintf(stderr, "%ld", m->value.l); break; case STRING: showstr(stderr, m->value.s, -1); break; case DATE: case LEDATE: case BEDATE: { char *rt, *pp = ctime((time_t*) &m->value.l); if ((rt = strchr(pp, '\n')) != NULL) *rt = '\0'; (void) fprintf(stderr, "%s,", pp); if (rt) *rt = '\n'; } break; default: (void) fputs("*bad*", stderr); break; } } (void) fprintf(stderr, ",\"%s\"]\n", m->desc); } /* * ckfputs - futs, but with error checking * ckfprintf - fprintf, but with error checking */ void ckfputs(str, fil) const char *str; FILE *fil; { if (fputs(str,fil) == EOF) error("write failed.\n"); } /*VARARGS*/ void #if __STDC__ ckfprintf(FILE *f, const char *fmt, ...) #else ckfprintf(va_alist) va_dcl #endif { va_list va; #if __STDC__ va_start(va, fmt); #else FILE *f; const char *fmt; va_start(va); f = va_arg(va, FILE *); fmt = va_arg(va, const char *); #endif (void) vfprintf(f, fmt, va); if (ferror(f)) error("write failed.\n"); va_end(va); } /* * error - print best error message possible and exit */ /*VARARGS*/ void #if __STDC__ error(const char *f, ...) #else error(va_alist) va_dcl #endif { va_list va; #if __STDC__ va_start(va, f); #else const char *f; va_start(va); f = va_arg(va, const char *); #endif /* cuz we use stdout for most, stderr here */ (void) fflush(stdout); if (progname != NULL) (void) fprintf(stderr, "%s: ", progname); (void) vfprintf(stderr, f, va); va_end(va); exit(1); } /*VARARGS*/ void #if __STDC__ magwarn(const char *f, ...) #else magwarn(va_alist) va_dcl #endif { va_list va; #if __STDC__ va_start(va, f); #else const char *f; va_start(va); f = va_arg(va, const char *); #endif /* cuz we use stdout for most, stderr here */ (void) fflush(stdout); if (progname != NULL) (void) fprintf(stderr, "%s: %s, %d: ", progname, magicfile, lineno); (void) vfprintf(stderr, f, va); va_end(va); fputc('\n', stderr); } Index: head/usr.bin/file/softmagic.c =================================================================== --- head/usr.bin/file/softmagic.c (revision 13586) +++ head/usr.bin/file/softmagic.c (revision 13587) @@ -1,463 +1,475 @@ /* * softmagic - interpret variable magic from /etc/magic * * Copyright (c) Ian F. Darwin, 1987. * Written by Ian F. Darwin. * * This software is not subject to any license of the American Telephone * and Telegraph Company or of the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. The author is not responsible for the consequences of use of this * software, no matter how awful, even if they arise from flaws in it. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Since few users ever read sources, * credits must appear in the documentation. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. Since few users * ever read sources, credits must appear in the documentation. * * 4. This notice may not be removed or altered. */ #include #include #include #include #include "file.h" #ifndef lint static char *moduleid = - "@(#)$Id: softmagic.c,v 1.2 1995/05/24 02:54:30 ache Exp $"; + "@(#)$Id: softmagic.c,v 1.3 1995/05/30 06:30:09 rgrimes Exp $"; #endif /* lint */ static int match __P((unsigned char *, int)); static int mget __P((union VALUETYPE *, unsigned char *, struct magic *, int)); static int mcheck __P((union VALUETYPE *, struct magic *)); static void mprint __P((union VALUETYPE *, struct magic *)); static void mdebug __P((long, char *, int)); static int mconvert __P((union VALUETYPE *, struct magic *)); /* * softmagic - lookup one file in database * (already read from /etc/magic by apprentice.c). * Passed the name and FILE * of one file to be typed. */ /*ARGSUSED1*/ /* nbytes passed for regularity, maybe need later */ int softmagic(buf, nbytes) unsigned char *buf; int nbytes; { if (match(buf, nbytes)) return 1; return 0; } /* * Go through the whole list, stopping if you find a match. Process all * the continuations of that match before returning. * * We support multi-level continuations: * * At any time when processing a successful top-level match, there is a * current continuation level; it represents the level of the last * successfully matched continuation. * * Continuations above that level are skipped as, if we see one, it * means that the continuation that controls them - i.e, the * lower-level continuation preceding them - failed to match. * * Continuations below that level are processed as, if we see one, * it means we've finished processing or skipping higher-level * continuations under the control of a successful or unsuccessful * lower-level continuation, and are now seeing the next lower-level * continuation and should process it. The current continuation * level reverts to the level of the one we're seeing. * * Continuations at the current level are processed as, if we see * one, there's no lower-level continuation that may have failed. * * If a continuation matches, we bump the current continuation level * so that higher-level continuations are processed. */ static int match(s, nbytes) unsigned char *s; int nbytes; { int magindex = 0; int cont_level = 0; int need_separator = 0; union VALUETYPE p; for (magindex = 0; magindex < nmagic; magindex++) { /* if main entry matches, print it... */ if (!mget(&p, s, &magic[magindex], nbytes) || !mcheck(&p, &magic[magindex])) { /* * main entry didn't match, * flush its continuations */ while (magindex < nmagic && magic[magindex + 1].cont_level != 0) magindex++; continue; } mprint(&p, &magic[magindex]); /* * If we printed something, we'll need to print * a blank before we print something else. */ if (magic[magindex].desc[0]) need_separator = 1; /* and any continuations that match */ cont_level++; while (magic[magindex+1].cont_level != 0 && ++magindex < nmagic) { if (cont_level >= magic[magindex].cont_level) { if (cont_level > magic[magindex].cont_level) { /* * We're at the end of the level * "cont_level" continuations. */ cont_level = magic[magindex].cont_level; } if (mget(&p, s, &magic[magindex], nbytes) && mcheck(&p, &magic[magindex])) { /* * This continuation matched. * Print its message, with * a blank before it if * the previous item printed * and this item isn't empty. */ /* space if previous printed */ if (need_separator && (magic[magindex].nospflag == 0) && (magic[magindex].desc[0] != '\0') ) { (void) putchar(' '); need_separator = 0; } mprint(&p, &magic[magindex]); if (magic[magindex].desc[0]) need_separator = 1; /* * If we see any continuations * at a higher level, * process them. */ cont_level++; } } } return 1; /* all through */ } return 0; /* no match at all */ } static void mprint(p, m) union VALUETYPE *p; struct magic *m; { char *pp, *rt; unsigned long v; switch (m->type) { case BYTE: v = p->b; + v = signextend(m, v) & m->mask; + (void) printf(m->desc, (unsigned char) v); break; case SHORT: case BESHORT: case LESHORT: v = p->h; + v = signextend(m, v) & m->mask; + (void) printf(m->desc, (unsigned short) v); break; case LONG: case BELONG: case LELONG: v = p->l; + v = signextend(m, v) & m->mask; + (void) printf(m->desc, (unsigned long) v); break; case STRING: if (m->reln == '=') { (void) printf(m->desc, m->value.s); } else { (void) printf(m->desc, p->s); } return; case DATE: case BEDATE: case LEDATE: pp = ctime((time_t*) &p->l); if ((rt = strchr(pp, '\n')) != NULL) *rt = '\0'; (void) printf(m->desc, pp); return; default: error("invalid m->type (%d) in mprint().\n", m->type); /*NOTREACHED*/ } - - v = signextend(m, v) & m->mask; - (void) printf(m->desc, v); } /* * Convert the byte order of the data we are looking at */ static int mconvert(p, m) union VALUETYPE *p; struct magic *m; { char *rt; switch (m->type) { case BYTE: case SHORT: case LONG: case DATE: return 1; case STRING: /* Null terminate and eat the return */ p->s[sizeof(p->s) - 1] = '\0'; if ((rt = strchr(p->s, '\n')) != NULL) *rt = '\0'; return 1; case BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); return 1; case BELONG: case BEDATE: p->l = (long) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); return 1; case LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); return 1; case LELONG: case LEDATE: p->l = (long) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); return 1; default: error("invalid type %d in mconvert().\n", m->type); return 0; } } static void mdebug(offset, str, len) long offset; char *str; int len; { - (void) fprintf(stderr, "mget @%d: ", offset); + (void) fprintf(stderr, "mget @%ld: ", offset); showstr(stderr, (char *) str, len); (void) fputc('\n', stderr); (void) fputc('\n', stderr); } static int mget(p, s, m, nbytes) union VALUETYPE* p; unsigned char *s; struct magic *m; int nbytes; { long offset = m->offset; - if (offset + sizeof(union VALUETYPE) > nbytes) - return 0; + if (offset + sizeof(union VALUETYPE) <= nbytes) + memcpy(p, s + offset, sizeof(union VALUETYPE)); + else { + /* + * the usefulness of padding with zeroes eludes me, it + * might even cause problems + */ + long have = nbytes - offset; + memset(p, 0, sizeof(union VALUETYPE)); + if (have > 0) + memcpy(p, s + offset, have); + } - memcpy(p, s + offset, sizeof(union VALUETYPE)); if (debug) { mdebug(offset, (char *) p, sizeof(union VALUETYPE)); mdump(m); } if (!mconvert(p, m)) return 0; if (m->flag & INDIR) { switch (m->in.type) { case BYTE: offset = p->b + m->in.offset; break; case SHORT: offset = p->h + m->in.offset; break; case LONG: offset = p->l + m->in.offset; break; } if (offset + sizeof(union VALUETYPE) > nbytes) return 0; memcpy(p, s + offset, sizeof(union VALUETYPE)); if (debug) { mdebug(offset, (char *) p, sizeof(union VALUETYPE)); mdump(m); } if (!mconvert(p, m)) return 0; } return 1; } static int mcheck(p, m) union VALUETYPE* p; struct magic *m; { register unsigned long l = m->value.l; register unsigned long v; int matched; if ( (m->value.s[0] == 'x') && (m->value.s[1] == '\0') ) { fprintf(stderr, "BOINK"); return 1; } switch (m->type) { case BYTE: v = p->b; break; case SHORT: case BESHORT: case LESHORT: v = p->h; break; case LONG: case BELONG: case LELONG: case DATE: case BEDATE: case LEDATE: v = p->l; break; case STRING: l = 0; /* What we want here is: * v = strncmp(m->value.s, p->s, m->vallen); * but ignoring any nulls. bcmp doesn't give -/+/0 * and isn't universally available anyway. */ v = 0; { register unsigned char *a = (unsigned char*)m->value.s; register unsigned char *b = (unsigned char*)p->s; register int len = m->vallen; while (--len >= 0) if ((v = *b++ - *a++) != 0) break; } break; default: error("invalid type %d in mcheck().\n", m->type); return 0;/*NOTREACHED*/ } v = signextend(m, v) & m->mask; switch (m->reln) { case 'x': if (debug) (void) fprintf(stderr, "%lu == *any* = 1\n", v); matched = 1; break; case '!': matched = v != l; if (debug) (void) fprintf(stderr, "%lu != %lu = %d\n", v, l, matched); break; case '=': matched = v == l; if (debug) (void) fprintf(stderr, "%lu == %lu = %d\n", v, l, matched); break; case '>': if (m->flag & UNSIGNED) { matched = v > l; if (debug) (void) fprintf(stderr, "%lu > %lu = %d\n", v, l, matched); } else { matched = (long) v > (long) l; if (debug) (void) fprintf(stderr, "%ld > %ld = %d\n", v, l, matched); } break; case '<': if (m->flag & UNSIGNED) { matched = v < l; if (debug) (void) fprintf(stderr, "%lu < %lu = %d\n", v, l, matched); } else { matched = (long) v < (long) l; if (debug) (void) fprintf(stderr, "%ld < %ld = %d\n", v, l, matched); } break; case '&': matched = (v & l) == l; if (debug) (void) fprintf(stderr, "((%lx & %lx) == %lx) = %d\n", v, l, l, matched); break; case '^': matched = (v & l) != l; if (debug) (void) fprintf(stderr, "((%lx & %lx) != %lx) = %d\n", v, l, l, matched); break; default: matched = 0; error("mcheck: can't happen: invalid relation %d.\n", m->reln); break;/*NOTREACHED*/ } return matched; }