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

From 092ed226f54b61139031e4bf26c8c3471ee1a9df 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)

(cherry picked from commit e6b07b2ef4a220d01681b9e3c7bede4bddeacadf)
---
 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 7df972ea..fa39ca9d 100644
--- a/libtiff/tif_dirread.c
+++ b/libtiff/tif_dirread.c
@@ -5534,13 +5534,38 @@ TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover)
 		case TIFF_SETGET_C32_UINT8:
 			{
 				uint8* data;
+				uint32 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*)origdata,count);
+				        data = (uint8*)origdata;
+				        count = (uint32)(count * 4);
+				    }
+				}
+				else
+				{
+				    err=TIFFReadDirEntryByteArray(tif,dp,&data);
+				    count = (uint32)(dp->tdir_count);
+				}
 				if (err==TIFFReadDirEntryErrOk)
 				{
 					int m;
-					m=TIFFSetField(tif,dp->tdir_tag,(uint32)(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 bc8c6105..4cce6cf2 100644
--- a/libtiff/tif_print.c
+++ b/libtiff/tif_print.c
@@ -200,13 +200,9 @@ _TIFFPrettyPrintField(TIFF* tif, const TIFFField *fip, FILE* fd, uint32 tag,
 			return 1;
 		}
 		case TIFFTAG_RICHTIFFIPTC:
-			/*
-			 * XXX: for some weird reason RichTIFFIPTC tag
-			 * defined as array of LONG values.
-			 */
 			fprintf(fd,
 			    "  RichTIFFIPTC Data: <present>, %lu bytes\n",
-			    (unsigned long) value_count * 4);
+			    (unsigned long) value_count );
 			return 1;
 
 		case TIFFTAG_PHOTOSHOP: