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

systemd / systemd / 23697482987

28 Mar 2026 10:46PM UTC coverage: 72.41% (+0.009%) from 72.401%
23697482987

push

github

daandemeyer
repart: Make it possible to set persistent allow-discards activation flag

AllowDiscards= will set allow-discards in the persistent flags which will make
activating the device automatically activate with that option. This is
useful for devices discovered through gpt-auto-generator without
needing to use some kernel command line to set the option.

12 of 16 new or added lines in 1 file covered. (75.0%)

356 existing lines in 53 files now uncovered.

318282 of 439554 relevant lines covered (72.41%)

1154815.25 hits per line

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

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

3
#include <stdio.h>
4
#include <sys/mman.h>
5
#include <sys/stat.h>
6
#include <unistd.h>
7

8
#if HAVE_LZ4
9
#include <lz4.h>
10
#include <lz4hc.h>
11
#include <lz4frame.h>
12
#endif
13

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

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

23
#include "sd-dlopen.h"
24

25
#include "alloc-util.h"
26
#include "bitfield.h"
27
#include "compress.h"
28
#include "dlfcn-util.h"
29
#include "fileio.h"
30
#include "io-util.h"
31
#include "log.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
static DLSYM_PROTOTYPE(LZ4_compress_HC) = NULL;
50
/* These are used in test-compress.c so we don't make them static. */
51
// NOLINTBEGIN(misc-use-internal-linkage)
52
DLSYM_PROTOTYPE(LZ4_compress_default) = NULL;
53
DLSYM_PROTOTYPE(LZ4_decompress_safe) = NULL;
54
DLSYM_PROTOTYPE(LZ4_decompress_safe_partial) = NULL;
55
DLSYM_PROTOTYPE(LZ4_versionNumber) = NULL;
56
// NOLINTEND(misc-use-internal-linkage)
57

58
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_compressionContext_t, sym_LZ4F_freeCompressionContext, LZ4F_freeCompressionContextp, NULL);
1✔
59
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_decompressionContext_t, sym_LZ4F_freeDecompressionContext, LZ4F_freeDecompressionContextp, NULL);
3✔
60
#endif
61

62
#if HAVE_ZSTD
63
static void *zstd_dl = NULL;
64

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

82
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_CCtx*, sym_ZSTD_freeCCtx, ZSTD_freeCCtxp, NULL);
21✔
83
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_DCtx*, sym_ZSTD_freeDCtx, ZSTD_freeDCtxp, NULL);
5,065,488✔
84

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

97
#if HAVE_XZ
98
static void *lzma_dl = NULL;
99

100
static DLSYM_PROTOTYPE(lzma_code) = NULL;
101
static DLSYM_PROTOTYPE(lzma_easy_encoder) = NULL;
102
static DLSYM_PROTOTYPE(lzma_end) = NULL;
103
static DLSYM_PROTOTYPE(lzma_stream_buffer_encode) = NULL;
104
static DLSYM_PROTOTYPE(lzma_stream_decoder) = NULL;
105
static DLSYM_PROTOTYPE(lzma_lzma_preset) = NULL;
106

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

119
#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t))
120

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

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

135
DEFINE_STRING_TABLE_LOOKUP(compression, Compression);
1,015✔
136
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
75✔
137

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

145
        assert(c >= 0);
2,676✔
146
        assert(c < _COMPRESSION_MAX);
2,676✔
147

148
        return BIT_SET(supported, c);
2,676✔
149
}
150

151
int dlopen_lzma(void) {
2,964✔
152
#if HAVE_XZ
153
        SD_ELF_NOTE_DLOPEN(
2,964✔
154
                        "lzma",
155
                        "Support lzma compression in journal and coredump files",
156
                        COMPRESSION_PRIORITY_XZ,
157
                        "liblzma.so.5");
158

159
        return dlopen_many_sym_or_warn(
2,964✔
160
                        &lzma_dl,
161
                        "liblzma.so.5", LOG_DEBUG,
162
                        DLSYM_ARG(lzma_code),
163
                        DLSYM_ARG(lzma_easy_encoder),
164
                        DLSYM_ARG(lzma_end),
165
                        DLSYM_ARG(lzma_stream_buffer_encode),
166
                        DLSYM_ARG(lzma_lzma_preset),
167
                        DLSYM_ARG(lzma_stream_decoder));
168
#else
169
        return -EOPNOTSUPP;
170
#endif
171
}
172

173
int compress_blob_xz(const void *src, uint64_t src_size,
18✔
174
                     void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
175

176
        assert(src);
18✔
177
        assert(src_size > 0);
18✔
178
        assert(dst);
18✔
179
        assert(dst_alloc_size > 0);
18✔
180
        assert(dst_size);
18✔
181

182
#if HAVE_XZ
183
        lzma_options_lzma opt = {
18✔
184
                1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT,
185
                LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4
186
        };
187
        lzma_filter filters[] = {
18✔
188
                { LZMA_FILTER_LZMA2, &opt },
189
                { LZMA_VLI_UNKNOWN, NULL }
190
        };
191
        lzma_ret ret;
18✔
192
        size_t out_pos = 0;
18✔
193
        int r;
18✔
194

195
        r = dlopen_lzma();
18✔
196
        if (r < 0)
18✔
197
                return r;
18✔
198

199
        if (level >= 0) {
18✔
UNCOV
200
                r = sym_lzma_lzma_preset(&opt, (uint32_t) level);
×
201
                if (r < 0)
202
                        return r;
203
        }
204

205
        /* Returns < 0 if we couldn't compress the data or the
206
         * compressed result is longer than the original */
207

208
        if (src_size < 80)
18✔
209
                return -ENOBUFS;
210

211
        ret = sym_lzma_stream_buffer_encode(filters, LZMA_CHECK_NONE, NULL,
18✔
212
                                        src, src_size, dst, &out_pos, dst_alloc_size);
213
        if (ret != LZMA_OK)
18✔
214
                return -ENOBUFS;
215

216
        *dst_size = out_pos;
15✔
217
        return 0;
15✔
218
#else
219
        return -EPROTONOSUPPORT;
220
#endif
221
}
222

223
int dlopen_lz4(void) {
3,334✔
224
#if HAVE_LZ4
225
        SD_ELF_NOTE_DLOPEN(
3,334✔
226
                        "lz4",
227
                        "Support lz4 compression in journal and coredump files",
228
                        COMPRESSION_PRIORITY_LZ4,
229
                        "liblz4.so.1");
230

231
        return dlopen_many_sym_or_warn(
3,334✔
232
                        &lz4_dl,
233
                        "liblz4.so.1", LOG_DEBUG,
234
                        DLSYM_ARG(LZ4F_compressBegin),
235
                        DLSYM_ARG(LZ4F_compressBound),
236
                        DLSYM_ARG(LZ4F_compressEnd),
237
                        DLSYM_ARG(LZ4F_compressUpdate),
238
                        DLSYM_ARG(LZ4F_createCompressionContext),
239
                        DLSYM_ARG(LZ4F_createDecompressionContext),
240
                        DLSYM_ARG(LZ4F_decompress),
241
                        DLSYM_ARG(LZ4F_freeCompressionContext),
242
                        DLSYM_ARG(LZ4F_freeDecompressionContext),
243
                        DLSYM_ARG(LZ4F_isError),
244
                        DLSYM_ARG(LZ4_compress_default),
245
                        DLSYM_ARG(LZ4_compress_HC),
246
                        DLSYM_ARG(LZ4_decompress_safe),
247
                        DLSYM_ARG(LZ4_decompress_safe_partial),
248
                        DLSYM_ARG(LZ4_versionNumber));
249
#else
250
        return -EOPNOTSUPP;
251
#endif
252
}
253

254
int compress_blob_lz4(const void *src, uint64_t src_size,
219✔
255
                      void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
256

257
        assert(src);
219✔
258
        assert(src_size > 0);
219✔
259
        assert(dst);
219✔
260
        assert(dst_alloc_size > 0);
219✔
261
        assert(dst_size);
219✔
262

263
#if HAVE_LZ4
264
        int r;
219✔
265

266
        r = dlopen_lz4();
219✔
267
        if (r < 0)
219✔
268
                return r;
269
        /* Returns < 0 if we couldn't compress the data or the
270
         * compressed result is longer than the original */
271

272
        if (src_size < 9)
219✔
273
                return -ENOBUFS;
274

275
        if (level <= 0)
219✔
276
                r = sym_LZ4_compress_default(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8);
219✔
277
        else
UNCOV
278
                r = sym_LZ4_compress_HC(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8, level);
×
279
        if (r <= 0)
219✔
280
                return -ENOBUFS;
281

282
        unaligned_write_le64(dst, src_size);
205✔
283
        *dst_size = r + 8;
205✔
284

285
        return 0;
205✔
286
#else
287
        return -EPROTONOSUPPORT;
288
#endif
289
}
290

291
int dlopen_zstd(void) {
5,066,291✔
292
#if HAVE_ZSTD
293
        SD_ELF_NOTE_DLOPEN(
5,066,291✔
294
                        "zstd",
295
                        "Support zstd compression in journal and coredump files",
296
                        COMPRESSION_PRIORITY_ZSTD,
297
                        "libzstd.so.1");
298

299
        return dlopen_many_sym_or_warn(
5,066,291✔
300
                        &zstd_dl,
301
                        "libzstd.so.1", LOG_DEBUG,
302
                        DLSYM_ARG(ZSTD_getErrorCode),
303
                        DLSYM_ARG(ZSTD_compress),
304
                        DLSYM_ARG(ZSTD_getFrameContentSize),
305
                        DLSYM_ARG(ZSTD_decompressStream),
306
                        DLSYM_ARG(ZSTD_getErrorName),
307
                        DLSYM_ARG(ZSTD_DStreamOutSize),
308
                        DLSYM_ARG(ZSTD_CStreamInSize),
309
                        DLSYM_ARG(ZSTD_CStreamOutSize),
310
                        DLSYM_ARG(ZSTD_CCtx_setParameter),
311
                        DLSYM_ARG(ZSTD_compressStream2),
312
                        DLSYM_ARG(ZSTD_DStreamInSize),
313
                        DLSYM_ARG(ZSTD_freeCCtx),
314
                        DLSYM_ARG(ZSTD_freeDCtx),
315
                        DLSYM_ARG(ZSTD_isError),
316
                        DLSYM_ARG(ZSTD_createDCtx),
317
                        DLSYM_ARG(ZSTD_createCCtx));
318
#else
319
        return -EOPNOTSUPP;
320
#endif
321
}
322

323
int compress_blob_zstd(
775✔
324
                const void *src, uint64_t src_size,
325
                void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
326

327
        assert(src);
775✔
328
        assert(src_size > 0);
775✔
329
        assert(dst);
775✔
330
        assert(dst_alloc_size > 0);
775✔
331
        assert(dst_size);
775✔
332

333
#if HAVE_ZSTD
334
        size_t k;
775✔
335
        int r;
775✔
336

337
        r = dlopen_zstd();
775✔
338
        if (r < 0)
775✔
339
                return r;
340

341
        k = sym_ZSTD_compress(dst, dst_alloc_size, src, src_size, level < 0 ? 0 : level);
775✔
342
        if (sym_ZSTD_isError(k))
775✔
343
                return zstd_ret_to_errno(k);
5✔
344

345
        *dst_size = k;
770✔
346
        return 0;
770✔
347
#else
348
        return -EPROTONOSUPPORT;
349
#endif
350
}
351

352
int decompress_blob_xz(
2,671✔
353
                const void *src,
354
                uint64_t src_size,
355
                void **dst,
356
                size_t* dst_size,
357
                size_t dst_max) {
358

359
        assert(src);
2,671✔
360
        assert(src_size > 0);
2,671✔
361
        assert(dst);
2,671✔
362
        assert(dst_size);
2,671✔
363

364
#if HAVE_XZ
365
        int r;
2,671✔
366

367
        r = dlopen_lzma();
2,671✔
368
        if (r < 0)
2,671✔
369
                return r;
2,671✔
370

371
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
2,671✔
372
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
2,671✔
373
        if (ret != LZMA_OK)
2,671✔
374
                return -ENOMEM;
375

376
        size_t space = MIN(src_size * 2, dst_max ?: SIZE_MAX);
2,671✔
377
        if (!greedy_realloc(dst, space, 1))
2,671✔
378
                return -ENOMEM;
379

380
        s.next_in = src;
2,671✔
381
        s.avail_in = src_size;
2,671✔
382

383
        s.next_out = *dst;
2,671✔
384
        s.avail_out = space;
2,671✔
385

386
        for (;;) {
2,857✔
387
                size_t used;
2,764✔
388

389
                ret = sym_lzma_code(&s, LZMA_FINISH);
2,764✔
390
                if (ret == LZMA_STREAM_END)
2,764✔
391
                        break;
392
                if (ret != LZMA_OK)
99✔
393
                        return -ENOMEM;
394

395
                if (dst_max > 0 && (space - s.avail_out) >= dst_max)
93✔
396
                        break;
397
                if (dst_max > 0 && space == dst_max)
93✔
398
                        return -ENOBUFS;
399

400
                used = space - s.avail_out;
93✔
401
                space = MIN(2 * space, dst_max ?: SIZE_MAX);
93✔
402
                if (!greedy_realloc(dst, space, 1))
93✔
403
                        return -ENOMEM;
404

405
                s.avail_out = space - used;
93✔
406
                s.next_out = *(uint8_t**)dst + used;
93✔
407
        }
408

409
        *dst_size = space - s.avail_out;
2,665✔
410
        return 0;
2,665✔
411
#else
412
        return -EPROTONOSUPPORT;
413
#endif
414
}
415

416
int decompress_blob_lz4(
2,839✔
417
                const void *src,
418
                uint64_t src_size,
419
                void **dst,
420
                size_t* dst_size,
421
                size_t dst_max) {
422

423
        assert(src);
2,839✔
424
        assert(src_size > 0);
2,839✔
425
        assert(dst);
2,839✔
426
        assert(dst_size);
2,839✔
427

428
#if HAVE_LZ4
429
        char* out;
2,839✔
430
        int r, size; /* LZ4 uses int for size */
2,839✔
431

432
        r = dlopen_lz4();
2,839✔
433
        if (r < 0)
2,839✔
434
                return r;
435

436
        if (src_size <= 8)
2,839✔
437
                return -EBADMSG;
438

439
        size = unaligned_read_le64(src);
2,837✔
440
        if (size < 0 || (unsigned) size != unaligned_read_le64(src))
2,837✔
441
                return -EFBIG;
442
        out = greedy_realloc(dst, size, 1);
2,833✔
443
        if (!out)
2,833✔
444
                return -ENOMEM;
445

446
        r = sym_LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
2,833✔
447
        if (r < 0 || r != size)
2,833✔
448
                return -EBADMSG;
449

450
        *dst_size = size;
2,833✔
451
        return 0;
2,833✔
452
#else
453
        return -EPROTONOSUPPORT;
454
#endif
455
}
456

457
int decompress_blob_zstd(
248,083✔
458
                const void *src,
459
                uint64_t src_size,
460
                void **dst,
461
                size_t *dst_size,
462
                size_t dst_max) {
463

464
        assert(src);
248,083✔
465
        assert(src_size > 0);
248,083✔
466
        assert(dst);
248,083✔
467
        assert(dst_size);
248,083✔
468

469
#if HAVE_ZSTD
470
        uint64_t size;
248,083✔
471
        int r;
248,083✔
472

473
        r = dlopen_zstd();
248,083✔
474
        if (r < 0)
248,083✔
475
                return r;
248,083✔
476

477
        size = sym_ZSTD_getFrameContentSize(src, src_size);
248,083✔
478
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
248,083✔
479
                return -EBADMSG;
480

481
        if (dst_max > 0 && size > dst_max)
248,077✔
482
                size = dst_max;
×
483
        if (size > SIZE_MAX)
248,077✔
484
                return -E2BIG;
485

486
        if (!(greedy_realloc(dst, MAX(sym_ZSTD_DStreamOutSize(), size), 1)))
248,077✔
487
                return -ENOMEM;
488

489
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
496,154✔
490
        if (!dctx)
248,077✔
491
                return -ENOMEM;
492

493
        ZSTD_inBuffer input = {
248,077✔
494
                .src = src,
495
                .size = src_size,
496
        };
497
        ZSTD_outBuffer output = {
496,154✔
498
                .dst = *dst,
248,077✔
499
                .size = MALLOC_SIZEOF_SAFE(*dst),
248,077✔
500
        };
501

502
        size_t k = sym_ZSTD_decompressStream(dctx, &output, &input);
248,077✔
503
        if (sym_ZSTD_isError(k))
248,077✔
504
                return log_debug_errno(zstd_ret_to_errno(k), "ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
505
        if (output.pos < size)
248,077✔
506
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoded less data than indicated, probably corrupted stream.");
×
507

508
        *dst_size = size;
248,077✔
509
        return 0;
248,077✔
510
#else
511
        return -EPROTONOSUPPORT;
512
#endif
513
}
514

515
int decompress_blob(
253,264✔
516
                Compression compression,
517
                const void *src,
518
                uint64_t src_size,
519
                void **dst,
520
                size_t* dst_size,
521
                size_t dst_max) {
522

523
        switch (compression) {
253,264✔
524
        case COMPRESSION_XZ:
2,660✔
525
                return decompress_blob_xz(
2,660✔
526
                                src, src_size,
527
                                dst, dst_size, dst_max);
528
        case COMPRESSION_LZ4:
2,638✔
529
                return decompress_blob_lz4(
2,638✔
530
                                src, src_size,
531
                                dst, dst_size, dst_max);
532
        case COMPRESSION_ZSTD:
247,966✔
533
                return decompress_blob_zstd(
247,966✔
534
                                src, src_size,
535
                                dst, dst_size, dst_max);
536
        default:
537
                return -EPROTONOSUPPORT;
538
        }
539
}
540

541
int decompress_startswith_xz(
270✔
542
                const void *src,
543
                uint64_t src_size,
544
                void **buffer,
545
                const void *prefix,
546
                size_t prefix_len,
547
                uint8_t extra) {
548

549
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
550
         * follow the prefix */
551

552
        assert(src);
270✔
553
        assert(src_size > 0);
270✔
554
        assert(buffer);
270✔
555
        assert(prefix);
270✔
556

557
#if HAVE_XZ
558
        int r;
270✔
559

560
        r = dlopen_lzma();
270✔
561
        if (r < 0)
270✔
562
                return r;
270✔
563

564
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
270✔
565
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
270✔
566
        if (ret != LZMA_OK)
270✔
567
                return -EBADMSG;
568

569
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
570
                return -ENOMEM;
571

572
        size_t allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
573

574
        s.next_in = src;
270✔
575
        s.avail_in = src_size;
270✔
576

577
        s.next_out = *buffer;
270✔
578
        s.avail_out = allocated;
270✔
579

580
        for (;;) {
270✔
581
                ret = sym_lzma_code(&s, LZMA_FINISH);
270✔
582

583
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
270✔
584
                        return -EBADMSG;
585

586
                if (allocated - s.avail_out >= prefix_len + 1)
270✔
587
                        return memcmp(*buffer, prefix, prefix_len) == 0 &&
540✔
588
                                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
589

590
                if (ret == LZMA_STREAM_END)
×
591
                        return 0;
592

593
                s.avail_out += allocated;
×
594

595
                if (!(greedy_realloc(buffer, allocated * 2, 1)))
×
596
                        return -ENOMEM;
597

598
                allocated = MALLOC_SIZEOF_SAFE(*buffer);
×
599
                s.next_out = *(uint8_t**)buffer + allocated - s.avail_out;
×
600
        }
601

602
#else
603
        return -EPROTONOSUPPORT;
604
#endif
605
}
606

607
int decompress_startswith_lz4(
270✔
608
                const void *src,
609
                uint64_t src_size,
610
                void **buffer,
611
                const void *prefix,
612
                size_t prefix_len,
613
                uint8_t extra) {
614

615
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
616
         * follow the prefix */
617

618
        assert(src);
270✔
619
        assert(src_size > 0);
270✔
620
        assert(buffer);
270✔
621
        assert(prefix);
270✔
622

623
#if HAVE_LZ4
624
        size_t allocated;
270✔
625
        int r;
270✔
626

627
        r = dlopen_lz4();
270✔
628
        if (r < 0)
270✔
629
                return r;
630

631
        if (src_size <= 8)
270✔
632
                return -EBADMSG;
633

634
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
635
                return -ENOMEM;
636
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
637

638
        r = sym_LZ4_decompress_safe_partial(
540✔
639
                        (char*)src + 8,
640
                        *buffer,
641
                        src_size - 8,
270✔
642
                        prefix_len + 1,
270✔
643
                        allocated);
644

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

652
                if (sym_LZ4_versionNumber() >= 10803)
×
653
                        /* We trust that the newer lz4 decompresses the number of bytes we
654
                         * requested if available in the compressed string. */
655
                        return 0;
×
656

657
                if (r > 0)
×
658
                        /* Compare what we have first, in case of mismatch we can
659
                         * shortcut the full comparison. */
660
                        if (memcmp(*buffer, prefix, r) != 0)
×
661
                                return 0;
662

663
                /* Before version 1.8.3, lz4 always tries to decode full a "sequence",
664
                 * so in pathological cases might need to decompress the full field. */
665
                r = decompress_blob_lz4(src, src_size, buffer, &size, 0);
×
666
                if (r < 0)
×
667
                        return r;
668

669
                if (size < prefix_len + 1)
×
670
                        return 0;
671
        }
672

673
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
270✔
674
                ((const uint8_t*) *buffer)[prefix_len] == extra;
267✔
675
#else
676
        return -EPROTONOSUPPORT;
677
#endif
678
}
679

680
int decompress_startswith_zstd(
4,817,398✔
681
                const void *src,
682
                uint64_t src_size,
683
                void **buffer,
684
                const void *prefix,
685
                size_t prefix_len,
686
                uint8_t extra) {
687

688
        assert(src);
4,817,398✔
689
        assert(src_size > 0);
4,817,398✔
690
        assert(buffer);
4,817,398✔
691
        assert(prefix);
4,817,398✔
692

693
#if HAVE_ZSTD
694
        int r;
4,817,398✔
695

696
        r = dlopen_zstd();
4,817,398✔
697
        if (r < 0)
4,817,398✔
698
                return r;
4,817,398✔
699

700
        uint64_t size = sym_ZSTD_getFrameContentSize(src, src_size);
4,817,398✔
701
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
4,817,398✔
702
                return -EBADMSG;
703

704
        if (size < prefix_len + 1)
4,817,398✔
705
                return 0; /* Decompressed text too short to match the prefix and extra */
706

707
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
9,634,796✔
708
        if (!dctx)
4,817,398✔
709
                return -ENOMEM;
710

711
        if (!(greedy_realloc(buffer, MAX(sym_ZSTD_DStreamOutSize(), prefix_len + 1), 1)))
4,817,398✔
712
                return -ENOMEM;
713

714
        ZSTD_inBuffer input = {
4,817,398✔
715
                .src = src,
716
                .size = src_size,
717
        };
718
        ZSTD_outBuffer output = {
9,634,796✔
719
                .dst = *buffer,
4,817,398✔
720
                .size = MALLOC_SIZEOF_SAFE(*buffer),
4,817,398✔
721
        };
722
        size_t k;
4,817,398✔
723

724
        k = sym_ZSTD_decompressStream(dctx, &output, &input);
4,817,398✔
725
        if (sym_ZSTD_isError(k)) {
4,817,398✔
726
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
727
                return zstd_ret_to_errno(k);
×
728
        }
729
        assert(output.pos >= prefix_len + 1);
4,817,398✔
730

731
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
4,817,398✔
732
                ((const uint8_t*) *buffer)[prefix_len] == extra;
19,757✔
733
#else
734
        return -EPROTONOSUPPORT;
735
#endif
736
}
737

738
int decompress_startswith(
4,817,140✔
739
                Compression compression,
740
                const void *src,
741
                uint64_t src_size,
742
                void **buffer,
743
                const void *prefix,
744
                size_t prefix_len,
745
                uint8_t extra) {
746

747
        switch (compression) {
4,817,140✔
748

749
        case COMPRESSION_XZ:
4✔
750
                return decompress_startswith_xz(
4✔
751
                                src, src_size,
752
                                buffer,
753
                                prefix, prefix_len,
754
                                extra);
755

756
        case COMPRESSION_LZ4:
4✔
757
                return decompress_startswith_lz4(
4✔
758
                                src, src_size,
759
                                buffer,
760
                                prefix, prefix_len,
761
                                extra);
762
        case COMPRESSION_ZSTD:
4,817,132✔
763
                return decompress_startswith_zstd(
4,817,132✔
764
                                src, src_size,
765
                                buffer,
766
                                prefix, prefix_len,
767
                                extra);
768
        default:
769
                return -EBADMSG;
770
        }
771
}
772

773
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
774
        assert(fdf >= 0);
1✔
775
        assert(fdt >= 0);
1✔
776

777
#if HAVE_XZ
778
        int r;
1✔
779

780
        r = dlopen_lzma();
1✔
781
        if (r < 0)
1✔
782
                return r;
1✔
783

784
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
1✔
785
        lzma_ret ret = sym_lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64);
1✔
786
        if (ret != LZMA_OK)
1✔
787
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
788
                                       "Failed to initialize XZ encoder: code %u",
789
                                       ret);
790

791
        uint8_t buf[BUFSIZ], out[BUFSIZ];
792
        lzma_action action = LZMA_RUN;
793
        for (;;) {
8✔
794
                if (s.avail_in == 0 && action == LZMA_RUN) {
8✔
795
                        size_t m = sizeof(buf);
7✔
796
                        ssize_t n;
7✔
797

798
                        if (max_bytes != UINT64_MAX && (uint64_t) m > max_bytes)
7✔
799
                                m = (size_t) max_bytes;
×
800

801
                        n = read(fdf, buf, m);
7✔
802
                        if (n < 0)
7✔
803
                                return -errno;
×
804
                        if (n == 0)
7✔
805
                                action = LZMA_FINISH;
806
                        else {
807
                                s.next_in = buf;
6✔
808
                                s.avail_in = n;
6✔
809

810
                                if (max_bytes != UINT64_MAX) {
6✔
811
                                        assert(max_bytes >= (uint64_t) n);
×
812
                                        max_bytes -= n;
×
813
                                }
814
                        }
815
                }
816

817
                if (s.avail_out == 0) {
8✔
818
                        s.next_out = out;
2✔
819
                        s.avail_out = sizeof(out);
2✔
820
                }
821

822
                ret = sym_lzma_code(&s, action);
8✔
823
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
8✔
824
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
×
825
                                               "Compression failed: code %u",
826
                                               ret);
827

828
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
8✔
829
                        ssize_t n, k;
2✔
830

831
                        n = sizeof(out) - s.avail_out;
2✔
832

833
                        k = loop_write(fdt, out, n);
2✔
834
                        if (k < 0)
2✔
835
                                return k;
836

837
                        if (ret == LZMA_STREAM_END) {
2✔
838
                                if (ret_uncompressed_size)
1✔
839
                                        *ret_uncompressed_size = s.total_in;
1✔
840

841
                                if (s.total_in == 0)
1✔
842
                                        log_debug("XZ compression finished (no input data)");
×
843
                                else
844
                                        log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
845
                                                  s.total_in, s.total_out,
846
                                                  (double) s.total_out / s.total_in * 100);
847

848
                                return 0;
1✔
849
                        }
850
                }
851
        }
852
#else
853
        return -EPROTONOSUPPORT;
854
#endif
855
}
856

857
#define LZ4_BUFSIZE (512*1024u)
858

859
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
860

861
#if HAVE_LZ4
862
        LZ4F_errorCode_t c;
1✔
863
        _cleanup_(LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL;
×
864
        _cleanup_free_ void *in_buff = NULL;
×
865
        _cleanup_free_ char *out_buff = NULL;
1✔
866
        size_t out_allocsize, n, offset = 0, frame_size;
1✔
867
        uint64_t total_in = 0, total_out;
1✔
868
        int r;
1✔
869
        static const LZ4F_preferences_t preferences = {
1✔
870
                .frameInfo.blockSizeID = 5,
871
        };
872

873
        r = dlopen_lz4();
1✔
874
        if (r < 0)
1✔
875
                return r;
876

877
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1✔
878
        if (sym_LZ4F_isError(c))
1✔
879
                return -ENOMEM;
880

881
        frame_size = sym_LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
1✔
882
        out_allocsize = frame_size + 64*1024; /* add some space for header and trailer */
1✔
883
        out_buff = malloc(out_allocsize);
1✔
884
        if (!out_buff)
1✔
885
                return -ENOMEM;
886

887
        in_buff = malloc(LZ4_BUFSIZE);
1✔
888
        if (!in_buff)
1✔
889
                return -ENOMEM;
890

891
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
1✔
892
        if (sym_LZ4F_isError(n))
1✔
893
                return -EINVAL;
894

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

897
        for (;;) {
2✔
898
                ssize_t k;
2✔
899

900
                k = loop_read(fdf, in_buff, LZ4_BUFSIZE, true);
2✔
901
                if (k < 0)
2✔
902
                        return k;
×
903
                if (k == 0)
2✔
904
                        break;
905
                n = sym_LZ4F_compressUpdate(ctx, out_buff + offset, out_allocsize - offset,
1✔
906
                                        in_buff, k, NULL);
907
                if (sym_LZ4F_isError(n))
1✔
908
                        return -ENOTRECOVERABLE;
909

910
                total_in += k;
1✔
911
                offset += n;
1✔
912
                total_out += n;
1✔
913

914
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes)
1✔
915
                        return log_debug_errno(SYNTHETIC_ERRNO(EFBIG),
×
916
                                               "Compressed stream longer than %" PRIu64 " bytes", max_bytes);
917

918
                if (out_allocsize - offset < frame_size + 4) {
1✔
919
                        k = loop_write(fdt, out_buff, offset);
×
920
                        if (k < 0)
×
921
                                return k;
922
                        offset = 0;
923
                }
924
        }
925

926
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
1✔
927
        if (sym_LZ4F_isError(n))
1✔
928
                return -ENOTRECOVERABLE;
929

930
        offset += n;
1✔
931
        total_out += n;
1✔
932
        r = loop_write(fdt, out_buff, offset);
1✔
933
        if (r < 0)
1✔
934
                return r;
935

936
        if (ret_uncompressed_size)
1✔
937
                *ret_uncompressed_size = total_in;
1✔
938

939
        if (total_in == 0)
1✔
940
                log_debug("LZ4 compression finished (no input data)");
×
941
        else
942
                log_debug("LZ4 compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
1✔
943
                          total_in, total_out,
944
                          (double) total_out / total_in * 100);
945

946
        return 0;
947
#else
948
        return -EPROTONOSUPPORT;
949
#endif
950
}
951

952
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
3✔
953
        assert(fdf >= 0);
3✔
954
        assert(fdt >= 0);
3✔
955

956
#if HAVE_XZ
957
        int r;
3✔
958

959
        r = dlopen_lzma();
3✔
960
        if (r < 0)
3✔
961
                return r;
3✔
962

963
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
3✔
964
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
3✔
965
        if (ret != LZMA_OK)
3✔
966
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEM),
×
967
                                       "Failed to initialize XZ decoder: code %u",
968
                                       ret);
969

970
        uint8_t buf[BUFSIZ], out[BUFSIZ];
971
        lzma_action action = LZMA_RUN;
972
        for (;;) {
15✔
973
                if (s.avail_in == 0 && action == LZMA_RUN) {
15✔
974
                        ssize_t n;
5✔
975

976
                        n = read(fdf, buf, sizeof(buf));
5✔
977
                        if (n < 0)
5✔
978
                                return -errno;
×
979
                        if (n == 0)
5✔
980
                                action = LZMA_FINISH;
981
                        else {
982
                                s.next_in = buf;
5✔
983
                                s.avail_in = n;
5✔
984
                        }
985
                }
986

987
                if (s.avail_out == 0) {
15✔
988
                        s.next_out = out;
13✔
989
                        s.avail_out = sizeof(out);
13✔
990
                }
991

992
                ret = sym_lzma_code(&s, action);
15✔
993
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
15✔
994
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1✔
995
                                               "Decompression failed: code %u",
996
                                               ret);
997

998
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
14✔
999
                        ssize_t n, k;
12✔
1000

1001
                        n = sizeof(out) - s.avail_out;
12✔
1002

1003
                        if (max_bytes != UINT64_MAX) {
12✔
1004
                                if (max_bytes < (uint64_t) n)
12✔
1005
                                        return -EFBIG;
1006

1007
                                max_bytes -= n;
11✔
1008
                        }
1009

1010
                        k = loop_write(fdt, out, n);
11✔
1011
                        if (k < 0)
11✔
1012
                                return k;
1013

1014
                        if (ret == LZMA_STREAM_END) {
11✔
1015
                                if (s.total_in == 0)
1✔
1016
                                        log_debug("XZ decompression finished (no input data)");
×
1017
                                else
1018
                                        log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
1019
                                                  s.total_in, s.total_out,
1020
                                                  (double) s.total_out / s.total_in * 100);
1021

1022
                                return 0;
1✔
1023
                        }
1024
                }
1025
        }
1026
#else
1027
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1028
                               "Cannot decompress file. Compiled without XZ support.");
1029
#endif
1030
}
1031

1032
int decompress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) {
3✔
1033
#if HAVE_LZ4
1034
        size_t c;
3✔
1035
        _cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
×
1036
        _cleanup_free_ char *buf = NULL;
3✔
1037
        char *src;
3✔
1038
        struct stat st;
3✔
1039
        int r;
3✔
1040
        size_t total_in = 0, total_out = 0;
3✔
1041

1042
        r = dlopen_lz4();
3✔
1043
        if (r < 0)
3✔
1044
                return r;
1045

1046
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
3✔
1047
        if (sym_LZ4F_isError(c))
3✔
1048
                return -ENOMEM;
1049

1050
        if (fstat(fdf, &st) < 0)
3✔
1051
                return log_debug_errno(errno, "fstat() failed: %m");
×
1052

1053
        if (file_offset_beyond_memory_size(st.st_size))
3✔
1054
                return -EFBIG;
1055

1056
        buf = malloc(LZ4_BUFSIZE);
3✔
1057
        if (!buf)
3✔
1058
                return -ENOMEM;
1059

1060
        src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
3✔
1061
        if (src == MAP_FAILED)
3✔
1062
                return -errno;
×
1063

1064
        while (total_in < (size_t) st.st_size) {
5✔
1065
                size_t produced = LZ4_BUFSIZE;
3✔
1066
                size_t used = st.st_size - total_in;
3✔
1067

1068
                c = sym_LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
3✔
1069
                if (sym_LZ4F_isError(c)) {
3✔
1070
                        r = -EBADMSG;
×
1071
                        goto cleanup;
1✔
1072
                }
1073

1074
                total_in += used;
3✔
1075
                total_out += produced;
3✔
1076

1077
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes) {
3✔
1078
                        log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
1✔
1079
                        r = -EFBIG;
1✔
1080
                        goto cleanup;
1✔
1081
                }
1082

1083
                r = loop_write(fdt, buf, produced);
2✔
1084
                if (r < 0)
2✔
1085
                        goto cleanup;
×
1086
        }
1087

1088
        if (total_in == 0)
2✔
1089
                log_debug("LZ4 decompression finished (no input data)");
×
1090
        else
1091
                log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
2✔
1092
                          total_in, total_out,
1093
                          (double) total_out / total_in * 100);
1094
        r = 0;
1095
 cleanup:
3✔
1096
        munmap(src, st.st_size);
3✔
1097
        return r;
3✔
1098
#else
1099
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1100
                               "Cannot decompress file. Compiled without LZ4 support.");
1101
#endif
1102
}
1103

1104
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
21✔
1105
        assert(fdf >= 0);
21✔
1106
        assert(fdt >= 0);
21✔
1107

1108
#if HAVE_ZSTD
1109
        _cleanup_(ZSTD_freeCCtxp) ZSTD_CCtx *cctx = NULL;
×
1110
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
21✔
1111
        size_t in_allocsize, out_allocsize;
21✔
1112
        size_t z;
21✔
1113
        uint64_t left = max_bytes, in_bytes = 0;
21✔
1114
        int r;
21✔
1115

1116
        r = dlopen_zstd();
21✔
1117
        if (r < 0)
21✔
1118
                return r;
1119

1120
        /* Create the context and buffers */
1121
        in_allocsize = sym_ZSTD_CStreamInSize();
21✔
1122
        out_allocsize = sym_ZSTD_CStreamOutSize();
21✔
1123
        in_buff = malloc(in_allocsize);
21✔
1124
        out_buff = malloc(out_allocsize);
21✔
1125
        cctx = sym_ZSTD_createCCtx();
21✔
1126
        if (!cctx || !out_buff || !in_buff)
21✔
1127
                return -ENOMEM;
1128

1129
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
21✔
1130
        if (sym_ZSTD_isError(z))
21✔
1131
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1132

1133
        /* This loop read from the input file, compresses that entire chunk,
1134
         * and writes all output produced to the output file.
1135
         */
1136
        for (;;) {
503✔
1137
                bool is_last_chunk;
524✔
1138
                ZSTD_inBuffer input = {
524✔
1139
                        .src = in_buff,
1140
                        .size = 0,
1141
                        .pos = 0
1142
                };
1143
                ssize_t red;
524✔
1144

1145
                red = loop_read(fdf, in_buff, in_allocsize, true);
524✔
1146
                if (red < 0)
524✔
1147
                        return red;
×
1148
                is_last_chunk = red == 0;
524✔
1149

1150
                in_bytes += (size_t) red;
524✔
1151
                input.size = (size_t) red;
524✔
1152

1153
                for (bool finished = false; !finished;) {
1,048✔
1154
                        ZSTD_outBuffer output = {
524✔
1155
                                .dst = out_buff,
1156
                                .size = out_allocsize,
1157
                                .pos = 0
1158
                        };
1159
                        size_t remaining;
524✔
1160
                        ssize_t wrote;
524✔
1161

1162
                        /* Compress into the output buffer and write all of the
1163
                         * output to the file so we can reuse the buffer next
1164
                         * iteration.
1165
                         */
1166
                        remaining = sym_ZSTD_compressStream2(
1,027✔
1167
                                cctx, &output, &input,
1168
                                is_last_chunk ? ZSTD_e_end : ZSTD_e_continue);
1169

1170
                        if (sym_ZSTD_isError(remaining)) {
524✔
1171
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1172
                                return zstd_ret_to_errno(remaining);
×
1173
                        }
1174

1175
                        if (left < output.pos)
524✔
1176
                                return -EFBIG;
1177

1178
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
524✔
1179
                        if (wrote < 0)
524✔
1180
                                return wrote;
1181

1182
                        left -= output.pos;
524✔
1183

1184
                        /* If we're on the last chunk we're finished when zstd
1185
                         * returns 0, which means its consumed all the input AND
1186
                         * finished the frame. Otherwise, we're finished when
1187
                         * we've consumed all the input.
1188
                         */
1189
                        finished = is_last_chunk ? (remaining == 0) : (input.pos == input.size);
524✔
1190
                }
1191

1192
                /* zstd only returns 0 when the input is completely consumed */
1193
                assert(input.pos == input.size);
524✔
1194
                if (is_last_chunk)
524✔
1195
                        break;
1196
        }
1197

1198
        if (ret_uncompressed_size)
21✔
1199
                *ret_uncompressed_size = in_bytes;
21✔
1200

1201
        if (in_bytes == 0)
21✔
1202
                log_debug("ZSTD compression finished (no input data)");
×
1203
        else
1204
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
21✔
1205
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1206

1207
        return 0;
1208
#else
1209
        return -EPROTONOSUPPORT;
1210
#endif
1211
}
1212

1213
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
13✔
1214
        assert(fdf >= 0);
13✔
1215
        assert(fdt >= 0);
13✔
1216

1217
#if HAVE_ZSTD
1218
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = NULL;
×
1219
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
13✔
1220
        size_t in_allocsize, out_allocsize;
13✔
1221
        size_t last_result = 0;
13✔
1222
        uint64_t left = max_bytes, in_bytes = 0;
13✔
1223
        int r;
13✔
1224

1225
        r = dlopen_zstd();
13✔
1226
        if (r < 0)
13✔
1227
                return r;
1228
        /* Create the context and buffers */
1229
        in_allocsize = sym_ZSTD_DStreamInSize();
13✔
1230
        out_allocsize = sym_ZSTD_DStreamOutSize();
13✔
1231
        in_buff = malloc(in_allocsize);
13✔
1232
        out_buff = malloc(out_allocsize);
13✔
1233
        dctx = sym_ZSTD_createDCtx();
13✔
1234
        if (!dctx || !out_buff || !in_buff)
13✔
1235
                return -ENOMEM;
1236

1237
        /* This loop assumes that the input file is one or more concatenated
1238
         * zstd streams. This example won't work if there is trailing non-zstd
1239
         * data at the end, but streaming decompression in general handles this
1240
         * case. ZSTD_decompressStream() returns 0 exactly when the frame is
1241
         * completed, and doesn't consume input after the frame.
1242
         */
1243
        for (;;) {
69✔
1244
                bool has_error = false;
41✔
1245
                ZSTD_inBuffer input = {
41✔
1246
                        .src = in_buff,
1247
                        .size = 0,
1248
                        .pos = 0
1249
                };
1250
                ssize_t red;
41✔
1251

1252
                red = loop_read(fdf, in_buff, in_allocsize, true);
41✔
1253
                if (red < 0)
41✔
1254
                        return red;
2✔
1255
                if (red == 0)
41✔
1256
                        break;
1257

1258
                in_bytes += (size_t) red;
31✔
1259
                input.size = (size_t) red;
31✔
1260
                input.pos = 0;
31✔
1261

1262
                /* Given a valid frame, zstd won't consume the last byte of the
1263
                 * frame until it has flushed all of the decompressed data of
1264
                 * the frame. So input.pos < input.size means frame is not done
1265
                 * or there is still output available.
1266
                 */
1267
                while (input.pos < input.size) {
266✔
1268
                        ZSTD_outBuffer output = {
238✔
1269
                                .dst = out_buff,
1270
                                .size = out_allocsize,
1271
                                .pos = 0
1272
                        };
1273
                        ssize_t wrote;
238✔
1274
                        /* The return code is zero if the frame is complete, but
1275
                         * there may be multiple frames concatenated together.
1276
                         * Zstd will automatically reset the context when a
1277
                         * frame is complete. Still, calling ZSTD_DCtx_reset()
1278
                         * can be useful to reset the context to a clean state,
1279
                         * for instance if the last decompression call returned
1280
                         * an error.
1281
                         */
1282
                        last_result = sym_ZSTD_decompressStream(dctx, &output, &input);
238✔
1283
                        if (sym_ZSTD_isError(last_result)) {
238✔
1284
                                has_error = true;
1✔
1285
                                break;
1✔
1286
                        }
1287

1288
                        if (left < output.pos)
237✔
1289
                                return -EFBIG;
2✔
1290

1291
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
236✔
1292
                        if (wrote < 0)
236✔
1293
                                return wrote;
1294

1295
                        left -= output.pos;
235✔
1296
                }
1297
                if (has_error)
29✔
1298
                        break;
1299
        }
1300

1301
        if (in_bytes == 0)
11✔
1302
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1303

1304
        if (last_result != 0) {
11✔
1305
                /* The last return value from ZSTD_decompressStream did not end
1306
                 * on a frame, but we reached the end of the file! We assume
1307
                 * this is an error, and the input was truncated.
1308
                 */
1309
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(last_result));
1✔
1310
                return zstd_ret_to_errno(last_result);
1✔
1311
        }
1312

1313
        if (in_bytes == 0)
10✔
1314
                log_debug("ZSTD decompression finished (no input data)");
1315
        else
1316
                log_debug("ZSTD decompression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
10✔
1317
                          in_bytes,
1318
                          max_bytes - left,
1319
                          (double) (max_bytes - left) / in_bytes * 100);
1320
        return 0;
1321
#else
1322
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1323
                               "Cannot decompress file. Compiled without ZSTD support.");
1324
#endif
1325
}
1326

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

1329
        if (endswith(filename, ".lz4"))
10✔
1330
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1331
        if (endswith(filename, ".xz"))
10✔
1332
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1333
        if (endswith(filename, ".zst"))
10✔
1334
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1335

1336
        return -EPROTONOSUPPORT;
1337
}
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