1 /*
2 * Copyright 1993 University of Liverpool Computer Science Department
3 *
4 * Permission to use, copy, modify, and distribute this software and its
5 * documentation for any purpose and without fee is hereby granted, provided
6 * that the above copyright notice appear in all copies and that both that
7 * copyright notice and this permission notice appear in supporting
8 * documentation, and that the name of L.U.C.S. not be used in advertising
9 * or publicity pertaining to distribution of the software without specific,
10 * written prior permission. L.U.C.S. makes no representations about the
11 * suitability of this software for any purpose. It is provided "as is"
12 * without express or implied warranty.
13 *
14 * FILE NAME: magic.c
15 * CREATED: Mon Oct 25 1993
16 * AUTHOR: Rik Turnbull
17 * DESCRIPTION: Using MAGIC numbers handle file types. Better than using the
18 * filename as a guide for the file type.
19 *
20 */
21
22 #include <fcntl.h>
23 #include <stdio.h>
24
25 #include "magic.h"
26
27 int magic_ftype(char *, int);
28
29 static unsigned char jpeg[2] = { 0xff, 0xd8 };
30 static unsigned char gif[3] = { 0x47, 0x49, 0x46 };
31 static unsigned char compress[3] = { 0x1f, 0x9d, 0x90 };
32 static unsigned char gzip[3] = { 0x1f, 0x8b, 0x08 };
33 static unsigned char troff[2] = { 0x5c, 0x22 };
34 static unsigned char postscript[2] = { 0x25, 0x21 };
35
36 /* magic_ftype:*******************************************************/
37 /* magic_ftype: Using magic numbers is file of type suggested? */
38 /* magic_ftype:*******************************************************/
39
magic_ftype(char * filename,int type)40 int magic_ftype(char *filename, int type)
41 {
42 unsigned char buffer[3];
43 int fp;
44
45 /* Open the file for reading */
46 if(filename == NULL) {
47 fp = 0;
48 } else {
49 if((fp = open(filename, O_RDONLY)) < 0)
50 return(0);
51 }
52
53 /* Read first 3 bytes */
54 if(read(fp, buffer, 3) != 3) {
55 if(filename == NULL)
56 rewind(stdin);
57 else
58 close(fp);
59 return(0);
60 }
61 if(filename == NULL)
62 rewind(stdin);
63 else
64 close(fp);
65
66 /* Compare bytes with type we are after */
67 switch(type) {
68 case MAGIC_JPEG:
69 if(!memcmp(buffer, jpeg, 2))
70 return(1);
71 break;
72 case MAGIC_GIF:
73 if(!memcmp(buffer, gif, 3))
74 return(1);
75 break;
76 case MAGIC_COMPRESS:
77 if(!memcmp(buffer, compress, 3))
78 return(1);
79 break;
80 case MAGIC_GZIP:
81 if(!memcmp(buffer, gzip, 3))
82 return(1);
83 break;
84 case MAGIC_TROFF:
85 if(!memcmp(buffer, troff, 2))
86 return(1);
87 break;
88 case MAGIC_POSTSCRIPT:
89 if(!memcmp(buffer, postscript, 2))
90 return(1);
91 break;
92 default:
93 return(0);
94 }
95
96 return(0);
97 }
98