libtiff: Deal with RichTIFFIPTC tag written with LONG type (fixes #225)

From e6b07b2ef4a220d01681b9e3c7bede4bddeacadf Mon Sep 17 00:00:00 2001
From: Even Rouault <[EMAIL REDACTED]>
Date: Tue, 9 Aug 2022 11:16:27 +0200
Subject: [PATCH] Deal with RichTIFFIPTC tag written with LONG type (fixes
 #225)

---
 libtiff/tif_dirread.c | 29 +++++++++++++++++++++++++++--
 libtiff/tif_print.c   |  6 +-----
 2 files changed, 28 insertions(+), 7 deletions(-)

diff --git a/libtiff/tif_dirread.c b/libtiff/tif_dirread.c
index 32653f04..c6218829 100644
--- a/libtiff/tif_dirread.c
+++ b/libtiff/tif_dirread.c
@@ -6168,13 +6168,38 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
 		case TIFF_SETGET_C32_UINT8:
 			{
 				uint8_t* data;
+				uint32_t count = 0;
 				assert(fip->field_readcount==TIFF_VARIABLE2);
 				assert(fip->field_passcount==1);
-				err=TIFFReadDirEntryByteArray(tif,dp,&data);
+				if( fip->field_tag == TIFFTAG_RICHTIFFIPTC &&
+				    dp->tdir_type == TIFF_LONG )
+				{
+				    /* Adobe's software (wrongly) writes RichTIFFIPTC tag with
+				     * data type LONG instead of UNDEFINED. Work around this
+				     * frequently found issue */
+				    void* origdata;
+				    err=TIFFReadDirEntryArray(tif,dp,&count,4,&origdata);
+				    if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
+				    {
+				        data = NULL;
+				    }
+				    else
+				    {
+				        if (tif->tif_flags&TIFF_SWAB)
+				            TIFFSwabArrayOfLong((uint32_t*)origdata,count);
+				        data = (uint8_t*)origdata;
+				        count = (uint32_t)(count * 4);
+				    }
+				}
+				else
+				{
+				    err=TIFFReadDirEntryByteArray(tif,dp,&data);
+				    count = (uint32_t)(dp->tdir_count);
+				}
 				if (err==TIFFReadDirEntryErrOk)
 				{
 					int m;
-					m=TIFFSetField(tif, dp->tdir_tag, (uint32_t)(dp->tdir_count), data);
+					m=TIFFSetField(tif, dp->tdir_tag, count, data);
 					if (data!=0)
 						_TIFFfree(data);
 					if (!m)
diff --git a/libtiff/tif_print.c b/libtiff/tif_print.c
index 80a9d90f..16ce5780 100644
--- a/libtiff/tif_print.c
+++ b/libtiff/tif_print.c
@@ -199,13 +199,9 @@ _TIFFPrettyPrintField(TIFF* tif, const TIFFField *fip, FILE* fd, uint32_t tag,
 			return 1;
 		}
 		case TIFFTAG_RICHTIFFIPTC:
-			/*
-			 * XXX: for some weird reason RichTIFFIPTC tag
-			 * defined as array of LONG values.
-			 */
 			fprintf(fd,
 			    "  RichTIFFIPTC Data: <present>, %"PRIu32" bytes\n",
-			    value_count * 4u);
+			    value_count);
 			return 1;
 
 		case TIFFTAG_PHOTOSHOP: