1 /*
2  * Copyright (c) 2001-2007, Eric M. Johnston <emj@postal.net>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Eric M. Johnston.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Id: exifutil.c,v 1.31 2007/12/16 01:14:26 ejohnst Exp $
33  */
34 
35 /*
36  * Utilities for dealing with Exif data.
37  *
38  */
39 
40 #include <stdlib.h>
41 #include <string.h>
42 #include <stdio.h>
43 #include <errno.h>
44 
45 #include "exif.h"
46 #include "exifint.h"
47 
48 
49 /*
50  * Some global variables we all need.
51  */
52 
53 int debug;
54 const char *progname;
55 
56 
57 /*
58  * Logging and error functions.
59  */
60 void
exifdie(const char * msg)61 exifdie(const char *msg)
62 {
63 
64 	fprintf(stderr, "%s: %s\n", progname, msg);
65 	exit(1);
66 }
67 
68 void
exifwarn(const char * msg)69 exifwarn(const char *msg)
70 {
71 
72 	fprintf(stderr, "%s: %s\n", progname, msg);
73 }
74 
75 void
exifwarn2(const char * msg1,const char * msg2)76 exifwarn2(const char *msg1, const char *msg2)
77 {
78 
79 	fprintf(stderr, "%s: %s (%s)\n", progname, msg1, msg2);
80 }
81 
82 
83 /*
84  * Sanity check a tag's count & value when used as an offset within
85  * the TIFF.  Checks for overflows.  Returns 0 if OK; !0 if not OK.
86  */
87 int
offsanity(struct exifprop * prop,u_int16_t size,struct ifd * dir)88 offsanity(struct exifprop *prop, u_int16_t size, struct ifd *dir)
89 {
90 	u_int32_t tifflen;
91 	const char *name;
92 
93 	/* XXX Hrm.  Should be OK with 64-bit addresses. */
94 	tifflen = dir->md.etiff - dir->md.btiff;
95 	if (prop->name)
96 		name = prop->name;
97 	else
98 		name = "Unknown";
99 
100 	if (!prop->count) {
101 		if (prop->value > tifflen) {
102 			exifwarn2("invalid field offset", name);
103 			prop->lvl = ED_BAD;
104 			return (1);
105 		}
106 		return (0);
107 	}
108 
109 	/* Does count * size overflow? */
110 
111 	if (size > (u_int32_t)(-1) / prop->count) {
112 		exifwarn2("invalid field count", name);
113 		prop->lvl = ED_BAD;
114 		return (1);
115 	}
116 
117 	/* Does count * size + value overflow? */
118 
119 	if ((u_int32_t)(-1) - prop->value < prop->count * size) {
120 		exifwarn2("invalid field offset", name);
121 		prop->lvl = ED_BAD;
122 		return (1);
123 	}
124 
125 	/* Is the offset valid? */
126 
127 	if (prop->value + prop->count * size > tifflen) {
128 		exifwarn2("invalid field offset", name);
129 		prop->lvl = ED_BAD;
130 		return (1);
131 	}
132 
133 	return (0);
134 }
135 
136 
137 /*
138  * Read an unsigned 2-byte int from the buffer.
139  */
140 u_int16_t
exif2byte(unsigned char * b,enum byteorder o)141 exif2byte(unsigned char *b, enum byteorder o)
142 {
143 
144 	if (o == BIG)
145 		return ((b[0] << 8) | b[1]);
146 	else
147 		return ((b[1] << 8) | b[0]);
148 }
149 
150 
151 /*
152  * Read a signed 2-byte int from the buffer.
153  */
154 int16_t
exif2sbyte(unsigned char * b,enum byteorder o)155 exif2sbyte(unsigned char *b, enum byteorder o)
156 {
157 
158 	if (o == BIG)
159 		return ((b[0] << 8) | b[1]);
160 	else
161 		return ((b[1] << 8) | b[0]);
162 }
163 
164 
165 /*
166  * Read an unsigned 4-byte int from the buffer.
167  */
168 u_int32_t
exif4byte(unsigned char * b,enum byteorder o)169 exif4byte(unsigned char *b, enum byteorder o)
170 {
171 
172 	if (o == BIG)
173 		return ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
174 	else
175 		return ((b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0]);
176 }
177 
178 
179 /*
180  * Write an unsigned 4-byte int to a buffer.
181  */
182 void
byte4exif(u_int32_t n,unsigned char * b,enum byteorder o)183 byte4exif(u_int32_t n, unsigned char *b, enum byteorder o)
184 {
185 	int i;
186 
187 	if (o == BIG)
188 		for (i = 0; i < 4; i++)
189 			b[3 - i] = (unsigned char)((n >> (i * 8)) & 0xff);
190 	else
191 		for (i = 0; i < 4; i++)
192 			b[i] = (unsigned char)((n >> (i * 8)) & 0xff);
193 }
194 
195 
196 /*
197  * Read a signed 4-byte int from the buffer.
198  */
199 int32_t
exif4sbyte(unsigned char * b,enum byteorder o)200 exif4sbyte(unsigned char *b, enum byteorder o)
201 {
202 
203 	if (o == BIG)
204 		return ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
205 	else
206 		return ((b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0]);
207 }
208 
209 
210 /*
211  * Lookup and allocate description for a value.
212  */
213 char *
finddescr(struct descrip * table,u_int16_t val)214 finddescr(struct descrip *table, u_int16_t val)
215 {
216 	int i;
217 	char *c;
218 
219 	for (i = 0; table[i].val != -1 && table[i].val != val; i++);
220 	if (!(c = (char *)malloc(strlen(table[i].descr) + 1)))
221 		exifdie((const char *)strerror(errno));
222 	strcpy(c, table[i].descr);
223 	return (c);
224 }
225 
226 
227 /*
228  * Lookup and append description for a value.
229  * Doesn't do anything if the value is unknown; first adds ", " if dest
230  * contains a value; returns number of bytes added.  len is total size
231  * of destination buffer.
232  */
233 int
catdescr(char * c,struct descrip * table,u_int16_t val,int len)234 catdescr(char *c, struct descrip *table, u_int16_t val, int len)
235 {
236 	int i, l;
237 
238 	l = 0;
239 	len -= 1;
240 	c[len] = '\0';
241 
242 	for (i = 0; table[i].val != -1 && table[i].val != val; i++);
243 	if (table[i].val == -1)
244 		return (0);
245 
246 	if (strlen(c)) {
247 		strncat(c, ", ", len - strlen(c));
248 		l += 2;
249 	}
250 	strncat(c, table[i].descr, len - strlen(c));
251 	l += strlen(table[i].descr);
252 	return (l);
253 }
254 
255 
256 /*
257  * Lookup a property entry belonging to a particular set of tags.
258  */
259 struct exifprop *
findprop(struct exifprop * prop,struct exiftag * tagset,u_int16_t tag)260 findprop(struct exifprop *prop, struct exiftag *tagset, u_int16_t tag)
261 {
262 
263 	for (; prop && (prop->tagset != tagset || prop->tag != tag ||
264 	    prop->lvl == ED_BAD); prop = prop->next);
265 	return (prop);
266 }
267 
268 
269 /*
270  * Allocate memory for an Exif property.
271  */
272 struct exifprop *
newprop(void)273 newprop(void)
274 {
275 	struct exifprop *prop;
276 
277 	prop = (struct exifprop *)malloc(sizeof(struct exifprop));
278 	if (!prop)
279 		exifdie((const char *)strerror(errno));
280 	memset(prop, 0, sizeof(struct exifprop));
281 	return (prop);
282 }
283 
284 
285 /*
286  * Given a parent, create a new child Exif property.  These are
287  * typically used by maker note modules when a single tag may contain
288  * multiple items of interest.
289  */
290 struct exifprop *
childprop(struct exifprop * parent)291 childprop(struct exifprop *parent)
292 {
293 	struct exifprop *prop;
294 
295 	prop = newprop();
296 
297 	/* By default, the child inherits most values from its parent. */
298 
299 	prop->tag = parent->tag;
300 	prop->type = TIFF_UNKN;
301 	prop->name = parent->name;
302 	prop->descr = parent->descr;
303 	prop->lvl = parent->lvl;
304 	prop->ifdseq = parent->ifdseq;
305 	prop->par = parent;
306 	prop->next = parent->next;
307 
308 	/* Now insert the new property into our list. */
309 
310 	parent->next = prop;
311 
312 	return (prop);
313 }
314 
315 
316 /*
317  * Allocate a buffer for a property's display string.
318  */
319 void
exifstralloc(char ** str,int len)320 exifstralloc(char **str, int len)
321 {
322 
323 	if (*str) {
324 		exifwarn("tried to alloc over non-null string");
325 		abort();
326 	}
327 	if (!(*str = (char *)calloc(1, len)))
328 		exifdie((const char *)strerror(errno));
329 }
330 
331 
332 /*
333  * Print hex values of a buffer.
334  */
335 void
hexprint(unsigned char * b,int len)336 hexprint(unsigned char *b, int len)
337 {
338 	int i;
339 
340 	for (i = 0; i < len; i++)
341 		printf(" %02X", b[i]);
342 }
343 
344 
345 /*
346  * Print debug info for a property.
347  */
348 void
dumpprop(struct exifprop * prop,struct field * afield)349 dumpprop(struct exifprop *prop, struct field *afield)
350 {
351 	int i;
352 
353 	if (!debug) return;
354 
355 	for (i = 0; ftypes[i].type && ftypes[i].type != prop->type; i++);
356 	if (afield) {
357 		printf("   %s (0x%04X): %s, %u; %u\n", prop->name,
358 		    prop->tag, ftypes[i].name, prop->count,
359 		    prop->value);
360 		printf("      ");
361 		hexprint(afield->tag, 2);
362 		printf(" |");
363 		hexprint(afield->type, 2);
364 		printf(" |");
365 		hexprint(afield->count, 4);
366 		printf(" |");
367 		hexprint(afield->value, 4);
368 		printf("\n");
369 	} else
370 		printf("   %s (0x%04X): %s, %d; %d, 0x%04X\n",
371 		    prop->name, prop->tag, ftypes[i].name,
372 		    prop->count, prop->value, prop->value);
373 }
374 
375 
376 /*
377  * Allocate and read an individual IFD.  Takes the beginning and end of the
378  * Exif buffer, returns the IFD and an offset to the next IFD.
379  */
380 u_int32_t
readifd(u_int32_t offset,struct ifd ** dir,struct exiftag * tagset,struct tiffmeta * md)381 readifd(u_int32_t offset, struct ifd **dir, struct exiftag *tagset,
382     struct tiffmeta *md)
383 {
384 	u_int32_t ifdsize, tifflen;
385 	unsigned char *b;
386 	struct ifdoff *ifdoffs, *lastoff;
387 
388 	tifflen = md->etiff - md->btiff;
389 	b = md->btiff;
390 	ifdoffs = (struct ifdoff *)(md->ifdoffs);
391 	lastoff = NULL;
392 	*dir = NULL;
393 
394 	/*
395 	 * Check to see if we've already visited this offset.  Otherwise
396 	 * we could loop.  (Need to add in TIFF start for Nikon makernotes.)
397 	 */
398 
399 	while (ifdoffs && ifdoffs->offset != b + offset) {
400 		lastoff = ifdoffs;
401 		ifdoffs = ifdoffs->next;
402 	}
403 	if (ifdoffs) {
404 		/* We'll only complain if debugging. */
405 		if (debug) exifwarn("loop in IFD reference");
406 		return (0);
407 	}
408 
409 	ifdoffs = (struct ifdoff *)malloc(sizeof(struct ifdoff));
410 	if (!ifdoffs) {
411 		exifwarn2("can't allocate IFD offset record",
412 		    (const char *)strerror(errno));
413 		return (0);
414 	}
415 	ifdoffs->offset = offset + b;
416 	ifdoffs->next = NULL;
417 
418 	/* The 0th (first) IFD establishes our list on the master tiffmeta. */
419 	if (lastoff)
420 		lastoff->next = ifdoffs;
421 	else
422 		md->ifdoffs = (void *)ifdoffs;
423 
424 	/*
425 	 * Verify that we have a valid offset.  Some maker note IFDs prepend
426 	 * a string and will screw us up otherwise (e.g., Olympus).
427 	 * (Number of directory entries is in the first 2 bytes.)
428 	 */
429 
430 	if ((u_int32_t)(-1) - offset < 2 || offset + 2 > tifflen)
431 		return (0);
432 
433 	*dir = (struct ifd *)malloc(sizeof(struct ifd));
434 	if (!*dir) {
435 		exifwarn2("can't allocate IFD record",
436 		    (const char *)strerror(errno));
437 		return (0);
438 	}
439 
440 	(*dir)->num = exif2byte(b + offset, md->order);
441 	(*dir)->par = NULL;
442 	(*dir)->tagset = tagset;
443 	(*dir)->md = *md;
444 	(*dir)->next = NULL;
445 
446 	/* Make sure ifdsize doesn't overflow. */
447 
448 	if ((*dir)->num &&
449 	    sizeof(struct field) > (u_int32_t)(-1) / (*dir)->num) {
450 		free(*dir);
451 		*dir = NULL;
452 		return (0);
453 	}
454 
455 	ifdsize = (*dir)->num * sizeof(struct field);
456 	b += offset + 2;
457 
458 	/* Sanity check our size (and check for overflows). */
459 
460 	if ((u_int32_t)(-1) - (offset + 2) < ifdsize ||
461 	    offset + 2 + ifdsize > tifflen) {
462 		free(*dir);
463 		*dir = NULL;
464 		return (0);
465 	}
466 
467 	/* Point to our array of fields. */
468 
469 	(*dir)->fields = (struct field *)b;
470 
471 	/*
472 	 * While we're here, find the offset to the next IFD.
473 	 *
474 	 * Note that this offset isn't always going to be valid.  It
475 	 * seems that some camera implementations of Exif ignore the spec
476 	 * and do not include the offset for all IFDs (e.g., maker note).
477 	 * Therefore, it may be necessary to call readifd() directly (in
478 	 * leiu of readifds()) to avoid problems when reading these non-
479 	 * standard IFDs.
480 	 */
481 
482 	return ((b + ifdsize + 4 > md->etiff) ? 0 :
483 	    exif4byte(b + ifdsize, md->order));
484 }
485 
486 
487 /*
488  * Read a chain of IFDs.  Takes the IFD offset and returns the first
489  * node in a chain of IFDs.  Note that it can return NULL.
490  */
491 struct ifd *
readifds(u_int32_t offset,struct exiftag * tagset,struct tiffmeta * md)492 readifds(u_int32_t offset, struct exiftag *tagset, struct tiffmeta *md)
493 {
494 	struct ifd *firstifd, *curifd;
495 
496 	/* Fetch our first one. */
497 
498 	offset = readifd(offset, &firstifd, tagset, md);
499 	curifd = firstifd;
500 
501 	/* Fetch any remaining ones. */
502 
503 	while (offset) {
504 		offset = readifd(offset, &(curifd->next), tagset, md);
505 		curifd = curifd->next;
506 	}
507 	return (firstifd);
508 }
509 
510 
511 /*
512  * Euclid's algorithm to find the GCD.
513  */
514 u_int32_t
gcd(u_int32_t a,u_int32_t b)515 gcd(u_int32_t a, u_int32_t b)
516 {
517 
518 	if (!b) return (a);
519 	return (gcd(b, a % b));
520 }
521