1 /* $Id: tif_dir.c,v 1.119 2014-12-27 15:20:42 erouault Exp $ */
2 
3 /*
4  * Copyright (c) 1988-1997 Sam Leffler
5  * Copyright (c) 1991-1997 Silicon Graphics, Inc.
6  *
7  * Permission to use, copy, modify, distribute, and sell this software and
8  * its documentation for any purpose is hereby granted without fee, provided
9  * that (i) the above copyright notices and this permission notice appear in
10  * all copies of the software and related documentation, and (ii) the names of
11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
12  * publicity relating to the software without the specific, prior written
13  * permission of Sam Leffler and Silicon Graphics.
14  *
15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24  * OF THIS SOFTWARE.
25  */
26 
27 /*
28  * TIFF Library.
29  *
30  * Directory Tag Get & Set Routines.
31  * (and also some miscellaneous stuff)
32  */
33 #include "tiffiop.h"
34 
35 /*
36  * These are used in the backwards compatibility code...
37  */
38 #define DATATYPE_VOID		0       /* !untyped data */
39 #define DATATYPE_INT		1       /* !signed integer data */
40 #define DATATYPE_UINT		2       /* !unsigned integer data */
41 #define DATATYPE_IEEEFP		3       /* !IEEE floating point data */
42 
43 static void
setByteArray(void ** vpp,void * vp,size_t nmemb,size_t elem_size)44 setByteArray(void** vpp, void* vp, size_t nmemb, size_t elem_size)
45 {
46 	if (*vpp)
47 		_TIFFfree(*vpp), *vpp = 0;
48 	if (vp) {
49 		tmsize_t bytes = (tmsize_t)(nmemb * elem_size);
50 		if (elem_size && bytes / elem_size == nmemb)
51 			*vpp = (void*) _TIFFmalloc(bytes);
52 		if (*vpp)
53 			_TIFFmemcpy(*vpp, vp, bytes);
54 	}
55 }
_TIFFsetByteArray(void ** vpp,void * vp,uint32 n)56 void _TIFFsetByteArray(void** vpp, void* vp, uint32 n)
57     { setByteArray(vpp, vp, n, 1); }
_TIFFsetString(char ** cpp,char * cp)58 void _TIFFsetString(char** cpp, char* cp)
59     { setByteArray((void**) cpp, (void*) cp, strlen(cp)+1, 1); }
_TIFFsetNString(char ** cpp,char * cp,uint32 n)60 void _TIFFsetNString(char** cpp, char* cp, uint32 n)
61     { setByteArray((void**) cpp, (void*) cp, n, 1); }
_TIFFsetShortArray(uint16 ** wpp,uint16 * wp,uint32 n)62 void _TIFFsetShortArray(uint16** wpp, uint16* wp, uint32 n)
63     { setByteArray((void**) wpp, (void*) wp, n, sizeof (uint16)); }
_TIFFsetLongArray(uint32 ** lpp,uint32 * lp,uint32 n)64 void _TIFFsetLongArray(uint32** lpp, uint32* lp, uint32 n)
65     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint32)); }
_TIFFsetLong8Array(uint64 ** lpp,uint64 * lp,uint32 n)66 void _TIFFsetLong8Array(uint64** lpp, uint64* lp, uint32 n)
67     { setByteArray((void**) lpp, (void*) lp, n, sizeof (uint64)); }
_TIFFsetFloatArray(float ** fpp,float * fp,uint32 n)68 void _TIFFsetFloatArray(float** fpp, float* fp, uint32 n)
69     { setByteArray((void**) fpp, (void*) fp, n, sizeof (float)); }
_TIFFsetDoubleArray(double ** dpp,double * dp,uint32 n)70 void _TIFFsetDoubleArray(double** dpp, double* dp, uint32 n)
71     { setByteArray((void**) dpp, (void*) dp, n, sizeof (double)); }
72 
73 static void
setDoubleArrayOneValue(double ** vpp,double value,size_t nmemb)74 setDoubleArrayOneValue(double** vpp, double value, size_t nmemb)
75 {
76 	if (*vpp)
77 		_TIFFfree(*vpp);
78 	*vpp = _TIFFmalloc(nmemb*sizeof(double));
79 	if (*vpp)
80 	{
81 		while (nmemb--)
82 			((double*)*vpp)[nmemb] = value;
83 	}
84 }
85 
86 /*
87  * Install extra samples information.
88  */
89 static int
setExtraSamples(TIFFDirectory * td,va_list ap,uint32 * v)90 setExtraSamples(TIFFDirectory* td, va_list ap, uint32* v)
91 {
92 /* XXX: Unassociated alpha data == 999 is a known Corel Draw bug, see below */
93 #define EXTRASAMPLE_COREL_UNASSALPHA 999
94 
95 	uint16* va;
96 	uint32 i;
97 
98 	*v = (uint16) va_arg(ap, uint16_vap);
99 	if ((uint16) *v > td->td_samplesperpixel)
100 		return 0;
101 	va = va_arg(ap, uint16*);
102 	if (*v > 0 && va == NULL)		/* typically missing param */
103 		return 0;
104 	for (i = 0; i < *v; i++) {
105 		if (va[i] > EXTRASAMPLE_UNASSALPHA) {
106 			/*
107 			 * XXX: Corel Draw is known to produce incorrect
108 			 * ExtraSamples tags which must be patched here if we
109 			 * want to be able to open some of the damaged TIFF
110 			 * files:
111 			 */
112 			if (va[i] == EXTRASAMPLE_COREL_UNASSALPHA)
113 				va[i] = EXTRASAMPLE_UNASSALPHA;
114 			else
115 				return 0;
116 		}
117 	}
118 	td->td_extrasamples = (uint16) *v;
119 	_TIFFsetShortArray(&td->td_sampleinfo, va, td->td_extrasamples);
120 	return 1;
121 
122 #undef EXTRASAMPLE_COREL_UNASSALPHA
123 }
124 
125 /*
126  * Confirm we have "samplesperpixel" ink names separated by \0.  Returns
127  * zero if the ink names are not as expected.
128  */
129 static uint32
checkInkNamesString(TIFF * tif,uint32 slen,const char * s)130 checkInkNamesString(TIFF* tif, uint32 slen, const char* s)
131 {
132 	TIFFDirectory* td = &tif->tif_dir;
133 	uint16 i = td->td_samplesperpixel;
134 
135 	if (slen > 0) {
136 		const char* ep = s+slen;
137 		const char* cp = s;
138 		for (; i > 0; i--) {
139 			for (; cp < ep && *cp != '\0'; cp++) {}
140 			if (cp >= ep)
141 				goto bad;
142 			cp++;				/* skip \0 */
143 		}
144 		return ((uint32)(cp-s));
145 	}
146 bad:
147 	TIFFErrorExt(tif->tif_clientdata, "TIFFSetField",
148 	    "%s: Invalid InkNames value; expecting %d names, found %d",
149 	    tif->tif_name,
150 	    td->td_samplesperpixel,
151 	    td->td_samplesperpixel-i);
152 	return (0);
153 }
154 
155 static int
_TIFFVSetField(TIFF * tif,uint32 tag,va_list ap)156 _TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
157 {
158 	static const char module[] = "_TIFFVSetField";
159 
160 	TIFFDirectory* td = &tif->tif_dir;
161 	int status = 1;
162 	uint32 v32, i, v;
163     double dblval;
164 	char* s;
165 	const TIFFField *fip = TIFFFindField(tif, tag, TIFF_ANY);
166 	uint32 standard_tag = tag;
167 	if( fip == NULL ) /* cannot happen since OkToChangeTag() already checks it */
168 	    return 0;
169 	/*
170 	 * We want to force the custom code to be used for custom
171 	 * fields even if the tag happens to match a well known
172 	 * one - important for reinterpreted handling of standard
173 	 * tag values in custom directories (ie. EXIF)
174 	 */
175 	if (fip->field_bit == FIELD_CUSTOM) {
176 		standard_tag = 0;
177 	}
178 
179 	switch (standard_tag) {
180 	case TIFFTAG_SUBFILETYPE:
181 		td->td_subfiletype = (uint32) va_arg(ap, uint32);
182 		break;
183 	case TIFFTAG_IMAGEWIDTH:
184 		td->td_imagewidth = (uint32) va_arg(ap, uint32);
185 		break;
186 	case TIFFTAG_IMAGELENGTH:
187 		td->td_imagelength = (uint32) va_arg(ap, uint32);
188 		break;
189 	case TIFFTAG_BITSPERSAMPLE:
190 		td->td_bitspersample = (uint16) va_arg(ap, uint16_vap);
191 		/*
192 		 * If the data require post-decoding processing to byte-swap
193 		 * samples, set it up here.  Note that since tags are required
194 		 * to be ordered, compression code can override this behaviour
195 		 * in the setup method if it wants to roll the post decoding
196 		 * work in with its normal work.
197 		 */
198 		if (tif->tif_flags & TIFF_SWAB) {
199 			if (td->td_bitspersample == 8)
200 				tif->tif_postdecode = _TIFFNoPostDecode;
201 			else if (td->td_bitspersample == 16)
202 				tif->tif_postdecode = _TIFFSwab16BitData;
203 			else if (td->td_bitspersample == 24)
204 				tif->tif_postdecode = _TIFFSwab24BitData;
205 			else if (td->td_bitspersample == 32)
206 				tif->tif_postdecode = _TIFFSwab32BitData;
207 			else if (td->td_bitspersample == 64)
208 				tif->tif_postdecode = _TIFFSwab64BitData;
209 			else if (td->td_bitspersample == 128) /* two 64's */
210 				tif->tif_postdecode = _TIFFSwab64BitData;
211 		}
212 		break;
213 	case TIFFTAG_COMPRESSION:
214 		v = (uint16) va_arg(ap, uint16_vap);
215 		/*
216 		 * If we're changing the compression scheme, the notify the
217 		 * previous module so that it can cleanup any state it's
218 		 * setup.
219 		 */
220 		if (TIFFFieldSet(tif, FIELD_COMPRESSION)) {
221 			if ((uint32)td->td_compression == v)
222 				break;
223 			(*tif->tif_cleanup)(tif);
224 			tif->tif_flags &= ~TIFF_CODERSETUP;
225 		}
226 		/*
227 		 * Setup new compression routine state.
228 		 */
229 		if( (status = TIFFSetCompressionScheme(tif, v)) != 0 )
230 		    td->td_compression = (uint16) v;
231 		else
232 		    status = 0;
233 		break;
234 	case TIFFTAG_PHOTOMETRIC:
235 		td->td_photometric = (uint16) va_arg(ap, uint16_vap);
236 		break;
237 	case TIFFTAG_THRESHHOLDING:
238 		td->td_threshholding = (uint16) va_arg(ap, uint16_vap);
239 		break;
240 	case TIFFTAG_FILLORDER:
241 		v = (uint16) va_arg(ap, uint16_vap);
242 		if (v != FILLORDER_LSB2MSB && v != FILLORDER_MSB2LSB)
243 			goto badvalue;
244 		td->td_fillorder = (uint16) v;
245 		break;
246 	case TIFFTAG_ORIENTATION:
247 		v = (uint16) va_arg(ap, uint16_vap);
248 		if (v < ORIENTATION_TOPLEFT || ORIENTATION_LEFTBOT < v)
249 			goto badvalue;
250 		else
251 			td->td_orientation = (uint16) v;
252 		break;
253 	case TIFFTAG_SAMPLESPERPIXEL:
254 		v = (uint16) va_arg(ap, uint16_vap);
255 		if (v == 0)
256 			goto badvalue;
257 		td->td_samplesperpixel = (uint16) v;
258 		break;
259 	case TIFFTAG_ROWSPERSTRIP:
260 		v32 = (uint32) va_arg(ap, uint32);
261 		if (v32 == 0)
262 			goto badvalue32;
263 		td->td_rowsperstrip = v32;
264 		if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
265 			td->td_tilelength = v32;
266 			td->td_tilewidth = td->td_imagewidth;
267 		}
268 		break;
269 	case TIFFTAG_MINSAMPLEVALUE:
270 		td->td_minsamplevalue = (uint16) va_arg(ap, uint16_vap);
271 		break;
272 	case TIFFTAG_MAXSAMPLEVALUE:
273 		td->td_maxsamplevalue = (uint16) va_arg(ap, uint16_vap);
274 		break;
275 	case TIFFTAG_SMINSAMPLEVALUE:
276 		if (tif->tif_flags & TIFF_PERSAMPLE)
277 			_TIFFsetDoubleArray(&td->td_sminsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);
278 		else
279 			setDoubleArrayOneValue(&td->td_sminsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
280 		break;
281 	case TIFFTAG_SMAXSAMPLEVALUE:
282 		if (tif->tif_flags & TIFF_PERSAMPLE)
283 			_TIFFsetDoubleArray(&td->td_smaxsamplevalue, va_arg(ap, double*), td->td_samplesperpixel);
284 		else
285 			setDoubleArrayOneValue(&td->td_smaxsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
286 		break;
287 	case TIFFTAG_XRESOLUTION:
288         dblval = va_arg(ap, double);
289         if( dblval < 0 )
290             goto badvaluedouble;
291 		td->td_xresolution = (float) dblval;
292 		break;
293 	case TIFFTAG_YRESOLUTION:
294         dblval = va_arg(ap, double);
295         if( dblval < 0 )
296             goto badvaluedouble;
297 		td->td_yresolution = (float) dblval;
298 		break;
299 	case TIFFTAG_PLANARCONFIG:
300 		v = (uint16) va_arg(ap, uint16_vap);
301 		if (v != PLANARCONFIG_CONTIG && v != PLANARCONFIG_SEPARATE)
302 			goto badvalue;
303 		td->td_planarconfig = (uint16) v;
304 		break;
305 	case TIFFTAG_XPOSITION:
306 		td->td_xposition = (float) va_arg(ap, double);
307 		break;
308 	case TIFFTAG_YPOSITION:
309 		td->td_yposition = (float) va_arg(ap, double);
310 		break;
311 	case TIFFTAG_RESOLUTIONUNIT:
312 		v = (uint16) va_arg(ap, uint16_vap);
313 		if (v < RESUNIT_NONE || RESUNIT_CENTIMETER < v)
314 			goto badvalue;
315 		td->td_resolutionunit = (uint16) v;
316 		break;
317 	case TIFFTAG_PAGENUMBER:
318 		td->td_pagenumber[0] = (uint16) va_arg(ap, uint16_vap);
319 		td->td_pagenumber[1] = (uint16) va_arg(ap, uint16_vap);
320 		break;
321 	case TIFFTAG_HALFTONEHINTS:
322 		td->td_halftonehints[0] = (uint16) va_arg(ap, uint16_vap);
323 		td->td_halftonehints[1] = (uint16) va_arg(ap, uint16_vap);
324 		break;
325 	case TIFFTAG_COLORMAP:
326 		v32 = (uint32)(1L<<td->td_bitspersample);
327 		_TIFFsetShortArray(&td->td_colormap[0], va_arg(ap, uint16*), v32);
328 		_TIFFsetShortArray(&td->td_colormap[1], va_arg(ap, uint16*), v32);
329 		_TIFFsetShortArray(&td->td_colormap[2], va_arg(ap, uint16*), v32);
330 		break;
331 	case TIFFTAG_EXTRASAMPLES:
332 		if (!setExtraSamples(td, ap, &v))
333 			goto badvalue;
334 		break;
335 	case TIFFTAG_MATTEING:
336 		td->td_extrasamples =  (((uint16) va_arg(ap, uint16_vap)) != 0);
337 		if (td->td_extrasamples) {
338 			uint16 sv = EXTRASAMPLE_ASSOCALPHA;
339 			_TIFFsetShortArray(&td->td_sampleinfo, &sv, 1);
340 		}
341 		break;
342 	case TIFFTAG_TILEWIDTH:
343 		v32 = (uint32) va_arg(ap, uint32);
344 		if (v32 % 16) {
345 			if (tif->tif_mode != O_RDONLY)
346 				goto badvalue32;
347 			TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
348 				"Nonstandard tile width %d, convert file", v32);
349 		}
350 		td->td_tilewidth = v32;
351 		tif->tif_flags |= TIFF_ISTILED;
352 		break;
353 	case TIFFTAG_TILELENGTH:
354 		v32 = (uint32) va_arg(ap, uint32);
355 		if (v32 % 16) {
356 			if (tif->tif_mode != O_RDONLY)
357 				goto badvalue32;
358 			TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
359 			    "Nonstandard tile length %d, convert file", v32);
360 		}
361 		td->td_tilelength = v32;
362 		tif->tif_flags |= TIFF_ISTILED;
363 		break;
364 	case TIFFTAG_TILEDEPTH:
365 		v32 = (uint32) va_arg(ap, uint32);
366 		if (v32 == 0)
367 			goto badvalue32;
368 		td->td_tiledepth = v32;
369 		break;
370 	case TIFFTAG_DATATYPE:
371 		v = (uint16) va_arg(ap, uint16_vap);
372 		switch (v) {
373 		case DATATYPE_VOID:	v = SAMPLEFORMAT_VOID;	break;
374 		case DATATYPE_INT:	v = SAMPLEFORMAT_INT;	break;
375 		case DATATYPE_UINT:	v = SAMPLEFORMAT_UINT;	break;
376 		case DATATYPE_IEEEFP:	v = SAMPLEFORMAT_IEEEFP;break;
377 		default:		goto badvalue;
378 		}
379 		td->td_sampleformat = (uint16) v;
380 		break;
381 	case TIFFTAG_SAMPLEFORMAT:
382 		v = (uint16) va_arg(ap, uint16_vap);
383 		if (v < SAMPLEFORMAT_UINT || SAMPLEFORMAT_COMPLEXIEEEFP < v)
384 			goto badvalue;
385 		td->td_sampleformat = (uint16) v;
386 
387 		/*  Try to fix up the SWAB function for complex data. */
388 		if( td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT
389 		    && td->td_bitspersample == 32
390 		    && tif->tif_postdecode == _TIFFSwab32BitData )
391 		    tif->tif_postdecode = _TIFFSwab16BitData;
392 		else if( (td->td_sampleformat == SAMPLEFORMAT_COMPLEXINT
393 			  || td->td_sampleformat == SAMPLEFORMAT_COMPLEXIEEEFP)
394 			 && td->td_bitspersample == 64
395 			 && tif->tif_postdecode == _TIFFSwab64BitData )
396 		    tif->tif_postdecode = _TIFFSwab32BitData;
397 		break;
398 	case TIFFTAG_IMAGEDEPTH:
399 		td->td_imagedepth = (uint32) va_arg(ap, uint32);
400 		break;
401 	case TIFFTAG_SUBIFD:
402 		if ((tif->tif_flags & TIFF_INSUBIFD) == 0) {
403 			td->td_nsubifd = (uint16) va_arg(ap, uint16_vap);
404 			_TIFFsetLong8Array(&td->td_subifd, (uint64*) va_arg(ap, uint64*),
405 			    (long) td->td_nsubifd);
406 		} else {
407 			TIFFErrorExt(tif->tif_clientdata, module,
408 				     "%s: Sorry, cannot nest SubIFDs",
409 				     tif->tif_name);
410 			status = 0;
411 		}
412 		break;
413 	case TIFFTAG_YCBCRPOSITIONING:
414 		td->td_ycbcrpositioning = (uint16) va_arg(ap, uint16_vap);
415 		break;
416 	case TIFFTAG_YCBCRSUBSAMPLING:
417 		td->td_ycbcrsubsampling[0] = (uint16) va_arg(ap, uint16_vap);
418 		td->td_ycbcrsubsampling[1] = (uint16) va_arg(ap, uint16_vap);
419 		break;
420 	case TIFFTAG_TRANSFERFUNCTION:
421 		v = (td->td_samplesperpixel - td->td_extrasamples) > 1 ? 3 : 1;
422 		for (i = 0; i < v; i++)
423 			_TIFFsetShortArray(&td->td_transferfunction[i],
424 			    va_arg(ap, uint16*), 1L<<td->td_bitspersample);
425 		break;
426 	case TIFFTAG_REFERENCEBLACKWHITE:
427 		/* XXX should check for null range */
428 		_TIFFsetFloatArray(&td->td_refblackwhite, va_arg(ap, float*), 6);
429 		break;
430 	case TIFFTAG_INKNAMES:
431 		v = (uint16) va_arg(ap, uint16_vap);
432 		s = va_arg(ap, char*);
433 		v = checkInkNamesString(tif, v, s);
434 		status = v > 0;
435 		if( v > 0 ) {
436 			_TIFFsetNString(&td->td_inknames, s, v);
437 			td->td_inknameslen = v;
438 		}
439 		break;
440 	case TIFFTAG_PERSAMPLE:
441 		v = (uint16) va_arg(ap, uint16_vap);
442 		if( v == PERSAMPLE_MULTI )
443 			tif->tif_flags |= TIFF_PERSAMPLE;
444 		else
445 			tif->tif_flags &= ~TIFF_PERSAMPLE;
446 		break;
447 	default: {
448 		TIFFTagValue *tv;
449 		int tv_size, iCustom;
450 
451 		/*
452 		 * This can happen if multiple images are open with different
453 		 * codecs which have private tags.  The global tag information
454 		 * table may then have tags that are valid for one file but not
455 		 * the other. If the client tries to set a tag that is not valid
456 		 * for the image's codec then we'll arrive here.  This
457 		 * happens, for example, when tiffcp is used to convert between
458 		 * compression schemes and codec-specific tags are blindly copied.
459 		 */
460 		if(fip->field_bit != FIELD_CUSTOM) {
461 			TIFFErrorExt(tif->tif_clientdata, module,
462 			    "%s: Invalid %stag \"%s\" (not supported by codec)",
463 			    tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
464 			    fip->field_name);
465 			status = 0;
466 			break;
467 		}
468 
469 		/*
470 		 * Find the existing entry for this custom value.
471 		 */
472 		tv = NULL;
473 		for (iCustom = 0; iCustom < td->td_customValueCount; iCustom++) {
474 			if (td->td_customValues[iCustom].info->field_tag == tag) {
475 				tv = td->td_customValues + iCustom;
476 				if (tv->value != NULL) {
477 					_TIFFfree(tv->value);
478 					tv->value = NULL;
479 				}
480 				break;
481 			}
482 		}
483 
484 		/*
485 		 * Grow the custom list if the entry was not found.
486 		 */
487 		if(tv == NULL) {
488 			TIFFTagValue *new_customValues;
489 
490 			td->td_customValueCount++;
491 			new_customValues = (TIFFTagValue *)
492 			    _TIFFrealloc(td->td_customValues,
493 			    sizeof(TIFFTagValue) * td->td_customValueCount);
494 			if (!new_customValues) {
495 				TIFFErrorExt(tif->tif_clientdata, module,
496 				    "%s: Failed to allocate space for list of custom values",
497 				    tif->tif_name);
498 				status = 0;
499 				goto end;
500 			}
501 
502 			td->td_customValues = new_customValues;
503 
504 			tv = td->td_customValues + (td->td_customValueCount - 1);
505 			tv->info = fip;
506 			tv->value = NULL;
507 			tv->count = 0;
508 		}
509 
510 		/*
511 		 * Set custom value ... save a copy of the custom tag value.
512 		 */
513 		tv_size = _TIFFDataSize(fip->field_type);
514 		if (tv_size == 0) {
515 			status = 0;
516 			TIFFErrorExt(tif->tif_clientdata, module,
517 			    "%s: Bad field type %d for \"%s\"",
518 			    tif->tif_name, fip->field_type,
519 			    fip->field_name);
520 			goto end;
521 		}
522 
523 		if (fip->field_type == TIFF_ASCII)
524 		{
525 			uint32 ma;
526 			char* mb;
527 			if (fip->field_passcount)
528 			{
529 				assert(fip->field_writecount==TIFF_VARIABLE2);
530 				ma=(uint32)va_arg(ap,uint32);
531 				mb=(char*)va_arg(ap,char*);
532 			}
533 			else
534 			{
535 				mb=(char*)va_arg(ap,char*);
536 				ma=(uint32)(strlen(mb)+1);
537 			}
538 			tv->count=ma;
539 			setByteArray(&tv->value,mb,ma,1);
540 		}
541 		else
542 		{
543 			if (fip->field_passcount) {
544 				if (fip->field_writecount == TIFF_VARIABLE2)
545 					tv->count = (uint32) va_arg(ap, uint32);
546 				else
547 					tv->count = (int) va_arg(ap, int);
548 			} else if (fip->field_writecount == TIFF_VARIABLE
549 			   || fip->field_writecount == TIFF_VARIABLE2)
550 				tv->count = 1;
551 			else if (fip->field_writecount == TIFF_SPP)
552 				tv->count = td->td_samplesperpixel;
553 			else
554 				tv->count = fip->field_writecount;
555 
556 			if (tv->count == 0) {
557 				status = 0;
558 				TIFFErrorExt(tif->tif_clientdata, module,
559 					     "%s: Null count for \"%s\" (type "
560 					     "%d, writecount %d, passcount %d)",
561 					     tif->tif_name,
562 					     fip->field_name,
563 					     fip->field_type,
564 					     fip->field_writecount,
565 					     fip->field_passcount);
566 				goto end;
567 			}
568 
569 			tv->value = _TIFFCheckMalloc(tif, tv->count, tv_size,
570 			    "custom tag binary object");
571 			if (!tv->value) {
572 				status = 0;
573 				goto end;
574 			}
575 
576 			if (fip->field_tag == TIFFTAG_DOTRANGE
577 			    && strcmp(fip->field_name,"DotRange") == 0) {
578 				/* TODO: This is an evil exception and should not have been
579 				   handled this way ... likely best if we move it into
580 				   the directory structure with an explicit field in
581 				   libtiff 4.1 and assign it a FIELD_ value */
582 				uint16 v[2];
583 				v[0] = (uint16)va_arg(ap, int);
584 				v[1] = (uint16)va_arg(ap, int);
585 				_TIFFmemcpy(tv->value, &v, 4);
586 			}
587 
588 			else if (fip->field_passcount
589 				  || fip->field_writecount == TIFF_VARIABLE
590 				  || fip->field_writecount == TIFF_VARIABLE2
591 				  || fip->field_writecount == TIFF_SPP
592 				  || tv->count > 1) {
593 				_TIFFmemcpy(tv->value, va_arg(ap, void *),
594 				    tv->count * tv_size);
595 			} else {
596 				char *val = (char *)tv->value;
597 				assert( tv->count == 1 );
598 
599 				switch (fip->field_type) {
600 				case TIFF_BYTE:
601 				case TIFF_UNDEFINED:
602 					{
603 						uint8 v = (uint8)va_arg(ap, int);
604 						_TIFFmemcpy(val, &v, tv_size);
605 					}
606 					break;
607 				case TIFF_SBYTE:
608 					{
609 						int8 v = (int8)va_arg(ap, int);
610 						_TIFFmemcpy(val, &v, tv_size);
611 					}
612 					break;
613 				case TIFF_SHORT:
614 					{
615 						uint16 v = (uint16)va_arg(ap, int);
616 						_TIFFmemcpy(val, &v, tv_size);
617 					}
618 					break;
619 				case TIFF_SSHORT:
620 					{
621 						int16 v = (int16)va_arg(ap, int);
622 						_TIFFmemcpy(val, &v, tv_size);
623 					}
624 					break;
625 				case TIFF_LONG:
626 				case TIFF_IFD:
627 					{
628 						uint32 v = va_arg(ap, uint32);
629 						_TIFFmemcpy(val, &v, tv_size);
630 					}
631 					break;
632 				case TIFF_SLONG:
633 					{
634 						int32 v = va_arg(ap, int32);
635 						_TIFFmemcpy(val, &v, tv_size);
636 					}
637 					break;
638 				case TIFF_LONG8:
639 				case TIFF_IFD8:
640 					{
641 						uint64 v = va_arg(ap, uint64);
642 						_TIFFmemcpy(val, &v, tv_size);
643 					}
644 					break;
645 				case TIFF_SLONG8:
646 					{
647 						int64 v = va_arg(ap, int64);
648 						_TIFFmemcpy(val, &v, tv_size);
649 					}
650 					break;
651 				case TIFF_RATIONAL:
652 				case TIFF_SRATIONAL:
653 				case TIFF_FLOAT:
654 					{
655 						float v = (float)va_arg(ap, double);
656 						_TIFFmemcpy(val, &v, tv_size);
657 					}
658 					break;
659 				case TIFF_DOUBLE:
660 					{
661 						double v = va_arg(ap, double);
662 						_TIFFmemcpy(val, &v, tv_size);
663 					}
664 					break;
665 				default:
666 					_TIFFmemset(val, 0, tv_size);
667 					status = 0;
668 					break;
669 				}
670 			}
671 		}
672 	}
673 	}
674 	if (status) {
675 		const TIFFField* fip=TIFFFieldWithTag(tif,tag);
676 		if (fip)
677 			TIFFSetFieldBit(tif, fip->field_bit);
678 		tif->tif_flags |= TIFF_DIRTYDIRECT;
679 	}
680 
681 end:
682 	va_end(ap);
683 	return (status);
684 badvalue:
685         {
686 		const TIFFField* fip=TIFFFieldWithTag(tif,tag);
687 		TIFFErrorExt(tif->tif_clientdata, module,
688 		     "%s: Bad value %u for \"%s\" tag",
689 		     tif->tif_name, v,
690 		     fip ? fip->field_name : "Unknown");
691 		va_end(ap);
692         }
693 	return (0);
694 badvalue32:
695         {
696 		const TIFFField* fip=TIFFFieldWithTag(tif,tag);
697 		TIFFErrorExt(tif->tif_clientdata, module,
698 		     "%s: Bad value %u for \"%s\" tag",
699 		     tif->tif_name, v32,
700 		     fip ? fip->field_name : "Unknown");
701 		va_end(ap);
702         }
703 	return (0);
704 badvaluedouble:
705         {
706         const TIFFField* fip=TIFFFieldWithTag(tif,tag);
707         TIFFErrorExt(tif->tif_clientdata, module,
708              "%s: Bad value %f for \"%s\" tag",
709              tif->tif_name, dblval,
710              fip ? fip->field_name : "Unknown");
711         va_end(ap);
712         }
713     return (0);
714 }
715 
716 /*
717  * Return 1/0 according to whether or not
718  * it is permissible to set the tag's value.
719  * Note that we allow ImageLength to be changed
720  * so that we can append and extend to images.
721  * Any other tag may not be altered once writing
722  * has commenced, unless its value has no effect
723  * on the format of the data that is written.
724  */
725 static int
OkToChangeTag(TIFF * tif,uint32 tag)726 OkToChangeTag(TIFF* tif, uint32 tag)
727 {
728 	const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
729 	if (!fip) {			/* unknown tag */
730 		TIFFErrorExt(tif->tif_clientdata, "TIFFSetField", "%s: Unknown %stag %u",
731 		    tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "", tag);
732 		return (0);
733 	}
734 	if (tag != TIFFTAG_IMAGELENGTH && (tif->tif_flags & TIFF_BEENWRITING) &&
735 	    !fip->field_oktochange) {
736 		/*
737 		 * Consult info table to see if tag can be changed
738 		 * after we've started writing.  We only allow changes
739 		 * to those tags that don't/shouldn't affect the
740 		 * compression and/or format of the data.
741 		 */
742 		TIFFErrorExt(tif->tif_clientdata, "TIFFSetField",
743 		    "%s: Cannot modify tag \"%s\" while writing",
744 		    tif->tif_name, fip->field_name);
745 		return (0);
746 	}
747 	return (1);
748 }
749 
750 /*
751  * Record the value of a field in the
752  * internal directory structure.  The
753  * field will be written to the file
754  * when/if the directory structure is
755  * updated.
756  */
757 int
TIFFSetField(TIFF * tif,uint32 tag,...)758 TIFFSetField(TIFF* tif, uint32 tag, ...)
759 {
760 	va_list ap;
761 	int status;
762 
763 	va_start(ap, tag);
764 	status = TIFFVSetField(tif, tag, ap);
765 	va_end(ap);
766 	return (status);
767 }
768 
769 /*
770  * Clear the contents of the field in the internal structure.
771  */
772 int
TIFFUnsetField(TIFF * tif,uint32 tag)773 TIFFUnsetField(TIFF* tif, uint32 tag)
774 {
775     const TIFFField *fip =  TIFFFieldWithTag(tif, tag);
776     TIFFDirectory* td = &tif->tif_dir;
777 
778     if( !fip )
779         return 0;
780 
781     if( fip->field_bit != FIELD_CUSTOM )
782         TIFFClrFieldBit(tif, fip->field_bit);
783     else
784     {
785         TIFFTagValue *tv = NULL;
786         int i;
787 
788         for (i = 0; i < td->td_customValueCount; i++) {
789 
790             tv = td->td_customValues + i;
791             if( tv->info->field_tag == tag )
792                 break;
793         }
794 
795         if( i < td->td_customValueCount )
796         {
797             _TIFFfree(tv->value);
798             for( ; i < td->td_customValueCount-1; i++) {
799                 td->td_customValues[i] = td->td_customValues[i+1];
800             }
801             td->td_customValueCount--;
802         }
803     }
804 
805     tif->tif_flags |= TIFF_DIRTYDIRECT;
806 
807     return (1);
808 }
809 
810 /*
811  * Like TIFFSetField, but taking a varargs
812  * parameter list.  This routine is useful
813  * for building higher-level interfaces on
814  * top of the library.
815  */
816 int
TIFFVSetField(TIFF * tif,uint32 tag,va_list ap)817 TIFFVSetField(TIFF* tif, uint32 tag, va_list ap)
818 {
819 	return OkToChangeTag(tif, tag) ?
820 	    (*tif->tif_tagmethods.vsetfield)(tif, tag, ap) : 0;
821 }
822 
823 static int
_TIFFVGetField(TIFF * tif,uint32 tag,va_list ap)824 _TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
825 {
826 	TIFFDirectory* td = &tif->tif_dir;
827 	int ret_val = 1;
828 	uint32 standard_tag = tag;
829 	const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
830 	if( fip == NULL ) /* cannot happen since TIFFGetField() already checks it */
831 	    return 0;
832 
833 	/*
834 	 * We want to force the custom code to be used for custom
835 	 * fields even if the tag happens to match a well known
836 	 * one - important for reinterpreted handling of standard
837 	 * tag values in custom directories (ie. EXIF)
838 	 */
839 	if (fip->field_bit == FIELD_CUSTOM) {
840 		standard_tag = 0;
841 	}
842 
843 	switch (standard_tag) {
844 		case TIFFTAG_SUBFILETYPE:
845 			*va_arg(ap, uint32*) = td->td_subfiletype;
846 			break;
847 		case TIFFTAG_IMAGEWIDTH:
848 			*va_arg(ap, uint32*) = td->td_imagewidth;
849 			break;
850 		case TIFFTAG_IMAGELENGTH:
851 			*va_arg(ap, uint32*) = td->td_imagelength;
852 			break;
853 		case TIFFTAG_BITSPERSAMPLE:
854 			*va_arg(ap, uint16*) = td->td_bitspersample;
855 			break;
856 		case TIFFTAG_COMPRESSION:
857 			*va_arg(ap, uint16*) = td->td_compression;
858 			break;
859 		case TIFFTAG_PHOTOMETRIC:
860 			*va_arg(ap, uint16*) = td->td_photometric;
861 			break;
862 		case TIFFTAG_THRESHHOLDING:
863 			*va_arg(ap, uint16*) = td->td_threshholding;
864 			break;
865 		case TIFFTAG_FILLORDER:
866 			*va_arg(ap, uint16*) = td->td_fillorder;
867 			break;
868 		case TIFFTAG_ORIENTATION:
869 			*va_arg(ap, uint16*) = td->td_orientation;
870 			break;
871 		case TIFFTAG_SAMPLESPERPIXEL:
872 			*va_arg(ap, uint16*) = td->td_samplesperpixel;
873 			break;
874 		case TIFFTAG_ROWSPERSTRIP:
875 			*va_arg(ap, uint32*) = td->td_rowsperstrip;
876 			break;
877 		case TIFFTAG_MINSAMPLEVALUE:
878 			*va_arg(ap, uint16*) = td->td_minsamplevalue;
879 			break;
880 		case TIFFTAG_MAXSAMPLEVALUE:
881 			*va_arg(ap, uint16*) = td->td_maxsamplevalue;
882 			break;
883 		case TIFFTAG_SMINSAMPLEVALUE:
884 			if (tif->tif_flags & TIFF_PERSAMPLE)
885 				*va_arg(ap, double**) = td->td_sminsamplevalue;
886 			else
887 			{
888 				/* libtiff historially treats this as a single value. */
889 				uint16 i;
890 				double v = td->td_sminsamplevalue[0];
891 				for (i=1; i < td->td_samplesperpixel; ++i)
892 					if( td->td_sminsamplevalue[i] < v )
893 						v = td->td_sminsamplevalue[i];
894 				*va_arg(ap, double*) = v;
895 			}
896 			break;
897 		case TIFFTAG_SMAXSAMPLEVALUE:
898 			if (tif->tif_flags & TIFF_PERSAMPLE)
899 				*va_arg(ap, double**) = td->td_smaxsamplevalue;
900 			else
901 			{
902 				/* libtiff historially treats this as a single value. */
903 				uint16 i;
904 				double v = td->td_smaxsamplevalue[0];
905 				for (i=1; i < td->td_samplesperpixel; ++i)
906 					if( td->td_smaxsamplevalue[i] > v )
907 						v = td->td_smaxsamplevalue[i];
908 				*va_arg(ap, double*) = v;
909 			}
910 			break;
911 		case TIFFTAG_XRESOLUTION:
912 			*va_arg(ap, float*) = td->td_xresolution;
913 			break;
914 		case TIFFTAG_YRESOLUTION:
915 			*va_arg(ap, float*) = td->td_yresolution;
916 			break;
917 		case TIFFTAG_PLANARCONFIG:
918 			*va_arg(ap, uint16*) = td->td_planarconfig;
919 			break;
920 		case TIFFTAG_XPOSITION:
921 			*va_arg(ap, float*) = td->td_xposition;
922 			break;
923 		case TIFFTAG_YPOSITION:
924 			*va_arg(ap, float*) = td->td_yposition;
925 			break;
926 		case TIFFTAG_RESOLUTIONUNIT:
927 			*va_arg(ap, uint16*) = td->td_resolutionunit;
928 			break;
929 		case TIFFTAG_PAGENUMBER:
930 			*va_arg(ap, uint16*) = td->td_pagenumber[0];
931 			*va_arg(ap, uint16*) = td->td_pagenumber[1];
932 			break;
933 		case TIFFTAG_HALFTONEHINTS:
934 			*va_arg(ap, uint16*) = td->td_halftonehints[0];
935 			*va_arg(ap, uint16*) = td->td_halftonehints[1];
936 			break;
937 		case TIFFTAG_COLORMAP:
938 			*va_arg(ap, uint16**) = td->td_colormap[0];
939 			*va_arg(ap, uint16**) = td->td_colormap[1];
940 			*va_arg(ap, uint16**) = td->td_colormap[2];
941 			break;
942 		case TIFFTAG_STRIPOFFSETS:
943 		case TIFFTAG_TILEOFFSETS:
944 			_TIFFFillStriles( tif );
945 			*va_arg(ap, uint64**) = td->td_stripoffset;
946 			break;
947 		case TIFFTAG_STRIPBYTECOUNTS:
948 		case TIFFTAG_TILEBYTECOUNTS:
949 			_TIFFFillStriles( tif );
950 			*va_arg(ap, uint64**) = td->td_stripbytecount;
951 			break;
952 		case TIFFTAG_MATTEING:
953 			*va_arg(ap, uint16*) =
954 			    (td->td_extrasamples == 1 &&
955 			    td->td_sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
956 			break;
957 		case TIFFTAG_EXTRASAMPLES:
958 			*va_arg(ap, uint16*) = td->td_extrasamples;
959 			*va_arg(ap, uint16**) = td->td_sampleinfo;
960 			break;
961 		case TIFFTAG_TILEWIDTH:
962 			*va_arg(ap, uint32*) = td->td_tilewidth;
963 			break;
964 		case TIFFTAG_TILELENGTH:
965 			*va_arg(ap, uint32*) = td->td_tilelength;
966 			break;
967 		case TIFFTAG_TILEDEPTH:
968 			*va_arg(ap, uint32*) = td->td_tiledepth;
969 			break;
970 		case TIFFTAG_DATATYPE:
971 			switch (td->td_sampleformat) {
972 				case SAMPLEFORMAT_UINT:
973 					*va_arg(ap, uint16*) = DATATYPE_UINT;
974 					break;
975 				case SAMPLEFORMAT_INT:
976 					*va_arg(ap, uint16*) = DATATYPE_INT;
977 					break;
978 				case SAMPLEFORMAT_IEEEFP:
979 					*va_arg(ap, uint16*) = DATATYPE_IEEEFP;
980 					break;
981 				case SAMPLEFORMAT_VOID:
982 					*va_arg(ap, uint16*) = DATATYPE_VOID;
983 					break;
984 			}
985 			break;
986 		case TIFFTAG_SAMPLEFORMAT:
987 			*va_arg(ap, uint16*) = td->td_sampleformat;
988 			break;
989 		case TIFFTAG_IMAGEDEPTH:
990 			*va_arg(ap, uint32*) = td->td_imagedepth;
991 			break;
992 		case TIFFTAG_SUBIFD:
993 			*va_arg(ap, uint16*) = td->td_nsubifd;
994 			*va_arg(ap, uint64**) = td->td_subifd;
995 			break;
996 		case TIFFTAG_YCBCRPOSITIONING:
997 			*va_arg(ap, uint16*) = td->td_ycbcrpositioning;
998 			break;
999 		case TIFFTAG_YCBCRSUBSAMPLING:
1000 			*va_arg(ap, uint16*) = td->td_ycbcrsubsampling[0];
1001 			*va_arg(ap, uint16*) = td->td_ycbcrsubsampling[1];
1002 			break;
1003 		case TIFFTAG_TRANSFERFUNCTION:
1004 			*va_arg(ap, uint16**) = td->td_transferfunction[0];
1005 			if (td->td_samplesperpixel - td->td_extrasamples > 1) {
1006 				*va_arg(ap, uint16**) = td->td_transferfunction[1];
1007 				*va_arg(ap, uint16**) = td->td_transferfunction[2];
1008 			}
1009 			break;
1010 		case TIFFTAG_REFERENCEBLACKWHITE:
1011 			*va_arg(ap, float**) = td->td_refblackwhite;
1012 			break;
1013 		case TIFFTAG_INKNAMES:
1014 			*va_arg(ap, char**) = td->td_inknames;
1015 			break;
1016 		default:
1017 			{
1018 				int i;
1019 
1020 				/*
1021 				 * This can happen if multiple images are open
1022 				 * with different codecs which have private
1023 				 * tags.  The global tag information table may
1024 				 * then have tags that are valid for one file
1025 				 * but not the other. If the client tries to
1026 				 * get a tag that is not valid for the image's
1027 				 * codec then we'll arrive here.
1028 				 */
1029 				if( fip->field_bit != FIELD_CUSTOM )
1030 				{
1031 					TIFFErrorExt(tif->tif_clientdata, "_TIFFVGetField",
1032 					    "%s: Invalid %stag \"%s\" "
1033 					    "(not supported by codec)",
1034 					    tif->tif_name,
1035 					    isPseudoTag(tag) ? "pseudo-" : "",
1036 					    fip->field_name);
1037 					ret_val = 0;
1038 					break;
1039 				}
1040 
1041 				/*
1042 				 * Do we have a custom value?
1043 				 */
1044 				ret_val = 0;
1045 				for (i = 0; i < td->td_customValueCount; i++) {
1046 					TIFFTagValue *tv = td->td_customValues + i;
1047 
1048 					if (tv->info->field_tag != tag)
1049 						continue;
1050 
1051 					if (fip->field_passcount) {
1052 						if (fip->field_readcount == TIFF_VARIABLE2)
1053 							*va_arg(ap, uint32*) = (uint32)tv->count;
1054 						else  /* Assume TIFF_VARIABLE */
1055 							*va_arg(ap, uint16*) = (uint16)tv->count;
1056 						*va_arg(ap, void **) = tv->value;
1057 						ret_val = 1;
1058 					} else if (fip->field_tag == TIFFTAG_DOTRANGE
1059 						   && strcmp(fip->field_name,"DotRange") == 0) {
1060 						/* TODO: This is an evil exception and should not have been
1061 						   handled this way ... likely best if we move it into
1062 						   the directory structure with an explicit field in
1063 						   libtiff 4.1 and assign it a FIELD_ value */
1064 						*va_arg(ap, uint16*) = ((uint16 *)tv->value)[0];
1065 						*va_arg(ap, uint16*) = ((uint16 *)tv->value)[1];
1066 						ret_val = 1;
1067 					} else {
1068 						if (fip->field_type == TIFF_ASCII
1069 						    || fip->field_readcount == TIFF_VARIABLE
1070 						    || fip->field_readcount == TIFF_VARIABLE2
1071 						    || fip->field_readcount == TIFF_SPP
1072 						    || tv->count > 1) {
1073 							*va_arg(ap, void **) = tv->value;
1074 							ret_val = 1;
1075 						} else {
1076 							char *val = (char *)tv->value;
1077 							assert( tv->count == 1 );
1078 							switch (fip->field_type) {
1079 							case TIFF_BYTE:
1080 							case TIFF_UNDEFINED:
1081 								*va_arg(ap, uint8*) =
1082 									*(uint8 *)val;
1083 								ret_val = 1;
1084 								break;
1085 							case TIFF_SBYTE:
1086 								*va_arg(ap, int8*) =
1087 									*(int8 *)val;
1088 								ret_val = 1;
1089 								break;
1090 							case TIFF_SHORT:
1091 								*va_arg(ap, uint16*) =
1092 									*(uint16 *)val;
1093 								ret_val = 1;
1094 								break;
1095 							case TIFF_SSHORT:
1096 								*va_arg(ap, int16*) =
1097 									*(int16 *)val;
1098 								ret_val = 1;
1099 								break;
1100 							case TIFF_LONG:
1101 							case TIFF_IFD:
1102 								*va_arg(ap, uint32*) =
1103 									*(uint32 *)val;
1104 								ret_val = 1;
1105 								break;
1106 							case TIFF_SLONG:
1107 								*va_arg(ap, int32*) =
1108 									*(int32 *)val;
1109 								ret_val = 1;
1110 								break;
1111 							case TIFF_LONG8:
1112 							case TIFF_IFD8:
1113 								*va_arg(ap, uint64*) =
1114 									*(uint64 *)val;
1115 								ret_val = 1;
1116 								break;
1117 							case TIFF_SLONG8:
1118 								*va_arg(ap, int64*) =
1119 									*(int64 *)val;
1120 								ret_val = 1;
1121 								break;
1122 							case TIFF_RATIONAL:
1123 							case TIFF_SRATIONAL:
1124 							case TIFF_FLOAT:
1125 								*va_arg(ap, float*) =
1126 									*(float *)val;
1127 								ret_val = 1;
1128 								break;
1129 							case TIFF_DOUBLE:
1130 								*va_arg(ap, double*) =
1131 									*(double *)val;
1132 								ret_val = 1;
1133 								break;
1134 							default:
1135 								ret_val = 0;
1136 								break;
1137 							}
1138 						}
1139 					}
1140 					break;
1141 				}
1142 			}
1143 	}
1144 	return(ret_val);
1145 }
1146 
1147 /*
1148  * Return the value of a field in the
1149  * internal directory structure.
1150  */
1151 int
TIFFGetField(TIFF * tif,uint32 tag,...)1152 TIFFGetField(TIFF* tif, uint32 tag, ...)
1153 {
1154 	int status;
1155 	va_list ap;
1156 
1157 	va_start(ap, tag);
1158 	status = TIFFVGetField(tif, tag, ap);
1159 	va_end(ap);
1160 	return (status);
1161 }
1162 
1163 /*
1164  * Like TIFFGetField, but taking a varargs
1165  * parameter list.  This routine is useful
1166  * for building higher-level interfaces on
1167  * top of the library.
1168  */
1169 int
TIFFVGetField(TIFF * tif,uint32 tag,va_list ap)1170 TIFFVGetField(TIFF* tif, uint32 tag, va_list ap)
1171 {
1172 	const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
1173 	return (fip && (isPseudoTag(tag) || TIFFFieldSet(tif, fip->field_bit)) ?
1174 	    (*tif->tif_tagmethods.vgetfield)(tif, tag, ap) : 0);
1175 }
1176 
1177 #define	CleanupField(member) {		\
1178     if (td->member) {			\
1179 	_TIFFfree(td->member);		\
1180 	td->member = 0;			\
1181     }					\
1182 }
1183 
1184 /*
1185  * Release storage associated with a directory.
1186  */
1187 void
TIFFFreeDirectory(TIFF * tif)1188 TIFFFreeDirectory(TIFF* tif)
1189 {
1190 	TIFFDirectory *td = &tif->tif_dir;
1191 	int            i;
1192 
1193 	_TIFFmemset(td->td_fieldsset, 0, FIELD_SETLONGS);
1194 	CleanupField(td_sminsamplevalue);
1195 	CleanupField(td_smaxsamplevalue);
1196 	CleanupField(td_colormap[0]);
1197 	CleanupField(td_colormap[1]);
1198 	CleanupField(td_colormap[2]);
1199 	CleanupField(td_sampleinfo);
1200 	CleanupField(td_subifd);
1201 	CleanupField(td_inknames);
1202 	CleanupField(td_refblackwhite);
1203 	CleanupField(td_transferfunction[0]);
1204 	CleanupField(td_transferfunction[1]);
1205 	CleanupField(td_transferfunction[2]);
1206 	CleanupField(td_stripoffset);
1207 	CleanupField(td_stripbytecount);
1208 	TIFFClrFieldBit(tif, FIELD_YCBCRSUBSAMPLING);
1209 	TIFFClrFieldBit(tif, FIELD_YCBCRPOSITIONING);
1210 
1211 	/* Cleanup custom tag values */
1212 	for( i = 0; i < td->td_customValueCount; i++ ) {
1213 		if (td->td_customValues[i].value)
1214 			_TIFFfree(td->td_customValues[i].value);
1215 	}
1216 
1217 	td->td_customValueCount = 0;
1218 	CleanupField(td_customValues);
1219 
1220 #if defined(DEFER_STRILE_LOAD)
1221         _TIFFmemset( &(td->td_stripoffset_entry), 0, sizeof(TIFFDirEntry));
1222         _TIFFmemset( &(td->td_stripbytecount_entry), 0, sizeof(TIFFDirEntry));
1223 #endif
1224 }
1225 #undef CleanupField
1226 
1227 /*
1228  * Client Tag extension support (from Niles Ritter).
1229  */
1230 static TIFFExtendProc _TIFFextender = (TIFFExtendProc) NULL;
1231 
1232 TIFFExtendProc
TIFFSetTagExtender(TIFFExtendProc extender)1233 TIFFSetTagExtender(TIFFExtendProc extender)
1234 {
1235 	TIFFExtendProc prev = _TIFFextender;
1236 	_TIFFextender = extender;
1237 	return (prev);
1238 }
1239 
1240 /*
1241  * Setup for a new directory.  Should we automatically call
1242  * TIFFWriteDirectory() if the current one is dirty?
1243  *
1244  * The newly created directory will not exist on the file till
1245  * TIFFWriteDirectory(), TIFFFlush() or TIFFClose() is called.
1246  */
1247 int
TIFFCreateDirectory(TIFF * tif)1248 TIFFCreateDirectory(TIFF* tif)
1249 {
1250 	TIFFDefaultDirectory(tif);
1251 	tif->tif_diroff = 0;
1252 	tif->tif_nextdiroff = 0;
1253 	tif->tif_curoff = 0;
1254 	tif->tif_row = (uint32) -1;
1255 	tif->tif_curstrip = (uint32) -1;
1256 
1257 	return 0;
1258 }
1259 
1260 int
TIFFCreateCustomDirectory(TIFF * tif,const TIFFFieldArray * infoarray)1261 TIFFCreateCustomDirectory(TIFF* tif, const TIFFFieldArray* infoarray)
1262 {
1263 	TIFFDefaultDirectory(tif);
1264 
1265 	/*
1266 	 * Reset the field definitions to match the application provided list.
1267 	 * Hopefully TIFFDefaultDirectory() won't have done anything irreversable
1268 	 * based on it's assumption this is an image directory.
1269 	 */
1270 	_TIFFSetupFields(tif, infoarray);
1271 
1272 	tif->tif_diroff = 0;
1273 	tif->tif_nextdiroff = 0;
1274 	tif->tif_curoff = 0;
1275 	tif->tif_row = (uint32) -1;
1276 	tif->tif_curstrip = (uint32) -1;
1277 
1278 	return 0;
1279 }
1280 
1281 int
TIFFCreateEXIFDirectory(TIFF * tif)1282 TIFFCreateEXIFDirectory(TIFF* tif)
1283 {
1284 	const TIFFFieldArray* exifFieldArray;
1285 	exifFieldArray = _TIFFGetExifFields();
1286 	return TIFFCreateCustomDirectory(tif, exifFieldArray);
1287 }
1288 
1289 /*
1290  * Setup a default directory structure.
1291  */
1292 int
TIFFDefaultDirectory(TIFF * tif)1293 TIFFDefaultDirectory(TIFF* tif)
1294 {
1295 	register TIFFDirectory* td = &tif->tif_dir;
1296 	const TIFFFieldArray* tiffFieldArray;
1297 
1298 	tiffFieldArray = _TIFFGetFields();
1299 	_TIFFSetupFields(tif, tiffFieldArray);
1300 
1301 	_TIFFmemset(td, 0, sizeof (*td));
1302 	td->td_fillorder = FILLORDER_MSB2LSB;
1303 	td->td_bitspersample = 1;
1304 	td->td_threshholding = THRESHHOLD_BILEVEL;
1305 	td->td_orientation = ORIENTATION_TOPLEFT;
1306 	td->td_samplesperpixel = 1;
1307 	td->td_rowsperstrip = (uint32) -1;
1308 	td->td_tilewidth = 0;
1309 	td->td_tilelength = 0;
1310 	td->td_tiledepth = 1;
1311 	td->td_stripbytecountsorted = 1; /* Our own arrays always sorted. */
1312 	td->td_resolutionunit = RESUNIT_INCH;
1313 	td->td_sampleformat = SAMPLEFORMAT_UINT;
1314 	td->td_imagedepth = 1;
1315 	td->td_ycbcrsubsampling[0] = 2;
1316 	td->td_ycbcrsubsampling[1] = 2;
1317 	td->td_ycbcrpositioning = YCBCRPOSITION_CENTERED;
1318 	tif->tif_postdecode = _TIFFNoPostDecode;
1319 	tif->tif_foundfield = NULL;
1320 	tif->tif_tagmethods.vsetfield = _TIFFVSetField;
1321 	tif->tif_tagmethods.vgetfield = _TIFFVGetField;
1322 	tif->tif_tagmethods.printdir = NULL;
1323 	/*
1324 	 *  Give client code a chance to install their own
1325 	 *  tag extensions & methods, prior to compression overloads,
1326 	 *  but do some prior cleanup first. (http://trac.osgeo.org/gdal/ticket/5054)
1327 	 */
1328 	if (tif->tif_nfieldscompat > 0) {
1329 		uint32 i;
1330 
1331 		for (i = 0; i < tif->tif_nfieldscompat; i++) {
1332 				if (tif->tif_fieldscompat[i].allocated_size)
1333 						_TIFFfree(tif->tif_fieldscompat[i].fields);
1334 		}
1335 		_TIFFfree(tif->tif_fieldscompat);
1336 		tif->tif_nfieldscompat = 0;
1337 		tif->tif_fieldscompat = NULL;
1338 	}
1339 	if (_TIFFextender)
1340 		(*_TIFFextender)(tif);
1341 	(void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
1342 	/*
1343 	 * NB: The directory is marked dirty as a result of setting
1344 	 * up the default compression scheme.  However, this really
1345 	 * isn't correct -- we want TIFF_DIRTYDIRECT to be set only
1346 	 * if the user does something.  We could just do the setup
1347 	 * by hand, but it seems better to use the normal mechanism
1348 	 * (i.e. TIFFSetField).
1349 	 */
1350 	tif->tif_flags &= ~TIFF_DIRTYDIRECT;
1351 
1352 	/*
1353 	 * As per http://bugzilla.remotesensing.org/show_bug.cgi?id=19
1354 	 * we clear the ISTILED flag when setting up a new directory.
1355 	 * Should we also be clearing stuff like INSUBIFD?
1356 	 */
1357 	tif->tif_flags &= ~TIFF_ISTILED;
1358 
1359 	return (1);
1360 }
1361 
1362 static int
TIFFAdvanceDirectory(TIFF * tif,uint64 * nextdir,uint64 * off)1363 TIFFAdvanceDirectory(TIFF* tif, uint64* nextdir, uint64* off)
1364 {
1365 	static const char module[] = "TIFFAdvanceDirectory";
1366 	if (isMapped(tif))
1367 	{
1368 		uint64 poff=*nextdir;
1369 		if (!(tif->tif_flags&TIFF_BIGTIFF))
1370 		{
1371 			tmsize_t poffa,poffb,poffc,poffd;
1372 			uint16 dircount;
1373 			uint32 nextdir32;
1374 			poffa=(tmsize_t)poff;
1375 			poffb=poffa+sizeof(uint16);
1376 			if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint16))||(poffb>tif->tif_size))
1377 			{
1378 				TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
1379                                   *nextdir=0;
1380 				return(0);
1381 			}
1382 			_TIFFmemcpy(&dircount,tif->tif_base+poffa,sizeof(uint16));
1383 			if (tif->tif_flags&TIFF_SWAB)
1384 				TIFFSwabShort(&dircount);
1385 			poffc=poffb+dircount*12;
1386 			poffd=poffc+sizeof(uint32);
1387 			if ((poffc<poffb)||(poffc<dircount*12)||(poffd<poffc)||(poffd<(tmsize_t)sizeof(uint32))||(poffd>tif->tif_size))
1388 			{
1389 				TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory link");
1390 				return(0);
1391 			}
1392 			if (off!=NULL)
1393 				*off=(uint64)poffc;
1394 			_TIFFmemcpy(&nextdir32,tif->tif_base+poffc,sizeof(uint32));
1395 			if (tif->tif_flags&TIFF_SWAB)
1396 				TIFFSwabLong(&nextdir32);
1397 			*nextdir=nextdir32;
1398 		}
1399 		else
1400 		{
1401 			tmsize_t poffa,poffb,poffc,poffd;
1402 			uint64 dircount64;
1403 			uint16 dircount16;
1404 			poffa=(tmsize_t)poff;
1405 			poffb=poffa+sizeof(uint64);
1406 			if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint64))||(poffb>tif->tif_size))
1407 			{
1408 				TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
1409 				return(0);
1410 			}
1411 			_TIFFmemcpy(&dircount64,tif->tif_base+poffa,sizeof(uint64));
1412 			if (tif->tif_flags&TIFF_SWAB)
1413 				TIFFSwabLong8(&dircount64);
1414 			if (dircount64>0xFFFF)
1415 			{
1416 				TIFFErrorExt(tif->tif_clientdata,module,"Sanity check on directory count failed");
1417 				return(0);
1418 			}
1419 			dircount16=(uint16)dircount64;
1420 			poffc=poffb+dircount16*20;
1421 			poffd=poffc+sizeof(uint64);
1422 			if ((poffc<poffb)||(poffc<dircount16*20)||(poffd<poffc)||(poffd<(tmsize_t)sizeof(uint64))||(poffd>tif->tif_size))
1423 			{
1424 				TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory link");
1425 				return(0);
1426 			}
1427 			if (off!=NULL)
1428 				*off=(uint64)poffc;
1429 			_TIFFmemcpy(nextdir,tif->tif_base+poffc,sizeof(uint64));
1430 			if (tif->tif_flags&TIFF_SWAB)
1431 				TIFFSwabLong8(nextdir);
1432 		}
1433 		return(1);
1434 	}
1435 	else
1436 	{
1437 		if (!(tif->tif_flags&TIFF_BIGTIFF))
1438 		{
1439 			uint16 dircount;
1440 			uint32 nextdir32;
1441 			if (!SeekOK(tif, *nextdir) ||
1442 			    !ReadOK(tif, &dircount, sizeof (uint16))) {
1443 				TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory count",
1444 				    tif->tif_name);
1445 				return (0);
1446 			}
1447 			if (tif->tif_flags & TIFF_SWAB)
1448 				TIFFSwabShort(&dircount);
1449 			if (off != NULL)
1450 				*off = TIFFSeekFile(tif,
1451 				    dircount*12, SEEK_CUR);
1452 			else
1453 				(void) TIFFSeekFile(tif,
1454 				    dircount*12, SEEK_CUR);
1455 			if (!ReadOK(tif, &nextdir32, sizeof (uint32))) {
1456 				TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
1457 				    tif->tif_name);
1458 				return (0);
1459 			}
1460 			if (tif->tif_flags & TIFF_SWAB)
1461 				TIFFSwabLong(&nextdir32);
1462 			*nextdir=nextdir32;
1463 		}
1464 		else
1465 		{
1466 			uint64 dircount64;
1467 			uint16 dircount16;
1468 			if (!SeekOK(tif, *nextdir) ||
1469 			    !ReadOK(tif, &dircount64, sizeof (uint64))) {
1470 				TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory count",
1471 				    tif->tif_name);
1472 				return (0);
1473 			}
1474 			if (tif->tif_flags & TIFF_SWAB)
1475 				TIFFSwabLong8(&dircount64);
1476 			if (dircount64>0xFFFF)
1477 			{
1478 				TIFFErrorExt(tif->tif_clientdata, module, "Error fetching directory count");
1479 				return(0);
1480 			}
1481 			dircount16 = (uint16)dircount64;
1482 			if (off != NULL)
1483 				*off = TIFFSeekFile(tif,
1484 				    dircount16*20, SEEK_CUR);
1485 			else
1486 				(void) TIFFSeekFile(tif,
1487 				    dircount16*20, SEEK_CUR);
1488 			if (!ReadOK(tif, nextdir, sizeof (uint64))) {
1489 				TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
1490 				    tif->tif_name);
1491 				return (0);
1492 			}
1493 			if (tif->tif_flags & TIFF_SWAB)
1494 				TIFFSwabLong8(nextdir);
1495 		}
1496 		return (1);
1497 	}
1498 }
1499 
1500 /*
1501  * Count the number of directories in a file.
1502  */
1503 uint16
TIFFNumberOfDirectories(TIFF * tif)1504 TIFFNumberOfDirectories(TIFF* tif)
1505 {
1506 	static const char module[] = "TIFFNumberOfDirectories";
1507 	uint64 nextdir;
1508 	uint16 n;
1509 	if (!(tif->tif_flags&TIFF_BIGTIFF))
1510 		nextdir = tif->tif_header.classic.tiff_diroff;
1511 	else
1512 		nextdir = tif->tif_header.big.tiff_diroff;
1513 	n = 0;
1514 	while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL))
1515         {
1516 		if(++n == 0)
1517                 {
1518                         TIFFErrorExt(tif->tif_clientdata, module,
1519                                      "Directory count exceeded 65535 limit, giving up on counting.");
1520                         return (65535);
1521                 }
1522         }
1523 	return (n);
1524 }
1525 
1526 /*
1527  * Set the n-th directory as the current directory.
1528  * NB: Directories are numbered starting at 0.
1529  */
1530 int
TIFFSetDirectory(TIFF * tif,uint16 dirn)1531 TIFFSetDirectory(TIFF* tif, uint16 dirn)
1532 {
1533 	uint64 nextdir;
1534 	uint16 n;
1535 
1536 	if (!(tif->tif_flags&TIFF_BIGTIFF))
1537 		nextdir = tif->tif_header.classic.tiff_diroff;
1538 	else
1539 		nextdir = tif->tif_header.big.tiff_diroff;
1540 	for (n = dirn; n > 0 && nextdir != 0; n--)
1541 		if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1542 			return (0);
1543 	tif->tif_nextdiroff = nextdir;
1544 	/*
1545 	 * Set curdir to the actual directory index.  The
1546 	 * -1 is because TIFFReadDirectory will increment
1547 	 * tif_curdir after successfully reading the directory.
1548 	 */
1549 	tif->tif_curdir = (dirn - n) - 1;
1550 	/*
1551 	 * Reset tif_dirnumber counter and start new list of seen directories.
1552 	 * We need this to prevent IFD loops.
1553 	 */
1554 	tif->tif_dirnumber = 0;
1555 	return (TIFFReadDirectory(tif));
1556 }
1557 
1558 /*
1559  * Set the current directory to be the directory
1560  * located at the specified file offset.  This interface
1561  * is used mainly to access directories linked with
1562  * the SubIFD tag (e.g. thumbnail images).
1563  */
1564 int
TIFFSetSubDirectory(TIFF * tif,uint64 diroff)1565 TIFFSetSubDirectory(TIFF* tif, uint64 diroff)
1566 {
1567 	tif->tif_nextdiroff = diroff;
1568 	/*
1569 	 * Reset tif_dirnumber counter and start new list of seen directories.
1570 	 * We need this to prevent IFD loops.
1571 	 */
1572 	tif->tif_dirnumber = 0;
1573 	return (TIFFReadDirectory(tif));
1574 }
1575 
1576 /*
1577  * Return file offset of the current directory.
1578  */
1579 uint64
TIFFCurrentDirOffset(TIFF * tif)1580 TIFFCurrentDirOffset(TIFF* tif)
1581 {
1582 	return (tif->tif_diroff);
1583 }
1584 
1585 /*
1586  * Return an indication of whether or not we are
1587  * at the last directory in the file.
1588  */
1589 int
TIFFLastDirectory(TIFF * tif)1590 TIFFLastDirectory(TIFF* tif)
1591 {
1592 	return (tif->tif_nextdiroff == 0);
1593 }
1594 
1595 /*
1596  * Unlink the specified directory from the directory chain.
1597  */
1598 int
TIFFUnlinkDirectory(TIFF * tif,uint16 dirn)1599 TIFFUnlinkDirectory(TIFF* tif, uint16 dirn)
1600 {
1601 	static const char module[] = "TIFFUnlinkDirectory";
1602 	uint64 nextdir;
1603 	uint64 off;
1604 	uint16 n;
1605 
1606 	if (tif->tif_mode == O_RDONLY) {
1607 		TIFFErrorExt(tif->tif_clientdata, module,
1608                              "Can not unlink directory in read-only file");
1609 		return (0);
1610 	}
1611 	/*
1612 	 * Go to the directory before the one we want
1613 	 * to unlink and nab the offset of the link
1614 	 * field we'll need to patch.
1615 	 */
1616 	if (!(tif->tif_flags&TIFF_BIGTIFF))
1617 	{
1618 		nextdir = tif->tif_header.classic.tiff_diroff;
1619 		off = 4;
1620 	}
1621 	else
1622 	{
1623 		nextdir = tif->tif_header.big.tiff_diroff;
1624 		off = 8;
1625 	}
1626 	for (n = dirn-1; n > 0; n--) {
1627 		if (nextdir == 0) {
1628 			TIFFErrorExt(tif->tif_clientdata, module, "Directory %d does not exist", dirn);
1629 			return (0);
1630 		}
1631 		if (!TIFFAdvanceDirectory(tif, &nextdir, &off))
1632 			return (0);
1633 	}
1634 	/*
1635 	 * Advance to the directory to be unlinked and fetch
1636 	 * the offset of the directory that follows.
1637 	 */
1638 	if (!TIFFAdvanceDirectory(tif, &nextdir, NULL))
1639 		return (0);
1640 	/*
1641 	 * Go back and patch the link field of the preceding
1642 	 * directory to point to the offset of the directory
1643 	 * that follows.
1644 	 */
1645 	(void) TIFFSeekFile(tif, off, SEEK_SET);
1646 	if (!(tif->tif_flags&TIFF_BIGTIFF))
1647 	{
1648 		uint32 nextdir32;
1649 		nextdir32=(uint32)nextdir;
1650 		assert((uint64)nextdir32==nextdir);
1651 		if (tif->tif_flags & TIFF_SWAB)
1652 			TIFFSwabLong(&nextdir32);
1653 		if (!WriteOK(tif, &nextdir32, sizeof (uint32))) {
1654 			TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link");
1655 			return (0);
1656 		}
1657 	}
1658 	else
1659 	{
1660 		if (tif->tif_flags & TIFF_SWAB)
1661 			TIFFSwabLong8(&nextdir);
1662 		if (!WriteOK(tif, &nextdir, sizeof (uint64))) {
1663 			TIFFErrorExt(tif->tif_clientdata, module, "Error writing directory link");
1664 			return (0);
1665 		}
1666 	}
1667 	/*
1668 	 * Leave directory state setup safely.  We don't have
1669 	 * facilities for doing inserting and removing directories,
1670 	 * so it's safest to just invalidate everything.  This
1671 	 * means that the caller can only append to the directory
1672 	 * chain.
1673 	 */
1674 	(*tif->tif_cleanup)(tif);
1675 	if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) {
1676 		_TIFFfree(tif->tif_rawdata);
1677 		tif->tif_rawdata = NULL;
1678 		tif->tif_rawcc = 0;
1679                 tif->tif_rawdataoff = 0;
1680                 tif->tif_rawdataloaded = 0;
1681 	}
1682 	tif->tif_flags &= ~(TIFF_BEENWRITING|TIFF_BUFFERSETUP|TIFF_POSTENCODE|TIFF_BUF4WRITE);
1683 	TIFFFreeDirectory(tif);
1684 	TIFFDefaultDirectory(tif);
1685 	tif->tif_diroff = 0;			/* force link on next write */
1686 	tif->tif_nextdiroff = 0;		/* next write must be at end */
1687 	tif->tif_curoff = 0;
1688 	tif->tif_row = (uint32) -1;
1689 	tif->tif_curstrip = (uint32) -1;
1690 	return (1);
1691 }
1692 
1693 /* vim: set ts=8 sts=8 sw=8 noet: */
1694 /*
1695  * Local Variables:
1696  * mode: c
1697  * c-basic-offset: 8
1698  * fill-column: 78
1699  * End:
1700  */
1701