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