• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 14369324968

09 Apr 2025 10:36PM UTC coverage: 71.955% (+0.04%) from 71.913%
14369324968

push

github

YHNdnzj
nspawn: replace prefix_roota() with chase()

5 of 7 new or added lines in 1 file covered. (71.43%)

1145 existing lines in 32 files now uncovered.

297058 of 412839 relevant lines covered (71.95%)

663845.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.79
/src/basic/compress.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <inttypes.h>
4
#include <malloc.h>
5
#include <stdlib.h>
6
#include <sys/mman.h>
7
#include <sys/stat.h>
8
#include <sys/types.h>
9
#include <unistd.h>
10

11
#if HAVE_LZ4
12
#include <lz4hc.h>
13
#endif
14

15
#if HAVE_XZ
16
#include <lzma.h>
17
#endif
18

19
#if HAVE_ZSTD
20
#include <zstd.h>
21
#include <zstd_errors.h>
22
#endif
23

24
#include "alloc-util.h"
25
#include "bitfield.h"
26
#include "compress.h"
27
#include "fd-util.h"
28
#include "fileio.h"
29
#include "io-util.h"
30
#include "macro.h"
31
#include "sparse-endian.h"
32
#include "string-table.h"
33
#include "string-util.h"
34
#include "unaligned.h"
35

36
#if HAVE_LZ4
37
static void *lz4_dl = NULL;
38

39
static DLSYM_PROTOTYPE(LZ4F_compressBegin) = NULL;
40
static DLSYM_PROTOTYPE(LZ4F_compressBound) = NULL;
41
static DLSYM_PROTOTYPE(LZ4F_compressEnd) = NULL;
42
static DLSYM_PROTOTYPE(LZ4F_compressUpdate) = NULL;
43
static DLSYM_PROTOTYPE(LZ4F_createCompressionContext) = NULL;
44
static DLSYM_PROTOTYPE(LZ4F_createDecompressionContext) = NULL;
45
static DLSYM_PROTOTYPE(LZ4F_decompress) = NULL;
46
static DLSYM_PROTOTYPE(LZ4F_freeCompressionContext) = NULL;
47
static DLSYM_PROTOTYPE(LZ4F_freeDecompressionContext) = NULL;
48
static DLSYM_PROTOTYPE(LZ4F_isError) = NULL;
49
DLSYM_PROTOTYPE(LZ4_compress_default) = NULL;
50
DLSYM_PROTOTYPE(LZ4_compress_HC) = NULL;
51
DLSYM_PROTOTYPE(LZ4_decompress_safe) = NULL;
52
DLSYM_PROTOTYPE(LZ4_decompress_safe_partial) = NULL;
53
DLSYM_PROTOTYPE(LZ4_versionNumber) = NULL;
54

55
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(LZ4F_compressionContext_t, sym_LZ4F_freeCompressionContext, NULL);
1✔
56
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(LZ4F_decompressionContext_t, sym_LZ4F_freeDecompressionContext, NULL);
3✔
57
#endif
58

59
#if HAVE_ZSTD
60
static void *zstd_dl = NULL;
61

62
static DLSYM_PROTOTYPE(ZSTD_CCtx_setParameter) = NULL;
63
static DLSYM_PROTOTYPE(ZSTD_compress) = NULL;
64
static DLSYM_PROTOTYPE(ZSTD_compressStream2) = NULL;
65
static DLSYM_PROTOTYPE(ZSTD_createCCtx) = NULL;
66
static DLSYM_PROTOTYPE(ZSTD_createDCtx) = NULL;
67
static DLSYM_PROTOTYPE(ZSTD_CStreamInSize) = NULL;
68
static DLSYM_PROTOTYPE(ZSTD_CStreamOutSize) = NULL;
69
static DLSYM_PROTOTYPE(ZSTD_decompressStream) = NULL;
70
static DLSYM_PROTOTYPE(ZSTD_DStreamInSize) = NULL;
71
static DLSYM_PROTOTYPE(ZSTD_DStreamOutSize) = NULL;
72
static DLSYM_PROTOTYPE(ZSTD_freeCCtx) = NULL;
73
static DLSYM_PROTOTYPE(ZSTD_freeDCtx) = NULL;
74
static DLSYM_PROTOTYPE(ZSTD_getErrorCode) = NULL;
75
static DLSYM_PROTOTYPE(ZSTD_getErrorName) = NULL;
76
static DLSYM_PROTOTYPE(ZSTD_getFrameContentSize) = NULL;
77
static DLSYM_PROTOTYPE(ZSTD_isError) = NULL;
78

79
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(ZSTD_CCtx*, sym_ZSTD_freeCCtx, NULL);
25✔
80
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(ZSTD_DCtx*, sym_ZSTD_freeDCtx, NULL);
246,461✔
81

82
static int zstd_ret_to_errno(size_t ret) {
6✔
83
        switch (sym_ZSTD_getErrorCode(ret)) {
6✔
84
        case ZSTD_error_dstSize_tooSmall:
85
                return -ENOBUFS;
86
        case ZSTD_error_memory_allocation:
×
87
                return -ENOMEM;
×
88
        default:
1✔
89
                return -EBADMSG;
1✔
90
        }
91
}
92
#endif
93

94
#if HAVE_XZ
95
static void *lzma_dl = NULL;
96

97
static DLSYM_PROTOTYPE(lzma_code) = NULL;
98
static DLSYM_PROTOTYPE(lzma_easy_encoder) = NULL;
99
static DLSYM_PROTOTYPE(lzma_end) = NULL;
100
static DLSYM_PROTOTYPE(lzma_stream_buffer_encode) = NULL;
101
static DLSYM_PROTOTYPE(lzma_stream_decoder) = NULL;
102
static DLSYM_PROTOTYPE(lzma_lzma_preset) = NULL;
103

104
/* We can't just do _cleanup_(sym_lzma_end) because a compiler bug makes
105
 * this fail with:
106
 * ../src/basic/compress.c: In function ‘decompress_blob_xz’:
107
 * ../src/basic/compress.c:304:9: error: cleanup argument not a function
108
 *   304 |         _cleanup_(sym_lzma_end) lzma_stream s = LZMA_STREAM_INIT;
109
 *       |         ^~~~~~~~~
110
 */
111
static inline void lzma_end_wrapper(lzma_stream *ls) {
2,793✔
112
        sym_lzma_end(ls);
2,793✔
113
}
114
#endif
115

116
#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t))
117

118
static const char* const compression_table[_COMPRESSION_MAX] = {
119
        [COMPRESSION_NONE] = "NONE",
120
        [COMPRESSION_XZ]   = "XZ",
121
        [COMPRESSION_LZ4]  = "LZ4",
122
        [COMPRESSION_ZSTD] = "ZSTD",
123
};
124

125
static const char* const compression_lowercase_table[_COMPRESSION_MAX] = {
126
        [COMPRESSION_NONE] = "none",
127
        [COMPRESSION_XZ]   = "xz",
128
        [COMPRESSION_LZ4]  = "lz4",
129
        [COMPRESSION_ZSTD] = "zstd",
130
};
131

132
DEFINE_STRING_TABLE_LOOKUP(compression, Compression);
536✔
133
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
93✔
134

135
bool compression_supported(Compression c) {
2,688✔
136
        static const unsigned supported =
2,688✔
137
                (1U << COMPRESSION_NONE) |
138
                (1U << COMPRESSION_XZ) * HAVE_XZ |
139
                (1U << COMPRESSION_LZ4) * HAVE_LZ4 |
140
                (1U << COMPRESSION_ZSTD) * HAVE_ZSTD;
141

142
        assert(c >= 0);
2,688✔
143
        assert(c < _COMPRESSION_MAX);
2,688✔
144

145
        return BIT_SET(supported, c);
2,688✔
146
}
147

148
#if HAVE_XZ
149
int dlopen_lzma(void) {
2,818✔
150
        ELF_NOTE_DLOPEN("lzma",
2,818✔
151
                        "Support lzma compression in journal and coredump files",
152
                        COMPRESSION_PRIORITY_XZ,
153
                        "liblzma.so.5");
154

155
        return dlopen_many_sym_or_warn(
2,818✔
156
                        &lzma_dl,
157
                        "liblzma.so.5", LOG_DEBUG,
158
                        DLSYM_ARG(lzma_code),
159
                        DLSYM_ARG(lzma_easy_encoder),
160
                        DLSYM_ARG(lzma_end),
161
                        DLSYM_ARG(lzma_stream_buffer_encode),
162
                        DLSYM_ARG(lzma_lzma_preset),
163
                        DLSYM_ARG(lzma_stream_decoder));
164
}
165
#endif
166

167
int compress_blob_xz(const void *src, uint64_t src_size,
24✔
168
                     void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
169

170
        assert(src);
24✔
171
        assert(src_size > 0);
24✔
172
        assert(dst);
24✔
173
        assert(dst_alloc_size > 0);
24✔
174
        assert(dst_size);
24✔
175

176
#if HAVE_XZ
177
        lzma_options_lzma opt = {
24✔
178
                1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT,
179
                LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4
180
        };
181
        lzma_filter filters[] = {
24✔
182
                { LZMA_FILTER_LZMA2, &opt },
183
                { LZMA_VLI_UNKNOWN, NULL }
184
        };
185
        lzma_ret ret;
24✔
186
        size_t out_pos = 0;
24✔
187
        int r;
24✔
188

189
        r = dlopen_lzma();
24✔
190
        if (r < 0)
24✔
191
                return r;
24✔
192

193
        if (level >= 0) {
24✔
194
                r = sym_lzma_lzma_preset(&opt, (uint32_t) level);
3✔
195
                if (r < 0)
196
                        return r;
197
        }
198

199
        /* Returns < 0 if we couldn't compress the data or the
200
         * compressed result is longer than the original */
201

202
        if (src_size < 80)
24✔
203
                return -ENOBUFS;
204

205
        ret = sym_lzma_stream_buffer_encode(filters, LZMA_CHECK_NONE, NULL,
24✔
206
                                        src, src_size, dst, &out_pos, dst_alloc_size);
207
        if (ret != LZMA_OK)
24✔
208
                return -ENOBUFS;
209

210
        *dst_size = out_pos;
21✔
211
        return 0;
21✔
212
#else
213
        return -EPROTONOSUPPORT;
214
#endif
215
}
216

217
#if HAVE_LZ4
218
int dlopen_lz4(void) {
3,130✔
219
        ELF_NOTE_DLOPEN("lz4",
3,130✔
220
                        "Support lz4 compression in journal and coredump files",
221
                        COMPRESSION_PRIORITY_LZ4,
222
                        "liblz4.so.1");
223

224
        return dlopen_many_sym_or_warn(
3,130✔
225
                        &lz4_dl,
226
                        "liblz4.so.1", LOG_DEBUG,
227
                        DLSYM_ARG(LZ4F_compressBegin),
228
                        DLSYM_ARG(LZ4F_compressBound),
229
                        DLSYM_ARG(LZ4F_compressEnd),
230
                        DLSYM_ARG(LZ4F_compressUpdate),
231
                        DLSYM_ARG(LZ4F_createCompressionContext),
232
                        DLSYM_ARG(LZ4F_createDecompressionContext),
233
                        DLSYM_ARG(LZ4F_decompress),
234
                        DLSYM_ARG(LZ4F_freeCompressionContext),
235
                        DLSYM_ARG(LZ4F_freeDecompressionContext),
236
                        DLSYM_ARG(LZ4F_isError),
237
                        DLSYM_ARG(LZ4_compress_default),
238
                        DLSYM_ARG(LZ4_compress_HC),
239
                        DLSYM_ARG(LZ4_decompress_safe),
240
                        DLSYM_ARG(LZ4_decompress_safe_partial),
241
                        DLSYM_ARG(LZ4_versionNumber));
242
}
243
#endif
244

245
int compress_blob_lz4(const void *src, uint64_t src_size,
185✔
246
                      void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
247

248
        assert(src);
185✔
249
        assert(src_size > 0);
185✔
250
        assert(dst);
185✔
251
        assert(dst_alloc_size > 0);
185✔
252
        assert(dst_size);
185✔
253

254
#if HAVE_LZ4
255
        int r;
185✔
256

257
        r = dlopen_lz4();
185✔
258
        if (r < 0)
185✔
259
                return r;
260
        /* Returns < 0 if we couldn't compress the data or the
261
         * compressed result is longer than the original */
262

263
        if (src_size < 9)
185✔
264
                return -ENOBUFS;
265

266
        if (level <= 0)
185✔
267
                r = sym_LZ4_compress_default(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8);
185✔
268
        else
UNCOV
269
                r = sym_LZ4_compress_HC(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8, level);
×
270
        if (r <= 0)
185✔
271
                return -ENOBUFS;
272

273
        unaligned_write_le64(dst, src_size);
173✔
274
        *dst_size = r + 8;
173✔
275

276
        return 0;
173✔
277
#else
278
        return -EPROTONOSUPPORT;
279
#endif
280
}
281

282
#if HAVE_ZSTD
283
int dlopen_zstd(void) {
246,757✔
284
        ELF_NOTE_DLOPEN("zstd",
246,757✔
285
                        "Support zstd compression in journal and coredump files",
286
                        COMPRESSION_PRIORITY_ZSTD,
287
                        "libzstd.so.1");
288

289
        return dlopen_many_sym_or_warn(
246,757✔
290
                        &zstd_dl,
291
                        "libzstd.so.1", LOG_DEBUG,
292
                        DLSYM_ARG(ZSTD_getErrorCode),
293
                        DLSYM_ARG(ZSTD_compress),
294
                        DLSYM_ARG(ZSTD_getFrameContentSize),
295
                        DLSYM_ARG(ZSTD_decompressStream),
296
                        DLSYM_ARG(ZSTD_getErrorName),
297
                        DLSYM_ARG(ZSTD_DStreamOutSize),
298
                        DLSYM_ARG(ZSTD_CStreamInSize),
299
                        DLSYM_ARG(ZSTD_CStreamOutSize),
300
                        DLSYM_ARG(ZSTD_CCtx_setParameter),
301
                        DLSYM_ARG(ZSTD_compressStream2),
302
                        DLSYM_ARG(ZSTD_DStreamInSize),
303
                        DLSYM_ARG(ZSTD_freeCCtx),
304
                        DLSYM_ARG(ZSTD_freeDCtx),
305
                        DLSYM_ARG(ZSTD_isError),
306
                        DLSYM_ARG(ZSTD_createDCtx),
307
                        DLSYM_ARG(ZSTD_createCCtx));
308
}
309
#endif
310

311
int compress_blob_zstd(
264✔
312
                const void *src, uint64_t src_size,
313
                void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
314

315
        assert(src);
264✔
316
        assert(src_size > 0);
264✔
317
        assert(dst);
264✔
318
        assert(dst_alloc_size > 0);
264✔
319
        assert(dst_size);
264✔
320

321
#if HAVE_ZSTD
322
        size_t k;
264✔
323
        int r;
264✔
324

325
        r = dlopen_zstd();
264✔
326
        if (r < 0)
264✔
327
                return r;
328

329
        k = sym_ZSTD_compress(dst, dst_alloc_size, src, src_size, level < 0 ? 0 : level);
264✔
330
        if (sym_ZSTD_isError(k))
264✔
331
                return zstd_ret_to_errno(k);
5✔
332

333
        *dst_size = k;
259✔
334
        return 0;
259✔
335
#else
336
        return -EPROTONOSUPPORT;
337
#endif
338
}
339

340
int decompress_blob_xz(
2,519✔
341
                const void *src,
342
                uint64_t src_size,
343
                void **dst,
344
                size_t* dst_size,
345
                size_t dst_max) {
346

347
        assert(src);
2,519✔
348
        assert(src_size > 0);
2,519✔
349
        assert(dst);
2,519✔
350
        assert(dst_size);
2,519✔
351

352
#if HAVE_XZ
353
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
2,519✔
354
        lzma_ret ret;
2,519✔
355
        size_t space;
2,519✔
356
        int r;
2,519✔
357

358
        r = dlopen_lzma();
2,519✔
359
        if (r < 0)
2,519✔
360
                return r;
361

362
        ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
2,519✔
363
        if (ret != LZMA_OK)
2,519✔
364
                return -ENOMEM;
365

366
        space = MIN(src_size * 2, dst_max ?: SIZE_MAX);
2,519✔
367
        if (!greedy_realloc(dst, space, 1))
2,519✔
368
                return -ENOMEM;
369

370
        s.next_in = src;
2,519✔
371
        s.avail_in = src_size;
2,519✔
372

373
        s.next_out = *dst;
2,519✔
374
        s.avail_out = space;
2,519✔
375

376
        for (;;) {
2,789✔
377
                size_t used;
2,654✔
378

379
                ret = sym_lzma_code(&s, LZMA_FINISH);
2,654✔
380

381
                if (ret == LZMA_STREAM_END)
2,654✔
382
                        break;
383
                else if (ret != LZMA_OK)
141✔
384
                        return -ENOMEM;
385

386
                if (dst_max > 0 && (space - s.avail_out) >= dst_max)
135✔
387
                        break;
388
                else if (dst_max > 0 && space == dst_max)
135✔
389
                        return -ENOBUFS;
390

391
                used = space - s.avail_out;
135✔
392
                space = MIN(2 * space, dst_max ?: SIZE_MAX);
135✔
393
                if (!greedy_realloc(dst, space, 1))
135✔
394
                        return -ENOMEM;
395

396
                s.avail_out = space - used;
135✔
397
                s.next_out = *(uint8_t**)dst + used;
135✔
398
        }
399

400
        *dst_size = space - s.avail_out;
2,513✔
401
        return 0;
2,513✔
402
#else
403
        return -EPROTONOSUPPORT;
404
#endif
405
}
406

407
int decompress_blob_lz4(
2,669✔
408
                const void *src,
409
                uint64_t src_size,
410
                void **dst,
411
                size_t* dst_size,
412
                size_t dst_max) {
413

414
        assert(src);
2,669✔
415
        assert(src_size > 0);
2,669✔
416
        assert(dst);
2,669✔
417
        assert(dst_size);
2,669✔
418

419
#if HAVE_LZ4
420
        char* out;
2,669✔
421
        int r, size; /* LZ4 uses int for size */
2,669✔
422

423
        r = dlopen_lz4();
2,669✔
424
        if (r < 0)
2,669✔
425
                return r;
426

427
        if (src_size <= 8)
2,669✔
428
                return -EBADMSG;
429

430
        size = unaligned_read_le64(src);
2,667✔
431
        if (size < 0 || (unsigned) size != unaligned_read_le64(src))
2,667✔
432
                return -EFBIG;
433
        out = greedy_realloc(dst, size, 1);
2,663✔
434
        if (!out)
2,663✔
435
                return -ENOMEM;
436

437
        r = sym_LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
2,663✔
438
        if (r < 0 || r != size)
2,663✔
439
                return -EBADMSG;
440

441
        *dst_size = size;
2,663✔
442
        return 0;
2,663✔
443
#else
444
        return -EPROTONOSUPPORT;
445
#endif
446
}
447

448
int decompress_blob_zstd(
201,717✔
449
                const void *src,
450
                uint64_t src_size,
451
                void **dst,
452
                size_t *dst_size,
453
                size_t dst_max) {
454

455
        assert(src);
201,717✔
456
        assert(src_size > 0);
201,717✔
457
        assert(dst);
201,717✔
458
        assert(dst_size);
201,717✔
459

460
#if HAVE_ZSTD
461
        uint64_t size;
201,717✔
462
        int r;
201,717✔
463

464
        r = dlopen_zstd();
201,717✔
465
        if (r < 0)
201,717✔
466
                return r;
201,717✔
467

468
        size = sym_ZSTD_getFrameContentSize(src, src_size);
201,717✔
469
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
403,428✔
470
                return -EBADMSG;
471

472
        if (dst_max > 0 && size > dst_max)
201,711✔
473
                size = dst_max;
×
474
        if (size > SIZE_MAX)
201,711✔
475
                return -E2BIG;
476

477
        if (!(greedy_realloc(dst, MAX(sym_ZSTD_DStreamOutSize(), size), 1)))
201,711✔
478
                return -ENOMEM;
479

480
        _cleanup_(sym_ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
403,422✔
481
        if (!dctx)
201,711✔
482
                return -ENOMEM;
483

484
        ZSTD_inBuffer input = {
201,711✔
485
                .src = src,
486
                .size = src_size,
487
        };
488
        ZSTD_outBuffer output = {
403,422✔
489
                .dst = *dst,
201,711✔
490
                .size = MALLOC_SIZEOF_SAFE(*dst),
201,711✔
491
        };
492

493
        size_t k = sym_ZSTD_decompressStream(dctx, &output, &input);
201,711✔
494
        if (sym_ZSTD_isError(k)) {
201,711✔
495
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
496
                return zstd_ret_to_errno(k);
×
497
        }
498
        assert(output.pos >= size);
201,711✔
499

500
        *dst_size = size;
201,711✔
501
        return 0;
201,711✔
502
#else
503
        return -EPROTONOSUPPORT;
504
#endif
505
}
506

507
int decompress_blob(
206,593✔
508
                Compression compression,
509
                const void *src,
510
                uint64_t src_size,
511
                void **dst,
512
                size_t* dst_size,
513
                size_t dst_max) {
514

515
        if (compression == COMPRESSION_XZ)
206,593✔
516
                return decompress_blob_xz(
2,505✔
517
                                src, src_size,
518
                                dst, dst_size, dst_max);
519
        else if (compression == COMPRESSION_LZ4)
204,088✔
520
                return decompress_blob_lz4(
2,500✔
521
                                src, src_size,
522
                                dst, dst_size, dst_max);
523
        else if (compression == COMPRESSION_ZSTD)
201,588✔
524
                return decompress_blob_zstd(
201,588✔
525
                                src, src_size,
526
                                dst, dst_size, dst_max);
527
        else
528
                return -EPROTONOSUPPORT;
529
}
530

531
int decompress_startswith_xz(
270✔
532
                const void *src,
533
                uint64_t src_size,
534
                void **buffer,
535
                const void *prefix,
536
                size_t prefix_len,
537
                uint8_t extra) {
538

539
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
540
         * follow the prefix */
541

542
        assert(src);
270✔
543
        assert(src_size > 0);
270✔
544
        assert(buffer);
270✔
545
        assert(prefix);
270✔
546

547
#if HAVE_XZ
548
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
270✔
549
        size_t allocated;
270✔
550
        lzma_ret ret;
270✔
551
        int r;
270✔
552

553
        r = dlopen_lzma();
270✔
554
        if (r < 0)
270✔
555
                return r;
556

557
        ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
270✔
558
        if (ret != LZMA_OK)
270✔
559
                return -EBADMSG;
560

561
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
562
                return -ENOMEM;
563

564
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
565

566
        s.next_in = src;
270✔
567
        s.avail_in = src_size;
270✔
568

569
        s.next_out = *buffer;
270✔
570
        s.avail_out = allocated;
270✔
571

572
        for (;;) {
270✔
573
                ret = sym_lzma_code(&s, LZMA_FINISH);
270✔
574

575
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
270✔
576
                        return -EBADMSG;
577

578
                if (allocated - s.avail_out >= prefix_len + 1)
270✔
579
                        return memcmp(*buffer, prefix, prefix_len) == 0 &&
540✔
580
                                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
581

582
                if (ret == LZMA_STREAM_END)
×
583
                        return 0;
584

585
                s.avail_out += allocated;
×
586

587
                if (!(greedy_realloc(buffer, allocated * 2, 1)))
×
588
                        return -ENOMEM;
589

590
                allocated = MALLOC_SIZEOF_SAFE(*buffer);
×
591
                s.next_out = *(uint8_t**)buffer + allocated - s.avail_out;
×
592
        }
593

594
#else
595
        return -EPROTONOSUPPORT;
596
#endif
597
}
598

599
int decompress_startswith_lz4(
270✔
600
                const void *src,
601
                uint64_t src_size,
602
                void **buffer,
603
                const void *prefix,
604
                size_t prefix_len,
605
                uint8_t extra) {
606

607
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
608
         * follow the prefix */
609

610
        assert(src);
270✔
611
        assert(src_size > 0);
270✔
612
        assert(buffer);
270✔
613
        assert(prefix);
270✔
614

615
#if HAVE_LZ4
616
        size_t allocated;
270✔
617
        int r;
270✔
618

619
        r = dlopen_lz4();
270✔
620
        if (r < 0)
270✔
621
                return r;
622

623
        if (src_size <= 8)
270✔
624
                return -EBADMSG;
625

626
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
627
                return -ENOMEM;
628
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
629

630
        r = sym_LZ4_decompress_safe_partial(
540✔
631
                        (char*)src + 8,
632
                        *buffer,
633
                        src_size - 8,
270✔
634
                        prefix_len + 1,
270✔
635
                        allocated);
636

637
        /* One lz4 < 1.8.3, we might get "failure" (r < 0), or "success" where just a part of the buffer is
638
         * decompressed. But if we get a smaller amount of bytes than requested, we don't know whether there
639
         * isn't enough data to fill the requested size or whether we just got a partial answer.
640
         */
641
        if (r < 0 || (size_t) r < prefix_len + 1) {
270✔
642
                size_t size;
×
643

644
                if (sym_LZ4_versionNumber() >= 10803)
×
645
                        /* We trust that the newer lz4 decompresses the number of bytes we
646
                         * requested if available in the compressed string. */
647
                        return 0;
×
648

649
                if (r > 0)
×
650
                        /* Compare what we have first, in case of mismatch we can
651
                         * shortcut the full comparison. */
652
                        if (memcmp(*buffer, prefix, r) != 0)
×
653
                                return 0;
654

655
                /* Before version 1.8.3, lz4 always tries to decode full a "sequence",
656
                 * so in pathological cases might need to decompress the full field. */
657
                r = decompress_blob_lz4(src, src_size, buffer, &size, 0);
×
658
                if (r < 0)
×
659
                        return r;
660

661
                if (size < prefix_len + 1)
×
662
                        return 0;
663
        }
664

665
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
270✔
666
                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
667
#else
668
        return -EPROTONOSUPPORT;
669
#endif
670
}
671

672
int decompress_startswith_zstd(
44,737✔
673
                const void *src,
674
                uint64_t src_size,
675
                void **buffer,
676
                const void *prefix,
677
                size_t prefix_len,
678
                uint8_t extra) {
679

680
        assert(src);
44,737✔
681
        assert(src_size > 0);
44,737✔
682
        assert(buffer);
44,737✔
683
        assert(prefix);
44,737✔
684

685
#if HAVE_ZSTD
686
        int r;
44,737✔
687

688
        r = dlopen_zstd();
44,737✔
689
        if (r < 0)
44,737✔
690
                return r;
44,737✔
691

692
        uint64_t size = sym_ZSTD_getFrameContentSize(src, src_size);
44,737✔
693
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
89,474✔
694
                return -EBADMSG;
695

696
        if (size < prefix_len + 1)
44,737✔
697
                return 0; /* Decompressed text too short to match the prefix and extra */
698

699
        _cleanup_(sym_ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
89,474✔
700
        if (!dctx)
44,737✔
701
                return -ENOMEM;
702

703
        if (!(greedy_realloc(buffer, MAX(sym_ZSTD_DStreamOutSize(), prefix_len + 1), 1)))
44,737✔
704
                return -ENOMEM;
705

706
        ZSTD_inBuffer input = {
44,737✔
707
                .src = src,
708
                .size = src_size,
709
        };
710
        ZSTD_outBuffer output = {
89,474✔
711
                .dst = *buffer,
44,737✔
712
                .size = MALLOC_SIZEOF_SAFE(*buffer),
44,737✔
713
        };
714
        size_t k;
44,737✔
715

716
        k = sym_ZSTD_decompressStream(dctx, &output, &input);
44,737✔
717
        if (sym_ZSTD_isError(k)) {
44,737✔
718
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
719
                return zstd_ret_to_errno(k);
×
720
        }
721
        assert(output.pos >= prefix_len + 1);
44,737✔
722

723
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
44,737✔
724
                ((const uint8_t*) *buffer)[prefix_len] == extra;
419✔
725
#else
726
        return -EPROTONOSUPPORT;
727
#endif
728
}
729

730
int decompress_startswith(
44,479✔
731
                Compression compression,
732
                const void *src,
733
                uint64_t src_size,
734
                void **buffer,
735
                const void *prefix,
736
                size_t prefix_len,
737
                uint8_t extra) {
738

739
        if (compression == COMPRESSION_XZ)
44,479✔
740
                return decompress_startswith_xz(
4✔
741
                                src, src_size,
742
                                buffer,
743
                                prefix, prefix_len,
744
                                extra);
745

746
        else if (compression == COMPRESSION_LZ4)
44,475✔
747
                return decompress_startswith_lz4(
4✔
748
                                src, src_size,
749
                                buffer,
750
                                prefix, prefix_len,
751
                                extra);
752
        else if (compression == COMPRESSION_ZSTD)
44,471✔
753
                return decompress_startswith_zstd(
44,471✔
754
                                src, src_size,
755
                                buffer,
756
                                prefix, prefix_len,
757
                                extra);
758
        else
759
                return -EBADMSG;
760
}
761

762
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
763
        assert(fdf >= 0);
1✔
764
        assert(fdt >= 0);
1✔
765

766
#if HAVE_XZ
767
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
1✔
768
        lzma_ret ret;
1✔
769
        uint8_t buf[BUFSIZ], out[BUFSIZ];
1✔
770
        lzma_action action = LZMA_RUN;
1✔
771
        int r;
1✔
772

773
        r = dlopen_lzma();
1✔
774
        if (r < 0)
1✔
775
                return r;
776

777
        ret = sym_lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64);
1✔
778
        if (ret != LZMA_OK)
1✔
779
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
780
                                       "Failed to initialize XZ encoder: code %u",
781
                                       ret);
782

783
        for (;;) {
8✔
784
                if (s.avail_in == 0 && action == LZMA_RUN) {
8✔
785
                        size_t m = sizeof(buf);
7✔
786
                        ssize_t n;
7✔
787

788
                        if (max_bytes != UINT64_MAX && (uint64_t) m > max_bytes)
7✔
789
                                m = (size_t) max_bytes;
×
790

791
                        n = read(fdf, buf, m);
7✔
792
                        if (n < 0)
7✔
793
                                return -errno;
×
794
                        if (n == 0)
7✔
795
                                action = LZMA_FINISH;
796
                        else {
797
                                s.next_in = buf;
6✔
798
                                s.avail_in = n;
6✔
799

800
                                if (max_bytes != UINT64_MAX) {
6✔
801
                                        assert(max_bytes >= (uint64_t) n);
×
802
                                        max_bytes -= n;
×
803
                                }
804
                        }
805
                }
806

807
                if (s.avail_out == 0) {
8✔
808
                        s.next_out = out;
2✔
809
                        s.avail_out = sizeof(out);
2✔
810
                }
811

812
                ret = sym_lzma_code(&s, action);
8✔
813
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
8✔
814
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
×
815
                                               "Compression failed: code %u",
816
                                               ret);
817

818
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
8✔
819
                        ssize_t n, k;
2✔
820

821
                        n = sizeof(out) - s.avail_out;
2✔
822

823
                        k = loop_write(fdt, out, n);
2✔
824
                        if (k < 0)
2✔
825
                                return k;
826

827
                        if (ret == LZMA_STREAM_END) {
2✔
828
                                if (ret_uncompressed_size)
1✔
829
                                        *ret_uncompressed_size = s.total_in;
1✔
830

831
                                log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
832
                                          s.total_in, s.total_out,
833
                                          (double) s.total_out / s.total_in * 100);
834

835
                                return 0;
1✔
836
                        }
837
                }
838
        }
839
#else
840
        return -EPROTONOSUPPORT;
841
#endif
842
}
843

844
#define LZ4_BUFSIZE (512*1024u)
845

846
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
847

848
#if HAVE_LZ4
849
        LZ4F_errorCode_t c;
1✔
850
        _cleanup_(sym_LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL;
×
851
        _cleanup_free_ void *in_buff = NULL;
×
852
        _cleanup_free_ char *out_buff = NULL;
1✔
853
        size_t out_allocsize, n, offset = 0, frame_size;
1✔
854
        uint64_t total_in = 0, total_out;
1✔
855
        int r;
1✔
856
        static const LZ4F_preferences_t preferences = {
1✔
857
                .frameInfo.blockSizeID = 5,
858
        };
859

860
        r = dlopen_lz4();
1✔
861
        if (r < 0)
1✔
862
                return r;
863

864
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1✔
865
        if (sym_LZ4F_isError(c))
1✔
866
                return -ENOMEM;
867

868
        frame_size = sym_LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
1✔
869
        out_allocsize = frame_size + 64*1024; /* add some space for header and trailer */
1✔
870
        out_buff = malloc(out_allocsize);
1✔
871
        if (!out_buff)
1✔
872
                return -ENOMEM;
873

874
        in_buff = malloc(LZ4_BUFSIZE);
1✔
875
        if (!in_buff)
1✔
876
                return -ENOMEM;
877

878
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
1✔
879
        if (sym_LZ4F_isError(n))
1✔
880
                return -EINVAL;
881

882
        log_debug("Buffer size is %zu bytes, header size %zu bytes.", out_allocsize, n);
1✔
883

884
        for (;;) {
2✔
885
                ssize_t k;
2✔
886

887
                k = loop_read(fdf, in_buff, LZ4_BUFSIZE, true);
2✔
888
                if (k < 0)
2✔
889
                        return k;
×
890
                if (k == 0)
2✔
891
                        break;
892
                n = sym_LZ4F_compressUpdate(ctx, out_buff + offset, out_allocsize - offset,
1✔
893
                                        in_buff, k, NULL);
894
                if (sym_LZ4F_isError(n))
1✔
895
                        return -ENOTRECOVERABLE;
896

897
                total_in += k;
1✔
898
                offset += n;
1✔
899
                total_out += n;
1✔
900

901
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes)
1✔
902
                        return log_debug_errno(SYNTHETIC_ERRNO(EFBIG),
×
903
                                               "Compressed stream longer than %" PRIu64 " bytes", max_bytes);
904

905
                if (out_allocsize - offset < frame_size + 4) {
1✔
906
                        k = loop_write(fdt, out_buff, offset);
×
907
                        if (k < 0)
×
908
                                return k;
909
                        offset = 0;
910
                }
911
        }
912

913
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
1✔
914
        if (sym_LZ4F_isError(n))
1✔
915
                return -ENOTRECOVERABLE;
916

917
        offset += n;
1✔
918
        total_out += n;
1✔
919
        r = loop_write(fdt, out_buff, offset);
1✔
920
        if (r < 0)
1✔
921
                return r;
922

923
        if (ret_uncompressed_size)
1✔
924
                *ret_uncompressed_size = total_in;
1✔
925

926
        log_debug("LZ4 compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
1✔
927
                  total_in, total_out,
928
                  (double) total_out / total_in * 100);
929

930
        return 0;
931
#else
932
        return -EPROTONOSUPPORT;
933
#endif
934
}
935

936
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
3✔
937
        assert(fdf >= 0);
3✔
938
        assert(fdt >= 0);
3✔
939

940
#if HAVE_XZ
941
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
3✔
942
        lzma_ret ret;
3✔
943

944
        uint8_t buf[BUFSIZ], out[BUFSIZ];
3✔
945
        lzma_action action = LZMA_RUN;
3✔
946
        int r;
3✔
947

948
        r = dlopen_lzma();
3✔
949
        if (r < 0)
3✔
950
                return r;
951

952
        ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
3✔
953
        if (ret != LZMA_OK)
3✔
954
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEM),
×
955
                                       "Failed to initialize XZ decoder: code %u",
956
                                       ret);
957

958
        for (;;) {
15✔
959
                if (s.avail_in == 0 && action == LZMA_RUN) {
15✔
960
                        ssize_t n;
5✔
961

962
                        n = read(fdf, buf, sizeof(buf));
5✔
963
                        if (n < 0)
5✔
964
                                return -errno;
×
965
                        if (n == 0)
5✔
966
                                action = LZMA_FINISH;
967
                        else {
968
                                s.next_in = buf;
5✔
969
                                s.avail_in = n;
5✔
970
                        }
971
                }
972

973
                if (s.avail_out == 0) {
15✔
974
                        s.next_out = out;
13✔
975
                        s.avail_out = sizeof(out);
13✔
976
                }
977

978
                ret = sym_lzma_code(&s, action);
15✔
979
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
15✔
980
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1✔
981
                                               "Decompression failed: code %u",
982
                                               ret);
983

984
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
14✔
985
                        ssize_t n, k;
12✔
986

987
                        n = sizeof(out) - s.avail_out;
12✔
988

989
                        if (max_bytes != UINT64_MAX) {
12✔
990
                                if (max_bytes < (uint64_t) n)
12✔
991
                                        return -EFBIG;
992

993
                                max_bytes -= n;
11✔
994
                        }
995

996
                        k = loop_write(fdt, out, n);
11✔
997
                        if (k < 0)
11✔
998
                                return k;
999

1000
                        if (ret == LZMA_STREAM_END) {
11✔
1001
                                log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
1002
                                          s.total_in, s.total_out,
1003
                                          (double) s.total_out / s.total_in * 100);
1004

1005
                                return 0;
1✔
1006
                        }
1007
                }
1008
        }
1009
#else
1010
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1011
                               "Cannot decompress file. Compiled without XZ support.");
1012
#endif
1013
}
1014

1015
int decompress_stream_lz4(int in, int out, uint64_t max_bytes) {
3✔
1016
#if HAVE_LZ4
1017
        size_t c;
3✔
1018
        _cleanup_(sym_LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
×
1019
        _cleanup_free_ char *buf = NULL;
3✔
1020
        char *src;
3✔
1021
        struct stat st;
3✔
1022
        int r;
3✔
1023
        size_t total_in = 0, total_out = 0;
3✔
1024

1025
        r = dlopen_lz4();
3✔
1026
        if (r < 0)
3✔
1027
                return r;
1028

1029
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
3✔
1030
        if (sym_LZ4F_isError(c))
3✔
1031
                return -ENOMEM;
1032

1033
        if (fstat(in, &st) < 0)
3✔
1034
                return log_debug_errno(errno, "fstat() failed: %m");
×
1035

1036
        if (file_offset_beyond_memory_size(st.st_size))
3✔
1037
                return -EFBIG;
1038

1039
        buf = malloc(LZ4_BUFSIZE);
3✔
1040
        if (!buf)
3✔
1041
                return -ENOMEM;
1042

1043
        src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, in, 0);
3✔
1044
        if (src == MAP_FAILED)
3✔
1045
                return -errno;
×
1046

1047
        while (total_in < (size_t) st.st_size) {
5✔
1048
                size_t produced = LZ4_BUFSIZE;
3✔
1049
                size_t used = st.st_size - total_in;
3✔
1050

1051
                c = sym_LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
3✔
1052
                if (sym_LZ4F_isError(c)) {
3✔
1053
                        r = -EBADMSG;
×
1054
                        goto cleanup;
1✔
1055
                }
1056

1057
                total_in += used;
3✔
1058
                total_out += produced;
3✔
1059

1060
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes) {
3✔
1061
                        log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
1✔
1062
                        r = -EFBIG;
1✔
1063
                        goto cleanup;
1✔
1064
                }
1065

1066
                r = loop_write(out, buf, produced);
2✔
1067
                if (r < 0)
2✔
1068
                        goto cleanup;
×
1069
        }
1070

1071
        log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
2✔
1072
                  total_in, total_out,
1073
                  total_in > 0 ? (double) total_out / total_in * 100 : 0.0);
1074
        r = 0;
1075
 cleanup:
3✔
1076
        munmap(src, st.st_size);
3✔
1077
        return r;
3✔
1078
#else
1079
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1080
                               "Cannot decompress file. Compiled without LZ4 support.");
1081
#endif
1082
}
1083

1084
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
25✔
1085
        assert(fdf >= 0);
25✔
1086
        assert(fdt >= 0);
25✔
1087

1088
#if HAVE_ZSTD
1089
        _cleanup_(sym_ZSTD_freeCCtxp) ZSTD_CCtx *cctx = NULL;
×
1090
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
25✔
1091
        size_t in_allocsize, out_allocsize;
25✔
1092
        size_t z;
25✔
1093
        uint64_t left = max_bytes, in_bytes = 0;
25✔
1094
        int r;
25✔
1095

1096
        r = dlopen_zstd();
25✔
1097
        if (r < 0)
25✔
1098
                return r;
1099

1100
        /* Create the context and buffers */
1101
        in_allocsize = sym_ZSTD_CStreamInSize();
25✔
1102
        out_allocsize = sym_ZSTD_CStreamOutSize();
25✔
1103
        in_buff = malloc(in_allocsize);
25✔
1104
        out_buff = malloc(out_allocsize);
25✔
1105
        cctx = sym_ZSTD_createCCtx();
25✔
1106
        if (!cctx || !out_buff || !in_buff)
25✔
1107
                return -ENOMEM;
1108

1109
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
25✔
1110
        if (sym_ZSTD_isError(z))
25✔
1111
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1112

1113
        /* This loop read from the input file, compresses that entire chunk,
1114
         * and writes all output produced to the output file.
1115
         */
1116
        for (;;) {
205✔
1117
                bool is_last_chunk;
230✔
1118
                ZSTD_inBuffer input = {
230✔
1119
                        .src = in_buff,
1120
                        .size = 0,
1121
                        .pos = 0
1122
                };
1123
                ssize_t red;
230✔
1124

1125
                red = loop_read(fdf, in_buff, in_allocsize, true);
230✔
1126
                if (red < 0)
230✔
1127
                        return red;
×
1128
                is_last_chunk = red == 0;
230✔
1129

1130
                in_bytes += (size_t) red;
230✔
1131
                input.size = (size_t) red;
230✔
1132

1133
                for (bool finished = false; !finished;) {
460✔
1134
                        ZSTD_outBuffer output = {
230✔
1135
                                .dst = out_buff,
1136
                                .size = out_allocsize,
1137
                                .pos = 0
1138
                        };
1139
                        size_t remaining;
230✔
1140
                        ssize_t wrote;
230✔
1141

1142
                        /* Compress into the output buffer and write all of the
1143
                         * output to the file so we can reuse the buffer next
1144
                         * iteration.
1145
                         */
1146
                        remaining = sym_ZSTD_compressStream2(
435✔
1147
                                cctx, &output, &input,
1148
                                is_last_chunk ? ZSTD_e_end : ZSTD_e_continue);
1149

1150
                        if (sym_ZSTD_isError(remaining)) {
230✔
1151
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1152
                                return zstd_ret_to_errno(remaining);
×
1153
                        }
1154

1155
                        if (left < output.pos)
230✔
1156
                                return -EFBIG;
1157

1158
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
230✔
1159
                        if (wrote < 0)
230✔
1160
                                return wrote;
1161

1162
                        left -= output.pos;
230✔
1163

1164
                        /* If we're on the last chunk we're finished when zstd
1165
                         * returns 0, which means its consumed all the input AND
1166
                         * finished the frame. Otherwise, we're finished when
1167
                         * we've consumed all the input.
1168
                         */
1169
                        finished = is_last_chunk ? (remaining == 0) : (input.pos == input.size);
230✔
1170
                }
1171

1172
                /* zstd only returns 0 when the input is completely consumed */
1173
                assert(input.pos == input.size);
230✔
1174
                if (is_last_chunk)
230✔
1175
                        break;
1176
        }
1177

1178
        if (ret_uncompressed_size)
25✔
1179
                *ret_uncompressed_size = in_bytes;
25✔
1180

1181
        if (in_bytes > 0)
25✔
1182
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
25✔
1183
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1184
        else
1185
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes)",
25✔
1186
                          in_bytes, max_bytes - left);
1187

1188
        return 0;
1189
#else
1190
        return -EPROTONOSUPPORT;
1191
#endif
1192
}
1193

1194
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
13✔
1195
        assert(fdf >= 0);
13✔
1196
        assert(fdt >= 0);
13✔
1197

1198
#if HAVE_ZSTD
1199
        _cleanup_(sym_ZSTD_freeDCtxp) ZSTD_DCtx *dctx = NULL;
×
1200
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
13✔
1201
        size_t in_allocsize, out_allocsize;
13✔
1202
        size_t last_result = 0;
13✔
1203
        uint64_t left = max_bytes, in_bytes = 0;
13✔
1204
        int r;
13✔
1205

1206
        r = dlopen_zstd();
13✔
1207
        if (r < 0)
13✔
1208
                return r;
1209
        /* Create the context and buffers */
1210
        in_allocsize = sym_ZSTD_DStreamInSize();
13✔
1211
        out_allocsize = sym_ZSTD_DStreamOutSize();
13✔
1212
        in_buff = malloc(in_allocsize);
13✔
1213
        out_buff = malloc(out_allocsize);
13✔
1214
        dctx = sym_ZSTD_createDCtx();
13✔
1215
        if (!dctx || !out_buff || !in_buff)
13✔
1216
                return -ENOMEM;
1217

1218
        /* This loop assumes that the input file is one or more concatenated
1219
         * zstd streams. This example won't work if there is trailing non-zstd
1220
         * data at the end, but streaming decompression in general handles this
1221
         * case. ZSTD_decompressStream() returns 0 exactly when the frame is
1222
         * completed, and doesn't consume input after the frame.
1223
         */
1224
        for (;;) {
33✔
1225
                bool has_error = false;
23✔
1226
                ZSTD_inBuffer input = {
23✔
1227
                        .src = in_buff,
1228
                        .size = 0,
1229
                        .pos = 0
1230
                };
1231
                ssize_t red;
23✔
1232

1233
                red = loop_read(fdf, in_buff, in_allocsize, true);
23✔
1234
                if (red < 0)
23✔
1235
                        return red;
2✔
1236
                if (red == 0)
23✔
1237
                        break;
1238

1239
                in_bytes += (size_t) red;
13✔
1240
                input.size = (size_t) red;
13✔
1241
                input.pos = 0;
13✔
1242

1243
                /* Given a valid frame, zstd won't consume the last byte of the
1244
                 * frame until it has flushed all of the decompressed data of
1245
                 * the frame. So input.pos < input.size means frame is not done
1246
                 * or there is still output available.
1247
                 */
1248
                while (input.pos < input.size) {
59✔
1249
                        ZSTD_outBuffer output = {
49✔
1250
                                .dst = out_buff,
1251
                                .size = out_allocsize,
1252
                                .pos = 0
1253
                        };
1254
                        ssize_t wrote;
49✔
1255
                        /* The return code is zero if the frame is complete, but
1256
                         * there may be multiple frames concatenated together.
1257
                         * Zstd will automatically reset the context when a
1258
                         * frame is complete. Still, calling ZSTD_DCtx_reset()
1259
                         * can be useful to reset the context to a clean state,
1260
                         * for instance if the last decompression call returned
1261
                         * an error.
1262
                         */
1263
                        last_result = sym_ZSTD_decompressStream(dctx, &output, &input);
49✔
1264
                        if (sym_ZSTD_isError(last_result)) {
49✔
1265
                                has_error = true;
1✔
1266
                                break;
1✔
1267
                        }
1268

1269
                        if (left < output.pos)
48✔
1270
                                return -EFBIG;
2✔
1271

1272
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
47✔
1273
                        if (wrote < 0)
47✔
1274
                                return wrote;
1275

1276
                        left -= output.pos;
46✔
1277
                }
1278
                if (has_error)
11✔
1279
                        break;
1280
        }
1281

1282
        if (in_bytes == 0)
11✔
1283
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1284

1285
        if (last_result != 0) {
11✔
1286
                /* The last return value from ZSTD_decompressStream did not end
1287
                 * on a frame, but we reached the end of the file! We assume
1288
                 * this is an error, and the input was truncated.
1289
                 */
1290
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(last_result));
1✔
1291
                return zstd_ret_to_errno(last_result);
1✔
1292
        }
1293

1294
        log_debug(
13✔
1295
                "ZSTD decompression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
1296
                in_bytes,
1297
                max_bytes - left,
1298
                (double) (max_bytes - left) / in_bytes * 100);
1299
        return 0;
1300
#else
1301
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1302
                               "Cannot decompress file. Compiled without ZSTD support.");
1303
#endif
1304
}
1305

1306
int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes) {
10✔
1307

1308
        if (endswith(filename, ".lz4"))
10✔
1309
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1310
        else if (endswith(filename, ".xz"))
10✔
1311
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1312
        else if (endswith(filename, ".zst"))
10✔
1313
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1314
        else
1315
                return -EPROTONOSUPPORT;
1316
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc