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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

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

90.41
/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 <lz4.h>
13
#include <lz4hc.h>
14
#include <lz4frame.h>
15
#endif
16

17
#if HAVE_XZ
18
#include <lzma.h>
19
#endif
20

21
#if HAVE_ZSTD
22
#include <zstd.h>
23
#include <zstd_errors.h>
24
#endif
25

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

39
#if HAVE_LZ4
40
static void *lz4_dl = NULL;
41

42
static DLSYM_PROTOTYPE(LZ4F_compressBegin) = NULL;
43
static DLSYM_PROTOTYPE(LZ4F_compressBound) = NULL;
44
static DLSYM_PROTOTYPE(LZ4F_compressEnd) = NULL;
45
static DLSYM_PROTOTYPE(LZ4F_compressUpdate) = NULL;
46
static DLSYM_PROTOTYPE(LZ4F_createCompressionContext) = NULL;
47
static DLSYM_PROTOTYPE(LZ4F_createDecompressionContext) = NULL;
48
static DLSYM_PROTOTYPE(LZ4F_decompress) = NULL;
49
static DLSYM_PROTOTYPE(LZ4F_freeCompressionContext) = NULL;
50
static DLSYM_PROTOTYPE(LZ4F_freeDecompressionContext) = NULL;
51
static DLSYM_PROTOTYPE(LZ4F_isError) = NULL;
52
static DLSYM_PROTOTYPE(LZ4_compress_HC) = NULL;
53
/* These are used in test-compress.c so we don't make them static. */
54
DLSYM_PROTOTYPE(LZ4_compress_default) = NULL;
55
DLSYM_PROTOTYPE(LZ4_decompress_safe) = NULL;
56
DLSYM_PROTOTYPE(LZ4_decompress_safe_partial) = NULL;
57
DLSYM_PROTOTYPE(LZ4_versionNumber) = NULL;
58

59
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(LZ4F_compressionContext_t, sym_LZ4F_freeCompressionContext, NULL);
1✔
60
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(LZ4F_decompressionContext_t, sym_LZ4F_freeDecompressionContext, NULL);
3✔
61
#endif
62

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

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

83
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(ZSTD_CCtx*, sym_ZSTD_freeCCtx, NULL);
21✔
84
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(ZSTD_DCtx*, sym_ZSTD_freeDCtx, NULL);
408,111✔
85

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

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

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

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

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

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

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

136
DEFINE_STRING_TABLE_LOOKUP(compression, Compression);
584✔
137
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
54✔
138

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

146
        assert(c >= 0);
2,664✔
147
        assert(c < _COMPRESSION_MAX);
2,664✔
148

149
        return BIT_SET(supported, c);
2,664✔
150
}
151

152
#if HAVE_XZ
153
int dlopen_lzma(void) {
2,837✔
154
        ELF_NOTE_DLOPEN("lzma",
2,837✔
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,837✔
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
}
169
#endif
170

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

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

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

193
        r = dlopen_lzma();
18✔
194
        if (r < 0)
18✔
195
                return r;
18✔
196

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

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

206
        if (src_size < 80)
18✔
207
                return -ENOBUFS;
208

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

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

221
#if HAVE_LZ4
222
int dlopen_lz4(void) {
3,034✔
223
        ELF_NOTE_DLOPEN("lz4",
3,034✔
224
                        "Support lz4 compression in journal and coredump files",
225
                        COMPRESSION_PRIORITY_LZ4,
226
                        "liblz4.so.1");
227

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

249
int compress_blob_lz4(const void *src, uint64_t src_size,
113✔
250
                      void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
251

252
        assert(src);
113✔
253
        assert(src_size > 0);
113✔
254
        assert(dst);
113✔
255
        assert(dst_alloc_size > 0);
113✔
256
        assert(dst_size);
113✔
257

258
#if HAVE_LZ4
259
        int r;
113✔
260

261
        r = dlopen_lz4();
113✔
262
        if (r < 0)
113✔
263
                return r;
264
        /* Returns < 0 if we couldn't compress the data or the
265
         * compressed result is longer than the original */
266

267
        if (src_size < 9)
113✔
268
                return -ENOBUFS;
269

270
        if (level <= 0)
113✔
271
                r = sym_LZ4_compress_default(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8);
113✔
272
        else
273
                r = sym_LZ4_compress_HC(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8, level);
×
274
        if (r <= 0)
113✔
275
                return -ENOBUFS;
276

277
        unaligned_write_le64(dst, src_size);
104✔
278
        *dst_size = r + 8;
104✔
279

280
        return 0;
104✔
281
#else
282
        return -EPROTONOSUPPORT;
283
#endif
284
}
285

286
#if HAVE_ZSTD
287
int dlopen_zstd(void) {
408,401✔
288
        ELF_NOTE_DLOPEN("zstd",
408,401✔
289
                        "Support zstd compression in journal and coredump files",
290
                        COMPRESSION_PRIORITY_ZSTD,
291
                        "libzstd.so.1");
292

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

315
int compress_blob_zstd(
262✔
316
                const void *src, uint64_t src_size,
317
                void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
318

319
        assert(src);
262✔
320
        assert(src_size > 0);
262✔
321
        assert(dst);
262✔
322
        assert(dst_alloc_size > 0);
262✔
323
        assert(dst_size);
262✔
324

325
#if HAVE_ZSTD
326
        size_t k;
262✔
327
        int r;
262✔
328

329
        r = dlopen_zstd();
262✔
330
        if (r < 0)
262✔
331
                return r;
332

333
        k = sym_ZSTD_compress(dst, dst_alloc_size, src, src_size, level < 0 ? 0 : level);
262✔
334
        if (sym_ZSTD_isError(k))
262✔
335
                return zstd_ret_to_errno(k);
2✔
336

337
        *dst_size = k;
260✔
338
        return 0;
260✔
339
#else
340
        return -EPROTONOSUPPORT;
341
#endif
342
}
343

344
int decompress_blob_xz(
2,544✔
345
                const void *src,
346
                uint64_t src_size,
347
                void **dst,
348
                size_t* dst_size,
349
                size_t dst_max) {
350

351
        assert(src);
2,544✔
352
        assert(src_size > 0);
2,544✔
353
        assert(dst);
2,544✔
354
        assert(dst_size);
2,544✔
355

356
#if HAVE_XZ
357
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
2,544✔
358
        lzma_ret ret;
2,544✔
359
        size_t space;
2,544✔
360
        int r;
2,544✔
361

362
        r = dlopen_lzma();
2,544✔
363
        if (r < 0)
2,544✔
364
                return r;
365

366
        ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
2,544✔
367
        if (ret != LZMA_OK)
2,544✔
368
                return -ENOMEM;
369

370
        space = MIN(src_size * 2, dst_max ?: SIZE_MAX);
2,544✔
371
        if (!greedy_realloc(dst, space, 1))
2,544✔
372
                return -ENOMEM;
373

374
        s.next_in = src;
2,544✔
375
        s.avail_in = src_size;
2,544✔
376

377
        s.next_out = *dst;
2,544✔
378
        s.avail_out = space;
2,544✔
379

380
        for (;;) {
2,730✔
381
                size_t used;
2,637✔
382

383
                ret = sym_lzma_code(&s, LZMA_FINISH);
2,637✔
384

385
                if (ret == LZMA_STREAM_END)
2,637✔
386
                        break;
387
                else if (ret != LZMA_OK)
99✔
388
                        return -ENOMEM;
389

390
                if (dst_max > 0 && (space - s.avail_out) >= dst_max)
93✔
391
                        break;
392
                else if (dst_max > 0 && space == dst_max)
93✔
393
                        return -ENOBUFS;
394

395
                used = space - s.avail_out;
93✔
396
                space = MIN(2 * space, dst_max ?: SIZE_MAX);
93✔
397
                if (!greedy_realloc(dst, space, 1))
93✔
398
                        return -ENOMEM;
399

400
                s.avail_out = space - used;
93✔
401
                s.next_out = *(uint8_t**)dst + used;
93✔
402
        }
403

404
        *dst_size = space - s.avail_out;
2,538✔
405
        return 0;
2,538✔
406
#else
407
        return -EPROTONOSUPPORT;
408
#endif
409
}
410

411
int decompress_blob_lz4(
2,645✔
412
                const void *src,
413
                uint64_t src_size,
414
                void **dst,
415
                size_t* dst_size,
416
                size_t dst_max) {
417

418
        assert(src);
2,645✔
419
        assert(src_size > 0);
2,645✔
420
        assert(dst);
2,645✔
421
        assert(dst_size);
2,645✔
422

423
#if HAVE_LZ4
424
        char* out;
2,645✔
425
        int r, size; /* LZ4 uses int for size */
2,645✔
426

427
        r = dlopen_lz4();
2,645✔
428
        if (r < 0)
2,645✔
429
                return r;
430

431
        if (src_size <= 8)
2,645✔
432
                return -EBADMSG;
433

434
        size = unaligned_read_le64(src);
2,643✔
435
        if (size < 0 || (unsigned) size != unaligned_read_le64(src))
2,643✔
436
                return -EFBIG;
437
        out = greedy_realloc(dst, size, 1);
2,639✔
438
        if (!out)
2,639✔
439
                return -ENOMEM;
440

441
        r = sym_LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
2,639✔
442
        if (r < 0 || r != size)
2,639✔
443
                return -EBADMSG;
444

445
        *dst_size = size;
2,639✔
446
        return 0;
2,639✔
447
#else
448
        return -EPROTONOSUPPORT;
449
#endif
450
}
451

452
int decompress_blob_zstd(
359,343✔
453
                const void *src,
454
                uint64_t src_size,
455
                void **dst,
456
                size_t *dst_size,
457
                size_t dst_max) {
458

459
        assert(src);
359,343✔
460
        assert(src_size > 0);
359,343✔
461
        assert(dst);
359,343✔
462
        assert(dst_size);
359,343✔
463

464
#if HAVE_ZSTD
465
        uint64_t size;
359,343✔
466
        int r;
359,343✔
467

468
        r = dlopen_zstd();
359,343✔
469
        if (r < 0)
359,343✔
470
                return r;
359,343✔
471

472
        size = sym_ZSTD_getFrameContentSize(src, src_size);
359,343✔
473
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
359,343✔
474
                return -EBADMSG;
475

476
        if (dst_max > 0 && size > dst_max)
359,337✔
477
                size = dst_max;
×
478
        if (size > SIZE_MAX)
359,337✔
479
                return -E2BIG;
480

481
        if (!(greedy_realloc(dst, MAX(sym_ZSTD_DStreamOutSize(), size), 1)))
359,337✔
482
                return -ENOMEM;
483

484
        _cleanup_(sym_ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
718,674✔
485
        if (!dctx)
359,337✔
486
                return -ENOMEM;
487

488
        ZSTD_inBuffer input = {
359,337✔
489
                .src = src,
490
                .size = src_size,
491
        };
492
        ZSTD_outBuffer output = {
718,674✔
493
                .dst = *dst,
359,337✔
494
                .size = MALLOC_SIZEOF_SAFE(*dst),
359,337✔
495
        };
496

497
        size_t k = sym_ZSTD_decompressStream(dctx, &output, &input);
359,337✔
498
        if (sym_ZSTD_isError(k))
359,337✔
499
                return log_debug_errno(zstd_ret_to_errno(k), "ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
500
        if (output.pos < size)
359,337✔
501
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoded less data than indicated, probably corrupted stream.");
×
502

503
        *dst_size = size;
359,337✔
504
        return 0;
359,337✔
505
#else
506
        return -EPROTONOSUPPORT;
507
#endif
508
}
509

510
int decompress_blob(
364,325✔
511
                Compression compression,
512
                const void *src,
513
                uint64_t src_size,
514
                void **dst,
515
                size_t* dst_size,
516
                size_t dst_max) {
517

518
        if (compression == COMPRESSION_XZ)
364,325✔
519
                return decompress_blob_xz(
2,533✔
520
                                src, src_size,
521
                                dst, dst_size, dst_max);
522
        else if (compression == COMPRESSION_LZ4)
361,792✔
523
                return decompress_blob_lz4(
2,545✔
524
                                src, src_size,
525
                                dst, dst_size, dst_max);
526
        else if (compression == COMPRESSION_ZSTD)
359,247✔
527
                return decompress_blob_zstd(
359,247✔
528
                                src, src_size,
529
                                dst, dst_size, dst_max);
530
        else
531
                return -EPROTONOSUPPORT;
532
}
533

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

542
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
543
         * follow the prefix */
544

545
        assert(src);
270✔
546
        assert(src_size > 0);
270✔
547
        assert(buffer);
270✔
548
        assert(prefix);
270✔
549

550
#if HAVE_XZ
551
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
270✔
552
        size_t allocated;
270✔
553
        lzma_ret ret;
270✔
554
        int r;
270✔
555

556
        r = dlopen_lzma();
270✔
557
        if (r < 0)
270✔
558
                return r;
559

560
        ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
270✔
561
        if (ret != LZMA_OK)
270✔
562
                return -EBADMSG;
563

564
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
565
                return -ENOMEM;
566

567
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
568

569
        s.next_in = src;
270✔
570
        s.avail_in = src_size;
270✔
571

572
        s.next_out = *buffer;
270✔
573
        s.avail_out = allocated;
270✔
574

575
        for (;;) {
270✔
576
                ret = sym_lzma_code(&s, LZMA_FINISH);
270✔
577

578
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
270✔
579
                        return -EBADMSG;
580

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

585
                if (ret == LZMA_STREAM_END)
×
586
                        return 0;
587

588
                s.avail_out += allocated;
×
589

590
                if (!(greedy_realloc(buffer, allocated * 2, 1)))
×
591
                        return -ENOMEM;
592

593
                allocated = MALLOC_SIZEOF_SAFE(*buffer);
×
594
                s.next_out = *(uint8_t**)buffer + allocated - s.avail_out;
×
595
        }
596

597
#else
598
        return -EPROTONOSUPPORT;
599
#endif
600
}
601

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

610
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
611
         * follow the prefix */
612

613
        assert(src);
270✔
614
        assert(src_size > 0);
270✔
615
        assert(buffer);
270✔
616
        assert(prefix);
270✔
617

618
#if HAVE_LZ4
619
        size_t allocated;
270✔
620
        int r;
270✔
621

622
        r = dlopen_lz4();
270✔
623
        if (r < 0)
270✔
624
                return r;
625

626
        if (src_size <= 8)
270✔
627
                return -EBADMSG;
628

629
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
630
                return -ENOMEM;
631
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
632

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

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

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

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

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

664
                if (size < prefix_len + 1)
×
665
                        return 0;
666
        }
667

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

675
int decompress_startswith_zstd(
48,761✔
676
                const void *src,
677
                uint64_t src_size,
678
                void **buffer,
679
                const void *prefix,
680
                size_t prefix_len,
681
                uint8_t extra) {
682

683
        assert(src);
48,761✔
684
        assert(src_size > 0);
48,761✔
685
        assert(buffer);
48,761✔
686
        assert(prefix);
48,761✔
687

688
#if HAVE_ZSTD
689
        int r;
48,761✔
690

691
        r = dlopen_zstd();
48,761✔
692
        if (r < 0)
48,761✔
693
                return r;
48,761✔
694

695
        uint64_t size = sym_ZSTD_getFrameContentSize(src, src_size);
48,761✔
696
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
48,761✔
697
                return -EBADMSG;
698

699
        if (size < prefix_len + 1)
48,761✔
700
                return 0; /* Decompressed text too short to match the prefix and extra */
701

702
        _cleanup_(sym_ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
97,522✔
703
        if (!dctx)
48,761✔
704
                return -ENOMEM;
705

706
        if (!(greedy_realloc(buffer, MAX(sym_ZSTD_DStreamOutSize(), prefix_len + 1), 1)))
48,761✔
707
                return -ENOMEM;
708

709
        ZSTD_inBuffer input = {
48,761✔
710
                .src = src,
711
                .size = src_size,
712
        };
713
        ZSTD_outBuffer output = {
97,522✔
714
                .dst = *buffer,
48,761✔
715
                .size = MALLOC_SIZEOF_SAFE(*buffer),
48,761✔
716
        };
717
        size_t k;
48,761✔
718

719
        k = sym_ZSTD_decompressStream(dctx, &output, &input);
48,761✔
720
        if (sym_ZSTD_isError(k)) {
48,761✔
721
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(k));
×
722
                return zstd_ret_to_errno(k);
×
723
        }
724
        assert(output.pos >= prefix_len + 1);
48,761✔
725

726
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
48,761✔
727
                ((const uint8_t*) *buffer)[prefix_len] == extra;
374✔
728
#else
729
        return -EPROTONOSUPPORT;
730
#endif
731
}
732

733
int decompress_startswith(
48,503✔
734
                Compression compression,
735
                const void *src,
736
                uint64_t src_size,
737
                void **buffer,
738
                const void *prefix,
739
                size_t prefix_len,
740
                uint8_t extra) {
741

742
        if (compression == COMPRESSION_XZ)
48,503✔
743
                return decompress_startswith_xz(
4✔
744
                                src, src_size,
745
                                buffer,
746
                                prefix, prefix_len,
747
                                extra);
748

749
        else if (compression == COMPRESSION_LZ4)
48,499✔
750
                return decompress_startswith_lz4(
4✔
751
                                src, src_size,
752
                                buffer,
753
                                prefix, prefix_len,
754
                                extra);
755
        else if (compression == COMPRESSION_ZSTD)
48,495✔
756
                return decompress_startswith_zstd(
48,495✔
757
                                src, src_size,
758
                                buffer,
759
                                prefix, prefix_len,
760
                                extra);
761
        else
762
                return -EBADMSG;
763
}
764

765
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
766
        assert(fdf >= 0);
1✔
767
        assert(fdt >= 0);
1✔
768

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

776
        r = dlopen_lzma();
1✔
777
        if (r < 0)
1✔
778
                return r;
779

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

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

791
                        if (max_bytes != UINT64_MAX && (uint64_t) m > max_bytes)
7✔
792
                                m = (size_t) max_bytes;
×
793

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

803
                                if (max_bytes != UINT64_MAX) {
6✔
804
                                        assert(max_bytes >= (uint64_t) n);
×
805
                                        max_bytes -= n;
×
806
                                }
807
                        }
808
                }
809

810
                if (s.avail_out == 0) {
8✔
811
                        s.next_out = out;
2✔
812
                        s.avail_out = sizeof(out);
2✔
813
                }
814

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

821
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
8✔
822
                        ssize_t n, k;
2✔
823

824
                        n = sizeof(out) - s.avail_out;
2✔
825

826
                        k = loop_write(fdt, out, n);
2✔
827
                        if (k < 0)
2✔
828
                                return k;
829

830
                        if (ret == LZMA_STREAM_END) {
2✔
831
                                if (ret_uncompressed_size)
1✔
832
                                        *ret_uncompressed_size = s.total_in;
1✔
833

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

838
                                return 0;
1✔
839
                        }
840
                }
841
        }
842
#else
843
        return -EPROTONOSUPPORT;
844
#endif
845
}
846

847
#define LZ4_BUFSIZE (512*1024u)
848

849
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
850

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

863
        r = dlopen_lz4();
1✔
864
        if (r < 0)
1✔
865
                return r;
866

867
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1✔
868
        if (sym_LZ4F_isError(c))
1✔
869
                return -ENOMEM;
870

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

877
        in_buff = malloc(LZ4_BUFSIZE);
1✔
878
        if (!in_buff)
1✔
879
                return -ENOMEM;
880

881
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
1✔
882
        if (sym_LZ4F_isError(n))
1✔
883
                return -EINVAL;
884

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

887
        for (;;) {
2✔
888
                ssize_t k;
2✔
889

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

900
                total_in += k;
1✔
901
                offset += n;
1✔
902
                total_out += n;
1✔
903

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

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

916
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
1✔
917
        if (sym_LZ4F_isError(n))
1✔
918
                return -ENOTRECOVERABLE;
919

920
        offset += n;
1✔
921
        total_out += n;
1✔
922
        r = loop_write(fdt, out_buff, offset);
1✔
923
        if (r < 0)
1✔
924
                return r;
925

926
        if (ret_uncompressed_size)
1✔
927
                *ret_uncompressed_size = total_in;
1✔
928

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

933
        return 0;
934
#else
935
        return -EPROTONOSUPPORT;
936
#endif
937
}
938

939
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
3✔
940
        assert(fdf >= 0);
3✔
941
        assert(fdt >= 0);
3✔
942

943
#if HAVE_XZ
944
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
3✔
945
        lzma_ret ret;
3✔
946

947
        uint8_t buf[BUFSIZ], out[BUFSIZ];
3✔
948
        lzma_action action = LZMA_RUN;
3✔
949
        int r;
3✔
950

951
        r = dlopen_lzma();
3✔
952
        if (r < 0)
3✔
953
                return r;
954

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

961
        for (;;) {
15✔
962
                if (s.avail_in == 0 && action == LZMA_RUN) {
15✔
963
                        ssize_t n;
5✔
964

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

976
                if (s.avail_out == 0) {
15✔
977
                        s.next_out = out;
13✔
978
                        s.avail_out = sizeof(out);
13✔
979
                }
980

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

987
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
14✔
988
                        ssize_t n, k;
12✔
989

990
                        n = sizeof(out) - s.avail_out;
12✔
991

992
                        if (max_bytes != UINT64_MAX) {
12✔
993
                                if (max_bytes < (uint64_t) n)
12✔
994
                                        return -EFBIG;
995

996
                                max_bytes -= n;
11✔
997
                        }
998

999
                        k = loop_write(fdt, out, n);
11✔
1000
                        if (k < 0)
11✔
1001
                                return k;
1002

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

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

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

1028
        r = dlopen_lz4();
3✔
1029
        if (r < 0)
3✔
1030
                return r;
1031

1032
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
3✔
1033
        if (sym_LZ4F_isError(c))
3✔
1034
                return -ENOMEM;
1035

1036
        if (fstat(in, &st) < 0)
3✔
1037
                return log_debug_errno(errno, "fstat() failed: %m");
×
1038

1039
        if (file_offset_beyond_memory_size(st.st_size))
3✔
1040
                return -EFBIG;
1041

1042
        buf = malloc(LZ4_BUFSIZE);
3✔
1043
        if (!buf)
3✔
1044
                return -ENOMEM;
1045

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

1050
        while (total_in < (size_t) st.st_size) {
5✔
1051
                size_t produced = LZ4_BUFSIZE;
3✔
1052
                size_t used = st.st_size - total_in;
3✔
1053

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

1060
                total_in += used;
3✔
1061
                total_out += produced;
3✔
1062

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

1069
                r = loop_write(out, buf, produced);
2✔
1070
                if (r < 0)
2✔
1071
                        goto cleanup;
×
1072
        }
1073

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

1087
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
21✔
1088
        assert(fdf >= 0);
21✔
1089
        assert(fdt >= 0);
21✔
1090

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

1099
        r = dlopen_zstd();
21✔
1100
        if (r < 0)
21✔
1101
                return r;
1102

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

1112
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
21✔
1113
        if (sym_ZSTD_isError(z))
21✔
1114
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1115

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

1128
                red = loop_read(fdf, in_buff, in_allocsize, true);
198✔
1129
                if (red < 0)
198✔
1130
                        return red;
×
1131
                is_last_chunk = red == 0;
198✔
1132

1133
                in_bytes += (size_t) red;
198✔
1134
                input.size = (size_t) red;
198✔
1135

1136
                for (bool finished = false; !finished;) {
396✔
1137
                        ZSTD_outBuffer output = {
198✔
1138
                                .dst = out_buff,
1139
                                .size = out_allocsize,
1140
                                .pos = 0
1141
                        };
1142
                        size_t remaining;
198✔
1143
                        ssize_t wrote;
198✔
1144

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

1153
                        if (sym_ZSTD_isError(remaining)) {
198✔
1154
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1155
                                return zstd_ret_to_errno(remaining);
×
1156
                        }
1157

1158
                        if (left < output.pos)
198✔
1159
                                return -EFBIG;
1160

1161
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
198✔
1162
                        if (wrote < 0)
198✔
1163
                                return wrote;
1164

1165
                        left -= output.pos;
198✔
1166

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

1175
                /* zstd only returns 0 when the input is completely consumed */
1176
                assert(input.pos == input.size);
198✔
1177
                if (is_last_chunk)
198✔
1178
                        break;
1179
        }
1180

1181
        if (ret_uncompressed_size)
21✔
1182
                *ret_uncompressed_size = in_bytes;
21✔
1183

1184
        if (in_bytes > 0)
21✔
1185
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
21✔
1186
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1187
        else
1188
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes)",
×
1189
                          in_bytes, max_bytes - left);
1190

1191
        return 0;
1192
#else
1193
        return -EPROTONOSUPPORT;
1194
#endif
1195
}
1196

1197
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
13✔
1198
        assert(fdf >= 0);
13✔
1199
        assert(fdt >= 0);
13✔
1200

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

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

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

1236
                red = loop_read(fdf, in_buff, in_allocsize, true);
23✔
1237
                if (red < 0)
23✔
1238
                        return red;
2✔
1239
                if (red == 0)
23✔
1240
                        break;
1241

1242
                in_bytes += (size_t) red;
13✔
1243
                input.size = (size_t) red;
13✔
1244
                input.pos = 0;
13✔
1245

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

1272
                        if (left < output.pos)
48✔
1273
                                return -EFBIG;
2✔
1274

1275
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
47✔
1276
                        if (wrote < 0)
47✔
1277
                                return wrote;
1278

1279
                        left -= output.pos;
46✔
1280
                }
1281
                if (has_error)
11✔
1282
                        break;
1283
        }
1284

1285
        if (in_bytes == 0)
11✔
1286
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1287

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

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

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

1311
        if (endswith(filename, ".lz4"))
10✔
1312
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1313
        else if (endswith(filename, ".xz"))
10✔
1314
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1315
        else if (endswith(filename, ".zst"))
10✔
1316
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1317
        else
1318
                return -EPROTONOSUPPORT;
1319
}
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