Coverage Report

Created: 2026-04-01 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/port/cpl_minizip_zip.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  CPL - Common Portability Library
4
 * Author:   Frank Warmerdam, warmerdam@pobox.com
5
 * Purpose:  Adjusted minizip "zip.c" source code for zip services.
6
 *
7
 * Modified version by Even Rouault. :
8
 *   - Decoration of symbol names unz* -> cpl_unz*
9
 *   - Undef EXPORT so that we are sure the symbols are not exported
10
 *   - Remove old C style function prototypes
11
 *   - Added CPL* simplified API at bottom.
12
 *
13
 *   Original license available in port/LICENCE_minizip
14
 *
15
 *****************************************************************************/
16
17
/* zip.c -- IO on .zip files using zlib
18
   Version 1.1, February 14h, 2010
19
   part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html
20
   )
21
22
         Copyright (C) 1998-2010 Gilles Vollant (minizip) (
23
   http://www.winimage.com/zLibDll/minizip.html )
24
25
         Modifications for Zip64 support
26
         Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
27
28
         For more info read MiniZip_info.txt
29
30
         Changes
31
   Oct-2009 - Mathias Svensson - Remove old C style function prototypes
32
   Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file
33
   archives Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring
34
   to get better overview of some functions. Oct-2009 - Mathias Svensson - Added
35
   zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data It is
36
   used when recreating zip archive with RAW when deleting items from a zip.
37
                                 ZIP64 data is automatically added to items that
38
   needs it, and existing ZIP64 data need to be removed. Oct-2009 - Mathias
39
   Svensson - Added support for BZIP2 as compression mode (bzip2 lib is
40
   required) Jan-2010 - back to unzip and minizip 1.0 name scheme, with
41
   compatibility layer
42
43
   Copyright (c) 2010-2018, Even Rouault <even dot rouault at spatialys.com>
44
45
*/
46
47
#include "cpl_port.h"
48
#include "cpl_minizip_zip.h"
49
50
#include <algorithm>
51
#include <limits>
52
53
#include <cassert>
54
#include <cinttypes>
55
#include <cstddef>
56
#include <cstdlib>
57
#include <cstring>
58
#include <fcntl.h>
59
#include <time.h>
60
61
#include "cpl_conv.h"
62
#include "cpl_error.h"
63
#include "cpl_minizip_unzip.h"
64
#include "cpl_multiproc.h"
65
#include "cpl_string.h"
66
#include "cpl_time.h"
67
#include "cpl_vsi_virtual.h"
68
69
#ifdef NO_ERRNO_H
70
extern int errno;
71
#else
72
#include <errno.h>
73
#endif
74
75
#ifndef VERSIONMADEBY
76
0
#define VERSIONMADEBY (0x0) /* platform dependent */
77
#endif
78
79
#ifndef Z_BUFSIZE
80
0
#define Z_BUFSIZE (16384)
81
#endif
82
83
#ifndef ALLOC
84
0
#define ALLOC(size) (malloc(size))
85
#endif
86
#ifndef TRYFREE
87
#define TRYFREE(p)                                                             \
88
0
    {                                                                          \
89
0
        if (p)                                                                 \
90
0
            free(p);                                                           \
91
0
    }
92
#endif
93
94
/*
95
#define SIZECENTRALDIRITEM (0x2e)
96
#define SIZEZIPLOCALHEADER (0x1e)
97
*/
98
99
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined... */
100
101
#ifndef SEEK_CUR
102
#define SEEK_CUR 1
103
#endif
104
105
#ifndef SEEK_END
106
#define SEEK_END 2
107
#endif
108
109
#ifndef SEEK_SET
110
#define SEEK_SET 0
111
#endif
112
113
#ifndef DEF_MEM_LEVEL
114
#if MAX_MEM_LEVEL >= 8
115
#define DEF_MEM_LEVEL 8
116
#else
117
#define DEF_MEM_LEVEL MAX_MEM_LEVEL
118
#endif
119
#endif
120
121
CPL_UNUSED static const char zip_copyright[] =
122
    " zip 1.01 Copyright 1998-2004 Gilles Vollant - "
123
    "http://www.winimage.com/zLibDll";
124
125
0
#define SIZEDATA_INDATABLOCK (4096 - (4 * 4))
126
127
0
#define LOCALHEADERMAGIC (0x04034b50)
128
0
#define CENTRALHEADERMAGIC (0x02014b50)
129
0
#define ENDHEADERMAGIC (0x06054b50)
130
0
#define ZIP64ENDHEADERMAGIC (0x6064b50)
131
0
#define ZIP64ENDLOCHEADERMAGIC (0x7064b50)
132
133
#define FLAG_LOCALHEADER_OFFSET (0x06)
134
#define CRC_LOCALHEADER_OFFSET (0x0e)
135
136
0
#define SIZECENTRALHEADER (0x2e) /* 46 */
137
138
typedef struct linkedlist_datablock_internal_s
139
{
140
    struct linkedlist_datablock_internal_s *next_datablock;
141
    uLong avail_in_this_block;
142
    uLong filled_in_this_block;
143
    uLong unused;  // For future use and alignment.
144
    unsigned char data[SIZEDATA_INDATABLOCK];
145
} linkedlist_datablock_internal;
146
147
typedef struct linkedlist_data_s
148
{
149
    linkedlist_datablock_internal *first_block;
150
    linkedlist_datablock_internal *last_block;
151
} linkedlist_data;
152
153
typedef struct
154
{
155
    z_stream stream;           /* zLib stream structure for inflate */
156
    int stream_initialised;    /* 1 is stream is initialized */
157
    uInt pos_in_buffered_data; /* last written byte in buffered_data */
158
159
    ZPOS64_T pos_local_header; /* offset of the local header of the file
160
                                 currently writing */
161
    char *local_header;
162
    uInt size_local_header;
163
    uInt size_local_header_extrafield;
164
165
    char *central_header; /* central header data for the current file */
166
    uLong size_centralExtra;
167
    uLong size_centralheader;    /* size of the central header for cur file */
168
    uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader
169
                                    but that are not used */
170
    uLong flag;                  /* flag of the file currently writing */
171
172
    // TODO: What is "wr"?  "to"?
173
    int method;                    /* compression method of file currently wr.*/
174
    int raw;                       /* 1 for directly writing raw data */
175
    Byte buffered_data[Z_BUFSIZE]; /* buffer contain compressed data to be
176
                                        written. */
177
    uLong dosDate;
178
    uLong crc32;
179
    int encrypt;
180
    ZPOS64_T pos_zip64extrainfo;
181
    ZPOS64_T totalCompressedData;
182
    ZPOS64_T totalUncompressedData;
183
#ifndef NOCRYPT
184
    unsigned long keys[3]; /* keys defining the pseudo-random sequence */
185
    const unsigned long *pcrc_32_tab;
186
    int crypt_header_size;
187
#endif
188
} curfile64_info;
189
190
typedef struct
191
{
192
    zlib_filefunc_def z_filefunc;
193
    voidpf filestream;           /* IO structure of the zipfile */
194
    linkedlist_data central_dir; /* datablock with central dir in construction*/
195
    int in_opened_file_inzip;    /* 1 if a file in the zip is currently writ.*/
196
    curfile64_info ci;           /* info on the file currently writing */
197
198
    ZPOS64_T begin_pos; /* position of the beginning of the zipfile */
199
    ZPOS64_T add_position_when_writing_offset;
200
    ZPOS64_T number_entry;
201
#ifndef NO_ADDFILEINEXISTINGZIP
202
    char *globalcomment;
203
#endif
204
    int use_cpl_io;
205
    vsi_l_offset vsi_raw_length_before;
206
    VSIVirtualHandle *vsi_deflate_handle;
207
    size_t nChunkSize;
208
    int nThreads;
209
    size_t nOffsetSize;
210
    std::vector<uint8_t> *sozip_index;
211
} zip64_internal;
212
213
#ifndef NOCRYPT
214
#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED
215
#include "crypt.h"
216
#endif
217
218
static linkedlist_datablock_internal *allocate_new_datablock()
219
0
{
220
0
    linkedlist_datablock_internal *ldi;
221
0
    ldi = static_cast<linkedlist_datablock_internal *>(
222
0
        ALLOC(sizeof(linkedlist_datablock_internal)));
223
0
    if (ldi != nullptr)
224
0
    {
225
0
        ldi->next_datablock = nullptr;
226
0
        ldi->filled_in_this_block = 0;
227
0
        ldi->avail_in_this_block = SIZEDATA_INDATABLOCK;
228
0
    }
229
0
    return ldi;
230
0
}
231
232
static void free_datablock(linkedlist_datablock_internal *ldi)
233
0
{
234
0
    while (ldi != nullptr)
235
0
    {
236
0
        linkedlist_datablock_internal *ldinext = ldi->next_datablock;
237
0
        TRYFREE(ldi);
238
0
        ldi = ldinext;
239
0
    }
240
0
}
241
242
static void init_linkedlist(linkedlist_data *ll)
243
0
{
244
0
    ll->first_block = ll->last_block = nullptr;
245
0
}
246
247
static void free_linkedlist(linkedlist_data *ll)
248
0
{
249
0
    free_datablock(ll->first_block);
250
0
    ll->first_block = ll->last_block = nullptr;
251
0
}
252
253
static int add_data_in_datablock(linkedlist_data *ll, const void *buf,
254
                                 uLong len)
255
0
{
256
0
    linkedlist_datablock_internal *ldi;
257
0
    const unsigned char *from_copy;
258
259
0
    if (ll == nullptr)
260
0
        return ZIP_INTERNALERROR;
261
262
0
    if (ll->last_block == nullptr)
263
0
    {
264
0
        ll->first_block = ll->last_block = allocate_new_datablock();
265
0
        if (ll->first_block == nullptr)
266
0
            return ZIP_INTERNALERROR;
267
0
    }
268
269
0
    ldi = ll->last_block;
270
0
    from_copy = reinterpret_cast<const unsigned char *>(buf);
271
272
0
    while (len > 0)
273
0
    {
274
0
        uInt copy_this;
275
0
        uInt i;
276
0
        unsigned char *to_copy;
277
278
0
        if (ldi->avail_in_this_block == 0)
279
0
        {
280
0
            ldi->next_datablock = allocate_new_datablock();
281
0
            if (ldi->next_datablock == nullptr)
282
0
                return ZIP_INTERNALERROR;
283
0
            ldi = ldi->next_datablock;
284
0
            ll->last_block = ldi;
285
0
        }
286
287
0
        if (ldi->avail_in_this_block < len)
288
0
            copy_this = static_cast<uInt>(ldi->avail_in_this_block);
289
0
        else
290
0
            copy_this = static_cast<uInt>(len);
291
292
0
        to_copy = &(ldi->data[ldi->filled_in_this_block]);
293
294
0
        for (i = 0; i < copy_this; i++)
295
0
            *(to_copy + i) = *(from_copy + i);
296
297
0
        ldi->filled_in_this_block += copy_this;
298
0
        ldi->avail_in_this_block -= copy_this;
299
0
        from_copy += copy_this;
300
0
        len -= copy_this;
301
0
    }
302
0
    return ZIP_OK;
303
0
}
304
305
/****************************************************************************/
306
307
#ifndef NO_ADDFILEINEXISTINGZIP
308
/* ===========================================================================
309
   Inputs a long in LSB order to the given file
310
   nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T)
311
*/
312
313
static int zip64local_putValue(const zlib_filefunc_def *pzlib_filefunc_def,
314
                               voidpf filestream, ZPOS64_T x, int nbByte)
315
0
{
316
0
    unsigned char buf[8];
317
0
    for (int n = 0; n < nbByte; n++)
318
0
    {
319
0
        buf[n] = static_cast<unsigned char>(x & 0xff);
320
0
        x >>= 8;
321
0
    }
322
0
    if (x != 0)
323
0
    { /* data overflow - hack for ZIP64 (X Roche) */
324
0
        for (int n = 0; n < nbByte; n++)
325
0
        {
326
0
            buf[n] = 0xff;
327
0
        }
328
0
    }
329
330
0
    if (ZWRITE64(*pzlib_filefunc_def, filestream, buf, nbByte) !=
331
0
        static_cast<uLong>(nbByte))
332
0
        return ZIP_ERRNO;
333
0
    else
334
0
        return ZIP_OK;
335
0
}
336
337
static void zip64local_putValue_inmemory(void *dest, ZPOS64_T x, int nbByte)
338
0
{
339
0
    unsigned char *buf = reinterpret_cast<unsigned char *>(dest);
340
0
    for (int n = 0; n < nbByte; n++)
341
0
    {
342
0
        buf[n] = static_cast<unsigned char>(x & 0xff);
343
0
        x >>= 8;
344
0
    }
345
346
0
    if (x != 0)
347
0
    { /* data overflow - hack for ZIP64 */
348
0
        for (int n = 0; n < nbByte; n++)
349
0
        {
350
0
            buf[n] = 0xff;
351
0
        }
352
0
    }
353
0
}
354
355
/****************************************************************************/
356
357
static uLong zip64local_TmzDateToDosDate(const tm_zip *ptm)
358
0
{
359
0
    uLong year = static_cast<uLong>(ptm->tm_year);
360
0
    if (year > 1980)
361
0
        year -= 1980;
362
0
    else if (year > 80)
363
0
        year -= 80;
364
0
    return static_cast<uLong>(
365
0
               ((ptm->tm_mday) + (32 * (ptm->tm_mon + 1)) + (512 * year))
366
0
               << 16) |
367
0
           ((ptm->tm_sec / 2) + (32 * ptm->tm_min) +
368
0
            (2048 * static_cast<uLong>(ptm->tm_hour)));
369
0
}
370
371
/****************************************************************************/
372
373
static int zip64local_getByte(const zlib_filefunc_def *pzlib_filefunc_def,
374
                              voidpf filestream, int *pi)
375
0
{
376
0
    unsigned char c = 0;
377
0
    const int err =
378
0
        static_cast<int>(ZREAD64(*pzlib_filefunc_def, filestream, &c, 1));
379
0
    if (err == 1)
380
0
    {
381
0
        *pi = static_cast<int>(c);
382
0
        return ZIP_OK;
383
0
    }
384
0
    else
385
0
    {
386
0
        if (ZERROR64(*pzlib_filefunc_def, filestream))
387
0
            return ZIP_ERRNO;
388
0
        else
389
0
            return ZIP_EOF;
390
0
    }
391
0
}
392
393
/* ===========================================================================
394
   Reads a long in LSB order from the given gz_stream. Sets
395
*/
396
static int zip64local_getShort(const zlib_filefunc_def *pzlib_filefunc_def,
397
                               voidpf filestream, uLong *pX)
398
0
{
399
0
    int i = 0;
400
0
    int err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
401
0
    uLong x = static_cast<uLong>(i);
402
403
0
    if (err == ZIP_OK)
404
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
405
0
    x += static_cast<uLong>(i) << 8;
406
407
0
    if (err == ZIP_OK)
408
0
        *pX = x;
409
0
    else
410
0
        *pX = 0;
411
0
    return err;
412
0
}
413
414
static int zip64local_getLong(const zlib_filefunc_def *pzlib_filefunc_def,
415
                              voidpf filestream, uLong *pX)
416
0
{
417
0
    int i = 0;
418
0
    int err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
419
0
    uLong x = static_cast<uLong>(i);
420
421
0
    if (err == ZIP_OK)
422
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
423
0
    x += static_cast<uLong>(i) << 8;
424
425
0
    if (err == ZIP_OK)
426
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
427
0
    x += static_cast<uLong>(i) << 16;
428
429
0
    if (err == ZIP_OK)
430
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
431
0
    x += static_cast<uLong>(i) << 24;
432
433
0
    if (err == ZIP_OK)
434
0
        *pX = x;
435
0
    else
436
0
        *pX = 0;
437
0
    return err;
438
0
}
439
440
static int zip64local_getLong64(const zlib_filefunc_def *pzlib_filefunc_def,
441
                                voidpf filestream, ZPOS64_T *pX)
442
0
{
443
0
    ZPOS64_T x;
444
0
    int i = 0;
445
0
    int err;
446
447
0
    err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
448
0
    x = static_cast<ZPOS64_T>(i);
449
450
0
    if (err == ZIP_OK)
451
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
452
0
    x += static_cast<ZPOS64_T>(i) << 8;
453
454
0
    if (err == ZIP_OK)
455
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
456
0
    x += static_cast<ZPOS64_T>(i) << 16;
457
458
0
    if (err == ZIP_OK)
459
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
460
0
    x += static_cast<ZPOS64_T>(i) << 24;
461
462
0
    if (err == ZIP_OK)
463
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
464
0
    x += static_cast<ZPOS64_T>(i) << 32;
465
466
0
    if (err == ZIP_OK)
467
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
468
0
    x += static_cast<ZPOS64_T>(i) << 40;
469
470
0
    if (err == ZIP_OK)
471
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
472
0
    x += static_cast<ZPOS64_T>(i) << 48;
473
474
0
    if (err == ZIP_OK)
475
0
        err = zip64local_getByte(pzlib_filefunc_def, filestream, &i);
476
0
    x += static_cast<ZPOS64_T>(i) << 56;
477
478
0
    if (err == ZIP_OK)
479
0
        *pX = x;
480
0
    else
481
0
        *pX = 0;
482
483
0
    return err;
484
0
}
485
486
#ifndef BUFREADCOMMENT
487
0
#define BUFREADCOMMENT (0x400)
488
#endif
489
/*
490
  Locate the Central directory of a zipfile (at the end, just before
491
    the global comment)
492
*/
493
static ZPOS64_T
494
zip64local_SearchCentralDir(const zlib_filefunc_def *pzlib_filefunc_def,
495
                            voidpf filestream)
496
0
{
497
0
    ZPOS64_T uMaxBack = 0xffff; /* maximum size of global comment */
498
0
    ZPOS64_T uPosFound = 0;
499
500
0
    if (ZSEEK64(*pzlib_filefunc_def, filestream, 0, ZLIB_FILEFUNC_SEEK_END) !=
501
0
        0)
502
0
        return 0;
503
504
0
    ZPOS64_T uSizeFile = ZTELL64(*pzlib_filefunc_def, filestream);
505
506
0
    if (uMaxBack > uSizeFile)
507
0
        uMaxBack = uSizeFile;
508
509
0
    unsigned char *buf =
510
0
        static_cast<unsigned char *>(ALLOC(BUFREADCOMMENT + 4));
511
0
    if (buf == nullptr)
512
0
        return 0;
513
514
0
    ZPOS64_T uBackRead = 4;
515
0
    while (uBackRead < uMaxBack)
516
0
    {
517
0
        if (uBackRead + BUFREADCOMMENT > uMaxBack)
518
0
            uBackRead = uMaxBack;
519
0
        else
520
0
            uBackRead += BUFREADCOMMENT;
521
0
        ZPOS64_T uReadPos = uSizeFile - uBackRead;
522
523
0
        uLong uReadSize = ((BUFREADCOMMENT + 4) < (uSizeFile - uReadPos))
524
0
                              ? (BUFREADCOMMENT + 4)
525
0
                              : static_cast<uLong>(uSizeFile - uReadPos);
526
0
        if (ZSEEK64(*pzlib_filefunc_def, filestream, uReadPos,
527
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
528
0
            break;
529
530
0
        if (ZREAD64(*pzlib_filefunc_def, filestream, buf, uReadSize) !=
531
0
            uReadSize)
532
0
            break;
533
534
0
        for (int i = static_cast<int>(uReadSize) - 3; (i--) > 0;)
535
0
            if (((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) &&
536
0
                ((*(buf + i + 2)) == 0x05) && ((*(buf + i + 3)) == 0x06))
537
0
            {
538
0
                uPosFound = uReadPos + i;
539
0
                break;
540
0
            }
541
542
0
        if (uPosFound != 0)
543
0
            break;
544
0
    }
545
0
    TRYFREE(buf);
546
0
    return uPosFound;
547
0
}
548
549
/*
550
Locate the End of Zip64 Central directory locator and from there find the CD of
551
a zipfile (at the end, just before the global comment)
552
*/
553
static ZPOS64_T
554
zip64local_SearchCentralDir64(const zlib_filefunc_def *pzlib_filefunc_def,
555
                              voidpf filestream)
556
0
{
557
0
    unsigned char *buf;
558
0
    ZPOS64_T uSizeFile;
559
0
    ZPOS64_T uBackRead;
560
0
    ZPOS64_T uMaxBack = 0xffff; /* maximum size of global comment */
561
0
    ZPOS64_T uPosFound = 0;
562
0
    uLong uL;
563
0
    ZPOS64_T relativeOffset;
564
565
0
    if (ZSEEK64(*pzlib_filefunc_def, filestream, 0, ZLIB_FILEFUNC_SEEK_END) !=
566
0
        0)
567
0
        return 0;
568
569
0
    uSizeFile = ZTELL64(*pzlib_filefunc_def, filestream);
570
571
0
    if (uMaxBack > uSizeFile)
572
0
        uMaxBack = uSizeFile;
573
574
0
    buf = static_cast<unsigned char *>(ALLOC(BUFREADCOMMENT + 4));
575
0
    if (buf == nullptr)
576
0
        return 0;
577
578
0
    uBackRead = 4;
579
0
    while (uBackRead < uMaxBack)
580
0
    {
581
0
        uLong uReadSize;
582
0
        ZPOS64_T uReadPos;
583
0
        int i;
584
0
        if (uBackRead + BUFREADCOMMENT > uMaxBack)
585
0
            uBackRead = uMaxBack;
586
0
        else
587
0
            uBackRead += BUFREADCOMMENT;
588
0
        uReadPos = uSizeFile - uBackRead;
589
590
0
        uReadSize = ((BUFREADCOMMENT + 4) < (uSizeFile - uReadPos))
591
0
                        ? (BUFREADCOMMENT + 4)
592
0
                        : static_cast<uLong>(uSizeFile - uReadPos);
593
0
        if (ZSEEK64(*pzlib_filefunc_def, filestream, uReadPos,
594
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
595
0
            break;
596
597
0
        if (ZREAD64(*pzlib_filefunc_def, filestream, buf, uReadSize) !=
598
0
            uReadSize)
599
0
            break;
600
601
0
        for (i = static_cast<int>(uReadSize) - 3; (i--) > 0;)
602
0
        {
603
            // Signature "0x07064b50" Zip64 end of central directory locater
604
0
            if (((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) &&
605
0
                ((*(buf + i + 2)) == 0x06) && ((*(buf + i + 3)) == 0x07))
606
0
            {
607
0
                uPosFound = uReadPos + i;
608
0
                break;
609
0
            }
610
0
        }
611
612
0
        if (uPosFound != 0)
613
0
            break;
614
0
    }
615
616
0
    TRYFREE(buf);
617
0
    if (uPosFound == 0)
618
0
        return 0;
619
620
    /* Zip64 end of central directory locator */
621
0
    if (ZSEEK64(*pzlib_filefunc_def, filestream, uPosFound,
622
0
                ZLIB_FILEFUNC_SEEK_SET) != 0)
623
0
        return 0;
624
625
    /* the signature, already checked */
626
0
    if (zip64local_getLong(pzlib_filefunc_def, filestream, &uL) != ZIP_OK)
627
0
        return 0;
628
629
    /* number of the disk with the start of the zip64 end of  central directory
630
     */
631
0
    if (zip64local_getLong(pzlib_filefunc_def, filestream, &uL) != ZIP_OK)
632
0
        return 0;
633
0
    if (uL != 0)
634
0
        return 0;
635
636
    /* relative offset of the zip64 end of central directory record */
637
0
    if (zip64local_getLong64(pzlib_filefunc_def, filestream, &relativeOffset) !=
638
0
        ZIP_OK)
639
0
        return 0;
640
641
    /* total number of disks */
642
0
    if (zip64local_getLong(pzlib_filefunc_def, filestream, &uL) != ZIP_OK)
643
0
        return 0;
644
    /* Some .zip declare 0 disks, such as in
645
     * http://trac.osgeo.org/gdal/ticket/5615 */
646
0
    if (uL != 0 && uL != 1)
647
0
        return 0;
648
649
    /* Goto Zip64 end of central directory record */
650
0
    if (ZSEEK64(*pzlib_filefunc_def, filestream, relativeOffset,
651
0
                ZLIB_FILEFUNC_SEEK_SET) != 0)
652
0
        return 0;
653
654
    /* the signature */
655
0
    if (zip64local_getLong(pzlib_filefunc_def, filestream, &uL) != ZIP_OK)
656
0
        return 0;
657
658
0
    if (uL != 0x06064b50)  // signature of 'Zip64 end of central directory'
659
0
        return 0;
660
661
0
    return relativeOffset;
662
0
}
663
664
static int LoadCentralDirectoryRecord(zip64_internal *pziinit)
665
0
{
666
0
    int err = ZIP_OK;
667
0
    ZPOS64_T byte_before_the_zipfile; /* byte before the zipfile, (>0 for sfx)*/
668
669
0
    ZPOS64_T size_central_dir;   /* size of the central directory  */
670
0
    ZPOS64_T offset_central_dir; /* offset of start of central directory */
671
0
    ZPOS64_T central_pos;
672
0
    uLong uL;
673
674
0
    uLong number_disk;         /* number of the current dist, used for
675
                               spanning ZIP, unsupported, always 0*/
676
0
    uLong number_disk_with_CD; /* number the disk with central dir, used
677
                               for spanning ZIP, unsupported, always 0*/
678
0
    ZPOS64_T number_entry;
679
0
    ZPOS64_T number_entry_CD; /* total number of entries in
680
                             the central dir
681
                             (same than number_entry on nospan) */
682
0
    uLong VersionMadeBy;
683
0
    uLong VersionNeeded;
684
0
    uLong size_comment;
685
686
0
    int hasZIP64Record = 0;
687
688
    // check first if we find a ZIP64 record
689
0
    central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,
690
0
                                                pziinit->filestream);
691
0
    if (central_pos > 0)
692
0
    {
693
0
        hasZIP64Record = 1;
694
0
    }
695
0
    else /* if (central_pos == 0) */
696
0
    {
697
0
        central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,
698
0
                                                  pziinit->filestream);
699
0
    }
700
701
    /* disable to allow appending to empty ZIP archive
702
            if (central_pos==0)
703
                err=ZIP_ERRNO;
704
    */
705
706
0
    if (hasZIP64Record)
707
0
    {
708
0
        ZPOS64_T sizeEndOfCentralDirectory;
709
0
        if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,
710
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
711
0
            err = ZIP_ERRNO;
712
713
        /* the signature, already checked */
714
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
715
0
                               &uL) != ZIP_OK)
716
0
            err = ZIP_ERRNO;
717
718
        /* size of zip64 end of central directory record */
719
0
        if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,
720
0
                                 &sizeEndOfCentralDirectory) != ZIP_OK)
721
0
            err = ZIP_ERRNO;
722
723
        /* version made by */
724
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
725
0
                                &VersionMadeBy) != ZIP_OK)
726
0
            err = ZIP_ERRNO;
727
728
        /* version needed to extract */
729
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
730
0
                                &VersionNeeded) != ZIP_OK)
731
0
            err = ZIP_ERRNO;
732
733
        /* number of this disk */
734
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
735
0
                               &number_disk) != ZIP_OK)
736
0
            err = ZIP_ERRNO;
737
738
        /* number of the disk with the start of the central directory */
739
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
740
0
                               &number_disk_with_CD) != ZIP_OK)
741
0
            err = ZIP_ERRNO;
742
743
        /* total number of entries in the central directory on this disk */
744
0
        if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,
745
0
                                 &number_entry) != ZIP_OK)
746
0
            err = ZIP_ERRNO;
747
748
        /* total number of entries in the central directory */
749
0
        if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,
750
0
                                 &number_entry_CD) != ZIP_OK)
751
0
            err = ZIP_ERRNO;
752
753
0
        if ((number_entry_CD != number_entry) || (number_disk_with_CD != 0) ||
754
0
            (number_disk != 0))
755
0
            err = ZIP_BADZIPFILE;
756
757
        /* size of the central directory */
758
0
        if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,
759
0
                                 &size_central_dir) != ZIP_OK)
760
0
            err = ZIP_ERRNO;
761
762
        /* offset of start of central directory with respect to the
763
        starting disk number */
764
0
        if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,
765
0
                                 &offset_central_dir) != ZIP_OK)
766
0
            err = ZIP_ERRNO;
767
768
        // TODO..
769
        // read the comment from the standard central header.
770
0
        size_comment = 0;
771
0
    }
772
0
    else
773
0
    {
774
        // Read End of central Directory info
775
0
        if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,
776
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
777
0
            err = ZIP_ERRNO;
778
779
        /* the signature, already checked */
780
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
781
0
                               &uL) != ZIP_OK)
782
0
            err = ZIP_ERRNO;
783
784
        /* number of this disk */
785
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
786
0
                                &number_disk) != ZIP_OK)
787
0
            err = ZIP_ERRNO;
788
789
        /* number of the disk with the start of the central directory */
790
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
791
0
                                &number_disk_with_CD) != ZIP_OK)
792
0
            err = ZIP_ERRNO;
793
794
        /* total number of entries in the central dir on this disk */
795
0
        number_entry = 0;
796
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
797
0
                                &uL) != ZIP_OK)
798
0
            err = ZIP_ERRNO;
799
0
        else
800
0
            number_entry = uL;
801
802
        /* total number of entries in the central dir */
803
0
        number_entry_CD = 0;
804
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
805
0
                                &uL) != ZIP_OK)
806
0
            err = ZIP_ERRNO;
807
0
        else
808
0
            number_entry_CD = uL;
809
810
0
        if ((number_entry_CD != number_entry) || (number_disk_with_CD != 0) ||
811
0
            (number_disk != 0))
812
0
            err = ZIP_BADZIPFILE;
813
814
        /* size of the central directory */
815
0
        size_central_dir = 0;
816
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
817
0
                               &uL) != ZIP_OK)
818
0
            err = ZIP_ERRNO;
819
0
        else
820
0
            size_central_dir = uL;
821
822
        /* offset of start of central directory with respect to the starting
823
         * disk number */
824
0
        offset_central_dir = 0;
825
0
        if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,
826
0
                               &uL) != ZIP_OK)
827
0
            err = ZIP_ERRNO;
828
0
        else
829
0
            offset_central_dir = uL;
830
831
        /* zipfile global comment length */
832
0
        if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,
833
0
                                &size_comment) != ZIP_OK)
834
0
            err = ZIP_ERRNO;
835
0
    }
836
837
0
    if ((central_pos < offset_central_dir + size_central_dir) &&
838
0
        (err == ZIP_OK))
839
0
        err = ZIP_BADZIPFILE;
840
841
0
    if (err != ZIP_OK)
842
0
    {
843
0
        ZCLOSE64(pziinit->z_filefunc, pziinit->filestream);
844
0
        return ZIP_ERRNO;
845
0
    }
846
847
0
    if (size_comment > 0)
848
0
    {
849
0
        pziinit->globalcomment = static_cast<char *>(ALLOC(size_comment + 1));
850
0
        if (pziinit->globalcomment)
851
0
        {
852
0
            size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream,
853
0
                                   pziinit->globalcomment, size_comment);
854
0
            pziinit->globalcomment[size_comment] = 0;
855
0
        }
856
0
    }
857
858
0
    byte_before_the_zipfile =
859
0
        central_pos - (offset_central_dir + size_central_dir);
860
0
    pziinit->add_position_when_writing_offset = byte_before_the_zipfile;
861
862
0
    {
863
0
        ZPOS64_T size_central_dir_to_read = size_central_dir;
864
0
        size_t buf_size = SIZEDATA_INDATABLOCK;
865
0
        void *buf_read = ALLOC(buf_size);
866
0
        if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream,
867
0
                    offset_central_dir + byte_before_the_zipfile,
868
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
869
0
            err = ZIP_ERRNO;
870
871
0
        while ((size_central_dir_to_read > 0) && (err == ZIP_OK))
872
0
        {
873
0
            ZPOS64_T read_this = SIZEDATA_INDATABLOCK;
874
0
            if (read_this > size_central_dir_to_read)
875
0
                read_this = size_central_dir_to_read;
876
877
0
            if (ZREAD64(pziinit->z_filefunc, pziinit->filestream, buf_read,
878
0
                        static_cast<uLong>(read_this)) != read_this)
879
0
                err = ZIP_ERRNO;
880
881
0
            if (err == ZIP_OK)
882
0
                err = add_data_in_datablock(&pziinit->central_dir, buf_read,
883
0
                                            static_cast<uLong>(read_this));
884
885
0
            size_central_dir_to_read -= read_this;
886
0
        }
887
0
        TRYFREE(buf_read);
888
0
    }
889
0
    pziinit->begin_pos = byte_before_the_zipfile;
890
0
    pziinit->number_entry = number_entry_CD;
891
892
0
    if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream,
893
0
                offset_central_dir + byte_before_the_zipfile,
894
0
                ZLIB_FILEFUNC_SEEK_SET) != 0)
895
0
        err = ZIP_ERRNO;
896
897
0
    return err;
898
0
}
899
900
#endif /* !NO_ADDFILEINEXISTINGZIP*/
901
902
/************************************************************/
903
extern zipFile ZEXPORT cpl_zipOpen2(const char *pathname, int append,
904
                                    zipcharpc *globalcomment,
905
                                    zlib_filefunc_def *pzlib_filefunc_def)
906
0
{
907
0
    zip64_internal ziinit;
908
0
    memset(&ziinit, 0, sizeof(ziinit));
909
910
0
    if (pzlib_filefunc_def == nullptr)
911
0
        cpl_fill_fopen_filefunc(&ziinit.z_filefunc);
912
0
    else
913
0
        ziinit.z_filefunc = *pzlib_filefunc_def;
914
915
0
    ziinit.filestream = (*(ziinit.z_filefunc.zopen_file))(
916
0
        ziinit.z_filefunc.opaque, pathname,
917
0
        (append == APPEND_STATUS_CREATE)
918
0
            ? (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE |
919
0
               ZLIB_FILEFUNC_MODE_CREATE)
920
0
            : (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE |
921
0
               ZLIB_FILEFUNC_MODE_EXISTING));
922
923
0
    if (ziinit.filestream == nullptr)
924
0
        return nullptr;
925
926
0
    if (append == APPEND_STATUS_CREATEAFTER)
927
0
        ZSEEK64(ziinit.z_filefunc, ziinit.filestream, 0, SEEK_END);
928
929
0
    ziinit.begin_pos = ZTELL64(ziinit.z_filefunc, ziinit.filestream);
930
0
    ziinit.in_opened_file_inzip = 0;
931
0
    ziinit.ci.stream_initialised = 0;
932
0
    ziinit.number_entry = 0;
933
0
    ziinit.add_position_when_writing_offset = 0;
934
0
    ziinit.use_cpl_io = (pzlib_filefunc_def == nullptr) ? 1 : 0;
935
0
    ziinit.vsi_raw_length_before = 0;
936
0
    ziinit.vsi_deflate_handle = nullptr;
937
0
    ziinit.nChunkSize = 0;
938
0
    ziinit.nThreads = 0;
939
0
    ziinit.nOffsetSize = 0;
940
0
    ziinit.sozip_index = nullptr;
941
0
    init_linkedlist(&(ziinit.central_dir));
942
943
0
    zip64_internal *zi =
944
0
        static_cast<zip64_internal *>(ALLOC(sizeof(zip64_internal)));
945
0
    if (zi == nullptr)
946
0
    {
947
0
        ZCLOSE64(ziinit.z_filefunc, ziinit.filestream);
948
0
        return nullptr;
949
0
    }
950
951
    /* now we add file in a zipfile */
952
0
#ifndef NO_ADDFILEINEXISTINGZIP
953
0
    ziinit.globalcomment = nullptr;
954
955
0
    int err = ZIP_OK;
956
0
    if (append == APPEND_STATUS_ADDINZIP)
957
0
    {
958
        // Read and Cache Central Directory Records
959
0
        err = LoadCentralDirectoryRecord(&ziinit);
960
0
    }
961
962
0
    if (globalcomment)
963
0
    {
964
0
        *globalcomment = ziinit.globalcomment;
965
0
    }
966
0
#endif /* !NO_ADDFILEINEXISTINGZIP*/
967
968
0
    if (err != ZIP_OK)
969
0
    {
970
0
#ifndef NO_ADDFILEINEXISTINGZIP
971
0
        TRYFREE(ziinit.globalcomment);
972
0
#endif /* !NO_ADDFILEINEXISTINGZIP*/
973
0
        TRYFREE(zi);
974
0
        return nullptr;
975
0
    }
976
0
    else
977
0
    {
978
0
        *zi = ziinit;
979
0
        return static_cast<zipFile>(zi);
980
0
    }
981
0
}
982
983
extern zipFile ZEXPORT cpl_zipOpen(const char *pathname, int append)
984
0
{
985
0
    return cpl_zipOpen2(pathname, append, nullptr, nullptr);
986
0
}
987
988
static void zip64local_putValue_inmemory_update(char **dest, ZPOS64_T x,
989
                                                int nbByte)
990
0
{
991
0
    zip64local_putValue_inmemory(*dest, x, nbByte);
992
0
    *dest += nbByte;
993
0
}
994
995
static int Write_LocalFileHeader(zip64_internal *zi, const char *filename,
996
                                 uInt size_extrafield_local,
997
                                 const void *extrafield_local, int zip64)
998
0
{
999
    /* write the local header */
1000
0
    int err = ZIP_OK;
1001
0
    uInt size_filename = static_cast<uInt>(strlen(filename));
1002
0
    uInt size_extrafield = size_extrafield_local;
1003
1004
0
    if (zip64)
1005
0
    {
1006
0
        size_extrafield += 20;
1007
0
    }
1008
1009
0
    uInt size_local_header = 30 + size_filename + size_extrafield;
1010
0
    char *local_header = static_cast<char *>(ALLOC(size_local_header));
1011
0
    char *p = local_header;
1012
1013
0
    zip64local_putValue_inmemory_update(&p, LOCALHEADERMAGIC, 4);
1014
0
    if (zip64)
1015
0
        zip64local_putValue_inmemory_update(&p, 45,
1016
0
                                            2); /* version needed to extract */
1017
0
    else
1018
0
        zip64local_putValue_inmemory_update(&p, 20,
1019
0
                                            2); /* version needed to extract */
1020
1021
0
    zip64local_putValue_inmemory_update(&p, zi->ci.flag, 2);
1022
1023
0
    zip64local_putValue_inmemory_update(&p, zi->ci.method, 2);
1024
1025
0
    zip64local_putValue_inmemory_update(&p, zi->ci.dosDate, 4);
1026
1027
    // CRC / Compressed size / Uncompressed size will be filled in later and
1028
    // rewritten later
1029
0
    zip64local_putValue_inmemory_update(&p, 0, 4); /* crc 32, unknown */
1030
1031
0
    if (zip64)
1032
0
        zip64local_putValue_inmemory_update(&p, 0xFFFFFFFFU,
1033
0
                                            4); /* compressed size, unknown */
1034
0
    else
1035
0
        zip64local_putValue_inmemory_update(&p, 0,
1036
0
                                            4); /* compressed size, unknown */
1037
1038
0
    if (zip64)
1039
0
        zip64local_putValue_inmemory_update(&p, 0xFFFFFFFFU,
1040
0
                                            4); /* uncompressed size, unknown */
1041
0
    else
1042
0
        zip64local_putValue_inmemory_update(&p, 0,
1043
0
                                            4); /* uncompressed size, unknown */
1044
1045
0
    zip64local_putValue_inmemory_update(&p, size_filename, 2);
1046
1047
0
    zi->ci.size_local_header_extrafield = size_extrafield;
1048
1049
0
    zip64local_putValue_inmemory_update(&p, size_extrafield, 2);
1050
1051
0
    if (size_filename > 0)
1052
0
    {
1053
0
        memcpy(p, filename, size_filename);
1054
0
        p += size_filename;
1055
0
    }
1056
1057
0
    if (size_extrafield_local > 0)
1058
0
    {
1059
0
        memcpy(p, extrafield_local, size_extrafield_local);
1060
0
        p += size_extrafield_local;
1061
0
    }
1062
1063
0
    if (zip64)
1064
0
    {
1065
        // write the Zip64 extended info
1066
0
        short HeaderID = 1;
1067
0
        short DataSize = 16;
1068
0
        ZPOS64_T CompressedSize = 0;
1069
0
        ZPOS64_T UncompressedSize = 0;
1070
1071
        // Remember position of Zip64 extended info for the local file header.
1072
        // (needed when we update size after done with file)
1073
0
        zi->ci.pos_zip64extrainfo =
1074
0
            ZTELL64(zi->z_filefunc, zi->filestream) + p - local_header;
1075
1076
0
        zip64local_putValue_inmemory_update(&p, HeaderID, 2);
1077
0
        zip64local_putValue_inmemory_update(&p, DataSize, 2);
1078
1079
0
        zip64local_putValue_inmemory_update(&p, UncompressedSize, 8);
1080
0
        zip64local_putValue_inmemory_update(&p, CompressedSize, 8);
1081
0
    }
1082
0
    assert(p == local_header + size_local_header);
1083
1084
0
    if (ZWRITE64(zi->z_filefunc, zi->filestream, local_header,
1085
0
                 size_local_header) != size_local_header)
1086
0
        err = ZIP_ERRNO;
1087
1088
0
    zi->ci.local_header = local_header;
1089
0
    zi->ci.size_local_header = size_local_header;
1090
1091
0
    return err;
1092
0
}
1093
1094
extern int ZEXPORT cpl_zipOpenNewFileInZip3(
1095
    zipFile file, const char *filename, const zip_fileinfo *zipfi,
1096
    const void *extrafield_local, uInt size_extrafield_local,
1097
    const void *extrafield_global, uInt size_extrafield_global,
1098
    const char *comment, int method, int level, int raw, int windowBits,
1099
    int memLevel, int strategy, const char *password,
1100
#ifdef NOCRYPT
1101
    uLong /* crcForCrypting */
1102
#else
1103
    uLong crcForCrypting
1104
#endif
1105
    ,
1106
    bool bZip64, bool bIncludeInCentralDirectory)
1107
0
{
1108
0
    zip64_internal *zi;
1109
0
    uInt size_filename;
1110
0
    uInt size_comment;
1111
0
    uInt i;
1112
0
    int err = ZIP_OK;
1113
0
    uLong flagBase = 0;
1114
1115
0
#ifdef NOCRYPT
1116
0
    if (password != nullptr)
1117
0
        return ZIP_PARAMERROR;
1118
0
#endif
1119
1120
0
    if (file == nullptr)
1121
0
        return ZIP_PARAMERROR;
1122
0
    if ((method != 0) && (method != Z_DEFLATED))
1123
0
        return ZIP_PARAMERROR;
1124
1125
0
    zi = reinterpret_cast<zip64_internal *>(file);
1126
1127
0
    if (zi->in_opened_file_inzip == 1)
1128
0
    {
1129
0
        err = cpl_zipCloseFileInZip(file);
1130
0
        if (err != ZIP_OK)
1131
0
            return err;
1132
0
    }
1133
1134
0
    if (filename == nullptr)
1135
0
        filename = "-";
1136
1137
    // The filename and comment length must fit in 16 bits.
1138
0
    if ((filename != nullptr) && (strlen(filename) > 0xffff))
1139
0
        return ZIP_PARAMERROR;
1140
0
    if ((comment != nullptr) && (strlen(comment) > 0xffff))
1141
0
        return ZIP_PARAMERROR;
1142
    // The extra field length must fit in 16 bits. If the member also requires
1143
    // a Zip64 extra block, that will also need to fit within that 16-bit
1144
    // length, but that will be checked for later.
1145
0
    if ((size_extrafield_local > 0xffff) || (size_extrafield_global > 0xffff))
1146
0
        return ZIP_PARAMERROR;
1147
1148
0
    if (comment == nullptr)
1149
0
        size_comment = 0;
1150
0
    else
1151
0
        size_comment = static_cast<uInt>(strlen(comment));
1152
1153
0
    size_filename = static_cast<uInt>(strlen(filename));
1154
1155
0
    if (zipfi == nullptr)
1156
0
        zi->ci.dosDate = 0;
1157
0
    else
1158
0
    {
1159
0
        if (zipfi->dosDate != 0)
1160
0
            zi->ci.dosDate = zipfi->dosDate;
1161
0
        else
1162
0
            zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date);
1163
0
    }
1164
1165
0
    zi->ci.flag = flagBase;
1166
0
    if ((level == 8) || (level == 9))
1167
0
        zi->ci.flag |= 2;
1168
0
    if (level == 2)
1169
0
        zi->ci.flag |= 4;
1170
0
    if (level == 1)
1171
0
        zi->ci.flag |= 6;
1172
#ifndef NOCRYPT
1173
    if (password != nullptr)
1174
        zi->ci.flag |= 1;
1175
#endif
1176
1177
0
    zi->ci.crc32 = 0;
1178
0
    zi->ci.method = method;
1179
0
    zi->ci.encrypt = 0;
1180
0
    zi->ci.stream_initialised = 0;
1181
0
    zi->ci.pos_in_buffered_data = 0;
1182
0
    zi->ci.raw = raw;
1183
0
    zi->ci.pos_local_header = ZTELL64(zi->z_filefunc, zi->filestream);
1184
1185
0
    if (bIncludeInCentralDirectory)
1186
0
    {
1187
0
        zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename +
1188
0
                                    size_extrafield_global + size_comment;
1189
0
        zi->ci.size_centralExtraFree =
1190
0
            32;  // Extra space we have reserved in case we need to add ZIP64
1191
                 // extra info data
1192
1193
0
        zi->ci.central_header = static_cast<char *>(ALLOC(static_cast<uInt>(
1194
0
            zi->ci.size_centralheader + zi->ci.size_centralExtraFree)));
1195
1196
0
        zi->ci.size_centralExtra = size_extrafield_global;
1197
0
        zip64local_putValue_inmemory(zi->ci.central_header, CENTRALHEADERMAGIC,
1198
0
                                     4);
1199
        /* version info */
1200
0
        zip64local_putValue_inmemory(zi->ci.central_header + 4, VERSIONMADEBY,
1201
0
                                     2);
1202
0
        zip64local_putValue_inmemory(zi->ci.central_header + 6, 20, 2);
1203
0
        zip64local_putValue_inmemory(zi->ci.central_header + 8,
1204
0
                                     static_cast<uLong>(zi->ci.flag), 2);
1205
0
        zip64local_putValue_inmemory(zi->ci.central_header + 10,
1206
0
                                     static_cast<uLong>(zi->ci.method), 2);
1207
0
        zip64local_putValue_inmemory(zi->ci.central_header + 12,
1208
0
                                     static_cast<uLong>(zi->ci.dosDate), 4);
1209
0
        zip64local_putValue_inmemory(zi->ci.central_header + 16, 0, 4); /*crc*/
1210
0
        zip64local_putValue_inmemory(zi->ci.central_header + 20, 0,
1211
0
                                     4); /*compr size*/
1212
0
        zip64local_putValue_inmemory(zi->ci.central_header + 24, 0,
1213
0
                                     4); /*uncompr size*/
1214
0
        zip64local_putValue_inmemory(zi->ci.central_header + 28,
1215
0
                                     static_cast<uLong>(size_filename), 2);
1216
0
        zip64local_putValue_inmemory(zi->ci.central_header + 30,
1217
0
                                     static_cast<uLong>(size_extrafield_global),
1218
0
                                     2);
1219
0
        zip64local_putValue_inmemory(zi->ci.central_header + 32,
1220
0
                                     static_cast<uLong>(size_comment), 2);
1221
0
        zip64local_putValue_inmemory(zi->ci.central_header + 34, 0,
1222
0
                                     2); /*disk nm start*/
1223
1224
0
        if (zipfi == nullptr)
1225
0
            zip64local_putValue_inmemory(zi->ci.central_header + 36, 0, 2);
1226
0
        else
1227
0
            zip64local_putValue_inmemory(zi->ci.central_header + 36,
1228
0
                                         static_cast<uLong>(zipfi->internal_fa),
1229
0
                                         2);
1230
1231
0
        if (zipfi == nullptr)
1232
0
            zip64local_putValue_inmemory(zi->ci.central_header + 38, 0, 4);
1233
0
        else
1234
0
            zip64local_putValue_inmemory(zi->ci.central_header + 38,
1235
0
                                         static_cast<uLong>(zipfi->external_fa),
1236
0
                                         4);
1237
1238
0
        if (zi->ci.pos_local_header >= 0xffffffff)
1239
0
            zip64local_putValue_inmemory(zi->ci.central_header + 42,
1240
0
                                         static_cast<uLong>(0xffffffff), 4);
1241
0
        else
1242
0
            zip64local_putValue_inmemory(
1243
0
                zi->ci.central_header + 42,
1244
0
                static_cast<uLong>(zi->ci.pos_local_header) -
1245
0
                    zi->add_position_when_writing_offset,
1246
0
                4);
1247
1248
0
        for (i = 0; i < size_filename; i++)
1249
0
            *(zi->ci.central_header + SIZECENTRALHEADER + i) = *(filename + i);
1250
1251
0
        for (i = 0; i < size_extrafield_global; i++)
1252
0
            *(zi->ci.central_header + SIZECENTRALHEADER + size_filename + i) =
1253
0
                *((reinterpret_cast<const char *>(extrafield_global)) + i);
1254
1255
0
        for (i = 0; i < size_comment; i++)
1256
0
            *(zi->ci.central_header + SIZECENTRALHEADER + size_filename +
1257
0
              size_extrafield_global + i) = *(comment + i);
1258
0
        if (zi->ci.central_header == nullptr)
1259
0
            return ZIP_INTERNALERROR;
1260
0
    }
1261
0
    else
1262
0
    {
1263
0
        zi->ci.central_header = nullptr;
1264
0
    }
1265
1266
0
    zi->ci.totalCompressedData = 0;
1267
0
    zi->ci.totalUncompressedData = 0;
1268
0
    zi->ci.pos_zip64extrainfo = 0;
1269
1270
    // For now default is to generate zip64 extra fields
1271
0
    err = Write_LocalFileHeader(zi, filename, size_extrafield_local,
1272
0
                                extrafield_local, bZip64 ? 1 : 0);
1273
1274
0
    zi->ci.stream.avail_in = 0;
1275
0
    zi->ci.stream.avail_out = Z_BUFSIZE;
1276
0
    zi->ci.stream.next_out = zi->ci.buffered_data;
1277
0
    zi->ci.stream.total_in = 0;
1278
0
    zi->ci.stream.total_out = 0;
1279
0
    zi->ci.stream.data_type = Z_UNKNOWN;
1280
1281
0
    if ((err == ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
1282
0
    {
1283
0
        zi->ci.stream.zalloc = nullptr;
1284
0
        zi->ci.stream.zfree = nullptr;
1285
0
        zi->ci.stream.opaque = nullptr;
1286
1287
0
        if (windowBits > 0)
1288
0
            windowBits = -windowBits;
1289
1290
0
        if (zi->use_cpl_io)
1291
0
        {
1292
0
            auto fpRaw = reinterpret_cast<VSIVirtualHandle *>(zi->filestream);
1293
0
            zi->vsi_raw_length_before = fpRaw->Tell();
1294
0
            zi->vsi_deflate_handle = VSICreateGZipWritable(
1295
0
                fpRaw, CPL_DEFLATE_TYPE_RAW_DEFLATE, false, zi->nThreads,
1296
0
                zi->nChunkSize, zi->nOffsetSize, zi->sozip_index);
1297
0
            err = Z_OK;
1298
0
        }
1299
0
        else
1300
0
        {
1301
0
            err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits,
1302
0
                               memLevel, strategy);
1303
0
        }
1304
1305
0
        if (err == Z_OK)
1306
0
            zi->ci.stream_initialised = 1;
1307
0
    }
1308
#ifndef NOCRYPT
1309
    zi->ci.crypt_header_size = 0;
1310
    if ((err == Z_OK) && (password != nullptr))
1311
    {
1312
        unsigned char bufHead[RAND_HEAD_LEN];
1313
        unsigned int sizeHead = 0;
1314
        zi->ci.encrypt = 1;
1315
        zi->ci.pcrc_32_tab = get_crc_table();
1316
        /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/
1317
1318
        sizeHead = crypthead(password, bufHead, RAND_HEAD_LEN, zi->ci.keys,
1319
                             zi->ci.pcrc_32_tab, crcForCrypting);
1320
        zi->ci.crypt_header_size = sizeHead;
1321
1322
        if (ZWRITE64(zi->z_filefunc, zi->filestream, bufHead, sizeHead) !=
1323
            sizeHead)
1324
            err = ZIP_ERRNO;
1325
    }
1326
#endif
1327
1328
0
    if (err == Z_OK)
1329
0
        zi->in_opened_file_inzip = 1;
1330
0
    else
1331
0
    {
1332
0
        free(zi->ci.central_header);
1333
0
        zi->ci.central_header = nullptr;
1334
0
        free(zi->ci.local_header);
1335
0
        zi->ci.local_header = nullptr;
1336
0
    }
1337
1338
0
    return err;
1339
0
}
1340
1341
extern int ZEXPORT cpl_zipOpenNewFileInZip2(
1342
    zipFile file, const char *filename, const zip_fileinfo *zipfi,
1343
    const void *extrafield_local, uInt size_extrafield_local,
1344
    const void *extrafield_global, uInt size_extrafield_global,
1345
    const char *comment, int method, int level, int raw)
1346
0
{
1347
0
    return cpl_zipOpenNewFileInZip3(
1348
0
        file, filename, zipfi, extrafield_local, size_extrafield_local,
1349
0
        extrafield_global, size_extrafield_global, comment, method, level, raw,
1350
0
        -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nullptr, 0, true, true);
1351
0
}
1352
1353
extern int ZEXPORT cpl_zipOpenNewFileInZip(
1354
    zipFile file, const char *filename, const zip_fileinfo *zipfi,
1355
    const void *extrafield_local, uInt size_extrafield_local,
1356
    const void *extrafield_global, uInt size_extrafield_global,
1357
    const char *comment, int method, int level)
1358
0
{
1359
0
    return cpl_zipOpenNewFileInZip2(
1360
0
        file, filename, zipfi, extrafield_local, size_extrafield_local,
1361
0
        extrafield_global, size_extrafield_global, comment, method, level, 0);
1362
0
}
1363
1364
static int zip64FlushWriteBuffer(zip64_internal *zi)
1365
0
{
1366
0
    int err = ZIP_OK;
1367
1368
0
    if (zi->ci.encrypt != 0)
1369
0
    {
1370
#ifndef NOCRYPT
1371
        int t = 0;
1372
        for (uInt i = 0; i < zi->ci.pos_in_buffered_data; i++)
1373
            zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab,
1374
                                              zi->ci.buffered_data[i], t);
1375
#endif
1376
0
    }
1377
0
    if (ZWRITE64(zi->z_filefunc, zi->filestream, zi->ci.buffered_data,
1378
0
                 zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data)
1379
0
        err = ZIP_ERRNO;
1380
1381
0
    zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data;
1382
0
    zi->ci.totalUncompressedData += zi->ci.stream.total_in;
1383
0
    zi->ci.stream.total_in = 0;
1384
1385
0
    zi->ci.pos_in_buffered_data = 0;
1386
0
    return err;
1387
0
}
1388
1389
extern int ZEXPORT cpl_zipWriteInFileInZip(zipFile file, const void *buf,
1390
                                           unsigned len)
1391
0
{
1392
0
    if (file == nullptr)
1393
0
        return ZIP_PARAMERROR;
1394
1395
0
    zip64_internal *zi = reinterpret_cast<zip64_internal *>(file);
1396
1397
0
    if (zi->in_opened_file_inzip == 0)
1398
0
        return ZIP_PARAMERROR;
1399
1400
0
    zi->ci.stream.next_in = reinterpret_cast<Bytef *>(const_cast<void *>(buf));
1401
0
    zi->ci.stream.avail_in = len;
1402
0
    zi->ci.crc32 =
1403
0
        crc32(zi->ci.crc32, reinterpret_cast<const Bytef *>(buf), len);
1404
1405
0
    int err = ZIP_OK;
1406
0
    while ((err == ZIP_OK) && (zi->ci.stream.avail_in > 0))
1407
0
    {
1408
0
        if (zi->ci.stream.avail_out == 0)
1409
0
        {
1410
0
            if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
1411
0
                err = ZIP_ERRNO;
1412
0
            zi->ci.stream.avail_out = Z_BUFSIZE;
1413
0
            zi->ci.stream.next_out = zi->ci.buffered_data;
1414
0
        }
1415
1416
0
        if (err != ZIP_OK)
1417
0
            break;
1418
1419
0
        if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
1420
0
        {
1421
0
            if (zi->vsi_deflate_handle)
1422
0
            {
1423
0
                zi->ci.totalUncompressedData += len;
1424
0
                if (zi->vsi_deflate_handle->Write(buf, 1, len) < len)
1425
0
                    err = ZIP_INTERNALERROR;
1426
0
                zi->ci.stream.avail_in = 0;
1427
0
            }
1428
0
            else
1429
0
            {
1430
0
                uLong uTotalOutBefore = zi->ci.stream.total_out;
1431
0
                err = deflate(&zi->ci.stream, Z_NO_FLUSH);
1432
0
                zi->ci.pos_in_buffered_data += static_cast<uInt>(
1433
0
                    zi->ci.stream.total_out - uTotalOutBefore);
1434
0
            }
1435
0
        }
1436
0
        else
1437
0
        {
1438
0
            uInt copy_this;
1439
0
            if (zi->ci.stream.avail_in < zi->ci.stream.avail_out)
1440
0
                copy_this = zi->ci.stream.avail_in;
1441
0
            else
1442
0
                copy_this = zi->ci.stream.avail_out;
1443
0
            for (uInt i = 0; i < copy_this; i++)
1444
0
                *((reinterpret_cast<char *>(zi->ci.stream.next_out)) + i) =
1445
0
                    *((reinterpret_cast<const char *>(zi->ci.stream.next_in)) +
1446
0
                      i);
1447
0
            {
1448
0
                zi->ci.stream.avail_in -= copy_this;
1449
0
                zi->ci.stream.avail_out -= copy_this;
1450
0
                zi->ci.stream.next_in += copy_this;
1451
0
                zi->ci.stream.next_out += copy_this;
1452
0
                zi->ci.stream.total_in += copy_this;
1453
0
                zi->ci.stream.total_out += copy_this;
1454
0
                zi->ci.pos_in_buffered_data += copy_this;
1455
0
            }
1456
0
        }
1457
0
    }
1458
1459
0
    return err;
1460
0
}
1461
1462
extern int ZEXPORT cpl_zipCloseFileInZipRaw(zipFile file,
1463
                                            ZPOS64_T uncompressed_size,
1464
                                            uLong crc32)
1465
0
{
1466
0
    if (file == nullptr)
1467
0
        return ZIP_PARAMERROR;
1468
1469
0
    zip64_internal *zi = reinterpret_cast<zip64_internal *>(file);
1470
1471
0
    if (zi->in_opened_file_inzip == 0)
1472
0
        return ZIP_PARAMERROR;
1473
0
    zi->ci.stream.avail_in = 0;
1474
1475
0
    int err = ZIP_OK;
1476
0
    if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
1477
0
    {
1478
0
        if (zi->vsi_deflate_handle)
1479
0
        {
1480
0
            auto fpRaw = reinterpret_cast<VSIVirtualHandle *>(zi->filestream);
1481
0
            delete zi->vsi_deflate_handle;
1482
0
            zi->vsi_deflate_handle = nullptr;
1483
0
            zi->ci.totalCompressedData =
1484
0
                fpRaw->Tell() - zi->vsi_raw_length_before;
1485
1486
0
            if (zi->sozip_index)
1487
0
            {
1488
0
                uint64_t nVal = CPL_AS_LSB(
1489
0
                    static_cast<uint64_t>(zi->ci.totalCompressedData));
1490
0
                memcpy(zi->sozip_index->data() + 24, &nVal, sizeof(uint64_t));
1491
0
            }
1492
0
        }
1493
0
        else
1494
0
        {
1495
0
            while (err == ZIP_OK)
1496
0
            {
1497
0
                if (zi->ci.stream.avail_out == 0)
1498
0
                {
1499
0
                    if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
1500
0
                    {
1501
0
                        err = ZIP_ERRNO;
1502
0
                        break;
1503
0
                    }
1504
0
                    zi->ci.stream.avail_out = Z_BUFSIZE;
1505
0
                    zi->ci.stream.next_out = zi->ci.buffered_data;
1506
0
                }
1507
0
                uLong uTotalOutBefore = zi->ci.stream.total_out;
1508
0
                err = deflate(&zi->ci.stream, Z_FINISH);
1509
0
                zi->ci.pos_in_buffered_data += static_cast<uInt>(
1510
0
                    zi->ci.stream.total_out - uTotalOutBefore);
1511
0
            }
1512
0
        }
1513
0
    }
1514
1515
0
    if (err == Z_STREAM_END)
1516
0
        err = ZIP_OK; /* this is normal */
1517
1518
0
    if ((zi->ci.pos_in_buffered_data > 0) && (err == ZIP_OK))
1519
0
        if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
1520
0
            err = ZIP_ERRNO;
1521
1522
0
    if (!zi->use_cpl_io && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
1523
0
    {
1524
0
        err = deflateEnd(&zi->ci.stream);
1525
0
        zi->ci.stream_initialised = 0;
1526
0
    }
1527
1528
0
    if (!zi->ci.raw)
1529
0
    {
1530
0
        crc32 = static_cast<uLong>(zi->ci.crc32);
1531
0
        uncompressed_size = zi->ci.totalUncompressedData;
1532
0
    }
1533
0
    ZPOS64_T compressed_size = zi->ci.totalCompressedData;
1534
#ifndef NOCRYPT
1535
    compressed_size += zi->ci.crypt_header_size;
1536
#endif
1537
1538
#ifdef disabled
1539
    // Code finally disabled since it causes compatibility issues with
1540
    // libreoffice for .xlsx or .ods files
1541
    if (zi->ci.pos_zip64extrainfo && uncompressed_size < 0xffffffff &&
1542
        compressed_size < 0xffffffff)
1543
    {
1544
        // Update the LocalFileHeader to be a regular one and not a ZIP64 one
1545
        // by removing its trailing 20 bytes, and moving it in the file
1546
        // 20 bytes further of its original position.
1547
1548
        ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc, zi->filestream);
1549
1550
        if (ZSEEK64(zi->z_filefunc, zi->filestream, zi->ci.pos_local_header,
1551
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
1552
            err = ZIP_ERRNO;
1553
1554
        // Insert leading padding
1555
        constexpr uInt nZIP64ExtraBytes = 20;
1556
        char padding[nZIP64ExtraBytes];
1557
        memset(padding, 0, sizeof(padding));
1558
        if (ZWRITE64(zi->z_filefunc, zi->filestream, padding,
1559
                     nZIP64ExtraBytes) != nZIP64ExtraBytes)
1560
            err = ZIP_ERRNO;
1561
1562
        // Correct version needed to extract
1563
        zip64local_putValue_inmemory(zi->ci.local_header + 4, 20, 2);
1564
1565
        // Correct extra field length
1566
        zi->ci.size_local_header_extrafield -= nZIP64ExtraBytes;
1567
        zip64local_putValue_inmemory(zi->ci.local_header + 28,
1568
                                     zi->ci.size_local_header_extrafield, 2);
1569
1570
        zi->ci.size_local_header -= nZIP64ExtraBytes;
1571
1572
        // Rewrite local header
1573
        if (ZWRITE64(zi->z_filefunc, zi->filestream, zi->ci.local_header,
1574
                     zi->ci.size_local_header) != zi->ci.size_local_header)
1575
            err = ZIP_ERRNO;
1576
1577
        if (ZSEEK64(zi->z_filefunc, zi->filestream, cur_pos_inzip,
1578
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
1579
            err = ZIP_ERRNO;
1580
1581
        zi->ci.pos_zip64extrainfo = 0;
1582
1583
        // Correct central header offset to local header
1584
        zi->ci.pos_local_header += nZIP64ExtraBytes;
1585
        if (zi->ci.central_header)
1586
        {
1587
            if (zi->ci.pos_local_header >= 0xffffffff)
1588
                zip64local_putValue_inmemory(zi->ci.central_header + 42,
1589
                                             static_cast<uLong>(0xffffffff), 4);
1590
            else
1591
                zip64local_putValue_inmemory(
1592
                    zi->ci.central_header + 42,
1593
                    static_cast<uLong>(zi->ci.pos_local_header) -
1594
                        zi->add_position_when_writing_offset,
1595
                    4);
1596
        }
1597
    }
1598
#endif
1599
1600
0
    const bool bInCentralHeader = zi->ci.central_header != nullptr;
1601
0
    if (zi->ci.central_header)
1602
0
    {
1603
        // update Current Item crc and sizes,
1604
0
        if (zi->ci.pos_zip64extrainfo || compressed_size >= 0xffffffff ||
1605
0
            uncompressed_size >= 0xffffffff ||
1606
0
            zi->ci.pos_local_header >= 0xffffffff)
1607
0
        {
1608
            /*version Made by*/
1609
0
            zip64local_putValue_inmemory(zi->ci.central_header + 4, 45, 2);
1610
            /*version needed*/
1611
0
            zip64local_putValue_inmemory(zi->ci.central_header + 6, 45, 2);
1612
0
        }
1613
1614
0
        zip64local_putValue_inmemory(zi->ci.central_header + 16, crc32,
1615
0
                                     4); /*crc*/
1616
1617
0
        const uLong invalidValue = 0xffffffff;
1618
0
        if (compressed_size >= 0xffffffff)
1619
0
            zip64local_putValue_inmemory(zi->ci.central_header + 20,
1620
0
                                         invalidValue, 4); /*compr size*/
1621
0
        else
1622
0
            zip64local_putValue_inmemory(zi->ci.central_header + 20,
1623
0
                                         compressed_size, 4); /*compr size*/
1624
1625
        /// set internal file attributes field
1626
0
        if (zi->ci.stream.data_type == Z_ASCII)
1627
0
            zip64local_putValue_inmemory(zi->ci.central_header + 36, Z_ASCII,
1628
0
                                         2);
1629
1630
0
        if (uncompressed_size >= 0xffffffff)
1631
0
            zip64local_putValue_inmemory(zi->ci.central_header + 24,
1632
0
                                         invalidValue, 4); /*uncompr size*/
1633
0
        else
1634
0
            zip64local_putValue_inmemory(zi->ci.central_header + 24,
1635
0
                                         uncompressed_size, 4); /*uncompr size*/
1636
1637
0
        short datasize = 0;
1638
        // Add ZIP64 extra info field for uncompressed size
1639
0
        if (uncompressed_size >= 0xffffffff)
1640
0
            datasize += 8;
1641
1642
        // Add ZIP64 extra info field for compressed size
1643
0
        if (compressed_size >= 0xffffffff)
1644
0
            datasize += 8;
1645
1646
        // Add ZIP64 extra info field for relative offset to local file header
1647
        // of current file
1648
0
        if (zi->ci.pos_local_header >= 0xffffffff)
1649
0
            datasize += 8;
1650
1651
0
        if (datasize > 0)
1652
0
        {
1653
0
            char *p = nullptr;
1654
1655
0
            if (static_cast<uLong>(datasize + 4) > zi->ci.size_centralExtraFree)
1656
0
            {
1657
                // we can not write more data to the buffer that we have room
1658
                // for.
1659
0
                return ZIP_BADZIPFILE;
1660
0
            }
1661
1662
0
            p = zi->ci.central_header + zi->ci.size_centralheader;
1663
1664
            // Add Extra Information Header for 'ZIP64 information'
1665
0
            zip64local_putValue_inmemory(p, 0x0001, 2);  // HeaderID
1666
0
            p += 2;
1667
0
            zip64local_putValue_inmemory(p, datasize, 2);  // DataSize
1668
0
            p += 2;
1669
1670
0
            if (uncompressed_size >= 0xffffffff)
1671
0
            {
1672
0
                zip64local_putValue_inmemory(p, uncompressed_size, 8);
1673
0
                p += 8;
1674
0
            }
1675
1676
0
            if (compressed_size >= 0xffffffff)
1677
0
            {
1678
0
                zip64local_putValue_inmemory(p, compressed_size, 8);
1679
0
                p += 8;
1680
0
            }
1681
1682
0
            if (zi->ci.pos_local_header >= 0xffffffff)
1683
0
            {
1684
0
                zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8);
1685
                // p += 8;
1686
0
            }
1687
1688
            // Update how much extra free space we got in the memory buffer
1689
            // and increase the centralheader size so the new ZIP64 fields are
1690
            // included ( 4 below is the size of HeaderID and DataSize field )
1691
0
            zi->ci.size_centralExtraFree -= datasize + 4;
1692
0
            zi->ci.size_centralheader += datasize + 4;
1693
1694
            // Update the extra info size field
1695
0
            zi->ci.size_centralExtra += datasize + 4;
1696
0
            zip64local_putValue_inmemory(
1697
0
                zi->ci.central_header + 30,
1698
0
                static_cast<uLong>(zi->ci.size_centralExtra), 2);
1699
0
        }
1700
1701
0
        if (err == ZIP_OK)
1702
0
            err = add_data_in_datablock(
1703
0
                &zi->central_dir, zi->ci.central_header,
1704
0
                static_cast<uLong>(zi->ci.size_centralheader));
1705
0
        free(zi->ci.central_header);
1706
0
        zi->ci.central_header = nullptr;
1707
0
    }
1708
1709
0
    free(zi->ci.local_header);
1710
0
    zi->ci.local_header = nullptr;
1711
1712
0
    if (err == ZIP_OK)
1713
0
    {
1714
        // Update the LocalFileHeader with the new values.
1715
1716
0
        ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc, zi->filestream);
1717
1718
0
        if (ZSEEK64(zi->z_filefunc, zi->filestream,
1719
0
                    zi->ci.pos_local_header + 14, ZLIB_FILEFUNC_SEEK_SET) != 0)
1720
0
            err = ZIP_ERRNO;
1721
1722
0
        if (err == ZIP_OK)
1723
0
            err = zip64local_putValue(&zi->z_filefunc, zi->filestream, crc32,
1724
0
                                      4); /* crc 32, unknown */
1725
1726
0
        if (uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff)
1727
0
        {
1728
0
            if (zi->ci.pos_zip64extrainfo > 0)
1729
0
            {
1730
                // Update the size in the ZIP64 extended field.
1731
0
                if (ZSEEK64(zi->z_filefunc, zi->filestream,
1732
0
                            zi->ci.pos_zip64extrainfo + 4,
1733
0
                            ZLIB_FILEFUNC_SEEK_SET) != 0)
1734
0
                    err = ZIP_ERRNO;
1735
1736
0
                if (err == ZIP_OK) /* compressed size, unknown */
1737
0
                    err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1738
0
                                              uncompressed_size, 8);
1739
1740
0
                if (err == ZIP_OK) /* uncompressed size, unknown */
1741
0
                    err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1742
0
                                              compressed_size, 8);
1743
0
            }
1744
0
            else
1745
0
                err = ZIP_BADZIPFILE;  // Caller passed zip64 = 0, so no room
1746
                                       // for zip64 info -> fatal
1747
0
        }
1748
0
        else
1749
0
        {
1750
0
            if (err == ZIP_OK) /* compressed size, unknown */
1751
0
                err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1752
0
                                          compressed_size, 4);
1753
1754
0
            if (err == ZIP_OK) /* uncompressed size, unknown */
1755
0
                err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1756
0
                                          uncompressed_size, 4);
1757
0
        }
1758
0
        if (ZSEEK64(zi->z_filefunc, zi->filestream, cur_pos_inzip,
1759
0
                    ZLIB_FILEFUNC_SEEK_SET) != 0)
1760
0
            err = ZIP_ERRNO;
1761
0
    }
1762
1763
0
    if (bInCentralHeader)
1764
0
        zi->number_entry++;
1765
0
    zi->in_opened_file_inzip = 0;
1766
1767
0
    return err;
1768
0
}
1769
1770
extern int ZEXPORT cpl_zipCloseFileInZip(zipFile file)
1771
0
{
1772
0
    return cpl_zipCloseFileInZipRaw(file, 0, 0);
1773
0
}
1774
1775
static int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal *zi,
1776
                                                   ZPOS64_T zip64eocd_pos_inzip)
1777
0
{
1778
0
    int err = ZIP_OK;
1779
0
    ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writing_offset;
1780
1781
0
    err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1782
0
                              ZIP64ENDLOCHEADERMAGIC, 4);
1783
1784
    /*num disks*/
1785
0
    if (err ==
1786
0
        ZIP_OK) /* number of the disk with the start of the central directory */
1787
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0, 4);
1788
1789
    /*relative offset*/
1790
0
    if (err == ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */
1791
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, pos, 8);
1792
1793
    /*total disks*/ /* Do not support spawning of disk so always say 1 here*/
1794
0
    if (err ==
1795
0
        ZIP_OK) /* number of the disk with the start of the central directory */
1796
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 1, 4);
1797
1798
0
    return err;
1799
0
}
1800
1801
static int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal *zi,
1802
                                                  uLong size_centraldir,
1803
                                                  ZPOS64_T centraldir_pos_inzip)
1804
0
{
1805
0
    int err = ZIP_OK;
1806
1807
0
    uLong Zip64DataSize = 44;
1808
1809
0
    err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1810
0
                              ZIP64ENDHEADERMAGIC, 4);
1811
1812
0
    if (err == ZIP_OK) /* size of this 'zip64 end of central directory' */
1813
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1814
0
                                  Zip64DataSize, 8);  // why ZPOS64_T of this ?
1815
1816
0
    if (err == ZIP_OK) /* version made by */
1817
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 45, 2);
1818
1819
0
    if (err == ZIP_OK) /* version needed */
1820
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 45, 2);
1821
1822
0
    if (err == ZIP_OK) /* number of this disk */
1823
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0, 4);
1824
1825
0
    if (err ==
1826
0
        ZIP_OK) /* number of the disk with the start of the central directory */
1827
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0, 4);
1828
1829
0
    if (err ==
1830
0
        ZIP_OK) /* total number of entries in the central dir on this disk */
1831
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1832
0
                                  zi->number_entry, 8);
1833
1834
0
    if (err == ZIP_OK) /* total number of entries in the central dir */
1835
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1836
0
                                  zi->number_entry, 8);
1837
1838
0
    if (err == ZIP_OK) /* size of the central directory */
1839
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1840
0
                                  size_centraldir, 8);
1841
1842
0
    if (err == ZIP_OK) /* offset of start of central directory with respect to
1843
                          the starting disk number */
1844
0
    {
1845
0
        ZPOS64_T pos =
1846
0
            centraldir_pos_inzip - zi->add_position_when_writing_offset;
1847
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, pos, 8);
1848
0
    }
1849
0
    return err;
1850
0
}
1851
1852
static int Write_EndOfCentralDirectoryRecord(zip64_internal *zi,
1853
                                             uLong size_centraldir,
1854
                                             ZPOS64_T centraldir_pos_inzip)
1855
0
{
1856
0
    int err = ZIP_OK;
1857
1858
    /*signature*/
1859
0
    err =
1860
0
        zip64local_putValue(&zi->z_filefunc, zi->filestream, ENDHEADERMAGIC, 4);
1861
1862
0
    if (err == ZIP_OK) /* number of this disk */
1863
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0, 2);
1864
1865
0
    if (err ==
1866
0
        ZIP_OK) /* number of the disk with the start of the central directory */
1867
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0, 2);
1868
1869
0
    if (err ==
1870
0
        ZIP_OK) /* total number of entries in the central dir on this disk */
1871
0
    {
1872
0
        {
1873
0
            if (zi->number_entry >= 0xFFFF)
1874
0
                err =
1875
0
                    zip64local_putValue(&zi->z_filefunc, zi->filestream, 0xffff,
1876
0
                                        2);  // use value in ZIP64 record
1877
0
            else
1878
0
                err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1879
0
                                          zi->number_entry, 2);
1880
0
        }
1881
0
    }
1882
1883
0
    if (err == ZIP_OK) /* total number of entries in the central dir */
1884
0
    {
1885
0
        if (zi->number_entry >= 0xFFFF)
1886
0
            err = zip64local_putValue(&zi->z_filefunc, zi->filestream, 0xffff,
1887
0
                                      2);  // use value in ZIP64 record
1888
0
        else
1889
0
            err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1890
0
                                      zi->number_entry, 2);
1891
0
    }
1892
1893
0
    if (err == ZIP_OK) /* size of the central directory */
1894
0
        err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1895
0
                                  size_centraldir, 4);
1896
1897
0
    if (err == ZIP_OK) /* offset of start of central directory with respect to
1898
                          the starting disk number */
1899
0
    {
1900
0
        ZPOS64_T pos =
1901
0
            centraldir_pos_inzip - zi->add_position_when_writing_offset;
1902
0
        if (pos >= 0xffffffff)
1903
0
        {
1904
0
            err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1905
0
                                      0xffffffff, 4);
1906
0
        }
1907
0
        else
1908
0
            err = zip64local_putValue(
1909
0
                &zi->z_filefunc, zi->filestream,
1910
0
                (centraldir_pos_inzip - zi->add_position_when_writing_offset),
1911
0
                4);
1912
0
    }
1913
1914
0
    return err;
1915
0
}
1916
1917
static int Write_GlobalComment(zip64_internal *zi, const char *global_comment)
1918
0
{
1919
0
    int err = ZIP_OK;
1920
0
    uInt size_global_comment = 0;
1921
1922
0
    if (global_comment != nullptr)
1923
0
        size_global_comment = static_cast<uInt>(strlen(global_comment));
1924
1925
0
    err = zip64local_putValue(&zi->z_filefunc, zi->filestream,
1926
0
                              size_global_comment, 2);
1927
1928
0
    if (err == ZIP_OK && size_global_comment > 0)
1929
0
    {
1930
0
        if (ZWRITE64(zi->z_filefunc, zi->filestream, global_comment,
1931
0
                     size_global_comment) != size_global_comment)
1932
0
            err = ZIP_ERRNO;
1933
0
    }
1934
0
    return err;
1935
0
}
1936
1937
extern int ZEXPORT cpl_zipClose(zipFile file, const char *global_comment)
1938
0
{
1939
0
    int err = 0;
1940
0
    uLong size_centraldir = 0;
1941
0
    ZPOS64_T centraldir_pos_inzip;
1942
0
    ZPOS64_T pos;
1943
1944
0
    if (file == nullptr)
1945
0
        return ZIP_PARAMERROR;
1946
1947
0
    zip64_internal *zi = reinterpret_cast<zip64_internal *>(file);
1948
1949
0
    if (zi->in_opened_file_inzip == 1)
1950
0
    {
1951
0
        err = cpl_zipCloseFileInZip(file);
1952
0
    }
1953
1954
0
#ifndef NO_ADDFILEINEXISTINGZIP
1955
0
    if (global_comment == nullptr)
1956
0
        global_comment = zi->globalcomment;
1957
0
#endif
1958
1959
0
    centraldir_pos_inzip = ZTELL64(zi->z_filefunc, zi->filestream);
1960
0
    if (err == ZIP_OK)
1961
0
    {
1962
0
        linkedlist_datablock_internal *ldi = zi->central_dir.first_block;
1963
0
        while (ldi != nullptr)
1964
0
        {
1965
0
            if ((err == ZIP_OK) && (ldi->filled_in_this_block > 0))
1966
0
                if (ZWRITE64(zi->z_filefunc, zi->filestream, ldi->data,
1967
0
                             ldi->filled_in_this_block) !=
1968
0
                    ldi->filled_in_this_block)
1969
0
                    err = ZIP_ERRNO;
1970
1971
0
            size_centraldir += ldi->filled_in_this_block;
1972
0
            ldi = ldi->next_datablock;
1973
0
        }
1974
0
    }
1975
0
    free_linkedlist(&(zi->central_dir));
1976
1977
0
    pos = centraldir_pos_inzip - zi->add_position_when_writing_offset;
1978
0
    if (pos >= 0xffffffff || zi->number_entry > 0xFFFF)
1979
0
    {
1980
0
        ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc, zi->filestream);
1981
0
        Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir,
1982
0
                                               centraldir_pos_inzip);
1983
1984
0
        Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos);
1985
0
    }
1986
1987
0
    if (err == ZIP_OK)
1988
0
        err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir,
1989
0
                                                centraldir_pos_inzip);
1990
1991
0
    if (err == ZIP_OK)
1992
0
        err = Write_GlobalComment(zi, global_comment);
1993
1994
0
    if (ZCLOSE64(zi->z_filefunc, zi->filestream) != 0)
1995
0
        if (err == ZIP_OK)
1996
0
            err = ZIP_ERRNO;
1997
1998
0
#ifndef NO_ADDFILEINEXISTINGZIP
1999
0
    TRYFREE(zi->globalcomment);
2000
0
#endif
2001
0
    TRYFREE(zi);
2002
2003
0
    return err;
2004
0
}
2005
2006
/************************************************************************/
2007
/* ==================================================================== */
2008
/*   The following is a simplified CPL API for creating ZIP files       */
2009
/*   exported from cpl_conv.h.                                          */
2010
/* ==================================================================== */
2011
/************************************************************************/
2012
2013
#include "cpl_minizip_unzip.h"
2014
2015
typedef struct
2016
{
2017
    zipFile hZip;
2018
    char **papszFilenames;
2019
} CPLZip;
2020
2021
/************************************************************************/
2022
/*                            CPLCreateZip()                            */
2023
/************************************************************************/
2024
2025
/** Create ZIP file */
2026
void *CPLCreateZip(const char *pszZipFilename, char **papszOptions)
2027
2028
0
{
2029
0
    const bool bAppend =
2030
0
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "APPEND", "FALSE"));
2031
0
    char **papszFilenames = nullptr;
2032
2033
0
    if (bAppend)
2034
0
    {
2035
0
        zipFile unzF = cpl_unzOpen(pszZipFilename);
2036
0
        if (unzF != nullptr)
2037
0
        {
2038
0
            if (cpl_unzGoToFirstFile(unzF) == UNZ_OK)
2039
0
            {
2040
0
                do
2041
0
                {
2042
0
                    char fileName[8193];
2043
0
                    unz_file_info file_info;
2044
0
                    cpl_unzGetCurrentFileInfo(unzF, &file_info, fileName,
2045
0
                                              sizeof(fileName) - 1, nullptr, 0,
2046
0
                                              nullptr, 0);
2047
0
                    fileName[sizeof(fileName) - 1] = '\0';
2048
0
                    papszFilenames = CSLAddString(papszFilenames, fileName);
2049
0
                } while (cpl_unzGoToNextFile(unzF) == UNZ_OK);
2050
0
            }
2051
0
            cpl_unzClose(unzF);
2052
0
        }
2053
0
    }
2054
2055
0
    zipFile hZip = cpl_zipOpen(pszZipFilename, bAppend ? APPEND_STATUS_ADDINZIP
2056
0
                                                       : APPEND_STATUS_CREATE);
2057
0
    if (hZip == nullptr)
2058
0
    {
2059
0
        CSLDestroy(papszFilenames);
2060
0
        return nullptr;
2061
0
    }
2062
2063
0
    CPLZip *psZip = static_cast<CPLZip *>(CPLMalloc(sizeof(CPLZip)));
2064
0
    psZip->hZip = hZip;
2065
0
    psZip->papszFilenames = papszFilenames;
2066
0
    return psZip;
2067
0
}
2068
2069
/************************************************************************/
2070
/*                         CPLCreateFileInZip()                         */
2071
/************************************************************************/
2072
2073
/** Create a file in a ZIP file */
2074
CPLErr CPLCreateFileInZip(void *hZip, const char *pszFilename,
2075
                          char **papszOptions)
2076
2077
0
{
2078
0
    if (hZip == nullptr)
2079
0
        return CE_Failure;
2080
2081
0
    CPLZip *psZip = static_cast<CPLZip *>(hZip);
2082
2083
0
    if (CSLFindString(psZip->papszFilenames, pszFilename) >= 0)
2084
0
    {
2085
0
        CPLError(CE_Failure, CPLE_AppDefined, "%s already exists in ZIP file",
2086
0
                 pszFilename);
2087
0
        return CE_Failure;
2088
0
    }
2089
2090
0
    const bool bCompressed =
2091
0
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "COMPRESSED", "TRUE"));
2092
2093
0
    char *pszCPFilename = nullptr;
2094
0
    std::vector<GByte> abyExtra;
2095
    // If the filename is not ASCII only, we need an extended field
2096
0
    if (!CPLIsASCII(pszFilename, strlen(pszFilename)))
2097
0
    {
2098
0
        const char *pszDestEncoding = CPLGetConfigOption("CPL_ZIP_ENCODING",
2099
#if defined(_WIN32) && !defined(HAVE_ICONV)
2100
                                                         "CP_OEMCP"
2101
#else
2102
0
                                                         "CP437"
2103
0
#endif
2104
0
        );
2105
2106
0
        {
2107
0
            CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2108
0
            pszCPFilename =
2109
0
                CPLRecode(pszFilename, CPL_ENC_UTF8, pszDestEncoding);
2110
2111
0
            char *pszBackToUTF8 =
2112
0
                CPLRecode(pszCPFilename, pszDestEncoding, CPL_ENC_UTF8);
2113
0
            if (strcmp(pszBackToUTF8, pszFilename) != 0)
2114
0
            {
2115
                // If the UTF-8 name cannot be properly encoded to CPL_ZIP_ENCODING,
2116
                // then generate an ASCII name for it where non-ASCII characters
2117
                // are replaced by an hexadecimal representation
2118
0
                std::string s;
2119
0
                for (int i = 0; pszFilename[i]; ++i)
2120
0
                {
2121
0
                    if (static_cast<unsigned char>(pszFilename[i]) <= 127)
2122
0
                    {
2123
0
                        s += pszFilename[i];
2124
0
                    }
2125
0
                    else
2126
0
                    {
2127
0
                        s += CPLSPrintf("0x%02X", static_cast<unsigned char>(
2128
0
                                                      pszFilename[i]));
2129
0
                    }
2130
0
                }
2131
0
                CPLFree(pszCPFilename);
2132
0
                pszCPFilename = CPLStrdup(s.c_str());
2133
0
            }
2134
0
            CPLFree(pszBackToUTF8);
2135
0
        }
2136
2137
        /* Create a Info-ZIP Unicode Path Extra Field (0x7075) */
2138
0
        const size_t nDataLength =
2139
0
            sizeof(GByte) + sizeof(uint32_t) + strlen(pszFilename);
2140
0
        if (abyExtra.size() + 2 * sizeof(uint16_t) + nDataLength >
2141
0
            std::numeric_limits<uint16_t>::max())
2142
0
        {
2143
0
            CPLError(CE_Warning, CPLE_AppDefined,
2144
0
                     "Too much content to fit in ZIP ExtraField");
2145
0
        }
2146
0
        else
2147
0
        {
2148
0
            const uint16_t nHeaderIdLE = CPL_LSBWORD16(0x7075);
2149
0
            abyExtra.insert(abyExtra.end(),
2150
0
                            reinterpret_cast<const GByte *>(&nHeaderIdLE),
2151
0
                            reinterpret_cast<const GByte *>(&nHeaderIdLE) + 2);
2152
0
            const uint16_t nDataLengthLE =
2153
0
                CPL_LSBWORD16(static_cast<uint16_t>(nDataLength));
2154
0
            abyExtra.insert(
2155
0
                abyExtra.end(), reinterpret_cast<const GByte *>(&nDataLengthLE),
2156
0
                reinterpret_cast<const GByte *>(&nDataLengthLE) + 2);
2157
0
            const GByte nVersion = 1;
2158
0
            abyExtra.push_back(nVersion);
2159
0
            const uint32_t nNameCRC32 = static_cast<uint32_t>(
2160
0
                crc32(0, reinterpret_cast<const Bytef *>(pszCPFilename),
2161
0
                      static_cast<uInt>(strlen(pszCPFilename))));
2162
0
            const uint32_t nNameCRC32LE = CPL_LSBWORD32(nNameCRC32);
2163
0
            abyExtra.insert(abyExtra.end(),
2164
0
                            reinterpret_cast<const GByte *>(&nNameCRC32LE),
2165
0
                            reinterpret_cast<const GByte *>(&nNameCRC32LE) + 4);
2166
0
            abyExtra.insert(abyExtra.end(),
2167
0
                            reinterpret_cast<const GByte *>(pszFilename),
2168
0
                            reinterpret_cast<const GByte *>(pszFilename) +
2169
0
                                strlen(pszFilename));
2170
0
        }
2171
0
    }
2172
0
    else
2173
0
    {
2174
0
        pszCPFilename = CPLStrdup(pszFilename);
2175
0
    }
2176
2177
0
    const char *pszContentType =
2178
0
        CSLFetchNameValue(papszOptions, "CONTENT_TYPE");
2179
0
    if (pszContentType)
2180
0
    {
2181
0
        const size_t nDataLength = strlen("KeyValuePairs") + sizeof(GByte) +
2182
0
                                   sizeof(uint16_t) + strlen("Content-Type") +
2183
0
                                   sizeof(uint16_t) + strlen(pszContentType);
2184
0
        if (abyExtra.size() + 2 * sizeof(uint16_t) + nDataLength >
2185
0
            std::numeric_limits<uint16_t>::max())
2186
0
        {
2187
0
            CPLError(CE_Warning, CPLE_AppDefined,
2188
0
                     "Too much content to fit in ZIP ExtraField");
2189
0
        }
2190
0
        else
2191
0
        {
2192
0
            abyExtra.push_back(GByte('K'));
2193
0
            abyExtra.push_back(GByte('V'));
2194
0
            const uint16_t nDataLengthLE =
2195
0
                CPL_AS_LSB(static_cast<uint16_t>(nDataLength));
2196
0
            abyExtra.insert(
2197
0
                abyExtra.end(), reinterpret_cast<const GByte *>(&nDataLengthLE),
2198
0
                reinterpret_cast<const GByte *>(&nDataLengthLE) + 2);
2199
0
            abyExtra.insert(abyExtra.end(),
2200
0
                            reinterpret_cast<const GByte *>("KeyValuePairs"),
2201
0
                            reinterpret_cast<const GByte *>("KeyValuePairs") +
2202
0
                                strlen("KeyValuePairs"));
2203
0
            abyExtra.push_back(1);  // number of key/value pairs
2204
0
            const uint16_t nKeyLenLSB =
2205
0
                CPL_AS_LSB(static_cast<uint16_t>(strlen("Content-Type")));
2206
0
            abyExtra.insert(abyExtra.end(),
2207
0
                            reinterpret_cast<const GByte *>(&nKeyLenLSB),
2208
0
                            reinterpret_cast<const GByte *>(&nKeyLenLSB) + 2);
2209
0
            abyExtra.insert(abyExtra.end(),
2210
0
                            reinterpret_cast<const GByte *>("Content-Type"),
2211
0
                            reinterpret_cast<const GByte *>("Content-Type") +
2212
0
                                strlen("Content-Type"));
2213
0
            const uint16_t nValLenLSB =
2214
0
                CPL_AS_LSB(static_cast<uint16_t>(strlen(pszContentType)));
2215
0
            abyExtra.insert(abyExtra.end(),
2216
0
                            reinterpret_cast<const GByte *>(&nValLenLSB),
2217
0
                            reinterpret_cast<const GByte *>(&nValLenLSB) + 2);
2218
0
            abyExtra.insert(abyExtra.end(),
2219
0
                            reinterpret_cast<const GByte *>(pszContentType),
2220
0
                            reinterpret_cast<const GByte *>(
2221
0
                                pszContentType + strlen(pszContentType)));
2222
0
        }
2223
0
    }
2224
2225
0
    const bool bIncludeInCentralDirectory = CPLTestBool(CSLFetchNameValueDef(
2226
0
        papszOptions, "INCLUDE_IN_CENTRAL_DIRECTORY", "YES"));
2227
0
    const bool bZip64 = CPLTestBool(CSLFetchNameValueDef(
2228
0
        papszOptions, "ZIP64", CPLGetConfigOption("CPL_CREATE_ZIP64", "ON")));
2229
2230
    // Set datetime to write
2231
0
    zip_fileinfo fileinfo;
2232
0
    memset(&fileinfo, 0, sizeof(fileinfo));
2233
0
    const char *pszTimeStamp =
2234
0
        CSLFetchNameValueDef(papszOptions, "TIMESTAMP", "NOW");
2235
0
    GIntBig unixTime =
2236
0
        EQUAL(pszTimeStamp, "NOW")
2237
0
            ? time(nullptr)
2238
0
            : static_cast<GIntBig>(std::strtoll(pszTimeStamp, nullptr, 10));
2239
0
    struct tm brokenDown;
2240
0
    CPLUnixTimeToYMDHMS(unixTime, &brokenDown);
2241
0
    fileinfo.tmz_date.tm_year = brokenDown.tm_year;
2242
0
    fileinfo.tmz_date.tm_mon = brokenDown.tm_mon;
2243
0
    fileinfo.tmz_date.tm_mday = brokenDown.tm_mday;
2244
0
    fileinfo.tmz_date.tm_hour = brokenDown.tm_hour;
2245
0
    fileinfo.tmz_date.tm_min = brokenDown.tm_min;
2246
0
    fileinfo.tmz_date.tm_sec = brokenDown.tm_sec;
2247
2248
0
    const int nErr = cpl_zipOpenNewFileInZip3(
2249
0
        psZip->hZip, pszCPFilename, &fileinfo,
2250
0
        abyExtra.empty() ? nullptr : abyExtra.data(),
2251
0
        static_cast<uInt>(abyExtra.size()),
2252
0
        abyExtra.empty() ? nullptr : abyExtra.data(),
2253
0
        static_cast<uInt>(abyExtra.size()), "", bCompressed ? Z_DEFLATED : 0,
2254
0
        bCompressed ? Z_DEFAULT_COMPRESSION : 0,
2255
0
        /* raw = */ 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
2256
0
        /* password = */ nullptr,
2257
0
        /* crcForCtypting = */ 0, bZip64, bIncludeInCentralDirectory);
2258
2259
0
    CPLFree(pszCPFilename);
2260
2261
0
    if (nErr != ZIP_OK)
2262
0
        return CE_Failure;
2263
2264
0
    if (bIncludeInCentralDirectory)
2265
0
        psZip->papszFilenames =
2266
0
            CSLAddString(psZip->papszFilenames, pszFilename);
2267
2268
0
    return CE_None;
2269
0
}
2270
2271
/************************************************************************/
2272
/*                         CPLWriteFileInZip()                          */
2273
/************************************************************************/
2274
2275
/** Write in current file inside a ZIP file */
2276
CPLErr CPLWriteFileInZip(void *hZip, const void *pBuffer, int nBufferSize)
2277
2278
0
{
2279
0
    if (hZip == nullptr)
2280
0
        return CE_Failure;
2281
2282
0
    CPLZip *psZip = static_cast<CPLZip *>(hZip);
2283
2284
0
    int nErr = cpl_zipWriteInFileInZip(psZip->hZip, pBuffer,
2285
0
                                       static_cast<unsigned int>(nBufferSize));
2286
2287
0
    if (nErr != ZIP_OK)
2288
0
        return CE_Failure;
2289
2290
0
    return CE_None;
2291
0
}
2292
2293
/************************************************************************/
2294
/*                         CPLCloseFileInZip()                          */
2295
/************************************************************************/
2296
2297
/** Close current file inside ZIP file */
2298
CPLErr CPLCloseFileInZip(void *hZip)
2299
2300
0
{
2301
0
    if (hZip == nullptr)
2302
0
        return CE_Failure;
2303
2304
0
    CPLZip *psZip = static_cast<CPLZip *>(hZip);
2305
2306
0
    int nErr = cpl_zipCloseFileInZip(psZip->hZip);
2307
2308
0
    if (nErr != ZIP_OK)
2309
0
        return CE_Failure;
2310
2311
0
    return CE_None;
2312
0
}
2313
2314
/************************************************************************/
2315
/*                          CPLAddFileInZip()                           */
2316
/************************************************************************/
2317
2318
/** Add a file inside a ZIP file opened/created with CPLCreateZip().
2319
 *
2320
 * This combines calls to CPLCreateFileInZip(), CPLWriteFileInZip(),
2321
 * and CPLCloseFileInZip() in a more convenient and powerful way.
2322
 *
2323
 * In particular, this enables to add a compressed file using the seek
2324
 * optimization extension.
2325
 *
2326
 * Supported options are:
2327
 * <ul>
2328
 * <li>SOZIP_ENABLED=AUTO/YES/NO: whether to generate a SOZip index for the
2329
 * file. The default can be changed with the CPL_SOZIP_ENABLED configuration
2330
 * option.</li>
2331
 * <li>SOZIP_CHUNK_SIZE: chunk size to use for SOZip generation. Defaults to
2332
 * 32768.
2333
 * </li>
2334
 * <li>SOZIP_MIN_FILE_SIZE: minimum file size to consider to enable SOZip index
2335
 * generation in SOZIP_ENABLED=AUTO mode. Defaults to 1 MB.
2336
 * </li>
2337
 * <li>NUM_THREADS: number of threads used for SOZip generation. Defaults to
2338
 * ALL_CPUS.</li>
2339
 * <li>TIMESTAMP=AUTO/NOW/timestamp_as_epoch_since_jan_1_1970: in AUTO mode,
2340
 * the timestamp of pszInputFilename will be used (if available), otherwise
2341
 * it will fallback to NOW.</li>
2342
 * <li>CONTENT_TYPE=string: Content-Type value for the file. This is stored as
2343
 * a key-value pair in the extra field extension 'KV' (0x564b) dedicated to
2344
 * storing key-value pair metadata.</li>
2345
 * </ul>
2346
 *
2347
 * @param hZip ZIP file handle
2348
 * @param pszArchiveFilename Filename (in UTF-8) stored in the archive.
2349
 * @param pszInputFilename Filename of the file to add. If NULL, fpInput must
2350
 * not be NULL
2351
 * @param fpInput File handle opened on the file to add. May be NULL if
2352
 * pszInputFilename is provided.
2353
 * @param papszOptions Options.
2354
 * @param pProgressFunc Progress callback, or NULL.
2355
 * @param pProgressData User data of progress callback, or NULL.
2356
 * @return CE_None in case of success.
2357
 *
2358
 * @since GDAL 3.7
2359
 */
2360
CPLErr CPLAddFileInZip(void *hZip, const char *pszArchiveFilename,
2361
                       const char *pszInputFilename, VSILFILE *fpInput,
2362
                       CSLConstList papszOptions,
2363
                       GDALProgressFunc pProgressFunc, void *pProgressData)
2364
0
{
2365
0
    if (!hZip || !pszArchiveFilename || (!pszInputFilename && !fpInput))
2366
0
        return CE_Failure;
2367
2368
0
    CPLZip *psZip = static_cast<CPLZip *>(hZip);
2369
0
    zip64_internal *zi = reinterpret_cast<zip64_internal *>(psZip->hZip);
2370
2371
0
    VSIVirtualHandleUniquePtr poFileHandleAutoClose;
2372
0
    if (!fpInput)
2373
0
    {
2374
0
        fpInput = VSIFOpenL(pszInputFilename, "rb");
2375
0
        if (!fpInput)
2376
0
            return CE_Failure;
2377
0
        poFileHandleAutoClose.reset(fpInput);
2378
0
    }
2379
2380
0
    VSIFSeekL(fpInput, 0, SEEK_END);
2381
0
    const uint64_t nUncompressedSize = VSIFTellL(fpInput);
2382
0
    VSIFSeekL(fpInput, 0, SEEK_SET);
2383
2384
0
    CPLStringList aosNewsOptions(papszOptions);
2385
0
    bool bSeekOptimized = false;
2386
0
    const char *pszSOZIP =
2387
0
        CSLFetchNameValueDef(papszOptions, "SOZIP_ENABLED",
2388
0
                             CPLGetConfigOption("CPL_SOZIP_ENABLED", "AUTO"));
2389
2390
0
    const char *pszChunkSize = CSLFetchNameValueDef(
2391
0
        papszOptions, "SOZIP_CHUNK_SIZE",
2392
0
        CPLGetConfigOption("CPL_VSIL_DEFLATE_CHUNK_SIZE", nullptr));
2393
0
    const bool bChunkSizeSpecified = pszChunkSize != nullptr;
2394
0
    if (!pszChunkSize)
2395
0
        pszChunkSize = "1024K";
2396
0
    unsigned nChunkSize = static_cast<unsigned>(atoi(pszChunkSize));
2397
0
    if (strchr(pszChunkSize, 'K'))
2398
0
        nChunkSize *= 1024;
2399
0
    else if (strchr(pszChunkSize, 'M'))
2400
0
        nChunkSize *= 1024 * 1024;
2401
0
    nChunkSize =
2402
0
        std::max(static_cast<unsigned>(1),
2403
0
                 std::min(static_cast<unsigned>(UINT_MAX), nChunkSize));
2404
2405
0
    const char *pszMinFileSize = CSLFetchNameValueDef(
2406
0
        papszOptions, "SOZIP_MIN_FILE_SIZE",
2407
0
        CPLGetConfigOption("CPL_SOZIP_MIN_FILE_SIZE", "1M"));
2408
0
    uint64_t nSOZipMinFileSize = std::strtoull(pszMinFileSize, nullptr, 10);
2409
0
    if (strchr(pszMinFileSize, 'K'))
2410
0
        nSOZipMinFileSize *= 1024;
2411
0
    else if (strchr(pszMinFileSize, 'M'))
2412
0
        nSOZipMinFileSize *= 1024 * 1024;
2413
0
    else if (strchr(pszMinFileSize, 'G'))
2414
0
        nSOZipMinFileSize *= 1024 * 1024 * 1024;
2415
2416
0
    std::vector<uint8_t> sozip_index;
2417
0
    uint64_t nExpectedIndexSize = 0;
2418
0
    constexpr unsigned nDefaultSOZipChunkSize = 32 * 1024;
2419
0
    constexpr size_t nOffsetSize = 8;
2420
0
    if (((EQUAL(pszSOZIP, "AUTO") && nUncompressedSize > nSOZipMinFileSize) ||
2421
0
         (!EQUAL(pszSOZIP, "AUTO") && CPLTestBool(pszSOZIP))) &&
2422
0
        ((bChunkSizeSpecified &&
2423
0
          nUncompressedSize > static_cast<unsigned>(nChunkSize)) ||
2424
0
         (!bChunkSizeSpecified && nUncompressedSize > nDefaultSOZipChunkSize)))
2425
0
    {
2426
0
        if (!bChunkSizeSpecified)
2427
0
            nChunkSize = nDefaultSOZipChunkSize;
2428
2429
0
        bSeekOptimized = true;
2430
2431
0
        aosNewsOptions.SetNameValue("UNCOMPRESSED_SIZE",
2432
0
                                    CPLSPrintf("%" PRIu64, nUncompressedSize));
2433
2434
0
        zi->nOffsetSize = nOffsetSize;
2435
0
        nExpectedIndexSize =
2436
0
            32 + ((nUncompressedSize - 1) / nChunkSize) * nOffsetSize;
2437
0
        if (nExpectedIndexSize >
2438
0
            static_cast<uint64_t>(std::numeric_limits<int>::max()))
2439
0
        {
2440
0
            CPLError(CE_Failure, CPLE_AppDefined,
2441
0
                     "Too big file w.r.t CHUNK_SIZE");
2442
0
            return CE_Failure;
2443
0
        }
2444
0
        try
2445
0
        {
2446
0
            sozip_index.reserve(static_cast<size_t>(nExpectedIndexSize));
2447
0
        }
2448
0
        catch (const std::exception &)
2449
0
        {
2450
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
2451
0
                     "Cannot allocate memory for SOZip index");
2452
0
            return CE_Failure;
2453
0
        }
2454
0
        sozip_index.resize(32);
2455
0
        uint32_t nVal32;
2456
        // Version
2457
0
        nVal32 = CPL_AS_LSB<uint32_t>(1);
2458
0
        memcpy(sozip_index.data(), &nVal32, sizeof(nVal32));
2459
        // Extra reserved space after 32 bytes of header
2460
0
        nVal32 = CPL_AS_LSB<uint32_t>(0);
2461
0
        memcpy(sozip_index.data() + 4, &nVal32, sizeof(nVal32));
2462
        // Chunksize
2463
0
        nVal32 = CPL_AS_LSB<uint32_t>(nChunkSize);
2464
0
        memcpy(sozip_index.data() + 8, &nVal32, sizeof(nVal32));
2465
        // SOZIPIndexEltSize
2466
0
        nVal32 = CPL_AS_LSB(static_cast<uint32_t>(nOffsetSize));
2467
0
        memcpy(sozip_index.data() + 12, &nVal32, sizeof(nVal32));
2468
        // Uncompressed size
2469
0
        uint64_t nVal64 = CPL_AS_LSB(nUncompressedSize);
2470
0
        memcpy(sozip_index.data() + 16, &nVal64, sizeof(nVal64));
2471
0
        zi->sozip_index = &sozip_index;
2472
2473
0
        zi->nChunkSize = nChunkSize;
2474
2475
0
        const char *pszThreads = CSLFetchNameValue(papszOptions, "NUM_THREADS");
2476
0
        if (pszThreads == nullptr || EQUAL(pszThreads, "ALL_CPUS"))
2477
0
            zi->nThreads = CPLGetNumCPUs();
2478
0
        else
2479
0
            zi->nThreads = atoi(pszThreads);
2480
0
        zi->nThreads = std::max(1, std::min(128, zi->nThreads));
2481
0
    }
2482
2483
0
    aosNewsOptions.SetNameValue("ZIP64",
2484
0
                                nUncompressedSize > 0xFFFFFFFFU ? "YES" : "NO");
2485
2486
0
    if (pszInputFilename != nullptr &&
2487
0
        aosNewsOptions.FetchNameValue("TIMESTAMP") == nullptr)
2488
0
    {
2489
0
        VSIStatBufL sStat;
2490
0
        if (VSIStatL(pszInputFilename, &sStat) == 0 && sStat.st_mtime != 0)
2491
0
        {
2492
0
            aosNewsOptions.SetNameValue(
2493
0
                "TIMESTAMP",
2494
0
                CPLSPrintf(CPL_FRMT_GIB, static_cast<GIntBig>(sStat.st_mtime)));
2495
0
        }
2496
0
    }
2497
2498
0
    if (CPLCreateFileInZip(hZip, pszArchiveFilename, aosNewsOptions.List()) !=
2499
0
        CE_None)
2500
0
    {
2501
0
        zi->sozip_index = nullptr;
2502
0
        zi->nChunkSize = 0;
2503
0
        zi->nThreads = 0;
2504
0
        return CE_Failure;
2505
0
    }
2506
0
    zi->nChunkSize = 0;
2507
0
    zi->nThreads = 0;
2508
2509
0
    constexpr int CHUNK_READ_MAX_SIZE = 1024 * 1024;
2510
0
    std::vector<GByte> abyChunk(CHUNK_READ_MAX_SIZE);
2511
0
    vsi_l_offset nOffset = 0;
2512
0
    while (true)
2513
0
    {
2514
0
        const int nRead = static_cast<int>(
2515
0
            VSIFReadL(abyChunk.data(), 1, abyChunk.size(), fpInput));
2516
0
        if (nRead > 0 &&
2517
0
            CPLWriteFileInZip(hZip, abyChunk.data(), nRead) != CE_None)
2518
0
        {
2519
0
            CPLCloseFileInZip(hZip);
2520
0
            zi->sozip_index = nullptr;
2521
0
            return CE_Failure;
2522
0
        }
2523
0
        nOffset += nRead;
2524
0
        if (pProgressFunc &&
2525
0
            !pProgressFunc(nUncompressedSize == 0
2526
0
                               ? 1.0
2527
0
                               : double(nOffset) / nUncompressedSize,
2528
0
                           nullptr, pProgressData))
2529
0
        {
2530
0
            CPLCloseFileInZip(hZip);
2531
0
            zi->sozip_index = nullptr;
2532
0
            return CE_Failure;
2533
0
        }
2534
0
        if (nRead < CHUNK_READ_MAX_SIZE)
2535
0
            break;
2536
0
    }
2537
2538
0
    if (CPLCloseFileInZip(hZip) != CE_None)
2539
0
    {
2540
0
        zi->sozip_index = nullptr;
2541
0
        return CE_Failure;
2542
0
    }
2543
2544
0
    if (bSeekOptimized && sozip_index.size() != nExpectedIndexSize)
2545
0
    {
2546
        // shouldn't happen
2547
0
        CPLError(CE_Failure, CPLE_AppDefined,
2548
0
                 "sozip_index.size() (=%u) != nExpectedIndexSize (=%u)",
2549
0
                 static_cast<unsigned>(sozip_index.size()),
2550
0
                 static_cast<unsigned>(nExpectedIndexSize));
2551
0
    }
2552
0
    else if (bSeekOptimized)
2553
0
    {
2554
0
        std::string osIdxName;
2555
0
        const char *pszLastSlash = strchr(pszArchiveFilename, '/');
2556
0
        if (pszLastSlash)
2557
0
        {
2558
0
            osIdxName.assign(pszArchiveFilename,
2559
0
                             pszLastSlash - pszArchiveFilename + 1);
2560
0
            osIdxName += '.';
2561
0
            osIdxName += pszLastSlash + 1;
2562
0
        }
2563
0
        else
2564
0
        {
2565
0
            osIdxName = '.';
2566
0
            osIdxName += pszArchiveFilename;
2567
0
        }
2568
0
        osIdxName += ".sozip.idx";
2569
2570
0
        CPLStringList aosIndexOptions;
2571
0
        aosIndexOptions.SetNameValue("COMPRESSED", "NO");
2572
0
        aosIndexOptions.SetNameValue("ZIP64", "NO");
2573
0
        aosIndexOptions.SetNameValue("INCLUDE_IN_CENTRAL_DIRECTORY", "NO");
2574
0
        aosIndexOptions.SetNameValue(
2575
0
            "TIMESTAMP", aosNewsOptions.FetchNameValue("TIMESTAMP"));
2576
0
        if (CPLCreateFileInZip(hZip, osIdxName.c_str(),
2577
0
                               aosIndexOptions.List()) != CE_None)
2578
0
        {
2579
0
            zi->sozip_index = nullptr;
2580
0
            return CE_Failure;
2581
0
        }
2582
2583
0
        if (CPLWriteFileInZip(hZip, sozip_index.data(),
2584
0
                              static_cast<int>(sozip_index.size())) != CE_None)
2585
0
        {
2586
0
            zi->sozip_index = nullptr;
2587
0
            CPLCloseFileInZip(hZip);
2588
0
            return CE_Failure;
2589
0
        }
2590
2591
0
        zi->sozip_index = nullptr;
2592
0
        if (CPLCloseFileInZip(hZip) != CE_None)
2593
0
        {
2594
0
            return CE_Failure;
2595
0
        }
2596
0
    }
2597
2598
0
    zi->sozip_index = nullptr;
2599
2600
0
    return CE_None;
2601
0
}
2602
2603
/************************************************************************/
2604
/*                            CPLCloseZip()                             */
2605
/************************************************************************/
2606
2607
/** Close ZIP file */
2608
CPLErr CPLCloseZip(void *hZip)
2609
0
{
2610
0
    if (hZip == nullptr)
2611
0
        return CE_Failure;
2612
2613
0
    CPLZip *psZip = static_cast<CPLZip *>(hZip);
2614
2615
0
    int nErr = cpl_zipClose(psZip->hZip, nullptr);
2616
2617
0
    psZip->hZip = nullptr;
2618
0
    CSLDestroy(psZip->papszFilenames);
2619
0
    psZip->papszFilenames = nullptr;
2620
0
    CPLFree(psZip);
2621
2622
0
    if (nErr != ZIP_OK)
2623
0
        return CE_Failure;
2624
2625
0
    return CE_None;
2626
0
}