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