Coverage Report

Created: 2026-10-27 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/karchive/src/kzip.cpp
Line
Count
Source
1
/* This file is part of the KDE libraries
2
   SPDX-FileCopyrightText: 2000 David Faure <faure@kde.org>
3
   SPDX-FileCopyrightText: 2002 Holger Schroeder <holger-kde@holgis.net>
4
5
   SPDX-License-Identifier: LGPL-2.0-or-later
6
*/
7
8
#include "kzip.h"
9
#include "karchive_p.h"
10
#include "kcompressiondevice.h"
11
#include "klimitediodevice_p.h"
12
#include "loggingcategory.h"
13
14
#include <QByteArray>
15
#include <QDate>
16
#include <QDebug>
17
#include <QDir>
18
#include <QFile>
19
#include <QHash>
20
#include <QList>
21
#include <QtEndian>
22
#include <qplatformdefs.h>
23
24
#include <string.h>
25
#include <time.h>
26
#include <zlib.h>
27
28
#ifndef QT_STAT_LNK
29
#define QT_STAT_LNK 0120000
30
#endif // QT_STAT_LNK
31
32
static const int max_path_len = 4095; // maximum number of character a path may contain
33
34
static quint16 parseUi16(const char *buffer)
35
2.64M
{
36
2.64M
    return quint16((uchar)buffer[0] | (uchar)buffer[1] << 8);
37
2.64M
}
38
39
static uint parseUi32(const char *buffer)
40
979k
{
41
979k
    return uint((uchar)buffer[0] | (uchar)buffer[1] << 8 | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
42
979k
}
43
44
static quint64 parseUi64(const char *buffer)
45
2.61k
{
46
2.61k
    const uint a = uint((uchar)buffer[0] | (uchar)buffer[1] << 8 | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
47
2.61k
    const uint b = uint((uchar)buffer[4] | (uchar)buffer[5] << 8 | (uchar)buffer[6] << 16 | (uchar)buffer[7] << 24);
48
2.61k
    return (a | (quint64)b << 32);
49
2.61k
}
50
51
static void transformToMsDos(const QDateTime &_dt, char *buffer)
52
0
{
53
0
    const QDateTime dt = _dt.isValid() ? _dt : QDateTime::currentDateTime();
54
    /* clang-format off */
55
0
    const quint16 time = (dt.time().hour() << 11) // 5 bit hour
56
0
                         | (dt.time().minute() << 5) // 6 bit minute
57
0
                         | (dt.time().second() >> 1); // 5 bit double seconds
58
    /* clang-format on */
59
60
0
    buffer[0] = char(time);
61
0
    buffer[1] = char(time >> 8);
62
63
    /* clang-format off */
64
0
    const quint16 date = ((dt.date().year() - 1980) << 9) // 7 bit year 1980-based
65
0
                         | (dt.date().month() << 5) // 4 bit month
66
0
                         | (dt.date().day()); // 5 bit day
67
    /* clang-format on */
68
69
0
    buffer[2] = char(date);
70
0
    buffer[3] = char(date >> 8);
71
0
}
72
73
static uint transformFromMsDos(const char *buffer)
74
403k
{
75
403k
    const quint16 time = parseUi16(buffer);
76
403k
    int h = time >> 11;
77
403k
    int m = (time & 0x7ff) >> 5;
78
403k
    int s = (time & 0x1f) * 2;
79
403k
    QTime qt(h, m, s);
80
81
403k
    const quint16 date = parseUi16(buffer + 2);
82
403k
    int y = (date >> 9) + 1980;
83
403k
    int o = (date & 0x1ff) >> 5;
84
403k
    int d = (date & 0x1f);
85
403k
    QDate qd(y, o, d);
86
87
403k
    QDateTime dt(qd, qt);
88
403k
    return dt.toSecsSinceEpoch();
89
403k
}
90
91
// == parsing routines for zip headers
92
93
/** all relevant information about parsing file information */
94
struct ParseFileInfo {
95
    // file related info
96
    mode_t perm; // permissions of this file
97
    // TODO: use quint32 instead of a uint?
98
    uint atime; // last access time (UNIX format)
99
    uint mtime; // modification time (UNIX format)
100
    uint ctime; // creation time (UNIX format)
101
    int uid; // user id (-1 if not specified)
102
    int gid; // group id (-1 if not specified)
103
    QByteArray guessed_symlink; // guessed symlink target
104
    uint dataoffset = 0; // offset from start of local header to data
105
106
    // parsing related info
107
    bool exttimestamp_seen; // true if extended timestamp extra field
108
    // has been parsed
109
    bool newinfounix_seen; // true if Info-ZIP Unix New extra field has
110
    // been parsed
111
112
    // file sizes from a ZIP64 extra field
113
    quint64 uncompressedSize = 0;
114
    quint64 compressedSize = 0;
115
    // position of the Local File Header itself, or from the
116
    // ZIP64 extra field in the Central Directory
117
    quint64 localheaderoffset = 0;
118
119
    ParseFileInfo()
120
487k
        : perm(0100644)
121
487k
        , uid(-1)
122
487k
        , gid(-1)
123
487k
        , exttimestamp_seen(false)
124
487k
        , newinfounix_seen(false)
125
487k
    {
126
487k
        ctime = mtime = atime = time(nullptr);
127
487k
    }
128
};
129
130
/** updates the parse information with the given extended timestamp extra field.
131
 * @param buffer start content of buffer known to contain an extended
132
 *  timestamp extra field (without magic & size)
133
 * @param size size of field content (must not count magic and size entries)
134
 * @param islocal true if this is a local field, false if central
135
 * @param pfi ParseFileInfo object to be updated
136
 * @return true if processing was successful
137
 */
138
static bool parseExtTimestamp(const char *buffer, int size, bool islocal, ParseFileInfo &pfi)
139
2.03k
{
140
2.03k
    if (size < 1) {
141
        // qCDebug(KArchiveLog) << "premature end of extended timestamp (#1)";
142
2
        return false;
143
2
    } /*end if*/
144
2.03k
    int flags = *buffer; // read flags
145
2.03k
    buffer += 1;
146
2.03k
    size -= 1;
147
148
2.03k
    if (flags & 1) { // contains modification time
149
912
        if (size < 4) {
150
            // qCDebug(KArchiveLog) << "premature end of extended timestamp (#2)";
151
3
            return false;
152
3
        } /*end if*/
153
909
        pfi.mtime = parseUi32(buffer);
154
909
        buffer += 4;
155
909
        size -= 4;
156
909
    } /*end if*/
157
    // central extended field cannot contain more than the modification time
158
    // even if other flags are set
159
2.02k
    if (!islocal) {
160
0
        pfi.exttimestamp_seen = true;
161
0
        return true;
162
0
    } /*end if*/
163
164
2.02k
    if (flags & 2) { // contains last access time
165
1.14k
        if (size < 4) {
166
            // qCDebug(KArchiveLog) << "premature end of extended timestamp (#3)";
167
650
            return true;
168
650
        } /*end if*/
169
492
        pfi.atime = parseUi32(buffer);
170
492
        buffer += 4;
171
492
        size -= 4;
172
492
    } /*end if*/
173
174
1.37k
    if (flags & 4) { // contains creation time
175
750
        if (size < 4) {
176
            // qCDebug(KArchiveLog) << "premature end of extended timestamp (#4)";
177
382
            return true;
178
382
        } /*end if*/
179
368
        pfi.ctime = parseUi32(buffer);
180
368
        buffer += 4;
181
368
    } /*end if*/
182
183
997
    pfi.exttimestamp_seen = true;
184
997
    return true;
185
1.37k
}
186
187
/** updates the parse information with the given Info-ZIP Unix old extra field.
188
 * @param buffer start of content of buffer known to contain an Info-ZIP
189
 *  Unix old extra field (without magic & size)
190
 * @param size size of field content (must not count magic and size entries)
191
 * @param islocal true if this is a local field, false if central
192
 * @param pfi ParseFileInfo object to be updated
193
 * @return true if processing was successful
194
 */
195
static bool parseInfoZipUnixOld(const char *buffer, int size, bool islocal, ParseFileInfo &pfi)
196
1.15k
{
197
    // spec mandates to omit this field if one of the newer fields are available
198
1.15k
    if (pfi.exttimestamp_seen || pfi.newinfounix_seen) {
199
325
        return true;
200
325
    }
201
202
828
    if (size < 8) {
203
        // qCDebug(KArchiveLog) << "premature end of Info-ZIP unix extra field old";
204
269
        return false;
205
269
    }
206
207
559
    pfi.atime = parseUi32(buffer);
208
559
    pfi.mtime = parseUi32(buffer + 4);
209
559
    if (islocal && size >= 12) {
210
364
        pfi.uid = parseUi16(buffer + 8);
211
364
        pfi.gid = parseUi16(buffer + 10);
212
364
    } /*end if*/
213
559
    return true;
214
828
}
215
216
#if 0 // not needed yet
217
/** updates the parse information with the given Info-ZIP Unix new extra field.
218
 * @param buffer start of content of buffer known to contain an Info-ZIP
219
 *      Unix new extra field (without magic & size)
220
 * @param size size of field content (must not count magic and size entries)
221
 * @param islocal true if this is a local field, false if central
222
 * @param pfi ParseFileInfo object to be updated
223
 * @return true if processing was successful
224
 */
225
static bool parseInfoZipUnixNew(const char *buffer, int size, bool islocal,
226
                                ParseFileInfo &pfi)
227
{
228
    if (!islocal) { // contains nothing in central field
229
        pfi.newinfounix = true;
230
        return true;
231
    }
232
233
    if (size < 4) {
234
        qCDebug(KArchiveLog) << "premature end of Info-ZIP unix extra field new";
235
        return false;
236
    }
237
238
    pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
239
    buffer += 2;
240
    pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
241
    buffer += 2;
242
243
    pfi.newinfounix = true;
244
    return true;
245
}
246
#endif
247
248
/**
249
 * parses the extra field
250
 *
251
 * the 64-bit values for uncompressed size, compressed size and local header offset
252
 * are retrieved only if the 32-bit values are 0xFFFFFFFF
253
 *
254
 * @param buffer start of buffer where the extra field is to be found
255
 * @param size size of the extra field
256
 * @param pfi ParseFileInfo object which to write the results into
257
 * @param uncompressedSize32 quint32 32-bit value for uncompressed size
258
 * @param compressedSize32 quint32 32-bit value for compressed size
259
 * @param localHeaderOffset32 quint32 32-bit value for local header offset
260
 * @return true if parsing was successful
261
 */
262
static bool parseExtraField(const char *buffer, int size, ParseFileInfo &pfi, quint32 uncompressedSize32, quint32 compressedSize32, quint32 localHeaderOffset32)
263
405k
{
264
419k
    while (size >= 4) { // as long as a potential extra field can be read
265
20.3k
        int magic = parseUi16(buffer);
266
20.3k
        int fieldsize = parseUi16(buffer + 2);
267
20.3k
        buffer += 4;
268
20.3k
        size -= 4;
269
270
20.3k
        if (fieldsize > size) {
271
            // qCDebug(KArchiveLog) << "fieldsize: " << fieldsize << " size: " << size;
272
            // qCDebug(KArchiveLog) << "premature end of extra fields reached";
273
5.24k
            break;
274
5.24k
        }
275
276
15.1k
        switch (magic) {
277
3.82k
        case 0x0001: {
278
            // ZIP64 extended file information
279
3.82k
            int offset = 0;
280
3.82k
            if (uncompressedSize32 == 0xFFFFFFFF && offset + 8 <= fieldsize) {
281
504
                pfi.uncompressedSize = parseUi64(buffer + offset);
282
504
                offset += 8;
283
504
            }
284
3.82k
            if (compressedSize32 == 0xFFFFFFFF && offset + 8 <= fieldsize) {
285
1.23k
                pfi.compressedSize = parseUi64(buffer + offset);
286
1.23k
                offset += 8;
287
1.23k
            }
288
3.82k
            if (localHeaderOffset32 == 0xFFFFFFFF && offset + 8 <= fieldsize) {
289
133
                pfi.localheaderoffset = parseUi64(buffer + offset);
290
133
                offset += 8;
291
133
            }
292
3.82k
            break;
293
0
        }
294
2.03k
        case 0x5455: // extended timestamp
295
2.03k
            if (!parseExtTimestamp(buffer, fieldsize, true, pfi)) {
296
5
                return false;
297
5
            }
298
2.02k
            break;
299
2.02k
        case 0x5855: // old Info-ZIP unix extra field
300
1.15k
            if (!parseInfoZipUnixOld(buffer, fieldsize, true, pfi)) {
301
269
                return false;
302
269
            }
303
884
            break;
304
#if 0 // not needed yet
305
        case 0x7855:        // new Info-ZIP unix extra field
306
            if (!parseInfoZipUnixNew(buffer, fieldsize, islocal, pfi)) {
307
                return false;
308
            }
309
            break;
310
#endif
311
8.12k
        default:
312
            /* ignore everything else */
313
8.12k
            ;
314
15.1k
        } /*end switch*/
315
316
14.8k
        buffer += fieldsize;
317
14.8k
        size -= fieldsize;
318
14.8k
    } /*wend*/
319
404k
    return true;
320
405k
}
321
322
/**
323
 * Advance the current file position to the next possible header location
324
 *
325
 * @param dev device that is read from
326
 * @param header storage location for the complete header
327
 * @param minSize required size of the header
328
 * @return true if a possible header location matching the 'PK' signature
329
 *     bytes have been found, false if the end of file has been reached
330
 */
331
static bool seekAnyHeader(QIODevice *dev, QByteArray &header, qsizetype minSize)
332
95.5k
{
333
95.5k
    header.resize(1024);
334
95.5k
    int n = dev->peek(header.data(), header.size());
335
336
130k
    while (n >= minSize) {
337
129k
        if (auto i = QByteArrayView(header.data(), n).indexOf("PK"); i >= 0) {
338
94.8k
            dev->skip(i);
339
94.8k
            if ((i + minSize) < n) {
340
94.1k
                header.remove(0, i);
341
94.1k
                header.resize(minSize);
342
94.1k
                return true;
343
94.1k
            } else {
344
637
                n = dev->peek(header.data(), minSize);
345
637
                header.resize(n);
346
637
                return n >= minSize;
347
637
            }
348
94.8k
        }
349
34.9k
        dev->skip(n - 1);
350
34.9k
        n = dev->peek(header.data(), header.size());
351
34.9k
    }
352
723
    header.resize(n);
353
723
    return false;
354
95.5k
}
355
356
/**
357
 * Advance the current file position to the next header following
358
 * a data descriptor
359
 *
360
 * @param dev device that is read from
361
 * @param isZip64 use Zip64 data descriptor layout
362
 * @return true if a data descriptor signature has been found, and the
363
 *     compressed size matches the current position advance
364
 */
365
static bool seekPostDataDescriptor(QIODevice *dev, bool isZip64)
366
1.98k
{
367
    // Both size fields are uint64 for Zip64, uint32 otherwise
368
1.98k
    const qsizetype descriptorSize = isZip64 ? 24 : 16;
369
370
1.98k
    QByteArray header;
371
1.98k
    const qint64 oldPos = dev->pos();
372
373
34.2k
    while (seekAnyHeader(dev, header, descriptorSize)) {
374
        // qCDebug(KArchiveLog) << "Possible data descriptor header at" << dev->pos() << header;
375
34.0k
        if (header.startsWith("PK\x07\x08")) {
376
3.03k
            const qint64 compressedSize = isZip64 ? parseUi64(header.constData() + 8) //
377
3.03k
                                                  : parseUi32(header.constData() + 8);
378
            // Do not move compressedSize to the left side of the check
379
            // we have on the left on purpose to prevent addition overflows
380
3.03k
            if ((compressedSize > 0) && (oldPos == dev->pos() - compressedSize)) {
381
1.75k
                dev->skip(descriptorSize);
382
1.75k
                return true;
383
1.75k
            }
384
1.28k
            dev->skip(4); // Skip found 'PK\7\8'
385
30.9k
        } else {
386
30.9k
            dev->skip(2); // Skip found 'PK'
387
30.9k
        }
388
34.0k
    }
389
230
    return false;
390
1.98k
}
391
392
/**
393
 * Advance the current file position to the next header
394
 * @param dev device that is read from
395
 * @return true if a local or central header token could be reached, false on error
396
 */
397
static bool seekToNextHeaderToken(QIODevice *dev)
398
16.8k
{
399
16.8k
    QByteArray header;
400
401
33.5k
    while (seekAnyHeader(dev, header, 4)) {
402
        // qCDebug(KArchiveLog) << "Possible header at" << dev->pos() << header;
403
        // PK34 for the next local header in case there is no data descriptor
404
        // PK12 for the central header in case there is no data descriptor
405
33.1k
        if (header.startsWith("PK\x03\x04") || header.startsWith("PK\x01\x02")) {
406
16.4k
            return true;
407
16.7k
        } else {
408
16.7k
            dev->skip(2); // Skip found 'PK'
409
16.7k
        }
410
33.1k
    }
411
374
    return false;
412
16.8k
}
413
414
////////////////////////////////////////////////////////////////////////
415
/////////////////////////// KZip ///////////////////////////////////////
416
////////////////////////////////////////////////////////////////////////
417
418
class Q_DECL_HIDDEN KZip::KZipPrivate
419
{
420
public:
421
    KZipPrivate()
422
9.12k
        : m_crc(0)
423
9.12k
        , m_currentFile(nullptr)
424
9.12k
        , m_currentDev(nullptr)
425
9.12k
        , m_compression(8)
426
9.12k
        , m_extraField(KZip::NoExtraField)
427
9.12k
        , m_offset(0)
428
9.12k
    {
429
9.12k
    }
430
431
    unsigned long m_crc; // checksum
432
    KZipFileEntry *m_currentFile; // file currently being written
433
    QIODevice *m_currentDev; // filterdev used to write to the above file
434
    QList<KZipFileEntry *> m_fileList; // flat list of all files, for the index (saves a recursive method ;)
435
    int m_compression;
436
    KZip::ExtraField m_extraField;
437
    // m_offset holds the offset of the place in the zip,
438
    // where new data can be appended. after openarchive it points to 0, when in
439
    // writeonly mode, or it points to the beginning of the central directory.
440
    // each call to writefile updates this value.
441
    quint64 m_offset;
442
    // Position of the first Local File Header
443
    quint64 m_startPos = 0;
444
};
445
446
KZip::KZip(const QString &fileName)
447
0
    : KArchive(fileName)
448
0
    , d(new KZipPrivate)
449
0
{
450
0
}
451
452
KZip::KZip(QIODevice *dev)
453
9.12k
    : KArchive(dev)
454
9.12k
    , d(new KZipPrivate)
455
9.12k
{
456
9.12k
}
457
458
KZip::~KZip()
459
9.12k
{
460
    // qCDebug(KArchiveLog) << this;
461
9.12k
    if (isOpen()) {
462
9.12k
        close();
463
9.12k
    }
464
9.12k
    delete d;
465
9.12k
}
466
467
bool KZip::openArchive(QIODevice::OpenMode mode)
468
9.12k
{
469
    // qCDebug(KArchiveLog);
470
9.12k
    d->m_fileList.clear();
471
472
9.12k
    if (mode == QIODevice::WriteOnly) {
473
0
        return true;
474
0
    }
475
476
9.12k
    char buffer[47];
477
478
    // Check that it's a valid ZIP file
479
    // KArchive::open() opened the underlying device already.
480
481
    // contains information gathered from the local file headers
482
9.12k
    QHash<QByteArray, ParseFileInfo> pfi_map;
483
484
9.12k
    QIODevice *dev = device();
485
486
    // We set a bool for knowing if we are allowed to skip the start of the file
487
9.12k
    bool startOfFile = true;
488
489
9.12k
    qint64 expectedStartPos = 0;
490
491
457k
    for (;;) { // repeat until 'end of entries' signature is reached
492
        // qCDebug(KArchiveLog) << "loop starts";
493
        // qCDebug(KArchiveLog) << "dev->pos() now : " << dev->pos();
494
457k
        int n = dev->read(buffer, 4);
495
496
457k
        if (n < 4) {
497
987
            setErrorString(tr("Invalid ZIP file. Unexpected end of file. (Error code: %1)").arg(1));
498
987
            return false;
499
987
        }
500
501
456k
        if (!memcmp(buffer, "PK\6\6", 4)) { // 'Zip64 end of central directory record'
502
275
            startOfFile = false;
503
275
            break;
504
275
        }
505
506
456k
        if (!memcmp(buffer, "PK\5\6", 4)) { // 'end of entries'
507
            // qCDebug(KArchiveLog) << "PK56 found end of archive at offset" << dev->pos();
508
5.01k
            startOfFile = false;
509
5.01k
            break;
510
5.01k
        }
511
512
451k
        if (!memcmp(buffer, "PK\3\4", 4)) { // local file header
513
            // qCDebug(KArchiveLog) << "PK34 found local file header at offset" << dev->pos();
514
403k
            startOfFile = false;
515
516
403k
            ParseFileInfo pfi;
517
403k
            pfi.localheaderoffset = dev->pos() - 4;
518
519
            // read static header stuff
520
403k
            n = dev->read(buffer, 26);
521
403k
            if (n < 26) {
522
139
                setErrorString(tr("Invalid ZIP file. Unexpected end of file. (Error code: %1)").arg(4));
523
139
                return false;
524
139
            }
525
403k
            int neededVersion = parseUi16(buffer);
526
403k
            bool isZip64 = neededVersion >= 45;
527
528
403k
            int gpf = (uchar)buffer[2]; // "general purpose flag" not "general protection fault" ;-)
529
403k
            int compression_mode = parseUi16(buffer + 4);
530
403k
            uint mtime = transformFromMsDos(buffer + 6);
531
532
403k
            qint64 compr_size = parseUi32(buffer + 14);
533
403k
            qint64 uncomp_size = parseUi32(buffer + 18);
534
403k
            const int namelen = parseUi16(buffer + 22);
535
403k
            const int extralen = parseUi16(buffer + 24);
536
537
            /*
538
              qCDebug(KArchiveLog) << "general purpose bit flag: " << gpf;
539
              qCDebug(KArchiveLog) << "compressed size: " << compr_size;
540
              qCDebug(KArchiveLog) << "uncompressed size: " << uncomp_size;
541
              qCDebug(KArchiveLog) << "namelen: " << namelen;
542
              qCDebug(KArchiveLog) << "extralen: " << extralen;
543
              qCDebug(KArchiveLog) << "archive size: " << dev->size();
544
            */
545
546
            // read fileName
547
403k
            if (namelen <= 0) {
548
34
                setErrorString(tr("Invalid ZIP file. Negative name length"));
549
34
                return false;
550
34
            }
551
403k
            QByteArray fileName = dev->read(namelen);
552
403k
            if (fileName.size() < namelen) {
553
225
                setErrorString(tr("Invalid ZIP file. Name not completely read (#2)"));
554
225
                return false;
555
225
            }
556
557
403k
            pfi.mtime = mtime;
558
403k
            pfi.dataoffset = 30 + extralen + namelen;
559
560
            // read and parse the beginning of the extra field,
561
            // skip rest of extra field in case it is too long
562
403k
            quint64 extraFieldEnd = dev->pos() + extralen;
563
403k
            int handledextralen = qMin(extralen, (int)sizeof buffer);
564
565
            // if (handledextralen)
566
            //    qCDebug(KArchiveLog) << "handledextralen: " << handledextralen;
567
568
403k
            n = dev->read(buffer, handledextralen);
569
            // no error msg necessary as we deliberately truncate the extra field
570
403k
            if (!parseExtraField(buffer, n, pfi, uncomp_size, compr_size, 0)) {
571
13
                setErrorString(tr("Invalid ZIP File. Broken ExtraField."));
572
13
                return false;
573
13
            }
574
575
403k
            if (compr_size == 0xFFFFFFFF) {
576
907
                compr_size = pfi.compressedSize;
577
907
            }
578
403k
            if (uncomp_size == 0xFFFFFFFF) {
579
473
                uncomp_size = pfi.uncompressedSize;
580
473
            }
581
582
            // jump to end of extra field
583
403k
            dev->seek(extraFieldEnd);
584
585
            // we have to take care of the 'general purpose bit flag'.
586
            // if bit 3 is set, the header doesn't contain the length of
587
            // the file and we look for the signature 'PK\7\8'.
588
403k
            if (gpf & 8) {
589
                // here we have to read through the compressed data to find
590
                // the next PKxx
591
1.98k
                if (!seekPostDataDescriptor(dev, isZip64)) {
592
230
                    setErrorString(tr("Could not seek to next header token"));
593
230
                    return false;
594
230
                }
595
401k
            } else {
596
                // here we skip the compressed data and jump to the next header
597
                // qCDebug(KArchiveLog) << "general purpose bit flag indicates, that local file header contains valid size";
598
401k
                bool foundSignature = false;
599
                // check if this could be a symbolic link
600
401k
                if (compression_mode == NoCompression //
601
383k
                    && uncomp_size <= max_path_len //
602
380k
                    && uncomp_size > 0) {
603
                    // read content and store it
604
                    // If it's not a symlink, then we'll just discard the data for now.
605
379k
                    pfi.guessed_symlink = dev->read(uncomp_size);
606
379k
                    if (pfi.guessed_symlink.size() < uncomp_size) {
607
27
                        setErrorString(tr("Invalid ZIP file. Unexpected end of file. (#5)"));
608
27
                        return false;
609
27
                    }
610
379k
                } else {
611
21.8k
                    if (compr_size > dev->size()) {
612
                        // here we cannot trust the compressed size, so scan through the compressed
613
                        // data to find the next header
614
16.8k
                        if (!seekToNextHeaderToken(dev)) {
615
374
                            setErrorString(tr("Could not seek to next header token"));
616
374
                            return false;
617
374
                        }
618
16.4k
                        foundSignature = true;
619
16.4k
                    } else {
620
                        //          qCDebug(KArchiveLog) << "before interesting dev->pos(): " << dev->pos();
621
5.04k
                        if (dev->skip(compr_size) != compr_size) {
622
135
                            setErrorString(tr("Could not seek to file compressed size"));
623
135
                            return false;
624
135
                        }
625
                        /*          qCDebug(KArchiveLog) << "after interesting dev->pos(): " << dev->pos();
626
                                                if (success)
627
                                                qCDebug(KArchiveLog) << "dev->at was successful... ";
628
                                                else
629
                                                qCDebug(KArchiveLog) << "dev->at failed... ";*/
630
5.04k
                    }
631
21.8k
                }
632
                // test for optional data descriptor
633
400k
                if (!foundSignature) {
634
                    //                     qCDebug(KArchiveLog) << "Testing for optional data descriptor";
635
                    // read static data descriptor
636
384k
                    n = dev->peek(buffer, 4);
637
384k
                    if (n < 4) {
638
73
                        setErrorString(tr("Invalid ZIP file. Unexpected end of file. (#1)"));
639
73
                        return false;
640
73
                    }
641
642
384k
                    QByteArrayView currentHead(buffer, 4);
643
                    // qCDebug(KArchiveLog) << "Testing for optional data descriptor @ " << dev->pos() << currentHead;
644
384k
                    if (currentHead.startsWith("PK\x07\x08")) {
645
200
                        dev->skip(16); // skip rest of the 'data_descriptor'
646
384k
                    } else if (!(currentHead.startsWith("PK\x03\x04") || currentHead.startsWith("PK\x01\x02"))) {
647
                        // assume data descriptor without signature
648
558
                        dev->skip(12); // skip rest of the 'data_descriptor'
649
558
                    }
650
384k
                }
651
652
                // not needed any more
653
                /*                // here we calculate the length of the file in the zip
654
                // with headers and jump to the next header.
655
                uint skip = compr_size + namelen + extralen;
656
                offset += 30 + skip;*/
657
400k
            }
658
402k
            pfi_map.insert(fileName, pfi);
659
402k
        } else if (!memcmp(buffer, "PK\1\2", 4)) { // central block
660
            // qCDebug(KArchiveLog) << "PK12 found central block at offset" << dev->pos();
661
41.7k
            startOfFile = false;
662
663
            // so we reached the central header at the end of the zip file
664
            // here we get all interesting data out of the central header
665
            // of a file
666
41.7k
            auto offset = dev->pos() - 4;
667
668
            // set offset for appending new files
669
41.7k
            if (d->m_offset == 0) {
670
8.48k
                d->m_offset = offset;
671
8.48k
            }
672
673
41.7k
            n = dev->read(buffer + 4, 42);
674
41.7k
            if (n < 42) {
675
95
                setErrorString(tr("Invalid ZIP file, central entry too short (not long enough for valid entry)"));
676
95
                return false;
677
95
            }
678
679
            // length of extra attributes
680
41.6k
            const int extralen = parseUi16(buffer + 30);
681
            // length of comment for this file
682
41.6k
            const int commlen = parseUi16(buffer + 32);
683
            // compression method of this file
684
41.6k
            const int cmethod = parseUi16(buffer + 10);
685
            // int gpf =  parseUi16(buffer + 8);
686
            // qCDebug(KArchiveLog) << "general purpose flag=" << gpf;
687
            // length of the fileName (well, pathname indeed)
688
41.6k
            const int namelen = parseUi16(buffer + 28);
689
41.6k
            if (namelen <= 0) {
690
8
                setErrorString(tr("Invalid ZIP file, file path name length is zero"));
691
8
                return false;
692
8
            }
693
41.6k
            const int varDataDesiredLength = namelen + extralen;
694
41.6k
            const QByteArray varData = dev->read(varDataDesiredLength);
695
41.6k
            if (varData.length() < varDataDesiredLength) {
696
100
                setErrorString(tr("Invalid ZIP file, unable to read %1 + %2 bytes for filename and extra data at offset %3")
697
100
                                   .arg(namelen, extralen, dev->pos() - varData.size()));
698
100
                return false;
699
100
            }
700
701
            // crc32 of the file
702
41.5k
            uint crc32 = parseUi32(buffer + 16);
703
            // 32 bit uncompressed file size
704
41.5k
            quint32 ucsize32 = parseUi32(buffer + 24);
705
            // 32 bit compressed file size
706
41.5k
            quint32 csize32 = parseUi32(buffer + 20);
707
            // 32 bit offset of local header
708
41.5k
            quint32 localheaderoffset_32 = parseUi32(buffer + 42);
709
710
41.5k
            ParseFileInfo extrafi;
711
41.5k
            if (extralen) {
712
1.49k
                parseExtraField(varData.constData() + namelen, extralen, extrafi, ucsize32, csize32, localheaderoffset_32);
713
1.49k
            }
714
715
            // uncompressed file size
716
41.5k
            quint64 ucsize = (ucsize32 == 0xFFFFFFFF) ? extrafi.uncompressedSize : ucsize32;
717
            // compressed file size
718
41.5k
            quint64 csize = (csize32 == 0xFFFFFFFF) ? extrafi.compressedSize : csize32;
719
            // offset of local header
720
41.5k
            quint64 localheaderoffset = (localheaderoffset_32 == 0xFFFFFFFF) ? extrafi.localheaderoffset : localheaderoffset_32;
721
722
41.5k
            QByteArray bufferName(varData.constData(), namelen);
723
724
41.5k
            ParseFileInfo pfi = pfi_map.value(bufferName, ParseFileInfo());
725
726
41.5k
            QString name(QFile::decodeName(bufferName));
727
728
            // qCDebug(KArchiveLog) << "name: " << name;
729
            // qCDebug(KArchiveLog) << "cmethod: " << cmethod;
730
            // qCDebug(KArchiveLog) << "extralen: " << extralen;
731
            // qCDebug(KArchiveLog) << "localheader dataoffset: " << pfi.dataoffset;
732
733
            // offset, where the real data for uncompression starts
734
41.5k
            qint64 dataoffset = localheaderoffset + pfi.dataoffset;
735
41.5k
            if (pfi.localheaderoffset != expectedStartPos + localheaderoffset) {
736
665
                if (pfi.localheaderoffset == d->m_startPos + localheaderoffset) {
737
240
                    qCDebug(KArchiveLog) << "warning:" << d->m_startPos << "extra bytes at beginning of zipfile";
738
240
                    expectedStartPos = d->m_startPos;
739
425
                } else {
740
425
                    setErrorString(tr("Invalid ZIP file, inconsistent Local Header Offset in Central Directory at %1").arg(offset));
741
425
                    return false;
742
425
                }
743
240
                dataoffset = localheaderoffset + pfi.dataoffset + d->m_startPos;
744
240
            }
745
746
            // qCDebug(KArchiveLog) << "csize: " << csize;
747
748
41.1k
            int os_madeby = (uchar)buffer[5];
749
41.1k
            bool isdir = false;
750
41.1k
            int access = 0100644;
751
752
41.1k
            if (os_madeby == 3) { // good ole unix
753
11.9k
                access = parseUi16(buffer + 40);
754
11.9k
            }
755
756
41.1k
            QString entryName;
757
758
41.1k
            if (name.endsWith(QLatin1Char('/'))) { // Entries with a trailing slash are directories
759
5.56k
                isdir = true;
760
5.56k
                name = name.left(name.length() - 1);
761
5.56k
                if (os_madeby != 3) {
762
5.04k
                    access = S_IFDIR | 0755;
763
5.04k
                } else {
764
523
                    access |= S_IFDIR | 0700;
765
523
                }
766
5.56k
            }
767
768
41.1k
            int pos = name.lastIndexOf(QLatin1Char('/'));
769
41.1k
            if (pos == -1) {
770
19.9k
                entryName = name;
771
21.2k
            } else {
772
21.2k
                entryName = name.mid(pos + 1);
773
21.2k
            }
774
41.1k
            if (entryName.isEmpty()) {
775
13
                setErrorString(tr("Invalid ZIP file, found empty entry name"));
776
13
                return false;
777
13
            }
778
779
41.1k
            KArchiveEntry *entry;
780
41.1k
            if (isdir) {
781
5.55k
                QString path = QDir::cleanPath(name);
782
5.55k
                const KArchiveEntry *ent = rootDir()->entry(path);
783
5.55k
                if (ent && ent->isDirectory()) {
784
                    // qCDebug(KArchiveLog) << "Directory already exists, NOT going to add it again";
785
1.89k
                    entry = nullptr;
786
3.66k
                } else {
787
3.66k
                    QDateTime mtime = KArchivePrivate::time_tToDateTime(pfi.mtime);
788
3.66k
                    entry = new KArchiveDirectory(this, entryName, access, mtime, rootDir()->user(), rootDir()->group(), QString());
789
                    // qCDebug(KArchiveLog) << "KArchiveDirectory created, entryName= " << entryName << ", name=" << name;
790
3.66k
                }
791
35.5k
            } else {
792
35.5k
                QString symlink;
793
35.5k
                if ((access & QT_STAT_MASK) == QT_STAT_LNK) {
794
1.08k
                    symlink = QFile::decodeName(pfi.guessed_symlink);
795
1.08k
                }
796
35.5k
                QDateTime mtime = KArchivePrivate::time_tToDateTime(pfi.mtime);
797
35.5k
                entry =
798
35.5k
                    new KZipFileEntry(this, entryName, access, mtime, rootDir()->user(), rootDir()->group(), symlink, name, dataoffset, ucsize, cmethod, csize);
799
35.5k
                static_cast<KZipFileEntry *>(entry)->setHeaderStart(localheaderoffset);
800
35.5k
                static_cast<KZipFileEntry *>(entry)->setCRC32(crc32);
801
                // qCDebug(KArchiveLog) << "KZipFileEntry created, entryName= " << entryName << ", name=" << name;
802
35.5k
                d->m_fileList.append(static_cast<KZipFileEntry *>(entry));
803
35.5k
            }
804
805
41.1k
            if (entry) {
806
39.2k
                if (pos == -1) {
807
                    // We don't want to fail opening potentially malformed files, so void the return value
808
18.9k
                    (void)rootDir()->addEntryV2(entry);
809
20.3k
                } else {
810
                    // In some tar files we can find dir/./file => call cleanPath
811
20.3k
                    QString path = QDir::cleanPath(name.left(pos));
812
                    // Ensure container directory exists, create otherwise
813
20.3k
                    KArchiveDirectory *tdir = findOrCreate(path);
814
20.3k
                    if (tdir) {
815
20.2k
                        (void)tdir->addEntryV2(entry);
816
20.2k
                    } else {
817
93
                        setErrorString(tr("File %1 is in folder %2, but %3 is actually a file.").arg(entryName, path, path));
818
93
                        delete entry;
819
93
                        return false;
820
93
                    }
821
20.3k
                }
822
39.2k
            }
823
824
            // calculate offset to next entry
825
41.0k
            offset += 46 + commlen + extralen + namelen;
826
41.0k
            const bool b = dev->seek(offset);
827
41.0k
            if (!b) {
828
433
                setErrorString(tr("Could not seek to next entry"));
829
433
                return false;
830
433
            }
831
41.0k
        } else if (startOfFile) {
832
            // The file does not start with any ZIP header (e.g. self-extractable ZIP files)
833
            // Therefore we need to find the first PK\003\004 (local header)
834
            // qCDebug(KArchiveLog) << "Try to skip start of file";
835
5.30k
            startOfFile = false;
836
5.30k
            bool foundSignature = false;
837
838
5.30k
            QByteArray header;
839
27.7k
            while (seekAnyHeader(dev, header, 4)) {
840
                // We have to detect the magic token for a local header: PK\003\004
841
                /*
842
                 * Note: we do not need to check the other magics, if the ZIP file has no
843
                 * local header, then it has not any files!
844
                 */
845
27.5k
                if (header.startsWith("PK\x03\x04")) {
846
5.16k
                    foundSignature = true;
847
5.16k
                    d->m_startPos = dev->pos();
848
5.16k
                    break;
849
5.16k
                }
850
22.4k
                if (dev->pos() > 4 * 1024 * 1024) {
851
0
                    break;
852
0
                }
853
22.4k
                dev->skip(2); // Skip found 'PK'
854
22.4k
            }
855
856
5.30k
            if (!foundSignature) {
857
139
                setErrorString(tr("Not a ZIP file, no Local File Header found."));
858
139
                return false;
859
139
            }
860
5.30k
        } else {
861
289
            setErrorString(tr("Invalid ZIP file. Unrecognized header at offset %1").arg(dev->pos() - 4));
862
289
            return false;
863
289
        }
864
451k
    }
865
    // qCDebug(KArchiveLog) << "*** done *** ";
866
5.28k
    return true;
867
9.12k
}
868
869
bool KZip::closeArchive()
870
9.12k
{
871
9.12k
    if (!(mode() & QIODevice::WriteOnly)) {
872
        // qCDebug(KArchiveLog) << "readonly";
873
9.12k
        return true;
874
9.12k
    }
875
876
    // ReadWrite or WriteOnly
877
    // write all central dir file entries
878
879
    // to be written at the end of the file...
880
0
    uLong crc = crc32(0L, nullptr, 0);
881
882
0
    qint64 centraldiroffset = device()->pos();
883
    // qCDebug(KArchiveLog) << "closearchive: centraldiroffset: " << centraldiroffset;
884
0
    qint64 atbackup = centraldiroffset;
885
0
    for (KZipFileEntry *entry : d->m_fileList) {
886
        // set crc and compressed size in each local file header
887
0
        if (!device()->seek(entry->headerStart() + 14)) {
888
0
            setErrorString(tr("Could not seek to next file header: %1").arg(device()->errorString()));
889
0
            return false;
890
0
        }
891
        // qCDebug(KArchiveLog) << "closearchive setcrcandcsize: fileName:"
892
        //    << entry->path()
893
        //    << "encoding:" << entry->encoding();
894
895
0
        QByteArray path = QFile::encodeName(entry->path());
896
0
        uLong mycrc = entry->crc32();
897
0
        qint64 compressedSize = entry->compressedSize();
898
0
        qint64 size = entry->size();
899
900
0
        bool compressedSizeNeeds64Bit = compressedSize >= 0xFFFFFFFF;
901
0
        bool uncompressedSizeNeeds64Bit = size >= 0xFFFFFFFF;
902
0
        bool isZip64File = (compressedSizeNeeds64Bit || uncompressedSizeNeeds64Bit);
903
904
0
        char buffer[12];
905
906
        // crc checksum
907
0
        qToLittleEndian<quint32>(mycrc, buffer);
908
909
0
        if (!isZip64File) {
910
0
            qToLittleEndian<quint32>(compressedSize, buffer + 4);
911
0
            qToLittleEndian<quint32>(size, buffer + 8);
912
913
0
            if (device()->write(buffer, 12) != 12) {
914
0
                setErrorString(tr("Could not write file header: %1").arg(device()->errorString()));
915
0
                return false;
916
0
            }
917
0
        } else {
918
            // compressed file size
919
0
            qToLittleEndian<quint32>(0xFFFFFFFF, buffer + 4);
920
            // uncompressed file size
921
0
            qToLittleEndian<quint32>(0xFFFFFFFF, buffer + 8);
922
923
0
            if (device()->write(buffer, 12) != 12) {
924
0
                setErrorString(tr("Could not write file header: %1").arg(device()->errorString()));
925
0
                return false;
926
0
            }
927
928
            // jump to the Local File Header Zip64 extra field to fill the 64-bit sizes
929
0
            qint64 extraFieldOffset = entry->headerStart() + 30 + path.length();
930
0
            if (d->m_extraField == ModificationTime) {
931
0
                extraFieldOffset += 17;
932
0
            }
933
            // skip Zip64 extra field header id and field size
934
0
            extraFieldOffset += 4;
935
0
            if (!device()->seek(extraFieldOffset)) {
936
0
                setErrorString(tr("Could not seek to Zip64 extra field: %1").arg(device()->errorString()));
937
0
                return false;
938
0
            }
939
940
0
            char z64Buffer[16];
941
0
            qToLittleEndian<quint64>(size, z64Buffer);
942
0
            qToLittleEndian<quint64>(compressedSize, z64Buffer + 8);
943
0
            if (device()->write(z64Buffer, 16) != 16) {
944
0
                setErrorString(tr("Could not write Zip64 compressed size: %1").arg(device()->errorString()));
945
0
                return false;
946
0
            }
947
0
        }
948
0
    }
949
950
0
    device()->seek(atbackup);
951
952
0
    for (KZipFileEntry *entry : d->m_fileList) {
953
        // qCDebug(KArchiveLog) << "fileName:" << entry->path()
954
        //              << "encoding:" << entry->encoding();
955
956
0
        QByteArray path = QFile::encodeName(entry->path());
957
0
        qint64 compressedSize = entry->compressedSize();
958
0
        qint64 size = entry->size();
959
0
        qint64 myhst = entry->headerStart();
960
961
0
        bool compressedSizeNeeds64Bit = compressedSize >= 0xFFFFFFFF;
962
0
        bool uncompressedSizeNeeds64Bit = size >= 0xFFFFFFFF;
963
0
        bool offsetNeeds64Bit = myhst >= 0xFFFFFFFF;
964
0
        bool entryNeedsZip64 = (compressedSizeNeeds64Bit || uncompressedSizeNeeds64Bit || offsetNeeds64Bit);
965
966
0
        int extra_field_len = (d->m_extraField == ModificationTime) ? 9 : 0;
967
0
        uint zip64FieldSize = 0;
968
0
        if (entryNeedsZip64) {
969
            // 2 header id + 2 field size +
970
            // 8 uncompressed size + 8 compressed size + 8 offset
971
0
            zip64FieldSize = 28;
972
0
        }
973
0
        extra_field_len += zip64FieldSize;
974
975
0
        const int bufferSize = extra_field_len + path.length() + 46;
976
0
        char *buffer = new char[bufferSize];
977
978
0
        memset(buffer, 0, 46); // zero is a nice default for most header fields
979
980
        // Central header signature
981
0
        buffer[0] = 'P';
982
0
        buffer[1] = 'K';
983
0
        buffer[2] = 1;
984
0
        buffer[3] = 2;
985
986
        // Version made by (UNIX)
987
0
        buffer[4] = 0x14;
988
0
        buffer[5] = 3;
989
        // Version needed to extract
990
0
        buffer[6] = entryNeedsZip64 ? 45 : 0x14;
991
0
        buffer[7] = 0;
992
993
        // General purpose bit flag
994
        // qToLittleEndian<quint16>(0, buffer + 8);
995
996
        // compression method
997
0
        qToLittleEndian<quint16>(char(entry->encoding()), buffer + 10);
998
999
0
        transformToMsDos(entry->date(), &buffer[12]);
1000
1001
0
        uLong mycrc = entry->crc32();
1002
        // crc checksum
1003
0
        qToLittleEndian<quint32>(mycrc, buffer + 16);
1004
1005
        // compressed file size
1006
0
        if (entryNeedsZip64) {
1007
0
            qToLittleEndian<quint32>(0xFFFFFFFF, buffer + 20);
1008
0
        } else {
1009
0
            qToLittleEndian<quint32>(compressedSize, buffer + 20);
1010
0
        }
1011
1012
        // uncompressed file size
1013
0
        if (entryNeedsZip64) {
1014
0
            qToLittleEndian<quint32>(0xFFFFFFFF, buffer + 24);
1015
0
        } else {
1016
0
            qToLittleEndian<quint32>(size, buffer + 24);
1017
0
        }
1018
1019
        // fileName length
1020
0
        qToLittleEndian<quint16>(path.length(), buffer + 28);
1021
1022
        // extra field length
1023
0
        qToLittleEndian<quint16>(extra_field_len, buffer + 30);
1024
1025
        // file comment length
1026
        // qToLittleEndian<quint16>(0, buffer + 32);
1027
1028
        // disk number where file starts
1029
        // qToLittleEndian<quint16>(0, buffer + 34);
1030
1031
        // internal file attributes
1032
        // none
1033
        // external file attributes
1034
0
        qToLittleEndian<quint32>(entry->permissions(), buffer + 40);
1035
1036
        // relative offset of local header
1037
0
        if (entryNeedsZip64) {
1038
0
            qToLittleEndian<quint32>(0xFFFFFFFF, buffer + 42);
1039
0
        } else {
1040
0
            qToLittleEndian<quint32>(myhst, buffer + 42);
1041
0
        }
1042
1043
        // file name
1044
0
        strncpy(buffer + 46, path.constData(), path.length());
1045
        // qCDebug(KArchiveLog) << "closearchive length to write: " << bufferSize;
1046
1047
        // extra field
1048
0
        char *extfield = buffer + 46 + path.length();
1049
0
        if (d->m_extraField == ModificationTime) {
1050
            // "Extended timestamp" header (0x5455)
1051
0
            extfield[0] = 'U';
1052
0
            extfield[1] = 'T';
1053
0
            extfield[2] = 5; // data size
1054
0
            extfield[3] = 0;
1055
0
            extfield[4] = 1 | 2 | 4; // specify flags from local field
1056
            // (unless I misread the spec)
1057
            // provide only modification time
1058
0
            unsigned long time = (unsigned long)entry->date().toSecsSinceEpoch();
1059
0
            qToLittleEndian<quint32>(time, extfield + 5);
1060
0
            extfield += 9;
1061
0
        }
1062
1063
0
        if (entryNeedsZip64) {
1064
            // zip64 header
1065
0
            extfield[0] = 0x01;
1066
0
            extfield[1] = 0x00;
1067
1068
            // zip64 field size
1069
0
            qToLittleEndian<quint16>(24, extfield + 2);
1070
1071
            // uncompressed file size
1072
0
            qToLittleEndian<quint64>(size, extfield + 4);
1073
1074
            // compressed file size
1075
0
            qToLittleEndian<quint64>(compressedSize, extfield + 12);
1076
1077
            // relative offset of local header
1078
0
            qToLittleEndian<quint64>(myhst, extfield + 20);
1079
1080
            // number of the disk on which this file starts
1081
            // qToLittleEndian<quint32>(0, extfield + 28);
1082
0
        }
1083
1084
0
        crc = crc32(crc, (Bytef *)buffer, bufferSize);
1085
0
        bool ok = (device()->write(buffer, bufferSize) == bufferSize);
1086
0
        delete[] buffer;
1087
0
        if (!ok) {
1088
0
            setErrorString(tr("Could not write file header: %1").arg(device()->errorString()));
1089
0
            return false;
1090
0
        }
1091
0
    }
1092
0
    qint64 centraldirendoffset = device()->pos();
1093
0
    qint64 cdsize = centraldirendoffset - centraldiroffset;
1094
    // total number of entries in central dir
1095
0
    qint64 count = d->m_fileList.count();
1096
1097
0
    bool archiveNeedsZip64 = (count >= 0xFFFF || cdsize >= 0xFFFFFFFF || centraldiroffset >= 0xFFFFFFFF);
1098
1099
0
    if (archiveNeedsZip64) {
1100
        // Write Zip64 End of Central Directory Record (PK\6\6)
1101
0
        char zip64Eocd[56];
1102
0
        zip64Eocd[0] = 'P';
1103
0
        zip64Eocd[1] = 'K';
1104
0
        zip64Eocd[2] = 6;
1105
0
        zip64Eocd[3] = 6;
1106
1107
        // size of the EOCD64 minus 12
1108
0
        quint64 eocdSize = 56 - 12;
1109
0
        qToLittleEndian<quint64>(eocdSize, zip64Eocd + 4);
1110
1111
        // Version made by
1112
0
        qToLittleEndian<quint16>(45, zip64Eocd + 12);
1113
        // Version needed to extract
1114
0
        qToLittleEndian<quint16>(45, zip64Eocd + 14);
1115
        // Number of this disk
1116
0
        qToLittleEndian<quint32>(0, zip64Eocd + 16);
1117
        // Disk where central directory starts
1118
0
        qToLittleEndian<quint32>(0, zip64Eocd + 20);
1119
        // Number of central directory records on this disk
1120
0
        qToLittleEndian<quint64>(count, zip64Eocd + 24);
1121
        // Total number of central directory records
1122
0
        qToLittleEndian<quint64>(count, zip64Eocd + 32);
1123
        // Size of central directory in bytes
1124
0
        qToLittleEndian<quint64>(cdsize, zip64Eocd + 40);
1125
        // Offset of start of central directory, relative to start of archive
1126
0
        qToLittleEndian<quint64>(centraldiroffset, zip64Eocd + 48);
1127
        // Comment (up to the size of EOCD64)
1128
        // no comment
1129
1130
0
        if (device()->write(zip64Eocd, 56) != 56) {
1131
0
            setErrorString(tr("Could not write Zip64 EOCD record: %1").arg(device()->errorString()));
1132
0
            return false;
1133
0
        }
1134
1135
        // Write Zip64 End of Central Directory Locator (PK\6\7)
1136
0
        char zip64EocdLocator[20];
1137
0
        zip64EocdLocator[0] = 'P';
1138
0
        zip64EocdLocator[1] = 'K';
1139
0
        zip64EocdLocator[2] = 6;
1140
0
        zip64EocdLocator[3] = 7;
1141
1142
        // Disk where EOCD64 starts
1143
0
        qToLittleEndian<quint32>(0, zip64EocdLocator + 4);
1144
        // Offset to start of EOCD64, relative to start of archive
1145
0
        qToLittleEndian<quint64>(centraldirendoffset, zip64EocdLocator + 8);
1146
        // Total number of disks
1147
0
        qToLittleEndian<quint32>(1, zip64EocdLocator + 16);
1148
1149
0
        if (device()->write(zip64EocdLocator, 20) != 20) {
1150
0
            setErrorString(tr("Could not write Zip64 EOCD locator: %1").arg(device()->errorString()));
1151
0
            return false;
1152
0
        }
1153
0
    }
1154
1155
    // qCDebug(KArchiveLog) << "closearchive: centraldirendoffset: " << centraldirendoffset;
1156
    // qCDebug(KArchiveLog) << "closearchive: device()->pos(): " << device()->pos();
1157
1158
    // write end of central dir record.
1159
0
    char eocd[22];
1160
0
    eocd[0] = 'P'; // end of central dir signature
1161
0
    eocd[1] = 'K';
1162
0
    eocd[2] = 5;
1163
0
    eocd[3] = 6;
1164
1165
    // Number of this disk (or FF FF for ZIP64)
1166
0
    if (archiveNeedsZip64) {
1167
0
        qToLittleEndian<quint16>(0xFFFF, eocd + 4);
1168
0
    } else {
1169
0
        qToLittleEndian<quint16>(0, eocd + 4);
1170
0
    }
1171
    // Disk where central directory starts (or FF FF for ZIP64)
1172
0
    if (archiveNeedsZip64) {
1173
0
        qToLittleEndian<quint16>(0xFFFF, eocd + 6);
1174
0
    } else {
1175
0
        qToLittleEndian<quint16>(0, eocd + 6);
1176
0
    }
1177
    // Number of central directory records on this disk (or FF FF for ZIP64)
1178
0
    if (archiveNeedsZip64) {
1179
0
        qToLittleEndian<quint16>(0xFFFF, eocd + 8);
1180
0
    } else {
1181
0
        qToLittleEndian<quint16>(count, eocd + 8);
1182
0
    }
1183
    // Total number of central directory records (or FF FF for ZIP64)
1184
0
    if (archiveNeedsZip64) {
1185
0
        qToLittleEndian<quint16>(0xFFFF, eocd + 10);
1186
0
    } else {
1187
0
        qToLittleEndian<quint16>(count, eocd + 10);
1188
0
    }
1189
    // qCDebug(KArchiveLog) << "number of files (count): " << count;
1190
1191
    // Size of central directory in bytes (or FF FF FF FF for ZIP64)
1192
0
    if (archiveNeedsZip64) {
1193
0
        qToLittleEndian<quint32>(0xFFFFFFFF, eocd + 12);
1194
0
    } else {
1195
0
        qToLittleEndian<quint32>(cdsize, eocd + 12);
1196
0
    }
1197
    // qCDebug(KArchiveLog) << "end : centraldirsize: " << cdsize;
1198
1199
    // Offset of start of central directory, relative to start of archive (or FF FF FF FF for ZIP64)
1200
0
    if (archiveNeedsZip64) {
1201
0
        qToLittleEndian<quint32>(0xFFFFFFFF, eocd + 16);
1202
0
    } else {
1203
0
        qToLittleEndian<quint32>(centraldiroffset, eocd + 16);
1204
0
    }
1205
    // qCDebug(KArchiveLog) << "end : centraldiroffset: " << centraldiroffset;
1206
1207
    // Comment length
1208
0
    qToLittleEndian<quint16>(0, eocd + 20);
1209
    // Comment (none)
1210
1211
0
    if (device()->write(eocd, 22) != 22) {
1212
0
        setErrorString(tr("Could not write central dir record: %1").arg(device()->errorString()));
1213
0
        return false;
1214
0
    }
1215
1216
0
    return true;
1217
0
}
1218
1219
bool KZip::doWriteDir(const QString &name,
1220
                      const QString &user,
1221
                      const QString &group,
1222
                      mode_t perm,
1223
                      const QDateTime &atime,
1224
                      const QDateTime &mtime,
1225
                      const QDateTime &ctime)
1226
0
{
1227
    // Zip files have no explicit directories, they are implicitly created during extraction time
1228
    // when file entries have paths in them.
1229
    // However, to support empty directories, we must create a dummy file entry which ends with '/'.
1230
0
    QString dirName = name;
1231
0
    if (!name.endsWith(QLatin1Char('/'))) {
1232
0
        dirName = dirName.append(QLatin1Char('/'));
1233
0
    }
1234
0
    return writeFile(dirName, QByteArrayView(), perm, user, group, atime, mtime, ctime);
1235
0
}
1236
1237
bool KZip::doPrepareWriting(const QString &name,
1238
                            const QString &user,
1239
                            const QString &group,
1240
                            qint64 size,
1241
                            mode_t perm,
1242
                            const QDateTime &accessTime,
1243
                            const QDateTime &modificationTime,
1244
                            const QDateTime &creationTime)
1245
0
{
1246
    // qCDebug(KArchiveLog);
1247
0
    if (!isOpen()) {
1248
0
        setErrorString(tr("Application error: ZIP file must be open before being written into"));
1249
0
        qCWarning(KArchiveLog) << "doPrepareWriting failed: !isOpen()";
1250
0
        return false;
1251
0
    }
1252
1253
0
    if (!(mode() & QIODevice::WriteOnly)) { // accept WriteOnly and ReadWrite
1254
0
        setErrorString(tr("Application error: attempted to write into non-writable ZIP file"));
1255
0
        qCWarning(KArchiveLog) << "doPrepareWriting failed: !(mode() & QIODevice::WriteOnly)";
1256
0
        return false;
1257
0
    }
1258
1259
0
    if (!device()) {
1260
0
        setErrorString(tr("Cannot create a device. Disk full?"));
1261
0
        return false;
1262
0
    }
1263
1264
    // set right offset in zip.
1265
0
    if (!device()->seek(d->m_offset)) {
1266
0
        setErrorString(tr("Cannot seek in ZIP file. Disk full?"));
1267
0
        return false;
1268
0
    }
1269
1270
0
    uint atime = accessTime.toSecsSinceEpoch();
1271
0
    uint mtime = modificationTime.toSecsSinceEpoch();
1272
0
    uint ctime = creationTime.toSecsSinceEpoch();
1273
1274
    // Find or create parent dir
1275
0
    KArchiveDirectory *parentDir = rootDir();
1276
0
    QString fileName(name);
1277
0
    int i = name.lastIndexOf(QLatin1Char('/'));
1278
0
    if (i != -1) {
1279
0
        QString dir = name.left(i);
1280
0
        fileName = name.mid(i + 1);
1281
        // qCDebug(KArchiveLog) << "ensuring" << dir << "exists. fileName=" << fileName;
1282
0
        parentDir = findOrCreate(dir);
1283
0
    }
1284
1285
    // delete entries in the filelist with the same fileName as the one we want
1286
    // to save, so that we don't have duplicate file entries when viewing the zip
1287
    // with konqi...
1288
    // CAUTION: the old file itself is still in the zip and won't be removed !!!
1289
    // qCDebug(KArchiveLog) << "fileName to write: " << name;
1290
0
    for (auto it = d->m_fileList.begin(); it != d->m_fileList.end();) {
1291
        // qCDebug(KArchiveLog) << "prepfileName: " << entry->path();
1292
0
        if (name == (*it)->path()) {
1293
            // also remove from the parentDir
1294
0
            if (!parentDir->removeEntryV2(*it)) {
1295
0
                return false;
1296
0
            }
1297
            // qCDebug(KArchiveLog) << "removing following entry: " << entry->path();
1298
0
            delete *it;
1299
0
            it = d->m_fileList.erase(it);
1300
0
        } else {
1301
0
            it++;
1302
0
        }
1303
0
    }
1304
1305
0
    bool isZip64Archive = size >= 0xFFFFFFFF;
1306
1307
0
    int extra_field_len = 0;
1308
0
    if (d->m_extraField == ModificationTime) {
1309
0
        extra_field_len = 17; // value also used in finishWriting()
1310
0
    }
1311
    // if isZip64Archive is true we write both sizes to the zip64 field
1312
0
    if (isZip64Archive) {
1313
        // 2 header id + 2 field size +
1314
        // 8 uncompressed size + 8 compressed size
1315
0
        extra_field_len += 20;
1316
0
    }
1317
1318
0
    QByteArray encodedName = QFile::encodeName(name);
1319
1320
    // construct a KZipFileEntry and add it to list
1321
0
    KZipFileEntry *e = new KZipFileEntry(this,
1322
0
                                         fileName,
1323
0
                                         perm,
1324
0
                                         modificationTime,
1325
0
                                         user,
1326
0
                                         group,
1327
0
                                         QString(),
1328
0
                                         name,
1329
0
                                         device()->pos() + 30 + encodedName.length() + extra_field_len, // start
1330
0
                                         0 /*size unknown yet*/,
1331
0
                                         d->m_compression,
1332
0
                                         0 /*csize unknown yet*/);
1333
0
    e->setHeaderStart(device()->pos());
1334
    // qCDebug(KArchiveLog) << "wrote file start: " << e->position() << " name: " << name;
1335
0
    if (!parentDir->addEntryV2(e)) {
1336
0
        return false;
1337
0
    }
1338
1339
0
    d->m_currentFile = e;
1340
0
    d->m_fileList.append(e);
1341
1342
    // write out zip header
1343
0
    int bufferSize = extra_field_len + encodedName.length() + 30;
1344
    // qCDebug(KArchiveLog) << "bufferSize=" << bufferSize;
1345
0
    char *buffer = new char[bufferSize];
1346
1347
0
    buffer[0] = 'P'; // local file header signature
1348
0
    buffer[1] = 'K';
1349
0
    buffer[2] = 3;
1350
0
    buffer[3] = 4;
1351
1352
    // version needed to extract
1353
0
    qToLittleEndian<quint16>(isZip64Archive ? 45 : 0x14, buffer + 4);
1354
1355
    // general purpose bit flag
1356
0
    qToLittleEndian<quint16>(0, buffer + 6);
1357
1358
    // compression method
1359
0
    qToLittleEndian<quint16>(char(e->encoding()), buffer + 8);
1360
1361
0
    transformToMsDos(e->date(), &buffer[10]);
1362
1363
0
    buffer[14] = 'C'; // dummy crc
1364
0
    buffer[15] = 'R';
1365
0
    buffer[16] = 'C';
1366
0
    buffer[17] = 'q';
1367
1368
0
    buffer[18] = 'C'; // compressed file size
1369
0
    buffer[19] = 'S';
1370
0
    buffer[20] = 'I';
1371
0
    buffer[21] = 'Z';
1372
1373
0
    buffer[22] = 'U'; // uncompressed file size
1374
0
    buffer[23] = 'S';
1375
0
    buffer[24] = 'I';
1376
0
    buffer[25] = 'Z';
1377
1378
    // fileName length
1379
0
    qToLittleEndian<quint16>(encodedName.length(), buffer + 26);
1380
1381
    // extra field length
1382
0
    qToLittleEndian<quint16>(extra_field_len, buffer + 28);
1383
1384
    // file name
1385
0
    strncpy(buffer + 30, encodedName.constData(), encodedName.length());
1386
1387
    // extra field
1388
0
    char *extfield = buffer + 30 + encodedName.length();
1389
0
    if (d->m_extraField == ModificationTime) {
1390
        // "Extended timestamp" header (0x5455)
1391
0
        extfield[0] = 'U';
1392
0
        extfield[1] = 'T';
1393
0
        extfield[2] = 13; // data size
1394
0
        extfield[3] = 0;
1395
0
        extfield[4] = 1 | 2 | 4; // contains mtime, atime, ctime
1396
1397
0
        qToLittleEndian<quint32>(mtime, extfield + 5);
1398
0
        qToLittleEndian<quint32>(atime, extfield + 9);
1399
0
        qToLittleEndian<quint32>(ctime, extfield + 13);
1400
0
        extfield += 17;
1401
0
    }
1402
1403
0
    if (isZip64Archive) {
1404
        // zip64 header
1405
0
        extfield[0] = 0x01;
1406
0
        extfield[1] = 0x00;
1407
        // size of uncompressed and compressed fields
1408
0
        qToLittleEndian<quint16>(16, extfield + 2);
1409
        // uncompressed size
1410
0
        qToLittleEndian<quint64>(size, extfield + 4);
1411
        // compressed size
1412
0
        qToLittleEndian<quint64>(0, extfield + 12);
1413
0
    }
1414
1415
    // Write header
1416
0
    bool b = (device()->write(buffer, bufferSize) == bufferSize);
1417
0
    d->m_crc = 0;
1418
0
    delete[] buffer;
1419
1420
0
    if (!b) {
1421
0
        setErrorString(tr("Could not write to the archive. Disk full?"));
1422
0
        return false;
1423
0
    }
1424
1425
    // Prepare device for writing the data
1426
    // Either device() if no compression, or a KCompressionDevice to compress
1427
0
    if (d->m_compression == 0) {
1428
0
        d->m_currentDev = device();
1429
0
        return true;
1430
0
    }
1431
1432
0
    auto compressionDevice = new KCompressionDevice(device(), false, KCompressionDevice::GZip);
1433
0
    d->m_currentDev = compressionDevice;
1434
0
    compressionDevice->setSkipHeaders(); // Just zlib, not gzip
1435
1436
0
    b = d->m_currentDev->open(QIODevice::WriteOnly);
1437
0
    Q_ASSERT(b);
1438
1439
0
    if (!b) {
1440
0
        setErrorString(tr("Could not open compression device: %1").arg(d->m_currentDev->errorString()));
1441
0
    }
1442
1443
0
    return b;
1444
0
}
1445
1446
bool KZip::doFinishWriting(qint64 size)
1447
0
{
1448
0
    if (d->m_currentFile->encoding() == 8) {
1449
        // Finish
1450
0
        (void)d->m_currentDev->write(nullptr, 0);
1451
0
        delete d->m_currentDev;
1452
0
    }
1453
    // If 0, d->m_currentDev was device() - don't delete ;)
1454
0
    d->m_currentDev = nullptr;
1455
1456
0
    Q_ASSERT(d->m_currentFile);
1457
    // qCDebug(KArchiveLog) << "fileName: " << d->m_currentFile->path();
1458
    // qCDebug(KArchiveLog) << "getpos (at): " << device()->pos();
1459
0
    d->m_currentFile->setSize(size);
1460
1461
0
    const QByteArray encodedName = QFile::encodeName(d->m_currentFile->path());
1462
0
    qint64 csize = device()->pos() - d->m_currentFile->position();
1463
0
    d->m_currentFile->setCompressedSize(csize);
1464
    // qCDebug(KArchiveLog) << "usize: " << d->m_currentFile->size();
1465
    // qCDebug(KArchiveLog) << "csize: " << d->m_currentFile->compressedSize();
1466
    // qCDebug(KArchiveLog) << "headerstart: " << d->m_currentFile->headerStart();
1467
1468
    // qCDebug(KArchiveLog) << "crc: " << d->m_crc;
1469
0
    d->m_currentFile->setCRC32(d->m_crc);
1470
1471
0
    d->m_currentFile = nullptr;
1472
1473
    // update saved offset for appending new files
1474
0
    d->m_offset = device()->pos();
1475
0
    return true;
1476
0
}
1477
1478
bool KZip::doWriteSymLink(const QString &name,
1479
                          const QString &target,
1480
                          const QString &user,
1481
                          const QString &group,
1482
                          mode_t perm,
1483
                          const QDateTime &atime,
1484
                          const QDateTime &mtime,
1485
                          const QDateTime &ctime)
1486
0
{
1487
    // reassure that symlink flag is set, otherwise strange things happen on
1488
    // extraction
1489
0
    perm |= QT_STAT_LNK;
1490
0
    Compression c = compression();
1491
0
    setCompression(NoCompression); // link targets are never compressed
1492
1493
0
    if (!doPrepareWriting(name, user, group, 0, perm, atime, mtime, ctime)) {
1494
0
        setCompression(c);
1495
0
        return false;
1496
0
    }
1497
1498
0
    QByteArray symlink_target = QFile::encodeName(target);
1499
0
    if (!writeData(symlink_target.constData(), symlink_target.length())) {
1500
0
        setCompression(c);
1501
0
        return false;
1502
0
    }
1503
1504
0
    if (!finishWriting(symlink_target.length())) {
1505
0
        setCompression(c);
1506
0
        return false;
1507
0
    }
1508
1509
0
    setCompression(c);
1510
0
    return true;
1511
0
}
1512
1513
void KZip::virtual_hook(int id, void *data)
1514
0
{
1515
0
    KArchive::virtual_hook(id, data);
1516
0
}
1517
1518
bool KZip::doWriteData(const char *data, qint64 size)
1519
0
{
1520
0
    Q_ASSERT(d->m_currentFile);
1521
0
    Q_ASSERT(d->m_currentDev);
1522
0
    if (!d->m_currentFile || !d->m_currentDev) {
1523
0
        setErrorString(tr("No file or device"));
1524
0
        return false;
1525
0
    }
1526
1527
    // crc to be calculated over uncompressed stuff...
1528
    // and they didn't mention it in their docs...
1529
0
    quint32 crc = d->m_crc;
1530
1531
0
    constexpr qint64 chunkSize = 2 * 1024 * 1024;
1532
0
    qint64 totalWritten = 0;
1533
0
    while (totalWritten < size) {
1534
0
        qint64 chunk = std::min(chunkSize, size - totalWritten);
1535
1536
0
        crc = crc32(crc, reinterpret_cast<const Bytef *>(data + totalWritten), static_cast<quint32>(chunk));
1537
1538
0
        qint64 currentWritten = d->m_currentDev->write(data + totalWritten, chunk);
1539
0
        if (currentWritten != chunk) {
1540
0
            setErrorString(tr("Error writing data chunk: %1").arg(d->m_currentDev->errorString()));
1541
0
            return false;
1542
0
        }
1543
1544
0
        totalWritten += currentWritten;
1545
0
    }
1546
1547
0
    d->m_crc = crc;
1548
1549
    // qCDebug(KArchiveLog) << "wrote" << size << "bytes.";
1550
0
    const bool ok = totalWritten == size;
1551
1552
0
    if (!ok) {
1553
0
        setErrorString(tr("Error writing data: %1").arg(d->m_currentDev->errorString()));
1554
0
    }
1555
1556
0
    return ok;
1557
0
}
1558
1559
void KZip::setCompression(Compression c)
1560
0
{
1561
0
    d->m_compression = (c == NoCompression) ? 0 : 8;
1562
0
}
1563
1564
KZip::Compression KZip::compression() const
1565
0
{
1566
0
    return (d->m_compression == 8) ? DeflateCompression : NoCompression;
1567
0
}
1568
1569
void KZip::setExtraField(ExtraField ef)
1570
0
{
1571
0
    d->m_extraField = ef;
1572
0
}
1573
1574
KZip::ExtraField KZip::extraField() const
1575
0
{
1576
0
    return d->m_extraField;
1577
0
}
1578
1579
////////////////////////////////////////////////////////////////////////
1580
////////////////////// KZipFileEntry////////////////////////////////////
1581
////////////////////////////////////////////////////////////////////////
1582
class Q_DECL_HIDDEN KZipFileEntry::KZipFileEntryPrivate
1583
{
1584
public:
1585
    KZipFileEntryPrivate()
1586
35.5k
        : crc(0)
1587
35.5k
        , compressedSize(0)
1588
35.5k
        , headerStart(0)
1589
35.5k
        , encoding(0)
1590
35.5k
    {
1591
35.5k
    }
1592
    unsigned long crc;
1593
    qint64 compressedSize;
1594
    qint64 headerStart;
1595
    int encoding;
1596
    QString path;
1597
};
1598
1599
KZipFileEntry::KZipFileEntry(KZip *zip,
1600
                             const QString &name,
1601
                             int access,
1602
                             const QDateTime &date,
1603
                             const QString &user,
1604
                             const QString &group,
1605
                             const QString &symlink,
1606
                             const QString &path,
1607
                             qint64 start,
1608
                             qint64 uncompressedSize,
1609
                             int encoding,
1610
                             qint64 compressedSize)
1611
35.5k
    : KArchiveFile(zip, name, access, date, user, group, symlink, start, uncompressedSize)
1612
35.5k
    , d(new KZipFileEntryPrivate)
1613
35.5k
{
1614
35.5k
    d->path = path;
1615
35.5k
    d->encoding = encoding;
1616
35.5k
    d->compressedSize = compressedSize;
1617
35.5k
}
1618
1619
KZipFileEntry::~KZipFileEntry()
1620
35.5k
{
1621
35.5k
    delete d;
1622
35.5k
}
1623
1624
int KZipFileEntry::encoding() const
1625
7.09k
{
1626
7.09k
    return d->encoding;
1627
7.09k
}
1628
1629
qint64 KZipFileEntry::compressedSize() const
1630
12.6k
{
1631
12.6k
    return d->compressedSize;
1632
12.6k
}
1633
1634
void KZipFileEntry::setCompressedSize(qint64 compressedSize)
1635
0
{
1636
0
    d->compressedSize = compressedSize;
1637
0
}
1638
1639
void KZipFileEntry::setHeaderStart(qint64 headerstart)
1640
35.5k
{
1641
35.5k
    d->headerStart = headerstart;
1642
35.5k
}
1643
1644
qint64 KZipFileEntry::headerStart() const
1645
0
{
1646
0
    return d->headerStart;
1647
0
}
1648
1649
unsigned long KZipFileEntry::crc32() const
1650
0
{
1651
0
    return d->crc;
1652
0
}
1653
1654
void KZipFileEntry::setCRC32(unsigned long crc32)
1655
35.5k
{
1656
35.5k
    d->crc = crc32;
1657
35.5k
}
1658
1659
const QString &KZipFileEntry::path() const
1660
64
{
1661
64
    return d->path;
1662
64
}
1663
1664
QByteArray KZipFileEntry::data() const
1665
5.46k
{
1666
5.46k
    QIODevice *dev = createDevice();
1667
5.46k
    QByteArray arr;
1668
5.46k
    if (dev) {
1669
5.37k
        const qint64 devSize = dev->size();
1670
5.37k
        if (devSize > kMaxQByteArraySize) {
1671
65
            qCWarning(KArchiveLog) << "KZipFileEntry::data: Failed to allocate memory for file of size" << devSize;
1672
65
            delete dev;
1673
65
            return {};
1674
65
        }
1675
5.31k
        arr = dev->readAll();
1676
5.31k
        delete dev;
1677
5.31k
    }
1678
5.39k
    return arr;
1679
5.46k
}
1680
1681
QIODevice *KZipFileEntry::createDevice() const
1682
5.46k
{
1683
5.46k
    if (compressedSize() < 0) {
1684
64
        qCWarning(KArchiveLog) << "KZipFileEntry::createDevice: Entry with negative size" << path() << compressedSize();
1685
64
        return nullptr;
1686
64
    }
1687
    // qCDebug(KArchiveLog) << "creating iodevice limited to pos=" << position() << ", csize=" << compressedSize();
1688
    // Limit the reading to the appropriate part of the underlying device (e.g. file)
1689
5.39k
    std::unique_ptr limitedDev = std::make_unique<KLimitedIODevice>(archive()->device(), position(), compressedSize());
1690
5.39k
    if (encoding() == 0 || compressedSize() == 0) { // no compression (or even no data)
1691
3.72k
        return limitedDev.release();
1692
3.72k
    }
1693
1694
1.67k
    if (encoding() == 8) {
1695
        // On top of that, create a device that uncompresses the zlib data
1696
1.65k
        KCompressionDevice *filterDev = new KCompressionDevice(std::move(limitedDev), KCompressionDevice::GZip, size());
1697
1698
1.65k
        if (!filterDev) {
1699
0
            return nullptr; // ouch
1700
0
        }
1701
1.65k
        filterDev->setSkipHeaders(); // Just zlib, not gzip
1702
1.65k
        bool b = filterDev->open(QIODevice::ReadOnly);
1703
1.65k
        Q_UNUSED(b);
1704
1.65k
        Q_ASSERT(b);
1705
1.65k
        return filterDev;
1706
1.65k
    }
1707
1708
1.67k
    qCCritical(KArchiveLog) << "This zip file contains files compressed with method" << encoding() << ", this method is currently not supported by KZip,"
1709
23
                            << "please use a command-line tool to handle this file.";
1710
23
    return nullptr;
1711
1.67k
}