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

systemd / systemd / 24165447443

08 Apr 2026 10:44PM UTC coverage: 72.303% (+0.1%) from 72.175%
24165447443

push

github

bluca
compress: write sparse files when decompressing to regular files

Core dumps are often very sparse, containing large zero-filled regions
whose actual disk usage can be significantly reduced by preserving
holes. Previously, decompress_stream() always wrote dense output,
expanding all zero regions into allocated disk blocks.

Each decompression backend (xz, lz4, zstd) now auto-detects whether the
output fd is suitable for sparse writes via a shared should_sparse()
helper. The check requires both S_ISREG (regular file) and !O_APPEND,
since O_APPEND causes write() to ignore the file position set by
lseek(), which would collapse the holes and corrupt the output. For
pipes, sockets, and append-mode files, dense writes are preserved via
loop_write_full() with USEC_INFINITY timeout, matching the original
behavior. After sparse decompression, finalize_sparse() sets the final
file size to account for any trailing holes.

This is transparent to callers — all public signatures are unchanged.
coredumpctl benefits automatically:
- coredumpctl debug: temp file in /var/tmp is now sparse
- coredumpctl dump -o file: output file is now sparse
- coredumpctl dump > file: redirected stdout is now sparse
- coredumpctl dump | ...: pipe output unchanged (dense)
- coredumpctl dump >> file: append mode, falls back to dense

Co-developed-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-developed-by: Codex (GPT-5) <noreply@openai.com>

123 of 132 new or added lines in 2 files covered. (93.18%)

5704 existing lines in 82 files now uncovered.

319660 of 442111 relevant lines covered (72.3%)

1196031.58 hits per line

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

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

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

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

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

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

24
#include "sd-dlopen.h"
25

26
#include "alloc-util.h"
27
#include "bitfield.h"
28
#include "compress.h"
29
#include "dlfcn-util.h"
30
#include "fileio.h"
31
#include "io-util.h"
32
#include "log.h"
33
#include "string-table.h"
34
#include "string-util.h"
35
#include "unaligned.h"
36

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

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

59
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_compressionContext_t, sym_LZ4F_freeCompressionContext, LZ4F_freeCompressionContextp, NULL);
4✔
60
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(LZ4F_decompressionContext_t, sym_LZ4F_freeDecompressionContext, LZ4F_freeDecompressionContextp, NULL);
6✔
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_RENAME(ZSTD_CCtx*, sym_ZSTD_freeCCtx, ZSTD_freeCCtxp, NULL);
28✔
84
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_DCtx*, sym_ZSTD_freeDCtx, ZSTD_freeDCtxp, NULL);
5,199,130✔
85

86
static int zstd_ret_to_errno(size_t ret) {
6✔
87
        switch (sym_ZSTD_getErrorCode(ret)) {
6✔
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,954✔
116
        sym_lzma_end(ls);
2,954✔
117
}
2,954✔
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);
1,015✔
137
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
87✔
138

139
bool compression_supported(Compression c) {
2,685✔
140
        static const unsigned supported =
2,685✔
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,685✔
147
        assert(c < _COMPRESSION_MAX);
2,685✔
148

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

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

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

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

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

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

196
        r = dlopen_lzma();
23✔
197
        if (r < 0)
23✔
198
                return r;
23✔
199

200
        if (level >= 0) {
23✔
201
                r = sym_lzma_lzma_preset(&opt, (uint32_t) level);
3✔
202
                if (r < 0)
203
                        return r;
204
        }
205

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

209
        if (src_size < 80)
23✔
210
                return -ENOBUFS;
211

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

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

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

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

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

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

264
#if HAVE_LZ4
265
        int r;
180✔
266

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

273
        if (src_size < 9)
180✔
274
                return -ENOBUFS;
275

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

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

286
        return 0;
167✔
287
#else
288
        return -EPROTONOSUPPORT;
289
#endif
290
}
291

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

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

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

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

334
#if HAVE_ZSTD
335
        size_t k;
771✔
336
        int r;
771✔
337

338
        r = dlopen_zstd();
771✔
339
        if (r < 0)
771✔
340
                return r;
341

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

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

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

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

365
#if HAVE_XZ
366
        int r;
2,674✔
367

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

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

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

381
        s.next_in = src;
2,674✔
382
        s.avail_in = src_size;
2,674✔
383

384
        s.next_out = *dst;
2,674✔
385
        s.avail_out = space;
2,674✔
386

387
        for (;;) {
2,918✔
388
                size_t used;
2,796✔
389

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

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

401
                used = space - s.avail_out;
122✔
402
                /* Silence static analyzers, space is bounded by allocation size */
403
                assert(space <= SIZE_MAX / 2);
122✔
404
                space = MIN(2 * space, dst_max ?: SIZE_MAX);
122✔
405
                if (!greedy_realloc(dst, space, 1))
122✔
406
                        return -ENOMEM;
407

408
                s.avail_out = space - used;
122✔
409
                s.next_out = *(uint8_t**)dst + used;
122✔
410
        }
411

412
        *dst_size = space - s.avail_out;
2,668✔
413
        return 0;
2,668✔
414
#else
415
        return -EPROTONOSUPPORT;
416
#endif
417
}
418

419
int decompress_blob_lz4(
2,811✔
420
                const void *src,
421
                uint64_t src_size,
422
                void **dst,
423
                size_t* dst_size,
424
                size_t dst_max) {
425

426
        assert(src);
2,811✔
427
        assert(src_size > 0);
2,811✔
428
        assert(dst);
2,811✔
429
        assert(dst_size);
2,811✔
430

431
#if HAVE_LZ4
432
        char* out;
2,811✔
433
        int r, size; /* LZ4 uses int for size */
2,811✔
434

435
        r = dlopen_lz4();
2,811✔
436
        if (r < 0)
2,811✔
437
                return r;
438

439
        if (src_size <= 8)
2,811✔
440
                return -EBADMSG;
441

442
        size = unaligned_read_le64(src);
2,809✔
443
        if (size < 0 || (unsigned) size != unaligned_read_le64(src))
2,809✔
444
                return -EFBIG;
445
        out = greedy_realloc(dst, size, 1);
2,805✔
446
        if (!out)
2,805✔
447
                return -ENOMEM;
448

449
        r = sym_LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
2,805✔
450
        if (r < 0 || r != size)
2,805✔
451
                return -EBADMSG;
452

453
        *dst_size = size;
2,805✔
454
        return 0;
2,805✔
455
#else
456
        return -EPROTONOSUPPORT;
457
#endif
458
}
459

460
int decompress_blob_zstd(
261,873✔
461
                const void *src,
462
                uint64_t src_size,
463
                void **dst,
464
                size_t *dst_size,
465
                size_t dst_max) {
466

467
        assert(src);
261,873✔
468
        assert(src_size > 0);
261,873✔
469
        assert(dst);
261,873✔
470
        assert(dst_size);
261,873✔
471

472
#if HAVE_ZSTD
473
        uint64_t size;
261,873✔
474
        int r;
261,873✔
475

476
        r = dlopen_zstd();
261,873✔
477
        if (r < 0)
261,873✔
478
                return r;
261,873✔
479

480
        size = sym_ZSTD_getFrameContentSize(src, src_size);
261,873✔
481
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
261,873✔
482
                return -EBADMSG;
483

484
        if (dst_max > 0 && size > dst_max)
261,867✔
485
                size = dst_max;
×
486
        if (size > SIZE_MAX)
261,867✔
487
                return -E2BIG;
488

489
        if (!(greedy_realloc(dst, MAX(sym_ZSTD_DStreamOutSize(), size), 1)))
261,867✔
490
                return -ENOMEM;
491

492
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
523,734✔
493
        if (!dctx)
261,867✔
494
                return -ENOMEM;
495

496
        ZSTD_inBuffer input = {
261,867✔
497
                .src = src,
498
                .size = src_size,
499
        };
500
        ZSTD_outBuffer output = {
523,734✔
501
                .dst = *dst,
261,867✔
502
                .size = MALLOC_SIZEOF_SAFE(*dst),
261,867✔
503
        };
504

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

511
        *dst_size = size;
261,867✔
512
        return 0;
261,867✔
513
#else
514
        return -EPROTONOSUPPORT;
515
#endif
516
}
517

518
int decompress_blob(
267,066✔
519
                Compression compression,
520
                const void *src,
521
                uint64_t src_size,
522
                void **dst,
523
                size_t* dst_size,
524
                size_t dst_max) {
525

526
        switch (compression) {
267,066✔
527
        case COMPRESSION_XZ:
2,661✔
528
                return decompress_blob_xz(
2,661✔
529
                                src, src_size,
530
                                dst, dst_size, dst_max);
531
        case COMPRESSION_LZ4:
2,652✔
532
                return decompress_blob_lz4(
2,652✔
533
                                src, src_size,
534
                                dst, dst_size, dst_max);
535
        case COMPRESSION_ZSTD:
261,753✔
536
                return decompress_blob_zstd(
261,753✔
537
                                src, src_size,
538
                                dst, dst_size, dst_max);
539
        default:
540
                return -EPROTONOSUPPORT;
541
        }
542
}
543

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

552
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
553
         * follow the prefix */
554

555
        assert(src);
270✔
556
        assert(src_size > 0);
270✔
557
        assert(buffer);
270✔
558
        assert(prefix);
270✔
559

560
#if HAVE_XZ
561
        int r;
270✔
562

563
        r = dlopen_lzma();
270✔
564
        if (r < 0)
270✔
565
                return r;
270✔
566

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

572
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
573
                return -ENOMEM;
574

575
        size_t allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
576

577
        s.next_in = src;
270✔
578
        s.avail_in = src_size;
270✔
579

580
        s.next_out = *buffer;
270✔
581
        s.avail_out = allocated;
270✔
582

583
        for (;;) {
270✔
584
                ret = sym_lzma_code(&s, LZMA_FINISH);
270✔
585

586
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
270✔
587
                        return -EBADMSG;
588

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

593
                if (ret == LZMA_STREAM_END)
×
594
                        return 0;
595

596
                s.avail_out += allocated;
×
597

598
                if (!(greedy_realloc(buffer, allocated * 2, 1)))
×
599
                        return -ENOMEM;
600

601
                allocated = MALLOC_SIZEOF_SAFE(*buffer);
×
602
                s.next_out = *(uint8_t**)buffer + allocated - s.avail_out;
×
603
        }
604

605
#else
606
        return -EPROTONOSUPPORT;
607
#endif
608
}
609

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

618
        /* Checks whether the decompressed blob starts with the mentioned prefix. The byte extra needs to
619
         * follow the prefix */
620

621
        assert(src);
270✔
622
        assert(src_size > 0);
270✔
623
        assert(buffer);
270✔
624
        assert(prefix);
270✔
625

626
#if HAVE_LZ4
627
        size_t allocated;
270✔
628
        int r;
270✔
629

630
        r = dlopen_lz4();
270✔
631
        if (r < 0)
270✔
632
                return r;
633

634
        if (src_size <= 8)
270✔
635
                return -EBADMSG;
636

637
        if (!(greedy_realloc(buffer, ALIGN_8(prefix_len + 1), 1)))
270✔
638
                return -ENOMEM;
639
        allocated = MALLOC_SIZEOF_SAFE(*buffer);
270✔
640

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

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

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

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

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

672
                if (size < prefix_len + 1)
×
673
                        return 0;
674
        }
675

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

683
int decompress_startswith_zstd(
4,937,247✔
684
                const void *src,
685
                uint64_t src_size,
686
                void **buffer,
687
                const void *prefix,
688
                size_t prefix_len,
689
                uint8_t extra) {
690

691
        assert(src);
4,937,247✔
692
        assert(src_size > 0);
4,937,247✔
693
        assert(buffer);
4,937,247✔
694
        assert(prefix);
4,937,247✔
695

696
#if HAVE_ZSTD
697
        int r;
4,937,247✔
698

699
        r = dlopen_zstd();
4,937,247✔
700
        if (r < 0)
4,937,247✔
701
                return r;
4,937,247✔
702

703
        uint64_t size = sym_ZSTD_getFrameContentSize(src, src_size);
4,937,247✔
704
        if (IN_SET(size, ZSTD_CONTENTSIZE_ERROR, ZSTD_CONTENTSIZE_UNKNOWN))
4,937,247✔
705
                return -EBADMSG;
706

707
        if (size < prefix_len + 1)
4,937,247✔
708
                return 0; /* Decompressed text too short to match the prefix and extra */
709

710
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
9,874,494✔
711
        if (!dctx)
4,937,247✔
712
                return -ENOMEM;
713

714
        if (!(greedy_realloc(buffer, MAX(sym_ZSTD_DStreamOutSize(), prefix_len + 1), 1)))
4,937,247✔
715
                return -ENOMEM;
716

717
        ZSTD_inBuffer input = {
4,937,247✔
718
                .src = src,
719
                .size = src_size,
720
        };
721
        ZSTD_outBuffer output = {
9,874,494✔
722
                .dst = *buffer,
4,937,247✔
723
                .size = MALLOC_SIZEOF_SAFE(*buffer),
4,937,247✔
724
        };
725
        size_t k;
4,937,247✔
726

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

734
        return memcmp(*buffer, prefix, prefix_len) == 0 &&
4,937,247✔
735
                ((const uint8_t*) *buffer)[prefix_len] == extra;
18,910✔
736
#else
737
        return -EPROTONOSUPPORT;
738
#endif
739
}
740

741
int decompress_startswith(
4,936,989✔
742
                Compression compression,
743
                const void *src,
744
                uint64_t src_size,
745
                void **buffer,
746
                const void *prefix,
747
                size_t prefix_len,
748
                uint8_t extra) {
749

750
        switch (compression) {
4,936,989✔
751

752
        case COMPRESSION_XZ:
4✔
753
                return decompress_startswith_xz(
4✔
754
                                src, src_size,
755
                                buffer,
756
                                prefix, prefix_len,
757
                                extra);
758

759
        case COMPRESSION_LZ4:
4✔
760
                return decompress_startswith_lz4(
4✔
761
                                src, src_size,
762
                                buffer,
763
                                prefix, prefix_len,
764
                                extra);
765
        case COMPRESSION_ZSTD:
4,936,981✔
766
                return decompress_startswith_zstd(
4,936,981✔
767
                                src, src_size,
768
                                buffer,
769
                                prefix, prefix_len,
770
                                extra);
771
        default:
772
                return -EBADMSG;
773
        }
774
}
775

776
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
4✔
777
        assert(fdf >= 0);
4✔
778
        assert(fdt >= 0);
4✔
779

780
#if HAVE_XZ
781
        int r;
4✔
782

783
        r = dlopen_lzma();
4✔
784
        if (r < 0)
4✔
785
                return r;
4✔
786

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

794
        uint8_t buf[BUFSIZ], out[BUFSIZ];
795
        lzma_action action = LZMA_RUN;
796
        for (;;) {
48✔
797
                if (s.avail_in == 0 && action == LZMA_RUN) {
48✔
798
                        size_t m = sizeof(buf);
46✔
799
                        ssize_t n;
46✔
800

801
                        if (max_bytes != UINT64_MAX && (uint64_t) m > max_bytes)
46✔
802
                                m = (size_t) max_bytes;
×
803

804
                        n = read(fdf, buf, m);
46✔
805
                        if (n < 0)
46✔
806
                                return -errno;
×
807
                        if (n == 0)
46✔
808
                                action = LZMA_FINISH;
809
                        else {
810
                                s.next_in = buf;
42✔
811
                                s.avail_in = n;
42✔
812

813
                                if (max_bytes != UINT64_MAX) {
42✔
814
                                        assert(max_bytes >= (uint64_t) n);
×
815
                                        max_bytes -= n;
×
816
                                }
817
                        }
818
                }
819

820
                if (s.avail_out == 0) {
48✔
821
                        s.next_out = out;
6✔
822
                        s.avail_out = sizeof(out);
6✔
823
                }
824

825
                ret = sym_lzma_code(&s, action);
48✔
826
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
48✔
827
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
×
828
                                               "Compression failed: code %u",
829
                                               ret);
830

831
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
48✔
832
                        ssize_t n, k;
6✔
833

834
                        n = sizeof(out) - s.avail_out;
6✔
835

836
                        k = loop_write(fdt, out, n);
6✔
837
                        if (k < 0)
6✔
838
                                return k;
839

840
                        if (ret == LZMA_STREAM_END) {
6✔
841
                                if (ret_uncompressed_size)
4✔
842
                                        *ret_uncompressed_size = s.total_in;
4✔
843

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

851
                                return 0;
4✔
852
                        }
853
                }
854
        }
855
#else
856
        return -EPROTONOSUPPORT;
857
#endif
858
}
859

860
#define LZ4_BUFSIZE (512*1024u)
861

862
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
4✔
863

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

876
        r = dlopen_lz4();
4✔
877
        if (r < 0)
4✔
878
                return r;
879

880
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
4✔
881
        if (sym_LZ4F_isError(c))
4✔
882
                return -ENOMEM;
883

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

890
        in_buff = malloc(LZ4_BUFSIZE);
4✔
891
        if (!in_buff)
4✔
892
                return -ENOMEM;
893

894
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
4✔
895
        if (sym_LZ4F_isError(n))
4✔
896
                return -EINVAL;
897

898
        log_debug("Buffer size is %zu bytes, header size %zu bytes.", out_allocsize, n);
4✔
899

900
        for (;;) {
8✔
901
                ssize_t k;
8✔
902

903
                k = loop_read(fdf, in_buff, LZ4_BUFSIZE, true);
8✔
904
                if (k < 0)
8✔
905
                        return k;
×
906
                if (k == 0)
8✔
907
                        break;
908
                n = sym_LZ4F_compressUpdate(ctx, out_buff + offset, out_allocsize - offset,
4✔
909
                                        in_buff, k, NULL);
910
                if (sym_LZ4F_isError(n))
4✔
911
                        return -ENOTRECOVERABLE;
912

913
                total_in += k;
4✔
914
                offset += n;
4✔
915
                total_out += n;
4✔
916

917
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes)
4✔
918
                        return log_debug_errno(SYNTHETIC_ERRNO(EFBIG),
×
919
                                               "Compressed stream longer than %" PRIu64 " bytes", max_bytes);
920

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

929
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
4✔
930
        if (sym_LZ4F_isError(n))
4✔
931
                return -ENOTRECOVERABLE;
932

933
        offset += n;
4✔
934
        total_out += n;
4✔
935
        r = loop_write(fdt, out_buff, offset);
4✔
936
        if (r < 0)
4✔
937
                return r;
938

939
        if (ret_uncompressed_size)
4✔
940
                *ret_uncompressed_size = total_in;
4✔
941

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

949
        return 0;
950
#else
951
        return -EPROTONOSUPPORT;
952
#endif
953
}
954

955
#if HAVE_COMPRESSION
956
/* Determine whether sparse writes should be used for this fd. Sparse writes are only safe on
957
 * regular files without O_APPEND (O_APPEND ignores lseek position, which would collapse holes). */
958
static int should_sparse(int fd) {
28✔
959
        struct stat st;
28✔
960

961
        assert(fd >= 0);
28✔
962

963
        if (fstat(fd, &st) < 0)
28✔
NEW
964
                return -errno;
×
965

966
        int flags = fcntl(fd, F_GETFL);
28✔
967
        if (flags < 0)
28✔
NEW
968
                return -errno;
×
969

970
        return S_ISREG(st.st_mode) && !FLAGS_SET(flags, O_APPEND);
28✔
971
}
972

973
/* After sparse decompression, set the file size to the current position to account for
974
 * trailing holes that sparse_write() created via lseek but never extended the file size for. */
975
static int finalize_sparse(int fd) {
22✔
976
        off_t pos;
22✔
977

978
        assert(fd >= 0);
22✔
979

980
        pos = lseek(fd, 0, SEEK_CUR);
22✔
981
        if (pos < 0)
22✔
NEW
982
                return -errno;
×
983

984
        if (ftruncate(fd, pos) < 0)
22✔
NEW
985
                return -errno;
×
986

987
        return 0;
988
}
989

990
static int maybe_sparse_write(int fd, const void *buf, size_t nbytes, bool sparse) {
294✔
991
        int r;
294✔
992

993
        if (sparse) {
294✔
994
                ssize_t k;
293✔
995

996
                /* Note: sparse_write() does not retry on EINTR and converts short writes to -EIO.
997
                 * This is fine here since sparse mode is only used on regular files, where short
998
                 * writes and EINTR are not expected in practice. */
999
                k = sparse_write(fd, buf, nbytes, 64);
293✔
1000
                if (k < 0)
293✔
NEW
1001
                        return (int) k;
×
1002
        } else {
1003
                r = loop_write_full(fd, buf, nbytes, USEC_INFINITY);
1✔
1004
                if (r < 0)
1✔
1005
                        return r;
1✔
1006
        }
1007

1008
        return 0;
1009
}
1010
#endif
1011

1012
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
6✔
1013
        assert(fdf >= 0);
6✔
1014
        assert(fdt >= 0);
6✔
1015

1016
#if HAVE_XZ
1017
        bool sparse = should_sparse(fdt) > 0;
6✔
1018
        int r;
6✔
1019

1020
        r = dlopen_lzma();
6✔
1021
        if (r < 0)
6✔
1022
                return r;
6✔
1023

1024
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
6✔
1025
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
6✔
1026
        if (ret != LZMA_OK)
6✔
1027
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEM),
×
1028
                                       "Failed to initialize XZ decoder: code %u",
1029
                                       ret);
1030

1031
        uint8_t buf[BUFSIZ], out[BUFSIZ];
1032
        lzma_action action = LZMA_RUN;
1033
        for (;;) {
55✔
1034
                if (s.avail_in == 0 && action == LZMA_RUN) {
55✔
1035
                        ssize_t n;
10✔
1036

1037
                        n = read(fdf, buf, sizeof(buf));
10✔
1038
                        if (n < 0)
10✔
1039
                                return -errno;
×
1040
                        if (n == 0)
10✔
1041
                                action = LZMA_FINISH;
1042
                        else {
1043
                                s.next_in = buf;
10✔
1044
                                s.avail_in = n;
10✔
1045
                        }
1046
                }
1047

1048
                if (s.avail_out == 0) {
55✔
1049
                        s.next_out = out;
51✔
1050
                        s.avail_out = sizeof(out);
51✔
1051
                }
1052

1053
                ret = sym_lzma_code(&s, action);
55✔
1054
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
55✔
1055
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1✔
1056
                                               "Decompression failed: code %u",
1057
                                               ret);
1058

1059
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
54✔
1060
                        ssize_t n, k;
50✔
1061

1062
                        n = sizeof(out) - s.avail_out;
50✔
1063

1064
                        if (max_bytes != UINT64_MAX) {
50✔
1065
                                if (max_bytes < (uint64_t) n)
50✔
1066
                                        return -EFBIG;
1067

1068
                                max_bytes -= n;
49✔
1069
                        }
1070

1071
                        k = maybe_sparse_write(fdt, out, n, sparse);
49✔
1072
                        if (k < 0)
49✔
1073
                                return k;
1074

1075
                        if (ret == LZMA_STREAM_END) {
49✔
1076
                                if (s.total_in == 0)
4✔
1077
                                        log_debug("XZ decompression finished (no input data)");
×
1078
                                else
1079
                                        log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
4✔
1080
                                                  s.total_in, s.total_out,
1081
                                                  (double) s.total_out / s.total_in * 100);
1082

1083
                                return sparse ? finalize_sparse(fdt) : 0;
4✔
1084
                        }
1085
                }
1086
        }
1087
#else
1088
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1089
                               "Cannot decompress file. Compiled without XZ support.");
1090
#endif
1091
}
1092

1093
int decompress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) {
6✔
1094
#if HAVE_LZ4
1095
        size_t c;
6✔
1096
        _cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
×
1097
        _cleanup_free_ char *buf = NULL;
6✔
1098
        char *src;
6✔
1099
        struct stat st;
6✔
1100
        bool sparse = should_sparse(fdt) > 0;
6✔
1101
        int r;
6✔
1102
        size_t total_in = 0, total_out = 0;
6✔
1103

1104
        r = dlopen_lz4();
6✔
1105
        if (r < 0)
6✔
1106
                return r;
1107

1108
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
6✔
1109
        if (sym_LZ4F_isError(c))
6✔
1110
                return -ENOMEM;
1111

1112
        if (fstat(fdf, &st) < 0)
6✔
1113
                return log_debug_errno(errno, "fstat() failed: %m");
×
1114

1115
        if (file_offset_beyond_memory_size(st.st_size))
6✔
1116
                return -EFBIG;
1117

1118
        buf = malloc(LZ4_BUFSIZE);
6✔
1119
        if (!buf)
6✔
1120
                return -ENOMEM;
1121

1122
        src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
6✔
1123
        if (src == MAP_FAILED)
6✔
1124
                return -errno;
×
1125

1126
        while (total_in < (size_t) st.st_size) {
11✔
1127
                size_t produced = LZ4_BUFSIZE;
6✔
1128
                size_t used = st.st_size - total_in;
6✔
1129

1130
                c = sym_LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
6✔
1131
                if (sym_LZ4F_isError(c)) {
6✔
1132
                        r = -EBADMSG;
×
1133
                        goto cleanup;
1✔
1134
                }
1135

1136
                total_in += used;
6✔
1137
                total_out += produced;
6✔
1138

1139
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes) {
6✔
1140
                        log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
1✔
1141
                        r = -EFBIG;
1✔
1142
                        goto cleanup;
1✔
1143
                }
1144

1145
                r = maybe_sparse_write(fdt, buf, produced, sparse);
5✔
1146
                if (r < 0)
5✔
1147
                        goto cleanup;
×
1148
        }
1149

1150
        if (total_in == 0)
5✔
1151
                log_debug("LZ4 decompression finished (no input data)");
×
1152
        else
1153
                log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
5✔
1154
                          total_in, total_out,
1155
                          (double) total_out / total_in * 100);
1156
        r = sparse ? finalize_sparse(fdt) : 0;
5✔
1157
 cleanup:
6✔
1158
        munmap(src, st.st_size);
6✔
1159
        return r;
6✔
1160
#else
1161
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1162
                               "Cannot decompress file. Compiled without LZ4 support.");
1163
#endif
1164
}
1165

1166
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
28✔
1167
        assert(fdf >= 0);
28✔
1168
        assert(fdt >= 0);
28✔
1169

1170
#if HAVE_ZSTD
1171
        _cleanup_(ZSTD_freeCCtxp) ZSTD_CCtx *cctx = NULL;
×
1172
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
28✔
1173
        size_t in_allocsize, out_allocsize;
28✔
1174
        size_t z;
28✔
1175
        uint64_t left = max_bytes, in_bytes = 0;
28✔
1176
        int r;
28✔
1177

1178
        r = dlopen_zstd();
28✔
1179
        if (r < 0)
28✔
1180
                return r;
1181

1182
        /* Create the context and buffers */
1183
        in_allocsize = sym_ZSTD_CStreamInSize();
28✔
1184
        out_allocsize = sym_ZSTD_CStreamOutSize();
28✔
1185
        in_buff = malloc(in_allocsize);
28✔
1186
        out_buff = malloc(out_allocsize);
28✔
1187
        cctx = sym_ZSTD_createCCtx();
28✔
1188
        if (!cctx || !out_buff || !in_buff)
28✔
1189
                return -ENOMEM;
1190

1191
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
28✔
1192
        if (sym_ZSTD_isError(z))
28✔
1193
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1194

1195
        /* This loop read from the input file, compresses that entire chunk,
1196
         * and writes all output produced to the output file.
1197
         */
1198
        for (;;) {
589✔
1199
                bool is_last_chunk;
617✔
1200
                ZSTD_inBuffer input = {
617✔
1201
                        .src = in_buff,
1202
                        .size = 0,
1203
                        .pos = 0
1204
                };
1205
                ssize_t red;
617✔
1206

1207
                red = loop_read(fdf, in_buff, in_allocsize, true);
617✔
1208
                if (red < 0)
617✔
1209
                        return red;
×
1210
                is_last_chunk = red == 0;
617✔
1211

1212
                in_bytes += (size_t) red;
617✔
1213
                input.size = (size_t) red;
617✔
1214

1215
                for (bool finished = false; !finished;) {
1,234✔
1216
                        ZSTD_outBuffer output = {
617✔
1217
                                .dst = out_buff,
1218
                                .size = out_allocsize,
1219
                                .pos = 0
1220
                        };
1221
                        size_t remaining;
617✔
1222
                        ssize_t wrote;
617✔
1223

1224
                        /* Compress into the output buffer and write all of the
1225
                         * output to the file so we can reuse the buffer next
1226
                         * iteration.
1227
                         */
1228
                        remaining = sym_ZSTD_compressStream2(
1,206✔
1229
                                cctx, &output, &input,
1230
                                is_last_chunk ? ZSTD_e_end : ZSTD_e_continue);
1231

1232
                        if (sym_ZSTD_isError(remaining)) {
617✔
1233
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1234
                                return zstd_ret_to_errno(remaining);
×
1235
                        }
1236

1237
                        if (left < output.pos)
617✔
1238
                                return -EFBIG;
1239

1240
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
617✔
1241
                        if (wrote < 0)
617✔
1242
                                return wrote;
1243

1244
                        left -= output.pos;
617✔
1245

1246
                        /* If we're on the last chunk we're finished when zstd
1247
                         * returns 0, which means its consumed all the input AND
1248
                         * finished the frame. Otherwise, we're finished when
1249
                         * we've consumed all the input.
1250
                         */
1251
                        finished = is_last_chunk ? (remaining == 0) : (input.pos == input.size);
617✔
1252
                }
1253

1254
                /* zstd only returns 0 when the input is completely consumed */
1255
                assert(input.pos == input.size);
617✔
1256
                if (is_last_chunk)
617✔
1257
                        break;
1258
        }
1259

1260
        if (ret_uncompressed_size)
28✔
1261
                *ret_uncompressed_size = in_bytes;
28✔
1262

1263
        if (in_bytes == 0)
28✔
1264
                log_debug("ZSTD compression finished (no input data)");
×
1265
        else
1266
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
28✔
1267
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1268

1269
        return 0;
1270
#else
1271
        return -EPROTONOSUPPORT;
1272
#endif
1273
}
1274

1275
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
16✔
1276
        assert(fdf >= 0);
16✔
1277
        assert(fdt >= 0);
16✔
1278

1279
#if HAVE_ZSTD
1280
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = NULL;
×
1281
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
16✔
1282
        bool sparse = should_sparse(fdt) > 0;
16✔
1283
        size_t in_allocsize, out_allocsize;
16✔
1284
        size_t last_result = 0;
16✔
1285
        uint64_t left = max_bytes, in_bytes = 0;
16✔
1286
        int r;
16✔
1287

1288
        r = dlopen_zstd();
16✔
1289
        if (r < 0)
16✔
1290
                return r;
1291
        /* Create the context and buffers */
1292
        in_allocsize = sym_ZSTD_DStreamInSize();
16✔
1293
        out_allocsize = sym_ZSTD_DStreamOutSize();
16✔
1294
        in_buff = malloc(in_allocsize);
16✔
1295
        out_buff = malloc(out_allocsize);
16✔
1296
        dctx = sym_ZSTD_createDCtx();
16✔
1297
        if (!dctx || !out_buff || !in_buff)
16✔
1298
                return -ENOMEM;
1299

1300
        /* This loop assumes that the input file is one or more concatenated
1301
         * zstd streams. This example won't work if there is trailing non-zstd
1302
         * data at the end, but streaming decompression in general handles this
1303
         * case. ZSTD_decompressStream() returns 0 exactly when the frame is
1304
         * completed, and doesn't consume input after the frame.
1305
         */
1306
        for (;;) {
78✔
1307
                bool has_error = false;
47✔
1308
                ZSTD_inBuffer input = {
47✔
1309
                        .src = in_buff,
1310
                        .size = 0,
1311
                        .pos = 0
1312
                };
1313
                ssize_t red;
47✔
1314

1315
                red = loop_read(fdf, in_buff, in_allocsize, true);
47✔
1316
                if (red < 0)
47✔
1317
                        return red;
2✔
1318
                if (red == 0)
47✔
1319
                        break;
1320

1321
                in_bytes += (size_t) red;
34✔
1322
                input.size = (size_t) red;
34✔
1323
                input.pos = 0;
34✔
1324

1325
                /* Given a valid frame, zstd won't consume the last byte of the
1326
                 * frame until it has flushed all of the decompressed data of
1327
                 * the frame. So input.pos < input.size means frame is not done
1328
                 * or there is still output available.
1329
                 */
1330
                while (input.pos < input.size) {
273✔
1331
                        ZSTD_outBuffer output = {
242✔
1332
                                .dst = out_buff,
1333
                                .size = out_allocsize,
1334
                                .pos = 0
1335
                        };
1336
                        ssize_t wrote;
242✔
1337
                        /* The return code is zero if the frame is complete, but
1338
                         * there may be multiple frames concatenated together.
1339
                         * Zstd will automatically reset the context when a
1340
                         * frame is complete. Still, calling ZSTD_DCtx_reset()
1341
                         * can be useful to reset the context to a clean state,
1342
                         * for instance if the last decompression call returned
1343
                         * an error.
1344
                         */
1345
                        last_result = sym_ZSTD_decompressStream(dctx, &output, &input);
242✔
1346
                        if (sym_ZSTD_isError(last_result)) {
242✔
1347
                                has_error = true;
1✔
1348
                                break;
1✔
1349
                        }
1350

1351
                        if (left < output.pos)
241✔
1352
                                return -EFBIG;
2✔
1353

1354
                        wrote = maybe_sparse_write(fdt, output.dst, output.pos, sparse);
240✔
1355
                        if (wrote < 0)
240✔
1356
                                return wrote;
1357

1358
                        left -= output.pos;
239✔
1359
                }
1360
                if (has_error)
32✔
1361
                        break;
1362
        }
1363

1364
        if (in_bytes == 0)
14✔
1365
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1366

1367
        if (last_result != 0) {
14✔
1368
                /* The last return value from ZSTD_decompressStream did not end
1369
                 * on a frame, but we reached the end of the file! We assume
1370
                 * this is an error, and the input was truncated.
1371
                 */
1372
                log_debug("ZSTD decoder failed: %s", sym_ZSTD_getErrorName(last_result));
1✔
1373
                return zstd_ret_to_errno(last_result);
1✔
1374
        }
1375

1376
        if (in_bytes == 0)
13✔
1377
                log_debug("ZSTD decompression finished (no input data)");
1378
        else
1379
                log_debug("ZSTD decompression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
13✔
1380
                          in_bytes,
1381
                          max_bytes - left,
1382
                          (double) (max_bytes - left) / in_bytes * 100);
1383
        return sparse ? finalize_sparse(fdt) : 0;
13✔
1384
#else
1385
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1386
                               "Cannot decompress file. Compiled without ZSTD support.");
1387
#endif
1388
}
1389

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

1392
        if (endswith(filename, ".lz4"))
10✔
1393
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1394
        if (endswith(filename, ".xz"))
10✔
1395
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1396
        if (endswith(filename, ".zst"))
10✔
1397
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1398

1399
        return -EPROTONOSUPPORT;
1400
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc