geotiff_extractor.c (52449B)
1 /* 2 This file is part of libextractor. 3 Copyright (C) 2026 Vidyut Samanta and Christian Grothoff 4 5 libextractor is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published 7 by the Free Software Foundation; either version 3, or (at your 8 option) any later version. 9 10 libextractor is distributed in the hope that it will be useful, but 11 WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with libextractor; see the file COPYING. If not, write to the 17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 18 Boston, MA 02110-1301, USA. 19 */ 20 /** 21 * @file plugins/geotiff_extractor.c 22 * @brief plugin to support GeoTIFF files 23 * @author Christian Grothoff 24 * 25 * A GeoTIFF is an ordinary TIFF 6.0 (or BigTIFF) file that additionally 26 * carries a handful of private tags describing where on the Earth the 27 * raster sits. We do not link libtiff or libgeotiff: all we need is a 28 * bounded walk over the image file directory, and the `tiff' plugin -- 29 * which does link libtiff -- is only built when that library is 30 * present, so this plugin has to stand on its own anyway. 31 * 32 * Deliberately, we say nothing at all about a plain TIFF: without one 33 * of the four georeferencing tags the file belongs to the `tiff' and 34 * `exiv2' plugins and we return without emitting anything. 35 * 36 * References: OGC GeoTIFF 1.1 (OGC 19-008r4), the original GeoTIFF 37 * 1.8.2 specification, TIFF 6.0 and Adobe's BigTIFF description. 38 */ 39 #include "platform.h" 40 #include "extractor.h" 41 #include "forensics.h" 42 43 #include <math.h> 44 45 46 /** 47 * How many image file directories we are willing to follow. Real 48 * files have one plus a handful of reduced-resolution overviews. 49 */ 50 #define GEOTIFF_MAX_IFD 16 51 52 /** 53 * How many entries we look at in a single IFD. GDAL writes a few 54 * dozen; anything past this is padding or an attack. 55 */ 56 #define GEOTIFF_MAX_ENTRIES 512 57 58 /** 59 * How many GeoTIFF keys we parse out of the key directory. The 60 * registry defines well under a hundred. 61 */ 62 #define GEOTIFF_MAX_KEYS 512 63 64 /** 65 * Cap on the number of bytes of any one tag value we will read (and 66 * hence allocate). The largest thing we touch is GDAL's XML blob. 67 */ 68 #define GEOTIFF_MAX_VALUE 65536 69 70 /** 71 * How many `<Item>' elements we pull out of GDAL_METADATA. 72 */ 73 #define GEOTIFF_MAX_GDAL_ITEMS 16 74 75 /** 76 * Exclusive upper bound on ImageWidth/ImageLength. Both are LONG in 77 * the TIFF specification, so 2^32 admits every legal file; the point of 78 * the bound is that the tag is read as a `double' (it may be typed 79 * DOUBLE in the file) and converting one larger than ULLONG_MAX to 80 * `unsigned long long' is undefined behaviour. 81 */ 82 #define GEOTIFF_MAX_DIM 4294967296.0 83 84 85 /* TIFF field types, from TIFF 6.0 plus the BigTIFF additions. */ 86 #define TT_BYTE 1 87 #define TT_ASCII 2 88 #define TT_SHORT 3 89 #define TT_LONG 4 90 #define TT_RATIONAL 5 91 #define TT_SBYTE 6 92 #define TT_UNDEFINED 7 93 #define TT_SSHORT 8 94 #define TT_SLONG 9 95 #define TT_SRATIONAL 10 96 #define TT_FLOAT 11 97 #define TT_DOUBLE 12 98 #define TT_LONG8 16 99 #define TT_SLONG8 17 100 #define TT_IFD8 18 101 102 103 /** 104 * The tags we care about. Used to index #Context::tags. 105 */ 106 enum WantedTag 107 { 108 W_WIDTH = 0, 109 W_LENGTH, 110 W_BITS, 111 W_COMPRESSION, 112 W_DESCRIPTION, 113 W_MAKE, 114 W_MODEL, 115 W_SAMPLES, 116 W_SOFTWARE, 117 W_DATETIME, 118 W_ARTIST, 119 W_COPYRIGHT, 120 W_PIXELSCALE, 121 W_TIEPOINT, 122 W_TRANSFORM, 123 W_GEOKEYS, 124 W_GEODOUBLE, 125 W_GEOASCII, 126 W_GDAL_META, 127 W_GDAL_NODATA, 128 W_COUNT 129 }; 130 131 132 /** 133 * TIFF tag numbers, in the order of `enum WantedTag'. 134 */ 135 static const uint16_t wanted_tags[W_COUNT] = { 136 256, /* ImageWidth */ 137 257, /* ImageLength */ 138 258, /* BitsPerSample */ 139 259, /* Compression */ 140 270, /* ImageDescription */ 141 271, /* Make */ 142 272, /* Model */ 143 277, /* SamplesPerPixel */ 144 305, /* Software */ 145 306, /* DateTime */ 146 315, /* Artist */ 147 33432, /* Copyright */ 148 33550, /* ModelPixelScaleTag */ 149 33922, /* ModelTiepointTag */ 150 34264, /* ModelTransformationTag */ 151 34735, /* GeoKeyDirectoryTag */ 152 34736, /* GeoDoubleParamsTag */ 153 34737, /* GeoAsciiParamsTag */ 154 42112, /* GDAL_METADATA */ 155 42113 /* GDAL_NODATA */ 156 }; 157 158 159 /** 160 * One directory entry we decided to keep. 161 */ 162 struct Entry 163 { 164 /** 165 * Number of values, from the entry's count field. 166 */ 167 uint64_t count; 168 169 /** 170 * Where the value lives, if it did not fit in the entry. Only 171 * meaningful when the total size exceeds the inline field. 172 */ 173 uint64_t offset; 174 175 /** 176 * The raw value/offset field, 4 bytes for classic TIFF and 8 for 177 * BigTIFF. Small values live here directly. 178 */ 179 unsigned char val[8]; 180 181 /** 182 * TIFF field type (one of the TT_* constants). 183 */ 184 uint16_t type; 185 186 /** 187 * True once we have seen this tag. We keep the first occurrence: 188 * later IFDs are overviews and thumbnails. 189 */ 190 int found; 191 }; 192 193 194 /** 195 * State for one extraction run. 196 */ 197 struct Context 198 { 199 /** 200 * Extraction context we were handed. 201 */ 202 struct EXTRACTOR_ExtractContext *ec; 203 204 /** 205 * Size of the file, used to bounds-check every offset. 206 */ 207 uint64_t fsize; 208 209 /** 210 * True if the file is big-endian (`MM'). 211 */ 212 int be; 213 214 /** 215 * True if the file is BigTIFF (version 43): 8-byte offsets and 216 * counts, 20-byte directory entries. 217 */ 218 int big; 219 220 /** 221 * The tags we found, indexed by `enum WantedTag'. 222 */ 223 struct Entry tags[W_COUNT]; 224 }; 225 226 227 /** 228 * The GeoTIFF keys we understand, as read out of the key directory. 229 */ 230 struct GeoKeys 231 { 232 /** 233 * GTModelTypeGeoKey (1024): 1 projected, 2 geographic, 3 geocentric. 234 */ 235 unsigned int model_type; 236 237 /** 238 * GTRasterTypeGeoKey (1025): 1 pixel-is-area, 2 pixel-is-point. 239 */ 240 unsigned int raster_type; 241 242 /** 243 * GeographicTypeGeoKey (2048), an EPSG geographic CRS code. 244 */ 245 unsigned int geographic; 246 247 /** 248 * ProjectedCSTypeGeoKey (3072), an EPSG projected CRS code. 249 */ 250 unsigned int projected; 251 252 /** 253 * VerticalCSTypeGeoKey (4096), an EPSG vertical CRS code. 254 */ 255 unsigned int vertical; 256 257 /** 258 * ProjLinearUnitsGeoKey (3076), an EPSG unit-of-measure code. 259 */ 260 unsigned int linear_units; 261 262 /** 263 * Which of the above were actually present, as a bit set of 264 * 1 << (key index); see the have_* flags below instead. 265 */ 266 int have_model_type; 267 268 int have_raster_type; 269 270 int have_geographic; 271 272 int have_projected; 273 274 int have_vertical; 275 276 int have_linear_units; 277 }; 278 279 280 /** 281 * Read a 16-bit integer in the file's byte order. 282 * 283 * @param ctx extraction state, for the byte order 284 * @param p the two bytes 285 * @return the value 286 */ 287 static uint16_t 288 geo_u16 (const struct Context *ctx, 289 const unsigned char *p) 290 { 291 return ctx->be 292 ? EXTRACTOR_forensic_be16_ (p) 293 : EXTRACTOR_forensic_le16_ (p); 294 } 295 296 297 /** 298 * Read a 32-bit integer in the file's byte order. 299 * 300 * @param ctx extraction state, for the byte order 301 * @param p the four bytes 302 * @return the value 303 */ 304 static uint32_t 305 geo_u32 (const struct Context *ctx, 306 const unsigned char *p) 307 { 308 return ctx->be 309 ? EXTRACTOR_forensic_be32_ (p) 310 : EXTRACTOR_forensic_le32_ (p); 311 } 312 313 314 /** 315 * Read a 64-bit integer in the file's byte order. 316 * 317 * @param ctx extraction state, for the byte order 318 * @param p the eight bytes 319 * @return the value 320 */ 321 static uint64_t 322 geo_u64 (const struct Context *ctx, 323 const unsigned char *p) 324 { 325 return ctx->be 326 ? EXTRACTOR_forensic_be64_ (p) 327 : EXTRACTOR_forensic_le64_ (p); 328 } 329 330 331 /** 332 * Read an IEEE 754 single as stored in the file. 333 * 334 * The bit pattern is assembled in host integer order first, so the 335 * only assumption left is that the host's `float' is IEEE 754 with the 336 * same byte order as its integers -- true on every platform 337 * libextractor builds on. 338 * 339 * @param ctx extraction state, for the byte order 340 * @param p the four bytes 341 * @return the value 342 */ 343 static double 344 geo_f32 (const struct Context *ctx, 345 const unsigned char *p) 346 { 347 uint32_t bits = geo_u32 (ctx, 348 p); 349 float f; 350 351 memcpy (&f, 352 &bits, 353 sizeof (f)); 354 return (double) f; 355 } 356 357 358 /** 359 * Read an IEEE 754 double as stored in the file. 360 * 361 * @param ctx extraction state, for the byte order 362 * @param p the eight bytes 363 * @return the value 364 */ 365 static double 366 geo_f64 (const struct Context *ctx, 367 const unsigned char *p) 368 { 369 uint64_t bits = geo_u64 (ctx, 370 p); 371 double d; 372 373 memcpy (&d, 374 &bits, 375 sizeof (d)); 376 return d; 377 } 378 379 380 /** 381 * Size in bytes of one value of the given TIFF field type. 382 * 383 * @param type the TIFF field type 384 * @return the size, 0 for a type we do not know (which makes the 385 * caller ignore the tag, as TIFF 6.0 requires) 386 */ 387 static size_t 388 type_size (uint16_t type) 389 { 390 switch (type) 391 { 392 case TT_BYTE: 393 case TT_ASCII: 394 case TT_SBYTE: 395 case TT_UNDEFINED: 396 return 1; 397 case TT_SHORT: 398 case TT_SSHORT: 399 return 2; 400 case TT_LONG: 401 case TT_SLONG: 402 case TT_FLOAT: 403 return 4; 404 case TT_RATIONAL: 405 case TT_SRATIONAL: 406 case TT_DOUBLE: 407 case TT_LONG8: 408 case TT_SLONG8: 409 case TT_IFD8: 410 return 8; 411 default: 412 return 0; 413 } 414 } 415 416 417 /** 418 * Fetch the bytes belonging to @a e, either from the entry itself or 419 * from wherever in the file it points. 420 * 421 * @param ctx extraction state 422 * @param e the directory entry 423 * @param cap refuse to read (and allocate) more than this many bytes 424 * @param[out] len number of bytes returned 425 * @return the bytes, to be freed by the caller, NULL on any error 426 */ 427 static unsigned char * 428 load_value (const struct Context *ctx, 429 const struct Entry *e, 430 size_t cap, 431 size_t *len) 432 { 433 size_t ts = type_size (e->type); 434 size_t inline_max = ctx->big ? 8 : 4; 435 size_t total; 436 unsigned char *buf; 437 438 if ( (! e->found) || 439 (0 == ts) || 440 (0 == e->count) ) 441 return NULL; 442 if (cap > GEOTIFF_MAX_VALUE) 443 cap = GEOTIFF_MAX_VALUE; 444 /* This is the count-times-size multiplication the file controls; 445 dividing instead of multiplying keeps it from wrapping. */ 446 if (e->count > ((uint64_t) cap) / ts) 447 return NULL; 448 total = (size_t) (e->count * ts); 449 buf = malloc (total); 450 if (NULL == buf) 451 return NULL; 452 if (total <= inline_max) 453 { 454 memcpy (buf, 455 e->val, 456 total); 457 *len = total; 458 return buf; 459 } 460 if ( (e->offset > ctx->fsize) || 461 (total > ctx->fsize - e->offset) || 462 (e->offset > (uint64_t) INT64_MAX) ) 463 { 464 free (buf); 465 return NULL; 466 } 467 if (! EXTRACTOR_forensic_read_ (ctx->ec, 468 (int64_t) e->offset, 469 buf, 470 total)) 471 { 472 free (buf); 473 return NULL; 474 } 475 *len = total; 476 return buf; 477 } 478 479 480 /** 481 * Interpret element @a idx of an already loaded tag value as a double. 482 * 483 * @param ctx extraction state, for the byte order 484 * @param type the TIFF field type the buffer holds 485 * @param buf the value bytes 486 * @param len number of bytes in @a buf 487 * @param idx which element to read 488 * @param[out] out where to store the value 489 * @return 1 on success, 0 if the index or the type does not work out 490 */ 491 static int 492 value_as_double (const struct Context *ctx, 493 uint16_t type, 494 const unsigned char *buf, 495 size_t len, 496 size_t idx, 497 double *out) 498 { 499 size_t ts = type_size (type); 500 const unsigned char *p; 501 502 if ( (0 == ts) || 503 (idx >= len / ts) ) 504 return 0; 505 p = &buf[idx * ts]; 506 switch (type) 507 { 508 case TT_BYTE: 509 case TT_UNDEFINED: 510 *out = (double) p[0]; 511 return 1; 512 case TT_SBYTE: 513 *out = (double) (int8_t) p[0]; 514 return 1; 515 case TT_SHORT: 516 *out = (double) geo_u16 (ctx, p); 517 return 1; 518 case TT_SSHORT: 519 *out = (double) (int16_t) geo_u16 (ctx, p); 520 return 1; 521 case TT_LONG: 522 *out = (double) geo_u32 (ctx, p); 523 return 1; 524 case TT_SLONG: 525 *out = (double) (int32_t) geo_u32 (ctx, p); 526 return 1; 527 case TT_FLOAT: 528 *out = geo_f32 (ctx, p); 529 return 1; 530 case TT_DOUBLE: 531 *out = geo_f64 (ctx, p); 532 return 1; 533 case TT_RATIONAL: 534 { 535 uint32_t num = geo_u32 (ctx, p); 536 uint32_t den = geo_u32 (ctx, p + 4); 537 538 if (0 == den) 539 return 0; 540 *out = ((double) num) / ((double) den); 541 return 1; 542 } 543 case TT_SRATIONAL: 544 { 545 int32_t num = (int32_t) geo_u32 (ctx, p); 546 int32_t den = (int32_t) geo_u32 (ctx, p + 4); 547 548 if (0 == den) 549 return 0; 550 *out = ((double) num) / ((double) den); 551 return 1; 552 } 553 case TT_LONG8: 554 case TT_IFD8: 555 *out = (double) geo_u64 (ctx, p); 556 return 1; 557 case TT_SLONG8: 558 *out = (double) (int64_t) geo_u64 (ctx, p); 559 return 1; 560 default: 561 return 0; 562 } 563 } 564 565 566 /** 567 * Read a single numeric value out of one of our tags. 568 * 569 * Only the one element is fetched, never the whole array: 570 * ModelTiepointTag holds a list of ground control points in files that 571 * are not a simple grid, and that list can run to many kilobytes we 572 * have no use for. 573 * 574 * @param ctx extraction state 575 * @param w which tag to read 576 * @param idx which element of the tag to read 577 * @param[out] out where to store the value 578 * @return 1 on success, 0 if the tag is absent or unusable 579 */ 580 static int 581 tag_double (const struct Context *ctx, 582 enum WantedTag w, 583 size_t idx, 584 double *out) 585 { 586 const struct Entry *e = &ctx->tags[w]; 587 size_t ts = type_size (e->type); 588 size_t inline_max = ctx->big ? 8 : 4; 589 unsigned char raw[8]; 590 uint64_t total; 591 uint64_t byte_off; 592 uint64_t room; 593 594 if ( (! e->found) || 595 (0 == ts) || 596 (((uint64_t) idx) >= e->count) ) 597 return 0; 598 if (e->count > UINT64_MAX / ts) 599 return 0; /* a count that cannot describe any real array */ 600 total = e->count * ts; 601 byte_off = ((uint64_t) idx) * ts; 602 if (total <= inline_max) 603 { 604 memcpy (raw, 605 &e->val[byte_off], 606 ts); 607 } 608 else 609 { 610 if ( (e->offset > ctx->fsize) || 611 (e->offset > (uint64_t) INT64_MAX) ) 612 return 0; 613 room = ctx->fsize - e->offset; 614 if ( (byte_off > room) || 615 (ts > room - byte_off) ) 616 return 0; 617 if (! EXTRACTOR_forensic_read_ (ctx->ec, 618 (int64_t) (e->offset + byte_off), 619 raw, 620 ts)) 621 return 0; 622 } 623 return value_as_double (ctx, 624 e->type, 625 raw, 626 ts, 627 0, 628 out); 629 } 630 631 632 /** 633 * Emit a string-valued tag, if it is present. 634 * 635 * @param ctx extraction state 636 * @param w which tag to emit 637 * @param type meta data type to report it as 638 * @return 1 if the caller should stop extracting, 0 to continue 639 */ 640 static int 641 emit_ascii_tag (const struct Context *ctx, 642 enum WantedTag w, 643 enum EXTRACTOR_MetaType type) 644 { 645 unsigned char *buf; 646 size_t len; 647 int stop; 648 649 if (TT_ASCII != ctx->tags[w].type) 650 return 0; 651 buf = load_value (ctx, 652 &ctx->tags[w], 653 EXTRACTOR_FORENSIC_MAX_STRING, 654 &len); 655 if (NULL == buf) 656 return 0; 657 stop = EXTRACTOR_forensic_emit_text_ (ctx->ec, 658 "geotiff", 659 type, 660 (const char *) buf, 661 len); 662 free (buf); 663 return stop; 664 } 665 666 667 /** 668 * Walk the chain of image file directories and remember the entries 669 * for the tags in #wanted_tags. 670 * 671 * @param ctx extraction state, updated in place 672 * @param first offset of the first IFD, from the header 673 */ 674 static void 675 walk_ifds (struct Context *ctx, 676 uint64_t first) 677 { 678 uint64_t seen[GEOTIFF_MAX_IFD]; 679 unsigned int nseen = 0; 680 uint64_t off = first; 681 size_t esz = ctx->big ? 20 : 12; 682 size_t cntsz = ctx->big ? 8 : 2; 683 size_t nextsz = ctx->big ? 8 : 4; 684 685 while ( (0 != off) && 686 (nseen < GEOTIFF_MAX_IFD) ) 687 { 688 unsigned char cnt[8]; 689 unsigned char *ents; 690 uint64_t avail; 691 uint64_t nent; 692 uint64_t declared; 693 int truncated = 0; 694 695 /* An IFD that points back at one we already parsed would loop 696 forever; the offset cap alone does not catch a 2-cycle. */ 697 for (unsigned int i = 0; i < nseen; i++) 698 if (seen[i] == off) 699 return; 700 seen[nseen++] = off; 701 if ( (off >= ctx->fsize) || 702 (off > (uint64_t) INT64_MAX) ) 703 return; 704 avail = ctx->fsize - off; 705 if (avail < cntsz) 706 return; 707 if (! EXTRACTOR_forensic_read_ (ctx->ec, 708 (int64_t) off, 709 cnt, 710 cntsz)) 711 return; 712 declared = ctx->big 713 ? geo_u64 (ctx, cnt) 714 : (uint64_t) geo_u16 (ctx, cnt); 715 nent = declared; 716 if (nent > GEOTIFF_MAX_ENTRIES) 717 { 718 nent = GEOTIFF_MAX_ENTRIES; 719 truncated = 1; 720 } 721 avail -= cntsz; 722 if (avail / esz < nent) 723 { 724 /* the file is shorter than it claims; take what is there */ 725 nent = avail / esz; 726 truncated = 1; 727 } 728 if (0 == nent) 729 return; 730 ents = malloc ((size_t) (nent * esz)); 731 if (NULL == ents) 732 return; 733 if (! EXTRACTOR_forensic_read_ (ctx->ec, 734 -1, 735 ents, 736 (size_t) (nent * esz))) 737 { 738 free (ents); 739 return; 740 } 741 for (uint64_t i = 0; i < nent; i++) 742 { 743 const unsigned char *p = &ents[i * esz]; 744 uint16_t tag = geo_u16 (ctx, p); 745 746 for (unsigned int k = 0; k < W_COUNT; k++) 747 { 748 struct Entry *e = &ctx->tags[k]; 749 750 if ( (wanted_tags[k] != tag) || 751 (e->found) ) 752 continue; 753 e->type = geo_u16 (ctx, p + 2); 754 if (ctx->big) 755 { 756 e->count = geo_u64 (ctx, p + 4); 757 memcpy (e->val, 758 p + 12, 759 8); 760 e->offset = geo_u64 (ctx, e->val); 761 } 762 else 763 { 764 e->count = (uint64_t) geo_u32 (ctx, p + 4); 765 memcpy (e->val, 766 p + 8, 767 4); 768 e->offset = (uint64_t) geo_u32 (ctx, e->val); 769 } 770 e->found = 1; 771 break; 772 } 773 } 774 free (ents); 775 if (truncated) 776 return; /* the next-IFD pointer is not where we think it is */ 777 /* the next-IFD offset follows the entries */ 778 if (avail - declared * esz < nextsz) 779 return; 780 if (! EXTRACTOR_forensic_read_ (ctx->ec, 781 -1, 782 cnt, 783 nextsz)) 784 return; 785 off = ctx->big 786 ? geo_u64 (ctx, cnt) 787 : (uint64_t) geo_u32 (ctx, cnt); 788 } 789 } 790 791 792 /** 793 * Human-readable name for the EPSG codes a first pass is most likely 794 * to run into. Anything else is reported as the bare code; resolving 795 * the full registry would mean shipping it. 796 * 797 * @param code the EPSG CRS code 798 * @param[out] buf where to write the name 799 * @param buf_size number of bytes in @a buf 800 * @return 1 if a name was written, 0 if the code is not one we know 801 */ 802 static int 803 epsg_name (unsigned int code, 804 char *buf, 805 size_t buf_size) 806 { 807 static const struct 808 { 809 unsigned int code; 810 const char *name; 811 } known[] = { 812 { 4326, "WGS 84" }, 813 { 4269, "NAD83" }, 814 { 4258, "ETRS89" }, 815 { 4979, "WGS 84 (3D)" }, 816 { 3857, "WGS 84 / Pseudo-Mercator" }, 817 { 3395, "WGS 84 / World Mercator" }, 818 { 5714, "MSL height" }, 819 { 5773, "EGM96 height" }, 820 { 3855, "EGM2008 height" }, 821 { 0, NULL } 822 }; 823 824 for (unsigned int i = 0; NULL != known[i].name; i++) 825 if (known[i].code == code) 826 { 827 if (((size_t) snprintf (buf, 828 buf_size, 829 "%s", 830 known[i].name)) >= buf_size) 831 return 0; 832 return 1; 833 } 834 if ( (32601 <= code) && 835 (32660 >= code) ) 836 { 837 snprintf (buf, 838 buf_size, 839 "WGS 84 / UTM zone %uN", 840 code - 32600); 841 return 1; 842 } 843 if ( (32701 <= code) && 844 (32760 >= code) ) 845 { 846 snprintf (buf, 847 buf_size, 848 "WGS 84 / UTM zone %uS", 849 code - 32700); 850 return 1; 851 } 852 return 0; 853 } 854 855 856 /** 857 * How many citation strings we remember in order not to report the 858 * same CRS name twice. 859 */ 860 #define GEOTIFF_MAX_CITATIONS 4 861 862 863 /** 864 * The citation strings emitted so far, so that the very common case of 865 * GTCitationGeoKey and PCSCitationGeoKey carrying the same text does 866 * not produce the same value twice. 867 */ 868 struct Citations 869 { 870 /** 871 * The strings, not NUL-terminated. 872 */ 873 char text[GEOTIFF_MAX_CITATIONS][128]; 874 875 /** 876 * Length of each entry in #text. 877 */ 878 size_t len[GEOTIFF_MAX_CITATIONS]; 879 880 /** 881 * How many entries of #text are in use. 882 */ 883 unsigned int count; 884 }; 885 886 887 /** 888 * Emit one GeoTIFF key whose value is a substring of 889 * GeoAsciiParamsTag. 890 * 891 * GeoASCII strings are packed into one blob and terminated by `|' 892 * rather than by NUL, because a NUL would end the whole TIFF ASCII 893 * field. 894 * 895 * @param ctx extraction state 896 * @param[in,out] cits citations reported so far 897 * @param ascii the GeoAsciiParamsTag bytes, NULL if the tag is absent 898 * @param ascii_len number of bytes in @a ascii 899 * @param off offset of the substring, from the key's Value_Offset 900 * @param count length of the substring, from the key's Count 901 * @param type meta data type to report it as 902 * @return 1 if the caller should stop extracting, 0 to continue 903 */ 904 static int 905 emit_geo_ascii (const struct Context *ctx, 906 struct Citations *cits, 907 const unsigned char *ascii, 908 size_t ascii_len, 909 size_t off, 910 size_t count, 911 enum EXTRACTOR_MetaType type) 912 { 913 size_t n; 914 915 if ( (NULL == ascii) || 916 (off >= ascii_len) ) 917 return 0; 918 n = count; 919 if (n > ascii_len - off) 920 n = ascii_len - off; 921 /* The string runs to its `|' terminator. Trusting Count instead 922 would run one string into the next whenever Count is wrong, and it 923 is the file that chooses Count. */ 924 for (size_t i = 0; i < n; i++) 925 if ('|' == ascii[off + i]) 926 { 927 n = i; 928 break; 929 } 930 if (0 == n) 931 return 0; 932 for (unsigned int i = 0; i < cits->count; i++) 933 { 934 if ( (cits->len[i] == n) && 935 (0 == memcmp (cits->text[i], 936 &ascii[off], 937 n)) ) 938 return 0; /* already reported under another key */ 939 } 940 if ( (cits->count < GEOTIFF_MAX_CITATIONS) && 941 (n <= sizeof (cits->text[0])) ) 942 { 943 memcpy (cits->text[cits->count], 944 &ascii[off], 945 n); 946 cits->len[cits->count] = n; 947 cits->count++; 948 } 949 return EXTRACTOR_forensic_emit_text_ (ctx->ec, 950 "geotiff", 951 type, 952 (const char *) &ascii[off], 953 n); 954 } 955 956 957 /** 958 * Parse GeoKeyDirectoryTag, emitting the human-readable citations as 959 * we go and collecting the numeric keys into @a gk. 960 * 961 * @param ctx extraction state 962 * @param[out] gk where to store the numeric keys 963 * @return 1 if the caller should stop extracting, 0 to continue 964 */ 965 static int 966 parse_geo_keys (const struct Context *ctx, 967 struct GeoKeys *gk) 968 { 969 struct Citations cits; 970 unsigned char *dir; 971 unsigned char *ascii = NULL; 972 size_t dir_len; 973 size_t ascii_len = 0; 974 size_t nvals; 975 size_t nkeys; 976 int stop = 0; 977 978 memset (gk, 979 0, 980 sizeof (*gk)); 981 memset (&cits, 982 0, 983 sizeof (cits)); 984 if (TT_SHORT != ctx->tags[W_GEOKEYS].type) 985 return 0; 986 dir = load_value (ctx, 987 &ctx->tags[W_GEOKEYS], 988 2 * (4 + 4 * GEOTIFF_MAX_KEYS), 989 &dir_len); 990 if (NULL == dir) 991 return 0; 992 nvals = dir_len / 2; 993 if (4 > nvals) 994 { 995 free (dir); 996 return 0; 997 } 998 nkeys = geo_u16 (ctx, 999 &dir[6]); 1000 if (nkeys > GEOTIFF_MAX_KEYS) 1001 nkeys = GEOTIFF_MAX_KEYS; 1002 /* NumberOfKeys is not to be trusted over the tag's own count */ 1003 if (nkeys > (nvals - 4) / 4) 1004 nkeys = (nvals - 4) / 4; 1005 if ( (0 != ctx->tags[W_GEOASCII].found) && 1006 (TT_ASCII == ctx->tags[W_GEOASCII].type) ) 1007 ascii = load_value (ctx, 1008 &ctx->tags[W_GEOASCII], 1009 GEOTIFF_MAX_VALUE, 1010 &ascii_len); 1011 for (size_t i = 0; (i < nkeys) && (0 == stop); i++) 1012 { 1013 const unsigned char *k = &dir[8 + i * 8]; 1014 uint16_t key_id = geo_u16 (ctx, k); 1015 uint16_t location = geo_u16 (ctx, k + 2); 1016 uint16_t count = geo_u16 (ctx, k + 4); 1017 uint16_t value = geo_u16 (ctx, k + 6); 1018 1019 if (34737 == location) 1020 { 1021 /* a substring of GeoAsciiParamsTag: these are the CRS names */ 1022 switch (key_id) 1023 { 1024 case 1026: /* GTCitationGeoKey */ 1025 case 2049: /* GeogCitationGeoKey */ 1026 case 3073: /* PCSCitationGeoKey */ 1027 case 4097: /* VerticalCitationGeoKey */ 1028 stop = emit_geo_ascii (ctx, 1029 &cits, 1030 ascii, 1031 ascii_len, 1032 value, 1033 count, 1034 EXTRACTOR_METATYPE_COORDINATE_SYSTEM); 1035 break; 1036 default: 1037 break; 1038 } 1039 continue; 1040 } 1041 if (34736 == location) 1042 continue; /* a DOUBLE in GeoDoubleParamsTag; none of the keys 1043 we report is double-valued (they are ellipsoid 1044 parameters and projection constants) */ 1045 if (0 != location) 1046 continue; /* not a location the specification defines */ 1047 if (1 != count) 1048 continue; /* an inline key is a single SHORT by definition */ 1049 switch (key_id) 1050 { 1051 case 1024: /* GTModelTypeGeoKey */ 1052 gk->model_type = value; 1053 gk->have_model_type = 1; 1054 break; 1055 case 1025: /* GTRasterTypeGeoKey */ 1056 gk->raster_type = value; 1057 gk->have_raster_type = 1; 1058 break; 1059 case 2048: /* GeographicTypeGeoKey */ 1060 gk->geographic = value; 1061 gk->have_geographic = 1; 1062 break; 1063 case 3072: /* ProjectedCSTypeGeoKey */ 1064 gk->projected = value; 1065 gk->have_projected = 1; 1066 break; 1067 case 3076: /* ProjLinearUnitsGeoKey */ 1068 gk->linear_units = value; 1069 gk->have_linear_units = 1; 1070 break; 1071 case 4096: /* VerticalCSTypeGeoKey */ 1072 gk->vertical = value; 1073 gk->have_vertical = 1; 1074 break; 1075 default: 1076 break; 1077 } 1078 } 1079 free (ascii); 1080 free (dir); 1081 return stop; 1082 } 1083 1084 1085 /** 1086 * Emit the coordinate reference system and the two descriptive keys. 1087 * 1088 * @param ctx extraction state 1089 * @param gk the parsed GeoTIFF keys 1090 * @return 1 if the caller should stop extracting, 0 to continue 1091 */ 1092 static int 1093 emit_crs (const struct Context *ctx, 1094 const struct GeoKeys *gk) 1095 { 1096 static const char *model_names[] = { 1097 NULL, 1098 "projected", 1099 "geographic", 1100 "geocentric" 1101 }; 1102 char name[128]; 1103 unsigned int code = 0; 1104 int have = 0; 1105 1106 /* A projected CRS is the more specific statement, so it wins; the 1107 geographic key is then only the datum the projection sits on. */ 1108 if ( (gk->have_projected) && 1109 (0 != gk->projected) && 1110 (32767 != gk->projected) ) 1111 { 1112 code = gk->projected; 1113 have = 1; 1114 } 1115 else if ( (gk->have_geographic) && 1116 (0 != gk->geographic) && 1117 (32767 != gk->geographic) ) 1118 { 1119 code = gk->geographic; 1120 have = 1; 1121 } 1122 else if ( (gk->have_vertical) && 1123 (0 != gk->vertical) && 1124 (32767 != gk->vertical) ) 1125 { 1126 code = gk->vertical; 1127 have = 1; 1128 } 1129 if (have) 1130 { 1131 if (epsg_name (code, 1132 name, 1133 sizeof (name))) 1134 { 1135 if (EXTRACTOR_forensic_emit_ (ctx->ec, 1136 "geotiff", 1137 EXTRACTOR_METATYPE_COORDINATE_SYSTEM, 1138 "EPSG:%u (%s)", 1139 code, 1140 name)) 1141 return 1; 1142 } 1143 else if (EXTRACTOR_forensic_emit_ (ctx->ec, 1144 "geotiff", 1145 EXTRACTOR_METATYPE_COORDINATE_SYSTEM, 1146 "EPSG:%u", 1147 code)) 1148 { 1149 return 1; 1150 } 1151 } 1152 if ( (gk->have_vertical) && 1153 (have) && 1154 (code != gk->vertical) && 1155 (0 != gk->vertical) && 1156 (32767 != gk->vertical) && 1157 (EXTRACTOR_forensic_emit_ (ctx->ec, 1158 "geotiff", 1159 EXTRACTOR_METATYPE_COORDINATE_SYSTEM, 1160 "vertical EPSG:%u", 1161 gk->vertical)) ) 1162 return 1; 1163 if ( (gk->have_model_type) && 1164 (gk->model_type < sizeof (model_names) / sizeof (model_names[0])) && 1165 (NULL != model_names[gk->model_type]) && 1166 (EXTRACTOR_forensic_emit_ (ctx->ec, 1167 "geotiff", 1168 EXTRACTOR_METATYPE_COMMENT, 1169 "GeoTIFF model type: %s", 1170 model_names[gk->model_type])) ) 1171 return 1; 1172 if ( (gk->have_raster_type) && 1173 ( (1 == gk->raster_type) || 1174 (2 == gk->raster_type) ) && 1175 (EXTRACTOR_forensic_emit_ (ctx->ec, 1176 "geotiff", 1177 EXTRACTOR_METATYPE_COMMENT, 1178 "GeoTIFF raster type: %s", 1179 (1 == gk->raster_type) 1180 ? "pixel is area" 1181 : "pixel is point")) ) 1182 return 1; 1183 return 0; 1184 } 1185 1186 1187 /** 1188 * Name of the unit the model coordinates are expressed in. 1189 * 1190 * @param gk the parsed GeoTIFF keys 1191 * @return a unit name, or NULL if we cannot tell 1192 */ 1193 static const char * 1194 model_units (const struct GeoKeys *gk) 1195 { 1196 if (gk->have_linear_units) 1197 switch (gk->linear_units) 1198 { 1199 case 9001: 1200 return "m"; 1201 case 9002: 1202 case 9003: 1203 return "ft"; 1204 case 9036: 1205 return "km"; 1206 default: 1207 break; 1208 } 1209 if (gk->have_model_type) 1210 { 1211 if (2 == gk->model_type) 1212 return "degrees"; /* a geographic CRS; angular units by definition */ 1213 if (1 == gk->model_type) 1214 return "m"; /* the overwhelmingly common projected case */ 1215 } 1216 if ( (gk->have_geographic) && 1217 (! gk->have_projected) ) 1218 return "degrees"; 1219 return NULL; 1220 } 1221 1222 1223 /** 1224 * Emit the georeferencing derived from the model tags: the pixel 1225 * scale, the extent of the raster, and the tiepoint elevation. 1226 * 1227 * @param ctx extraction state 1228 * @param gk the parsed GeoTIFF keys 1229 * @return 1 if the caller should stop extracting, 0 to continue 1230 */ 1231 static int 1232 emit_geometry (const struct Context *ctx, 1233 const struct GeoKeys *gk) 1234 { 1235 const char *units = model_units (gk); 1236 double width; 1237 double height; 1238 double sx; 1239 double sy; 1240 double sz; 1241 double west = 0.0; 1242 double east = 0.0; 1243 double north = 0.0; 1244 double south = 0.0; 1245 int have_scale; 1246 int have_box = 0; 1247 1248 if ( (! tag_double (ctx, W_WIDTH, 0, &width)) || 1249 (! tag_double (ctx, W_LENGTH, 0, &height)) || 1250 (! isfinite (width)) || 1251 (! isfinite (height)) || 1252 (1.0 > width) || 1253 (1.0 > height) ) 1254 { 1255 width = 0.0; 1256 height = 0.0; 1257 } 1258 have_scale = (tag_double (ctx, W_PIXELSCALE, 0, &sx) && 1259 tag_double (ctx, W_PIXELSCALE, 1, &sy) && 1260 isfinite (sx) && 1261 isfinite (sy) && 1262 (0.0 != sx) && 1263 (0.0 != sy)); 1264 if ( (! tag_double (ctx, W_PIXELSCALE, 2, &sz)) || 1265 (! isfinite (sz)) ) 1266 sz = 0.0; 1267 if (have_scale) 1268 { 1269 if (NULL != units) 1270 { 1271 if (EXTRACTOR_forensic_emit_ (ctx->ec, 1272 "geotiff", 1273 EXTRACTOR_METATYPE_IMAGE_RESOLUTION, 1274 "%.10g x %.10g %s/pixel", 1275 sx, 1276 sy, 1277 units)) 1278 return 1; 1279 } 1280 else if (EXTRACTOR_forensic_emit_ (ctx->ec, 1281 "geotiff", 1282 EXTRACTOR_METATYPE_IMAGE_RESOLUTION, 1283 "%.10g x %.10g per pixel", 1284 sx, 1285 sy)) 1286 { 1287 return 1; 1288 } 1289 } 1290 /* Preferred georeferencing: one tiepoint plus a pixel scale. The 1291 model coordinate of raster point (i,j) is 1292 x = x_tie + (i - i_tie) * sx, y = y_tie - (j - j_tie) * sy 1293 (y grows northwards while j grows downwards, which is why sy is 1294 subtracted). Note that with GTRasterTypeGeoKey = RasterPixelIsArea 1295 the tiepoint names the *corner* of the pixel and the extent below 1296 is exact, whereas with RasterPixelIsPoint it names the pixel 1297 *centre* and the true extent is half a pixel larger on every side. 1298 We do not correct for that: half a pixel is not worth a second 1299 code path, but it is worth knowing about. */ 1300 if (have_scale && 1301 (0.0 < width) && 1302 (0.0 < height)) 1303 { 1304 double ti; 1305 double tj; 1306 double tx; 1307 double ty; 1308 1309 if (tag_double (ctx, W_TIEPOINT, 0, &ti) && 1310 tag_double (ctx, W_TIEPOINT, 1, &tj) && 1311 tag_double (ctx, W_TIEPOINT, 3, &tx) && 1312 tag_double (ctx, W_TIEPOINT, 4, &ty) && 1313 isfinite (ti) && isfinite (tj) && 1314 isfinite (tx) && isfinite (ty)) 1315 { 1316 double x0 = tx + (0.0 - ti) * sx; 1317 double x1 = tx + (width - ti) * sx; 1318 double y0 = ty - (0.0 - tj) * sy; 1319 double y1 = ty - (height - tj) * sy; 1320 1321 west = (x0 < x1) ? x0 : x1; 1322 east = (x0 < x1) ? x1 : x0; 1323 south = (y0 < y1) ? y0 : y1; 1324 north = (y0 < y1) ? y1 : y0; 1325 have_box = 1; 1326 } 1327 } 1328 if ( (! have_box) && 1329 (0.0 < width) && 1330 (0.0 < height) ) 1331 { 1332 /* Fall back on ModelTransformationTag, a row-major 4x4 matrix that 1333 maps (i,j,k,1) to (x,y,z,1); only the first two rows matter for 1334 an extent. The mapping may rotate, so take the extremes over 1335 all four raster corners rather than assuming axis alignment. */ 1336 double m[8]; 1337 int ok = 1; 1338 1339 for (unsigned int i = 0; i < 8; i++) 1340 if ( (! tag_double (ctx, W_TRANSFORM, i, &m[i])) || 1341 (! isfinite (m[i])) ) 1342 { 1343 ok = 0; 1344 break; 1345 } 1346 if (ok) 1347 { 1348 static const double corner[4][2] = { 1349 { 0.0, 0.0 }, { 1.0, 0.0 }, { 0.0, 1.0 }, { 1.0, 1.0 } 1350 }; 1351 1352 for (unsigned int c = 0; c < 4; c++) 1353 { 1354 double i = corner[c][0] * width; 1355 double j = corner[c][1] * height; 1356 double x = m[0] * i + m[1] * j + m[3]; 1357 double y = m[4] * i + m[5] * j + m[7]; 1358 1359 if ( (! isfinite (x)) || 1360 (! isfinite (y)) ) 1361 { 1362 have_box = 0; 1363 break; 1364 } 1365 if (0 == c) 1366 { 1367 west = east = x; 1368 south = north = y; 1369 have_box = 1; 1370 continue; 1371 } 1372 if (x < west) 1373 west = x; 1374 if (x > east) 1375 east = x; 1376 if (y < south) 1377 south = y; 1378 if (y > north) 1379 north = y; 1380 } 1381 } 1382 } 1383 /* The box is in whatever units the CRS uses -- degrees for a 1384 geographic CRS, metres for a typical projected one. We emit it 1385 unconverted and let COORDINATE_SYSTEM say which; reprojecting 1386 would mean linking PROJ. */ 1387 if ( (have_box) && 1388 (EXTRACTOR_forensic_emit_ (ctx->ec, 1389 "geotiff", 1390 EXTRACTOR_METATYPE_BOUNDING_BOX, 1391 "%.10g,%.10g,%.10g,%.10g", 1392 west, 1393 south, 1394 east, 1395 north)) ) 1396 return 1; 1397 { 1398 double tz; 1399 1400 /* The tiepoint's z is only meaningful when the file actually 1401 carries a vertical dimension; a plain 2D raster stores 0 there. */ 1402 if ( (tag_double (ctx, W_TIEPOINT, 5, &tz)) && 1403 (isfinite (tz)) && 1404 (0.0 != tz) && 1405 ( (gk->have_vertical) || 1406 (0.0 != sz) ) && 1407 (EXTRACTOR_forensic_emit_ (ctx->ec, 1408 "geotiff", 1409 EXTRACTOR_METATYPE_LOCATION_ELEVATION, 1410 "%.10g", 1411 tz)) ) 1412 return 1; 1413 } 1414 return 0; 1415 } 1416 1417 1418 /** 1419 * Find @a needle in @a hay. 1420 * 1421 * @param hay where to search 1422 * @param hay_len number of bytes in @a hay 1423 * @param from index to start searching at 1424 * @param needle NUL-terminated string to look for 1425 * @param[out] pos index of the match 1426 * @return 1 if found, 0 if not 1427 */ 1428 static int 1429 find_sub (const char *hay, 1430 size_t hay_len, 1431 size_t from, 1432 const char *needle, 1433 size_t *pos) 1434 { 1435 size_t nlen = strlen (needle); 1436 1437 if ( (0 == nlen) || 1438 (hay_len < nlen) ) 1439 return 0; 1440 for (size_t i = from; i + nlen <= hay_len; i++) 1441 if (0 == memcmp (&hay[i], 1442 needle, 1443 nlen)) 1444 { 1445 *pos = i; 1446 return 1; 1447 } 1448 return 0; 1449 } 1450 1451 1452 /** 1453 * Pull `<Item name="...">value</Item>' pairs out of GDAL's private 1454 * metadata tag. This is where a GDAL-produced raster keeps its real 1455 * provenance: the acquisition time, the sensor, the processing chain. 1456 * 1457 * We do not decode XML entities or attributes beyond `name'; the point 1458 * is a cheap characterisation, and a value that needed unescaping is 1459 * still recognisable. 1460 * 1461 * @param ctx extraction state 1462 * @param xml the tag contents 1463 * @param len number of bytes in @a xml 1464 * @return 1 if the caller should stop extracting, 0 to continue 1465 */ 1466 static int 1467 scan_gdal_metadata (const struct Context *ctx, 1468 const char *xml, 1469 size_t len) 1470 { 1471 /* GDAL item names that name the thing that made the data rather 1472 than describing the data. */ 1473 static const char *device_items[] = { 1474 "SENSOR", 1475 "SENSOR_NAME", 1476 "SENSORNAME", 1477 "SENSOR_ID", 1478 "INSTRUMENT", 1479 "PLATFORM", 1480 "SATELLITEID", 1481 NULL 1482 }; 1483 unsigned int items = 0; 1484 size_t i = 0; 1485 1486 while ( (i < len) && 1487 (items < GEOTIFF_MAX_GDAL_ITEMS) ) 1488 { 1489 size_t open; 1490 size_t tag_end; 1491 size_t name_start; 1492 size_t name_end; 1493 size_t close; 1494 size_t name_len; 1495 size_t val_len; 1496 enum EXTRACTOR_MetaType type = EXTRACTOR_METATYPE_COMMENT; 1497 char buf[EXTRACTOR_FORENSIC_MAX_STRING]; 1498 int n; 1499 1500 if (! find_sub (xml, len, i, "<Item", &open)) 1501 break; 1502 if (! find_sub (xml, len, open, ">", &tag_end)) 1503 break; 1504 i = tag_end + 1; 1505 if (! find_sub (xml, tag_end, open, "name=\"", &name_start)) 1506 continue; /* an Item without a name; skip it, keep scanning */ 1507 name_start += strlen ("name=\""); 1508 if (! find_sub (xml, tag_end, name_start, "\"", &name_end)) 1509 continue; 1510 if (! find_sub (xml, len, tag_end, "</Item>", &close)) 1511 break; 1512 name_len = name_end - name_start; 1513 val_len = close - (tag_end + 1); 1514 i = close + strlen ("</Item>"); 1515 items++; 1516 if ( (0 == name_len) || 1517 (64 < name_len) || 1518 (0 == val_len) || 1519 (256 < val_len) ) 1520 continue; 1521 for (unsigned int k = 0; NULL != device_items[k]; k++) 1522 if ( (strlen (device_items[k]) == name_len) && 1523 (0 == memcmp (device_items[k], 1524 &xml[name_start], 1525 name_len)) ) 1526 { 1527 type = EXTRACTOR_METATYPE_SOURCE_DEVICE; 1528 break; 1529 } 1530 if (EXTRACTOR_METATYPE_SOURCE_DEVICE == type) 1531 n = snprintf (buf, 1532 sizeof (buf), 1533 "%.*s", 1534 (int) val_len, 1535 &xml[tag_end + 1]); 1536 else 1537 n = snprintf (buf, 1538 sizeof (buf), 1539 "%.*s=%.*s", 1540 (int) name_len, 1541 &xml[name_start], 1542 (int) val_len, 1543 &xml[tag_end + 1]); 1544 if ( (0 >= n) || 1545 (((size_t) n) >= sizeof (buf)) ) 1546 continue; 1547 if (EXTRACTOR_forensic_emit_text_ (ctx->ec, 1548 "geotiff", 1549 type, 1550 buf, 1551 (size_t) n)) 1552 return 1; 1553 } 1554 return 0; 1555 } 1556 1557 1558 /** 1559 * Emit the GDAL private tags, if the file has them. 1560 * 1561 * @param ctx extraction state 1562 * @return 1 if the caller should stop extracting, 0 to continue 1563 */ 1564 static int 1565 emit_gdal (const struct Context *ctx) 1566 { 1567 unsigned char *buf; 1568 size_t len; 1569 int stop; 1570 1571 if ( (ctx->tags[W_GDAL_NODATA].found) && 1572 (TT_ASCII == ctx->tags[W_GDAL_NODATA].type) ) 1573 { 1574 buf = load_value (ctx, 1575 &ctx->tags[W_GDAL_NODATA], 1576 64, 1577 &len); 1578 if (NULL != buf) 1579 { 1580 char nod[128]; 1581 int n; 1582 1583 /* trim to the C string GDAL wrote, then label it: a bare "-9999" 1584 under COMMENT would be unreadable */ 1585 for (size_t i = 0; i < len; i++) 1586 if ('\0' == buf[i]) 1587 { 1588 len = i; 1589 break; 1590 } 1591 n = snprintf (nod, 1592 sizeof (nod), 1593 "GDAL nodata value: %.*s", 1594 (int) len, 1595 (const char *) buf); 1596 free (buf); 1597 if ( (0 < n) && 1598 (((size_t) n) < sizeof (nod)) && 1599 (EXTRACTOR_forensic_emit_text_ (ctx->ec, 1600 "geotiff", 1601 EXTRACTOR_METATYPE_COMMENT, 1602 nod, 1603 (size_t) n)) ) 1604 return 1; 1605 } 1606 } 1607 if ( (! ctx->tags[W_GDAL_META].found) || 1608 (TT_ASCII != ctx->tags[W_GDAL_META].type) ) 1609 return 0; 1610 buf = load_value (ctx, 1611 &ctx->tags[W_GDAL_META], 1612 GEOTIFF_MAX_VALUE, 1613 &len); 1614 if (NULL == buf) 1615 return 0; 1616 for (size_t i = 0; i < len; i++) 1617 if ('\0' == buf[i]) 1618 { 1619 len = i; 1620 break; 1621 } 1622 stop = scan_gdal_metadata (ctx, 1623 (const char *) buf, 1624 len); 1625 free (buf); 1626 return stop; 1627 } 1628 1629 1630 /** 1631 * Emit the plain TIFF descriptive tags: geometry, codec and the 1632 * provenance strings. 1633 * 1634 * @param ctx extraction state 1635 * @return 1 if the caller should stop extracting, 0 to continue 1636 */ 1637 static int 1638 emit_image_tags (const struct Context *ctx) 1639 { 1640 static const struct 1641 { 1642 unsigned int code; 1643 const char *name; 1644 } codecs[] = { 1645 { 1, "none" }, 1646 { 2, "CCITT modified Huffman RLE" }, 1647 { 3, "CCITT Group 3 fax" }, 1648 { 4, "CCITT Group 4 fax" }, 1649 { 5, "LZW" }, 1650 { 6, "JPEG (old-style)" }, 1651 { 7, "JPEG" }, 1652 { 8, "Adobe Deflate" }, 1653 { 32773, "PackBits" }, 1654 { 32946, "Deflate" }, 1655 { 34712, "JPEG 2000" }, 1656 { 34887, "LERC" }, 1657 { 34925, "LZMA" }, 1658 { 50000, "ZSTD" }, 1659 { 50001, "WEBP" }, 1660 { 0, NULL } 1661 }; 1662 double width; 1663 double height; 1664 double bits; 1665 double samples; 1666 double comp; 1667 1668 if ( (tag_double (ctx, W_WIDTH, 0, &width)) && 1669 (tag_double (ctx, W_LENGTH, 0, &height)) && 1670 (isfinite (width)) && 1671 (isfinite (height)) && 1672 (0.0 < width) && 1673 (0.0 < height) && 1674 (GEOTIFF_MAX_DIM > width) && 1675 (GEOTIFF_MAX_DIM > height) && 1676 (EXTRACTOR_forensic_emit_ (ctx->ec, 1677 "geotiff", 1678 EXTRACTOR_METATYPE_IMAGE_DIMENSIONS, 1679 "%llux%llu", 1680 (unsigned long long) width, 1681 (unsigned long long) height)) ) 1682 return 1; 1683 if ( (tag_double (ctx, W_BITS, 0, &bits)) && 1684 (isfinite (bits)) && 1685 (0.0 < bits) && 1686 (4096.0 > bits) && 1687 (EXTRACTOR_forensic_emit_ (ctx->ec, 1688 "geotiff", 1689 EXTRACTOR_METATYPE_COLOR_DEPTH, 1690 "%llu", 1691 (unsigned long long) bits)) ) 1692 return 1; 1693 if ( (tag_double (ctx, W_SAMPLES, 0, &samples)) && 1694 (isfinite (samples)) && 1695 (0.0 < samples) && 1696 (4096.0 > samples) && 1697 (EXTRACTOR_forensic_emit_ (ctx->ec, 1698 "geotiff", 1699 EXTRACTOR_METATYPE_CHANNELS, 1700 "%llu", 1701 (unsigned long long) samples)) ) 1702 return 1; 1703 if ( (tag_double (ctx, W_COMPRESSION, 0, &comp)) && 1704 (isfinite (comp)) && 1705 (0.0 <= comp) && 1706 (65536.0 > comp) ) 1707 { 1708 unsigned int code = (unsigned int) comp; 1709 const char *name = NULL; 1710 1711 for (unsigned int i = 0; NULL != codecs[i].name; i++) 1712 if (codecs[i].code == code) 1713 { 1714 name = codecs[i].name; 1715 break; 1716 } 1717 if (NULL != name) 1718 { 1719 if (EXTRACTOR_forensic_emit_ (ctx->ec, 1720 "geotiff", 1721 EXTRACTOR_METATYPE_CODEC, 1722 "%s", 1723 name)) 1724 return 1; 1725 } 1726 else if (EXTRACTOR_forensic_emit_ (ctx->ec, 1727 "geotiff", 1728 EXTRACTOR_METATYPE_CODEC, 1729 "TIFF compression %u", 1730 code)) 1731 { 1732 return 1; 1733 } 1734 } 1735 if (emit_ascii_tag (ctx, 1736 W_SOFTWARE, 1737 EXTRACTOR_METATYPE_CREATED_BY_SOFTWARE)) 1738 return 1; 1739 if (emit_ascii_tag (ctx, 1740 W_DESCRIPTION, 1741 EXTRACTOR_METATYPE_DESCRIPTION)) 1742 return 1; 1743 if (emit_ascii_tag (ctx, 1744 W_ARTIST, 1745 EXTRACTOR_METATYPE_AUTHOR_NAME)) 1746 return 1; 1747 if (emit_ascii_tag (ctx, 1748 W_COPYRIGHT, 1749 EXTRACTOR_METATYPE_COPYRIGHT)) 1750 return 1; 1751 if (emit_ascii_tag (ctx, 1752 W_MAKE, 1753 EXTRACTOR_METATYPE_DEVICE_MANUFACTURER)) 1754 return 1; 1755 if (emit_ascii_tag (ctx, 1756 W_MODEL, 1757 EXTRACTOR_METATYPE_DEVICE_MODEL)) 1758 return 1; 1759 return 0; 1760 } 1761 1762 1763 /** 1764 * Emit TIFF's DateTime tag, which is `YYYY:MM:DD HH:MM:SS' in 1765 * unspecified local time. 1766 * 1767 * We re-spell it as ISO 8601 but deliberately do not append a `Z': 1768 * TIFF 6.0 attaches no time zone to the field, and claiming UTC would 1769 * be inventing information. 1770 * 1771 * @param ctx extraction state 1772 * @return 1 if the caller should stop extracting, 0 to continue 1773 */ 1774 static int 1775 emit_datetime (const struct Context *ctx) 1776 { 1777 unsigned char *buf; 1778 size_t len; 1779 unsigned int v[6]; 1780 int stop; 1781 1782 if (TT_ASCII != ctx->tags[W_DATETIME].type) 1783 return 0; 1784 buf = load_value (ctx, 1785 &ctx->tags[W_DATETIME], 1786 64, 1787 &len); 1788 if (NULL == buf) 1789 return 0; 1790 if (19 > len) 1791 { 1792 free (buf); 1793 return 0; 1794 } 1795 /* fixed layout: 4-2-2 date, space, 2-2-2 time, all digits */ 1796 { 1797 static const unsigned int digit_at[] = { 1798 0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18 1799 }; 1800 int ok = ( (':' == buf[4]) && 1801 (':' == buf[7]) && 1802 (' ' == buf[10]) && 1803 (':' == buf[13]) && 1804 (':' == buf[16]) ); 1805 1806 for (unsigned int i = 0; 1807 (ok) && (i < sizeof (digit_at) / sizeof (digit_at[0])); 1808 i++) 1809 if ( ('0' > buf[digit_at[i]]) || 1810 ('9' < buf[digit_at[i]]) ) 1811 ok = 0; 1812 if (! ok) 1813 { 1814 free (buf); 1815 return 0; 1816 } 1817 } 1818 v[0] = (unsigned int) ((buf[0] - '0') * 1000 + (buf[1] - '0') * 100 1819 + (buf[2] - '0') * 10 + (buf[3] - '0')); 1820 v[1] = (unsigned int) ((buf[5] - '0') * 10 + (buf[6] - '0')); 1821 v[2] = (unsigned int) ((buf[8] - '0') * 10 + (buf[9] - '0')); 1822 v[3] = (unsigned int) ((buf[11] - '0') * 10 + (buf[12] - '0')); 1823 v[4] = (unsigned int) ((buf[14] - '0') * 10 + (buf[15] - '0')); 1824 v[5] = (unsigned int) ((buf[17] - '0') * 10 + (buf[18] - '0')); 1825 free (buf); 1826 if ( (1900 > v[0]) || 1827 (2200 < v[0]) || 1828 (1 > v[1]) || (12 < v[1]) || 1829 (1 > v[2]) || (31 < v[2]) || 1830 (23 < v[3]) || (59 < v[4]) || (60 < v[5]) ) 1831 return 0; /* a zeroed or garbage field, not a date */ 1832 stop = EXTRACTOR_forensic_emit_ (ctx->ec, 1833 "geotiff", 1834 EXTRACTOR_METATYPE_CREATION_DATE, 1835 "%04u-%02u-%02uT%02u:%02u:%02u", 1836 v[0], v[1], v[2], v[3], v[4], v[5]); 1837 return stop; 1838 } 1839 1840 1841 /** 1842 * Main entry method for the GeoTIFF extraction plugin. 1843 * 1844 * @param ec extraction context provided to the plugin 1845 */ 1846 void 1847 EXTRACTOR_geotiff_extract_method (struct EXTRACTOR_ExtractContext *ec); 1848 1849 void 1850 EXTRACTOR_geotiff_extract_method (struct EXTRACTOR_ExtractContext *ec) 1851 { 1852 struct Context ctx; 1853 struct GeoKeys gk; 1854 unsigned char hdr[16]; 1855 uint64_t first; 1856 uint16_t version; 1857 1858 memset (&ctx, 1859 0, 1860 sizeof (ctx)); 1861 ctx.ec = ec; 1862 ctx.fsize = ec->get_size (ec->cls); 1863 if ( (UINT64_MAX == ctx.fsize) || 1864 (16 > ctx.fsize) || 1865 (ctx.fsize > (uint64_t) INT64_MAX) ) 1866 return; 1867 if (! EXTRACTOR_forensic_read_ (ec, 1868 0, 1869 hdr, 1870 sizeof (hdr))) 1871 return; 1872 /* Bail out on the very first bytes: almost nothing we are handed is 1873 a TIFF, and this plugin must cost nothing for the rest. */ 1874 if (0 == memcmp (hdr, "II", 2)) 1875 ctx.be = 0; 1876 else if (0 == memcmp (hdr, "MM", 2)) 1877 ctx.be = 1; 1878 else 1879 return; 1880 version = geo_u16 (&ctx, 1881 &hdr[2]); 1882 if (42 == version) 1883 { 1884 ctx.big = 0; 1885 first = (uint64_t) geo_u32 (&ctx, 1886 &hdr[4]); 1887 } 1888 else if (43 == version) 1889 { 1890 /* BigTIFF: the header states the offset width, which the format 1891 has so far only ever used as 8. */ 1892 ctx.big = 1; 1893 if (8 != geo_u16 (&ctx, &hdr[4])) 1894 return; 1895 if (0 != geo_u16 (&ctx, &hdr[6])) 1896 return; 1897 first = geo_u64 (&ctx, 1898 &hdr[8]); 1899 } 1900 else 1901 { 1902 return; /* a TIFF-like magic we do not know */ 1903 } 1904 walk_ifds (&ctx, 1905 first); 1906 /* This is the whole point of the plugin being separate from `tiff': 1907 unless one of the four georeferencing tags is present the file is 1908 an ordinary TIFF and we say nothing at all about it. */ 1909 if ( (! ctx.tags[W_PIXELSCALE].found) && 1910 (! ctx.tags[W_TIEPOINT].found) && 1911 (! ctx.tags[W_TRANSFORM].found) && 1912 (! ctx.tags[W_GEOKEYS].found) ) 1913 return; 1914 if (0 != 1915 ec->proc (ec->cls, 1916 "geotiff", 1917 EXTRACTOR_METATYPE_MIMETYPE, 1918 EXTRACTOR_METAFORMAT_UTF8, 1919 "text/plain", 1920 "image/tiff", 1921 strlen ("image/tiff") + 1)) 1922 return; 1923 if (0 != 1924 ec->proc (ec->cls, 1925 "geotiff", 1926 EXTRACTOR_METATYPE_FORMAT, 1927 EXTRACTOR_METAFORMAT_UTF8, 1928 "text/plain", 1929 "GeoTIFF", 1930 strlen ("GeoTIFF") + 1)) 1931 return; 1932 if (ctx.big && 1933 (0 != 1934 ec->proc (ec->cls, 1935 "geotiff", 1936 EXTRACTOR_METATYPE_FORMAT_VERSION, 1937 EXTRACTOR_METAFORMAT_UTF8, 1938 "text/plain", 1939 "BigTIFF", 1940 strlen ("BigTIFF") + 1))) 1941 return; 1942 if (emit_image_tags (&ctx)) 1943 return; 1944 if (emit_datetime (&ctx)) 1945 return; 1946 if (parse_geo_keys (&ctx, 1947 &gk)) 1948 return; 1949 if (emit_crs (&ctx, 1950 &gk)) 1951 return; 1952 if (emit_geometry (&ctx, 1953 &gk)) 1954 return; 1955 if (emit_gdal (&ctx)) 1956 return; 1957 } 1958 1959 1960 /* end of geotiff_extractor.c */