Increase the git clone depth.
[platform/upstream/libexif.git] / libexif / exif-data.c
1 /* exif-data.c
2  *
3  * Copyright (c) 2001 Lutz Mueller <lutz@users.sourceforge.net>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA  02110-1301  USA.
19  */
20
21 #include <config.h>
22
23 #include <libexif/exif-mnote-data.h>
24 #include <libexif/exif-data.h>
25 #include <libexif/exif-ifd.h>
26 #include <libexif/exif-mnote-data-priv.h>
27 #include <libexif/exif-utils.h>
28 #include <libexif/exif-loader.h>
29 #include <libexif/exif-log.h>
30 #include <libexif/i18n.h>
31 #include <libexif/exif-system.h>
32
33 #include <libexif/canon/exif-mnote-data-canon.h>
34 #include <libexif/fuji/exif-mnote-data-fuji.h>
35 #include <libexif/olympus/exif-mnote-data-olympus.h>
36 #include <libexif/pentax/exif-mnote-data-pentax.h>
37
38 #include <math.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42
43 #undef JPEG_MARKER_SOI
44 #define JPEG_MARKER_SOI  0xd8
45 #undef JPEG_MARKER_APP0
46 #define JPEG_MARKER_APP0 0xe0
47 #undef JPEG_MARKER_APP1
48 #define JPEG_MARKER_APP1 0xe1
49
50 static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
51
52 struct _ExifDataPrivate
53 {
54         ExifByteOrder order;
55
56         ExifMnoteData *md;
57
58         ExifLog *log;
59         ExifMem *mem;
60
61         unsigned int ref_count;
62
63         /* Temporarily used while loading data */
64         unsigned int offset_mnote;
65
66         ExifDataOption options;
67         ExifDataType data_type;
68 };
69
70 static void *
71 exif_data_alloc (ExifData *data, unsigned int i)
72 {
73         void *d;
74
75         if (!data || !i) 
76                 return NULL;
77
78         d = exif_mem_alloc (data->priv->mem, i);
79         if (d) 
80                 return d;
81
82         EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", i);
83         return NULL;
84 }
85
86 ExifMnoteData *
87 exif_data_get_mnote_data (ExifData *d)
88 {
89         return (d && d->priv) ? d->priv->md : NULL;
90 }
91
92 ExifData *
93 exif_data_new (void)
94 {
95         ExifMem *mem = exif_mem_new_default ();
96         ExifData *d = exif_data_new_mem (mem);
97
98         exif_mem_unref (mem);
99
100         return d;
101 }
102
103 ExifData *
104 exif_data_new_mem (ExifMem *mem)
105 {
106         ExifData *data;
107         unsigned int i;
108
109         if (!mem) 
110                 return NULL;
111
112         data = exif_mem_alloc (mem, sizeof (ExifData));
113         if (!data) 
114                 return (NULL);
115         data->priv = exif_mem_alloc (mem, sizeof (ExifDataPrivate));
116         if (!data->priv) { 
117                 exif_mem_free (mem, data); 
118                 return (NULL); 
119         }
120         data->priv->ref_count = 1;
121
122         data->priv->mem = mem;
123         exif_mem_ref (mem);
124
125         for (i = 0; i < EXIF_IFD_COUNT; i++) {
126                 data->ifd[i] = exif_content_new_mem (data->priv->mem);
127                 if (!data->ifd[i]) {
128                         exif_data_free (data);
129                         return (NULL);
130                 }
131                 data->ifd[i]->parent = data;
132         }
133
134         /* Default options */
135 #ifndef NO_VERBOSE_TAG_STRINGS
136         /*
137          * When the tag list is compiled away, setting this option prevents
138          * any tags from being loaded
139          */
140         exif_data_set_option (data, EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS);
141 #endif
142         exif_data_set_option (data, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION);
143
144         /* Default data type: none */
145         exif_data_set_data_type (data, EXIF_DATA_TYPE_COUNT);
146
147         return (data);
148 }
149
150 ExifData *
151 exif_data_new_from_data (const unsigned char *data, unsigned int size)
152 {
153         ExifData *edata;
154
155         edata = exif_data_new ();
156         exif_data_load_data (edata, data, size);
157         return (edata);
158 }
159
160 static int
161 exif_data_load_data_entry (ExifData *data, ExifEntry *entry,
162                            const unsigned char *d,
163                            unsigned int size, unsigned int offset)
164 {
165         unsigned int s, doff;
166
167         entry->tag        = exif_get_short (d + offset + 0, data->priv->order);
168         entry->format     = exif_get_short (d + offset + 2, data->priv->order);
169         entry->components = exif_get_long  (d + offset + 4, data->priv->order);
170
171         /* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent 
172          * has not been set yet
173          */
174         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
175                   "Loading entry 0x%x ('%s')...", entry->tag,
176                   exif_tag_get_name (entry->tag));
177
178         /* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } 
179          *   -> { 0x000000000 .. 0x7fffffff8 } */
180         s = exif_format_get_size(entry->format) * entry->components;
181         if ((s < entry->components) || (s == 0)){
182                 return 0;
183         }
184
185         /*
186          * Size? If bigger than 4 bytes, the actual data is not
187          * in the entry but somewhere else (offset).
188          */
189         if (s > 4)
190                 doff = exif_get_long (d + offset + 8, data->priv->order);
191         else
192                 doff = offset + 8;
193
194         /* Sanity checks */
195         if ((doff + s < doff) || (doff + s < s) || (doff + s > size)) {
196                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
197                                   "Tag data past end of buffer (%u > %u)", doff+s, size);       
198                 return 0;
199         }
200
201         entry->data = exif_data_alloc (data, s);
202         if (entry->data) {
203                 entry->size = s;
204                 memcpy (entry->data, d + doff, s);
205         } else {
206                 EXIF_LOG_NO_MEMORY(data->priv->log, "ExifData", s);
207                 return 0;
208         }
209
210         /* If this is the MakerNote, remember the offset */
211         if (entry->tag == EXIF_TAG_MAKER_NOTE) {
212                 if (!entry->data) {
213                         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
214                                           "MakerNote found with empty data");   
215                 } else if (entry->size > 6) {
216                         exif_log (data->priv->log,
217                                                EXIF_LOG_CODE_DEBUG, "ExifData",
218                                                "MakerNote found (%02x %02x %02x %02x "
219                                                "%02x %02x %02x...).",
220                                                entry->data[0], entry->data[1], entry->data[2],
221                                                entry->data[3], entry->data[4], entry->data[5],
222                                                entry->data[6]);
223                 }
224                 data->priv->offset_mnote = doff;
225         }
226         return 1;
227 }
228
229 static void
230 exif_data_save_data_entry (ExifData *data, ExifEntry *e,
231                            unsigned char **d, unsigned int *ds,
232                            unsigned int offset)
233 {
234         unsigned int doff, s;
235         unsigned int ts;
236
237         if (!data || !data->priv) 
238                 return;
239
240         /*
241          * Each entry is 12 bytes long. The memory for the entry has
242          * already been allocated.
243          */
244         exif_set_short (*d + 6 + offset + 0,
245                         data->priv->order, (ExifShort) e->tag);
246         exif_set_short (*d + 6 + offset + 2,
247                         data->priv->order, (ExifShort) e->format);
248
249         if (!(data->priv->options & EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE)) {
250                 /* If this is the maker note tag, update it. */
251                 if ((e->tag == EXIF_TAG_MAKER_NOTE) && data->priv->md) {
252                         /* TODO: this is using the wrong ExifMem to free e->data */
253                         exif_mem_free (data->priv->mem, e->data);
254                         e->data = NULL;
255                         e->size = 0;
256                         exif_mnote_data_set_offset (data->priv->md, *ds - 6);
257                         exif_mnote_data_save (data->priv->md, &e->data, &e->size);
258                         e->components = e->size;
259                         if (exif_format_get_size (e->format) != 1) {
260                                 /* e->format is taken from input code,
261                                  * but we need to make sure it is a 1 byte
262                                  * entity due to the multiplication below. */
263                                 e->format = EXIF_FORMAT_UNDEFINED;
264                         }
265                 }
266         }
267
268         exif_set_long  (*d + 6 + offset + 4,
269                         data->priv->order, e->components);
270
271         /*
272          * Size? If bigger than 4 bytes, the actual data is not in
273          * the entry but somewhere else.
274          */
275         s = exif_format_get_size (e->format) * e->components;
276         if (s > 4) {
277                 unsigned char *t;
278                 doff = *ds - 6;
279                 ts = *ds + s;
280
281                 /*
282                  * According to the TIFF specification,
283                  * the offset must be an even number. If we need to introduce
284                  * a padding byte, we set it to 0.
285                  */
286                 if (s & 1)
287                         ts++;
288                 t = exif_mem_realloc (data->priv->mem, *d, ts);
289                 if (!t) {
290                         EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts);
291                         return;
292                 }
293                 *d = t;
294                 *ds = ts;
295                 exif_set_long (*d + 6 + offset + 8, data->priv->order, doff);
296                 if (s & 1) 
297                         *(*d + *ds - 1) = '\0';
298
299         } else
300                 doff = offset + 8;
301
302         /* Write the data. Fill unneeded bytes with 0. Do not crash with
303          * e->data is NULL */
304         if (e->data) {
305                 memcpy (*d + 6 + doff, e->data, s);
306         } else {
307                 memset (*d + 6 + doff, 0, s);
308         }
309         if (s < 4) 
310                 memset (*d + 6 + doff + s, 0, (4 - s));
311 }
312
313 static void
314 exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,
315                                unsigned int ds, ExifLong o, ExifLong s)
316 {
317         /* Sanity checks */
318         if ((o + s < o) || (o + s < s) || (o + s > ds) || (o > ds)) {
319                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
320                           "Bogus thumbnail offset (%u) or size (%u).",
321                           o, s);
322                 return;
323         }
324
325         if (data->data) 
326                 exif_mem_free (data->priv->mem, data->data);
327         if (!(data->data = exif_data_alloc (data, s))) {
328                 EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", s);
329                 data->size = 0;
330                 return;
331         }
332         data->size = s;
333         memcpy (data->data, d + o, s);
334 }
335
336 #undef CHECK_REC
337 #define CHECK_REC(i)                                    \
338 if ((i) == ifd) {                               \
339         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \
340                 "ExifData", "Recursive entry in IFD "   \
341                 "'%s' detected. Skipping...",           \
342                 exif_ifd_get_name (i));                 \
343         break;                                          \
344 }                                                       \
345 if (data->ifd[(i)]->count) {                            \
346         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \
347                 "ExifData", "Attempt to load IFD "      \
348                 "'%s' multiple times detected. "        \
349                 "Skipping...",                          \
350                 exif_ifd_get_name (i));                 \
351         break;                                          \
352 }
353
354 /*! Calculate the recursion cost added by one level of IFD loading.
355  *
356  * The work performed is related to the cost in the exponential relation
357  *   work=1.1**cost
358  */
359 static unsigned int
360 level_cost(unsigned int n)
361 {
362     static const double log_1_1 = 0.09531017980432493;
363
364         /* Adding 0.1 protects against the case where n==1 */
365         return ceil(log(n + 0.1)/log_1_1);
366 }
367
368 /*! Load data for an IFD.
369  *
370  * \param[in,out] data #ExifData
371  * \param[in] ifd IFD to load
372  * \param[in] d pointer to buffer containing raw IFD data
373  * \param[in] ds size of raw data in buffer at \c d
374  * \param[in] offset offset into buffer at \c d at which IFD starts
375  * \param[in] recursion_cost factor indicating how expensive this recursive
376  * call could be
377  */
378 static void
379 exif_data_load_data_content (ExifData *data, ExifIfd ifd,
380                              const unsigned char *d,
381                              unsigned int ds, unsigned int offset, unsigned int recursion_cost)
382 {
383         ExifLong o, thumbnail_offset = 0, thumbnail_length = 0;
384         ExifShort n;
385         ExifEntry *entry;
386         unsigned int i;
387         ExifTag tag;
388
389         if (!data || !data->priv) 
390                 return;
391
392         /* check for valid ExifIfd enum range */
393         if ((((int)ifd) < 0) || ( ((int)ifd) >= EXIF_IFD_COUNT))
394           return;
395
396         if (recursion_cost > 170) {
397                 /*
398                  * recursion_cost is a logarithmic-scale indicator of how expensive this
399                  * recursive call might end up being. It is an indicator of the depth of
400                  * recursion as well as the potential for worst-case future recursive
401                  * calls. Since it's difficult to tell ahead of time how often recursion
402                  * will occur, this assumes the worst by assuming every tag could end up
403                  * causing recursion.
404                  * The value of 170 was chosen to limit typical EXIF structures to a
405                  * recursive depth of about 6, but pathological ones (those with very
406                  * many tags) to only 2.
407                  */
408                 exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData",
409                           "Deep/expensive recursion detected!");
410                 return;
411         }
412
413         /* Read the number of entries */
414         if ((offset + 2 < offset) || (offset + 2 < 2) || (offset + 2 > ds)) {
415                 exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData",
416                           "Tag data past end of buffer (%u > %u)", offset+2, ds);
417                 return;
418         }
419         n = exif_get_short (d + offset, data->priv->order);
420         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
421                   "Loading %hu entries...", n);
422         offset += 2;
423
424         /* Check if we have enough data. */
425         if (offset + 12 * n > ds) {
426                 n = (ds - offset) / 12;
427                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
428                                   "Short data; only loading %hu entries...", n);
429         }
430
431         for (i = 0; i < n; i++) {
432
433                 tag = exif_get_short (d + offset + 12 * i, data->priv->order);
434                 switch (tag) {
435                 case EXIF_TAG_EXIF_IFD_POINTER:
436                 case EXIF_TAG_GPS_INFO_IFD_POINTER:
437                 case EXIF_TAG_INTEROPERABILITY_IFD_POINTER:
438                 case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH:
439                 case EXIF_TAG_JPEG_INTERCHANGE_FORMAT:
440                         o = exif_get_long (d + offset + 12 * i + 8,
441                                            data->priv->order);
442                         /* FIXME: IFD_POINTER tags aren't marked as being in a
443                          * specific IFD, so exif_tag_get_name_in_ifd won't work
444                          */
445                         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
446                                   "Sub-IFD entry 0x%x ('%s') at %u.", tag,
447                                   exif_tag_get_name(tag), o);
448                         switch (tag) {
449                         case EXIF_TAG_EXIF_IFD_POINTER:
450                                 CHECK_REC (EXIF_IFD_EXIF);
451                                 exif_data_load_data_content (data, EXIF_IFD_EXIF, d, ds, o,
452                                         recursion_cost + level_cost(n));
453                                 break;
454                         case EXIF_TAG_GPS_INFO_IFD_POINTER:
455                                 CHECK_REC (EXIF_IFD_GPS);
456                                 exif_data_load_data_content (data, EXIF_IFD_GPS, d, ds, o,
457                                         recursion_cost + level_cost(n));
458                                 break;
459                         case EXIF_TAG_INTEROPERABILITY_IFD_POINTER:
460                                 CHECK_REC (EXIF_IFD_INTEROPERABILITY);
461                                 exif_data_load_data_content (data, EXIF_IFD_INTEROPERABILITY, d, ds, o,
462                                         recursion_cost + level_cost(n));
463                                 break;
464                         case EXIF_TAG_JPEG_INTERCHANGE_FORMAT:
465                                 thumbnail_offset = o;
466                                 if (thumbnail_offset && thumbnail_length)
467                                         exif_data_load_data_thumbnail (data, d,
468                                                                        ds, thumbnail_offset,
469                                                                        thumbnail_length);
470                                 break;
471                         case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH:
472                                 thumbnail_length = o;
473                                 if (thumbnail_offset && thumbnail_length)
474                                         exif_data_load_data_thumbnail (data, d,
475                                                                        ds, thumbnail_offset,
476                                                                        thumbnail_length);
477                                 break;
478                         default:
479                                 return;
480                         }
481                         break;
482                 default:
483
484                         /*
485                          * If we don't know the tag, don't fail. It could be that new 
486                          * versions of the standard have defined additional tags. Note that
487                          * 0 is a valid tag in the GPS IFD.
488                          */
489                         if (!exif_tag_get_name_in_ifd (tag, ifd)) {
490
491                                 /*
492                                  * Special case: Tag and format 0. That's against specification
493                                  * (at least up to 2.2). But Photoshop writes it anyways.
494                                  */
495                                 if (!memcmp (d + offset + 12 * i, "\0\0\0\0", 4)) {
496                                         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
497                                                   "Skipping empty entry at position %u in '%s'.", i, 
498                                                   exif_ifd_get_name (ifd));
499                                         break;
500                                 }
501                                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
502                                           "Unknown tag 0x%04x (entry %u in '%s'). Please report this tag "
503                                           "to <libexif-devel@lists.sourceforge.net>.", tag, i,
504                                           exif_ifd_get_name (ifd));
505                                 if (data->priv->options & EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS)
506                                         break;
507                         }
508                         entry = exif_entry_new_mem (data->priv->mem);
509                         if (!entry) {
510                                   exif_log (data->priv->log, EXIF_LOG_CODE_NO_MEMORY, "ExifData",
511                                           "Could not allocate memory");
512                                   return;
513                         }
514                         if (exif_data_load_data_entry (data, entry, d, ds,
515                                                    offset + 12 * i))
516                                 exif_content_add_entry (data->ifd[ifd], entry);
517                         exif_entry_unref (entry);
518                         break;
519                 }
520         }
521 }
522
523 static int
524 cmp_func (const unsigned char *p1, const unsigned char *p2, ExifByteOrder o)
525 {
526         ExifShort tag1 = exif_get_short (p1, o);
527         ExifShort tag2 = exif_get_short (p2, o);
528
529         return (tag1 < tag2) ? -1 : (tag1 > tag2) ? 1 : 0;
530 }
531
532 static int
533 cmp_func_intel (const void *elem1, const void *elem2)
534 {
535         return cmp_func ((const unsigned char *) elem1,
536                          (const unsigned char *) elem2, EXIF_BYTE_ORDER_INTEL);
537 }
538
539 static int
540 cmp_func_motorola (const void *elem1, const void *elem2)
541 {
542         return cmp_func ((const unsigned char *) elem1,
543                          (const unsigned char *) elem2, EXIF_BYTE_ORDER_MOTOROLA);
544 }
545
546 static void
547 exif_data_save_data_content (ExifData *data, ExifContent *ifd,
548                              unsigned char **d, unsigned int *ds,
549                              unsigned int offset)
550 {
551         unsigned int j, n_ptr = 0, n_thumb = 0;
552         ExifIfd i;
553         unsigned char *t;
554         unsigned int ts;
555
556         if (!data || !data->priv || !ifd || !d || !ds) 
557                 return;
558
559         for (i = 0; i < EXIF_IFD_COUNT; i++)
560                 if (ifd == data->ifd[i])
561                         break;
562         if (i == EXIF_IFD_COUNT)
563                 return; /* error */
564
565         /*
566          * Check if we need some extra entries for pointers or the thumbnail.
567          */
568         switch (i) {
569         case EXIF_IFD_0:
570
571                 /*
572                  * The pointer to IFD_EXIF is in IFD_0. The pointer to
573                  * IFD_INTEROPERABILITY is in IFD_EXIF.
574                  */
575                 if (data->ifd[EXIF_IFD_EXIF]->count ||
576                     data->ifd[EXIF_IFD_INTEROPERABILITY]->count)
577                         n_ptr++;
578
579                 /* The pointer to IFD_GPS is in IFD_0. */
580                 if (data->ifd[EXIF_IFD_GPS]->count)
581                         n_ptr++;
582
583                 break;
584         case EXIF_IFD_1:
585                 if (data->size)
586                         n_thumb = 2;
587                 break;
588         case EXIF_IFD_EXIF:
589                 if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count)
590                         n_ptr++;
591         default:
592                 break;
593         }
594
595         /*
596          * Allocate enough memory for all entries
597          * and the number of entries.
598          */
599         ts = *ds + (2 + (ifd->count + n_ptr + n_thumb) * 12 + 4);
600         t = exif_mem_realloc (data->priv->mem, *d, ts);
601         if (!t) {
602                 EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts);
603                 return;
604         }
605         *d = t;
606         *ds = ts;
607
608         /* Save the number of entries */
609         exif_set_short (*d + 6 + offset, data->priv->order,
610                         (ExifShort) (ifd->count + n_ptr + n_thumb));
611         offset += 2;
612
613         /*
614          * Save each entry. Make sure that no memcpys from NULL pointers are
615          * performed
616          */
617         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
618                   "Saving %i entries (IFD '%s', offset: %i)...",
619                   ifd->count, exif_ifd_get_name (i), offset);
620         for (j = 0; j < ifd->count; j++) {
621                 if (ifd->entries[j]) {
622                         exif_data_save_data_entry (data, ifd->entries[j], d, ds,
623                                 offset + 12 * j);
624                 }
625         }
626
627         offset += 12 * ifd->count;
628
629         /* Now save special entries. */
630         switch (i) {
631         case EXIF_IFD_0:
632
633                 /*
634                  * The pointer to IFD_EXIF is in IFD_0.
635                  * However, the pointer to IFD_INTEROPERABILITY is in IFD_EXIF,
636                  * therefore, if IFD_INTEROPERABILITY is not empty, we need
637                  * IFD_EXIF even if latter is empty.
638                  */
639                 if (data->ifd[EXIF_IFD_EXIF]->count ||
640                     data->ifd[EXIF_IFD_INTEROPERABILITY]->count) {
641                         exif_set_short (*d + 6 + offset + 0, data->priv->order,
642                                         EXIF_TAG_EXIF_IFD_POINTER);
643                         exif_set_short (*d + 6 + offset + 2, data->priv->order,
644                                         EXIF_FORMAT_LONG);
645                         exif_set_long  (*d + 6 + offset + 4, data->priv->order,
646                                         1);
647                         exif_set_long  (*d + 6 + offset + 8, data->priv->order,
648                                         *ds - 6);
649                         exif_data_save_data_content (data,
650                                                      data->ifd[EXIF_IFD_EXIF], d, ds, *ds - 6);
651                         offset += 12;
652                 }
653
654                 /* The pointer to IFD_GPS is in IFD_0, too. */
655                 if (data->ifd[EXIF_IFD_GPS]->count) {
656                         exif_set_short (*d + 6 + offset + 0, data->priv->order,
657                                         EXIF_TAG_GPS_INFO_IFD_POINTER);
658                         exif_set_short (*d + 6 + offset + 2, data->priv->order,
659                                         EXIF_FORMAT_LONG);
660                         exif_set_long  (*d + 6 + offset + 4, data->priv->order,
661                                         1);
662                         exif_set_long  (*d + 6 + offset + 8, data->priv->order,
663                                         *ds - 6);
664                         exif_data_save_data_content (data,
665                                                      data->ifd[EXIF_IFD_GPS], d, ds, *ds - 6);
666                         offset += 12;
667                 }
668
669                 break;
670         case EXIF_IFD_EXIF:
671
672                 /*
673                  * The pointer to IFD_INTEROPERABILITY is in IFD_EXIF.
674                  * See note above.
675                  */
676                 if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count) {
677                         exif_set_short (*d + 6 + offset + 0, data->priv->order,
678                                         EXIF_TAG_INTEROPERABILITY_IFD_POINTER);
679                         exif_set_short (*d + 6 + offset + 2, data->priv->order,
680                                         EXIF_FORMAT_LONG);
681                         exif_set_long  (*d + 6 + offset + 4, data->priv->order,
682                                         1);
683                         exif_set_long  (*d + 6 + offset + 8, data->priv->order,
684                                         *ds - 6);
685                         exif_data_save_data_content (data,
686                                                      data->ifd[EXIF_IFD_INTEROPERABILITY], d, ds,
687                                                      *ds - 6);
688                         offset += 12;
689                 }
690
691                 break;
692         case EXIF_IFD_1:
693
694                 /*
695                  * Information about the thumbnail (if any) is saved in
696                  * IFD_1.
697                  */
698                 if (data->size) {
699
700                         /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT */
701                         exif_set_short (*d + 6 + offset + 0, data->priv->order,
702                                         EXIF_TAG_JPEG_INTERCHANGE_FORMAT);
703                         exif_set_short (*d + 6 + offset + 2, data->priv->order,
704                                         EXIF_FORMAT_LONG);
705                         exif_set_long  (*d + 6 + offset + 4, data->priv->order,
706                                         1);
707                         exif_set_long  (*d + 6 + offset + 8, data->priv->order,
708                                         *ds - 6);
709                         ts = *ds + data->size;
710                         t = exif_mem_realloc (data->priv->mem, *d, ts);
711                         if (!t) {
712                                 EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData",
713                                                     ts);
714                                 return;
715                         }
716                         *d = t;
717                         *ds = ts;
718                         memcpy (*d + *ds - data->size, data->data, data->size);
719                         offset += 12;
720
721                         /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH */
722                         exif_set_short (*d + 6 + offset + 0, data->priv->order,
723                                         EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
724                         exif_set_short (*d + 6 + offset + 2, data->priv->order,
725                                         EXIF_FORMAT_LONG);
726                         exif_set_long  (*d + 6 + offset + 4, data->priv->order,
727                                         1);
728                         exif_set_long  (*d + 6 + offset + 8, data->priv->order,
729                                         data->size);
730                         offset += 12;
731                 }
732
733                 break;
734         default:
735                 break;
736         }
737
738         /* Sort the directory according to TIFF specification */
739         qsort (*d + 6 + offset - (ifd->count + n_ptr + n_thumb) * 12,
740                (ifd->count + n_ptr + n_thumb), 12,
741                (data->priv->order == EXIF_BYTE_ORDER_INTEL) ? cmp_func_intel : cmp_func_motorola);
742
743         /* Correctly terminate the directory */
744         if (i == EXIF_IFD_0 && (data->ifd[EXIF_IFD_1]->count ||
745                                 data->size)) {
746
747                 /*
748                  * We are saving IFD 0. Tell where IFD 1 starts and save
749                  * IFD 1.
750                  */
751                 exif_set_long (*d + 6 + offset, data->priv->order, *ds - 6);
752                 exif_data_save_data_content (data, data->ifd[EXIF_IFD_1], d, ds,
753                                              *ds - 6);
754         } else
755                 exif_set_long (*d + 6 + offset, data->priv->order, 0);
756 }
757
758 typedef enum {
759         EXIF_DATA_TYPE_MAKER_NOTE_NONE          = 0,
760         EXIF_DATA_TYPE_MAKER_NOTE_CANON         = 1,
761         EXIF_DATA_TYPE_MAKER_NOTE_OLYMPUS       = 2,
762         EXIF_DATA_TYPE_MAKER_NOTE_PENTAX        = 3,
763         EXIF_DATA_TYPE_MAKER_NOTE_NIKON         = 4,
764         EXIF_DATA_TYPE_MAKER_NOTE_CASIO         = 5,
765         EXIF_DATA_TYPE_MAKER_NOTE_FUJI          = 6
766 } ExifDataTypeMakerNote;
767
768 /*! If MakerNote is recognized, load it.
769  *
770  * \param[in,out] data #ExifData
771  * \param[in] d pointer to raw EXIF data
772  * \param[in] ds length of data at d
773  */
774 static void
775 interpret_maker_note(ExifData *data, const unsigned char *d, unsigned int ds)
776 {
777         int mnoteid;
778         ExifEntry* e = exif_data_get_entry (data, EXIF_TAG_MAKER_NOTE);
779         if (!e)
780                 return;
781         
782         if ((mnoteid = exif_mnote_data_olympus_identify (data, e)) != 0) {
783                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG,
784                         "ExifData", "Olympus MakerNote variant type %d", mnoteid);
785                 data->priv->md = exif_mnote_data_olympus_new (data->priv->mem);
786
787         } else if ((mnoteid = exif_mnote_data_canon_identify (data, e)) != 0) {
788                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG,
789                         "ExifData", "Canon MakerNote variant type %d", mnoteid);
790                 data->priv->md = exif_mnote_data_canon_new (data->priv->mem, data->priv->options);
791
792         } else if ((mnoteid = exif_mnote_data_fuji_identify (data, e)) != 0) {
793                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG,
794                         "ExifData", "Fuji MakerNote variant type %d", mnoteid);
795                 data->priv->md = exif_mnote_data_fuji_new (data->priv->mem);
796
797         /* NOTE: Must do Pentax detection last because some of the
798          * heuristics are pretty general. */
799         } else if ((mnoteid = exif_mnote_data_pentax_identify (data, e)) != 0) {
800                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG,
801                         "ExifData", "Pentax MakerNote variant type %d", mnoteid);
802                 data->priv->md = exif_mnote_data_pentax_new (data->priv->mem);
803         }
804
805         /* 
806          * If we are able to interpret the maker note, do so.
807          */
808         if (data->priv->md) {
809                 exif_mnote_data_log (data->priv->md, data->priv->log);
810                 exif_mnote_data_set_byte_order (data->priv->md,
811                                                 data->priv->order);
812                 exif_mnote_data_set_offset (data->priv->md,
813                                             data->priv->offset_mnote);
814                 exif_mnote_data_load (data->priv->md, d, ds);
815         }
816 }
817
818 #define LOG_TOO_SMALL \
819 exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", \
820                 _("Size of data too small to allow for EXIF data."));
821
822 void
823 exif_data_load_data (ExifData *data, const unsigned char *d_orig,
824                      unsigned int ds)
825 {
826         unsigned int l;
827         ExifLong offset;
828         ExifShort n;
829         const unsigned char *d = d_orig;
830         unsigned int len, fullds;
831
832         if (!data || !data->priv || !d || !ds)
833                 return;
834
835         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
836                   "Parsing %i byte(s) EXIF data...\n", ds);
837
838         /*
839          * It can be that the data starts with the EXIF header. If it does
840          * not, search the EXIF marker.
841          */
842         if (ds < 6) {
843                 LOG_TOO_SMALL;
844                 return;
845         }
846         if (!memcmp (d, ExifHeader, 6)) {
847                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
848                           "Found EXIF header at start.");
849         } else {
850                 while (ds >= 3) {
851                         while (ds && (d[0] == 0xff)) {
852                                 d++;
853                                 ds--;
854                         }
855
856                         /* JPEG_MARKER_SOI */
857                         if (ds && d[0] == JPEG_MARKER_SOI) {
858                                 d++;
859                                 ds--;
860                                 continue;
861                         }
862
863                         /* JPEG_MARKER_APP1 */
864                         if (ds && d[0] == JPEG_MARKER_APP1)
865                                 break;
866
867                         /* Skip irrelevant APP markers. The branch for APP1 must come before this,
868                            otherwise this code block will cause APP1 to be skipped. This code path
869                            is only relevant for files that are nonconformant to the EXIF
870                            specification. For conformant files, the APP1 code path above will be
871                            taken. */
872                         if (ds >= 3 && d[0] >= 0xe0 && d[0] <= 0xef) {  /* JPEG_MARKER_APPn */
873                                 d++;
874                                 ds--;
875                                 l = (d[0] << 8) | d[1];
876                                 if (l > ds)
877                                         return;
878                                 d += l;
879                                 ds -= l;
880                                 continue;
881                         }
882
883                         /* Unknown marker or data. Give up. */
884                         exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,
885                                   "ExifData", _("EXIF marker not found."));
886                         return;
887                 }
888                 if (ds < 3) {
889                         LOG_TOO_SMALL;
890                         return;
891                 }
892                 d++;
893                 ds--;
894                 len = (d[0] << 8) | d[1];
895                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
896                           "We have to deal with %i byte(s) of EXIF data.",
897                           len);
898                 d += 2;
899                 ds -= 2;
900         }
901
902         /*
903          * Verify the exif header
904          * (offset 2, length 6).
905          */
906         if (ds < 6) {
907                 LOG_TOO_SMALL;
908                 return;
909         }
910         if (memcmp (d, ExifHeader, 6)) {
911                 exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,
912                           "ExifData", _("EXIF header not found."));
913                 return;
914         }
915
916         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
917                   "Found EXIF header.");
918
919         /* Sanity check the data length */
920         if (ds < 14)
921                 return;
922
923         /* The JPEG APP1 section can be no longer than 64 KiB (including a
924            16-bit length), so cap the data length to protect against overflow
925            in future offset calculations */
926         fullds = ds;
927         if (ds > 0xfffe)
928                 ds = 0xfffe;
929
930         /* Byte order (offset 6, length 2) */
931         if (!memcmp (d + 6, "II", 2))
932                 data->priv->order = EXIF_BYTE_ORDER_INTEL;
933         else if (!memcmp (d + 6, "MM", 2))
934                 data->priv->order = EXIF_BYTE_ORDER_MOTOROLA;
935         else {
936                 exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,
937                           "ExifData", _("Unknown encoding."));
938                 return;
939         }
940
941         /* Fixed value */
942         if (exif_get_short (d + 8, data->priv->order) != 0x002a)
943                 return;
944
945         /* IFD 0 offset */
946         offset = exif_get_long (d + 10, data->priv->order);
947         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", 
948                   "IFD 0 at %i.", (int) offset);
949
950         /* Sanity check the offset, being careful about overflow */
951         if (offset > ds || offset + 6 + 2 > ds)
952                 return;
953
954         /* Parse the actual exif data (usually offset 14 from start) */
955         exif_data_load_data_content (data, EXIF_IFD_0, d + 6, ds - 6, offset, 0);
956
957         /* IFD 1 offset */
958         n = exif_get_short (d + 6 + offset, data->priv->order);
959         if (offset + 6 + 2 + 12 * n + 4 > ds)
960                 return;
961
962         offset = exif_get_long (d + 6 + offset + 2 + 12 * n, data->priv->order);
963         if (offset) {
964                 exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
965                           "IFD 1 at %i.", (int) offset);
966
967                 /* Sanity check. */
968                 if (offset > ds || offset + 6 > ds) {
969                         exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA,
970                                   "ExifData", "Bogus offset of IFD1.");
971                 } else {
972                    exif_data_load_data_content (data, EXIF_IFD_1, d + 6, ds - 6, offset, 0);
973                 }
974         }
975
976         /*
977          * If we got an EXIF_TAG_MAKER_NOTE, try to interpret it. Some
978          * cameras use pointers in the maker note tag that point to the
979          * space between IFDs. Here is the only place where we have access
980          * to that data.
981          */
982         interpret_maker_note(data, d, fullds);
983
984         /* Fixup tags if requested */
985         if (data->priv->options & EXIF_DATA_OPTION_FOLLOW_SPECIFICATION)
986                 exif_data_fix (data);
987 }
988
989 void
990 exif_data_save_data (ExifData *data, unsigned char **d, unsigned int *ds)
991 {
992         if (ds)
993                 *ds = 0;        /* This means something went wrong */
994
995         if (!data || !d || !ds)
996                 return;
997
998         /* Header */
999         *ds = 14;
1000         *d = exif_data_alloc (data, *ds);
1001         if (!*d)  {
1002                 *ds = 0;
1003                 return;
1004         }
1005         memcpy (*d, ExifHeader, 6);
1006
1007         /* Order (offset 6) */
1008         if (data->priv->order == EXIF_BYTE_ORDER_INTEL) {
1009                 memcpy (*d + 6, "II", 2);
1010         } else {
1011                 memcpy (*d + 6, "MM", 2);
1012         }
1013
1014         /* Fixed value (2 bytes, offset 8) */
1015         exif_set_short (*d + 8, data->priv->order, 0x002a);
1016
1017         /*
1018          * IFD 0 offset (4 bytes, offset 10).
1019          * We will start 8 bytes after the
1020          * EXIF header (2 bytes for order, another 2 for the test, and
1021          * 4 bytes for the IFD 0 offset make 8 bytes together).
1022          */
1023         exif_set_long (*d + 10, data->priv->order, 8);
1024
1025         /* Now save IFD 0. IFD 1 will be saved automatically. */
1026         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
1027                   "Saving IFDs...");
1028         exif_data_save_data_content (data, data->ifd[EXIF_IFD_0], d, ds,
1029                                      *ds - 6);
1030         exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData",
1031                   "Saved %i byte(s) EXIF data.", *ds);
1032 }
1033
1034 ExifData *
1035 exif_data_new_from_file (const char *path)
1036 {
1037         ExifData *edata;
1038         ExifLoader *loader;
1039
1040         loader = exif_loader_new ();
1041         exif_loader_write_file (loader, path);
1042         edata = exif_loader_get_data (loader);
1043         exif_loader_unref (loader);
1044
1045         return (edata);
1046 }
1047
1048 void
1049 exif_data_ref (ExifData *data)
1050 {
1051         if (!data)
1052                 return;
1053
1054         data->priv->ref_count++;
1055 }
1056
1057 void
1058 exif_data_unref (ExifData *data)
1059 {
1060         if (!data) 
1061                 return;
1062
1063         data->priv->ref_count--;
1064         if (!data->priv->ref_count) 
1065                 exif_data_free (data);
1066 }
1067
1068 void
1069 exif_data_free (ExifData *data)
1070 {
1071         unsigned int i;
1072         ExifMem *mem = (data && data->priv) ? data->priv->mem : NULL;
1073
1074         if (!data) 
1075                 return;
1076
1077         for (i = 0; i < EXIF_IFD_COUNT; i++) {
1078                 if (data->ifd[i]) {
1079                         exif_content_unref (data->ifd[i]);
1080                         data->ifd[i] = NULL;
1081                 }
1082         }
1083
1084         if (data->data) {
1085                 exif_mem_free (mem, data->data);
1086                 data->data = NULL;
1087         }
1088
1089         if (data->priv) {
1090                 if (data->priv->log) {
1091                         exif_log_unref (data->priv->log);
1092                         data->priv->log = NULL;
1093                 }
1094                 if (data->priv->md) {
1095                         exif_mnote_data_unref (data->priv->md);
1096                         data->priv->md = NULL;
1097                 }
1098                 exif_mem_free (mem, data->priv);
1099                 exif_mem_free (mem, data);
1100         }
1101
1102         exif_mem_unref (mem);
1103 }
1104
1105 void
1106 exif_data_dump (ExifData *data)
1107 {
1108         unsigned int i;
1109
1110         if (!data)
1111                 return;
1112
1113         for (i = 0; i < EXIF_IFD_COUNT; i++) {
1114                 if (data->ifd[i] && data->ifd[i]->count) {
1115                         printf ("Dumping IFD '%s'...\n",
1116                                 exif_ifd_get_name (i));
1117                         exif_content_dump (data->ifd[i], 0);
1118                 }
1119         }
1120
1121         if (data->data) {
1122                 printf ("%i byte(s) thumbnail data available: ", data->size);
1123                 if (data->size >= 4) {
1124                         printf ("0x%02x 0x%02x ... 0x%02x 0x%02x\n",
1125                                 data->data[0], data->data[1],
1126                                 data->data[data->size - 2],
1127                                 data->data[data->size - 1]);
1128                 }
1129         }
1130 }
1131
1132 ExifByteOrder
1133 exif_data_get_byte_order (ExifData *data)
1134 {
1135         if (!data)
1136                 return (0);
1137
1138         return (data->priv->order);
1139 }
1140
1141 void
1142 exif_data_foreach_content (ExifData *data, ExifDataForeachContentFunc func,
1143                            void *user_data)
1144 {
1145         unsigned int i;
1146
1147         if (!data || !func)
1148                 return;
1149
1150         for (i = 0; i < EXIF_IFD_COUNT; i++)
1151                 func (data->ifd[i], user_data);
1152 }
1153
1154 typedef struct _ByteOrderChangeData ByteOrderChangeData;
1155 struct _ByteOrderChangeData {
1156         ExifByteOrder old, new;
1157 };
1158
1159 static void
1160 entry_set_byte_order (ExifEntry *e, void *data)
1161 {
1162         ByteOrderChangeData *d = data;
1163
1164         if (!e)
1165                 return;
1166
1167         exif_array_set_byte_order (e->format, e->data, e->components, d->old, d->new);
1168 }
1169
1170 static void
1171 content_set_byte_order (ExifContent *content, void *data)
1172 {
1173         exif_content_foreach_entry (content, entry_set_byte_order, data);
1174 }
1175
1176 void
1177 exif_data_set_byte_order (ExifData *data, ExifByteOrder order)
1178 {
1179         ByteOrderChangeData d;
1180
1181         if (!data || (order == data->priv->order))
1182                 return;
1183
1184         d.old = data->priv->order;
1185         d.new = order;
1186         exif_data_foreach_content (data, content_set_byte_order, &d);
1187         data->priv->order = order;
1188         if (data->priv->md)
1189                 exif_mnote_data_set_byte_order (data->priv->md, order);
1190 }
1191
1192 void
1193 exif_data_log (ExifData *data, ExifLog *log)
1194 {
1195         unsigned int i;
1196
1197         if (!data || !data->priv) 
1198                 return;
1199         exif_log_unref (data->priv->log);
1200         data->priv->log = log;
1201         exif_log_ref (log);
1202
1203         for (i = 0; i < EXIF_IFD_COUNT; i++)
1204                 exif_content_log (data->ifd[i], log);
1205 }
1206
1207 /* Used internally within libexif */
1208 ExifLog *exif_data_get_log (ExifData *);
1209 ExifLog *
1210 exif_data_get_log (ExifData *data)
1211 {
1212         if (!data || !data->priv) 
1213                 return NULL;
1214         return data->priv->log;
1215 }
1216
1217 static const struct {
1218         ExifDataOption option;
1219         const char *name;
1220         const char *description;
1221 } exif_data_option[] = {
1222         {EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS, N_("Ignore unknown tags"),
1223          N_("Ignore unknown tags when loading EXIF data.")},
1224         {EXIF_DATA_OPTION_FOLLOW_SPECIFICATION, N_("Follow specification"),
1225          N_("Add, correct and remove entries to get EXIF data that follows "
1226             "the specification.")},
1227         {EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE, N_("Do not change maker note"),
1228          N_("When loading and resaving Exif data, save the maker note unmodified."
1229             " Be aware that the maker note can get corrupted.")},
1230         {0, NULL, NULL}
1231 };
1232
1233 const char *
1234 exif_data_option_get_name (ExifDataOption o)
1235 {
1236         unsigned int i;
1237
1238         for (i = 0; exif_data_option[i].name; i++)
1239                 if (exif_data_option[i].option == o) 
1240                         break;
1241         return _(exif_data_option[i].name);
1242 }
1243
1244 const char *
1245 exif_data_option_get_description (ExifDataOption o)
1246 {
1247         unsigned int i;
1248
1249         for (i = 0; exif_data_option[i].description; i++)
1250                 if (exif_data_option[i].option == o) 
1251                         break;
1252         return _(exif_data_option[i].description);
1253 }
1254
1255 void
1256 exif_data_set_option (ExifData *d, ExifDataOption o)
1257 {
1258         if (!d) 
1259                 return;
1260
1261         d->priv->options |= o;
1262 }
1263
1264 void
1265 exif_data_unset_option (ExifData *d, ExifDataOption o)
1266 {
1267         if (!d) 
1268                 return;
1269
1270         d->priv->options &= ~o;
1271 }
1272
1273 static void
1274 fix_func (ExifContent *c, void *UNUSED(data))
1275 {
1276         switch (exif_content_get_ifd (c)) {
1277         case EXIF_IFD_1:
1278                 if (c->parent->data)
1279                         exif_content_fix (c);
1280                 else if (c->count) {
1281                         exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data",
1282                                   "No thumbnail but entries on thumbnail. These entries have been "
1283                                   "removed.");
1284                         while (c->count) {
1285                                 unsigned int cnt = c->count;
1286                                 exif_content_remove_entry (c, c->entries[c->count - 1]);
1287                                 if (cnt == c->count) {
1288                                         /* safety net */
1289                                         exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data",
1290                                         "failed to remove last entry from entries.");
1291                                         c->count--;
1292                                 }
1293                         }
1294                 }
1295                 break;
1296         default:
1297                 exif_content_fix (c);
1298         }
1299 }
1300
1301 void
1302 exif_data_fix (ExifData *d)
1303 {
1304         exif_data_foreach_content (d, fix_func, NULL);
1305 }
1306
1307 void
1308 exif_data_set_data_type (ExifData *d, ExifDataType dt)
1309 {
1310         if (!d || !d->priv) 
1311                 return;
1312
1313         d->priv->data_type = dt;
1314 }
1315
1316 ExifDataType
1317 exif_data_get_data_type (ExifData *d)
1318 {
1319         return (d && d->priv) ? d->priv->data_type : EXIF_DATA_TYPE_UNKNOWN;
1320 }