summaryrefslogtreecommitdiff
path: root/shell/source/win32/zipfile/zipfile.cxx
blob: cf05a56882f5d8faf0a53f829cf8b0c7dd071db1 (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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/* -*- 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 "zipexcptn.hxx"
#include "internal/zipfile.hxx"
#include "internal/global.hxx"
#include "internal/types.hxx"
#include "internal/stream_helper.hxx"

#include <malloc.h>
#include <algorithm>
#include <functional>

#include <string.h>

namespace
{

struct LocalFileHeader
{
    unsigned short min_version;
    unsigned short general_flag;
    unsigned short compression;
    unsigned short lastmod_time;
    unsigned short lastmod_date;
    unsigned crc32;
    unsigned compressed_size;
    unsigned uncompressed_size;
    unsigned short filename_size;
    unsigned short extra_field_size;
    std::string filename;
    std::string extra_field;
    LocalFileHeader()
        : min_version(0), general_flag(0), compression(0), lastmod_time(0), lastmod_date(0),
          crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0), extra_field_size(0),
          filename(), extra_field() {}
    ~LocalFileHeader() {}
};

struct CentralDirectoryEntry
{
    unsigned short creator_version;
    unsigned short min_version;
    unsigned short general_flag;
    unsigned short compression;
    unsigned short lastmod_time;
    unsigned short lastmod_date;
    unsigned crc32;
    unsigned compressed_size;
    unsigned uncompressed_size;
    unsigned short filename_size;
    unsigned short extra_field_size;
    unsigned short file_comment_size;
    unsigned short disk_num;
    unsigned short internal_attr;
    unsigned external_attr;
    unsigned offset;
    std::string filename;
    std::string extra_field;
    std::string file_comment;
    CentralDirectoryEntry()
        : creator_version(0), min_version(0), general_flag(0), compression(0), lastmod_time(0),
          lastmod_date(0), crc32(0), compressed_size(0), uncompressed_size(0), filename_size(0),
          extra_field_size(0), file_comment_size(0), disk_num(0), internal_attr(0),
          external_attr(0), offset(0), filename(), extra_field(), file_comment() {}
    ~CentralDirectoryEntry() {}
};

struct CentralDirectoryEnd
{
    unsigned short disk_num;
    unsigned short cdir_disk;
    unsigned short disk_entries;
    unsigned short cdir_entries;
    unsigned cdir_size;
    unsigned cdir_offset;
    unsigned short comment_size;
    std::string comment;
    CentralDirectoryEnd()
        : disk_num(0), cdir_disk(0), disk_entries(0), cdir_entries(0),
          cdir_size(0), cdir_offset(0), comment_size(0), comment() {}
    ~CentralDirectoryEnd() {}
};

#define CDIR_ENTRY_SIG 0x02014b50
#define LOC_FILE_HEADER_SIG 0x04034b50
#define CDIR_END_SIG 0x06054b50

// This little lot performs in a truly appalling way without
// buffering eg. on an IStream.

static unsigned char readByte(StreamInterface *stream)
{
    if (!stream || stream->stell() == -1)
        throw IOException(-1);
    unsigned char tmpBuf;
    unsigned long numBytesRead = stream->sread(&tmpBuf, 1);
    if (numBytesRead != 1)
        throw IOException(-1);
    return tmpBuf;
}

static unsigned short readShort(StreamInterface *stream)
{
    unsigned short p0 = (unsigned short)readByte(stream);
    unsigned short p1 = (unsigned short)readByte(stream);
    return (unsigned short)(p0|(p1<<8));
}

static unsigned readInt(StreamInterface *stream)
{
    unsigned p0 = (unsigned)readByte(stream);
    unsigned p1 = (unsigned)readByte(stream);
    unsigned p2 = (unsigned)readByte(stream);
    unsigned p3 = (unsigned)readByte(stream);
    return (unsigned)(p0|(p1<<8)|(p2<<16)|(p3<<24));
}

static bool readCentralDirectoryEnd(StreamInterface *stream, CentralDirectoryEnd &end)
{
    try
    {
        unsigned signature = readInt(stream);
        if (signature != CDIR_END_SIG)
            return false;

        end.disk_num = readShort(stream);
        end.cdir_disk = readShort(stream);
        end.disk_entries = readShort(stream);
        end.cdir_entries = readShort(stream);
        end.cdir_size = readInt(stream);
        end.cdir_offset = readInt(stream);
        end.comment_size = readShort(stream);
        end.comment.clear();
        for (unsigned short i = 0; i < end.comment_size; i++)
            end.comment.append(1,(char)readByte(stream));
    }
    catch (...)
    {
        return false;
    }
    return true;
}

static bool readCentralDirectoryEntry(StreamInterface *stream, CentralDirectoryEntry &entry)
{
    try
    {
        unsigned signature = readInt(stream);
        if (signature != CDIR_ENTRY_SIG)
            return false;

        entry.creator_version = readShort(stream);
        entry.min_version = readShort(stream);
        entry.general_flag = readShort(stream);
        entry.compression = readShort(stream);
        entry.lastmod_time = readShort(stream);
        entry.lastmod_date = readShort(stream);
        entry.crc32 = readInt(stream);
        entry.compressed_size = readInt(stream);
        entry.uncompressed_size = readInt(stream);
        entry.filename_size = readShort(stream);
        entry.extra_field_size = readShort(stream);
        entry.file_comment_size = readShort(stream);
        entry.disk_num = readShort(stream);
        entry.internal_attr = readShort(stream);
        entry.external_attr = readInt(stream);
        entry.offset = readInt(stream);
        unsigned short i = 0;
        entry.filename.clear();
        for (i=0; i < entry.filename_size; i++)
            entry.filename.append(1,(char)readByte(stream));
        entry.extra_field.clear();
        for (i=0; i < entry.extra_field_size; i++)
            entry.extra_field.append(1,(char)readByte(stream));
        entry.file_comment.clear();
        for (i=0; i < entry.file_comment_size; i++)
            entry.file_comment.append(1,(char)readByte(stream));
    }
    catch (...)
    {
        return false;
    }
    return true;
}

static bool readLocalFileHeader(StreamInterface *stream, LocalFileHeader &header)
{
    try
    {
        unsigned signature = readInt(stream);
        if (signature != LOC_FILE_HEADER_SIG)
            return false;

        header.min_version = readShort(stream);
        header.general_flag = readShort(stream);
        header.compression = readShort(stream);
        header.lastmod_time = readShort(stream);
        header.lastmod_date = readShort(stream);
        header.crc32 = readInt(stream);
        header.compressed_size = readInt(stream);
        header.uncompressed_size = readInt(stream);
        header.filename_size = readShort(stream);
        header.extra_field_size = readShort(stream);
        unsigned short i = 0;
        header.filename.clear();
        for (i=0; i < header.filename_size; i++)
            header.filename.append(1,(char)readByte(stream));
        header.extra_field.clear();
        for (i=0; i < header.extra_field_size; i++)
            header.extra_field.append(1,(char)readByte(stream));
    }
    catch (...)
    {
        return false;
    }
    return true;
}

static bool areHeadersConsistent(const LocalFileHeader &header, const CentralDirectoryEntry &entry)
{
    if (header.min_version != entry.min_version)
        return false;
    if (header.general_flag != entry.general_flag)
        return false;
    if (header.compression != entry.compression)
        return false;
    if (!(header.general_flag & 0x08))
    {
        if (header.crc32 != entry.crc32)
            return false;
        if (header.compressed_size != entry.compressed_size)
            return false;
        if (header.uncompressed_size != entry.uncompressed_size)
            return false;
    }
    return true;
}

#define BLOCK_SIZE 0x800

static bool findSignatureAtOffset(StreamInterface *stream, unsigned long nOffset)
{
    // read in reasonably sized chunk, and read more, to get overlapping sigs
    unsigned char aBuffer[ BLOCK_SIZE + 4 ];

    stream->sseek(nOffset, SEEK_SET);

    unsigned long nBytesRead = stream->sread(aBuffer, sizeof(aBuffer));
    if (nBytesRead < 0)
        return false;

    for (long n = nBytesRead - 4; n >= 0; n--)
    {
        if (aBuffer[n  ] == 0x50 && aBuffer[n+1] == 0x4b &&
            aBuffer[n+2] == 0x05 && aBuffer[n+3] == 0x06)
        { // a palpable hit ...
            stream->sseek(nOffset + n, SEEK_SET);
            return true;
        }
    }

    return false;
}

static bool findCentralDirectoryEnd(StreamInterface *stream)
{
    if (!stream)
        return false;

    stream->sseek(0,SEEK_END);

    long nLength = stream->stell();
    if (nLength == -1)
        return false;

    try
    {
        for (long nOffset = nLength - BLOCK_SIZE;
             nOffset > 0; nOffset -= BLOCK_SIZE)
        {
            if (findSignatureAtOffset(stream, nOffset))
                return true;
        }
        return findSignatureAtOffset(stream, 0);
    }
    catch (...)
    {
        return false;
    }
}

static bool isZipStream(StreamInterface *stream)
{
    if (!findCentralDirectoryEnd(stream))
        return false;
    CentralDirectoryEnd end;
    if (!readCentralDirectoryEnd(stream, end))
        return false;
    stream->sseek(end.cdir_offset, SEEK_SET);
    CentralDirectoryEntry entry;
    if (!readCentralDirectoryEntry(stream, entry))
        return false;
    stream->sseek(entry.offset, SEEK_SET);
    LocalFileHeader header;
    if (!readLocalFileHeader(stream, header))
        return false;
    if (!areHeadersConsistent(header, entry))
        return false;
    return true;
}

} // anonymous namespace

namespace internal
{
/* for case in-sensitive string comparison */
struct stricmp : public std::unary_function<std::string, bool>
{
    stricmp(const std::string &str) : str_(str)
    {}

    bool operator() (const std::string &other)
    {
        return (0 == _stricmp(str_.c_str(), other.c_str()));
    }

    std::string str_;
};
} // namespace internal

/** Checks whether a file is a zip file or not

    @precond    The given parameter must be a string with length > 0
            The file must exist
            The file must be readable for the current user

    @returns    true if the file is a zip file
            false if the file is not a zip file

    @throws ParameterException if the given file name is empty
            IOException if the specified file doesn't exist
            AccessViolationException if read access to the file is denied
*/
bool ZipFile::IsZipFile(const std::string& /*FileName*/)
{
    return true;
}

bool ZipFile::IsZipFile(void* /*stream*/)
{
    return true;
}


/** Returns wheter the version of the specified zip file may be uncompressed with the
          currently used zlib version or not

    @precond    The given parameter must be a string with length > 0
            The file must exist
            The file must be readable for the current user
            The file must be a valid zip file

    @returns    true if the file may be uncompressed with the currently used zlib
            false if the file may not be uncompressed with the currently used zlib

    @throws ParameterException if the given file name is empty
            IOException if the specified file doesn't exist or is no zip file
            AccessViolationException if read access to the file is denied
*/
bool ZipFile::IsValidZipFileVersionNumber(const std::string& /*FileName*/)
{
    return true;
}

bool ZipFile::IsValidZipFileVersionNumber(void* /* stream*/)
{
    return true;
}


/** Constructs a zip file from a zip file

    @precond    The given parameter must be a string with length > 0
            The file must exist
            The file must be readable for the current user

    @throws ParameterException if the given file name is empty
            IOException if the specified file doesn't exist or is no valid zip file
            AccessViolationException if read access to the file is denied
            WrongZipVersionException if the zip file cannot be uncompressed
            with the used zlib version
*/
ZipFile::ZipFile(const std::string &FileName) :
    m_pStream(0),
    m_bShouldFree(true)
{
    m_pStream = new FileStream(FileName.c_str());
    if (m_pStream && !isZipStream(m_pStream))
    {
        delete m_pStream;
        m_pStream = 0;
    }
}

ZipFile::ZipFile(StreamInterface *stream) :
    m_pStream(stream),
    m_bShouldFree(false)
{
    if (!isZipStream(stream))
        m_pStream = 0;
}


/** Destroys a zip file
*/
ZipFile::~ZipFile()
{
    if (m_pStream && m_bShouldFree)
        delete m_pStream;
}

/** Provides an interface to read the uncompressed data of a content of the zip file

    @precond    The specified content must exist in this file
            ppstm must not be NULL
*/
void ZipFile::GetUncompressedContent(
    const std::string &ContentName, /*inout*/ ZipContentBuffer_t &ContentBuffer)
{
    if (!findCentralDirectoryEnd(m_pStream))
        return;
    CentralDirectoryEnd end;
    if (!readCentralDirectoryEnd(m_pStream, end))
        return;
    m_pStream->sseek(end.cdir_offset, SEEK_SET);
    CentralDirectoryEntry entry;
    while (m_pStream->stell() != -1 && (unsigned long)m_pStream->stell() < end.cdir_offset + end.cdir_size)
    {
        if (!readCentralDirectoryEntry(m_pStream, entry))
            return;
        if (ContentName.length() == entry.filename_size && !_stricmp(entry.filename.c_str(), ContentName.c_str()))
            break;
    }
    if (ContentName.length() != entry.filename_size)
        return;
    if (_stricmp(entry.filename.c_str(), ContentName.c_str()))
        return;
    m_pStream->sseek(entry.offset, SEEK_SET);
    LocalFileHeader header;
    if (!readLocalFileHeader(m_pStream, header))
        return;
    if (!areHeadersConsistent(header, entry))
        return;
    ContentBuffer.clear();
    ContentBuffer = ZipContentBuffer_t(entry.uncompressed_size);
    if (!entry.compression)
        m_pStream->sread((unsigned char *)&ContentBuffer[0], entry.uncompressed_size);
    else
    {
        int ret;
        z_stream strm;

        /* allocate inflate state */
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = 0;
        strm.next_in = Z_NULL;
        ret = inflateInit2(&strm,-MAX_WBITS);
        if (ret != Z_OK)
            return;

        std::vector<unsigned char> tmpBuffer(entry.compressed_size);
        if (entry.compressed_size != m_pStream->sread(&tmpBuffer[0], entry.compressed_size))
            return;

        strm.avail_in = entry.compressed_size;
        strm.next_in = reinterpret_cast<Bytef *>(&tmpBuffer[0]);

        strm.avail_out = entry.uncompressed_size;
        strm.next_out = reinterpret_cast<Bytef *>(&ContentBuffer[0]);
        ret = inflate(&strm, Z_FINISH);
        switch (ret)
        {
        case Z_NEED_DICT:
        case Z_DATA_ERROR:
        case Z_MEM_ERROR:
            (void)inflateEnd(&strm);
            ContentBuffer.clear();
            return;
        }
        (void)inflateEnd(&strm);
    }
}

/** Returns a list with the content names contained within this file

*/
ZipFile::DirectoryPtr_t ZipFile::GetDirectory() const
{
    DirectoryPtr_t dir(new Directory_t());
    if (!findCentralDirectoryEnd(m_pStream))
        return dir;
    CentralDirectoryEnd end;
    if (!readCentralDirectoryEnd(m_pStream, end))
        return dir;
    m_pStream->sseek(end.cdir_offset, SEEK_SET);
    CentralDirectoryEntry entry;
    while (m_pStream->stell() != -1 && (unsigned long)m_pStream->stell() < end.cdir_offset + end.cdir_size)
    {
        if (!readCentralDirectoryEntry(m_pStream, entry))
            return dir;
        if (entry.filename_size)
            dir->push_back(entry.filename);
    }
    return dir;
}

/** Convinience query function may even realized with
    iterating over a ZipFileDirectory returned by
    GetDirectory */
bool ZipFile::HasContent(const std::string &ContentName) const
{
    //#i34314# we need to compare package content names
    //case in-sensitive as it is not defined that such
    //names must be handled case sensitive
    DirectoryPtr_t dir = GetDirectory();
    Directory_t::iterator iter =
        std::find_if(dir->begin(), dir->end(), internal::stricmp(ContentName));

    return (iter != dir->end());
}


/** Returns the length of the longest file name
        in the current zip file
*/
long ZipFile::GetFileLongestFileNameLength() const
{
    long lmax = 0;
    if (!findCentralDirectoryEnd(m_pStream))
        return lmax;
    CentralDirectoryEnd end;
    if (!readCentralDirectoryEnd(m_pStream, end))
        return lmax;
    m_pStream->sseek(end.cdir_offset, SEEK_SET);
    CentralDirectoryEntry entry;
    while (m_pStream->stell() != -1 && (unsigned long)m_pStream->stell() < end.cdir_offset + end.cdir_size)
    {
        if (!readCentralDirectoryEntry(m_pStream, entry))
            return lmax;
        if (entry.filename_size > lmax)
            lmax = entry.filename_size;
    }
    return lmax;
}

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