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

systemd / systemd / 22810165351

07 Mar 2026 03:22PM UTC coverage: 72.6% (-0.03%) from 72.63%
22810165351

push

github

web-flow
user-record: fix segfault when processing matchHostname field (#40979)

Fix a typo which causes a segfault when processing a user record
with `matchHostname` when it's an array instead of a simple string:

```
$ echo '{"userName":"crashhostarray","perMachine":[{"matchHostname":["host1","host2"],"locked":false}]}' | userdbctl -F -
Segmentation fault         (core dumped)

$ coredumpctl info
...
       Message: Process 1172301 (userdbctl) of user 1000 dumped core.

                Module libz.so.1 from rpm zlib-ng-2.3.3-1.fc43.x86_64
                Module libcrypto.so.3 from rpm openssl-3.5.4-2.fc43.x86_64
                Stack trace of thread 1172301:
                #0  0x00007fded7b3a656 __strcmp_evex (libc.so.6 + 0x159656)
                #1  0x00007fded7e95397 per_machine_hostname_match (libsystemd-shared-260.so + 0x295397)
                #2  0x00007fded7e955b5 per_machine_match (libsystemd-shared-260.so + 0x2955b5)
                #3  0x00007fded7e957c6 dispatch_per_machine (libsystemd-shared-260.so + 0x2957c6)
                #4  0x00007fded7e96c97 user_record_load (libsystemd-shared-260.so + 0x296c97)
                #5  0x000000000040572d display_user (/home/fsumsal/repos/@systemd/systemd/build/userdbctl + 0x572d)
                #6  0x00007fded7ea9727 dispatch_verb (libsystemd-shared-260.so + 0x2a9727)
                #7  0x000000000041077c run (/home/fsumsal/repos/@systemd/systemd/build/userdbctl + 0x1077c)
                #8  0x00000000004107ce main (/home/fsumsal/repos/@systemd/systemd/build/userdbctl + 0x107ce)
                #9  0x00007fded79e45b5 __libc_start_call_main (libc.so.6 + 0x35b5)
                #10 0x00007fded79e4668 __libc_start_main@@GLIBC_2.34 (libc.so.6 + 0x3668)
                #11 0x00000000004038d5 _start (/home/fsumsal/repos/@systemd/systemd/build/userdbctl + 0x38d5)
                ELF object binary architecture: AMD x86-64
```

5 of 35 new or added lines in 2 files covered. (14.29%)

340 existing lines in 46 files now uncovered.

316214 of 435555 relevant lines covered (72.6%)

1144732.27 hits per line

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

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

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

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

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

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

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

34
#if HAVE_LZ4
35
static void *lz4_dl = NULL;
36

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

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

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

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

80
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_CCtx*, sym_ZSTD_freeCCtx, ZSTD_freeCCtxp, NULL);
25✔
81
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_RENAME(ZSTD_DCtx*, sym_ZSTD_freeDCtx, ZSTD_freeDCtxp, NULL);
4,980,058✔
82

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

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

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

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

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

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

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

133
DEFINE_STRING_TABLE_LOOKUP(compression, Compression);
1,019✔
134
DEFINE_STRING_TABLE_LOOKUP(compression_lowercase, Compression);
67✔
135

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

143
        assert(c >= 0);
2,671✔
144
        assert(c < _COMPRESSION_MAX);
2,671✔
145

146
        return BIT_SET(supported, c);
2,671✔
147
}
148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

259
#if HAVE_LZ4
260
        int r;
138✔
261

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

268
        if (src_size < 9)
138✔
269
                return -ENOBUFS;
270

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

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

281
        return 0;
129✔
282
#else
283
        return -EPROTONOSUPPORT;
284
#endif
285
}
286

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

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

318
int compress_blob_zstd(
771✔
319
                const void *src, uint64_t src_size,
320
                void *dst, size_t dst_alloc_size, size_t *dst_size, int level) {
321

322
        assert(src);
771✔
323
        assert(src_size > 0);
771✔
324
        assert(dst);
771✔
325
        assert(dst_alloc_size > 0);
771✔
326
        assert(dst_size);
771✔
327

328
#if HAVE_ZSTD
329
        size_t k;
771✔
330
        int r;
771✔
331

332
        r = dlopen_zstd();
771✔
333
        if (r < 0)
771✔
334
                return r;
335

336
        k = sym_ZSTD_compress(dst, dst_alloc_size, src, src_size, level < 0 ? 0 : level);
771✔
337
        if (sym_ZSTD_isError(k))
771✔
338
                return zstd_ret_to_errno(k);
4✔
339

340
        *dst_size = k;
767✔
341
        return 0;
767✔
342
#else
343
        return -EPROTONOSUPPORT;
344
#endif
345
}
346

347
int decompress_blob_xz(
2,652✔
348
                const void *src,
349
                uint64_t src_size,
350
                void **dst,
351
                size_t* dst_size,
352
                size_t dst_max) {
353

354
        assert(src);
2,652✔
355
        assert(src_size > 0);
2,652✔
356
        assert(dst);
2,652✔
357
        assert(dst_size);
2,652✔
358

359
#if HAVE_XZ
360
        int r;
2,652✔
361

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

366
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
2,652✔
367
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
2,652✔
368
        if (ret != LZMA_OK)
2,652✔
369
                return -ENOMEM;
370

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

375
        s.next_in = src;
2,652✔
376
        s.avail_in = src_size;
2,652✔
377

378
        s.next_out = *dst;
2,652✔
379
        s.avail_out = space;
2,652✔
380

381
        for (;;) {
2,838✔
382
                size_t used;
2,745✔
383

384
                ret = sym_lzma_code(&s, LZMA_FINISH);
2,745✔
385
                if (ret == LZMA_STREAM_END)
2,745✔
386
                        break;
387
                if (ret != LZMA_OK)
99✔
388
                        return -ENOMEM;
389

390
                if (dst_max > 0 && (space - s.avail_out) >= dst_max)
93✔
391
                        break;
392
                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,646✔
405
        return 0;
2,646✔
406
#else
407
        return -EPROTONOSUPPORT;
408
#endif
409
}
410

411
int decompress_blob_lz4(
2,779✔
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,779✔
419
        assert(src_size > 0);
2,779✔
420
        assert(dst);
2,779✔
421
        assert(dst_size);
2,779✔
422

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

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

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

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

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

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

452
int decompress_blob_zstd(
241,390✔
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);
241,390✔
460
        assert(src_size > 0);
241,390✔
461
        assert(dst);
241,390✔
462
        assert(dst_size);
241,390✔
463

464
#if HAVE_ZSTD
465
        uint64_t size;
241,390✔
466
        int r;
241,390✔
467

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

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

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

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

484
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
482,768✔
485
        if (!dctx)
241,384✔
486
                return -ENOMEM;
487

488
        ZSTD_inBuffer input = {
241,384✔
489
                .src = src,
490
                .size = src_size,
491
        };
492
        ZSTD_outBuffer output = {
482,768✔
493
                .dst = *dst,
241,384✔
494
                .size = MALLOC_SIZEOF_SAFE(*dst),
241,384✔
495
        };
496

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

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

510
int decompress_blob(
246,570✔
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
        switch (compression) {
246,570✔
519
        case COMPRESSION_XZ:
2,641✔
520
                return decompress_blob_xz(
2,641✔
521
                                src, src_size,
522
                                dst, dst_size, dst_max);
523
        case COMPRESSION_LZ4:
2,654✔
524
                return decompress_blob_lz4(
2,654✔
525
                                src, src_size,
526
                                dst, dst_size, dst_max);
527
        case COMPRESSION_ZSTD:
241,275✔
528
                return decompress_blob_zstd(
241,275✔
529
                                src, src_size,
530
                                dst, dst_size, dst_max);
531
        default:
532
                return -EPROTONOSUPPORT;
533
        }
534
}
535

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

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

547
        assert(src);
270✔
548
        assert(src_size > 0);
270✔
549
        assert(buffer);
270✔
550
        assert(prefix);
270✔
551

552
#if HAVE_XZ
553
        int r;
270✔
554

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

559
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
270✔
560
        lzma_ret 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
        size_t 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(
4,738,661✔
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);
4,738,661✔
684
        assert(src_size > 0);
4,738,661✔
685
        assert(buffer);
4,738,661✔
686
        assert(prefix);
4,738,661✔
687

688
#if HAVE_ZSTD
689
        int r;
4,738,661✔
690

691
        r = dlopen_zstd();
4,738,661✔
692
        if (r < 0)
4,738,661✔
693
                return r;
4,738,661✔
694

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

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

702
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = sym_ZSTD_createDCtx();
9,477,322✔
703
        if (!dctx)
4,738,661✔
704
                return -ENOMEM;
705

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

709
        ZSTD_inBuffer input = {
4,738,661✔
710
                .src = src,
711
                .size = src_size,
712
        };
713
        ZSTD_outBuffer output = {
9,477,322✔
714
                .dst = *buffer,
4,738,661✔
715
                .size = MALLOC_SIZEOF_SAFE(*buffer),
4,738,661✔
716
        };
717
        size_t k;
4,738,661✔
718

719
        k = sym_ZSTD_decompressStream(dctx, &output, &input);
4,738,661✔
720
        if (sym_ZSTD_isError(k)) {
4,738,661✔
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);
4,738,661✔
725

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

733
int decompress_startswith(
4,738,403✔
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
        switch (compression) {
4,738,403✔
743

744
        case COMPRESSION_XZ:
4✔
745
                return decompress_startswith_xz(
4✔
746
                                src, src_size,
747
                                buffer,
748
                                prefix, prefix_len,
749
                                extra);
750

751
        case COMPRESSION_LZ4:
4✔
752
                return decompress_startswith_lz4(
4✔
753
                                src, src_size,
754
                                buffer,
755
                                prefix, prefix_len,
756
                                extra);
757
        case COMPRESSION_ZSTD:
4,738,395✔
758
                return decompress_startswith_zstd(
4,738,395✔
759
                                src, src_size,
760
                                buffer,
761
                                prefix, prefix_len,
762
                                extra);
763
        default:
764
                return -EBADMSG;
765
        }
766
}
767

768
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
769
        assert(fdf >= 0);
1✔
770
        assert(fdt >= 0);
1✔
771

772
#if HAVE_XZ
773
        int r;
1✔
774

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

779
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
1✔
780
        lzma_ret 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
        uint8_t buf[BUFSIZ], out[BUFSIZ];
787
        lzma_action action = LZMA_RUN;
788
        for (;;) {
8✔
789
                if (s.avail_in == 0 && action == LZMA_RUN) {
8✔
790
                        size_t m = sizeof(buf);
7✔
791
                        ssize_t n;
7✔
792

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

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

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

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

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

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

826
                        n = sizeof(out) - s.avail_out;
2✔
827

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

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

836
                                if (s.total_in == 0)
1✔
837
                                        log_debug("XZ compression finished (no input data)");
×
838
                                else
839
                                        log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
1✔
840
                                                  s.total_in, s.total_out,
841
                                                  (double) s.total_out / s.total_in * 100);
842

843
                                return 0;
1✔
844
                        }
845
                }
846
        }
847
#else
848
        return -EPROTONOSUPPORT;
849
#endif
850
}
851

852
#define LZ4_BUFSIZE (512*1024u)
853

854
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
1✔
855

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

868
        r = dlopen_lz4();
1✔
869
        if (r < 0)
1✔
870
                return r;
871

872
        c = sym_LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1✔
873
        if (sym_LZ4F_isError(c))
1✔
874
                return -ENOMEM;
875

876
        frame_size = sym_LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
1✔
877
        out_allocsize = frame_size + 64*1024; /* add some space for header and trailer */
1✔
878
        out_buff = malloc(out_allocsize);
1✔
879
        if (!out_buff)
1✔
880
                return -ENOMEM;
881

882
        in_buff = malloc(LZ4_BUFSIZE);
1✔
883
        if (!in_buff)
1✔
884
                return -ENOMEM;
885

886
        n = offset = total_out = sym_LZ4F_compressBegin(ctx, out_buff, out_allocsize, &preferences);
1✔
887
        if (sym_LZ4F_isError(n))
1✔
888
                return -EINVAL;
889

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

892
        for (;;) {
2✔
893
                ssize_t k;
2✔
894

895
                k = loop_read(fdf, in_buff, LZ4_BUFSIZE, true);
2✔
896
                if (k < 0)
2✔
897
                        return k;
×
898
                if (k == 0)
2✔
899
                        break;
900
                n = sym_LZ4F_compressUpdate(ctx, out_buff + offset, out_allocsize - offset,
1✔
901
                                        in_buff, k, NULL);
902
                if (sym_LZ4F_isError(n))
1✔
903
                        return -ENOTRECOVERABLE;
904

905
                total_in += k;
1✔
906
                offset += n;
1✔
907
                total_out += n;
1✔
908

909
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes)
1✔
910
                        return log_debug_errno(SYNTHETIC_ERRNO(EFBIG),
×
911
                                               "Compressed stream longer than %" PRIu64 " bytes", max_bytes);
912

913
                if (out_allocsize - offset < frame_size + 4) {
1✔
914
                        k = loop_write(fdt, out_buff, offset);
×
915
                        if (k < 0)
×
916
                                return k;
917
                        offset = 0;
918
                }
919
        }
920

921
        n = sym_LZ4F_compressEnd(ctx, out_buff + offset, out_allocsize - offset, NULL);
1✔
922
        if (sym_LZ4F_isError(n))
1✔
923
                return -ENOTRECOVERABLE;
924

925
        offset += n;
1✔
926
        total_out += n;
1✔
927
        r = loop_write(fdt, out_buff, offset);
1✔
928
        if (r < 0)
1✔
929
                return r;
930

931
        if (ret_uncompressed_size)
1✔
932
                *ret_uncompressed_size = total_in;
1✔
933

934
        if (total_in == 0)
1✔
935
                log_debug("LZ4 compression finished (no input data)");
×
936
        else
937
                log_debug("LZ4 compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
1✔
938
                          total_in, total_out,
939
                          (double) total_out / total_in * 100);
940

941
        return 0;
942
#else
943
        return -EPROTONOSUPPORT;
944
#endif
945
}
946

947
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
3✔
948
        assert(fdf >= 0);
3✔
949
        assert(fdt >= 0);
3✔
950

951
#if HAVE_XZ
952
        int r;
3✔
953

954
        r = dlopen_lzma();
3✔
955
        if (r < 0)
3✔
956
                return r;
3✔
957

958
        _cleanup_(lzma_end_wrapper) lzma_stream s = LZMA_STREAM_INIT;
3✔
959
        lzma_ret ret = sym_lzma_stream_decoder(&s, UINT64_MAX, 0);
3✔
960
        if (ret != LZMA_OK)
3✔
961
                return log_debug_errno(SYNTHETIC_ERRNO(ENOMEM),
×
962
                                       "Failed to initialize XZ decoder: code %u",
963
                                       ret);
964

965
        uint8_t buf[BUFSIZ], out[BUFSIZ];
966
        lzma_action action = LZMA_RUN;
967
        for (;;) {
15✔
968
                if (s.avail_in == 0 && action == LZMA_RUN) {
15✔
969
                        ssize_t n;
5✔
970

971
                        n = read(fdf, buf, sizeof(buf));
5✔
972
                        if (n < 0)
5✔
973
                                return -errno;
×
974
                        if (n == 0)
5✔
975
                                action = LZMA_FINISH;
976
                        else {
977
                                s.next_in = buf;
5✔
978
                                s.avail_in = n;
5✔
979
                        }
980
                }
981

982
                if (s.avail_out == 0) {
15✔
983
                        s.next_out = out;
13✔
984
                        s.avail_out = sizeof(out);
13✔
985
                }
986

987
                ret = sym_lzma_code(&s, action);
15✔
988
                if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
15✔
989
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1✔
990
                                               "Decompression failed: code %u",
991
                                               ret);
992

993
                if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
14✔
994
                        ssize_t n, k;
12✔
995

996
                        n = sizeof(out) - s.avail_out;
12✔
997

998
                        if (max_bytes != UINT64_MAX) {
12✔
999
                                if (max_bytes < (uint64_t) n)
12✔
1000
                                        return -EFBIG;
1001

1002
                                max_bytes -= n;
11✔
1003
                        }
1004

1005
                        k = loop_write(fdt, out, n);
11✔
1006
                        if (k < 0)
11✔
1007
                                return k;
1008

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

1017
                                return 0;
1✔
1018
                        }
1019
                }
1020
        }
1021
#else
1022
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT),
1023
                               "Cannot decompress file. Compiled without XZ support.");
1024
#endif
1025
}
1026

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

1037
        r = dlopen_lz4();
3✔
1038
        if (r < 0)
3✔
1039
                return r;
1040

1041
        c = sym_LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
3✔
1042
        if (sym_LZ4F_isError(c))
3✔
1043
                return -ENOMEM;
1044

1045
        if (fstat(fdf, &st) < 0)
3✔
1046
                return log_debug_errno(errno, "fstat() failed: %m");
×
1047

1048
        if (file_offset_beyond_memory_size(st.st_size))
3✔
1049
                return -EFBIG;
1050

1051
        buf = malloc(LZ4_BUFSIZE);
3✔
1052
        if (!buf)
3✔
1053
                return -ENOMEM;
1054

1055
        src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
3✔
1056
        if (src == MAP_FAILED)
3✔
1057
                return -errno;
×
1058

1059
        while (total_in < (size_t) st.st_size) {
5✔
1060
                size_t produced = LZ4_BUFSIZE;
3✔
1061
                size_t used = st.st_size - total_in;
3✔
1062

1063
                c = sym_LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
3✔
1064
                if (sym_LZ4F_isError(c)) {
3✔
1065
                        r = -EBADMSG;
×
1066
                        goto cleanup;
1✔
1067
                }
1068

1069
                total_in += used;
3✔
1070
                total_out += produced;
3✔
1071

1072
                if (max_bytes != UINT64_MAX && total_out > (size_t) max_bytes) {
3✔
1073
                        log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
1✔
1074
                        r = -EFBIG;
1✔
1075
                        goto cleanup;
1✔
1076
                }
1077

1078
                r = loop_write(fdt, buf, produced);
2✔
1079
                if (r < 0)
2✔
1080
                        goto cleanup;
×
1081
        }
1082

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

1099
int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) {
25✔
1100
        assert(fdf >= 0);
25✔
1101
        assert(fdt >= 0);
25✔
1102

1103
#if HAVE_ZSTD
1104
        _cleanup_(ZSTD_freeCCtxp) ZSTD_CCtx *cctx = NULL;
×
1105
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
25✔
1106
        size_t in_allocsize, out_allocsize;
25✔
1107
        size_t z;
25✔
1108
        uint64_t left = max_bytes, in_bytes = 0;
25✔
1109
        int r;
25✔
1110

1111
        r = dlopen_zstd();
25✔
1112
        if (r < 0)
25✔
1113
                return r;
1114

1115
        /* Create the context and buffers */
1116
        in_allocsize = sym_ZSTD_CStreamInSize();
25✔
1117
        out_allocsize = sym_ZSTD_CStreamOutSize();
25✔
1118
        in_buff = malloc(in_allocsize);
25✔
1119
        out_buff = malloc(out_allocsize);
25✔
1120
        cctx = sym_ZSTD_createCCtx();
25✔
1121
        if (!cctx || !out_buff || !in_buff)
25✔
1122
                return -ENOMEM;
1123

1124
        z = sym_ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1);
25✔
1125
        if (sym_ZSTD_isError(z))
25✔
1126
                log_debug("Failed to enable ZSTD checksum, ignoring: %s", sym_ZSTD_getErrorName(z));
×
1127

1128
        /* This loop read from the input file, compresses that entire chunk,
1129
         * and writes all output produced to the output file.
1130
         */
1131
        for (;;) {
525✔
1132
                bool is_last_chunk;
550✔
1133
                ZSTD_inBuffer input = {
550✔
1134
                        .src = in_buff,
1135
                        .size = 0,
1136
                        .pos = 0
1137
                };
1138
                ssize_t red;
550✔
1139

1140
                red = loop_read(fdf, in_buff, in_allocsize, true);
550✔
1141
                if (red < 0)
550✔
1142
                        return red;
×
1143
                is_last_chunk = red == 0;
550✔
1144

1145
                in_bytes += (size_t) red;
550✔
1146
                input.size = (size_t) red;
550✔
1147

1148
                for (bool finished = false; !finished;) {
1,100✔
1149
                        ZSTD_outBuffer output = {
550✔
1150
                                .dst = out_buff,
1151
                                .size = out_allocsize,
1152
                                .pos = 0
1153
                        };
1154
                        size_t remaining;
550✔
1155
                        ssize_t wrote;
550✔
1156

1157
                        /* Compress into the output buffer and write all of the
1158
                         * output to the file so we can reuse the buffer next
1159
                         * iteration.
1160
                         */
1161
                        remaining = sym_ZSTD_compressStream2(
1,075✔
1162
                                cctx, &output, &input,
1163
                                is_last_chunk ? ZSTD_e_end : ZSTD_e_continue);
1164

1165
                        if (sym_ZSTD_isError(remaining)) {
550✔
1166
                                log_debug("ZSTD encoder failed: %s", sym_ZSTD_getErrorName(remaining));
×
1167
                                return zstd_ret_to_errno(remaining);
×
1168
                        }
1169

1170
                        if (left < output.pos)
550✔
1171
                                return -EFBIG;
1172

1173
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
550✔
1174
                        if (wrote < 0)
550✔
1175
                                return wrote;
1176

1177
                        left -= output.pos;
550✔
1178

1179
                        /* If we're on the last chunk we're finished when zstd
1180
                         * returns 0, which means its consumed all the input AND
1181
                         * finished the frame. Otherwise, we're finished when
1182
                         * we've consumed all the input.
1183
                         */
1184
                        finished = is_last_chunk ? (remaining == 0) : (input.pos == input.size);
550✔
1185
                }
1186

1187
                /* zstd only returns 0 when the input is completely consumed */
1188
                assert(input.pos == input.size);
550✔
1189
                if (is_last_chunk)
550✔
1190
                        break;
1191
        }
1192

1193
        if (ret_uncompressed_size)
25✔
1194
                *ret_uncompressed_size = in_bytes;
25✔
1195

1196
        if (in_bytes == 0)
25✔
1197
                log_debug("ZSTD compression finished (no input data)");
×
1198
        else
1199
                log_debug("ZSTD compression finished (%" PRIu64 " -> %" PRIu64 " bytes, %.1f%%)",
25✔
1200
                          in_bytes, max_bytes - left, (double) (max_bytes - left) / in_bytes * 100);
1201

1202
        return 0;
1203
#else
1204
        return -EPROTONOSUPPORT;
1205
#endif
1206
}
1207

1208
int decompress_stream_zstd(int fdf, int fdt, uint64_t max_bytes) {
13✔
1209
        assert(fdf >= 0);
13✔
1210
        assert(fdt >= 0);
13✔
1211

1212
#if HAVE_ZSTD
1213
        _cleanup_(ZSTD_freeDCtxp) ZSTD_DCtx *dctx = NULL;
×
1214
        _cleanup_free_ void *in_buff = NULL, *out_buff = NULL;
13✔
1215
        size_t in_allocsize, out_allocsize;
13✔
1216
        size_t last_result = 0;
13✔
1217
        uint64_t left = max_bytes, in_bytes = 0;
13✔
1218
        int r;
13✔
1219

1220
        r = dlopen_zstd();
13✔
1221
        if (r < 0)
13✔
1222
                return r;
1223
        /* Create the context and buffers */
1224
        in_allocsize = sym_ZSTD_DStreamInSize();
13✔
1225
        out_allocsize = sym_ZSTD_DStreamOutSize();
13✔
1226
        in_buff = malloc(in_allocsize);
13✔
1227
        out_buff = malloc(out_allocsize);
13✔
1228
        dctx = sym_ZSTD_createDCtx();
13✔
1229
        if (!dctx || !out_buff || !in_buff)
13✔
1230
                return -ENOMEM;
1231

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

1247
                red = loop_read(fdf, in_buff, in_allocsize, true);
41✔
1248
                if (red < 0)
41✔
1249
                        return red;
2✔
1250
                if (red == 0)
41✔
1251
                        break;
1252

1253
                in_bytes += (size_t) red;
31✔
1254
                input.size = (size_t) red;
31✔
1255
                input.pos = 0;
31✔
1256

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

1283
                        if (left < output.pos)
237✔
1284
                                return -EFBIG;
2✔
1285

1286
                        wrote = loop_write_full(fdt, output.dst, output.pos, USEC_INFINITY);
236✔
1287
                        if (wrote < 0)
236✔
1288
                                return wrote;
1289

1290
                        left -= output.pos;
235✔
1291
                }
1292
                if (has_error)
29✔
1293
                        break;
1294
        }
1295

1296
        if (in_bytes == 0)
11✔
1297
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "ZSTD decoder failed: no data read");
×
1298

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

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

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

1324
        if (endswith(filename, ".lz4"))
10✔
1325
                return decompress_stream_lz4(fdf, fdt, max_bytes);
×
1326
        if (endswith(filename, ".xz"))
10✔
1327
                return decompress_stream_xz(fdf, fdt, max_bytes);
×
1328
        if (endswith(filename, ".zst"))
10✔
1329
                return decompress_stream_zstd(fdf, fdt, max_bytes);
10✔
1330

1331
        return -EPROTONOSUPPORT;
1332
}
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