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: exif.c,v 1.77 2007/12/16 00:25:08 ejohnst Exp $
33  */
34 
35 /*
36  * Exchangeable image file format (Exif) parser.
37  *
38  * Developed using the TIFF 6.0 specification:
39  * (http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf)
40  * and the EXIF 2.21 standard: (http://tsc.jeita.or.jp/avs/data/cp3451_1.pdf).
41  *
42  * Portions of this code were developed while referencing the public domain
43  * 'Jhead' program (version 1.2) by Matthias Wandel <mwandel@rim.net>.
44  *
45  */
46 
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <errno.h>
51 #include <math.h>
52 #include <float.h>
53 #include <ctype.h>
54 
55 #include "exif.h"
56 #include "exifint.h"
57 #include "makers.h"
58 
59 #define OLYMPUS_BUGS		/* Work around Olympus stupidity. */
60 #define WINXP_BUGS		/* Work around Windows XP stupidity. */
61 #define SIGMA_BUGS		/* Work around Sigma stupidity. */
62 #define UNCREDITED_BUGS		/* Work around uncredited stupidity. */
63 
64 
65 /* Function prototypes. */
66 
67 static void parsetag(struct exifprop *prop, struct ifd *dir,
68     struct exiftags *t, int domkr);
69 
70 
71 /*
72  * Create an Exif property from the raw IFD field data.
73  */
74 static void
readtag(struct field * afield,int ifdseq,struct ifd * dir,struct exiftags * t,int domkr)75 readtag(struct field *afield, int ifdseq, struct ifd *dir, struct exiftags *t,
76     int domkr)
77 {
78 	int i, j;
79 	struct exifprop *prop, *tmpprop;
80 	u_int16_t tag;
81 
82 	prop = newprop();
83 	if (dir->par)
84 		tag = dir->par->tag;
85 	else
86 		tag = EXIF_T_UNKNOWN;
87 
88 	/* Field info. */
89 
90 	prop->tag = exif2byte(afield->tag, dir->md.order);
91 	prop->type = exif2byte(afield->type, dir->md.order);
92 	prop->count = exif4byte(afield->count, dir->md.order);
93 	/* XXX Makes dealing with two shorts somewhat messy. */
94 	if ((prop->type == TIFF_SHORT || prop->type == TIFF_SSHORT) &&
95 	    prop->count <= 1)
96 		prop->value = exif2byte(afield->value, dir->md.order);
97 	else
98 		prop->value = exif4byte(afield->value, dir->md.order);
99 
100 	/* IFD identifying info. */
101 
102 	prop->ifdseq = ifdseq;
103 	prop->par = dir->par;
104 	prop->tagset = dir->tagset;
105 
106 	/* Lookup the field name. */
107 
108 	for (i = 0; prop->tagset[i].tag < EXIF_T_UNKNOWN &&
109 	    prop->tagset[i].tag != prop->tag; i++);
110 	prop->name = prop->tagset[i].name;
111 	prop->descr = prop->tagset[i].descr;
112 	prop->lvl = prop->tagset[i].lvl;
113 
114 	/*
115 	 * Lookup and check the field type.
116 	 *
117 	 * We have to be pretty severe with entries that have an invalid
118 	 * field type -- too many assumptions in the rest of the code.
119 	 */
120 
121 	for (j = 0; ftypes[j].type && ftypes[j].type != prop->type; j++);
122 	if (!ftypes[j].type) {
123 		exifwarn2("unknown TIFF field type; discarding", prop->name);
124 		free(prop);
125 		return;
126 	}
127 
128 	/* Skip sanity checking on maker note tags; we'll get to them later. */
129 
130 	if (tag != EXIF_T_MAKERNOTE) {
131 		/*
132 		 * XXX Ignore UserComment -- a hack to get around an apparent
133 		 * WinXP Picture Viewer bug (err, liberty).  When you rotate
134 		 * a picture in the viewer, it modifies the IFD1 (thumbnail)
135 		 * tags to UserComment without changing the type appropriately.
136 		 * (At least we're able to ID invalid comments...)
137 		 */
138 
139 		if (prop->tagset[i].type && prop->tagset[i].type !=
140 		    prop->type) {
141 #ifdef WINXP_BUGS
142 			if (prop->tag != EXIF_T_USERCOMMENT)
143 #endif
144 				exifwarn2("field type mismatch", prop->name);
145 			prop->lvl = ED_BAD;
146 		}
147 
148 		/*
149 		 * Check the field count.
150 		 * XXX For whatever the reason, Sigma doesn't follow the
151 		 * spec on count for FileSource.
152 		 */
153 
154 		if (prop->tagset[i].count && prop->tagset[i].count !=
155 #ifdef SIGMA_BUGS
156 		    prop->count && prop->tag != EXIF_T_FILESRC) {
157 #else
158 		    prop->count) {
159 #endif
160 			exifwarn2("field count mismatch", prop->name);
161 
162 			/* Let's be forgiving with ASCII fields. */
163 			if (prop->type != TIFF_ASCII)
164 				prop->lvl = ED_BAD;
165 		}
166 	}
167 
168 	/* Debuggage. */
169 
170 	dumpprop(prop, afield);
171 
172 	/*
173 	 * Do as much as we can with the tag at this point and add it
174 	 * to our list.
175 	 */
176 
177 	parsetag(prop, dir, t, domkr);
178 	if ((tmpprop = t->props)) {
179 		while (tmpprop->next)
180 			tmpprop = tmpprop->next;
181 		tmpprop->next = prop;
182 	} else
183 		t->props = prop;
184 }
185 
186 
187 /*
188  * Process the Exif tags for each field of an IFD.
189  *
190  * Note that this function is only called once per IFD.  Therefore, in order
191  * to associate an IFD sequence number with the property, we keep track of
192  * the count here.  Root IFDs (0 and 1) are processed first (along with any
193  * other "root" IFDs we find), then any nested IFDs in the order they're
194  * encountered.
195  */
196 static void
197 readtags(struct ifd *dir, int seq, struct exiftags *t, int domkr)
198 {
199 	int i;
200 
201 	if (debug) {
202 		/* XXX Byte order info can be off for maker notes. */
203 		if (dir->par && dir->par->tag != EXIF_T_UNKNOWN) {
204 			printf("Processing %s directory, %d entries, "
205 			    "%s-endian\n",
206 			    dir->par->name, dir->num, dir->md.order == BIG ?
207 			    "big" : "little");
208 		} else
209 			printf("Processing directory %d, %d entries, "
210 			    "%s-endian\n",
211 			    seq, dir->num, dir->md.order == BIG ? "big" :
212 			    "little");
213 	}
214 
215 	for (i = 0; i < dir->num; i++)
216 		readtag(&(dir->fields[i]), seq, dir, t, domkr);
217 
218 	if (debug)
219 		printf("\n");
220 }
221 
222 
223 /*
224  * Post-process property values.  By now we've got all of the standard
225  * Exif tags read in (but not maker tags), so it's safe to work out
226  * dependencies between tags.
227  *
228  * XXX At this point, we've lost IFD-level TIFF metadata.  Therefore,
229  * assumptions about byte order and beginning of the TIFF might be false.
230  */
231 static void
232 postprop(struct exifprop *prop, struct exiftags *t)
233 {
234 	struct exifprop *tmpprop;
235 	u_int16_t v;
236 	u_int32_t val;
237 	float fval;
238 	enum byteorder o = t->md.order;
239 	struct exifprop *h = t->props;
240 
241 	/* Skip bad properties. */
242 
243 	if (prop->lvl == ED_BAD)
244 		return;
245 
246 	/*
247 	 * Process tags from special IFDs.
248 	 */
249 
250 	if (prop->par && prop->par->tagset == tags) {
251 		switch (prop->par->tag) {
252 
253 		case EXIF_T_MAKERNOTE:
254 			if (makers[t->mkrval].propfun) {
255 				makers[t->mkrval].propfun(prop, t);
256 				return;
257 			}
258 			break;
259 
260 		case EXIF_T_GPSIFD:
261 			gpsprop(prop, t);
262 			return;
263 		}
264 	}
265 
266 	/* Process normal tags. */
267 
268 	if (prop->tagset != tags)
269 		return;
270 
271 	switch (prop->tag) {
272 
273 	case EXIF_T_XRES:
274 	case EXIF_T_YRES:
275 	case EXIF_T_FPXRES:
276 	case EXIF_T_FPYRES:
277 		if (prop->tag == EXIF_T_XRES || prop->tag == EXIF_T_YRES) {
278 			if (!(tmpprop = findprop(h, tags, EXIF_T_RESUNITS)))
279 				break;
280 		} else {
281 			if (!(tmpprop = findprop(h, tags, EXIF_T_FPRESUNITS)))
282 				break;
283 		}
284 		val = exif4byte(t->md.btiff + prop->value, o) /
285 		    exif4byte(t->md.btiff + prop->value + 4, o);
286 		snprintf(prop->str, 31, "%d dp%s", val, tmpprop->str);
287 		prop->str[31] = '\0';
288 		break;
289 
290 	/*
291 	 * Shutter speed doesn't seem all that useful.  It's usually the
292 	 * same as exposure time and when it's not, it's wrong.
293 	 * Exposure time overrides it.
294 	 */
295 
296 	case EXIF_T_SHUTTER:
297 		fval = (float)exif4sbyte(t->md.btiff + prop->value, o) /
298 		    (float)exif4sbyte(t->md.btiff + prop->value + 4, o);
299 		if (isnan(fval)) fval = 0;
300 		/* 1 / (2^speed) */
301 		snprintf(prop->str, 31, "1/%d",
302 		    (int)floor(pow(2, (double)fval) + 0.5));
303 		prop->str[31] = '\0';
304 		/* FALLTHROUGH */
305 
306 	case EXIF_T_EXPOSURE:
307 		if (strlen(prop->str) > 27) break;
308 		strcat(prop->str, " sec");
309 		if (prop->tag == EXIF_T_EXPOSURE)
310 			prop->override = EXIF_T_SHUTTER;
311 		break;
312 
313 	case EXIF_T_FNUMBER:
314 		fval = (float)exif4byte(t->md.btiff + prop->value, o) /
315 		    (float)exif4byte(t->md.btiff + prop->value + 4, o);
316 		if (isnan(fval)) fval = 0;
317 		snprintf(prop->str, 31, "f/%.1f", fval);
318 		prop->str[31] = '\0';
319 		break;
320 
321 	case EXIF_T_LAPERTURE:
322 	case EXIF_T_MAXAPERTURE:
323 		fval = (float)exif4byte(t->md.btiff + prop->value, o) /
324 		    (float)exif4byte(t->md.btiff + prop->value + 4, o);
325 		if (isnan(fval)) fval = 0;
326 		/* sqrt(2)^aperture */
327 		snprintf(prop->str, 31, "f/%.1f", pow(1.4142, (double)fval));
328 		prop->str[31] = '\0';
329 		break;
330 
331 	case EXIF_T_BRIGHTVAL:
332 		if (exif4byte(t->md.btiff + prop->value, o) == 0xffffffff) {
333 			strcpy(prop->str, "Unknown");
334 			break;
335 		}
336 		/* FALLTHROUGH */
337 
338 	case EXIF_T_EXPBIASVAL:
339 		if (strlen(prop->str) > 28) break;
340 		strcat(prop->str, " EV");
341 		break;
342 
343 	case EXIF_T_DISTANCE:
344 		if (exif4byte(t->md.btiff + prop->value, o) == 0xffffffff) {
345 			strcpy(prop->str, "Infinity");
346 			break;
347 		}
348 		if (exif4byte(t->md.btiff + prop->value + 4, o) == 0) {
349 			strcpy(prop->str, "Unknown");
350 			break;
351 		}
352 		fval = (float)exif4byte(t->md.btiff + prop->value, o) /
353 		    (float)exif4byte(t->md.btiff + prop->value + 4, o);
354 		if (isnan(fval)) fval = 0;
355 		snprintf(prop->str, 31, "%.2f m", fval);
356 		prop->str[31] = '\0';
357 		break;
358 
359 	/* Flash consists of a number of bits, which expanded with v2.2. */
360 
361 #define LFLSH 96
362 
363 	case EXIF_T_FLASH:
364 		if (t->exifmaj <= 2 && t->exifmin < 20)
365 			v = (u_int16_t)(prop->value & 0x7);
366 		else
367 			v = (u_int16_t)(prop->value & 0x7F);
368 
369 		exifstralloc(&prop->str, LFLSH);
370 
371 		/* Don't do anything else if there isn't a flash. */
372 
373 		if (catdescr(prop->str, flash_func, (u_int16_t)(v & 0x20),
374 		    LFLSH))
375 			break;
376 
377 		catdescr(prop->str, flash_fire, (u_int16_t)(v & 0x01), LFLSH);
378 		catdescr(prop->str, flash_mode, (u_int16_t)(v & 0x18), LFLSH);
379 		catdescr(prop->str, flash_redeye, (u_int16_t)(v & 0x40), LFLSH);
380 		catdescr(prop->str, flash_return, (u_int16_t)(v & 0x06), LFLSH);
381 		break;
382 
383 	case EXIF_T_FOCALLEN:
384 		fval = (float)exif4byte(t->md.btiff + prop->value, o) /
385 		    (float)exif4byte(t->md.btiff + prop->value + 4, o);
386 		if (isnan(fval)) fval = 0;
387 		snprintf(prop->str, 31, "%.2f mm", fval);
388 		prop->str[31] = '\0';
389 		break;
390 
391 	/* Digital zoom: set to verbose if numerator is 0 or fraction = 1. */
392 
393 	case EXIF_T_DIGIZOOM:
394 		if (!exif4byte(t->md.btiff + prop->value, o))
395 			strcpy(prop->str, "Unused");
396 		else if (exif4byte(t->md.btiff + prop->value, o) !=
397 		    exif4byte(t->md.btiff + prop->value + 4, o))
398 			break;
399 		prop->lvl = ED_VRB;
400 		break;
401 
402 	case EXIF_T_FOCALLEN35:
403 		exifstralloc(&prop->str, 16);
404 		snprintf(prop->str, 15, "%d mm", prop->value);
405 		break;
406 
407 	/*
408 	 * XXX This really should be in parsetag() to guarantee that it's
409 	 * done before we process the maker notes.  However, I haven't seen
410 	 * model not come first, so it should be safe (and more convenient).
411 	 */
412 
413 	case EXIF_T_MODEL:
414 		t->model = prop->str;
415 		break;
416 	}
417 }
418 
419 
420 /*
421  * This gives us an opportunity to change the dump level based on
422  * property values after all properties are established.
423  */
424 static void
425 tweaklvl(struct exifprop *prop, struct exiftags *t)
426 {
427 	char *c;
428 	struct exifprop *tmpprop;
429 
430 	/* Change any ASCII properties to verbose if they're empty. */
431 
432 	if (prop->type == TIFF_ASCII &&
433 	    (prop->lvl & (ED_CAM | ED_IMG | ED_PAS))) {
434 		c = prop->str;
435 		while (c && *c && (isspace((int)*c) ||
436 		    (unsigned char)*c < ' ')) c++;
437 		if (!c || !*c)
438 			prop->lvl = ED_VRB;
439 	}
440 
441 	/*
442 	 * Don't let unprintable characters slip through -- we'll just replace
443 	 * them with '_'.  (Can see this with some corrupt maker notes.)
444 	 * Remove trailing whitespace while we're at it.
445 	 */
446 
447 	if (prop->str && prop->type == TIFF_ASCII) {
448 		c = prop->str;
449 		while (*c) {
450 			/* Catch those pesky chars > 127. */
451 			if ((unsigned char)*c < ' ')
452 				*c = '_';
453 			c++;
454 		}
455 
456 		c = prop->str + strlen(prop->str);
457 		while (c > prop->str && isspace((int)*(c - 1))) --c;
458 		*c = '\0';
459 	}
460 
461 	/*
462 	 * IFD1 refers to the thumbnail image; we don't really care.
463 	 * It seems that some images might not have an IFD1 (does FinePix
464 	 * Viewer strip it?), so make sure that the property doesn't have
465 	 * a parent association.
466 	 */
467 
468 	if (prop->ifdseq == 1 && !prop->par && prop->lvl != ED_UNK)
469 		prop->lvl = ED_VRB;
470 
471 	/* Maker tags can override normal Exif tags. */
472 
473 	if (prop->override && (tmpprop = findprop(t->props, tags,
474 	    prop->override)))
475 		if (tmpprop->lvl & (ED_CAM | ED_IMG | ED_PAS))
476 			tmpprop->lvl = ED_OVR;
477 }
478 
479 
480 /*
481  * Fetch the data for an Exif tag.
482  */
483 static void
484 parsetag(struct exifprop *prop, struct ifd *dir, struct exiftags *t, int domkr)
485 {
486 	unsigned int i, len;
487 	u_int16_t v = (u_int16_t)prop->value;
488 	u_int32_t un, ud, denom;
489 	int32_t sn, sd;
490 	char buf[32], *c, *d;
491 	struct tiffmeta *md;
492 	unsigned char *btiff = dir->md.btiff;
493 	enum byteorder o = dir->md.order;
494 
495 	/* If the tag's already marked as bad, no sense in continuing. */
496 
497 	if (prop->lvl == ED_BAD)
498 		return;
499 
500 	/* Set description if we have a lookup table. */
501 
502 	for (i = 0; prop->tagset[i].tag < EXIF_T_UNKNOWN &&
503 	    prop->tagset[i].tag != prop->tag; i++);
504 	if (prop->tagset[i].table) {
505 		prop->str = finddescr(prop->tagset[i].table, v);
506 		return;
507 	}
508 
509 	/* XXX Probably shouldn't process this switch for non-standard tags. */
510 
511 	switch (prop->tag) {
512 
513 	/* Process an Exif IFD. */
514 
515 	case EXIF_T_EXIFIFD:
516 	case EXIF_T_GPSIFD:
517 	case EXIF_T_INTEROP:
518 		md = &dir->md;
519 		while (dir->next)
520 			dir = dir->next;
521 
522 		/*
523 		 * XXX Olympus cameras don't seem to include a proper offset
524 		 * at the end of the ExifOffset IFD, so just read one IFD.
525 		 * Hopefully this won't cause us to miss anything...
526 		 */
527 #ifdef OLYMPUS_BUGS
528 		if (prop->tag == EXIF_T_EXIFIFD)
529 			readifd(prop->value, &dir->next, tags, md);
530 		else
531 #endif
532 			if (prop->tag == EXIF_T_GPSIFD) {
533 				dir->next = readifds(prop->value, gpstags, md);
534 			} else {
535 				dir->next = readifds(prop->value, tags, md);
536 			}
537 
538 		if (!dir->next) {
539 
540 			/*
541 			 * XXX Ignore the case where interoperability offset
542 			 * is invalid.  This appears to be the case with some
543 			 * Olympus cameras, and we don't want to abort things
544 			 * things on an IFD we don't really care about anyway.
545 			 */
546 #ifdef OLYMPUS_BUGS
547 			if (prop->tag == EXIF_T_INTEROP)
548 				break;
549 #endif
550 			exifwarn2("invalid Exif format: IFD length mismatch",
551 			    prop->name);
552 			break;
553 		}
554 
555 		/* XXX Doesn't catch multiple IFDs. */
556 		dir->next->par = prop;
557 		return;
558 
559 	/* Record the Exif version. */
560 
561 	case EXIF_T_VERSION:
562 		byte4exif(prop->value, (unsigned char *)buf, o);
563 		buf[4] = '\0';
564 		t->exifmin = (short)atoi(buf + 2);
565 		buf[2] = '\0';
566 		t->exifmaj = (short)atoi(buf);
567 
568 		exifstralloc(&prop->str, 8);
569 		snprintf(prop->str, 7, "%d.%02d", t->exifmaj, t->exifmin);
570 		break;
571 
572 	/* Process a maker note. */
573 
574 	case EXIF_T_MAKERNOTE:
575 		if (!domkr)
576 			return;
577 
578 		/* Maker function can change metadata if necessary. */
579 
580 		t->mkrmd = dir->md;
581 		md = &t->mkrmd;
582 		while (dir->next)
583 			dir = dir->next;
584 
585 		/*
586 		 * Try to process maker note IFDs using the function
587 		 * specified for the maker.
588 		 *
589 		 * XXX Note that for this to work right, we have to see
590 		 * the manufacturer tag first to figure out makerifd().
591 		 */
592 
593 		if (makers[t->mkrval].ifdfun) {
594 			if (!offsanity(prop, 1, dir))
595 				dir->next =
596 				    makers[t->mkrval].ifdfun(prop->value, md);
597 		} else
598 			exifwarn("maker note not supported");
599 
600 		if (!dir->next)
601 			break;
602 
603 		/* XXX Doesn't catch multiple IFDs. */
604 		dir->next->par = prop;
605 		return;
606 
607 	/* Lookup functions for maker note. */
608 
609 	case EXIF_T_EQUIPMAKE:
610 
611 		/* Sanity check the offset. */
612 
613 		if (offsanity(prop, 1, dir))
614 			return;
615 
616 		strncpy(buf, (const char *)(btiff + prop->value), sizeof(buf));
617 		buf[sizeof(buf) - 1] = '\0';
618 		for (c = buf; *c; c++) *c = tolower(*c);
619 
620 		for (i = 0; makers[i].val != EXIF_MKR_UNKNOWN; i++)
621 			if (!strncmp(buf, makers[i].name,
622 			    strlen(makers[i].name)))
623 				break;
624 		t->mkrval = (short)i;
625 
626 		/* Keep processing (ASCII value). */
627 		break;
628 
629 	/*
630 	 * Handle user comment.  According to the spec, the first 8 bytes
631 	 * of the comment indicate what charset follows.  For now, we
632 	 * just support ASCII.
633 	 *
634 	 * XXX A handful of the GPS tags are also stored in this format.
635 	 */
636 
637 	case 0x001b:	/* GPSProcessingMethod */
638 	case 0x001c:	/* GPSAreaInformation */
639 		/*
640 		 * XXX Note that this is kind of dangerous -- any other
641 		 * tag set won't reach the end of the switch...
642 		 */
643 		if (prop->tagset != gpstags)
644 			break;
645 		/* FALLTHROUGH */
646 
647 	case EXIF_T_USERCOMMENT:
648 
649 		/* Check for a comment type and sane offset. */
650 
651 		if (prop->count < 8) {
652 			exifwarn("invalid user comment length");
653 			prop->lvl = ED_BAD;
654 			return;
655 		}
656 
657 		if (offsanity(prop, 1, dir))
658 			return;
659 
660 		/* Ignore the 'comments' WinXP creates when rotating. */
661 #ifdef WINXP_BUGS
662 		for (i = 0; tags[i].tag < EXIF_T_UNKNOWN &&
663 		    tags[i].tag != EXIF_T_USERCOMMENT; i++);
664 		if (tags[i].type && tags[i].type != prop->type)
665 			break;
666 #endif
667 		/* Lookup the comment type. */
668 
669 		for (i = 0; ucomment[i].descr; i++)
670 			if (!memcmp(ucomment[i].descr, btiff + prop->value, 8))
671 				break;
672 
673 		/* Handle an ASCII comment; strip any trailing whitespace. */
674 
675 		if (ucomment[i].val == TIFF_ASCII) {
676 			c = (char *)(btiff + prop->value + 8);
677 			d = strlen(c) < prop->count - 8 ? c + strlen(c) :
678 			    c + prop->count - 8;
679 
680 			while (d > c && isspace((int)*(d - 1))) --d;
681 
682 			exifstralloc(&prop->str, d - c + 1);
683 			strncpy(prop->str, c, d - c);
684 			prop->lvl = prop->str[0] ? ED_IMG : ED_VRB;
685 			return;
686 		}
687 		break;
688 
689 	case EXIF_T_FILESRC:
690 		/*
691 		 * This 'undefined' field is one byte; runs afoul of XP
692 		 * not zeroing out stuff.
693 		 */
694 #ifdef WINXP_BUGS
695 		prop->str = finddescr(filesrcs, (u_int16_t)(v & 0xFFU));
696 #else
697 		prop->str = finddescr(filesrcs, v);
698 #endif
699 		return;
700 	}
701 
702 	/*
703 	 * ASCII types.
704 	 */
705 
706 	if (prop->type == TIFF_ASCII) {
707 		/* Should fit in the value field. */
708 		if (prop->count < 5) {
709 			exifstralloc(&prop->str, 5);
710 			byte4exif(prop->value, (unsigned char *)prop->str, o);
711 			return;
712 		}
713 
714 		/* Sanity check the offset. */
715 		if (!offsanity(prop, 1, dir)) {
716 			exifstralloc(&prop->str, prop->count + 1);
717 			strncpy(prop->str, (const char *)(btiff + prop->value),
718 			    prop->count);
719 		}
720 		return;
721 	}
722 
723 	/*
724 	 * Rational types.  (Note that we'll redo some in our later pass.)
725 	 * We'll reduce and simplify the fraction.
726 	 *
727 	 * XXX Misses multiple rationals.
728 	 */
729 
730 	if ((prop->type == TIFF_RTNL || prop->type == TIFF_SRTNL) &&
731 	    !offsanity(prop, 8, dir)) {
732 
733 		exifstralloc(&prop->str, 32);
734 
735 		if (prop->type == TIFF_RTNL) {
736 			un = exif4byte(btiff + prop->value, o);
737 			ud = exif4byte(btiff + prop->value + 4, o);
738 			denom = gcd(un, ud);
739 			fixfract(prop->str, un, ud, denom);
740 		} else {
741 			sn = exif4sbyte(btiff + prop->value, o);
742 			sd = exif4sbyte(btiff + prop->value + 4, o);
743 			denom = gcd(abs(sn), abs(sd));
744 			fixfract(prop->str, sn, sd, (int32_t)denom);
745 		}
746 		return;
747 	}
748 
749 	/*
750 	 * Multiple short values.
751 	 * XXX For now, we're going to ignore tags with count > 8.  Maker
752 	 * note tags frequently consist of many shorts; we don't really
753 	 * want to be spitting these out.  (Plus, TransferFunction is huge.)
754 	 *
755 	 * XXX Note that this doesn't apply to two shorts, which are
756 	 * stuffed into the value.
757 	 */
758 
759 	if ((prop->type == TIFF_SHORT || prop->type == TIFF_SSHORT) &&
760 	    prop->count > 2 && !offsanity(prop, 2, dir)) {
761 
762 		if (prop->count > 8)
763 			return;
764 		len = 8 * prop->count + 1;
765 		exifstralloc(&prop->str, len);
766 
767 		for (i = 0; i < prop->count; i++) {
768 			if (prop->type == TIFF_SHORT)
769 				snprintf(prop->str + strlen(prop->str),
770 				    len - strlen(prop->str) - 1, "%d, ",
771 				    exif2byte(btiff + prop->value +
772 				    (i * 2), o));
773 			else
774 				snprintf(prop->str + strlen(prop->str),
775 				    len - strlen(prop->str) - 1, "%d, ",
776 				    exif2sbyte(btiff + prop->value +
777 				    (i * 2), o));
778 		}
779 		prop->str[strlen(prop->str) - 2] = '\0';
780 		return;
781 	}
782 	return;
783 }
784 
785 
786 /*
787  * Delete dynamic Exif property and IFD memory.
788  */
789 void
790 exiffree(struct exiftags *t)
791 {
792 	struct exifprop *tmpprop;
793 	struct ifdoff *tmpoff;
794 
795 	if (!t) return;
796 
797 	while ((tmpprop = t->props)) {
798 		if (t->props->str) free(t->props->str);
799 		t->props = t->props->next;
800 		free(tmpprop);
801 	}
802 	while ((tmpoff = (struct ifdoff *)(t->md.ifdoffs))) {
803 		t->md.ifdoffs = (void *)tmpoff->next;
804 		free(tmpoff);
805 	}
806 	free(t);
807 }
808 
809 
810 /*
811  * Scan the Exif section.
812  */
813 struct exiftags *
814 exifscan(unsigned char *b, int len, int domkr)
815 {
816 	int seq;
817 	u_int32_t ifdoff;
818 	struct exiftags *t;
819 	struct ifd *curifd, *tmpifd;
820 
821 	/* Create and initialize our file info structure. */
822 
823 	t = (struct exiftags *)malloc(sizeof(struct exiftags));
824 	if (!t) {
825 		exifwarn2("can't allocate file info",
826 		    (const char *)strerror(errno));
827 		return (NULL);
828 	}
829 	memset(t, 0, sizeof(struct exiftags));
830 
831 	seq = 0;
832 	t->md.etiff = b + len;	/* End of TIFF. */
833 
834 	/*
835 	 * Make sure we've got the proper Exif header.  If not, we're
836 	 * looking at somebody else's APP1 (e.g., Photoshop).
837 	 */
838 
839 	if (memcmp(b, "Exif\0\0", 6)) {
840 		exiffree(t);
841 		return (NULL);
842 	}
843 	b += 6;
844 
845 	/* Determine endianness of the TIFF data. */
846 
847 	if (!memcmp(b, "MM", 2))
848 		t->md.order = BIG;
849 	else if (!memcmp(b, "II", 2))
850 		t->md.order = LITTLE;
851 	else {
852 		exifwarn("invalid TIFF header");
853 		exiffree(t);
854 		return (NULL);
855 	}
856 
857 	t->md.btiff = b;	/* Beginning of TIFF. */
858 	b += 2;
859 
860 	/* Verify the TIFF header. */
861 
862 	if (exif2byte(b, t->md.order) != 42) {
863 		exifwarn("invalid TIFF header");
864 		exiffree(t);
865 		return (NULL);
866 	}
867 	b += 2;
868 
869 	/* Get the 0th IFD, where all of the good stuff should start. */
870 
871 	ifdoff = exif4byte(b, t->md.order);
872 	curifd = readifds(ifdoff, tags, &t->md);
873 	if (!curifd) {
874 		exifwarn("invalid Exif format (couldn't read IFD0)");
875 		exiffree(t);
876 		return (NULL);
877 	}
878 
879 	/* Now, let's parse the fields... */
880 
881 	while ((tmpifd = curifd)) {
882 		readtags(curifd, seq++, t, domkr);
883 		curifd = curifd->next;
884 		free(tmpifd);		/* No need to keep it around... */
885 	}
886 
887 	return (t);
888 }
889 
890 
891 /*
892  * Read the Exif section and prepare the data for output.
893  */
894 struct exiftags *
895 exifparse(unsigned char *b, int len)
896 {
897 	struct exiftags *t;
898 	struct exifprop *curprop;
899 
900 	/* Find the section and scan it. */
901 
902 	if (!(t = exifscan(b, len, TRUE)))
903 		return (NULL);
904 
905 	/* Make field values pretty. */
906 
907 	curprop = t->props;
908 	while (curprop) {
909 		postprop(curprop, t);
910 		tweaklvl(curprop, t);
911 		curprop = curprop->next;
912 	}
913 
914 	return (t);
915 }
916