File: archive_writer.cpp

package info (click to toggle)
sight 25.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 43,252 kB
  • sloc: cpp: 310,629; xml: 17,622; ansic: 9,960; python: 1,379; sh: 144; makefile: 33
file content (633 lines) | stat: -rw-r--r-- 20,262 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/************************************************************************
 *
 * Copyright (C) 2021-2025 IRCAD France
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "archive_writer.hpp"

#include "exception/write.hpp"

#include "minizip/mz.h"
#include "minizip/mz_os.h"
#include "minizip/mz_strm.h"
#include "minizip/mz_strm_os.h"
#include "minizip/mz_zip.h"
#include "minizip/mz_zip_rw.h"

#include <core/exceptionmacros.hpp>

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4702)
#endif

#include <boost/iostreams/stream.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <cstdlib>
#include <cstring>
#include <fstream>
#include <tuple>

/**
 * Do not mark `madeby` as incorrect.
 * cspell:ignore madeby
 */
namespace sight::io::zip
{

namespace
{

// Force deflate if env variable is set
const bool LEGACY_COMPRESSION =
    []
    {
        const char* const env_legacy_compression = std::getenv("SIGHT_LEGACY_COMPRESSION");

        return env_legacy_compression != nullptr && std::strncmp(env_legacy_compression, "1", 1) == 0;
    }();

/// Convert argument to minizip dialect
inline std::tuple<std::uint16_t, std::int16_t> to_minizip_parameter(method _method, level _level)
{
    std::uint16_t minizip_method = MZ_COMPRESS_METHOD_ZSTD;
    std::int16_t minizip_level   = MZ_COMPRESS_LEVEL_DEFAULT;

    switch(_method)
    {
        case method::store:
            minizip_method = MZ_COMPRESS_METHOD_STORE;
            minizip_level  = MZ_COMPRESS_LEVEL_DEFAULT;

            break;

        case method::deflate:
            minizip_method = MZ_COMPRESS_METHOD_DEFLATE;

            switch(_level)
            {
                case level::best:
                case level::ultra:
                    minizip_level = MZ_COMPRESS_LEVEL_BEST;
                    break;

                case level::fast:
                    minizip_level = MZ_COMPRESS_LEVEL_FAST;
                    break;

                default:
                    minizip_level = MZ_COMPRESS_LEVEL_DEFAULT;
                    break;
            }

            break;

        case method::zstd:
            minizip_method = MZ_COMPRESS_METHOD_ZSTD;

            switch(_level)
            {
                case level::ultra:
                    minizip_level = 22;
                    break;

                case level::best:
                    minizip_level = 19;
                    break;

                case level::fast:
                    minizip_level = 1;
                    break;

                default:
                    minizip_level = 5;
                    break;
            }

            break;

        default:
            return to_minizip_parameter(method::zstd, _level);
    }

    if(LEGACY_COMPRESSION && minizip_method != MZ_COMPRESS_METHOD_DEFLATE)
    {
        return to_minizip_parameter(method::deflate, _level);
    }

    return {minizip_method, minizip_level};
}

class raw_archive_writer final : public archive_writer
{
public:

    SIGHT_DECLARE_CLASS(raw_archive_writer, archive_writer);

    /// Delete default constructors and assignment operators, as we don't want to allow resources duplication
    raw_archive_writer()                                     = delete;
    raw_archive_writer(const raw_archive_writer&)            = delete;
    raw_archive_writer(raw_archive_writer&&)                 = delete;
    raw_archive_writer& operator=(const raw_archive_writer&) = delete;
    raw_archive_writer& operator=(raw_archive_writer&&)      = delete;

    explicit raw_archive_writer(const std::filesystem::path& _root) :
        archive_writer(_root),
        m_root(_root)
    {
        // Create the sub directories if needed
        std::filesystem::create_directories(_root);
    }

    ~raw_archive_writer() final = default;

    //------------------------------------------------------------------------------

    std::unique_ptr<std::ostream> open_file(
        const std::filesystem::path& _file_path,
        [[maybe_unused]] const core::crypto::secure_string& _password = "",
        [[maybe_unused]] method _method                               = method::DEFAULT,
        [[maybe_unused]] level _level                                 = level::DEFAULT
    ) final
    {
        // Create the sub directories if needed
        const std::filesystem::path& full_path = m_root / _file_path.relative_path();

        if(full_path.has_parent_path())
        {
            std::filesystem::create_directories(full_path.parent_path());
        }

        return std::make_unique<std::ofstream>(full_path, std::ios::out | std::ios::binary | std::ios::trunc);
    }

    //------------------------------------------------------------------------------

    void write_file(
        const std::filesystem::path& _file_path,
        const std::string& _content,
        [[maybe_unused]] const core::crypto::secure_string& _password = "",
        [[maybe_unused]] method _method                               = method::DEFAULT,
        [[maybe_unused]] level _level                                 = level::DEFAULT
    ) final
    {
        // Create the sub directories if needed
        const std::filesystem::path& full_path = m_root / _file_path.relative_path();

        if(full_path.has_parent_path())
        {
            std::filesystem::create_directories(full_path.parent_path());
        }

        std::ofstream file(full_path, std::ios::out | std::ios::binary | std::ios::trunc);
        file.write(_content.data(), std::streamsize(_content.size()));
    }

    //------------------------------------------------------------------------------

    [[nodiscard]] bool is_raw() const final
    {
        return true;
    }

private:

    /// Path of the root directory
    const std::filesystem::path m_root;
};

class zip_handle final
{
public:

    /// Delete default constructors and assignment operators, as we don't want to allow resources duplication
    zip_handle()                             = delete;
    zip_handle(const zip_handle&)            = delete;
    zip_handle(zip_handle&&)                 = delete;
    zip_handle& operator=(const zip_handle&) = delete;
    zip_handle& operator=(zip_handle&&)      = delete;

    zip_handle(const std::filesystem::path& _archive_path, const archive::archive_format _format) :
        m_archive_path(_archive_path.string()),
        m_format(_format),
        m_zip_writer(mz_zip_writer_create())
    {
        // Create the sub directories if needed
        if(_archive_path.has_parent_path())
        {
            std::filesystem::create_directories(_archive_path.parent_path());
        }

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot create zip writer instance",
                MZ_MEM_ERROR
            ),
            m_zip_writer == nullptr
        );

        const method default_method = m_format == archive::archive_format::compatible
                                      ? method::deflate
                                      : m_format == archive::archive_format::optimized
                                      ? method::zstd
                                      : method::DEFAULT;

        // Set default options
        auto [minizipMethod, minizipLevel] = to_minizip_parameter(default_method, level::DEFAULT);

        mz_zip_writer_set_compress_method(m_zip_writer, minizipMethod);
        mz_zip_writer_set_compress_level(m_zip_writer, minizipLevel);
        mz_zip_writer_set_zip_cd(
            m_zip_writer,
            LEGACY_COMPRESSION || m_format == archive::archive_format::compatible ? 0 : 1
        );

        // Open the zip file
        auto result = mz_zip_writer_open_file(m_zip_writer, m_archive_path.c_str(), 0, 0);

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot open archive '" + m_archive_path + "'. Error code: " + std::to_string(result),
                result
            ),
            result != MZ_OK
        );
    }

    ~zip_handle()
    {
        // Close zip handle
        const auto result = mz_zip_writer_close(m_zip_writer);

        // Cleanup
        mz_zip_writer_delete(&m_zip_writer);

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot close writer for archive '"
                + m_archive_path
                + "'. Error code: "
                + std::to_string(result),
                result
            ),
            result != MZ_OK
        );
    }

    // Path to the archive converted to string because on Windows std::filesystem::path.c_str() returns a wchar*
    const std::string m_archive_path;

    // Default compression method
    const archive::archive_format m_format {archive::archive_format::DEFAULT};

    // Zip writer handle
    void* m_zip_writer {nullptr};
};

class zip_file_handle final
{
public:

    /// Delete default constructors and assignment operators, as we don't want to allow resources duplication
    zip_file_handle()                                  = delete;
    zip_file_handle(const zip_file_handle&)            = delete;
    zip_file_handle(zip_file_handle&&)                 = delete;
    zip_file_handle& operator=(const zip_file_handle&) = delete;
    zip_file_handle& operator=(zip_file_handle&&)      = delete;

    zip_file_handle(
        std::shared_ptr<zip_handle> _zip_handle,
        const std::filesystem::path& _file_path,
        core::crypto::secure_string _password = "",
        const method _method                  = method::DEFAULT,
        const level _level                    = level::DEFAULT
    ) :
        m_file_name(_file_path.string()),
        m_password(std::move(_password)),
        m_zip_handle(std::move(_zip_handle))
    {
        // Translate to minizip dialect
        auto [minizipMethod, minizipLevel] = to_minizip_parameter(
            _method != method::DEFAULT
            ? _method
            : m_zip_handle->m_format == archive::archive_format::compatible
            ? method::deflate
            : m_zip_handle->m_format == archive::archive_format::optimized
            ? method::zstd
            : method::DEFAULT,
            _level
        );

        // Set compression method and level
        mz_zip_writer_set_compress_method(m_zip_handle->m_zip_writer, minizipMethod);
        mz_zip_writer_set_compress_level(m_zip_handle->m_zip_writer, minizipLevel);

        // Set encryption
        const bool use_encryption = !m_password.empty();
        mz_zip_writer_set_aes(m_zip_handle->m_zip_writer, use_encryption ? 1 : 0);
        mz_zip_writer_set_password(m_zip_handle->m_zip_writer, use_encryption ? m_password.c_str() : nullptr);

        const auto now = time(nullptr);

        mz_zip_file zip_file;
        std::memset(&zip_file, 0, sizeof(zip_file));

        zip_file.version_madeby     = MZ_VERSION_MADEBY;
        zip_file.flag               = MZ_ZIP_FLAG_UTF8;
        zip_file.compression_method = minizipMethod;
        zip_file.modified_date      = now;
        zip_file.accessed_date      = now;
        zip_file.creation_date      = now;
        zip_file.filename           = m_file_name.c_str();

        if(use_encryption)
        {
            zip_file.aes_version  = MZ_AES_VERSION;
            zip_file.aes_strength = MZ_AES_STRENGTH_256;
        }

        const auto result = mz_zip_writer_entry_open(m_zip_handle->m_zip_writer, &zip_file);

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot write file '"
                + m_file_name
                + "' in archive '"
                + m_zip_handle->m_archive_path
                + "'. Error code: "
                + std::to_string(result),
                result
            ),
            result != MZ_OK
        );
    }

    ~zip_file_handle()
    {
        const auto result = mz_zip_writer_entry_close(m_zip_handle->m_zip_writer);

        // Restore defaults
        mz_zip_writer_set_compress_method(m_zip_handle->m_zip_writer, MZ_COMPRESS_METHOD_ZSTD);
        mz_zip_writer_set_compress_level(m_zip_handle->m_zip_writer, MZ_COMPRESS_LEVEL_DEFAULT);
        mz_zip_writer_set_aes(m_zip_handle->m_zip_writer, 0);
        mz_zip_writer_set_password(m_zip_handle->m_zip_writer, nullptr);

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot close file '"
                + m_file_name
                + "' in archive '"
                + m_zip_handle->m_archive_path
                + "'. Error code: "
                + std::to_string(result),
                result
            ),
            result != MZ_OK
        );
    }

private:

    friend class zip_sink;
    friend class zip_archive_writer;

    // Path to the file converted to string because on Windows std::filesystem::path.c_str() returns a wchar*
    const std::string m_file_name;

    // The password must be kept alive since minizip doesn't copy it
    const core::crypto::secure_string m_password;

    // Zip handles pack which contains the zip writer
    const std::shared_ptr<zip_handle> m_zip_handle;
};

class zip_sink final
{
public:

    // Needed by Boost
    using char_type = char;
    using category  = boost::iostreams::sink_tag;

    // BEWARE: Boost make shallow copies of the zip_sink...
    explicit zip_sink(std::shared_ptr<zip_file_handle> _zip_file_handle) :
        m_zip_file_handle(std::move(_zip_file_handle))
    {
    }

    // Boost use this to write things
    std::streamsize write(const char* _buffer, std::streamsize _size)
    {
        std::streamsize remaining_size = _size;
        const char* remaining_buffer   = _buffer;

        std::int32_t block_size = std::int32_t(
            std::min(_size, std::streamsize(std::numeric_limits<std::int32_t>::max()))
        );

        while(remaining_size > 0)
        {
            const auto written = mz_zip_writer_entry_write(
                m_zip_file_handle->m_zip_handle->m_zip_writer,
                remaining_buffer,
                block_size
            );

            SIGHT_THROW_EXCEPTION_IF(
                exception::write(
                    "Cannot write in file '"
                    + m_zip_file_handle->m_file_name
                    + "' in archive '"
                    + m_zip_file_handle->m_zip_handle->m_archive_path
                    + "'. Error code: "
                    + std::to_string(written),
                    written
                ),
                written < 0
            );

            remaining_size   -= written;
            remaining_buffer += written;
        }

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot write in file '"
                + m_zip_file_handle->m_file_name
                + "' in archive '"
                + m_zip_file_handle->m_zip_handle->m_archive_path
                + "'. Remaining: "
                + std::to_string(remaining_size),
                MZ_WRITE_ERROR
            ),
            remaining_size > 0
        );

        return _size;
    }

private:

    const std::shared_ptr<zip_file_handle> m_zip_file_handle;
};

class zip_archive_writer final : public archive_writer
{
public:

    SIGHT_DECLARE_CLASS(zip_archive_writer, archive_writer);

    /// Delete default constructors and assignment operators, as we don't want to allow resources duplication
    zip_archive_writer()                                     = delete;
    zip_archive_writer(const zip_archive_writer&)            = delete;
    zip_archive_writer(zip_archive_writer&&)                 = delete;
    zip_archive_writer& operator=(const zip_archive_writer&) = delete;
    zip_archive_writer& operator=(zip_archive_writer&&)      = delete;

    zip_archive_writer(const std::filesystem::path& _archive_path, const archive_format _format) :
        archive_writer(_archive_path),
        m_zip_handle(std::make_shared<zip_handle>(_archive_path, _format))
    {
    }

    ~zip_archive_writer() final = default;

    //------------------------------------------------------------------------------

    std::unique_ptr<std::ostream> open_file(
        const std::filesystem::path& _file_path,
        const core::crypto::secure_string& _password = "",
        method _method                               = method::DEFAULT,
        level _level                                 = level::DEFAULT
    ) final
    {
        const auto zip_file_handle = std::make_shared<io::zip::zip_file_handle>(
            m_zip_handle,
            _file_path,
            _password,
            _method,
            _level
        );

        return std::make_unique<boost::iostreams::stream<zip_sink> >(zip_file_handle);
    }

    //------------------------------------------------------------------------------

    void write_file(
        const std::filesystem::path& _file_path,
        const std::string& _content,
        const core::crypto::secure_string& _password = "",
        method _method                               = method::DEFAULT,
        level _level                                 = level::DEFAULT
    ) final
    {
        const auto zip_file_handle = std::make_shared<io::zip::zip_file_handle>(
            m_zip_handle,
            _file_path,
            _password,
            _method,
            _level
        );

        std::size_t remaining_size   = _content.size();
        const char* remaining_buffer = _content.data();

        std::int32_t block_size = std::int32_t(
            std::min(_content.size(), std::size_t(std::numeric_limits<std::int32_t>::max()))
        );

        while(remaining_size > 0)
        {
            const auto written = mz_zip_writer_entry_write(
                zip_file_handle->m_zip_handle->m_zip_writer,
                remaining_buffer,
                block_size
            );

            SIGHT_THROW_EXCEPTION_IF(
                exception::write(
                    "Cannot write in file '"
                    + zip_file_handle->m_file_name
                    + "' in archive '"
                    + zip_file_handle->m_zip_handle->m_archive_path
                    + "'. Error code: "
                    + std::to_string(written),
                    written
                ),
                written < 0
            );

            remaining_size   -= std::size_t(written);
            remaining_buffer += written;
        }

        SIGHT_THROW_EXCEPTION_IF(
            exception::write(
                "Cannot write in file '"
                + zip_file_handle->m_file_name
                + "' in archive '"
                + zip_file_handle->m_zip_handle->m_archive_path
                + "'. Remaining: "
                + std::to_string(remaining_size),
                MZ_WRITE_ERROR
            ),
            remaining_size > 0
        );
    }

    //------------------------------------------------------------------------------

    [[nodiscard]] bool is_raw() const final
    {
        return false;
    }

private:

    std::shared_ptr<zip_handle> m_zip_handle;
};

} // namespace

archive_writer::archive_writer(const std::filesystem::path& _archive_path) :
    archive(_archive_path)
{
}

//------------------------------------------------------------------------------

archive_writer::uptr archive_writer::get(
    const std::filesystem::path& _archive_path,
    const archive_format _format
)
{
    if(_format == archive_format::filesystem)
    {
        return std::make_unique<raw_archive_writer>(_archive_path);
    }

    return std::make_unique<zip_archive_writer>(_archive_path, _format);
}

} // namespace sight::io::zip