summaryrefslogtreecommitdiff
path: root/vcl/source/filter/itiff/itiff.cxx
blob: bdf4999df514bff16797028b7462fc81fbe63e80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>
#include <sal/log.hxx>

#include <comphelper/scopeguard.hxx>
#include <vcl/graph.hxx>
#include <vcl/BitmapTools.hxx>
#include <vcl/animate/Animation.hxx>
#include <vcl/BitmapWriteAccess.hxx>
#include <tools/fract.hxx>
#include <tools/stream.hxx>
#include <comphelper/configuration.hxx>

#include <tiffio.h>

#include <filter/TiffReader.hxx>

namespace
{
    struct Context
    {
        SvStream& rStream;
        tsize_t nStart;
        tsize_t nSize;
        ErrCode nOrigError;
        bool bAllowOneShortRead;
        Context(SvStream& rInStream)
            : rStream(rInStream)
            , nStart(rInStream.Tell())
            , nSize(rInStream.remainingSize())
            , nOrigError(rInStream.GetError())
            , bAllowOneShortRead(false)
        {
        }
        ~Context()
        {
            rStream.SetError(nOrigError);
        }
    };
}

static tsize_t tiff_read(thandle_t handle, tdata_t buf, tsize_t size)
{
    Context* pContext = static_cast<Context*>(handle);
    if (pContext->rStream.bad())
        return 0;

    tsize_t nRead = pContext->rStream.ReadBytes(buf, size);
    // tdf#149417 allow one short read, which is similar to what
    // we do for jpeg since tdf#138950
    if (nRead < size && pContext->bAllowOneShortRead)
    {
        memset(static_cast<char*>(buf) + nRead, 0, size - nRead);
        pContext->bAllowOneShortRead = false;
        return size;
    }
    return nRead;
}

static tsize_t tiff_write(thandle_t, tdata_t, tsize_t)
{
    return -1;
}

static toff_t tiff_seek(thandle_t handle, toff_t offset, int whence)
{
    Context* pContext = static_cast<Context*>(handle);

    switch (whence)
    {
        case SEEK_SET:
            offset = pContext->nStart + offset;
            break;
        case SEEK_CUR:
            offset = pContext->rStream.Tell() + offset;
            break;
        case SEEK_END:
            offset = pContext->rStream.TellEnd() + offset;
            break;
        default:
            assert(false && "unknown seek type");
            break;
    }

    if (pContext->rStream.bad() || !checkSeek(pContext->rStream, offset))
    {
        offset = pContext->rStream.Tell();
        pContext->rStream.SetError(SVSTREAM_SEEK_ERROR);
    }

    return offset - pContext->nStart;
}

static int tiff_close(thandle_t)
{
    return 0;
}

static toff_t tiff_size(thandle_t handle)
{
    Context* pContext = static_cast<Context*>(handle);
    return pContext->nSize;
}

bool ImportTiffGraphicImport(SvStream& rTIFF, Graphic& rGraphic)
{
    auto origErrorHandler = TIFFSetErrorHandler(nullptr);
    auto origWarningHandler = TIFFSetWarningHandler(nullptr);
    comphelper::ScopeGuard restoreDefaultHandlers([&]() {
        TIFFSetErrorHandler(origErrorHandler);
        TIFFSetWarningHandler(origWarningHandler);
    });

    Context aContext(rTIFF);
    TIFF* tif = TIFFClientOpen("libtiff-svstream", "r", &aContext,
                               tiff_read, tiff_write,
                               tiff_seek, tiff_close,
                               tiff_size, nullptr, nullptr);

    if (!tif)
        return false;

    const auto nOrigPos = rTIFF.Tell();

    Animation aAnimation;

    const bool bFuzzing = comphelper::IsFuzzing();
    uint64_t nTotalPixelsRequired = 0;

    do
    {
        uint32_t w, h;

        if (TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w) != 1)
        {
            SAL_WARN("filter.tiff", "missing width");
            break;
        }

        if (TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h) != 1)
        {
            SAL_WARN("filter.tiff", "missing height");
            break;
        }

        if (w > SAL_MAX_INT32 / 32 || h > SAL_MAX_INT32 / 32)
        {
            SAL_WARN("filter.tiff", "image too large");
            break;
        }

        uint32_t nPixelsRequired;
        constexpr size_t nMaxPixelsAllowed = SAL_MAX_INT32/4;
        // two buffers currently required, so limit further
        bool bOk = !o3tl::checked_multiply(w, h, nPixelsRequired) && nPixelsRequired <= nMaxPixelsAllowed / 2;
        SAL_WARN_IF(!bOk, "filter.tiff", "skipping oversized tiff image " << w << " x " << h);

        if (!TIFFIsTiled(tif))
        {
            size_t nStripSize = TIFFStripSize(tif);
            if (nStripSize > SAL_MAX_INT32)
            {
                SAL_WARN("filter.tiff", "skipping oversized tiff strip size " << nStripSize);
                bOk = false;
            }
        }

        uint16_t PhotometricInterpretation(0);
        uint16_t Compression(COMPRESSION_NONE);
        if (bOk)
        {
            TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &PhotometricInterpretation);
            TIFFGetField(tif, TIFFTAG_COMPRESSION, &Compression);
        }

        if (bOk && bFuzzing)
        {
            const uint64_t MAX_PIXEL_SIZE = 120000000;
            const uint64_t MAX_TILE_SIZE = 100000000;
            nTotalPixelsRequired += nPixelsRequired;
            if (TIFFTileSize64(tif) > MAX_TILE_SIZE || nTotalPixelsRequired > MAX_PIXEL_SIZE)
            {
                SAL_WARN("filter.tiff", "skipping large tiffs");
                break;
            }

            if (TIFFIsTiled(tif))
            {
                uint32_t tw, th;
                TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw);
                TIFFGetField(tif, TIFFTAG_TILELENGTH, &th);

                if (tw > w || th > h)
                {
                    bOk = th < 1000 * tw && tw < 1000 * th;
                    SAL_WARN_IF(!bOk, "filter.tiff", "skipping slow bizarre ratio tile of " << tw << " x " << th << " for image of " << w << " x " << h);
                }

                if (PhotometricInterpretation == PHOTOMETRIC_LOGL)
                {
                    uint32_t nLogLBufferRequired;
                    bOk &= !o3tl::checked_multiply(tw, th, nLogLBufferRequired) && nLogLBufferRequired < MAX_PIXEL_SIZE;
                    SAL_WARN_IF(!bOk, "filter.tiff", "skipping oversized tiff tile " << tw << " x " << th);
                }

                if (Compression == COMPRESSION_CCITTFAX4)
                {
                    uint32_t DspRuns;
                    bOk &= !o3tl::checked_multiply(tw, static_cast<uint32_t>(4), DspRuns) && DspRuns < MAX_PIXEL_SIZE;
                    SAL_WARN_IF(!bOk, "filter.tiff", "skipping oversized tiff tile width: " << tw);
                }
            }
        }

        if (!bOk)
            break;

        std::vector<uint32_t> raster(nPixelsRequired);

        const bool bNewCodec = Compression >= COMPRESSION_ZSTD; // >= 50000 at time of writing
        // For tdf#149417 we generally allow one short read for fidelity with the old
        // parser that this replaced. But don't allow that for:
        // a) new compression variations that the old parser didn't handle
        // b) complicated pixel layout variations that the old parser didn't handle
        // so we don't take libtiff into uncharted territory.
        aContext.bAllowOneShortRead = !bNewCodec && PhotometricInterpretation != PHOTOMETRIC_YCBCR;

        if (TIFFReadRGBAImageOriented(tif, w, h, raster.data(), ORIENTATION_TOPLEFT, 1))
        {
            Bitmap bitmap(Size(w, h), vcl::PixelFormat::N24_BPP);
            BitmapScopedWriteAccess access(bitmap);
            if (!access)
            {
                SAL_WARN("filter.tiff", "cannot create image " << w << " x " << h);
                break;
            }

            AlphaMask bitmapAlpha(Size(w, h));
            BitmapScopedWriteAccess accessAlpha(bitmapAlpha);
            if (!accessAlpha)
            {
                SAL_WARN("filter.tiff", "cannot create alpha " << w << " x " << h);
                break;
            }

            /*
                ORIENTATION_TOPLEFT = 1
                ORIENTATION_TOPRIGHT = 2
                ORIENTATION_BOTRIGHT = 3
                ORIENTATION_BOTLEFT = 4
                ORIENTATION_LEFTTOP = 5
                ORIENTATION_RIGHTTOP = 6
                ORIENTATION_RIGHTBOT = 7
                ORIENTATION_LEFTBOT = 8
             */
            uint16_t nOrientation;
            if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &nOrientation) != 1)
                nOrientation = 0;

            for (uint32_t y = 0; y < h; ++y)
            {
                const uint32_t* src = raster.data() + w * y;
                for (uint32_t x = 0; x < w; ++x)
                {
                    sal_uInt8 r = TIFFGetR(*src);
                    sal_uInt8 g = TIFFGetG(*src);
                    sal_uInt8 b = TIFFGetB(*src);
                    sal_uInt8 a = TIFFGetA(*src);

                    uint32_t dest;
                    switch (nOrientation)
                    {
                        case ORIENTATION_LEFTBOT:
                            dest = w - 1 - x;
                            break;
                        default:
                            dest = x;
                            break;
                    }

                    access->SetPixel(y, dest, Color(r, g, b));
                    accessAlpha->SetPixelIndex(y, dest, a);
                    ++src;
                }
            }

            raster.clear();

            access.reset();
            accessAlpha.reset();

            BitmapEx aBitmapEx(bitmap, bitmapAlpha);

            if (!bFuzzing)
            {
                switch (nOrientation)
                {
                    case ORIENTATION_LEFTBOT:
                        aBitmapEx.Rotate(2700_deg10, COL_BLACK);
                        break;
                    default:
                        break;
                }
            }

            MapMode aMapMode;
            uint16_t ResolutionUnit = RESUNIT_NONE;
            if (TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &ResolutionUnit) == 1 && ResolutionUnit != RESUNIT_NONE)
            {
                float xres = 0, yres = 0;

                if (TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) == 1 &&
                    TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) == 1 &&
                    xres != 0 && yres != 0)
                {
                    if (ResolutionUnit == RESUNIT_INCH)
                        aMapMode =  MapMode(MapUnit::MapInch, Point(0,0), Fraction(1/xres), Fraction(1/yres));
                    else if (ResolutionUnit == RESUNIT_CENTIMETER)
                        aMapMode =  MapMode(MapUnit::MapCM, Point(0,0), Fraction(1/xres), Fraction(1/yres));
                }
            }
            aBitmapEx.SetPrefMapMode(aMapMode);
            aBitmapEx.SetPrefSize(Size(w, h));

            AnimationFrame aAnimationFrame(aBitmapEx, Point(0, 0), aBitmapEx.GetSizePixel(),
                                             ANIMATION_TIMEOUT_ON_CLICK, Disposal::Back);
            aAnimation.Insert(aAnimationFrame);
        }
        else
            break;
    } while (TIFFReadDirectory(tif));

    TIFFClose(tif);

    const auto nImages = aAnimation.Count();
    if (nImages)
    {
        if (nImages == 1)
            rGraphic = aAnimation.GetBitmapEx();
        else
            rGraphic = aAnimation;

        // seek to end of TIFF if succeeded
        rTIFF.Seek(STREAM_SEEK_TO_END);

        return true;
    }

    rTIFF.Seek(nOrigPos);
    return false;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */