1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
14    |          Marcus Boerger <helly@php.net>                              |
15    +----------------------------------------------------------------------+
16  */
17 
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21 
22 #include "php.h"
23 #include "ext/standard/file.h"
24 
25 /* When EXIF_DEBUG is defined the module generates a lot of debug messages
26  * that help understanding what is going on. This can and should be used
27  * while extending the module as it shows if you are at the right position.
28  * You are always considered to have a copy of TIFF6.0 and EXIF2.10 standard.
29  */
30 #undef EXIF_DEBUG
31 
32 #ifdef EXIF_DEBUG
33 #define EXIFERR_DC , const char *_file, size_t _line
34 #define EXIFERR_CC , __FILE__, __LINE__
35 #else
36 #define EXIFERR_DC
37 #define EXIFERR_CC
38 #endif
39 
40 #include "php_exif.h"
41 #include "exif_arginfo.h"
42 #include <math.h>
43 #include "php_ini.h"
44 #include "ext/standard/php_string.h"
45 #include "ext/standard/php_image.h"
46 #include "ext/standard/info.h"
47 
48 /* needed for ssize_t definition */
49 #include <sys/types.h>
50 
51 #ifdef __SANITIZE_ADDRESS__
52 # include <sanitizer/asan_interface.h>
53 #endif
54 
55 typedef unsigned char uchar;
56 
57 #ifndef max
58 #	define max(a,b) ((a)>(b) ? (a) : (b))
59 #endif
60 
61 #define EFREE_IF(ptr)	if (ptr) efree(ptr)
62 
63 #define MAX_IFD_NESTING_LEVEL 10
64 #define MAX_IFD_TAGS 1000
65 
66 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(exif)67 PHP_MINFO_FUNCTION(exif)
68 {
69 	php_info_print_table_start();
70 	php_info_print_table_row(2, "EXIF Support", "enabled");
71 	php_info_print_table_row(2, "Supported EXIF Version", "0220");
72 	php_info_print_table_row(2, "Supported filetypes", "JPEG, TIFF");
73 
74 	if (zend_hash_str_exists(&module_registry, "mbstring", sizeof("mbstring")-1)) {
75 		php_info_print_table_row(2, "Multibyte decoding support using mbstring", "enabled");
76 	} else {
77 		php_info_print_table_row(2, "Multibyte decoding support using mbstring", "disabled");
78 	}
79 
80 	php_info_print_table_row(2, "Extended EXIF tag formats", "Canon, Casio, Fujifilm, Nikon, Olympus, Samsung, Panasonic, DJI, Sony, Pentax, Minolta, Sigma, Foveon, Kyocera, Ricoh, AGFA, Epson");
81 	php_info_print_table_end();
82 
83 	DISPLAY_INI_ENTRIES();
84 }
85 /* }}} */
86 
87 ZEND_BEGIN_MODULE_GLOBALS(exif)
88 	char * encode_unicode;
89 	char * decode_unicode_be;
90 	char * decode_unicode_le;
91 	char * encode_jis;
92 	char * decode_jis_be;
93 	char * decode_jis_le;
94 	HashTable *tag_table_cache;
95 ZEND_END_MODULE_GLOBALS(exif)
96 
ZEND_DECLARE_MODULE_GLOBALS(exif)97 ZEND_DECLARE_MODULE_GLOBALS(exif)
98 #define EXIF_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(exif, v)
99 
100 #if defined(ZTS) && defined(COMPILE_DL_EXIF)
101 ZEND_TSRMLS_CACHE_DEFINE()
102 #endif
103 
104 /* {{{ PHP_INI */
105 
106 ZEND_INI_MH(OnUpdateEncode)
107 {
108 	if (new_value && ZSTR_LEN(new_value)) {
109 		const zend_encoding **return_list;
110 		size_t return_size;
111 		if (FAILURE == zend_multibyte_parse_encoding_list(ZSTR_VAL(new_value), ZSTR_LEN(new_value),
112 	&return_list, &return_size, 0)) {
113 			php_error_docref(NULL, E_WARNING, "Illegal encoding ignored: '%s'", ZSTR_VAL(new_value));
114 			return FAILURE;
115 		}
116 		pefree((void *) return_list, 0);
117 	}
118 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
119 }
120 
ZEND_INI_MH(OnUpdateDecode)121 ZEND_INI_MH(OnUpdateDecode)
122 {
123 	if (new_value) {
124 		const zend_encoding **return_list;
125 		size_t return_size;
126 		if (FAILURE == zend_multibyte_parse_encoding_list(ZSTR_VAL(new_value), ZSTR_LEN(new_value),
127 	&return_list, &return_size, 0)) {
128 			php_error_docref(NULL, E_WARNING, "Illegal encoding ignored: '%s'", ZSTR_VAL(new_value));
129 			return FAILURE;
130 		}
131 		pefree((void *) return_list, 0);
132 	}
133 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
134 }
135 
136 PHP_INI_BEGIN()
137 	STD_PHP_INI_ENTRY("exif.encode_unicode",          "ISO-8859-15", PHP_INI_ALL, OnUpdateEncode, encode_unicode,    zend_exif_globals, exif_globals)
138 	STD_PHP_INI_ENTRY("exif.decode_unicode_motorola", "UCS-2BE",     PHP_INI_ALL, OnUpdateDecode, decode_unicode_be, zend_exif_globals, exif_globals)
139 	STD_PHP_INI_ENTRY("exif.decode_unicode_intel",    "UCS-2LE",     PHP_INI_ALL, OnUpdateDecode, decode_unicode_le, zend_exif_globals, exif_globals)
140 	STD_PHP_INI_ENTRY("exif.encode_jis",              "",            PHP_INI_ALL, OnUpdateEncode, encode_jis,        zend_exif_globals, exif_globals)
141 	STD_PHP_INI_ENTRY("exif.decode_jis_motorola",     "JIS",         PHP_INI_ALL, OnUpdateDecode, decode_jis_be,     zend_exif_globals, exif_globals)
142 	STD_PHP_INI_ENTRY("exif.decode_jis_intel",        "JIS",         PHP_INI_ALL, OnUpdateDecode, decode_jis_le,     zend_exif_globals, exif_globals)
PHP_INI_END()143 PHP_INI_END()
144 /* }}} */
145 
146 /* {{{ PHP_GINIT_FUNCTION */
147 static PHP_GINIT_FUNCTION(exif)
148 {
149 #if defined(COMPILE_DL_EXIF) && defined(ZTS)
150 	ZEND_TSRMLS_CACHE_UPDATE();
151 #endif
152 	exif_globals->encode_unicode    = NULL;
153 	exif_globals->decode_unicode_be = NULL;
154 	exif_globals->decode_unicode_le = NULL;
155 	exif_globals->encode_jis        = NULL;
156 	exif_globals->decode_jis_be     = NULL;
157 	exif_globals->decode_jis_le     = NULL;
158 	exif_globals->tag_table_cache   = NULL;
159 }
160 /* }}} */
161 
162 /* {{{ PHP_MINIT_FUNCTION(exif) */
PHP_MINIT_FUNCTION(exif)163 PHP_MINIT_FUNCTION(exif)
164 {
165 	REGISTER_INI_ENTRIES();
166 	if (zend_hash_str_exists(&module_registry, "mbstring", sizeof("mbstring")-1)) {
167 		REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 1, CONST_CS | CONST_PERSISTENT);
168 	} else {
169 		REGISTER_LONG_CONSTANT("EXIF_USE_MBSTRING", 0, CONST_CS | CONST_PERSISTENT);
170 	}
171 	return SUCCESS;
172 }
173 /* }}} */
174 
175 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(exif)176 PHP_MSHUTDOWN_FUNCTION(exif)
177 {
178 	UNREGISTER_INI_ENTRIES();
179 	if (EXIF_G(tag_table_cache)) {
180 		zend_hash_destroy(EXIF_G(tag_table_cache));
181 		free(EXIF_G(tag_table_cache));
182 	}
183 	return SUCCESS;
184 }
185 /* }}} */
186 
187 /* {{{ exif dependencies */
188 static const zend_module_dep exif_module_deps[] = {
189 	ZEND_MOD_REQUIRED("standard")
190 	ZEND_MOD_OPTIONAL("mbstring")
191 	ZEND_MOD_END
192 };
193 /* }}} */
194 
195 /* {{{ exif_module_entry */
196 zend_module_entry exif_module_entry = {
197 	STANDARD_MODULE_HEADER_EX, NULL,
198 	exif_module_deps,
199 	"exif",
200 	ext_functions,
201 	PHP_MINIT(exif),
202 	PHP_MSHUTDOWN(exif),
203 	NULL, NULL,
204 	PHP_MINFO(exif),
205 	PHP_EXIF_VERSION,
206 	PHP_MODULE_GLOBALS(exif),
207 	PHP_GINIT(exif),
208 	NULL,
209 	NULL,
210 	STANDARD_MODULE_PROPERTIES_EX
211 };
212 /* }}} */
213 
214 #ifdef COMPILE_DL_EXIF
ZEND_GET_MODULE(exif)215 ZEND_GET_MODULE(exif)
216 #endif
217 
218 /* {{{ php_strnlen
219  * get length of string if buffer if less than buffer size or buffer size */
220 static size_t php_strnlen(char* str, size_t maxlen) {
221 	size_t len = 0;
222 
223 	if (str && maxlen && *str) {
224 		do {
225 			len++;
226 		} while (--maxlen && *(++str));
227 	}
228 	return len;
229 }
230 /* }}} */
231 
232 /* {{{ error messages */
233 static const char * EXIF_ERROR_FILEEOF   = "Unexpected end of file reached";
234 static const char * EXIF_ERROR_CORRUPT   = "File structure corrupted";
235 static const char * EXIF_ERROR_THUMBEOF  = "Thumbnail goes IFD boundary or end of file reached";
236 static const char * EXIF_ERROR_FSREALLOC = "Illegal reallocating of undefined file section";
237 
238 #define EXIF_ERRLOG_FILEEOF(ImageInfo)    exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_FILEEOF);
239 #define EXIF_ERRLOG_CORRUPT(ImageInfo)    exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_CORRUPT);
240 #define EXIF_ERRLOG_THUMBEOF(ImageInfo)   exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_THUMBEOF);
241 #define EXIF_ERRLOG_FSREALLOC(ImageInfo)  exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s", EXIF_ERROR_FSREALLOC);
242 /* }}} */
243 
244 /* {{{ format description defines
245    Describes format descriptor
246 */
247 static int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1};
248 #define NUM_FORMATS 13
249 
250 #define TAG_FMT_BYTE       1
251 #define TAG_FMT_STRING     2
252 #define TAG_FMT_USHORT     3
253 #define TAG_FMT_ULONG      4
254 #define TAG_FMT_URATIONAL  5
255 #define TAG_FMT_SBYTE      6
256 #define TAG_FMT_UNDEFINED  7
257 #define TAG_FMT_SSHORT     8
258 #define TAG_FMT_SLONG      9
259 #define TAG_FMT_SRATIONAL 10
260 #define TAG_FMT_SINGLE    11
261 #define TAG_FMT_DOUBLE    12
262 #define TAG_FMT_IFD       13
263 
264 #ifdef EXIF_DEBUG
exif_get_tagformat(int format)265 static char *exif_get_tagformat(int format)
266 {
267 	switch(format) {
268 		case TAG_FMT_BYTE:      return "BYTE";
269 		case TAG_FMT_STRING:    return "STRING";
270 		case TAG_FMT_USHORT:    return "USHORT";
271 		case TAG_FMT_ULONG:     return "ULONG";
272 		case TAG_FMT_URATIONAL: return "URATIONAL";
273 		case TAG_FMT_SBYTE:     return "SBYTE";
274 		case TAG_FMT_UNDEFINED: return "UNDEFINED";
275 		case TAG_FMT_SSHORT:    return "SSHORT";
276 		case TAG_FMT_SLONG:     return "SLONG";
277 		case TAG_FMT_SRATIONAL: return "SRATIONAL";
278 		case TAG_FMT_SINGLE:    return "SINGLE";
279 		case TAG_FMT_DOUBLE:    return "DOUBLE";
280 		case TAG_FMT_IFD:       return "IFD";
281 	}
282 	return "*Illegal";
283 }
284 #endif
285 
286 /* Describes tag values */
287 #define TAG_GPS_VERSION_ID              0x0000
288 #define TAG_GPS_LATITUDE_REF            0x0001
289 #define TAG_GPS_LATITUDE                0x0002
290 #define TAG_GPS_LONGITUDE_REF           0x0003
291 #define TAG_GPS_LONGITUDE               0x0004
292 #define TAG_GPS_ALTITUDE_REF            0x0005
293 #define TAG_GPS_ALTITUDE                0x0006
294 #define TAG_GPS_TIME_STAMP              0x0007
295 #define TAG_GPS_SATELLITES              0x0008
296 #define TAG_GPS_STATUS                  0x0009
297 #define TAG_GPS_MEASURE_MODE            0x000A
298 #define TAG_GPS_DOP                     0x000B
299 #define TAG_GPS_SPEED_REF               0x000C
300 #define TAG_GPS_SPEED                   0x000D
301 #define TAG_GPS_TRACK_REF               0x000E
302 #define TAG_GPS_TRACK                   0x000F
303 #define TAG_GPS_IMG_DIRECTION_REF       0x0010
304 #define TAG_GPS_IMG_DIRECTION           0x0011
305 #define TAG_GPS_MAP_DATUM               0x0012
306 #define TAG_GPS_DEST_LATITUDE_REF       0x0013
307 #define TAG_GPS_DEST_LATITUDE           0x0014
308 #define TAG_GPS_DEST_LONGITUDE_REF      0x0015
309 #define TAG_GPS_DEST_LONGITUDE          0x0016
310 #define TAG_GPS_DEST_BEARING_REF        0x0017
311 #define TAG_GPS_DEST_BEARING            0x0018
312 #define TAG_GPS_DEST_DISTANCE_REF       0x0019
313 #define TAG_GPS_DEST_DISTANCE           0x001A
314 #define TAG_GPS_PROCESSING_METHOD       0x001B
315 #define TAG_GPS_AREA_INFORMATION        0x001C
316 #define TAG_GPS_DATE_STAMP              0x001D
317 #define TAG_GPS_DIFFERENTIAL            0x001E
318 #define TAG_TIFF_COMMENT                0x00FE /* SHOULDN'T HAPPEN */
319 #define TAG_NEW_SUBFILE                 0x00FE /* New version of subfile tag */
320 #define TAG_SUBFILE_TYPE                0x00FF /* Old version of subfile tag */
321 #define TAG_IMAGEWIDTH                  0x0100
322 #define TAG_IMAGEHEIGHT                 0x0101
323 #define TAG_BITS_PER_SAMPLE             0x0102
324 #define TAG_COMPRESSION                 0x0103
325 #define TAG_PHOTOMETRIC_INTERPRETATION  0x0106
326 #define TAG_TRESHHOLDING                0x0107
327 #define TAG_CELL_WIDTH                  0x0108
328 #define TAG_CELL_HEIGHT                 0x0109
329 #define TAG_FILL_ORDER                  0x010A
330 #define TAG_DOCUMENT_NAME               0x010D
331 #define TAG_IMAGE_DESCRIPTION           0x010E
332 #define TAG_MAKE                        0x010F
333 #define TAG_MODEL                       0x0110
334 #define TAG_STRIP_OFFSETS               0x0111
335 #define TAG_ORIENTATION                 0x0112
336 #define TAG_SAMPLES_PER_PIXEL           0x0115
337 #define TAG_ROWS_PER_STRIP              0x0116
338 #define TAG_STRIP_BYTE_COUNTS           0x0117
339 #define TAG_MIN_SAMPPLE_VALUE           0x0118
340 #define TAG_MAX_SAMPLE_VALUE            0x0119
341 #define TAG_X_RESOLUTION                0x011A
342 #define TAG_Y_RESOLUTION                0x011B
343 #define TAG_PLANAR_CONFIGURATION        0x011C
344 #define TAG_PAGE_NAME                   0x011D
345 #define TAG_X_POSITION                  0x011E
346 #define TAG_Y_POSITION                  0x011F
347 #define TAG_FREE_OFFSETS                0x0120
348 #define TAG_FREE_BYTE_COUNTS            0x0121
349 #define TAG_GRAY_RESPONSE_UNIT          0x0122
350 #define TAG_GRAY_RESPONSE_CURVE         0x0123
351 #define TAG_RESOLUTION_UNIT             0x0128
352 #define TAG_PAGE_NUMBER                 0x0129
353 #define TAG_TRANSFER_FUNCTION           0x012D
354 #define TAG_SOFTWARE                    0x0131
355 #define TAG_DATETIME                    0x0132
356 #define TAG_ARTIST                      0x013B
357 #define TAG_HOST_COMPUTER               0x013C
358 #define TAG_PREDICTOR                   0x013D
359 #define TAG_WHITE_POINT                 0x013E
360 #define TAG_PRIMARY_CHROMATICITIES      0x013F
361 #define TAG_COLOR_MAP                   0x0140
362 #define TAG_HALFTONE_HINTS              0x0141
363 #define TAG_TILE_WIDTH                  0x0142
364 #define TAG_TILE_LENGTH                 0x0143
365 #define TAG_TILE_OFFSETS                0x0144
366 #define TAG_TILE_BYTE_COUNTS            0x0145
367 #define TAG_SUB_IFD                     0x014A
368 #define TAG_INK_SETMPUTER               0x014C
369 #define TAG_INK_NAMES                   0x014D
370 #define TAG_NUMBER_OF_INKS              0x014E
371 #define TAG_DOT_RANGE                   0x0150
372 #define TAG_TARGET_PRINTER              0x0151
373 #define TAG_EXTRA_SAMPLE                0x0152
374 #define TAG_SAMPLE_FORMAT               0x0153
375 #define TAG_S_MIN_SAMPLE_VALUE          0x0154
376 #define TAG_S_MAX_SAMPLE_VALUE          0x0155
377 #define TAG_TRANSFER_RANGE              0x0156
378 #define TAG_JPEG_TABLES                 0x015B
379 #define TAG_JPEG_PROC                   0x0200
380 #define TAG_JPEG_INTERCHANGE_FORMAT     0x0201
381 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202
382 #define TAG_JPEG_RESTART_INTERVAL       0x0203
383 #define TAG_JPEG_LOSSLESS_PREDICTOR     0x0205
384 #define TAG_JPEG_POINT_TRANSFORMS       0x0206
385 #define TAG_JPEG_Q_TABLES               0x0207
386 #define TAG_JPEG_DC_TABLES              0x0208
387 #define TAG_JPEG_AC_TABLES              0x0209
388 #define TAG_YCC_COEFFICIENTS            0x0211
389 #define TAG_YCC_SUB_SAMPLING            0x0212
390 #define TAG_YCC_POSITIONING             0x0213
391 #define TAG_REFERENCE_BLACK_WHITE       0x0214
392 /* 0x0301 - 0x0302 */
393 /* 0x0320 */
394 /* 0x0343 */
395 /* 0x5001 - 0x501B */
396 /* 0x5021 - 0x503B */
397 /* 0x5090 - 0x5091 */
398 /* 0x5100 - 0x5101 */
399 /* 0x5110 - 0x5113 */
400 /* 0x80E3 - 0x80E6 */
401 /* 0x828d - 0x828F */
402 #define TAG_COPYRIGHT                   0x8298
403 #define TAG_EXPOSURETIME                0x829A
404 #define TAG_FNUMBER                     0x829D
405 #define TAG_EXIF_IFD_POINTER            0x8769
406 #define TAG_ICC_PROFILE                 0x8773
407 #define TAG_EXPOSURE_PROGRAM            0x8822
408 #define TAG_SPECTRAL_SENSITY            0x8824
409 #define TAG_GPS_IFD_POINTER             0x8825
410 #define TAG_ISOSPEED                    0x8827
411 #define TAG_OPTOELECTRIC_CONVERSION_F   0x8828
412 /* 0x8829 - 0x882b */
413 #define TAG_EXIFVERSION                 0x9000
414 #define TAG_DATE_TIME_ORIGINAL          0x9003
415 #define TAG_DATE_TIME_DIGITIZED         0x9004
416 #define TAG_COMPONENT_CONFIG            0x9101
417 #define TAG_COMPRESSED_BITS_PER_PIXEL   0x9102
418 #define TAG_SHUTTERSPEED                0x9201
419 #define TAG_APERTURE                    0x9202
420 #define TAG_BRIGHTNESS_VALUE            0x9203
421 #define TAG_EXPOSURE_BIAS_VALUE         0x9204
422 #define TAG_MAX_APERTURE                0x9205
423 #define TAG_SUBJECT_DISTANCE            0x9206
424 #define TAG_METRIC_MODULE               0x9207
425 #define TAG_LIGHT_SOURCE                0x9208
426 #define TAG_FLASH                       0x9209
427 #define TAG_FOCAL_LENGTH                0x920A
428 /* 0x920B - 0x920D */
429 /* 0x9211 - 0x9216 */
430 #define TAG_SUBJECT_AREA                0x9214
431 #define TAG_MAKER_NOTE                  0x927C
432 #define TAG_USERCOMMENT                 0x9286
433 #define TAG_SUB_SEC_TIME                0x9290
434 #define TAG_SUB_SEC_TIME_ORIGINAL       0x9291
435 #define TAG_SUB_SEC_TIME_DIGITIZED      0x9292
436 /* 0x923F */
437 /* 0x935C */
438 #define TAG_XP_TITLE                    0x9C9B
439 #define TAG_XP_COMMENTS                 0x9C9C
440 #define TAG_XP_AUTHOR                   0x9C9D
441 #define TAG_XP_KEYWORDS                 0x9C9E
442 #define TAG_XP_SUBJECT                  0x9C9F
443 #define TAG_FLASH_PIX_VERSION           0xA000
444 #define TAG_COLOR_SPACE                 0xA001
445 #define TAG_COMP_IMAGE_WIDTH            0xA002 /* compressed images only */
446 #define TAG_COMP_IMAGE_HEIGHT           0xA003
447 #define TAG_RELATED_SOUND_FILE          0xA004
448 #define TAG_INTEROP_IFD_POINTER         0xA005 /* IFD pointer */
449 #define TAG_FLASH_ENERGY                0xA20B
450 #define TAG_SPATIAL_FREQUENCY_RESPONSE  0xA20C
451 #define TAG_FOCALPLANE_X_RES            0xA20E
452 #define TAG_FOCALPLANE_Y_RES            0xA20F
453 #define TAG_FOCALPLANE_RESOLUTION_UNIT  0xA210
454 #define TAG_SUBJECT_LOCATION            0xA214
455 #define TAG_EXPOSURE_INDEX              0xA215
456 #define TAG_SENSING_METHOD              0xA217
457 #define TAG_FILE_SOURCE                 0xA300
458 #define TAG_SCENE_TYPE                  0xA301
459 #define TAG_CFA_PATTERN                 0xA302
460 #define TAG_CUSTOM_RENDERED             0xA401
461 #define TAG_EXPOSURE_MODE               0xA402
462 #define TAG_WHITE_BALANCE               0xA403
463 #define TAG_DIGITAL_ZOOM_RATIO          0xA404
464 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM  0xA405
465 #define TAG_SCENE_CAPTURE_TYPE          0xA406
466 #define TAG_GAIN_CONTROL                0xA407
467 #define TAG_CONTRAST                    0xA408
468 #define TAG_SATURATION                  0xA409
469 #define TAG_SHARPNESS                   0xA40A
470 #define TAG_DEVICE_SETTING_DESCRIPTION  0xA40B
471 #define TAG_SUBJECT_DISTANCE_RANGE      0xA40C
472 #define TAG_IMAGE_UNIQUE_ID             0xA420
473 
474 /* Olympus specific tags */
475 #define TAG_OLYMPUS_SPECIALMODE         0x0200
476 #define TAG_OLYMPUS_JPEGQUAL            0x0201
477 #define TAG_OLYMPUS_MACRO               0x0202
478 #define TAG_OLYMPUS_DIGIZOOM            0x0204
479 #define TAG_OLYMPUS_SOFTWARERELEASE     0x0207
480 #define TAG_OLYMPUS_PICTINFO            0x0208
481 #define TAG_OLYMPUS_CAMERAID            0x0209
482 /* end Olympus specific tags */
483 
484 /* Internal */
485 #define TAG_NONE               			-1 /* note that -1 <> 0xFFFF */
486 #define TAG_COMPUTED_VALUE     			-2
487 #define TAG_END_OF_LIST                 0xFFFD
488 
489 /* Values for TAG_PHOTOMETRIC_INTERPRETATION */
490 #define PMI_BLACK_IS_ZERO       0
491 #define PMI_WHITE_IS_ZERO       1
492 #define PMI_RGB          	    2
493 #define PMI_PALETTE_COLOR       3
494 #define PMI_TRANSPARENCY_MASK   4
495 #define PMI_SEPARATED           5
496 #define PMI_YCBCR               6
497 #define PMI_CIELAB              8
498 
499 /* }}} */
500 
501 /* {{{ TabTable[] */
502 typedef const struct {
503 	unsigned short Tag;
504 	char *Desc;
505 } tag_info_type;
506 
507 typedef tag_info_type  tag_info_array[];
508 typedef tag_info_type  *tag_table_type;
509 
510 #define TAG_TABLE_END \
511   {TAG_NONE,           "No tag value"},\
512   {TAG_COMPUTED_VALUE, "Computed value"},\
513   {TAG_END_OF_LIST,    ""}  /* Important for exif_get_tagname() IF value != "" function result is != false */
514 
515 static tag_info_array tag_table_IFD = {
516   { 0x000B, "ACDComment"},
517   { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */
518   { 0x00FF, "SubFile"},
519   { 0x0100, "ImageWidth"},
520   { 0x0101, "ImageLength"},
521   { 0x0102, "BitsPerSample"},
522   { 0x0103, "Compression"},
523   { 0x0106, "PhotometricInterpretation"},
524   { 0x010A, "FillOrder"},
525   { 0x010D, "DocumentName"},
526   { 0x010E, "ImageDescription"},
527   { 0x010F, "Make"},
528   { 0x0110, "Model"},
529   { 0x0111, "StripOffsets"},
530   { 0x0112, "Orientation"},
531   { 0x0115, "SamplesPerPixel"},
532   { 0x0116, "RowsPerStrip"},
533   { 0x0117, "StripByteCounts"},
534   { 0x0118, "MinSampleValue"},
535   { 0x0119, "MaxSampleValue"},
536   { 0x011A, "XResolution"},
537   { 0x011B, "YResolution"},
538   { 0x011C, "PlanarConfiguration"},
539   { 0x011D, "PageName"},
540   { 0x011E, "XPosition"},
541   { 0x011F, "YPosition"},
542   { 0x0120, "FreeOffsets"},
543   { 0x0121, "FreeByteCounts"},
544   { 0x0122, "GrayResponseUnit"},
545   { 0x0123, "GrayResponseCurve"},
546   { 0x0124, "T4Options"},
547   { 0x0125, "T6Options"},
548   { 0x0128, "ResolutionUnit"},
549   { 0x0129, "PageNumber"},
550   { 0x012D, "TransferFunction"},
551   { 0x0131, "Software"},
552   { 0x0132, "DateTime"},
553   { 0x013B, "Artist"},
554   { 0x013C, "HostComputer"},
555   { 0x013D, "Predictor"},
556   { 0x013E, "WhitePoint"},
557   { 0x013F, "PrimaryChromaticities"},
558   { 0x0140, "ColorMap"},
559   { 0x0141, "HalfToneHints"},
560   { 0x0142, "TileWidth"},
561   { 0x0143, "TileLength"},
562   { 0x0144, "TileOffsets"},
563   { 0x0145, "TileByteCounts"},
564   { 0x014A, "SubIFD"},
565   { 0x014C, "InkSet"},
566   { 0x014D, "InkNames"},
567   { 0x014E, "NumberOfInks"},
568   { 0x0150, "DotRange"},
569   { 0x0151, "TargetPrinter"},
570   { 0x0152, "ExtraSample"},
571   { 0x0153, "SampleFormat"},
572   { 0x0154, "SMinSampleValue"},
573   { 0x0155, "SMaxSampleValue"},
574   { 0x0156, "TransferRange"},
575   { 0x0157, "ClipPath"},
576   { 0x0158, "XClipPathUnits"},
577   { 0x0159, "YClipPathUnits"},
578   { 0x015A, "Indexed"},
579   { 0x015B, "JPEGTables"},
580   { 0x015F, "OPIProxy"},
581   { 0x0200, "JPEGProc"},
582   { 0x0201, "JPEGInterchangeFormat"},
583   { 0x0202, "JPEGInterchangeFormatLength"},
584   { 0x0203, "JPEGRestartInterval"},
585   { 0x0205, "JPEGLosslessPredictors"},
586   { 0x0206, "JPEGPointTransforms"},
587   { 0x0207, "JPEGQTables"},
588   { 0x0208, "JPEGDCTables"},
589   { 0x0209, "JPEGACTables"},
590   { 0x0211, "YCbCrCoefficients"},
591   { 0x0212, "YCbCrSubSampling"},
592   { 0x0213, "YCbCrPositioning"},
593   { 0x0214, "ReferenceBlackWhite"},
594   { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */
595   { 0x0301, "Gamma"},
596   { 0x0302, "ICCProfileDescriptor"},
597   { 0x0303, "SRGBRenderingIntent"},
598   { 0x0320, "ImageTitle"},
599   { 0x5001, "ResolutionXUnit"},
600   { 0x5002, "ResolutionYUnit"},
601   { 0x5003, "ResolutionXLengthUnit"},
602   { 0x5004, "ResolutionYLengthUnit"},
603   { 0x5005, "PrintFlags"},
604   { 0x5006, "PrintFlagsVersion"},
605   { 0x5007, "PrintFlagsCrop"},
606   { 0x5008, "PrintFlagsBleedWidth"},
607   { 0x5009, "PrintFlagsBleedWidthScale"},
608   { 0x500A, "HalftoneLPI"},
609   { 0x500B, "HalftoneLPIUnit"},
610   { 0x500C, "HalftoneDegree"},
611   { 0x500D, "HalftoneShape"},
612   { 0x500E, "HalftoneMisc"},
613   { 0x500F, "HalftoneScreen"},
614   { 0x5010, "JPEGQuality"},
615   { 0x5011, "GridSize"},
616   { 0x5012, "ThumbnailFormat"},
617   { 0x5013, "ThumbnailWidth"},
618   { 0x5014, "ThumbnailHeight"},
619   { 0x5015, "ThumbnailColorDepth"},
620   { 0x5016, "ThumbnailPlanes"},
621   { 0x5017, "ThumbnailRawBytes"},
622   { 0x5018, "ThumbnailSize"},
623   { 0x5019, "ThumbnailCompressedSize"},
624   { 0x501A, "ColorTransferFunction"},
625   { 0x501B, "ThumbnailData"},
626   { 0x5020, "ThumbnailImageWidth"},
627   { 0x5021, "ThumbnailImageHeight"},
628   { 0x5022, "ThumbnailBitsPerSample"},
629   { 0x5023, "ThumbnailCompression"},
630   { 0x5024, "ThumbnailPhotometricInterp"},
631   { 0x5025, "ThumbnailImageDescription"},
632   { 0x5026, "ThumbnailEquipMake"},
633   { 0x5027, "ThumbnailEquipModel"},
634   { 0x5028, "ThumbnailStripOffsets"},
635   { 0x5029, "ThumbnailOrientation"},
636   { 0x502A, "ThumbnailSamplesPerPixel"},
637   { 0x502B, "ThumbnailRowsPerStrip"},
638   { 0x502C, "ThumbnailStripBytesCount"},
639   { 0x502D, "ThumbnailResolutionX"},
640   { 0x502E, "ThumbnailResolutionY"},
641   { 0x502F, "ThumbnailPlanarConfig"},
642   { 0x5030, "ThumbnailResolutionUnit"},
643   { 0x5031, "ThumbnailTransferFunction"},
644   { 0x5032, "ThumbnailSoftwareUsed"},
645   { 0x5033, "ThumbnailDateTime"},
646   { 0x5034, "ThumbnailArtist"},
647   { 0x5035, "ThumbnailWhitePoint"},
648   { 0x5036, "ThumbnailPrimaryChromaticities"},
649   { 0x5037, "ThumbnailYCbCrCoefficients"},
650   { 0x5038, "ThumbnailYCbCrSubsampling"},
651   { 0x5039, "ThumbnailYCbCrPositioning"},
652   { 0x503A, "ThumbnailRefBlackWhite"},
653   { 0x503B, "ThumbnailCopyRight"},
654   { 0x5090, "LuminanceTable"},
655   { 0x5091, "ChrominanceTable"},
656   { 0x5100, "FrameDelay"},
657   { 0x5101, "LoopCount"},
658   { 0x5110, "PixelUnit"},
659   { 0x5111, "PixelPerUnitX"},
660   { 0x5112, "PixelPerUnitY"},
661   { 0x5113, "PaletteHistogram"},
662   { 0x1000, "RelatedImageFileFormat"},
663   { 0x800D, "ImageID"},
664   { 0x80E3, "Matteing"},   /* obsoleted by ExtraSamples */
665   { 0x80E4, "DataType"},   /* obsoleted by SampleFormat */
666   { 0x80E5, "ImageDepth"},
667   { 0x80E6, "TileDepth"},
668   { 0x828D, "CFARepeatPatternDim"},
669   { 0x828E, "CFAPattern"},
670   { 0x828F, "BatteryLevel"},
671   { 0x8298, "Copyright"},
672   { 0x829A, "ExposureTime"},
673   { 0x829D, "FNumber"},
674   { 0x83BB, "IPTC/NAA"},
675   { 0x84E3, "IT8RasterPadding"},
676   { 0x84E5, "IT8ColorTable"},
677   { 0x8649, "ImageResourceInformation"}, /* PhotoShop */
678   { 0x8769, "Exif_IFD_Pointer"},
679   { 0x8773, "ICC_Profile"},
680   { 0x8822, "ExposureProgram"},
681   { 0x8824, "SpectralSensity"},
682   { 0x8825, "GPS_IFD_Pointer"},
683   { 0x8827, "ISOSpeedRatings"},
684   { 0x8828, "OECF"},
685   { 0x9000, "ExifVersion"},
686   { 0x9003, "DateTimeOriginal"},
687   { 0x9004, "DateTimeDigitized"},
688   { 0x9101, "ComponentsConfiguration"},
689   { 0x9102, "CompressedBitsPerPixel"},
690   { 0x9201, "ShutterSpeedValue"},
691   { 0x9202, "ApertureValue"},
692   { 0x9203, "BrightnessValue"},
693   { 0x9204, "ExposureBiasValue"},
694   { 0x9205, "MaxApertureValue"},
695   { 0x9206, "SubjectDistance"},
696   { 0x9207, "MeteringMode"},
697   { 0x9208, "LightSource"},
698   { 0x9209, "Flash"},
699   { 0x920A, "FocalLength"},
700   { 0x920B, "FlashEnergy"},                 /* 0xA20B  in JPEG   */
701   { 0x920C, "SpatialFrequencyResponse"},    /* 0xA20C    -  -    */
702   { 0x920D, "Noise"},
703   { 0x920E, "FocalPlaneXResolution"},       /* 0xA20E    -  -    */
704   { 0x920F, "FocalPlaneYResolution"},       /* 0xA20F    -  -    */
705   { 0x9210, "FocalPlaneResolutionUnit"},    /* 0xA210    -  -    */
706   { 0x9211, "ImageNumber"},
707   { 0x9212, "SecurityClassification"},
708   { 0x9213, "ImageHistory"},
709   { 0x9214, "SubjectLocation"},             /* 0xA214    -  -    */
710   { 0x9215, "ExposureIndex"},               /* 0xA215    -  -    */
711   { 0x9216, "TIFF/EPStandardID"},
712   { 0x9217, "SensingMethod"},               /* 0xA217    -  -    */
713   { 0x923F, "StoNits"},
714   { 0x927C, "MakerNote"},
715   { 0x9286, "UserComment"},
716   { 0x9290, "SubSecTime"},
717   { 0x9291, "SubSecTimeOriginal"},
718   { 0x9292, "SubSecTimeDigitized"},
719   { 0x935C, "ImageSourceData"},             /* "Adobe Photoshop Document Data Block": 8BIM... */
720   { 0x9c9b, "Title" },                      /* Win XP specific, Unicode  */
721   { 0x9c9c, "Comments" },                   /* Win XP specific, Unicode  */
722   { 0x9c9d, "Author" },                     /* Win XP specific, Unicode  */
723   { 0x9c9e, "Keywords" },                   /* Win XP specific, Unicode  */
724   { 0x9c9f, "Subject" },                    /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */
725   { 0xA000, "FlashPixVersion"},
726   { 0xA001, "ColorSpace"},
727   { 0xA002, "ExifImageWidth"},
728   { 0xA003, "ExifImageLength"},
729   { 0xA004, "RelatedSoundFile"},
730   { 0xA005, "InteroperabilityOffset"},
731   { 0xA20B, "FlashEnergy"},                 /* 0x920B in TIFF/EP */
732   { 0xA20C, "SpatialFrequencyResponse"},    /* 0x920C    -  -    */
733   { 0xA20D, "Noise"},
734   { 0xA20E, "FocalPlaneXResolution"},    	/* 0x920E    -  -    */
735   { 0xA20F, "FocalPlaneYResolution"},       /* 0x920F    -  -    */
736   { 0xA210, "FocalPlaneResolutionUnit"},    /* 0x9210    -  -    */
737   { 0xA211, "ImageNumber"},
738   { 0xA212, "SecurityClassification"},
739   { 0xA213, "ImageHistory"},
740   { 0xA214, "SubjectLocation"},             /* 0x9214    -  -    */
741   { 0xA215, "ExposureIndex"},               /* 0x9215    -  -    */
742   { 0xA216, "TIFF/EPStandardID"},
743   { 0xA217, "SensingMethod"},               /* 0x9217    -  -    */
744   { 0xA300, "FileSource"},
745   { 0xA301, "SceneType"},
746   { 0xA302, "CFAPattern"},
747   { 0xA401, "CustomRendered"},
748   { 0xA402, "ExposureMode"},
749   { 0xA403, "WhiteBalance"},
750   { 0xA404, "DigitalZoomRatio"},
751   { 0xA405, "FocalLengthIn35mmFilm"},
752   { 0xA406, "SceneCaptureType"},
753   { 0xA407, "GainControl"},
754   { 0xA408, "Contrast"},
755   { 0xA409, "Saturation"},
756   { 0xA40A, "Sharpness"},
757   { 0xA40B, "DeviceSettingDescription"},
758   { 0xA40C, "SubjectDistanceRange"},
759   { 0xA420, "ImageUniqueID"},
760   TAG_TABLE_END
761 } ;
762 
763 static tag_info_array tag_table_GPS = {
764   { 0x0000, "GPSVersion"},
765   { 0x0001, "GPSLatitudeRef"},
766   { 0x0002, "GPSLatitude"},
767   { 0x0003, "GPSLongitudeRef"},
768   { 0x0004, "GPSLongitude"},
769   { 0x0005, "GPSAltitudeRef"},
770   { 0x0006, "GPSAltitude"},
771   { 0x0007, "GPSTimeStamp"},
772   { 0x0008, "GPSSatellites"},
773   { 0x0009, "GPSStatus"},
774   { 0x000A, "GPSMeasureMode"},
775   { 0x000B, "GPSDOP"},
776   { 0x000C, "GPSSpeedRef"},
777   { 0x000D, "GPSSpeed"},
778   { 0x000E, "GPSTrackRef"},
779   { 0x000F, "GPSTrack"},
780   { 0x0010, "GPSImgDirectionRef"},
781   { 0x0011, "GPSImgDirection"},
782   { 0x0012, "GPSMapDatum"},
783   { 0x0013, "GPSDestLatitudeRef"},
784   { 0x0014, "GPSDestLatitude"},
785   { 0x0015, "GPSDestLongitudeRef"},
786   { 0x0016, "GPSDestLongitude"},
787   { 0x0017, "GPSDestBearingRef"},
788   { 0x0018, "GPSDestBearing"},
789   { 0x0019, "GPSDestDistanceRef"},
790   { 0x001A, "GPSDestDistance"},
791   { 0x001B, "GPSProcessingMode"},
792   { 0x001C, "GPSAreaInformation"},
793   { 0x001D, "GPSDateStamp"},
794   { 0x001E, "GPSDifferential"},
795   TAG_TABLE_END
796 };
797 
798 static tag_info_array tag_table_IOP = {
799   { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */
800   { 0x0002, "InterOperabilityVersion"},
801   { 0x1000, "RelatedFileFormat"},
802   { 0x1001, "RelatedImageWidth"},
803   { 0x1002, "RelatedImageHeight"},
804   TAG_TABLE_END
805 };
806 
807 static tag_info_array tag_table_VND_CANON = {
808   { 0x0001, "ModeArray"}, /* guess */
809   { 0x0004, "ImageInfo"}, /* guess */
810   { 0x0006, "ImageType"},
811   { 0x0007, "FirmwareVersion"},
812   { 0x0008, "ImageNumber"},
813   { 0x0009, "OwnerName"},
814   { 0x000C, "Camera"},
815   { 0x000F, "CustomFunctions"},
816   TAG_TABLE_END
817 };
818 
819 static tag_info_array tag_table_VND_CASIO = {
820   { 0x0001, "RecordingMode"},
821   { 0x0002, "Quality"},
822   { 0x0003, "FocusingMode"},
823   { 0x0004, "FlashMode"},
824   { 0x0005, "FlashIntensity"},
825   { 0x0006, "ObjectDistance"},
826   { 0x0007, "WhiteBalance"},
827   { 0x000A, "DigitalZoom"},
828   { 0x000B, "Sharpness"},
829   { 0x000C, "Contrast"},
830   { 0x000D, "Saturation"},
831   { 0x0014, "CCDSensitivity"},
832   TAG_TABLE_END
833 };
834 
835 static tag_info_array tag_table_VND_FUJI = {
836   { 0x0000, "Version"},
837   { 0x1000, "Quality"},
838   { 0x1001, "Sharpness"},
839   { 0x1002, "WhiteBalance"},
840   { 0x1003, "Color"},
841   { 0x1004, "Tone"},
842   { 0x1010, "FlashMode"},
843   { 0x1011, "FlashStrength"},
844   { 0x1020, "Macro"},
845   { 0x1021, "FocusMode"},
846   { 0x1030, "SlowSync"},
847   { 0x1031, "PictureMode"},
848   { 0x1100, "ContTake"},
849   { 0x1300, "BlurWarning"},
850   { 0x1301, "FocusWarning"},
851   { 0x1302, "AEWarning "},
852   TAG_TABLE_END
853 };
854 
855 static tag_info_array tag_table_VND_NIKON = {
856   { 0x0003, "Quality"},
857   { 0x0004, "ColorMode"},
858   { 0x0005, "ImageAdjustment"},
859   { 0x0006, "CCDSensitivity"},
860   { 0x0007, "WhiteBalance"},
861   { 0x0008, "Focus"},
862   { 0x000a, "DigitalZoom"},
863   { 0x000b, "Converter"},
864   TAG_TABLE_END
865 };
866 
867 static tag_info_array tag_table_VND_NIKON_990 = {
868   { 0x0001, "Version"},
869   { 0x0002, "ISOSetting"},
870   { 0x0003, "ColorMode"},
871   { 0x0004, "Quality"},
872   { 0x0005, "WhiteBalance"},
873   { 0x0006, "ImageSharpening"},
874   { 0x0007, "FocusMode"},
875   { 0x0008, "FlashSetting"},
876   { 0x000F, "ISOSelection"},
877   { 0x0080, "ImageAdjustment"},
878   { 0x0082, "AuxiliaryLens"},
879   { 0x0085, "ManualFocusDistance"},
880   { 0x0086, "DigitalZoom"},
881   { 0x0088, "AFFocusPosition"},
882   { 0x0010, "DataDump"},
883   TAG_TABLE_END
884 };
885 
886 static tag_info_array tag_table_VND_OLYMPUS = {
887   { 0x0200, "SpecialMode"},
888   { 0x0201, "JPEGQuality"},
889   { 0x0202, "Macro"},
890   { 0x0204, "DigitalZoom"},
891   { 0x0207, "SoftwareRelease"},
892   { 0x0208, "PictureInfo"},
893   { 0x0209, "CameraId"},
894   { 0x0F00, "DataDump"},
895   TAG_TABLE_END
896 };
897 
898 static tag_info_array tag_table_VND_SAMSUNG = {
899   { 0x0001, "Version"},
900   { 0x0021, "PictureWizard"},
901   { 0x0030, "LocalLocationName"},
902   { 0x0031, "LocationName"},
903   { 0x0035, "Preview"},
904   { 0x0043, "CameraTemperature"},
905   { 0xa001, "FirmwareName"},
906   { 0xa003, "LensType"},
907   { 0xa004, "LensFirmware"},
908   { 0xa010, "SensorAreas"},
909   { 0xa011, "ColorSpace"},
910   { 0xa012, "SmartRange"},
911   { 0xa013, "ExposureBiasValue"},
912   { 0xa014, "ISO"},
913   { 0xa018, "ExposureTime"},
914   { 0xa019, "FNumber"},
915   { 0xa01a, "FocalLengthIn35mmFormat"},
916   { 0xa020, "EncryptionKey"},
917   { 0xa021, "WB_RGGBLevelsUncorrected"},
918   { 0xa022, "WB_RGGBLevelsAuto"},
919   { 0xa023, "WB_RGGBLevelsIlluminator1"},
920   { 0xa024, "WB_RGGBLevelsIlluminator2"},
921   { 0xa028, "WB_RGGBLevelsBlack"},
922   { 0xa030, "ColorMatrix"},
923   { 0xa031, "ColorMatrixSRGB"},
924   { 0xa032, "ColorMatrixAdobeRGB"},
925   { 0xa040, "ToneCurve1"},
926   { 0xa041, "ToneCurve2"},
927   { 0xa042, "ToneCurve3"},
928   { 0xa043, "ToneCurve4"},
929   TAG_TABLE_END
930 };
931 
932 static tag_info_array tag_table_VND_PANASONIC = {
933   { 0x0001, "Quality"},
934   { 0x0002, "FirmwareVersion"},
935   { 0x0003, "WhiteBalance"},
936   { 0x0007, "FocusMode"},
937   { 0x000f, "AFMode"},
938   { 0x001a, "ImageStabilization"},
939   { 0x001c, "Macro"},
940   { 0x001f, "ShootingMode"},
941   { 0x0020, "Audio"},
942   { 0x0021, "DataDump"},
943   { 0x0023, "WhiteBalanceBias"},
944   { 0x0024, "FlashBias"},
945   { 0x0025, "InternalSerialNumber"},
946   { 0x0026, "ExifVersion"},
947   { 0x0028, "ColorEffect"},
948   { 0x0029, "TimeSincePowerOn"},
949   { 0x002a, "BurstMode"},
950   { 0x002b, "SequenceNumber"},
951   { 0x002c, "Contrast"},
952   { 0x002d, "NoiseReduction"},
953   { 0x002e, "SelfTimer"},
954   { 0x0030, "Rotation"},
955   { 0x0031, "AFAssistLamp"},
956   { 0x0032, "ColorMode"},
957   { 0x0033, "BabyAge1"},
958   { 0x0034, "OpticalZoomMode"},
959   { 0x0035, "ConversionLens"},
960   { 0x0036, "TravelDay"},
961   { 0x0039, "Contrast"},
962   { 0x003a, "WorldTimeLocation"},
963   { 0x003b, "TextStamp1"},
964   { 0x003c, "ProgramISO"},
965   { 0x003d, "AdvancedSceneType"},
966   { 0x003e, "TextStamp2"},
967   { 0x003f, "FacesDetected"},
968   { 0x0040, "Saturation"},
969   { 0x0041, "Sharpness"},
970   { 0x0042, "FilmMode"},
971   { 0x0044, "ColorTempKelvin"},
972   { 0x0045, "BracketSettings"},
973   { 0x0046, "WBAdjustAB"},
974   { 0x0047, "WBAdjustGM"},
975   { 0x0048, "FlashCurtain"},
976   { 0x0049, "LongShutterNoiseReduction"},
977   { 0x004b, "ImageWidth"},
978   { 0x004c, "ImageHeight"},
979   { 0x004d, "AFPointPosition"},
980   { 0x004e, "FaceDetInfo"},
981   { 0x0051, "LensType"},
982   { 0x0052, "LensSerialNumber"},
983   { 0x0053, "AccessoryType"},
984   { 0x0054, "AccessorySerialNumber"},
985   { 0x0059, "Transform1"},
986   { 0x005d, "IntelligentExposure"},
987   { 0x0060, "LensFirmwareVersion"},
988   { 0x0061, "FaceRecInfo"},
989   { 0x0062, "FlashWarning"},
990   { 0x0065, "Title"},
991   { 0x0066, "BabyName"},
992   { 0x0067, "Location"},
993   { 0x0069, "Country"},
994   { 0x006b, "State"},
995   { 0x006d, "City"},
996   { 0x006f, "Landmark"},
997   { 0x0070, "IntelligentResolution"},
998   { 0x0077, "BurstSheed"},
999   { 0x0079, "IntelligentDRange"},
1000   { 0x007c, "ClearRetouch"},
1001   { 0x0080, "City2"},
1002   { 0x0086, "ManometerPressure"},
1003   { 0x0089, "PhotoStyle"},
1004   { 0x008a, "ShadingCompensation"},
1005   { 0x008c, "AccelerometerZ"},
1006   { 0x008d, "AccelerometerX"},
1007   { 0x008e, "AccelerometerY"},
1008   { 0x008f, "CameraOrientation"},
1009   { 0x0090, "RollAngle"},
1010   { 0x0091, "PitchAngle"},
1011   { 0x0093, "SweepPanoramaDirection"},
1012   { 0x0094, "PanoramaFieldOfView"},
1013   { 0x0096, "TimerRecording"},
1014   { 0x009d, "InternalNDFilter"},
1015   { 0x009e, "HDR"},
1016   { 0x009f, "ShutterType"},
1017   { 0x00a3, "ClearRetouchValue"},
1018   { 0x00ab, "TouchAE"},
1019   { 0x0e00, "PrintIM"},
1020   { 0x8000, "MakerNoteVersion"},
1021   { 0x8001, "SceneMode"},
1022   { 0x8004, "WBRedLevel"},
1023   { 0x8005, "WBGreenLevel"},
1024   { 0x8006, "WBBlueLevel"},
1025   { 0x8007, "FlashFired"},
1026   { 0x8008, "TextStamp3"},
1027   { 0x8009, "TextStamp4"},
1028   { 0x8010, "BabyAge2"},
1029   { 0x8012, "Transform2"},
1030   TAG_TABLE_END
1031 };
1032 
1033 static tag_info_array tag_table_VND_DJI = {
1034   { 0x0001, "Make"},
1035   { 0x0003, "SpeedX"},
1036   { 0x0004, "SpeedY"},
1037   { 0x0005, "SpeedZ"},
1038   { 0x0006, "Pitch"},
1039   { 0x0007, "Yaw"},
1040   { 0x0008, "Roll"},
1041   { 0x0009, "CameraPitch"},
1042   { 0x000a, "CameraYaw"},
1043   { 0x000b, "CameraRoll"},
1044   TAG_TABLE_END
1045 };
1046 
1047 static tag_info_array tag_table_VND_SONY = {
1048   { 0x0102, "Quality"},
1049   { 0x0104, "FlashExposureComp"},
1050   { 0x0105, "Teleconverter"},
1051   { 0x0112, "WhiteBalanceFineTune"},
1052   { 0x0114, "CameraSettings"},
1053   { 0x0115, "WhiteBalance"},
1054   { 0x0116, "ExtraInfo"},
1055   { 0x0e00, "PrintIM"},
1056   { 0x1000, "MultiBurstMode"},
1057   { 0x1001, "MultiBurstImageWidth"},
1058   { 0x1002, "MultiBurstImageHeight"},
1059   { 0x1003, "Panorama"},
1060   { 0x2001, "PreviewImage"},
1061   { 0x2002, "Rating"},
1062   { 0x2004, "Contrast"},
1063   { 0x2005, "Saturation"},
1064   { 0x2006, "Sharpness"},
1065   { 0x2007, "Brightness"},
1066   { 0x2008, "LongExposureNoiseReduction"},
1067   { 0x2009, "HighISONoiseReduction"},
1068   { 0x200a, "AutoHDR"},
1069   { 0x3000, "ShotInfo"},
1070   { 0xb000, "FileFormat"},
1071   { 0xb001, "SonyModelID"},
1072   { 0xb020, "ColorReproduction"},
1073   { 0xb021, "ColorTemperature"},
1074   { 0xb022, "ColorCompensationFilter"},
1075   { 0xb023, "SceneMode"},
1076   { 0xb024, "ZoneMatching"},
1077   { 0xb025, "DynamicRangeOptimizer"},
1078   { 0xb026, "ImageStabilization"},
1079   { 0xb027, "LensID"},
1080   { 0xb028, "MinoltaMakerNote"},
1081   { 0xb029, "ColorMode"},
1082   { 0xb02b, "FullImageSize"},
1083   { 0xb02c, "PreviewImageSize"},
1084   { 0xb040, "Macro"},
1085   { 0xb041, "ExposureMode"},
1086   { 0xb042, "FocusMode"},
1087   { 0xb043, "AFMode"},
1088   { 0xb044, "AFIlluminator"},
1089   { 0xb047, "JPEGQuality"},
1090   { 0xb048, "FlashLevel"},
1091   { 0xb049, "ReleaseMode"},
1092   { 0xb04a, "SequenceNumber"},
1093   { 0xb04b, "AntiBlur"},
1094   { 0xb04e, "FocusMode"},
1095   { 0xb04f, "DynamicRangeOptimizer"},
1096   { 0xb050, "HighISONoiseReduction2"},
1097   { 0xb052, "IntelligentAuto"},
1098   { 0xb054, "WhiteBalance2"},
1099   TAG_TABLE_END
1100 };
1101 
1102 static tag_info_array tag_table_VND_PENTAX = {
1103   { 0x0000, "Version"},
1104   { 0x0001, "Mode"},
1105   { 0x0002, "PreviewResolution"},
1106   { 0x0003, "PreviewLength"},
1107   { 0x0004, "PreviewOffset"},
1108   { 0x0005, "ModelID"},
1109   { 0x0006, "Date"},
1110   { 0x0007, "Time"},
1111   { 0x0008, "Quality"},
1112   { 0x0009, "Size"},
1113   { 0x000c, "Flash"},
1114   { 0x000d, "Focus"},
1115   { 0x000e, "AFPoint"},
1116   { 0x000f, "AFPointInFocus"},
1117   { 0x0012, "ExposureTime"},
1118   { 0x0013, "FNumber"},
1119   { 0x0014, "ISO"},
1120   { 0x0016, "ExposureCompensation"},
1121   { 0x0017, "MeteringMode"},
1122   { 0x0018, "AutoBracketing"},
1123   { 0x0019, "WhiteBalance"},
1124   { 0x001a, "WhiteBalanceMode"},
1125   { 0x001b, "BlueBalance"},
1126   { 0x001c, "RedBalance"},
1127   { 0x001d, "FocalLength"},
1128   { 0x001e, "DigitalZoom"},
1129   { 0x001f, "Saturation"},
1130   { 0x0020, "Contrast"},
1131   { 0x0021, "Sharpness"},
1132   { 0x0022, "Location"},
1133   { 0x0023, "Hometown"},
1134   { 0x0024, "Destination"},
1135   { 0x0025, "HometownDST"},
1136   { 0x0026, "DestinationDST"},
1137   { 0x0027, "DSPFirmwareVersion"},
1138   { 0x0028, "CPUFirmwareVersion"},
1139   { 0x0029, "FrameNumber"},
1140   { 0x002d, "EffectiveLV"},
1141   { 0x0032, "ImageProcessing"},
1142   { 0x0033, "PictureMode"},
1143   { 0x0034, "DriveMode"},
1144   { 0x0037, "ColorSpace"},
1145   { 0x0038, "ImageAreaOffset"},
1146   { 0x0039, "RawImageSize"},
1147   { 0x003e, "PreviewImageBorders"},
1148   { 0x003f, "LensType"},
1149   { 0x0040, "SensitivityAdjust"},
1150   { 0x0041, "DigitalFilter"},
1151   { 0x0047, "Temperature"},
1152   { 0x0048, "AELock"},
1153   { 0x0049, "NoiseReduction"},
1154   { 0x004d, "FlashExposureCompensation"},
1155   { 0x004f, "ImageTone"},
1156   { 0x0050, "ColorTemperature"},
1157   { 0x005c, "ShakeReduction"},
1158   { 0x005d, "ShutterCount"},
1159   { 0x0069, "DynamicRangeExpansion"},
1160   { 0x0071, "HighISONoiseReduction"},
1161   { 0x0072, "AFAdjustment"},
1162   { 0x0200, "BlackPoint"},
1163   { 0x0201, "WhitePoint"},
1164   { 0x0205, "ShotInfo"},
1165   { 0x0206, "AEInfo"},
1166   { 0x0207, "LensInfo"},
1167   { 0x0208, "FlashInfo"},
1168   { 0x0209, "AEMeteringSegments"},
1169   { 0x020a, "FlashADump"},
1170   { 0x020b, "FlashBDump"},
1171   { 0x020d, "WB_RGGBLevelsDaylight"},
1172   { 0x020e, "WB_RGGBLevelsShade"},
1173   { 0x020f, "WB_RGGBLevelsCloudy"},
1174   { 0x0210, "WB_RGGBLevelsTungsten"},
1175   { 0x0211, "WB_RGGBLevelsFluorescentD"},
1176   { 0x0212, "WB_RGGBLevelsFluorescentN"},
1177   { 0x0213, "WB_RGGBLevelsFluorescentW"},
1178   { 0x0214, "WB_RGGBLevelsFlash"},
1179   { 0x0215, "CameraInfo"},
1180   { 0x0216, "BatteryInfo"},
1181   { 0x021f, "AFInfo"},
1182   { 0x0222, "ColorInfo"},
1183   { 0x0229, "SerialNumber"},
1184   TAG_TABLE_END
1185 };
1186 
1187 static tag_info_array tag_table_VND_MINOLTA = {
1188   { 0x0000, "Version"},
1189   { 0x0001, "CameraSettingsStdOld"},
1190   { 0x0003, "CameraSettingsStdNew"},
1191   { 0x0004, "CameraSettings7D"},
1192   { 0x0018, "ImageStabilizationData"},
1193   { 0x0020, "WBInfoA100"},
1194   { 0x0040, "CompressedImageSize"},
1195   { 0x0081, "Thumbnail"},
1196   { 0x0088, "ThumbnailOffset"},
1197   { 0x0089, "ThumbnailLength"},
1198   { 0x0100, "SceneMode"},
1199   { 0x0101, "ColorMode"},
1200   { 0x0102, "Quality"},
1201   { 0x0104, "FlashExposureComp"},
1202   { 0x0105, "Teleconverter"},
1203   { 0x0107, "ImageStabilization"},
1204   { 0x0109, "RawAndJpgRecording"},
1205   { 0x010a, "ZoneMatching"},
1206   { 0x010b, "ColorTemperature"},
1207   { 0x010c, "LensID"},
1208   { 0x0111, "ColorCompensationFilter"},
1209   { 0x0112, "WhiteBalanceFineTune"},
1210   { 0x0113, "ImageStabilizationA100"},
1211   { 0x0114, "CameraSettings5D"},
1212   { 0x0115, "WhiteBalance"},
1213   { 0x0e00, "PrintIM"},
1214   { 0x0f00, "CameraSettingsZ1"},
1215   TAG_TABLE_END
1216 };
1217 
1218 static tag_info_array tag_table_VND_SIGMA = {
1219   { 0x0002, "SerialNumber"},
1220   { 0x0003, "DriveMode"},
1221   { 0x0004, "ResolutionMode"},
1222   { 0x0005, "AutofocusMode"},
1223   { 0x0006, "FocusSetting"},
1224   { 0x0007, "WhiteBalance"},
1225   { 0x0008, "ExposureMode"},
1226   { 0x0009, "MeteringMode"},
1227   { 0x000a, "LensRange"},
1228   { 0x000b, "ColorSpace"},
1229   { 0x000c, "Exposure"},
1230   { 0x000d, "Contrast"},
1231   { 0x000e, "Shadow"},
1232   { 0x000f, "Highlight"},
1233   { 0x0010, "Saturation"},
1234   { 0x0011, "Sharpness"},
1235   { 0x0012, "FillLight"},
1236   { 0x0014, "ColorAdjustment"},
1237   { 0x0015, "AdjustmentMode"},
1238   { 0x0016, "Quality"},
1239   { 0x0017, "Firmware"},
1240   { 0x0018, "Software"},
1241   { 0x0019, "AutoBracket"},
1242   TAG_TABLE_END
1243 };
1244 
1245 static tag_info_array tag_table_VND_KYOCERA = {
1246   { 0x0001, "FormatThumbnail"},
1247   { 0x0E00, "PrintImageMatchingInfo"},
1248   TAG_TABLE_END
1249 };
1250 
1251 static tag_info_array tag_table_VND_RICOH = {
1252   { 0x0001, "MakerNoteDataType"},
1253   { 0x0002, "Version"},
1254   { 0x0E00, "PrintImageMatchingInfo"},
1255   { 0x2001, "RicohCameraInfoMakerNoteSubIFD"},
1256   TAG_TABLE_END
1257 };
1258 
1259 typedef enum mn_byte_order_t {
1260 	MN_ORDER_INTEL    = 0,
1261 	MN_ORDER_MOTOROLA = 1,
1262 	MN_ORDER_NORMAL
1263 } mn_byte_order_t;
1264 
1265 typedef enum mn_offset_mode_t {
1266 	MN_OFFSET_NORMAL,
1267 	MN_OFFSET_MAKER
1268 } mn_offset_mode_t;
1269 
1270 typedef struct {
1271 	tag_table_type   tag_table;
1272 	char *           make;
1273 	char *           id_string;
1274 	int              id_string_len;
1275 	int              offset;
1276 	mn_byte_order_t  byte_order;
1277 	mn_offset_mode_t offset_mode;
1278 } maker_note_type;
1279 
1280 /* Remember to update PHP_MINFO if updated */
1281 static const maker_note_type maker_note_array[] = {
1282   { tag_table_VND_CANON,     "Canon",                   NULL,								0,  0,  MN_ORDER_INTEL,    MN_OFFSET_NORMAL},
1283   { tag_table_VND_CASIO,     "CASIO",                   NULL,							 	0,  0,  MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL},
1284   { tag_table_VND_FUJI,      "FUJIFILM",                "FUJIFILM\x0C\x00\x00\x00",		 	12, 12, MN_ORDER_INTEL,    MN_OFFSET_MAKER},
1285   { tag_table_VND_NIKON,     "NIKON",                   "Nikon\x00\x01\x00",				8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1286   { tag_table_VND_NIKON_990, "NIKON",                   NULL,								0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1287   { tag_table_VND_OLYMPUS,   "OLYMPUS OPTICAL CO.,LTD", "OLYMP\x00\x01\x00",				8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1288   { tag_table_VND_SAMSUNG,   "SAMSUNG",                 NULL,								0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1289   { tag_table_VND_PANASONIC, "Panasonic",               "Panasonic\x00\x00\x00",			12, 12, MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1290   { tag_table_VND_DJI,       "DJI",                     NULL,								0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1291   { tag_table_VND_SONY,      "SONY",                    "SONY DSC \x00\x00\x00",			12, 12, MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1292   { tag_table_VND_SONY,      "SONY",                    NULL,								0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1293   { tag_table_VND_PENTAX,    "PENTAX",                  "AOC\x00",						 	6,  6,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1294   { tag_table_VND_MINOLTA,   "Minolta, KONICA MINOLTA", NULL,								0,  0,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1295   { tag_table_VND_SIGMA,     "SIGMA, FOVEON",           "SIGMA\x00\x00\x00",				10, 10, MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1296   { tag_table_VND_SIGMA,     "SIGMA, FOVEON",           "FOVEON\x00\x00\x00",				10, 10, MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1297   { tag_table_VND_KYOCERA,   "KYOCERA, CONTAX",			"KYOCERA            \x00\x00\x00",	22, 22, MN_ORDER_NORMAL,   MN_OFFSET_MAKER},
1298   { tag_table_VND_RICOH,	 "RICOH",					"Ricoh",							5,  5,  MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL},
1299   { tag_table_VND_RICOH,     "RICOH",					"RICOH",							5,  5,  MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL},
1300 
1301   /* These re-uses existing formats */
1302   { tag_table_VND_OLYMPUS,   "AGFA",					"AGFA \x00\x01",					8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL},
1303   { tag_table_VND_OLYMPUS,   "EPSON",					"EPSON\x00\x01\x00",				8,  8,  MN_ORDER_NORMAL,   MN_OFFSET_NORMAL}
1304 };
1305 /* }}} */
1306 
exif_make_tag_ht(tag_info_type * tag_table)1307 static HashTable *exif_make_tag_ht(tag_info_type *tag_table)
1308 {
1309 	HashTable *ht = malloc(sizeof(HashTable));
1310 	zend_hash_init(ht, 0, NULL, NULL, 1);
1311 	while (tag_table->Tag != TAG_END_OF_LIST) {
1312 		if (!zend_hash_index_add_ptr(ht, tag_table->Tag, tag_table->Desc)) {
1313 			zend_error(E_CORE_ERROR, "Duplicate tag %x", tag_table->Tag);
1314 		}
1315 		tag_table++;
1316 	}
1317 	return ht;
1318 }
1319 
exif_tag_ht_dtor(zval * zv)1320 static void exif_tag_ht_dtor(zval *zv)
1321 {
1322 	HashTable *ht = Z_PTR_P(zv);
1323 	zend_hash_destroy(ht);
1324 	free(ht);
1325 }
1326 
exif_get_tag_ht(tag_info_type * tag_table)1327 static HashTable *exif_get_tag_ht(tag_info_type *tag_table)
1328 {
1329 	HashTable *ht;
1330 
1331 	if (!EXIF_G(tag_table_cache)) {
1332 		EXIF_G(tag_table_cache) = malloc(sizeof(HashTable));
1333 		zend_hash_init(EXIF_G(tag_table_cache), 0, NULL, exif_tag_ht_dtor, 1);
1334 	}
1335 
1336 	ht = zend_hash_index_find_ptr(EXIF_G(tag_table_cache), (uintptr_t) tag_table);
1337 	if (ht) {
1338 		return ht;
1339 	}
1340 
1341 	ht = exif_make_tag_ht(tag_table);
1342 	zend_hash_index_add_new_ptr(EXIF_G(tag_table_cache), (uintptr_t) tag_table, ht);
1343 	return ht;
1344 }
1345 
1346 /* {{{ exif_get_tagname
1347 	Get headername for tag_num or NULL if not defined */
exif_get_tagname(int tag_num,tag_table_type tag_table)1348 static char *exif_get_tagname(int tag_num, tag_table_type tag_table)
1349 {
1350 	return zend_hash_index_find_ptr(exif_get_tag_ht(tag_table), tag_num);
1351 }
1352 /* }}} */
1353 
exif_get_tagname_debug(int tag_num,tag_table_type tag_table)1354 static char *exif_get_tagname_debug(int tag_num, tag_table_type tag_table)
1355 {
1356 	char *desc = zend_hash_index_find_ptr(exif_get_tag_ht(tag_table), tag_num);
1357 	if (desc) {
1358 		return desc;
1359 	}
1360 	return "UndefinedTag";
1361 }
1362 
exif_get_tagname_key(int tag_num,char * buf,size_t buf_size,tag_table_type tag_table)1363 static char *exif_get_tagname_key(int tag_num, char *buf, size_t buf_size, tag_table_type tag_table)
1364 {
1365 	char *desc = zend_hash_index_find_ptr(exif_get_tag_ht(tag_table), tag_num);
1366 	if (desc) {
1367 		return desc;
1368 	}
1369 	snprintf(buf, buf_size, "UndefinedTag:0x%04X", tag_num);
1370 	return buf;
1371 }
1372 
1373 /* {{{ exif_char_dump
1374  * Do not use! This is a debug function... */
1375 #ifdef EXIF_DEBUG
exif_char_dump(char * addr,int len,int offset)1376 static char* exif_char_dump(char * addr, int len, int offset)
1377 {
1378 	static char buf[4096+1];
1379 	static char tmp[20];
1380 	int c, i, p=0, n = 5+31;
1381 
1382 	p += slprintf(buf+p, sizeof(buf)-p, "\nDump Len: %08X (%d)", len, len);
1383 	if (len) {
1384 		for(i=0; i<len+15 && p+n<=sizeof(buf); i++) {
1385 			if (i%16==0) {
1386 				p += slprintf(buf+p, sizeof(buf)-p, "\n%08X: ", i+offset);
1387 			}
1388 			if (i<len) {
1389 				c = *((unsigned char *)addr++);
1390 				p += slprintf(buf+p, sizeof(buf)-p, "%02X ", c);
1391 				tmp[i%16] = c>=32 ? c : '.';
1392 				tmp[(i%16)+1] = '\0';
1393 			} else {
1394 				p += slprintf(buf+p, sizeof(buf)-p, "   ");
1395 			}
1396 			if (i%16==15) {
1397 				p += slprintf(buf+p, sizeof(buf)-p, "    %s", tmp);
1398 				if (i>=len) {
1399 					break;
1400 				}
1401 			}
1402 		}
1403 	}
1404 	buf[sizeof(buf)-1] = '\0';
1405 	return buf;
1406 }
1407 #endif
1408 /* }}} */
1409 
1410 /* {{{ php_jpg_get16
1411    Get 16 bits motorola order (always) for jpeg header stuff.
1412 */
php_jpg_get16(void * value)1413 static int php_jpg_get16(void *value)
1414 {
1415 	return (((uchar *)value)[0] << 8) | ((uchar *)value)[1];
1416 }
1417 /* }}} */
1418 
1419 /* {{{ php_ifd_get16u
1420  * Convert a 16 bit unsigned value from file's native byte order */
php_ifd_get16u(void * value,int motorola_intel)1421 static int php_ifd_get16u(void *value, int motorola_intel)
1422 {
1423 	if (motorola_intel) {
1424 		return (((uchar *)value)[0] << 8) | ((uchar *)value)[1];
1425 	} else {
1426 		return (((uchar *)value)[1] << 8) | ((uchar *)value)[0];
1427 	}
1428 }
1429 /* }}} */
1430 
1431 /* {{{ php_ifd_get16s
1432  * Convert a 16 bit signed value from file's native byte order */
php_ifd_get16s(void * value,int motorola_intel)1433 static signed short php_ifd_get16s(void *value, int motorola_intel)
1434 {
1435 	return (signed short)php_ifd_get16u(value, motorola_intel);
1436 }
1437 /* }}} */
1438 
1439 /* {{{ php_ifd_get32u
1440  * Convert a 32 bit unsigned value from file's native byte order */
php_ifd_get32u(void * void_value,int motorola_intel)1441 static unsigned php_ifd_get32u(void *void_value, int motorola_intel)
1442 {
1443 	uchar *value = (uchar *) void_value;
1444 	if (motorola_intel) {
1445 		return  ((unsigned)value[0] << 24)
1446 			  | ((unsigned)value[1] << 16)
1447 			  | ((unsigned)value[2] << 8 )
1448 			  | ((unsigned)value[3]      );
1449 	} else {
1450 		return  ((unsigned)value[3] << 24)
1451 			  | ((unsigned)value[2] << 16)
1452 			  | ((unsigned)value[1] << 8 )
1453 			  | ((unsigned)value[0]      );
1454 	}
1455 }
1456 /* }}} */
1457 
1458 /* {{{ php_ifd_get64u
1459  * Convert a 64 bit unsigned value from file's native byte order */
php_ifd_get64u(void * void_value,int motorola_intel)1460 static uint64_t php_ifd_get64u(void *void_value, int motorola_intel)
1461 {
1462 	uchar *value = (uchar *) void_value;
1463 	if (motorola_intel) {
1464 		return ((uint64_t)value[0] << 56)
1465 			| ((uint64_t)value[1] << 48)
1466 			| ((uint64_t)value[2] << 40)
1467 			| ((uint64_t)value[3] << 32)
1468 			| ((uint64_t)value[4] << 24)
1469 			| ((uint64_t)value[5] << 16)
1470 			| ((uint64_t)value[6] << 8 )
1471 			| ((uint64_t)value[7]      );
1472 	} else {
1473 		return ((uint64_t)value[7] << 56)
1474 			| ((uint64_t)value[6] << 48)
1475 			| ((uint64_t)value[5] << 40)
1476 			| ((uint64_t)value[4] << 32)
1477 			| ((uint64_t)value[3] << 24)
1478 			| ((uint64_t)value[2] << 16)
1479 			| ((uint64_t)value[1] << 8 )
1480 			| ((uint64_t)value[0]      );
1481 	}
1482 }
1483 /* }}} */
1484 
1485 /* {{{ php_ifd_get32u
1486  * Convert a 32 bit signed value from file's native byte order */
php_ifd_get32s(void * value,int motorola_intel)1487 static unsigned php_ifd_get32s(void *value, int motorola_intel)
1488 {
1489 	return (int) php_ifd_get32u(value, motorola_intel);
1490 }
1491 /* }}} */
1492 
1493 /* {{{ php_ifd_set16u
1494  * Write 16 bit unsigned value to data */
php_ifd_set16u(char * data,unsigned int value,int motorola_intel)1495 static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel)
1496 {
1497 	if (motorola_intel) {
1498 		data[0] = (value & 0xFF00) >> 8;
1499 		data[1] = (value & 0x00FF);
1500 	} else {
1501 		data[1] = (value & 0xFF00) >> 8;
1502 		data[0] = (value & 0x00FF);
1503 	}
1504 }
1505 /* }}} */
1506 
1507 /* {{{ php_ifd_set32u
1508  * Convert a 32 bit unsigned value from file's native byte order */
php_ifd_set32u(char * data,size_t value,int motorola_intel)1509 static void php_ifd_set32u(char *data, size_t value, int motorola_intel)
1510 {
1511 	if (motorola_intel) {
1512 		data[0] = (value & 0xFF000000) >> 24;
1513 		data[1] = (char) ((value & 0x00FF0000) >> 16);
1514 		data[2] = (value & 0x0000FF00) >>  8;
1515 		data[3] = (value & 0x000000FF);
1516 	} else {
1517 		data[3] = (value & 0xFF000000) >> 24;
1518 		data[2] = (char) ((value & 0x00FF0000) >> 16);
1519 		data[1] = (value & 0x0000FF00) >>  8;
1520 		data[0] = (value & 0x000000FF);
1521 	}
1522 }
1523 /* }}} */
1524 
php_ifd_get_float(char * data)1525 static float php_ifd_get_float(char *data) {
1526 	union { uint32_t i; float f; } u;
1527 	u.i = php_ifd_get32u(data, 0);
1528 	return u.f;
1529 }
1530 
php_ifd_get_double(char * data)1531 static double php_ifd_get_double(char *data) {
1532 	union { uint64_t i; double f; } u;
1533 	u.i = php_ifd_get64u(data, 0);
1534 	return u.f;
1535 }
1536 
1537 #ifdef EXIF_DEBUG
exif_dump_data(int * dump_free,int format,int components,int motorola_intel,char * value_ptr)1538 char * exif_dump_data(int *dump_free, int format, int components, int motorola_intel, char *value_ptr) /* {{{ */
1539 {
1540 	char *dump;
1541 	int len;
1542 
1543 	*dump_free = 0;
1544 	if (format == TAG_FMT_STRING) {
1545 		return value_ptr ? value_ptr : "<no data>";
1546 	}
1547 	if (format == TAG_FMT_UNDEFINED) {
1548 		return "<undefined>";
1549 	}
1550 	if (format == TAG_FMT_IFD) {
1551 		return "";
1552 	}
1553 	if (format == TAG_FMT_SINGLE || format == TAG_FMT_DOUBLE) {
1554 		return "<not implemented>";
1555 	}
1556 	*dump_free = 1;
1557 	if (components > 1) {
1558 		len = spprintf(&dump, 0, "(%d) {", components);
1559 	} else {
1560 		len = spprintf(&dump, 0, "{");
1561 	}
1562 	while(components > 0) {
1563 		switch(format) {
1564 			case TAG_FMT_BYTE:
1565 			case TAG_FMT_UNDEFINED:
1566 			case TAG_FMT_STRING:
1567 			case TAG_FMT_SBYTE:
1568 				dump = erealloc(dump, len + 4 + 1);
1569 				snprintf(dump + len, 4 + 1, "0x%02X", *value_ptr);
1570 				len += 4;
1571 				value_ptr++;
1572 				break;
1573 			case TAG_FMT_USHORT:
1574 			case TAG_FMT_SSHORT:
1575 				dump = erealloc(dump, len + 6 + 1);
1576 				snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel));
1577 				len += 6;
1578 				value_ptr += 2;
1579 				break;
1580 			case TAG_FMT_ULONG:
1581 			case TAG_FMT_SLONG:
1582 				dump = erealloc(dump, len + 6 + 1);
1583 				snprintf(dump + len, 6 + 1, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel));
1584 				len += 6;
1585 				value_ptr += 4;
1586 				break;
1587 			case TAG_FMT_URATIONAL:
1588 			case TAG_FMT_SRATIONAL:
1589 				dump = erealloc(dump, len + 13 + 1);
1590 				snprintf(dump + len, 13 + 1, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel));
1591 				len += 13;
1592 				value_ptr += 8;
1593 				break;
1594 		}
1595 		if (components > 0) {
1596 			dump = erealloc(dump, len + 2 + 1);
1597 			snprintf(dump + len, 2 + 1, ", ");
1598 			len += 2;
1599 			components--;
1600 		} else{
1601 			break;
1602 		}
1603 	}
1604 	dump = erealloc(dump, len + 1 + 1);
1605 	snprintf(dump + len, 1 + 1, "}");
1606 	return dump;
1607 }
1608 /* }}} */
1609 #endif
1610 
1611 /* {{{ exif_convert_any_format
1612  * Evaluate number, be it int, rational, or float from directory. */
exif_convert_any_format(void * value,int format,int motorola_intel)1613 static double exif_convert_any_format(void *value, int format, int motorola_intel)
1614 {
1615 	int 		s_den;
1616 	unsigned 	u_den;
1617 
1618 	switch(format) {
1619 		case TAG_FMT_SBYTE:     return *(signed char *)value;
1620 		case TAG_FMT_BYTE:      return *(uchar *)value;
1621 
1622 		case TAG_FMT_USHORT:    return php_ifd_get16u(value, motorola_intel);
1623 		case TAG_FMT_ULONG:     return php_ifd_get32u(value, motorola_intel);
1624 
1625 		case TAG_FMT_URATIONAL:
1626 			u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
1627 			if (u_den == 0) {
1628 				return 0;
1629 			} else {
1630 				return (double)php_ifd_get32u(value, motorola_intel) / u_den;
1631 			}
1632 
1633 		case TAG_FMT_SRATIONAL:
1634 			s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
1635 			if (s_den == 0) {
1636 				return 0;
1637 			} else {
1638 				return (double)php_ifd_get32s(value, motorola_intel) / s_den;
1639 			}
1640 
1641 		case TAG_FMT_SSHORT:    return (signed short)php_ifd_get16u(value, motorola_intel);
1642 		case TAG_FMT_SLONG:     return php_ifd_get32s(value, motorola_intel);
1643 
1644 		/* Not sure if this is correct (never seen float used in Exif format) */
1645 		case TAG_FMT_SINGLE:
1646 #ifdef EXIF_DEBUG
1647 			php_error_docref(NULL, E_NOTICE, "Found value of type single");
1648 #endif
1649 			return (double) php_ifd_get_float(value);
1650 		case TAG_FMT_DOUBLE:
1651 #ifdef EXIF_DEBUG
1652 			php_error_docref(NULL, E_NOTICE, "Found value of type double");
1653 #endif
1654 			return php_ifd_get_double(value);
1655 	}
1656 	return 0;
1657 }
1658 /* }}} */
1659 
1660 /* {{{ exif_rewrite_tag_format_to_unsigned
1661  * Rewrite format tag so that it specifies an unsigned type for a tag */
exif_rewrite_tag_format_to_unsigned(int format)1662 static int exif_rewrite_tag_format_to_unsigned(int format)
1663 {
1664 	switch(format) {
1665 		case TAG_FMT_SBYTE: return TAG_FMT_BYTE;
1666 		case TAG_FMT_SRATIONAL: return TAG_FMT_URATIONAL;
1667 		case TAG_FMT_SSHORT: return TAG_FMT_USHORT;
1668 		case TAG_FMT_SLONG: return TAG_FMT_ULONG;
1669 	}
1670 	return format;
1671 }
1672 /* }}} */
1673 
1674 /* Use saturation for out of bounds values to avoid UB */
float_to_size_t(float x)1675 static size_t float_to_size_t(float x) {
1676 	if (x < 0.0f || zend_isnan(x)) {
1677 		return 0;
1678 	} else if (x > (float) SIZE_MAX) {
1679 		return SIZE_MAX;
1680 	} else {
1681 		return (size_t) x;
1682 	}
1683 }
1684 
double_to_size_t(double x)1685 static size_t double_to_size_t(double x) {
1686 	if (x < 0.0 || zend_isnan(x)) {
1687 		return 0;
1688 	} else if (x > (double) SIZE_MAX) {
1689 		return SIZE_MAX;
1690 	} else {
1691 		return (size_t) x;
1692 	}
1693 }
1694 
1695 /* {{{ exif_convert_any_to_int
1696  * Evaluate number, be it int, rational, or float from directory. */
exif_convert_any_to_int(void * value,int format,int motorola_intel)1697 static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel)
1698 {
1699 	switch (format) {
1700 		case TAG_FMT_SBYTE:     return *(signed char *)value;
1701 		case TAG_FMT_BYTE:      return *(uchar *)value;
1702 
1703 		case TAG_FMT_USHORT:    return php_ifd_get16u(value, motorola_intel);
1704 		case TAG_FMT_ULONG:     return php_ifd_get32u(value, motorola_intel);
1705 
1706 		case TAG_FMT_URATIONAL: {
1707 			unsigned u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
1708 			if (u_den == 0) {
1709 				return 0;
1710 			} else {
1711 				return php_ifd_get32u(value, motorola_intel) / u_den;
1712 			}
1713 		}
1714 
1715 		case TAG_FMT_SRATIONAL: {
1716 			int s_num = php_ifd_get32s(value, motorola_intel);
1717 			int s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
1718 			if (s_den == 0) {
1719 				return 0;
1720 			} else if (s_num == INT_MIN && s_den == -1) {
1721 				return INT_MAX;
1722 			} else {
1723 				return s_num / s_den;
1724 			}
1725 		}
1726 
1727 		case TAG_FMT_SSHORT:    return php_ifd_get16u(value, motorola_intel);
1728 		case TAG_FMT_SLONG:     return php_ifd_get32s(value, motorola_intel);
1729 
1730 		/* Not sure if this is correct (never seen float used in Exif format) */
1731 		case TAG_FMT_SINGLE:
1732 #ifdef EXIF_DEBUG
1733 			php_error_docref(NULL, E_NOTICE, "Found value of type single");
1734 #endif
1735 			return float_to_size_t(php_ifd_get_float(value));
1736 		case TAG_FMT_DOUBLE:
1737 #ifdef EXIF_DEBUG
1738 			php_error_docref(NULL, E_NOTICE, "Found value of type double");
1739 #endif
1740 			return double_to_size_t(php_ifd_get_double(value));
1741 	}
1742 	return 0;
1743 }
1744 /* }}} */
1745 
1746 /* {{{ struct image_info_value, image_info_list */
1747 #ifndef WORD
1748 #define WORD unsigned short
1749 #endif
1750 #ifndef DWORD
1751 #define DWORD unsigned int
1752 #endif
1753 
1754 typedef struct {
1755 	int             num;
1756 	int             den;
1757 } signed_rational;
1758 
1759 typedef struct {
1760 	unsigned int    num;
1761 	unsigned int    den;
1762 } unsigned_rational;
1763 
1764 typedef union _image_info_value {
1765 	char 				*s;
1766 	unsigned            u;
1767 	int 				i;
1768 	float               f;
1769 	double              d;
1770 	signed_rational 	sr;
1771 	unsigned_rational 	ur;
1772 	union _image_info_value   *list;
1773 } image_info_value;
1774 
1775 typedef struct {
1776 	WORD                tag;
1777 	WORD                format;
1778 	DWORD               length;
1779 	DWORD               dummy;  /* value ptr of tiff directory entry */
1780 	char 				*name;
1781 	image_info_value    value;
1782 } image_info_data;
1783 
1784 typedef struct {
1785 	int                 count;
1786 	int                 alloc_count;
1787 	image_info_data 	*list;
1788 } image_info_list;
1789 /* }}} */
1790 
1791 /* {{{ exif_get_sectionname
1792  Returns the name of a section
1793 */
1794 #define SECTION_FILE        0
1795 #define SECTION_COMPUTED    1
1796 #define SECTION_ANY_TAG     2
1797 #define SECTION_IFD0        3
1798 #define SECTION_THUMBNAIL   4
1799 #define SECTION_COMMENT     5
1800 #define SECTION_APP0        6
1801 #define SECTION_EXIF        7
1802 #define SECTION_FPIX        8
1803 #define SECTION_GPS         9
1804 #define SECTION_INTEROP     10
1805 #define SECTION_APP12       11
1806 #define SECTION_WINXP       12
1807 #define SECTION_MAKERNOTE   13
1808 #define SECTION_COUNT       14
1809 
1810 #define FOUND_FILE          (1<<SECTION_FILE)
1811 #define FOUND_COMPUTED      (1<<SECTION_COMPUTED)
1812 #define FOUND_ANY_TAG       (1<<SECTION_ANY_TAG)
1813 #define FOUND_IFD0          (1<<SECTION_IFD0)
1814 #define FOUND_THUMBNAIL     (1<<SECTION_THUMBNAIL)
1815 #define FOUND_COMMENT       (1<<SECTION_COMMENT)
1816 #define FOUND_APP0          (1<<SECTION_APP0)
1817 #define FOUND_EXIF          (1<<SECTION_EXIF)
1818 #define FOUND_FPIX          (1<<SECTION_FPIX)
1819 #define FOUND_GPS           (1<<SECTION_GPS)
1820 #define FOUND_INTEROP       (1<<SECTION_INTEROP)
1821 #define FOUND_APP12         (1<<SECTION_APP12)
1822 #define FOUND_WINXP         (1<<SECTION_WINXP)
1823 #define FOUND_MAKERNOTE     (1<<SECTION_MAKERNOTE)
1824 
exif_get_sectionname(int section)1825 static char *exif_get_sectionname(int section)
1826 {
1827 	switch(section) {
1828 		case SECTION_FILE:      return "FILE";
1829 		case SECTION_COMPUTED:  return "COMPUTED";
1830 		case SECTION_ANY_TAG:   return "ANY_TAG";
1831 		case SECTION_IFD0:      return "IFD0";
1832 		case SECTION_THUMBNAIL: return "THUMBNAIL";
1833 		case SECTION_COMMENT:   return "COMMENT";
1834 		case SECTION_APP0:      return "APP0";
1835 		case SECTION_EXIF:      return "EXIF";
1836 		case SECTION_FPIX:      return "FPIX";
1837 		case SECTION_GPS:       return "GPS";
1838 		case SECTION_INTEROP:   return "INTEROP";
1839 		case SECTION_APP12:     return "APP12";
1840 		case SECTION_WINXP:     return "WINXP";
1841 		case SECTION_MAKERNOTE: return "MAKERNOTE";
1842 	}
1843 	return "";
1844 }
1845 
exif_get_tag_table(int section)1846 static tag_table_type exif_get_tag_table(int section)
1847 {
1848 	switch(section) {
1849 		case SECTION_FILE:      return &tag_table_IFD[0];
1850 		case SECTION_COMPUTED:  return &tag_table_IFD[0];
1851 		case SECTION_ANY_TAG:   return &tag_table_IFD[0];
1852 		case SECTION_IFD0:      return &tag_table_IFD[0];
1853 		case SECTION_THUMBNAIL: return &tag_table_IFD[0];
1854 		case SECTION_COMMENT:   return &tag_table_IFD[0];
1855 		case SECTION_APP0:      return &tag_table_IFD[0];
1856 		case SECTION_EXIF:      return &tag_table_IFD[0];
1857 		case SECTION_FPIX:      return &tag_table_IFD[0];
1858 		case SECTION_GPS:       return &tag_table_GPS[0];
1859 		case SECTION_INTEROP:   return &tag_table_IOP[0];
1860 		case SECTION_APP12:     return &tag_table_IFD[0];
1861 		case SECTION_WINXP:     return &tag_table_IFD[0];
1862 	}
1863 	return &tag_table_IFD[0];
1864 }
1865 /* }}} */
1866 
1867 /* {{{ exif_get_sectionlist
1868    Return list of sectionnames specified by sectionlist. Return value must be freed
1869 */
exif_get_sectionlist(int sectionlist)1870 static char *exif_get_sectionlist(int sectionlist)
1871 {
1872 	int i, len, ml = 0;
1873 	char *sections;
1874 
1875 	for(i=0; i<SECTION_COUNT; i++) {
1876 		ml += strlen(exif_get_sectionname(i))+2;
1877 	}
1878 	sections = safe_emalloc(ml, 1, 1);
1879 	sections[0] = '\0';
1880 	len = 0;
1881 	for(i=0; i<SECTION_COUNT; i++) {
1882 		if (sectionlist&(1<<i)) {
1883 			snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i));
1884 			len = strlen(sections);
1885 		}
1886 	}
1887 	if (len>2)
1888 		sections[len-2] = '\0';
1889 	return sections;
1890 }
1891 /* }}} */
1892 
1893 /* {{{ struct image_info_type
1894    This structure stores Exif header image elements in a simple manner
1895    Used to store camera data as extracted from the various ways that it can be
1896    stored in a nexif header
1897 */
1898 
1899 typedef struct {
1900 	int     type;
1901 	size_t  size;
1902 	uchar   *data;
1903 } file_section;
1904 
1905 typedef struct {
1906 	int             count;
1907 	int             alloc_count;
1908 	file_section    *list;
1909 } file_section_list;
1910 
1911 typedef struct {
1912 	image_filetype  filetype;
1913 	size_t          width, height;
1914 	size_t          size;
1915 	size_t          offset;
1916 	char 	        *data;
1917 } thumbnail_data;
1918 
1919 typedef struct {
1920 	char			*value;
1921 	size_t			size;
1922 	int				tag;
1923 } xp_field_type;
1924 
1925 typedef struct {
1926 	int             count;
1927 	xp_field_type   *list;
1928 } xp_field_list;
1929 
1930 /* This structure is used to store a section of a Jpeg file. */
1931 typedef struct {
1932 	php_stream      *infile;
1933 	char            *FileName;
1934 	time_t          FileDateTime;
1935 	size_t          FileSize;
1936 	image_filetype  FileType;
1937 	int             Height, Width;
1938 	int             IsColor;
1939 
1940 	char            *make;
1941 	char            *model;
1942 
1943 	float           ApertureFNumber;
1944 	float           ExposureTime;
1945 	double          FocalplaneUnits;
1946 	float           CCDWidth;
1947 	double          FocalplaneXRes;
1948 	size_t          ExifImageWidth;
1949 	float           FocalLength;
1950 	float           Distance;
1951 
1952 	int             motorola_intel; /* 1 Motorola; 0 Intel */
1953 
1954 	char            *UserComment;
1955 	int             UserCommentLength;
1956 	char            *UserCommentEncoding;
1957 	char            *encode_unicode;
1958 	char            *decode_unicode_be;
1959 	char            *decode_unicode_le;
1960 	char            *encode_jis;
1961 	char            *decode_jis_be;
1962 	char            *decode_jis_le;
1963 	char            *Copyright;/* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */
1964 	char            *CopyrightPhotographer;
1965 	char            *CopyrightEditor;
1966 
1967 	xp_field_list   xp_fields;
1968 
1969 	thumbnail_data  Thumbnail;
1970 	/* other */
1971 	int             sections_found; /* FOUND_<marker> */
1972 	image_info_list info_list[SECTION_COUNT];
1973 	/* for parsing */
1974 	int             read_thumbnail;
1975 	int             read_all;
1976 	int             ifd_nesting_level;
1977 	int             ifd_count;
1978 	int             num_errors;
1979 	/* internal */
1980 	file_section_list 	file;
1981 } image_info_type;
1982 /* }}} */
1983 
1984 // EXIF_DEBUG can produce lots of messages
1985 #ifndef EXIF_DEBUG
1986 #define EXIF_MAX_ERRORS 10
1987 #else
1988 #define EXIF_MAX_ERRORS 100000
1989 #endif
1990 
1991 /* {{{ exif_error_docref */
exif_error_docref(const char * docref EXIFERR_DC,image_info_type * ImageInfo,int type,const char * format,...)1992 static void exif_error_docref(const char *docref EXIFERR_DC, image_info_type *ImageInfo, int type, const char *format, ...)
1993 {
1994 	va_list args;
1995 
1996 	if (ImageInfo) {
1997 		if (++ImageInfo->num_errors > EXIF_MAX_ERRORS) {
1998 			if (ImageInfo->num_errors == EXIF_MAX_ERRORS+1) {
1999 				php_error_docref(docref, type,
2000 					"Further exif parsing errors have been suppressed");
2001 			}
2002 			return;
2003 		}
2004 	}
2005 
2006 	va_start(args, format);
2007 #ifdef EXIF_DEBUG
2008 	{
2009 		char *buf;
2010 
2011 		spprintf(&buf, 0, "%s(%ld): %s", _file, _line, format);
2012 		php_verror(docref, ImageInfo && ImageInfo->FileName ? ImageInfo->FileName:"", type, buf, args);
2013 		efree(buf);
2014 	}
2015 #else
2016 	php_verror(docref, ImageInfo && ImageInfo->FileName ? ImageInfo->FileName:"", type, format, args);
2017 #endif
2018 	va_end(args);
2019 }
2020 /* }}} */
2021 
2022 /* {{{ jpeg_sof_info */
2023 typedef struct {
2024 	int     bits_per_sample;
2025 	size_t  width;
2026 	size_t  height;
2027 	int     num_components;
2028 } jpeg_sof_info;
2029 /* }}} */
2030 
2031 /* Base address for offset references, together with valid memory range.
2032  * The valid range does not necessarily include the offset base. */
2033 typedef struct {
2034 	char *offset_base;
2035 	char *valid_start; /* inclusive */
2036 	char *valid_end;   /* exclusive */
2037 } exif_offset_info;
2038 
ptr_offset_overflows(char * ptr,size_t offset)2039 static zend_always_inline bool ptr_offset_overflows(char *ptr, size_t offset) {
2040 	return UINTPTR_MAX - (uintptr_t) ptr < offset;
2041 }
2042 
exif_offset_info_init(exif_offset_info * info,char * offset_base,char * valid_start,size_t valid_length)2043 static inline void exif_offset_info_init(
2044 		exif_offset_info *info, char *offset_base, char *valid_start, size_t valid_length) {
2045 	ZEND_ASSERT(!ptr_offset_overflows(valid_start, valid_length));
2046 #ifdef __SANITIZE_ADDRESS__
2047 	ZEND_ASSERT(!__asan_region_is_poisoned(valid_start, valid_length));
2048 #endif
2049 	info->offset_base = offset_base;
2050 	info->valid_start = valid_start;
2051 	info->valid_end = valid_start + valid_length;
2052 }
2053 
2054 /* Try to get a pointer at offset_base+offset with length dereferenceable bytes. */
exif_offset_info_try_get(const exif_offset_info * info,size_t offset,size_t length)2055 static inline char *exif_offset_info_try_get(
2056 		const exif_offset_info *info, size_t offset, size_t length) {
2057 	char *start, *end;
2058 	if (ptr_offset_overflows(info->offset_base, offset)) {
2059 		return NULL;
2060 	}
2061 
2062 	start = info->offset_base + offset;
2063 	if (ptr_offset_overflows(start, length)) {
2064 		return NULL;
2065 	}
2066 
2067 	end = start + length;
2068 	if (start < info->valid_start || end > info->valid_end) {
2069 		return NULL;
2070 	}
2071 
2072 	return start;
2073 }
2074 
exif_offset_info_contains(const exif_offset_info * info,char * start,size_t length)2075 static inline bool exif_offset_info_contains(
2076 		const exif_offset_info *info, char *start, size_t length) {
2077 	char *end;
2078 	if (ptr_offset_overflows(start, length)) {
2079 		return 0;
2080 	}
2081 
2082 	/* start and valid_start are both inclusive, end and valid_end are both exclusive,
2083 	 * so we use >= and <= to do the checks, respectively. */
2084 	end = start + length;
2085 	return start >= info->valid_start && end <= info->valid_end;
2086 }
2087 
2088 #ifdef EXIF_DEBUG
exif_offset_info_length(const exif_offset_info * info)2089 static inline int exif_offset_info_length(const exif_offset_info *info)
2090 {
2091 	return info->valid_end - info->valid_start;
2092 }
2093 #endif
2094 
2095 /* {{{ exif_file_sections_add
2096  Add a file_section to image_info
2097  returns the used block or -1. if size>0 and data == NULL buffer of size is allocated
2098 */
exif_file_sections_add(image_info_type * ImageInfo,int type,size_t size,uchar * data)2099 static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, uchar *data)
2100 {
2101 	int count = ImageInfo->file.count;
2102 	if (count == ImageInfo->file.alloc_count) {
2103 		int new_alloc_count = ImageInfo->file.alloc_count ? ImageInfo->file.alloc_count * 2 : 1;
2104 		ImageInfo->file.list = safe_erealloc(
2105 			ImageInfo->file.list, new_alloc_count, sizeof(file_section), 0);
2106 		ImageInfo->file.alloc_count = new_alloc_count;
2107 	}
2108 
2109 	ImageInfo->file.list[count].type = 0xFFFF;
2110 	ImageInfo->file.list[count].data = NULL;
2111 	ImageInfo->file.list[count].size = 0;
2112 	ImageInfo->file.count = count+1;
2113 	if (!size) {
2114 		data = NULL;
2115 	} else if (data == NULL) {
2116 		data = safe_emalloc(size, 1, 0);
2117 	}
2118 	ImageInfo->file.list[count].type = type;
2119 	ImageInfo->file.list[count].data = data;
2120 	ImageInfo->file.list[count].size = size;
2121 	return count;
2122 }
2123 /* }}} */
2124 
2125 /* {{{ exif_file_sections_realloc
2126  Reallocate a file section returns 0 on success and -1 on failure
2127 */
exif_file_sections_realloc(image_info_type * ImageInfo,int section_index,size_t size)2128 static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size)
2129 {
2130 	void *tmp;
2131 
2132 	/* This is not a malloc/realloc check. It is a plausibility check for the
2133 	 * function parameters (requirements engineering).
2134 	 */
2135 	if (section_index >= ImageInfo->file.count) {
2136 		EXIF_ERRLOG_FSREALLOC(ImageInfo)
2137 		return -1;
2138 	}
2139 	tmp = safe_erealloc(ImageInfo->file.list[section_index].data, 1, size, 0);
2140 	ImageInfo->file.list[section_index].data = tmp;
2141 	ImageInfo->file.list[section_index].size = size;
2142 	return 0;
2143 }
2144 /* }}} */
2145 
2146 /* {{{ exif_file_section_free
2147    Discard all file_sections in ImageInfo
2148 */
exif_file_sections_free(image_info_type * ImageInfo)2149 static bool exif_file_sections_free(image_info_type *ImageInfo)
2150 {
2151 	int i;
2152 
2153 	if (ImageInfo->file.count) {
2154 		for (i=0; i<ImageInfo->file.count; i++) {
2155 			EFREE_IF(ImageInfo->file.list[i].data);
2156 		}
2157 	}
2158 	EFREE_IF(ImageInfo->file.list);
2159 	ImageInfo->file.count = 0;
2160 	return true;
2161 }
2162 /* }}} */
2163 
exif_alloc_image_info_data(image_info_list * info_list)2164 static image_info_data *exif_alloc_image_info_data(image_info_list *info_list) {
2165 	if (info_list->count == info_list->alloc_count) {
2166 		int new_alloc_count = info_list->alloc_count ? info_list->alloc_count * 2 : 1;
2167 		info_list->list = safe_erealloc(
2168 			info_list->list, new_alloc_count, sizeof(image_info_data), 0);
2169 		info_list->alloc_count = new_alloc_count;
2170 	}
2171 	return &info_list->list[info_list->count++];
2172 }
2173 
2174 /* {{{ exif_iif_add_value
2175  Add a value to image_info
2176 */
exif_iif_add_value(image_info_type * image_info,int section_index,char * name,int tag,int format,int length,void * value,size_t value_len,int motorola_intel)2177 static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, size_t value_len, int motorola_intel)
2178 {
2179 	size_t idex;
2180 	void *vptr, *vptr_end;
2181 	image_info_value *info_value;
2182 	image_info_data  *info_data;
2183 
2184 	if (length < 0) {
2185 		return;
2186 	}
2187 
2188 	info_data = exif_alloc_image_info_data(&image_info->info_list[section_index]);
2189 	memset(info_data, 0, sizeof(image_info_data));
2190 	info_data->tag    = tag;
2191 	info_data->format = format;
2192 	info_data->length = length;
2193 	info_data->name   = estrdup(name);
2194 	info_value        = &info_data->value;
2195 
2196 	switch (format) {
2197 		case TAG_FMT_STRING:
2198 			if (length > value_len) {
2199 				exif_error_docref("exif_iif_add_value" EXIFERR_CC, image_info, E_WARNING, "length > value_len: %d > %zu", length, value_len);
2200 				value = NULL;
2201 			}
2202 			if (value) {
2203 				length = (int)php_strnlen(value, length);
2204 				info_value->s = estrndup(value, length);
2205 				info_data->length = length;
2206 			} else {
2207 				info_data->length = 0;
2208 				info_value->s = estrdup("");
2209 			}
2210 			break;
2211 
2212 		default:
2213 			/* Standard says more types possible but skip them...
2214 			 * but allow users to handle data if they know how to
2215 			 * So not return but use type UNDEFINED
2216 			 * return;
2217 			 */
2218 			info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */
2219 			ZEND_FALLTHROUGH;
2220 		case TAG_FMT_SBYTE:
2221 		case TAG_FMT_BYTE:
2222 		/* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 */
2223 			if (!length) {
2224 				break;
2225 			}
2226 			ZEND_FALLTHROUGH;
2227 		case TAG_FMT_UNDEFINED:
2228 			if (length > value_len) {
2229 				exif_error_docref("exif_iif_add_value" EXIFERR_CC, image_info, E_WARNING, "length > value_len: %d > %zu", length, value_len);
2230 				value = NULL;
2231 			}
2232 			if (value) {
2233 				if (tag == TAG_MAKER_NOTE) {
2234 					length = (int) php_strnlen(value, length);
2235 				}
2236 
2237 				/* do not recompute length here */
2238 				info_value->s = estrndup(value, length);
2239 				info_data->length = length;
2240 			} else {
2241 				info_data->length = 0;
2242 				info_value->s = estrdup("");
2243 			}
2244 			break;
2245 
2246 		case TAG_FMT_USHORT:
2247 		case TAG_FMT_ULONG:
2248 		case TAG_FMT_URATIONAL:
2249 		case TAG_FMT_SSHORT:
2250 		case TAG_FMT_SLONG:
2251 		case TAG_FMT_SRATIONAL:
2252 		case TAG_FMT_SINGLE:
2253 		case TAG_FMT_DOUBLE:
2254 			if (length==0) {
2255 				break;
2256 			} else
2257 			if (length>1) {
2258 				info_value->list = safe_emalloc(length, sizeof(image_info_value), 0);
2259 			} else {
2260 				info_value = &info_data->value;
2261 			}
2262 			vptr_end = (char *) value + value_len;
2263 			for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) {
2264 				if ((char *) vptr_end - (char *) vptr < php_tiff_bytes_per_format[format]) {
2265 					exif_error_docref("exif_iif_add_value" EXIFERR_CC, image_info, E_WARNING, "Value too short");
2266 					break;
2267 				}
2268 				if (length>1) {
2269 					info_value = &info_data->value.list[idex];
2270 				}
2271 				switch (format) {
2272 					case TAG_FMT_USHORT:
2273 						info_value->u = php_ifd_get16u(vptr, motorola_intel);
2274 						break;
2275 
2276 					case TAG_FMT_ULONG:
2277 						info_value->u = php_ifd_get32u(vptr, motorola_intel);
2278 						break;
2279 
2280 					case TAG_FMT_URATIONAL:
2281 						info_value->ur.num = php_ifd_get32u(vptr, motorola_intel);
2282 						info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
2283 						break;
2284 
2285 					case TAG_FMT_SSHORT:
2286 						info_value->i = php_ifd_get16s(vptr, motorola_intel);
2287 						break;
2288 
2289 					case TAG_FMT_SLONG:
2290 						info_value->i = php_ifd_get32s(vptr, motorola_intel);
2291 						break;
2292 
2293 					case TAG_FMT_SRATIONAL:
2294 						info_value->sr.num = php_ifd_get32u(vptr, motorola_intel);
2295 						info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);
2296 						break;
2297 
2298 					case TAG_FMT_SINGLE:
2299 #ifdef EXIF_DEBUG
2300 						php_error_docref(NULL, E_WARNING, "Found value of type single");
2301 #endif
2302 						info_value->f = php_ifd_get_float(value);
2303 						break;
2304 					case TAG_FMT_DOUBLE:
2305 #ifdef EXIF_DEBUG
2306 						php_error_docref(NULL, E_WARNING, "Found value of type double");
2307 #endif
2308 						info_value->d = php_ifd_get_double(value);
2309 						break;
2310 				}
2311 			}
2312 	}
2313 	image_info->sections_found |= 1<<section_index;
2314 }
2315 /* }}} */
2316 
2317 /* {{{ exif_iif_add_tag
2318  Add a tag from IFD to image_info
2319 */
exif_iif_add_tag(image_info_type * image_info,int section_index,char * name,int tag,int format,size_t length,void * value,size_t value_len)2320 static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value, size_t value_len)
2321 {
2322 	exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, value_len, image_info->motorola_intel);
2323 }
2324 /* }}} */
2325 
2326 /* {{{ exif_iif_add_int
2327  Add an int value to image_info
2328 */
exif_iif_add_int(image_info_type * image_info,int section_index,char * name,int value)2329 static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value)
2330 {
2331 	image_info_data *info_data = exif_alloc_image_info_data(&image_info->info_list[section_index]);
2332 	info_data->tag    = TAG_NONE;
2333 	info_data->format = TAG_FMT_SLONG;
2334 	info_data->length = 1;
2335 	info_data->name   = estrdup(name);
2336 	info_data->value.i = value;
2337 	image_info->sections_found |= 1<<section_index;
2338 }
2339 /* }}} */
2340 
2341 /* {{{ exif_iif_add_str
2342  Add a string value to image_info MUST BE NUL TERMINATED
2343 */
exif_iif_add_str(image_info_type * image_info,int section_index,char * name,char * value)2344 static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value)
2345 {
2346 	if (value) {
2347 		image_info_data *info_data =
2348 			exif_alloc_image_info_data(&image_info->info_list[section_index]);
2349 		info_data->tag    = TAG_NONE;
2350 		info_data->format = TAG_FMT_STRING;
2351 		info_data->length = 1;
2352 		info_data->name   = estrdup(name);
2353 		info_data->value.s = estrdup(value);
2354 		image_info->sections_found |= 1<<section_index;
2355 	}
2356 }
2357 /* }}} */
2358 
2359 /* {{{ exif_iif_add_fmt
2360  Add a format string value to image_info MUST BE NUL TERMINATED
2361 */
exif_iif_add_fmt(image_info_type * image_info,int section_index,char * name,char * value,...)2362 static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name, char *value, ...)
2363 {
2364 	char             *tmp;
2365 	va_list 		 arglist;
2366 
2367 	va_start(arglist, value);
2368 	if (value) {
2369 		vspprintf(&tmp, 0, value, arglist);
2370 		exif_iif_add_str(image_info, section_index, name, tmp);
2371 		efree(tmp);
2372 	}
2373 	va_end(arglist);
2374 }
2375 /* }}} */
2376 
2377 /* {{{ exif_iif_add_str
2378  Add a string value to image_info MUST BE NUL TERMINATED
2379 */
exif_iif_add_buffer(image_info_type * image_info,int section_index,char * name,int length,char * value)2380 static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value)
2381 {
2382 	if (value) {
2383 		image_info_data *info_data =
2384 			exif_alloc_image_info_data(&image_info->info_list[section_index]);
2385 		info_data->tag    = TAG_NONE;
2386 		info_data->format = TAG_FMT_UNDEFINED;
2387 		info_data->length = length;
2388 		info_data->name   = estrdup(name);
2389 		info_data->value.s = safe_emalloc(length, 1, 1);
2390 		memcpy(info_data->value.s, value, length);
2391 		info_data->value.s[length] = 0;
2392 		image_info->sections_found |= 1<<section_index;
2393 	}
2394 }
2395 /* }}} */
2396 
2397 /* {{{ exif_iif_free
2398  Free memory allocated for image_info
2399 */
exif_iif_free(image_info_type * image_info,int section_index)2400 static void exif_iif_free(image_info_type *image_info, int section_index) {
2401 	int  i;
2402 	void *f; /* faster */
2403 
2404 	if (image_info->info_list[section_index].count) {
2405 		for (i=0; i < image_info->info_list[section_index].count; i++) {
2406 			if ((f=image_info->info_list[section_index].list[i].name) != NULL) {
2407 				efree(f);
2408 			}
2409 			switch(image_info->info_list[section_index].list[i].format) {
2410 				case TAG_FMT_UNDEFINED:
2411 				case TAG_FMT_STRING:
2412 				case TAG_FMT_SBYTE:
2413 				case TAG_FMT_BYTE:
2414 				default:
2415 					if ((f=image_info->info_list[section_index].list[i].value.s) != NULL) {
2416 						efree(f);
2417 					}
2418 					break;
2419 
2420 				case TAG_FMT_USHORT:
2421 				case TAG_FMT_ULONG:
2422 				case TAG_FMT_URATIONAL:
2423 				case TAG_FMT_SSHORT:
2424 				case TAG_FMT_SLONG:
2425 				case TAG_FMT_SRATIONAL:
2426 				case TAG_FMT_SINGLE:
2427 				case TAG_FMT_DOUBLE:
2428 					/* nothing to do here */
2429 					if (image_info->info_list[section_index].list[i].length > 1) {
2430 						if ((f=image_info->info_list[section_index].list[i].value.list) != NULL) {
2431 							efree(f);
2432 						}
2433 					}
2434 					break;
2435 			}
2436 		}
2437 	}
2438 	EFREE_IF(image_info->info_list[section_index].list);
2439 }
2440 /* }}} */
2441 
2442 /* {{{ add_assoc_image_info
2443  * Add image_info to associative array value. */
add_assoc_image_info(zval * value,int sub_array,image_info_type * image_info,int section_index)2444 static void add_assoc_image_info(zval *value, int sub_array, image_info_type *image_info, int section_index)
2445 {
2446 	char buffer[64], uname[64];
2447 	int idx = 0, unknown = 0;
2448 
2449 	if (!image_info->info_list[section_index].count) {
2450 		return;
2451 	}
2452 
2453 	zval tmpi;
2454 	if (sub_array) {
2455 		array_init(&tmpi);
2456 	} else {
2457 		ZVAL_COPY_VALUE(&tmpi, value);
2458 	}
2459 
2460 	for (int i = 0; i<image_info->info_list[section_index].count; i++) {
2461 		image_info_data *info_data = &image_info->info_list[section_index].list[i];
2462 		image_info_value *info_value = &info_data->value;
2463 		const char *name = info_data->name;
2464 		if (!name) {
2465 			snprintf(uname, sizeof(uname), "%d", unknown++);
2466 			name = uname;
2467 		}
2468 
2469 		if (info_data->length == 0) {
2470 			add_assoc_null(&tmpi, name);
2471 		} else {
2472 			switch (info_data->format) {
2473 				default:
2474 					/* Standard says more types possible but skip them...
2475 					 * but allow users to handle data if they know how to
2476 					 * So not return but use type UNDEFINED
2477 					 * return;
2478 					 */
2479 				case TAG_FMT_BYTE:
2480 				case TAG_FMT_SBYTE:
2481 				case TAG_FMT_UNDEFINED:
2482 					if (!info_value->s) {
2483 						add_assoc_stringl(&tmpi, name, "", 0);
2484 					} else {
2485 						add_assoc_stringl(&tmpi, name, info_value->s, info_data->length);
2486 					}
2487 					break;
2488 
2489 				case TAG_FMT_STRING: {
2490 					const char *val = info_value->s ? info_value->s : "";
2491 					if (section_index==SECTION_COMMENT) {
2492 						add_index_string(&tmpi, idx++, val);
2493 					} else {
2494 						add_assoc_string(&tmpi, name, val);
2495 					}
2496 					break;
2497 				}
2498 
2499 				case TAG_FMT_URATIONAL:
2500 				case TAG_FMT_SRATIONAL:
2501 				case TAG_FMT_USHORT:
2502 				case TAG_FMT_SSHORT:
2503 				case TAG_FMT_SINGLE:
2504 				case TAG_FMT_DOUBLE:
2505 				case TAG_FMT_ULONG:
2506 				case TAG_FMT_SLONG: {
2507 					/* now the rest, first see if it becomes an array */
2508 					zval array;
2509 					int l = info_data->length;
2510 					if (l > 1) {
2511 						array_init(&array);
2512 					}
2513 					for (int ap = 0; ap < l; ap++) {
2514 						if (l>1) {
2515 							info_value = &info_data->value.list[ap];
2516 						}
2517 						switch (info_data->format) {
2518 							case TAG_FMT_BYTE:
2519 								if (l>1) {
2520 									info_value = &info_data->value;
2521 									for (int b = 0; b < l; b++) {
2522 										add_index_long(&array, b, (int)(info_value->s[b]));
2523 									}
2524 									break;
2525 								}
2526 								ZEND_FALLTHROUGH;
2527 							case TAG_FMT_USHORT:
2528 							case TAG_FMT_ULONG:
2529 								if (l==1) {
2530 									add_assoc_long(&tmpi, name, (int)info_value->u);
2531 								} else {
2532 									add_index_long(&array, ap, (int)info_value->u);
2533 								}
2534 								break;
2535 
2536 							case TAG_FMT_URATIONAL:
2537 								snprintf(buffer, sizeof(buffer), "%u/%u", info_value->ur.num, info_value->ur.den);
2538 								if (l==1) {
2539 									add_assoc_string(&tmpi, name, buffer);
2540 								} else {
2541 									add_index_string(&array, ap, buffer);
2542 								}
2543 								break;
2544 
2545 							case TAG_FMT_SBYTE:
2546 								if (l>1) {
2547 									info_value = &info_data->value;
2548 									for (int b = 0; b < l; b++) {
2549 										add_index_long(&array, ap, (int)info_value->s[b]);
2550 									}
2551 									break;
2552 								}
2553 								ZEND_FALLTHROUGH;
2554 							case TAG_FMT_SSHORT:
2555 							case TAG_FMT_SLONG:
2556 								if (l==1) {
2557 									add_assoc_long(&tmpi, name, info_value->i);
2558 								} else {
2559 									add_index_long(&array, ap, info_value->i);
2560 								}
2561 								break;
2562 
2563 							case TAG_FMT_SRATIONAL:
2564 								snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den);
2565 								if (l==1) {
2566 									add_assoc_string(&tmpi, name, buffer);
2567 								} else {
2568 									add_index_string(&array, ap, buffer);
2569 								}
2570 								break;
2571 
2572 							case TAG_FMT_SINGLE:
2573 								if (l==1) {
2574 									add_assoc_double(&tmpi, name, info_value->f);
2575 								} else {
2576 									add_index_double(&array, ap, info_value->f);
2577 								}
2578 								break;
2579 
2580 							case TAG_FMT_DOUBLE:
2581 								if (l==1) {
2582 									add_assoc_double(&tmpi, name, info_value->d);
2583 								} else {
2584 									add_index_double(&array, ap, info_value->d);
2585 								}
2586 								break;
2587 						}
2588 					}
2589 					if (l > 1) {
2590 						add_assoc_zval(&tmpi, name, &array);
2591 					}
2592 					break;
2593 				}
2594 			}
2595 		}
2596 	}
2597 	if (sub_array) {
2598 		add_assoc_zval(value, exif_get_sectionname(section_index), &tmpi);
2599 	}
2600 }
2601 /* }}} */
2602 
2603 /* {{{ Markers
2604    JPEG markers consist of one or more 0xFF bytes, followed by a marker
2605    code byte (which is not an FF).  Here are the marker codes of interest
2606    in this program.  (See jdmarker.c for a more complete list.)
2607 */
2608 
2609 #define M_TEM   0x01    /* temp for arithmetic coding              */
2610 #define M_RES   0x02    /* reserved                                */
2611 #define M_SOF0  0xC0    /* Start Of Frame N                        */
2612 #define M_SOF1  0xC1    /* N indicates which compression process   */
2613 #define M_SOF2  0xC2    /* Only SOF0-SOF2 are now in common use    */
2614 #define M_SOF3  0xC3
2615 #define M_DHT   0xC4
2616 #define M_SOF5  0xC5    /* NB: codes C4 and CC are NOT SOF markers */
2617 #define M_SOF6  0xC6
2618 #define M_SOF7  0xC7
2619 #define M_JPEG  0x08    /* reserved for extensions                 */
2620 #define M_SOF9  0xC9
2621 #define M_SOF10 0xCA
2622 #define M_SOF11 0xCB
2623 #define M_DAC   0xCC    /* arithmetic table                         */
2624 #define M_SOF13 0xCD
2625 #define M_SOF14 0xCE
2626 #define M_SOF15 0xCF
2627 #define M_RST0  0xD0    /* restart segment                          */
2628 #define M_RST1  0xD1
2629 #define M_RST2  0xD2
2630 #define M_RST3  0xD3
2631 #define M_RST4  0xD4
2632 #define M_RST5  0xD5
2633 #define M_RST6  0xD6
2634 #define M_RST7  0xD7
2635 #define M_SOI   0xD8    /* Start Of Image (beginning of datastream) */
2636 #define M_EOI   0xD9    /* End Of Image (end of datastream)         */
2637 #define M_SOS   0xDA    /* Start Of Scan (begins compressed data)   */
2638 #define M_DQT   0xDB
2639 #define M_DNL   0xDC
2640 #define M_DRI   0xDD
2641 #define M_DHP   0xDE
2642 #define M_EXP   0xDF
2643 #define M_APP0  0xE0    /* JPEG: 'JFIFF' AND (additional 'JFXX')    */
2644 #define M_EXIF  0xE1    /* Exif Attribute Information               */
2645 #define M_APP2  0xE2    /* Flash Pix Extension Data?                */
2646 #define M_APP3  0xE3
2647 #define M_APP4  0xE4
2648 #define M_APP5  0xE5
2649 #define M_APP6  0xE6
2650 #define M_APP7  0xE7
2651 #define M_APP8  0xE8
2652 #define M_APP9  0xE9
2653 #define M_APP10 0xEA
2654 #define M_APP11 0xEB
2655 #define M_APP12 0xEC
2656 #define M_APP13 0xED    /* IPTC International Press Telecommunications Council */
2657 #define M_APP14 0xEE    /* Software, Copyright?                     */
2658 #define M_APP15 0xEF
2659 #define M_JPG0  0xF0
2660 #define M_JPG1  0xF1
2661 #define M_JPG2  0xF2
2662 #define M_JPG3  0xF3
2663 #define M_JPG4  0xF4
2664 #define M_JPG5  0xF5
2665 #define M_JPG6  0xF6
2666 #define M_JPG7  0xF7
2667 #define M_JPG8  0xF8
2668 #define M_JPG9  0xF9
2669 #define M_JPG10 0xFA
2670 #define M_JPG11 0xFB
2671 #define M_JPG12 0xFC
2672 #define M_JPG13 0xFD
2673 #define M_COM   0xFE    /* COMment                                  */
2674 
2675 #define M_PSEUDO 0x123 	/* Extra value.                             */
2676 /* }}} */
2677 
2678 /* {{{ exif_process_COM
2679    Process a COM marker.
2680    We want to print out the marker contents as legible text;
2681    we must guard against random junk and varying newline representations.
2682 */
exif_process_COM(image_info_type * image_info,char * value,size_t length)2683 static void exif_process_COM (image_info_type *image_info, char *value, size_t length)
2684 {
2685 	exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2, length-2);
2686 }
2687 /* }}} */
2688 
2689 /* {{{ exif_process_SOFn
2690  * Process a SOFn marker.  This is useful for the image dimensions */
exif_process_SOFn(uchar * Data,int marker,jpeg_sof_info * result)2691 static void exif_process_SOFn (uchar *Data, int marker, jpeg_sof_info *result)
2692 {
2693 	/* 0xFF SOSn SectLen(2) Bits(1) Height(2) Width(2) Channels(1)  3*Channels (1)  */
2694 	result->bits_per_sample = Data[2];
2695 	result->height          = php_jpg_get16(Data+3);
2696 	result->width           = php_jpg_get16(Data+5);
2697 	result->num_components  = Data[7];
2698 }
2699 /* }}} */
2700 
2701 /* forward declarations */
2702 static bool exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, const exif_offset_info *info, size_t displacement, int section_index, int tag);
2703 static bool exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, const exif_offset_info *info, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table);
2704 static bool exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index);
2705 
2706 /* {{{ exif_get_markername
2707 	Get name of marker */
2708 #ifdef EXIF_DEBUG
exif_get_markername(int marker)2709 static char * exif_get_markername(int marker)
2710 {
2711 	switch(marker) {
2712 		case 0xC0: return "SOF0";
2713 		case 0xC1: return "SOF1";
2714 		case 0xC2: return "SOF2";
2715 		case 0xC3: return "SOF3";
2716 		case 0xC4: return "DHT";
2717 		case 0xC5: return "SOF5";
2718 		case 0xC6: return "SOF6";
2719 		case 0xC7: return "SOF7";
2720 		case 0xC9: return "SOF9";
2721 		case 0xCA: return "SOF10";
2722 		case 0xCB: return "SOF11";
2723 		case 0xCD: return "SOF13";
2724 		case 0xCE: return "SOF14";
2725 		case 0xCF: return "SOF15";
2726 		case 0xD8: return "SOI";
2727 		case 0xD9: return "EOI";
2728 		case 0xDA: return "SOS";
2729 		case 0xDB: return "DQT";
2730 		case 0xDC: return "DNL";
2731 		case 0xDD: return "DRI";
2732 		case 0xDE: return "DHP";
2733 		case 0xDF: return "EXP";
2734 		case 0xE0: return "APP0";
2735 		case 0xE1: return "EXIF";
2736 		case 0xE2: return "FPIX";
2737 		case 0xE3: return "APP3";
2738 		case 0xE4: return "APP4";
2739 		case 0xE5: return "APP5";
2740 		case 0xE6: return "APP6";
2741 		case 0xE7: return "APP7";
2742 		case 0xE8: return "APP8";
2743 		case 0xE9: return "APP9";
2744 		case 0xEA: return "APP10";
2745 		case 0xEB: return "APP11";
2746 		case 0xEC: return "APP12";
2747 		case 0xED: return "APP13";
2748 		case 0xEE: return "APP14";
2749 		case 0xEF: return "APP15";
2750 		case 0xF0: return "JPG0";
2751 		case 0xFD: return "JPG13";
2752 		case 0xFE: return "COM";
2753 		case 0x01: return "TEM";
2754 	}
2755 	return "Unknown";
2756 }
2757 #endif
2758 /* }}} */
2759 
2760 /* {{{ Get headername for index or false if not defined */
PHP_FUNCTION(exif_tagname)2761 PHP_FUNCTION(exif_tagname)
2762 {
2763 	zend_long tag;
2764 	char *szTemp;
2765 
2766 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &tag) == FAILURE) {
2767 		RETURN_THROWS();
2768 	}
2769 
2770 	szTemp = exif_get_tagname(tag, tag_table_IFD);
2771 	if (tag < 0 || !szTemp) {
2772 		RETURN_FALSE;
2773 	}
2774 
2775 	RETURN_STRING(szTemp);
2776 }
2777 /* }}} */
2778 
2779 /* {{{ exif_ifd_make_value
2780  * Create a value for an ifd from an info_data pointer */
exif_ifd_make_value(image_info_data * info_data,int motorola_intel)2781 static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel) {
2782 	size_t  byte_count;
2783 	char    *value_ptr, *data_ptr;
2784 	size_t  i;
2785 
2786 	image_info_value  *info_value;
2787 
2788 	byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2789 	value_ptr = safe_emalloc(max(byte_count, 4), 1, 0);
2790 	memset(value_ptr, 0, 4);
2791 	if (!info_data->length) {
2792 		return value_ptr;
2793 	}
2794 	if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING
2795 	  || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))
2796 	) {
2797 		memmove(value_ptr, info_data->value.s, byte_count);
2798 		return value_ptr;
2799 	} else if (info_data->format == TAG_FMT_BYTE) {
2800 		*value_ptr = info_data->value.u;
2801 		return value_ptr;
2802 	} else if (info_data->format == TAG_FMT_SBYTE) {
2803 		*value_ptr = info_data->value.i;
2804 		return value_ptr;
2805 	} else {
2806 		data_ptr = value_ptr;
2807 		for(i=0; i<info_data->length; i++) {
2808 			if (info_data->length==1) {
2809 				info_value = &info_data->value;
2810 			} else {
2811 				info_value = &info_data->value.list[i];
2812 			}
2813 			switch(info_data->format) {
2814 				case TAG_FMT_USHORT:
2815 					php_ifd_set16u(data_ptr, info_value->u, motorola_intel);
2816 					data_ptr += 2;
2817 					break;
2818 				case TAG_FMT_ULONG:
2819 					php_ifd_set32u(data_ptr, info_value->u, motorola_intel);
2820 					data_ptr += 4;
2821 					break;
2822 				case TAG_FMT_SSHORT:
2823 					php_ifd_set16u(data_ptr, info_value->i, motorola_intel);
2824 					data_ptr += 2;
2825 					break;
2826 				case TAG_FMT_SLONG:
2827 					php_ifd_set32u(data_ptr, info_value->i, motorola_intel);
2828 					data_ptr += 4;
2829 					break;
2830 				case TAG_FMT_URATIONAL:
2831 					php_ifd_set32u(data_ptr,   info_value->sr.num, motorola_intel);
2832 					php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel);
2833 					data_ptr += 8;
2834 					break;
2835 				case TAG_FMT_SRATIONAL:
2836 					php_ifd_set32u(data_ptr,   info_value->ur.num, motorola_intel);
2837 					php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel);
2838 					data_ptr += 8;
2839 					break;
2840 				case TAG_FMT_SINGLE:
2841 					memmove(data_ptr, &info_value->f, 4);
2842 					data_ptr += 4;
2843 					break;
2844 				case TAG_FMT_DOUBLE:
2845 					memmove(data_ptr, &info_value->d, 8);
2846 					data_ptr += 8;
2847 					break;
2848 			}
2849 		}
2850 	}
2851 	return value_ptr;
2852 }
2853 /* }}} */
2854 
2855 /* {{{ exif_thumbnail_build
2856  * Check and build thumbnail */
exif_thumbnail_build(image_info_type * ImageInfo)2857 static void exif_thumbnail_build(image_info_type *ImageInfo) {
2858 	size_t            new_size, new_move, new_value;
2859 	char              *new_data;
2860 	void              *value_ptr;
2861 	int               i, byte_count;
2862 	image_info_list   *info_list;
2863 	image_info_data   *info_data;
2864 
2865 	if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) {
2866 		return; /* ignore this call */
2867 	}
2868 #ifdef EXIF_DEBUG
2869 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: filetype = %d", ImageInfo->Thumbnail.filetype);
2870 #endif
2871 	switch(ImageInfo->Thumbnail.filetype) {
2872 		default:
2873 		case IMAGE_FILETYPE_JPEG:
2874 			/* done */
2875 			break;
2876 		case IMAGE_FILETYPE_TIFF_II:
2877 		case IMAGE_FILETYPE_TIFF_MM:
2878 			info_list = &ImageInfo->info_list[SECTION_THUMBNAIL];
2879 			new_size  = 8 + 2 + info_list->count * 12 + 4;
2880 #ifdef EXIF_DEBUG
2881 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size of signature + directory(%d): 0x%02X", info_list->count, new_size);
2882 #endif
2883 			new_value= new_size; /* offset for ifd values outside ifd directory */
2884 			for (i=0; i<info_list->count; i++) {
2885 				info_data  = &info_list->list[i];
2886 				byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2887 				if (byte_count > 4) {
2888 					new_size += byte_count;
2889 				}
2890 			}
2891 			new_move = new_size;
2892 			new_data = safe_erealloc(ImageInfo->Thumbnail.data, 1, ImageInfo->Thumbnail.size, new_size);
2893 			ImageInfo->Thumbnail.data = new_data;
2894 			memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
2895 			ImageInfo->Thumbnail.size += new_size;
2896 			/* fill in data */
2897 			if (ImageInfo->motorola_intel) {
2898 				memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8);
2899 			} else {
2900 				memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8);
2901 			}
2902 			new_data += 8;
2903 			php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel);
2904 			new_data += 2;
2905 			for (i=0; i<info_list->count; i++) {
2906 				info_data  = &info_list->list[i];
2907 				byte_count = php_tiff_bytes_per_format[info_data->format] * info_data->length;
2908 #ifdef EXIF_DEBUG
2909 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process tag(x%04X=%s): %s%s (%d bytes)", info_data->tag, exif_get_tagname_debug(info_data->tag, tag_table_IFD), (info_data->length>1)&&info_data->format!=TAG_FMT_UNDEFINED&&info_data->format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(info_data->format), byte_count);
2910 #endif
2911 				if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) {
2912 					php_ifd_set16u(new_data + 0, info_data->tag,    ImageInfo->motorola_intel);
2913 					php_ifd_set16u(new_data + 2, TAG_FMT_ULONG,     ImageInfo->motorola_intel);
2914 					php_ifd_set32u(new_data + 4, 1,                 ImageInfo->motorola_intel);
2915 					php_ifd_set32u(new_data + 8, new_move,          ImageInfo->motorola_intel);
2916 				} else {
2917 					php_ifd_set16u(new_data + 0, info_data->tag,    ImageInfo->motorola_intel);
2918 					php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel);
2919 					php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel);
2920 					value_ptr  = exif_ifd_make_value(info_data, ImageInfo->motorola_intel);
2921 					if (byte_count <= 4) {
2922 						memmove(new_data+8, value_ptr, 4);
2923 					} else {
2924 						php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel);
2925 #ifdef EXIF_DEBUG
2926 						exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: writing with value offset: 0x%04X + 0x%02X", new_value, byte_count);
2927 #endif
2928 						memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count);
2929 						new_value += byte_count;
2930 					}
2931 					efree(value_ptr);
2932 				}
2933 				new_data += 12;
2934 			}
2935 			memset(new_data, 0, 4); /* next ifd pointer */
2936 #ifdef EXIF_DEBUG
2937 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: created");
2938 #endif
2939 			break;
2940 	}
2941 }
2942 /* }}} */
2943 
2944 /* {{{ exif_thumbnail_extract
2945  * Grab the thumbnail, corrected */
exif_thumbnail_extract(image_info_type * ImageInfo,const exif_offset_info * info)2946 static void exif_thumbnail_extract(image_info_type *ImageInfo, const exif_offset_info *info) {
2947 	if (ImageInfo->Thumbnail.data) {
2948 		exif_error_docref("exif_read_data#error_mult_thumb" EXIFERR_CC, ImageInfo, E_WARNING, "Multiple possible thumbnails");
2949 		return; /* Should not happen */
2950 	}
2951 	if (!ImageInfo->read_thumbnail)	{
2952 		return; /* ignore this call */
2953 	}
2954 	/* according to exif2.1, the thumbnail is not supposed to be greater than 64K */
2955 	if (ImageInfo->Thumbnail.size >= 65536
2956 	 || ImageInfo->Thumbnail.size <= 0
2957 	 || ImageInfo->Thumbnail.offset <= 0
2958 	) {
2959 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Illegal thumbnail size/offset");
2960 		return;
2961 	}
2962 	/* Check to make sure we are not going to go past the ExifLength */
2963 	char *thumbnail = exif_offset_info_try_get(
2964 		info, ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
2965 	if (!thumbnail) {
2966 		EXIF_ERRLOG_THUMBEOF(ImageInfo)
2967 		return;
2968 	}
2969 	ImageInfo->Thumbnail.data = estrndup(thumbnail, ImageInfo->Thumbnail.size);
2970 	exif_thumbnail_build(ImageInfo);
2971 }
2972 /* }}} */
2973 
2974 /* {{{ exif_process_undefined
2975  * Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */
exif_process_undefined(char ** result,char * value,size_t byte_count)2976 static int exif_process_undefined(char **result, char *value, size_t byte_count) {
2977 	/* we cannot use strlcpy - here the problem is that we have to copy NUL
2978 	 * chars up to byte_count, we also have to add a single NUL character to
2979 	 * force end of string.
2980 	 * estrndup does not return length
2981 	 */
2982 	if (byte_count) {
2983 		(*result) = estrndup(value, byte_count); /* NULL @ byte_count!!! */
2984 		return byte_count+1;
2985 	}
2986 	return 0;
2987 }
2988 /* }}} */
2989 
2990 /* {{{ exif_process_string_raw
2991  * Copy a string in Exif header to a character string returns length of allocated buffer if any. */
exif_process_string_raw(char ** result,char * value,size_t byte_count)2992 static int exif_process_string_raw(char **result, char *value, size_t byte_count) {
2993 	/* we cannot use strlcpy - here the problem is that we have to copy NUL
2994 	 * chars up to byte_count, we also have to add a single NUL character to
2995 	 * force end of string.
2996 	 */
2997 	if (byte_count) {
2998 		(*result) = safe_emalloc(byte_count, 1, 1);
2999 		memcpy(*result, value, byte_count);
3000 		(*result)[byte_count] = '\0';
3001 		return byte_count+1;
3002 	}
3003 	return 0;
3004 }
3005 /* }}} */
3006 
3007 /* {{{ exif_process_string
3008  * Copy a string in Exif header to a character string and return length of allocated buffer if any.
3009  * In contrast to exif_process_string this function does always return a string buffer */
exif_process_string(char ** result,char * value,size_t byte_count)3010 static int exif_process_string(char **result, char *value, size_t byte_count) {
3011 	/* we cannot use strlcpy - here the problem is that we cannot use strlen to
3012 	 * determine length of string and we cannot use strlcpy with len=byte_count+1
3013 	 * because then we might get into an EXCEPTION if we exceed an allocated
3014 	 * memory page...so we use php_strnlen in conjunction with memcpy and add the NUL
3015 	 * char.
3016 	 * estrdup would sometimes allocate more memory and does not return length
3017 	 */
3018 	if ((byte_count=php_strnlen(value, byte_count)) > 0) {
3019 		return exif_process_undefined(result, value, byte_count);
3020 	}
3021 	(*result) = estrndup("", 1); /* force empty string */
3022 	return byte_count+1;
3023 }
3024 /* }}} */
3025 
3026 /* {{{ exif_process_user_comment
3027  * Process UserComment in IFD. */
exif_process_user_comment(image_info_type * ImageInfo,char ** pszInfoPtr,char ** pszEncoding,char * szValuePtr,int ByteCount)3028 static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount)
3029 {
3030 	int   a;
3031 	char  *decode;
3032 	size_t len;
3033 
3034 	*pszEncoding = NULL;
3035 	/* Copy the comment */
3036 	if (ByteCount>=8) {
3037 		const zend_encoding *from, *to;
3038 		if (!memcmp(szValuePtr, "UNICODE\0", 8)) {
3039 			*pszEncoding = estrdup((const char*)szValuePtr);
3040 			szValuePtr = szValuePtr+8;
3041 			ByteCount -= 8;
3042 			/* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16)
3043 			 * since we have no encoding support for the BOM yet we skip that.
3044 			 */
3045 			if (ByteCount >=2 && !memcmp(szValuePtr, "\xFE\xFF", 2)) {
3046 				decode = "UCS-2BE";
3047 				szValuePtr = szValuePtr+2;
3048 				ByteCount -= 2;
3049 			} else if (ByteCount >=2 && !memcmp(szValuePtr, "\xFF\xFE", 2)) {
3050 				decode = "UCS-2LE";
3051 				szValuePtr = szValuePtr+2;
3052 				ByteCount -= 2;
3053 			} else if (ImageInfo->motorola_intel) {
3054 				decode = ImageInfo->decode_unicode_be;
3055 			} else {
3056 				decode = ImageInfo->decode_unicode_le;
3057 			}
3058 			to = zend_multibyte_fetch_encoding(ImageInfo->encode_unicode);
3059 			from = zend_multibyte_fetch_encoding(decode);
3060 			/* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
3061 			if (!to || !from || zend_multibyte_encoding_converter(
3062 					(unsigned char**)pszInfoPtr,
3063 					&len,
3064 					(unsigned char*)szValuePtr,
3065 					ByteCount,
3066 					to,
3067 					from) == (size_t)-1) {
3068 				len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);
3069 			}
3070 			return len;
3071 		} else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) {
3072 			*pszEncoding = estrdup((const char*)szValuePtr);
3073 			szValuePtr = szValuePtr+8;
3074 			ByteCount -= 8;
3075 		} else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) {
3076 			/* JIS should be translated to MB or we leave it to the user - leave it to the user */
3077 			*pszEncoding = estrdup((const char*)szValuePtr);
3078 			szValuePtr = szValuePtr+8;
3079 			ByteCount -= 8;
3080 			/* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
3081 			to = zend_multibyte_fetch_encoding(ImageInfo->encode_jis);
3082 			from = zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le);
3083 			if (!to || !from || zend_multibyte_encoding_converter(
3084 					(unsigned char**)pszInfoPtr,
3085 					&len,
3086 					(unsigned char*)szValuePtr,
3087 					ByteCount,
3088 					to,
3089 					from) == (size_t)-1) {
3090 				len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount);
3091 			}
3092 			return len;
3093 		} else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) {
3094 			/* 8 NULL means undefined and should be ASCII... */
3095 			*pszEncoding = estrdup("UNDEFINED");
3096 			szValuePtr = szValuePtr+8;
3097 			ByteCount -= 8;
3098 		}
3099 	}
3100 
3101 	/* Olympus has this padded with trailing spaces.  Remove these first. */
3102 	if (ByteCount>0) {
3103 		for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) {
3104 			(szValuePtr)[a] = '\0';
3105 		}
3106 	}
3107 
3108 	/* normal text without encoding */
3109 	exif_process_string(pszInfoPtr, szValuePtr, ByteCount);
3110 	return strlen(*pszInfoPtr);
3111 }
3112 /* }}} */
3113 
3114 /* {{{ exif_process_unicode
3115  * Process unicode field in IFD. */
exif_process_unicode(image_info_type * ImageInfo,xp_field_type * xp_field,int tag,char * szValuePtr,int ByteCount)3116 static int exif_process_unicode(image_info_type *ImageInfo, xp_field_type *xp_field, int tag, char *szValuePtr, int ByteCount)
3117 {
3118 	xp_field->tag = tag;
3119 	xp_field->value = NULL;
3120 	/* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX   */
3121 	if (zend_multibyte_encoding_converter(
3122 			(unsigned char**)&xp_field->value,
3123 			&xp_field->size,
3124 			(unsigned char*)szValuePtr,
3125 			ByteCount,
3126 			zend_multibyte_fetch_encoding(ImageInfo->encode_unicode),
3127 			zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_unicode_be : ImageInfo->decode_unicode_le)
3128 			) == (size_t)-1) {
3129 		xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount);
3130 	}
3131 	return xp_field->size;
3132 }
3133 /* }}} */
3134 
3135 /* {{{ exif_process_IFD_in_MAKERNOTE
3136  * Process nested IFDs directories in Maker Note. */
exif_process_IFD_in_MAKERNOTE(image_info_type * ImageInfo,char * value_ptr,int value_len,const exif_offset_info * info,size_t displacement)3137 static bool exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, const exif_offset_info *info, size_t displacement)
3138 {
3139 	size_t i;
3140 	int de, section_index = SECTION_MAKERNOTE;
3141 	int NumDirEntries, old_motorola_intel;
3142 	const maker_note_type *maker_note;
3143 	char *dir_start;
3144 	exif_offset_info new_info;
3145 
3146 	for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {
3147 		if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) {
3148 #ifdef EXIF_DEBUG
3149 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, ImageInfo->make ? strlen(ImageInfo->make) : 0);
3150 #endif
3151 			/* unknown manufacturer, not an error, use it as a string */
3152 			return true;
3153 		}
3154 
3155 		maker_note = maker_note_array+i;
3156 
3157 		if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))
3158 			continue;
3159 		if (maker_note->id_string && value_len >= maker_note->id_string_len
3160 				&& strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))
3161 			continue;
3162 		break;
3163 	}
3164 
3165 	if (value_len < 2 || maker_note->offset >= value_len - 1) {
3166 		/* Do not go past the value end */
3167 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset);
3168 		return true;
3169 	}
3170 
3171 	dir_start = value_ptr + maker_note->offset;
3172 
3173 #ifdef EXIF_DEBUG
3174 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (intptr_t)dir_start-(intptr_t)info->offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (intptr_t)dir_start-(intptr_t)info->offset_base+maker_note->offset+displacement));
3175 #endif
3176 
3177 	ImageInfo->sections_found |= FOUND_MAKERNOTE;
3178 
3179 	old_motorola_intel = ImageInfo->motorola_intel;
3180 	switch (maker_note->byte_order) {
3181 		case MN_ORDER_INTEL:
3182 			ImageInfo->motorola_intel = 0;
3183 			break;
3184 		case MN_ORDER_MOTOROLA:
3185 			ImageInfo->motorola_intel = 1;
3186 			break;
3187 		default:
3188 		case MN_ORDER_NORMAL:
3189 			break;
3190 	}
3191 
3192 	NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
3193 
3194 	/* It can be that motorola_intel is wrongly mapped, let's try inverting it */
3195 	if ((2+NumDirEntries*12) > value_len) {
3196 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Potentially invalid endianess, trying again with different endianness before imminent failure.");
3197 
3198 		ImageInfo->motorola_intel = ImageInfo->motorola_intel == 0 ? 1 : 0;
3199 		NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
3200 	}
3201 
3202 	if ((2+NumDirEntries*12) > value_len) {
3203 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len);
3204 		return false;
3205 	}
3206 	if ((dir_start - value_ptr) > value_len - (2+NumDirEntries*12)) {
3207 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 0x%04X > 0x%04X", (dir_start - value_ptr) + (2+NumDirEntries*12), value_len);
3208 		return false;
3209 	}
3210 
3211 	switch (maker_note->offset_mode) {
3212 		case MN_OFFSET_MAKER:
3213 			exif_offset_info_init(&new_info, value_ptr, value_ptr, value_len);
3214 			info = &new_info;
3215 			break;
3216 		default:
3217 		case MN_OFFSET_NORMAL:
3218 			break;
3219 	}
3220 
3221 	for (de=0;de<NumDirEntries;de++) {
3222 		size_t offset = 2 + 12 * de;
3223 		if (!exif_process_IFD_TAG(ImageInfo, dir_start + offset,
3224 								  info, displacement, section_index, 0, maker_note->tag_table)) {
3225 			return false;
3226 		}
3227 	}
3228 	ImageInfo->motorola_intel = old_motorola_intel;
3229 /*	NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/
3230 #ifdef EXIF_DEBUG
3231 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE));
3232 #endif
3233 	return true;
3234 }
3235 /* }}} */
3236 
3237 #define REQUIRE_NON_EMPTY() do { \
3238 	if (byte_count == 0) { \
3239 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Cannot be empty", tag, exif_get_tagname_debug(tag, tag_table)); \
3240 		return false; \
3241 	} \
3242 } while (0)
3243 
3244 
3245 /* {{{ exif_process_IFD_TAG
3246  * Process one of the nested IFDs directories. */
exif_process_IFD_TAG_impl(image_info_type * ImageInfo,char * dir_entry,const exif_offset_info * info,size_t displacement,int section_index,int ReadNextIFD,tag_table_type tag_table)3247 static bool exif_process_IFD_TAG_impl(image_info_type *ImageInfo, char *dir_entry, const exif_offset_info *info, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table)
3248 {
3249 	size_t length;
3250 	unsigned int tag, format, components;
3251 	char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
3252 	size_t byte_count, offset_val, fpos, fgot;
3253 	int64_t byte_count_signed;
3254 	xp_field_type *tmp_xp;
3255 #ifdef EXIF_DEBUG
3256 	char *dump_data;
3257 	int dump_free;
3258 #endif /* EXIF_DEBUG */
3259 
3260 	tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
3261 	format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
3262 	components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
3263 
3264 	if (!format || format > NUM_FORMATS) {
3265 		/* (-1) catches illegal zero case as unsigned underflows to positive large. */
3266 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname_debug(tag, tag_table), format);
3267 		format = TAG_FMT_BYTE;
3268 	}
3269 
3270 	byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
3271 
3272 	if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
3273 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname_debug(tag, tag_table));
3274 		return false;
3275 	}
3276 
3277 	byte_count = (size_t)byte_count_signed;
3278 
3279 	if (byte_count > 4) {
3280 		/* If its bigger than 4 bytes, the dir entry contains an offset. */
3281 		offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
3282 		value_ptr = exif_offset_info_try_get(info, offset_val, byte_count);
3283 		if (!value_ptr) {
3284 			/* It is important to check for IMAGE_FILETYPE_TIFF
3285 			 * JPEG does not use absolute pointers instead its pointers are
3286 			 * relative to the start of the TIFF header in APP1 section. */
3287 			// TODO: Shouldn't we also be taking "displacement" into account here?
3288 			if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
3289 				exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname_debug(tag, tag_table), offset_val, byte_count, offset_val+byte_count, ImageInfo->FileSize);
3290 				return false;
3291 			}
3292 			if (byte_count>sizeof(cbuf)) {
3293 				/* mark as outside range and get buffer */
3294 				value_ptr = safe_emalloc(byte_count, 1, 0);
3295 				outside = value_ptr;
3296 			} else {
3297 				/* In most cases we only access a small range so
3298 				 * it is faster to use a static buffer there
3299 				 * BUT it offers also the possibility to have
3300 				 * pointers read without the need to free them
3301 				 * explicitley before returning. */
3302 				memset(&cbuf, 0, sizeof(cbuf));
3303 				value_ptr = cbuf;
3304 			}
3305 
3306 			fpos = php_stream_tell(ImageInfo->infile);
3307 			php_stream_seek(ImageInfo->infile, displacement+offset_val, SEEK_SET);
3308 			fgot = php_stream_tell(ImageInfo->infile);
3309 			if (fgot!=displacement+offset_val) {
3310 				EFREE_IF(outside);
3311 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, displacement+offset_val);
3312 				return false;
3313 			}
3314 			fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
3315 			php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
3316 			if (fgot != byte_count) {
3317 				EFREE_IF(outside);
3318 				EXIF_ERRLOG_FILEEOF(ImageInfo)
3319 				return false;
3320 			}
3321 		}
3322 	} else {
3323 		/* 4 bytes or less and value is in the dir entry itself */
3324 		value_ptr = dir_entry+8;
3325 		// TODO: This is dubious, but the value is only used for debugging.
3326 		offset_val = value_ptr-info->offset_base;
3327 	}
3328 
3329 	ImageInfo->sections_found |= FOUND_ANY_TAG;
3330 #ifdef EXIF_DEBUG
3331 	dump_data = exif_dump_data(&dump_free, format, components, ImageInfo->motorola_intel, value_ptr);
3332 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE,
3333 		"Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s",
3334 		tag, exif_get_tagname_debug(tag, tag_table), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
3335 	if (dump_free) {
3336 		efree(dump_data);
3337 	}
3338 #endif
3339 
3340 	/* NB: The following code may not assume that there is at least one component!
3341 	 * byte_count may be zero! */
3342 
3343 	if (section_index==SECTION_THUMBNAIL) {
3344 		if (!ImageInfo->Thumbnail.data) {
3345 			REQUIRE_NON_EMPTY();
3346 			switch(tag) {
3347 				case TAG_IMAGEWIDTH:
3348 				case TAG_COMP_IMAGE_WIDTH:
3349 					ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3350 					break;
3351 
3352 				case TAG_IMAGEHEIGHT:
3353 				case TAG_COMP_IMAGE_HEIGHT:
3354 					ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3355 					break;
3356 
3357 				case TAG_STRIP_OFFSETS:
3358 				case TAG_JPEG_INTERCHANGE_FORMAT:
3359 					/* accept both formats */
3360 					ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3361 					break;
3362 
3363 				case TAG_STRIP_BYTE_COUNTS:
3364 					if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
3365 						ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
3366 					} else {
3367 						/* motorola is easier to read */
3368 						ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
3369 					}
3370 					ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3371 					break;
3372 
3373 				case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
3374 					if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
3375 						ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
3376 						ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3377 					}
3378 					break;
3379 			}
3380 		}
3381 	} else {
3382 		if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
3383 		switch(tag) {
3384 			case TAG_COPYRIGHT:
3385 				/* check for "<photographer> NUL <editor> NUL" */
3386 				if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
3387 					if (length<byte_count-1) {
3388 						/* When there are any characters after the first NUL */
3389 						EFREE_IF(ImageInfo->CopyrightPhotographer);
3390 						EFREE_IF(ImageInfo->CopyrightEditor);
3391 						EFREE_IF(ImageInfo->Copyright);
3392 						ImageInfo->CopyrightPhotographer  = estrdup(value_ptr);
3393 						ImageInfo->CopyrightEditor        = estrndup(value_ptr+length+1, byte_count-length-1);
3394 						spprintf(&ImageInfo->Copyright, 0, "%s, %s", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor);
3395 						/* format = TAG_FMT_UNDEFINED; this mustn't be ASCII         */
3396 						/* but we are not supposed to change this                   */
3397 						/* keep in mind that image_info does not store editor value */
3398 					} else {
3399 						EFREE_IF(ImageInfo->Copyright);
3400 						ImageInfo->Copyright = estrndup(value_ptr, byte_count);
3401 					}
3402 				}
3403 				break;
3404 
3405 			case TAG_USERCOMMENT:
3406 				EFREE_IF(ImageInfo->UserComment);
3407 				ImageInfo->UserComment = NULL;
3408 				EFREE_IF(ImageInfo->UserCommentEncoding);
3409 				ImageInfo->UserCommentEncoding = NULL;
3410 				ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count);
3411 				break;
3412 
3413 			case TAG_XP_TITLE:
3414 			case TAG_XP_COMMENTS:
3415 			case TAG_XP_AUTHOR:
3416 			case TAG_XP_KEYWORDS:
3417 			case TAG_XP_SUBJECT:
3418 				tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
3419 				ImageInfo->sections_found |= FOUND_WINXP;
3420 				ImageInfo->xp_fields.list = tmp_xp;
3421 				ImageInfo->xp_fields.count++;
3422 				exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count);
3423 				break;
3424 
3425 			case TAG_FNUMBER:
3426 				/* Simplest way of expressing aperture, so I trust it the most.
3427 				   (overwrite previously computed value if there is one) */
3428 				REQUIRE_NON_EMPTY();
3429 				ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);
3430 				break;
3431 
3432 			case TAG_APERTURE:
3433 			case TAG_MAX_APERTURE:
3434 				/* More relevant info always comes earlier, so only use this field if we don't
3435 				   have appropriate aperture information yet. */
3436 				if (ImageInfo->ApertureFNumber == 0) {
3437 					REQUIRE_NON_EMPTY();
3438 					ImageInfo->ApertureFNumber
3439 						= expf(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*logf(2.0)*0.5);
3440 				}
3441 				break;
3442 
3443 			case TAG_SHUTTERSPEED:
3444 				/* More complicated way of expressing exposure time, so only use
3445 				   this value if we don't already have it from somewhere else.
3446 				   SHUTTERSPEED comes after EXPOSURE TIME
3447 				  */
3448 				if (ImageInfo->ExposureTime == 0) {
3449 					REQUIRE_NON_EMPTY();
3450 					ImageInfo->ExposureTime
3451 						= expf(-exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*logf(2.0));
3452 				}
3453 				break;
3454 			case TAG_EXPOSURETIME:
3455 				ImageInfo->ExposureTime = -1;
3456 				break;
3457 
3458 			case TAG_COMP_IMAGE_WIDTH:
3459 				REQUIRE_NON_EMPTY();
3460 				ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, exif_rewrite_tag_format_to_unsigned(format), ImageInfo->motorola_intel);
3461 				break;
3462 
3463 			case TAG_FOCALPLANE_X_RES:
3464 				REQUIRE_NON_EMPTY();
3465 				ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);
3466 				break;
3467 
3468 			case TAG_SUBJECT_DISTANCE:
3469 				/* Inidcates the distacne the autofocus camera is focused to.
3470 				   Tends to be less accurate as distance increases. */
3471 				REQUIRE_NON_EMPTY();
3472 				ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel);
3473 				break;
3474 
3475 			case TAG_FOCALPLANE_RESOLUTION_UNIT:
3476 				REQUIRE_NON_EMPTY();
3477 				switch (exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel)) {
3478 					case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
3479 					case 2:
3480 						/* According to the information I was using, 2 measn meters.
3481 						   But looking at the Cannon powershot's files, inches is the only
3482 						   sensible value. */
3483 						ImageInfo->FocalplaneUnits = 25.4;
3484 						break;
3485 
3486 					case 3: ImageInfo->FocalplaneUnits = 10;   break;  /* centimeter */
3487 					case 4: ImageInfo->FocalplaneUnits = 1;    break;  /* milimeter  */
3488 					case 5: ImageInfo->FocalplaneUnits = .001; break;  /* micrometer */
3489 				}
3490 				break;
3491 
3492 			case TAG_SUB_IFD:
3493 				if (format==TAG_FMT_IFD) {
3494 					/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
3495 					/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
3496 					/* JPEG do we have the data area and what to do with it */
3497 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
3498 				}
3499 				break;
3500 
3501 			case TAG_MAKE:
3502 				EFREE_IF(ImageInfo->make);
3503 				ImageInfo->make = estrndup(value_ptr, byte_count);
3504 				break;
3505 			case TAG_MODEL:
3506 				EFREE_IF(ImageInfo->model);
3507 				ImageInfo->model = estrndup(value_ptr, byte_count);
3508 				break;
3509 
3510 			case TAG_MAKER_NOTE:
3511 				if (!exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, info, displacement)) {
3512 					EFREE_IF(outside);
3513 					return false;
3514 				}
3515 				break;
3516 
3517 			case TAG_EXIF_IFD_POINTER:
3518 			case TAG_GPS_IFD_POINTER:
3519 			case TAG_INTEROP_IFD_POINTER:
3520 				if (ReadNextIFD) {
3521 					REQUIRE_NON_EMPTY();
3522 					char *Subdir_start;
3523 					int sub_section_index = 0;
3524 					switch(tag) {
3525 						case TAG_EXIF_IFD_POINTER:
3526 #ifdef EXIF_DEBUG
3527 							exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
3528 #endif
3529 							ImageInfo->sections_found |= FOUND_EXIF;
3530 							sub_section_index = SECTION_EXIF;
3531 							break;
3532 						case TAG_GPS_IFD_POINTER:
3533 #ifdef EXIF_DEBUG
3534 							exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
3535 #endif
3536 							ImageInfo->sections_found |= FOUND_GPS;
3537 							sub_section_index = SECTION_GPS;
3538 							break;
3539 						case TAG_INTEROP_IFD_POINTER:
3540 #ifdef EXIF_DEBUG
3541 							exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
3542 #endif
3543 							ImageInfo->sections_found |= FOUND_INTEROP;
3544 							sub_section_index = SECTION_INTEROP;
3545 							break;
3546 					}
3547 					offset_val = php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
3548 					Subdir_start = exif_offset_info_try_get(info, offset_val, 0);
3549 					if (!Subdir_start) {
3550 						exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
3551 						EFREE_IF(outside);
3552 						return false;
3553 					}
3554 					if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, info, displacement, sub_section_index, tag)) {
3555 						EFREE_IF(outside);
3556 						return false;
3557 					}
3558 #ifdef EXIF_DEBUG
3559 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
3560 #endif
3561 				}
3562 		}
3563 	}
3564 	exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname_key(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr, byte_count);
3565 	EFREE_IF(outside);
3566 	return true;
3567 }
3568 /* }}} */
3569 
exif_process_IFD_TAG(image_info_type * ImageInfo,char * dir_entry,const exif_offset_info * info,size_t displacement,int section_index,int ReadNextIFD,tag_table_type tag_table)3570 static bool exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, const exif_offset_info *info, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table)
3571 {
3572 	bool result;
3573 	/* Protect against corrupt headers */
3574 	if (ImageInfo->ifd_count++ > MAX_IFD_TAGS) {
3575 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum IFD tag count reached");
3576 		return false;
3577 	}
3578 	if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
3579 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
3580 		return false;
3581 	}
3582 	ImageInfo->ifd_nesting_level++;
3583 	result = exif_process_IFD_TAG_impl(ImageInfo, dir_entry, info, displacement, section_index, ReadNextIFD, tag_table);
3584 	ImageInfo->ifd_nesting_level--;
3585 	return result;
3586 }
3587 
3588 /* {{{ exif_process_IFD_in_JPEG
3589  * Process one of the nested IFDs directories. */
exif_process_IFD_in_JPEG(image_info_type * ImageInfo,char * dir_start,const exif_offset_info * info,size_t displacement,int section_index,int tag)3590 static bool exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, const exif_offset_info *info, size_t displacement, int section_index, int tag)
3591 {
3592 	int de;
3593 	int NumDirEntries;
3594 	int NextDirOffset = 0;
3595 
3596 #ifdef EXIF_DEBUG
3597 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s (x%04X(=%d))", exif_get_sectionname(section_index), exif_offset_info_length(info), exif_offset_info_length(info));
3598 #endif
3599 
3600 	ImageInfo->sections_found |= FOUND_IFD0;
3601 
3602 	if (!exif_offset_info_contains(info, dir_start, 2)) {
3603 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size");
3604 		return false;
3605 	}
3606 
3607 	NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
3608 
3609 	if (!exif_offset_info_contains(info, dir_start+2, NumDirEntries*12)) {
3610 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04X", (int)((size_t)dir_start+2-(size_t)info->valid_start), NumDirEntries, (int)((size_t)dir_start+2+NumDirEntries*12-(size_t)info->valid_start), info->valid_end - info->valid_start);
3611 		return false;
3612 	}
3613 
3614 	for (de=0;de<NumDirEntries;de++) {
3615 		if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
3616 								  info, displacement, section_index, 1, exif_get_tag_table(section_index))) {
3617 			return false;
3618 		}
3619 	}
3620 	/*
3621 	 * Ignore IFD2 if it purportedly exists
3622 	 */
3623 	if (section_index == SECTION_THUMBNAIL) {
3624 		return true;
3625 	}
3626 	/*
3627 	 * Hack to make it process IDF1 I hope
3628 	 * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail
3629 	 */
3630 	if (!exif_offset_info_contains(info, dir_start+2+NumDirEntries*12, 4)) {
3631 		exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size");
3632 		return false;
3633 	}
3634 
3635 	if (tag != TAG_EXIF_IFD_POINTER && tag != TAG_GPS_IFD_POINTER) {
3636 		NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);
3637 	}
3638 
3639 	if (NextDirOffset) {
3640 		char *next_dir_start = exif_offset_info_try_get(info, NextDirOffset, 0);
3641 		if (!next_dir_start) {
3642 			exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD offset");
3643 			return false;
3644 		}
3645 		/* That is the IFD for the first thumbnail */
3646 #ifdef EXIF_DEBUG
3647 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Expect next IFD to be thumbnail");
3648 #endif
3649 		if (exif_process_IFD_in_JPEG(ImageInfo, next_dir_start, info, displacement, SECTION_THUMBNAIL, 0)) {
3650 #ifdef EXIF_DEBUG
3651 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail size: 0x%04X", ImageInfo->Thumbnail.size);
3652 #endif
3653 			if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
3654 			&&  ImageInfo->Thumbnail.size
3655 			&&  ImageInfo->Thumbnail.offset
3656 			&&  ImageInfo->read_thumbnail
3657 			) {
3658 				exif_thumbnail_extract(ImageInfo, info);
3659 			}
3660 			return true;
3661 		} else {
3662 			return false;
3663 		}
3664 	}
3665 	return true;
3666 }
3667 /* }}} */
3668 
3669 /* {{{ exif_process_TIFF_in_JPEG
3670    Process a TIFF header in a JPEG file
3671 */
exif_process_TIFF_in_JPEG(image_info_type * ImageInfo,char * CharBuf,size_t length,size_t displacement)3672 static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement)
3673 {
3674 	unsigned exif_value_2a, offset_of_ifd;
3675 	exif_offset_info info;
3676 
3677 	if (length < 2) {
3678 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Missing TIFF alignment marker");
3679 		return;
3680 	}
3681 
3682 	if (length < 2) {
3683 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Missing TIFF alignment marker");
3684 		return;
3685 	}
3686 
3687 	/* set the thumbnail stuff to nothing so we can test to see if they get set up */
3688 	if (memcmp(CharBuf, "II", 2) == 0) {
3689 		ImageInfo->motorola_intel = 0;
3690 	} else if (memcmp(CharBuf, "MM", 2) == 0) {
3691 		ImageInfo->motorola_intel = 1;
3692 	} else {
3693 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker");
3694 		return;
3695 	}
3696 
3697 	/* Check the next two values for correctness. */
3698 	if (length < 8) {
3699 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)");
3700 		return;
3701 	}
3702 	exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel);
3703 	offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel);
3704 	if (exif_value_2a != 0x2a || offset_of_ifd < 0x08) {
3705 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)");
3706 		return;
3707 	}
3708 	if (offset_of_ifd > length) {
3709 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid IFD start");
3710 		return;
3711 	}
3712 
3713 	ImageInfo->sections_found |= FOUND_IFD0;
3714 	/* First directory starts at offset 8. Offsets starts at 0. */
3715 	exif_offset_info_init(&info, CharBuf, CharBuf, length/*-14*/);
3716 	exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, &info, displacement, SECTION_IFD0, 0);
3717 
3718 #ifdef EXIF_DEBUG
3719 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process TIFF in JPEG done");
3720 #endif
3721 
3722 	/* Compute the CCD width, in millimeters. */
3723 	if (ImageInfo->FocalplaneXRes != 0) {
3724 		ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes);
3725 	}
3726 }
3727 /* }}} */
3728 
3729 /* {{{ exif_process_APP1
3730    Process an JPEG APP1 block marker
3731    Describes all the drivel that most digital cameras include...
3732 */
exif_process_APP1(image_info_type * ImageInfo,char * CharBuf,size_t length,size_t displacement)3733 static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement)
3734 {
3735 	/* Check the APP1 for Exif Identifier Code */
3736 	static const uchar ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
3737 	if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) {
3738 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Incorrect APP1 Exif Identifier Code");
3739 		return;
3740 	}
3741 	exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8);
3742 #ifdef EXIF_DEBUG
3743 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process APP1/EXIF done");
3744 #endif
3745 }
3746 /* }}} */
3747 
3748 /* {{{ exif_process_APP12
3749    Process an JPEG APP12 block marker used by OLYMPUS
3750 */
exif_process_APP12(image_info_type * ImageInfo,char * buffer,size_t length)3751 static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length)
3752 {
3753 	size_t l1, l2=0;
3754 
3755 	if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
3756 		exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2, l1);
3757 		if (length > 2+l1+1) {
3758 			l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);
3759 			exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1, l2);
3760 		}
3761 	}
3762 #ifdef EXIF_DEBUG
3763 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section APP12 with l1=%d, l2=%d done", l1, l2);
3764 #endif
3765 }
3766 /* }}} */
3767 
3768 /* {{{ exif_scan_JPEG_header
3769  * Parse the marker stream until SOS or EOI is seen; */
exif_scan_JPEG_header(image_info_type * ImageInfo)3770 static bool exif_scan_JPEG_header(image_info_type *ImageInfo)
3771 {
3772 	int section, sn;
3773 	int marker = 0, last_marker = M_PSEUDO, comment_correction=1;
3774 	unsigned int ll, lh;
3775 	uchar *Data;
3776 	size_t fpos, size, got, itemlen;
3777 	jpeg_sof_info sof_info;
3778 
3779 	for(section=0;;section++) {
3780 #ifdef EXIF_DEBUG
3781 		fpos = php_stream_tell(ImageInfo->infile);
3782 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Needing section %d @ 0x%08X", ImageInfo->file.count, fpos);
3783 #endif
3784 
3785 		/* get marker byte, swallowing possible padding                           */
3786 		/* some software does not count the length bytes of COM section           */
3787 		/* one company doing so is very much involved in JPEG... so we accept too */
3788 		if (last_marker==M_COM && comment_correction) {
3789 			comment_correction = 2;
3790 		}
3791 		do {
3792 			if ((marker = php_stream_getc(ImageInfo->infile)) == EOF) {
3793 				EXIF_ERRLOG_CORRUPT(ImageInfo)
3794 				return false;
3795 			}
3796 			if (last_marker==M_COM && comment_correction>0) {
3797 				if (marker!=0xFF) {
3798 					marker = 0xff;
3799 					comment_correction--;
3800 				} else  {
3801 					last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */
3802 				}
3803 			}
3804 		} while (marker == 0xff);
3805 		if (last_marker==M_COM && !comment_correction) {
3806 			exif_error_docref("exif_read_data#error_mcom" EXIFERR_CC, ImageInfo, E_NOTICE, "Image has corrupt COM section: some software set wrong length information");
3807 		}
3808 		if (last_marker==M_COM && comment_correction)
3809 			return M_EOI; /* ah illegal: char after COM section not 0xFF */
3810 
3811 		fpos = php_stream_tell(ImageInfo->infile);
3812 
3813 		if (marker == 0xff) {
3814 			/* 0xff is legal padding, but if we get that many, something's wrong. */
3815 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "To many padding bytes");
3816 			return false;
3817 		}
3818 
3819 		/* Read the length of the section. */
3820 		if ((lh = php_stream_getc(ImageInfo->infile)) == (unsigned int)EOF) {
3821 			EXIF_ERRLOG_CORRUPT(ImageInfo)
3822 			return false;
3823 		}
3824 		if ((ll = php_stream_getc(ImageInfo->infile)) == (unsigned int)EOF) {
3825 			EXIF_ERRLOG_CORRUPT(ImageInfo)
3826 			return false;
3827 		}
3828 
3829 		itemlen = (lh << 8) | ll;
3830 
3831 		if (itemlen < 2) {
3832 #ifdef EXIF_DEBUG
3833 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "%s, Section length: 0x%02X%02X", EXIF_ERROR_CORRUPT, lh, ll);
3834 #else
3835 			EXIF_ERRLOG_CORRUPT(ImageInfo)
3836 #endif
3837 			return false;
3838 		}
3839 
3840 		sn = exif_file_sections_add(ImageInfo, marker, itemlen, NULL);
3841 		Data = ImageInfo->file.list[sn].data;
3842 
3843 		/* Store first two pre-read bytes. */
3844 		Data[0] = (uchar)lh;
3845 		Data[1] = (uchar)ll;
3846 
3847 		got = php_stream_read(ImageInfo->infile, (char*)(Data+2), itemlen-2); /* Read the whole section. */
3848 		if (got != itemlen-2) {
3849 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error reading from file: got=x%04X(=%d) != itemlen-2=x%04X(=%d)", got, got, itemlen-2, itemlen-2);
3850 			return false;
3851 		}
3852 
3853 #ifdef EXIF_DEBUG
3854 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process section(x%02X=%s) @ x%04X + x%04X(=%d)", marker, exif_get_markername(marker), fpos, itemlen, itemlen);
3855 #endif
3856 		switch(marker) {
3857 			case M_SOS:   /* stop before hitting compressed data  */
3858 				/* If reading entire image is requested, read the rest of the data. */
3859 				if (ImageInfo->read_all) {
3860 					/* Determine how much file is left. */
3861 					fpos = php_stream_tell(ImageInfo->infile);
3862 					size = ImageInfo->FileSize - fpos;
3863 					sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, NULL);
3864 					Data = ImageInfo->file.list[sn].data;
3865 					got = php_stream_read(ImageInfo->infile, (char*)Data, size);
3866 					if (got != size) {
3867 						EXIF_ERRLOG_FILEEOF(ImageInfo)
3868 						return false;
3869 					}
3870 				}
3871 				return true;
3872 
3873 			case M_EOI:   /* in case it's a tables-only JPEG stream */
3874 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "No image in jpeg!");
3875 				return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? true : false;
3876 
3877 			case M_COM: /* Comment section */
3878 				exif_process_COM(ImageInfo, (char *)Data, itemlen);
3879 				break;
3880 
3881 			case M_EXIF:
3882 				if (!(ImageInfo->sections_found&FOUND_IFD0)) {
3883 					/*ImageInfo->sections_found |= FOUND_EXIF;*/
3884 					/* Seen files from some 'U-lead' software with Vivitar scanner
3885 					   that uses marker 31 later in the file (no clue what for!) */
3886 					exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos);
3887 				}
3888 				break;
3889 
3890 			case M_APP12:
3891 				exif_process_APP12(ImageInfo, (char *)Data, itemlen);
3892 				break;
3893 
3894 
3895 			case M_SOF0:
3896 			case M_SOF1:
3897 			case M_SOF2:
3898 			case M_SOF3:
3899 			case M_SOF5:
3900 			case M_SOF6:
3901 			case M_SOF7:
3902 			case M_SOF9:
3903 			case M_SOF10:
3904 			case M_SOF11:
3905 			case M_SOF13:
3906 			case M_SOF14:
3907 			case M_SOF15:
3908 				if ((itemlen - 2) < 6) {
3909 					return false;
3910 				}
3911 
3912 				exif_process_SOFn(Data, marker, &sof_info);
3913 				ImageInfo->Width  = sof_info.width;
3914 				ImageInfo->Height = sof_info.height;
3915 				if (sof_info.num_components == 3) {
3916 					ImageInfo->IsColor = 1;
3917 				} else {
3918 					ImageInfo->IsColor = 0;
3919 				}
3920 				break;
3921 			default:
3922 				/* skip any other marker silently. */
3923 				break;
3924 		}
3925 
3926 		/* keep track of last marker */
3927 		last_marker = marker;
3928 	}
3929 #ifdef EXIF_DEBUG
3930 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Done");
3931 #endif
3932 	return true;
3933 }
3934 /* }}} */
3935 
3936 /* {{{ exif_scan_thumbnail
3937  * scan JPEG in thumbnail (memory) */
exif_scan_thumbnail(image_info_type * ImageInfo)3938 static bool exif_scan_thumbnail(image_info_type *ImageInfo)
3939 {
3940 	uchar           c, *data = (uchar*)ImageInfo->Thumbnail.data;
3941 	int             n, marker;
3942 	size_t          length=2, pos=0;
3943 	jpeg_sof_info   sof_info;
3944 
3945 	if (!data || ImageInfo->Thumbnail.size < 4) {
3946 		return false; /* nothing to do here */
3947 	}
3948 	if (memcmp(data, "\xFF\xD8\xFF", 3)) {
3949 		if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) {
3950 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Thumbnail is not a JPEG image");
3951 		}
3952 		return false;
3953 	}
3954 	for (;;) {
3955 		pos += length;
3956 		if (pos>=ImageInfo->Thumbnail.size)
3957 			return false;
3958 		c = data[pos++];
3959 		if (pos>=ImageInfo->Thumbnail.size)
3960 			return false;
3961 		if (c != 0xFF) {
3962 			return false;
3963 		}
3964 		n = 8;
3965 		while ((c = data[pos++]) == 0xFF && n--) {
3966 			if (pos+3>=ImageInfo->Thumbnail.size)
3967 				return false;
3968 			/* +3 = pos++ of next check when reaching marker + 2 bytes for length */
3969 		}
3970 		if (c == 0xFF)
3971 			return false;
3972 		marker = c;
3973 		if (pos>=ImageInfo->Thumbnail.size)
3974 			return false;
3975 		length = php_jpg_get16(data+pos);
3976 		if (length > ImageInfo->Thumbnail.size || pos >= ImageInfo->Thumbnail.size - length) {
3977 			return false;
3978 		}
3979 #ifdef EXIF_DEBUG
3980 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: process section(x%02X=%s) @ x%04X + x%04X", marker, exif_get_markername(marker), pos, length);
3981 #endif
3982 		switch (marker) {
3983 			case M_SOF0:
3984 			case M_SOF1:
3985 			case M_SOF2:
3986 			case M_SOF3:
3987 			case M_SOF5:
3988 			case M_SOF6:
3989 			case M_SOF7:
3990 			case M_SOF9:
3991 			case M_SOF10:
3992 			case M_SOF11:
3993 			case M_SOF13:
3994 			case M_SOF14:
3995 			case M_SOF15:
3996 				/* handle SOFn block */
3997 				if (length < 8 || ImageInfo->Thumbnail.size - 8 < pos) {
3998 					/* exif_process_SOFn needs 8 bytes */
3999 					return false;
4000 				}
4001 				exif_process_SOFn(data+pos, marker, &sof_info);
4002 				ImageInfo->Thumbnail.height   = sof_info.height;
4003 				ImageInfo->Thumbnail.width    = sof_info.width;
4004 #ifdef EXIF_DEBUG
4005 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Thumbnail: size: %d * %d", sof_info.width, sof_info.height);
4006 #endif
4007 				return true;
4008 
4009 			case M_SOS:
4010 			case M_EOI:
4011 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
4012 				return false;
4013 				break;
4014 
4015 			default:
4016 				/* just skip */
4017 				break;
4018 		}
4019 	}
4020 
4021 	exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Could not compute size of thumbnail");
4022 	return false;
4023 }
4024 /* }}} */
4025 
4026 /* {{{ exif_process_IFD_in_TIFF
4027  * Parse the TIFF header; */
exif_process_IFD_in_TIFF_impl(image_info_type * ImageInfo,size_t dir_offset,int section_index)4028 static bool exif_process_IFD_in_TIFF_impl(image_info_type *ImageInfo, size_t dir_offset, int section_index)
4029 {
4030 	int i, sn, num_entries, sub_section_index = 0;
4031 	unsigned char *dir_entry;
4032 	size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot;
4033 	int entry_tag , entry_type;
4034 	tag_table_type tag_table = exif_get_tag_table(section_index);
4035 
4036 	if (ImageInfo->FileSize >= 2 && ImageInfo->FileSize - 2 >= dir_offset) {
4037 		sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, NULL);
4038 #ifdef EXIF_DEBUG
4039 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, 2);
4040 #endif
4041 		php_stream_seek(ImageInfo->infile, dir_offset, SEEK_SET); /* we do not know the order of sections */
4042 		php_stream_read(ImageInfo->infile, (char*)ImageInfo->file.list[sn].data, 2);
4043 		num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel);
4044 		dir_size = 2/*num dir entries*/ +12/*length of entry*/*(size_t)num_entries +4/* offset to next ifd (points to thumbnail or NULL)*/;
4045 		if (ImageInfo->FileSize >= dir_size && ImageInfo->FileSize - dir_size >= dir_offset) {
4046 #ifdef EXIF_DEBUG
4047 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD dir(x%04X + x%04X), IFD entries(%d)", ImageInfo->FileSize, dir_offset+2, dir_size-2, num_entries);
4048 #endif
4049 			if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) {
4050 				return false;
4051 			}
4052 			php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+2), dir_size-2);
4053 			next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel);
4054 #ifdef EXIF_DEBUG
4055 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF done, next offset x%04X", next_offset);
4056 #endif
4057 			/* now we have the directory we can look how long it should be */
4058 			ifd_size = dir_size;
4059 			for(i=0;i<num_entries;i++) {
4060 				dir_entry 	 = ImageInfo->file.list[sn].data+2+i*12;
4061 				entry_tag    = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
4062 				entry_type   = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
4063 				if (entry_type > NUM_FORMATS) {
4064 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: tag(0x%04X,%12s): Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname_debug(entry_tag, tag_table), entry_type);
4065 					/* Since this is repeated in exif_process_IFD_TAG make it a notice here */
4066 					/* and make it a warning in the exif_process_IFD_TAG which is called    */
4067 					/* elsewhere. */
4068 					entry_type = TAG_FMT_BYTE;
4069 					/*The next line would break the image on writeback: */
4070 					/* php_ifd_set16u(dir_entry+2, entry_type, ImageInfo->motorola_intel);*/
4071 				}
4072 				entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * php_tiff_bytes_per_format[entry_type];
4073 				if (entry_length <= 4) {
4074 					switch(entry_type) {
4075 						case TAG_FMT_USHORT:
4076 							entry_value  = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel);
4077 							break;
4078 						case TAG_FMT_SSHORT:
4079 							entry_value  = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel);
4080 							break;
4081 						case TAG_FMT_ULONG:
4082 							entry_value  = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
4083 							break;
4084 						case TAG_FMT_SLONG:
4085 							entry_value  = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel);
4086 							break;
4087 					}
4088 					switch(entry_tag) {
4089 						case TAG_IMAGEWIDTH:
4090 						case TAG_COMP_IMAGE_WIDTH:
4091 							ImageInfo->Width  = entry_value;
4092 							break;
4093 						case TAG_IMAGEHEIGHT:
4094 						case TAG_COMP_IMAGE_HEIGHT:
4095 							ImageInfo->Height = entry_value;
4096 							break;
4097 						case TAG_PHOTOMETRIC_INTERPRETATION:
4098 							switch (entry_value) {
4099 								case PMI_BLACK_IS_ZERO:
4100 								case PMI_WHITE_IS_ZERO:
4101 								case PMI_TRANSPARENCY_MASK:
4102 									ImageInfo->IsColor = 0;
4103 									break;
4104 								case PMI_RGB:
4105 								case PMI_PALETTE_COLOR:
4106 								case PMI_SEPARATED:
4107 								case PMI_YCBCR:
4108 								case PMI_CIELAB:
4109 									ImageInfo->IsColor = 1;
4110 									break;
4111 							}
4112 							break;
4113 					}
4114 				} else {
4115 					entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
4116 					/* if entry needs expading ifd cache and entry is at end of current ifd cache. */
4117 					/* otherwise there may be huge holes between two entries */
4118 					if (entry_offset + entry_length > dir_offset + ifd_size
4119 					  && entry_offset == dir_offset + ifd_size) {
4120 						ifd_size = entry_offset + entry_length - dir_offset;
4121 #ifdef EXIF_DEBUG
4122 						exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Resize struct: x%04X + x%04X - x%04X = x%04X", entry_offset, entry_length, dir_offset, ifd_size);
4123 #endif
4124 					}
4125 				}
4126 			}
4127 			if (ImageInfo->FileSize >= ImageInfo->file.list[sn].size && ImageInfo->FileSize - ImageInfo->file.list[sn].size >= dir_offset) {
4128 				if (ifd_size > dir_size) {
4129 					if (ImageInfo->FileSize < ifd_size || dir_offset > ImageInfo->FileSize - ifd_size) {
4130 						exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
4131 						return false;
4132 					}
4133 					if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) {
4134 						return false;
4135 					}
4136 					/* read values not stored in directory itself */
4137 #ifdef EXIF_DEBUG
4138 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF: filesize(x%04X), IFD(x%04X + x%04X)", ImageInfo->FileSize, dir_offset, ifd_size);
4139 #endif
4140 					php_stream_read(ImageInfo->infile, (char*)(ImageInfo->file.list[sn].data+dir_size), ifd_size-dir_size);
4141 #ifdef EXIF_DEBUG
4142 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read from TIFF, done");
4143 #endif
4144 				}
4145 				/* now process the tags */
4146 				for(i=0;i<num_entries;i++) {
4147 					dir_entry 	 = ImageInfo->file.list[sn].data+2+i*12;
4148 					entry_tag    = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel);
4149 					entry_type   = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
4150 					/*entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);*/
4151 					if (entry_tag == TAG_EXIF_IFD_POINTER ||
4152 						entry_tag == TAG_INTEROP_IFD_POINTER ||
4153 						entry_tag == TAG_GPS_IFD_POINTER ||
4154 						entry_tag == TAG_SUB_IFD
4155 					) {
4156 						switch(entry_tag) {
4157 							case TAG_EXIF_IFD_POINTER:
4158 								ImageInfo->sections_found |= FOUND_EXIF;
4159 								sub_section_index = SECTION_EXIF;
4160 								break;
4161 							case TAG_GPS_IFD_POINTER:
4162 								ImageInfo->sections_found |= FOUND_GPS;
4163 								sub_section_index = SECTION_GPS;
4164 								break;
4165 							case TAG_INTEROP_IFD_POINTER:
4166 								ImageInfo->sections_found |= FOUND_INTEROP;
4167 								sub_section_index = SECTION_INTEROP;
4168 								break;
4169 							case TAG_SUB_IFD:
4170 								ImageInfo->sections_found |= FOUND_THUMBNAIL;
4171 								sub_section_index = SECTION_THUMBNAIL;
4172 								break;
4173 						}
4174 						entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
4175 #ifdef EXIF_DEBUG
4176 						exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s @x%04X", exif_get_sectionname(sub_section_index), entry_offset);
4177 #endif
4178 						exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index);
4179 						if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) {
4180 							if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN
4181 							&&  ImageInfo->Thumbnail.size
4182 							&&  ImageInfo->Thumbnail.offset
4183 							&&  ImageInfo->read_thumbnail
4184 							) {
4185 #ifdef EXIF_DEBUG
4186 								exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
4187 #endif
4188 								if (!ImageInfo->Thumbnail.data) {
4189 									ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
4190 									php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
4191 									fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
4192 									if (fgot != ImageInfo->Thumbnail.size) {
4193 										EXIF_ERRLOG_THUMBEOF(ImageInfo)
4194 										efree(ImageInfo->Thumbnail.data);
4195 
4196 										ImageInfo->Thumbnail.data = NULL;
4197 									} else {
4198 										exif_thumbnail_build(ImageInfo);
4199 									}
4200 								}
4201 							}
4202 						}
4203 #ifdef EXIF_DEBUG
4204 						exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Next IFD: %s done", exif_get_sectionname(sub_section_index));
4205 #endif
4206 					} else {
4207 						exif_offset_info info;
4208 						exif_offset_info_init(&info,
4209 							(char *) (ImageInfo->file.list[sn].data - dir_offset),
4210 							(char *) ImageInfo->file.list[sn].data, ifd_size);
4211 						if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry, &info,
4212 												  0, section_index, 0, tag_table)) {
4213 							return false;
4214 						}
4215 					}
4216 				}
4217 				/* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */
4218 				if (next_offset && section_index != SECTION_THUMBNAIL) {
4219 					/* this should be a thumbnail IFD */
4220 					/* the thumbnail itself is stored at Tag=StripOffsets */
4221 #ifdef EXIF_DEBUG
4222 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) at x%04X", next_offset);
4223 #endif
4224 					exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL);
4225 #ifdef EXIF_DEBUG
4226 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "%s THUMBNAIL @0x%04X + 0x%04X", ImageInfo->Thumbnail.data ? "Ignore" : "Read", ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size);
4227 #endif
4228 					if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) {
4229 						ImageInfo->Thumbnail.data = safe_emalloc(ImageInfo->Thumbnail.size, 1, 0);
4230 						php_stream_seek(ImageInfo->infile, ImageInfo->Thumbnail.offset, SEEK_SET);
4231 						fgot = php_stream_read(ImageInfo->infile, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size);
4232 						if (fgot != ImageInfo->Thumbnail.size) {
4233 							EXIF_ERRLOG_THUMBEOF(ImageInfo)
4234 							efree(ImageInfo->Thumbnail.data);
4235 							ImageInfo->Thumbnail.data = NULL;
4236 						} else {
4237 							exif_thumbnail_build(ImageInfo);
4238 						}
4239 					}
4240 #ifdef EXIF_DEBUG
4241 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Read next IFD (THUMBNAIL) done");
4242 #endif
4243 				}
4244 				return true;
4245 			} else {
4246 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD(x%04X)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size);
4247 				return false;
4248 			}
4249 		} else {
4250 			exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than size of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+dir_size);
4251 			return false;
4252 		}
4253 	} else {
4254 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Error in TIFF: filesize(x%04X) less than start of IFD dir(x%04X)", ImageInfo->FileSize, dir_offset+2);
4255 		return false;
4256 	}
4257 }
4258 /* }}} */
4259 
exif_process_IFD_in_TIFF(image_info_type * ImageInfo,size_t dir_offset,int section_index)4260 static bool exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index)
4261 {
4262 	bool result;
4263 	if (ImageInfo->ifd_count++ > MAX_IFD_TAGS) {
4264 		return false;
4265 	}
4266 	if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
4267 		return false;
4268 	}
4269 	ImageInfo->ifd_nesting_level++;
4270 	result = exif_process_IFD_in_TIFF_impl(ImageInfo, dir_offset, section_index);
4271 	ImageInfo->ifd_nesting_level--;
4272 	return result;
4273 }
4274 
4275 /* {{{ exif_scan_FILE_header
4276  * Parse the marker stream until SOS or EOI is seen; */
exif_scan_FILE_header(image_info_type * ImageInfo)4277 static bool exif_scan_FILE_header(image_info_type *ImageInfo)
4278 {
4279 	unsigned char file_header[8];
4280 	bool ret = false;
4281 
4282 	ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN;
4283 
4284 	if (ImageInfo->FileSize >= 2) {
4285 		php_stream_seek(ImageInfo->infile, 0, SEEK_SET);
4286 		if (php_stream_read(ImageInfo->infile, (char*)file_header, 2) != 2) {
4287 			return false;
4288 		}
4289 		if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) {
4290 			ImageInfo->FileType = IMAGE_FILETYPE_JPEG;
4291 			if (exif_scan_JPEG_header(ImageInfo)) {
4292 				ret = true;
4293 			} else {
4294 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid JPEG file");
4295 			}
4296 		} else if (ImageInfo->FileSize >= 8) {
4297 			if (php_stream_read(ImageInfo->infile, (char*)(file_header+2), 6) != 6) {
4298 				return false;
4299 			}
4300 			if (!memcmp(file_header, "II\x2A\x00", 4)) {
4301 				ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II;
4302 				ImageInfo->motorola_intel = 0;
4303 #ifdef EXIF_DEBUG
4304 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "File has TIFF/II format");
4305 #endif
4306 				ImageInfo->sections_found |= FOUND_IFD0;
4307 				if (exif_process_IFD_in_TIFF(ImageInfo,
4308 											 php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel),
4309 											 SECTION_IFD0)) {
4310 					ret = true;
4311 				} else {
4312 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF file");
4313 				}
4314 			} else if (!memcmp(file_header, "MM\x00\x2a", 4)) {
4315 				ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM;
4316 				ImageInfo->motorola_intel = 1;
4317 #ifdef EXIF_DEBUG
4318 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "File has TIFF/MM format");
4319 #endif
4320 				ImageInfo->sections_found |= FOUND_IFD0;
4321 				if (exif_process_IFD_in_TIFF(ImageInfo,
4322 											 php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel),
4323 											 SECTION_IFD0)) {
4324 					ret = true;
4325 				} else {
4326 					exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF file");
4327 				}
4328 			} else {
4329 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "File not supported");
4330 				return false;
4331 			}
4332 		}
4333 	} else {
4334 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "File too small (%d)", ImageInfo->FileSize);
4335 	}
4336 	return ret;
4337 }
4338 /* }}} */
4339 
4340 /* {{{ exif_discard_imageinfo
4341    Discard data scanned by exif_read_file.
4342 */
exif_discard_imageinfo(image_info_type * ImageInfo)4343 static bool exif_discard_imageinfo(image_info_type *ImageInfo)
4344 {
4345 	int i;
4346 
4347 	EFREE_IF(ImageInfo->FileName);
4348 	EFREE_IF(ImageInfo->UserComment);
4349 	EFREE_IF(ImageInfo->UserCommentEncoding);
4350 	EFREE_IF(ImageInfo->Copyright);
4351 	EFREE_IF(ImageInfo->CopyrightPhotographer);
4352 	EFREE_IF(ImageInfo->CopyrightEditor);
4353 	EFREE_IF(ImageInfo->Thumbnail.data);
4354 	EFREE_IF(ImageInfo->encode_unicode);
4355 	EFREE_IF(ImageInfo->decode_unicode_be);
4356 	EFREE_IF(ImageInfo->decode_unicode_le);
4357 	EFREE_IF(ImageInfo->encode_jis);
4358 	EFREE_IF(ImageInfo->decode_jis_be);
4359 	EFREE_IF(ImageInfo->decode_jis_le);
4360 	EFREE_IF(ImageInfo->make);
4361 	EFREE_IF(ImageInfo->model);
4362 	for (i=0; i<ImageInfo->xp_fields.count; i++) {
4363 		EFREE_IF(ImageInfo->xp_fields.list[i].value);
4364 	}
4365 	EFREE_IF(ImageInfo->xp_fields.list);
4366 	for (i=0; i<SECTION_COUNT; i++) {
4367 		exif_iif_free(ImageInfo, i);
4368 	}
4369 	exif_file_sections_free(ImageInfo);
4370 	memset(ImageInfo, 0, sizeof(*ImageInfo));
4371 	return true;
4372 }
4373 /* }}} */
4374 
4375 /* {{{ exif_read_from_impl */
exif_read_from_impl(image_info_type * ImageInfo,php_stream * stream,int read_thumbnail,int read_all)4376 static bool exif_read_from_impl(image_info_type *ImageInfo, php_stream *stream, int read_thumbnail, int read_all)
4377 {
4378 	bool ret;
4379 	zend_stat_t st;
4380 
4381 	/* Start with an empty image information structure. */
4382 	memset(ImageInfo, 0, sizeof(*ImageInfo));
4383 
4384 	ImageInfo->motorola_intel	= -1; /* flag as unknown */
4385 	ImageInfo->infile			= stream;
4386 	ImageInfo->FileName			= NULL;
4387 
4388 	if (php_stream_is(ImageInfo->infile, PHP_STREAM_IS_STDIO)) {
4389 		if (VCWD_STAT(stream->orig_path, &st) >= 0) {
4390 			zend_string *base;
4391 			if ((st.st_mode & S_IFMT) != S_IFREG) {
4392 				exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Not a file");
4393 				ImageInfo->infile = NULL;
4394 				return false;
4395 			}
4396 
4397 			/* Store file name */
4398 			base = php_basename(stream->orig_path, strlen(stream->orig_path), NULL, 0);
4399 			ImageInfo->FileName = estrndup(ZSTR_VAL(base), ZSTR_LEN(base));
4400 
4401 			zend_string_release_ex(base, 0);
4402 
4403 			/* Store file date/time. */
4404 			ImageInfo->FileDateTime = st.st_mtime;
4405 			ImageInfo->FileSize = st.st_size;
4406 		}
4407 	} else {
4408 		if (!ImageInfo->FileSize) {
4409 			php_stream_seek(ImageInfo->infile, 0, SEEK_END);
4410 			ImageInfo->FileSize = php_stream_tell(ImageInfo->infile);
4411 			php_stream_seek(ImageInfo->infile, 0, SEEK_SET);
4412 		}
4413 	}
4414 
4415 	ImageInfo->read_thumbnail		= read_thumbnail;
4416 	ImageInfo->read_all				= read_all;
4417 	ImageInfo->Thumbnail.filetype	= IMAGE_FILETYPE_UNKNOWN;
4418 
4419 	ImageInfo->encode_unicode		= estrdup(EXIF_G(encode_unicode));
4420 	ImageInfo->decode_unicode_be	= estrdup(EXIF_G(decode_unicode_be));
4421 	ImageInfo->decode_unicode_le	= estrdup(EXIF_G(decode_unicode_le));
4422 	ImageInfo->encode_jis			= estrdup(EXIF_G(encode_jis));
4423 	ImageInfo->decode_jis_be	 	= estrdup(EXIF_G(decode_jis_be));
4424 	ImageInfo->decode_jis_le		= estrdup(EXIF_G(decode_jis_le));
4425 
4426 
4427 	ImageInfo->ifd_nesting_level = 0;
4428 	ImageInfo->ifd_count = 0;
4429 	ImageInfo->num_errors = 0;
4430 
4431 	/* Scan the headers */
4432 	ret = exif_scan_FILE_header(ImageInfo);
4433 
4434 	return ret;
4435 }
4436 /* }}} */
4437 
4438 /* {{{ exif_read_from_stream */
exif_read_from_stream(image_info_type * ImageInfo,php_stream * stream,int read_thumbnail,int read_all)4439 static bool exif_read_from_stream(image_info_type *ImageInfo, php_stream *stream, int read_thumbnail, int read_all)
4440 {
4441 	bool ret;
4442 	off_t old_pos = php_stream_tell(stream);
4443 
4444 	if (old_pos) {
4445 		php_stream_seek(stream, 0, SEEK_SET);
4446 	}
4447 
4448 	ret = exif_read_from_impl(ImageInfo, stream, read_thumbnail, read_all);
4449 
4450 	if (old_pos) {
4451 		php_stream_seek(stream, old_pos, SEEK_SET);
4452 	}
4453 
4454 	return ret;
4455 }
4456 /* }}} */
4457 
4458 /* {{{ exif_read_from_file */
exif_read_from_file(image_info_type * ImageInfo,char * FileName,int read_thumbnail,int read_all)4459 static bool exif_read_from_file(image_info_type *ImageInfo, char *FileName, int read_thumbnail, int read_all)
4460 {
4461 	bool ret;
4462 	php_stream *stream;
4463 
4464 	stream = php_stream_open_wrapper(FileName, "rb", STREAM_MUST_SEEK | IGNORE_PATH, NULL);
4465 
4466 	if (!stream) {
4467 		memset(&ImageInfo, 0, sizeof(ImageInfo));
4468 
4469 		exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Unable to open file");
4470 
4471 		return false;
4472 	}
4473 
4474 	ret = exif_read_from_stream(ImageInfo, stream, read_thumbnail, read_all);
4475 
4476 	php_stream_close(stream);
4477 
4478 	return ret;
4479 }
4480 /* }}} */
4481 
4482 /* {{{ Reads header data from an image and optionally reads the internal thumbnails */
PHP_FUNCTION(exif_read_data)4483 PHP_FUNCTION(exif_read_data)
4484 {
4485 	zend_string *z_sections_needed = NULL;
4486 	bool sub_arrays = 0, read_thumbnail = 0, read_all = 0;
4487 	zval *stream;
4488 	bool ret;
4489 	int i, sections_needed = 0;
4490 	image_info_type ImageInfo;
4491 	char tmp[64], *sections_str, *s;
4492 
4493 	/* Parse arguments */
4494 	ZEND_PARSE_PARAMETERS_START(1, 4)
4495 		Z_PARAM_ZVAL(stream)
4496 		Z_PARAM_OPTIONAL
4497 		Z_PARAM_STR_OR_NULL(z_sections_needed)
4498 		Z_PARAM_BOOL(sub_arrays)
4499 		Z_PARAM_BOOL(read_thumbnail)
4500 	ZEND_PARSE_PARAMETERS_END();
4501 
4502 	memset(&ImageInfo, 0, sizeof(ImageInfo));
4503 
4504 	if (z_sections_needed) {
4505 		spprintf(&sections_str, 0, ",%s,", ZSTR_VAL(z_sections_needed));
4506 		/* sections_str DOES start with , and SPACES are NOT allowed in names */
4507 		s = sections_str;
4508 		while (*++s) {
4509 			if (*s == ' ') {
4510 				*s = ',';
4511 			}
4512 		}
4513 
4514 		for (i = 0; i < SECTION_COUNT; i++) {
4515 			snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i));
4516 			if (strstr(sections_str, tmp)) {
4517 				sections_needed |= 1<<i;
4518 			}
4519 		}
4520 		EFREE_IF(sections_str);
4521 		/* now see what we need */
4522 #ifdef EXIF_DEBUG
4523 		sections_str = exif_get_sectionlist(sections_needed);
4524 		if (!sections_str) {
4525 			RETURN_FALSE;
4526 		}
4527 		exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections needed: %s", sections_str[0] ? sections_str : "None");
4528 		EFREE_IF(sections_str);
4529 #endif
4530 	}
4531 
4532 	if (Z_TYPE_P(stream) == IS_RESOURCE) {
4533 		php_stream *p_stream = NULL;
4534 
4535 		php_stream_from_res(p_stream, Z_RES_P(stream));
4536 
4537 		ret = exif_read_from_stream(&ImageInfo, p_stream, read_thumbnail, read_all);
4538 	} else {
4539 		if (!try_convert_to_string(stream)) {
4540 			RETURN_THROWS();
4541 		}
4542 
4543 		if (!Z_STRLEN_P(stream)) {
4544 			zend_argument_value_error(1, "cannot be empty");
4545 			RETURN_THROWS();
4546 		}
4547 
4548 		if (CHECK_NULL_PATH(Z_STRVAL_P(stream), Z_STRLEN_P(stream))) {
4549 			zend_argument_value_error(1, "must not contain any null bytes");
4550 			RETURN_THROWS();
4551 		}
4552 
4553 		ret = exif_read_from_file(&ImageInfo, Z_STRVAL_P(stream), read_thumbnail, read_all);
4554 	}
4555 
4556 	sections_str = exif_get_sectionlist(ImageInfo.sections_found);
4557 
4558 #ifdef EXIF_DEBUG
4559 	if (sections_str) {
4560 		exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Sections found: %s", sections_str[0] ? sections_str : "None");
4561 	}
4562 #endif
4563 
4564 	ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE;/* do not inform about in debug*/
4565 
4566 	if (ret == false || (sections_needed && !(sections_needed&ImageInfo.sections_found))) {
4567 		/* array_init must be checked at last! otherwise the array must be freed if a later test fails. */
4568 		exif_discard_imageinfo(&ImageInfo);
4569 	   	EFREE_IF(sections_str);
4570 		RETURN_FALSE;
4571 	}
4572 
4573 	array_init(return_value);
4574 
4575 #ifdef EXIF_DEBUG
4576 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section FILE");
4577 #endif
4578 
4579 	/* now we can add our information */
4580 	exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName",      ImageInfo.FileName);
4581 	exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime",  ImageInfo.FileDateTime);
4582 	exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize",      ImageInfo.FileSize);
4583 	exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType",      ImageInfo.FileType);
4584 	exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType",      (char*)php_image_type_to_mime_type(ImageInfo.FileType));
4585 	exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : "NONE");
4586 
4587 #ifdef EXIF_DEBUG
4588 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Generate section COMPUTED");
4589 #endif
4590 
4591 	if (ImageInfo.Width>0 &&  ImageInfo.Height>0) {
4592 		exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html"   , "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height);
4593 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height);
4594 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width",  ImageInfo.Width);
4595 	}
4596 	exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor);
4597 	if (ImageInfo.motorola_intel != -1) {
4598 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel);
4599 	}
4600 	if (ImageInfo.FocalLength) {
4601 		exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength);
4602 		if(ImageInfo.CCDWidth) {
4603 			exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5));
4604 		}
4605 	}
4606 	if(ImageInfo.CCDWidth) {
4607 		exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth);
4608 	}
4609 	if(ImageInfo.ExposureTime>0) {
4610 		float recip_exposure_time = 0.5f + 1.0f/ImageInfo.ExposureTime;
4611 		if (ImageInfo.ExposureTime <= 0.5 && recip_exposure_time < (float)INT_MAX) {
4612 			exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int) recip_exposure_time);
4613 		} else {
4614 			exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime);
4615 		}
4616 	}
4617 	if(ImageInfo.ApertureFNumber) {
4618 		exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber);
4619 	}
4620 	if(ImageInfo.Distance) {
4621 		if(ImageInfo.Distance<0) {
4622 			exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite");
4623 		} else {
4624 			exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance);
4625 		}
4626 	}
4627 	if (ImageInfo.UserComment) {
4628 		exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment);
4629 		if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) {
4630 			exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding);
4631 		}
4632 	}
4633 
4634 	exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright",              ImageInfo.Copyright);
4635 	exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer);
4636 	exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor",       ImageInfo.CopyrightEditor);
4637 
4638 	for (i=0; i<ImageInfo.xp_fields.count; i++) {
4639 		exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname_debug(ImageInfo.xp_fields.list[i].tag, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value);
4640 	}
4641 	if (ImageInfo.Thumbnail.size) {
4642 		if (read_thumbnail) {
4643 			/* not exif_iif_add_str : this is a buffer */
4644 			exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size);
4645 		}
4646 		if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) {
4647 			/* try to evaluate if thumbnail data is present */
4648 			exif_scan_thumbnail(&ImageInfo);
4649 		}
4650 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype);
4651 		exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype));
4652 	}
4653 	if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) {
4654 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height);
4655 		exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width",  ImageInfo.Thumbnail.width);
4656 	}
4657 	EFREE_IF(sections_str);
4658 
4659 #ifdef EXIF_DEBUG
4660 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Adding image infos");
4661 #endif
4662 
4663 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FILE      );
4664 	add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_COMPUTED  );
4665 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_ANY_TAG   );
4666 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_IFD0      );
4667 	add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_THUMBNAIL );
4668 	add_assoc_image_info(return_value, 1,          &ImageInfo, SECTION_COMMENT   );
4669 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_EXIF      );
4670 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_GPS       );
4671 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_INTEROP   );
4672 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_FPIX      );
4673 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_APP12     );
4674 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_WINXP     );
4675 	add_assoc_image_info(return_value, sub_arrays, &ImageInfo, SECTION_MAKERNOTE );
4676 
4677 #ifdef EXIF_DEBUG
4678 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info");
4679 #endif
4680 
4681 	exif_discard_imageinfo(&ImageInfo);
4682 
4683 #ifdef EXIF_DEBUG
4684 	php_error_docref1(NULL, (Z_TYPE_P(stream) == IS_RESOURCE ? "<stream>" : Z_STRVAL_P(stream)), E_NOTICE, "Done");
4685 #endif
4686 }
4687 /* }}} */
4688 
4689 /* {{{ Reads the embedded thumbnail */
PHP_FUNCTION(exif_thumbnail)4690 PHP_FUNCTION(exif_thumbnail)
4691 {
4692 	bool ret;
4693 	int arg_c = ZEND_NUM_ARGS();
4694 	image_info_type ImageInfo;
4695 	zval *stream;
4696 	zval *z_width = NULL, *z_height = NULL, *z_imagetype = NULL;
4697 
4698 	/* Parse arguments */
4699 	ZEND_PARSE_PARAMETERS_START(1, 4)
4700 		Z_PARAM_ZVAL(stream)
4701 		Z_PARAM_OPTIONAL
4702 		Z_PARAM_ZVAL(z_width)
4703 		Z_PARAM_ZVAL(z_height)
4704 		Z_PARAM_ZVAL(z_imagetype)
4705 	ZEND_PARSE_PARAMETERS_END();
4706 
4707 	memset(&ImageInfo, 0, sizeof(ImageInfo));
4708 
4709 	if (Z_TYPE_P(stream) == IS_RESOURCE) {
4710 		php_stream *p_stream = NULL;
4711 
4712 		php_stream_from_res(p_stream, Z_RES_P(stream));
4713 
4714 		ret = exif_read_from_stream(&ImageInfo, p_stream, 1, 0);
4715 	} else {
4716 		if (!try_convert_to_string(stream)) {
4717 			RETURN_THROWS();
4718 		}
4719 
4720 		if (!Z_STRLEN_P(stream)) {
4721 			zend_argument_value_error(1, "cannot be empty");
4722 			RETURN_THROWS();
4723 		}
4724 
4725 		if (CHECK_NULL_PATH(Z_STRVAL_P(stream), Z_STRLEN_P(stream))) {
4726 			zend_argument_value_error(1, "must not contain any null bytes");
4727 			RETURN_THROWS();
4728 		}
4729 
4730 		ret = exif_read_from_file(&ImageInfo, Z_STRVAL_P(stream), 1, 0);
4731 	}
4732 
4733 	if (ret == false) {
4734 		exif_discard_imageinfo(&ImageInfo);
4735 		RETURN_FALSE;
4736 	}
4737 
4738 #ifdef EXIF_DEBUG
4739 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Thumbnail data %d %d %d, %d x %d", ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.filetype, ImageInfo.Thumbnail.width, ImageInfo.Thumbnail.height);
4740 #endif
4741 	if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) {
4742 		exif_discard_imageinfo(&ImageInfo);
4743 		RETURN_FALSE;
4744 	}
4745 
4746 #ifdef EXIF_DEBUG
4747 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Returning thumbnail(%d)", ImageInfo.Thumbnail.size);
4748 #endif
4749 
4750 	ZVAL_STRINGL(return_value, ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size);
4751 	if (arg_c >= 3) {
4752 		if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) {
4753 			if (!exif_scan_thumbnail(&ImageInfo)) {
4754 				ImageInfo.Thumbnail.width = ImageInfo.Thumbnail.height = 0;
4755 			}
4756 		}
4757 		ZEND_TRY_ASSIGN_REF_LONG(z_width,  ImageInfo.Thumbnail.width);
4758 		ZEND_TRY_ASSIGN_REF_LONG(z_height, ImageInfo.Thumbnail.height);
4759 	}
4760 	if (arg_c >= 4)	{
4761 		ZEND_TRY_ASSIGN_REF_LONG(z_imagetype, ImageInfo.Thumbnail.filetype);
4762 	}
4763 
4764 #ifdef EXIF_DEBUG
4765 	exif_error_docref(NULL EXIFERR_CC, &ImageInfo, E_NOTICE, "Discarding info");
4766 #endif
4767 
4768 	exif_discard_imageinfo(&ImageInfo);
4769 
4770 #ifdef EXIF_DEBUG
4771 	php_error_docref1(NULL, (Z_TYPE_P(stream) == IS_RESOURCE ? "<stream>" : Z_STRVAL_P(stream)), E_NOTICE, "Done");
4772 #endif
4773 }
4774 /* }}} */
4775 
4776 /* {{{ Get the type of an image */
PHP_FUNCTION(exif_imagetype)4777 PHP_FUNCTION(exif_imagetype)
4778 {
4779 	char *imagefile;
4780 	size_t imagefile_len;
4781 	php_stream * stream;
4782 	int itype = 0;
4783 
4784 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &imagefile, &imagefile_len) == FAILURE) {
4785 		RETURN_THROWS();
4786 	}
4787 
4788 	stream = php_stream_open_wrapper(imagefile, "rb", IGNORE_PATH|REPORT_ERRORS, NULL);
4789 
4790 	if (stream == NULL) {
4791 		RETURN_FALSE;
4792 	}
4793 
4794 	itype = php_getimagetype(stream, imagefile, NULL);
4795 
4796 	php_stream_close(stream);
4797 
4798 	if (itype == IMAGE_FILETYPE_UNKNOWN) {
4799 		RETURN_FALSE;
4800 	} else {
4801 		ZVAL_LONG(return_value, itype);
4802 	}
4803 }
4804 /* }}} */
4805