| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "alloc-util.h" |
| 4 |
#include "fd-util.h" |
| 5 |
#include "fileio.h" |
| 6 |
#include "log.h" |
| 7 |
#include "memstream-util.h" |
| 8 |
|
| 9 |
void memstream_done(MemStream *m) { |
| 10 |
assert(m); |
| 11 |
|
| 12 |
/* First, close file stream, as the buffer may be reallocated on close. */ |
| 13 |
safe_fclose(m->f); |
| 14 |
|
| 15 |
/* Then, free buffer. */ |
| 16 |
free(m->buf); |
| 17 |
} |
| 18 |
|
| 19 |
FILE* memstream_init(MemStream *m) { |
| 20 |
assert(m); |
| 21 |
assert(!m->f); |
| 22 |
|
| 23 |
m->f = open_memstream_unlocked(&m->buf, &m->sz); |
| 24 |
return m->f; |
| 25 |
} |
| 26 |
|
| 27 |
int memstream_finalize(MemStream *m, char **ret_buf, size_t *ret_size) { |
| 28 |
int r; |
| 29 |
|
| 30 |
assert(m); |
| 31 |
assert(m->f); |
| 32 |
assert(ret_buf); |
| 33 |
|
| 34 |
/* Add terminating NUL, so that the output buffer is a valid string. */ |
| 35 |
fputc('\0', m->f); |
| 36 |
|
| 37 |
r = fflush_and_check(m->f); |
| 38 |
if (r < 0) |
| 39 |
return r; |
| 40 |
|
| 41 |
m->f = safe_fclose(m->f); |
| 42 |
|
| 43 |
/* On fclose(), the buffer may be reallocated, and may trigger OOM. */ |
| 44 |
if (!m->buf) |
| 45 |
return -ENOMEM; |
| 46 |
|
| 47 |
assert(m->sz > 0); |
| 48 |
|
| 49 |
*ret_buf = TAKE_PTR(m->buf); |
| 50 |
if (ret_size) |
| 51 |
*ret_size = m->sz - 1; |
| 52 |
|
| 53 |
m->sz = 0; /* For safety when the MemStream object will be reused later. */ |
| 54 |
return 0; |
| 55 |
} |
| 56 |
|
| 57 |
int memstream_dump_internal( |
| 58 |
int level, |
| 59 |
int error, |
| 60 |
const char *file, |
| 61 |
int line, |
| 62 |
const char *func, |
| 63 |
MemStream *m) { |
| 64 |
|
| 65 |
_cleanup_free_ char *buf = NULL; |
| 66 |
int r; |
| 67 |
|
| 68 |
assert(m); |
| 69 |
|
| 70 |
r = memstream_finalize(m, &buf, NULL); |
| 71 |
if (r < 0) |
| 72 |
return log_full_errno(level, r, "Failed to flush memstream: %m"); |
| 73 |
|
| 74 |
return log_dump_internal(level, error, file, line, func, buf); |
| 75 |
} |