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