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