1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "alloc-util.h"
10 #include "errno-util.h"
11 #include "extract-word.h"
15 #include "hexdecoct.h"
19 #include "nulstr-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "socket-util.h"
23 #include "stat-util.h"
24 #include "stdio-util.h"
25 #include "string-util.h"
27 #include "sync-util.h"
28 #include "terminal-util.h"
29 #include "time-util.h"
30 #include "tmpfile-util.h"
32 /* The maximum size of the file we'll read in one go in read_full_file() (64M). */
33 #define READ_FULL_BYTES_MAX (64U * U64_MB - UINT64_C(1))
34 /* Used when a size is specified for read_full_file() with READ_FULL_FILE_UNBASE64 or _UNHEX */
35 #define READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY 3
37 /* The maximum size of virtual files (i.e. procfs, sysfs, and other virtual "API" files) we'll read in one go
38 * in read_virtual_file(). Note that this limit is different (and much lower) than the READ_FULL_BYTES_MAX
39 * limit. This reflects the fact that we use different strategies for reading virtual and regular files:
40 * virtual files we generally have to read in a single read() syscall since the kernel doesn't support
41 * continuation read()s for them. Thankfully they are somewhat size constrained. Thus we can allocate the
42 * full potential buffer in advance. Regular files OTOH can be much larger, and there we grow the allocations
43 * exponentially in a loop. We use a size limit of 4M-2 because 4M-1 is the maximum buffer that /proc/sys/
44 * allows us to read() (larger reads will fail with ENOMEM), and we want to read one extra byte so that we
46 #define READ_VIRTUAL_BYTES_MAX (4U * U64_MB - UINT64_C(2))
48 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
51 FILE *f
= fdopen(fd
, options
);
55 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
61 int take_fdopen_unlocked(int *fd
, const char *options
, FILE **ret
) {
66 r
= fdopen_unlocked(*fd
, options
, ret
);
75 FILE* take_fdopen(int *fd
, const char *options
) {
78 FILE *f
= fdopen(*fd
, options
);
87 DIR* take_fdopendir(int *dfd
) {
90 DIR *d
= fdopendir(*dfd
);
99 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
100 FILE *f
= open_memstream(ptr
, sizeloc
);
104 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
109 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
110 FILE *f
= fmemopen(buf
, size
, mode
);
114 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
119 int write_string_stream_full(
122 WriteStringFileFlags flags
,
123 const struct timespec
*ts
) {
135 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
136 * an fd. Let's fail early in that case. */
142 if (flags
& WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL
) {
143 _cleanup_free_
char *t
= NULL
;
145 /* If value to be written is same as that of the existing value, then suppress the write. */
153 /* Read an additional byte to detect cases where the prefix matches but the rest
154 * doesn't. Also, 0 returned by read_virtual_file_fd() means the read was truncated and
155 * it won't be equal to the new value. */
156 if (read_virtual_file_fd(fd
, strlen(line
)+1, &t
, NULL
) > 0 &&
157 streq_skip_trailing_chars(line
, t
, NEWLINE
)) {
158 log_debug("No change in value '%s', suppressing write", line
);
162 if (lseek(fd
, 0, SEEK_SET
) < 0)
166 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
168 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
169 /* If STDIO buffering was disabled, then let's append the newline character to the string
170 * itself, so that the write goes out in one go, instead of two */
172 line
= strjoina(line
, "\n");
176 if (fputs(line
, f
) == EOF
)
180 if (fputc('\n', f
) == EOF
)
183 if (flags
& WRITE_STRING_FILE_SYNC
)
184 r
= fflush_sync_and_check(f
);
186 r
= fflush_and_check(f
);
191 const struct timespec twice
[2] = {*ts
, *ts
};
194 if (futimens(fd
, twice
) < 0)
201 static mode_t
write_string_file_flags_to_mode(WriteStringFileFlags flags
) {
203 /* We support three different modes, that are the ones that really make sense for text files like this:
205 * → 0600 (i.e. root-only)
206 * → 0444 (i.e. read-only)
207 * → 0644 (i.e. writable for root, readable for everyone else)
210 return FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 :
211 FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0444
) ? 0444 : 0644;
214 static int write_string_file_atomic_at(
218 WriteStringFileFlags flags
,
219 const struct timespec
*ts
) {
221 _cleanup_fclose_
FILE *f
= NULL
;
222 _cleanup_free_
char *p
= NULL
;
228 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
229 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
231 mode_t mode
= write_string_file_flags_to_mode(flags
);
233 bool call_label_ops_post
= false;
234 if (FLAGS_SET(flags
, WRITE_STRING_FILE_LABEL
)) {
235 r
= label_ops_pre(dir_fd
, fn
, mode
);
239 call_label_ops_post
= true;
242 r
= fopen_temporary_at(dir_fd
, fn
, &f
, &p
);
243 if (call_label_ops_post
)
244 /* If fopen_temporary_at() failed in the above, propagate the error code, and ignore failures
245 * in label_ops_post(). */
246 RET_GATHER(r
, label_ops_post(f
? fileno(f
) : dir_fd
, f
? NULL
: fn
, /* created= */ !!f
));
250 r
= write_string_stream_full(f
, line
, flags
, ts
);
254 r
= fchmod_umask(fileno(f
), mode
);
258 r
= RET_NERRNO(renameat(dir_fd
, p
, dir_fd
, fn
));
262 if (FLAGS_SET(flags
, WRITE_STRING_FILE_SYNC
)) {
263 /* Sync the rename, too */
264 r
= fsync_directory_of_file(fileno(f
));
273 (void) unlinkat(dir_fd
, p
, 0);
277 int write_string_file_full(
281 WriteStringFileFlags flags
,
282 const struct timespec
*ts
,
283 const char *label_fn
) {
285 bool made_file
= false;
286 _cleanup_fclose_
FILE *f
= NULL
;
287 _cleanup_close_
int fd
= -EBADF
;
290 assert(dir_fd
== AT_FDCWD
|| dir_fd
>= 0);
293 /* We don't know how to verify whether the file contents was already on-disk. */
294 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
296 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
299 r
= mkdirat_parents(dir_fd
, fn
, 0755);
304 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
306 assert(flags
& WRITE_STRING_FILE_CREATE
);
308 r
= write_string_file_atomic_at(dir_fd
, fn
, line
, flags
, ts
);
315 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
318 ASSERT_FD(dir_fd
), O_CLOEXEC
| O_NOCTTY
|
319 (FLAGS_SET(flags
, WRITE_STRING_FILE_TRUNCATE
) ? O_TRUNC
: 0) |
320 (FLAGS_SET(flags
, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL
) ? O_RDWR
: O_WRONLY
) |
321 (FLAGS_SET(flags
, WRITE_STRING_FILE_OPEN_NONBLOCKING
) ? O_NONBLOCK
: 0));
323 mode_t mode
= write_string_file_flags_to_mode(flags
);
324 bool call_label_ops_post
= false;
326 if (FLAGS_SET(flags
, WRITE_STRING_FILE_LABEL
|WRITE_STRING_FILE_CREATE
)) {
327 r
= label_ops_pre(dir_fd
, label_fn
?: fn
, mode
);
331 call_label_ops_post
= true;
334 r
= fd
= openat_report_new(
335 dir_fd
, fn
, O_CLOEXEC
| O_NOCTTY
|
336 (FLAGS_SET(flags
, WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0) |
337 (FLAGS_SET(flags
, WRITE_STRING_FILE_CREATE
) ? O_CREAT
: 0) |
338 (FLAGS_SET(flags
, WRITE_STRING_FILE_TRUNCATE
) ? O_TRUNC
: 0) |
339 (FLAGS_SET(flags
, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL
) ? O_RDWR
: O_WRONLY
) |
340 (FLAGS_SET(flags
, WRITE_STRING_FILE_OPEN_NONBLOCKING
) ? O_NONBLOCK
: 0),
343 if (call_label_ops_post
)
344 /* If openat_report_new() failed in the above, propagate the error code, and ignore
345 * failures in label_ops_post(). */
346 RET_GATHER(r
, label_ops_post(fd
>= 0 ? fd
: dir_fd
, fd
>= 0 ? NULL
: fn
, made_file
));
351 r
= take_fdopen_unlocked(&fd
, "w", &f
);
355 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
356 setvbuf(f
, NULL
, _IONBF
, 0);
358 r
= write_string_stream_full(f
, line
, flags
, ts
);
366 (void) unlinkat(dir_fd
, fn
, 0);
368 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
374 /* OK, the operation failed, but let's see if the right contents in place already. If so, eat up the
376 if (verify_file_at(dir_fd
, fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) || (flags
& WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE
)) > 0)
382 int write_string_filef(
384 WriteStringFileFlags flags
,
385 const char *format
, ...) {
387 _cleanup_free_
char *p
= NULL
;
391 va_start(ap
, format
);
392 r
= vasprintf(&p
, format
, ap
);
398 return write_string_file(fn
, p
, flags
);
401 int write_base64_file_at(
404 const struct iovec
*data
,
405 WriteStringFileFlags flags
) {
407 _cleanup_free_
char *encoded
= NULL
;
410 n
= base64mem_full(data
? data
->iov_base
: NULL
, data
? data
->iov_len
: 0, 79, &encoded
);
414 return write_string_file_at(dir_fd
, fn
, encoded
, flags
);
417 int read_one_line_file_at(int dir_fd
, const char *filename
, char **ret
) {
418 _cleanup_fclose_
FILE *f
= NULL
;
421 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
425 r
= fopen_unlocked_at(dir_fd
, filename
, "re", 0, &f
);
429 return read_line(f
, LONG_LINE_MAX
, ret
);
432 int verify_file_at(int dir_fd
, const char *fn
, const char *blob
, bool accept_extra_nl
) {
433 _cleanup_fclose_
FILE *f
= NULL
;
434 _cleanup_free_
char *buf
= NULL
;
442 if (accept_extra_nl
&& endswith(blob
, "\n"))
443 accept_extra_nl
= false;
445 buf
= malloc(l
+ accept_extra_nl
+ 1);
449 r
= fopen_unlocked_at(dir_fd
, strempty(fn
), "re", 0, &f
);
453 /* We try to read one byte more than we need, so that we know whether we hit eof */
455 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
457 return errno_or_else(EIO
);
459 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
461 if (memcmp(buf
, blob
, l
) != 0)
463 if (k
> l
&& buf
[l
] != '\n')
469 int read_virtual_file_at(
471 const char *filename
,
476 _cleanup_free_
char *buf
= NULL
;
479 bool truncated
= false;
481 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
482 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
483 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
484 * case, the content of the virtual file must be retrieved with a single read otherwise a second read
485 * might get the new value instead of finding EOF immediately. That's the reason why the usage of
486 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
487 * EOF. See issue #13585.
489 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
490 * the full file is too large to read, an error is returned. For other values of max_size, *partial
491 * contents* may be returned. (Though the read is still done using one syscall.) Returns 0 on
492 * partial success, 1 if untruncated contents were read.
494 * Rule: for kernfs files using "seq_file" → use regular read_full_file_at()
495 * for kernfs files using "raw" → use read_virtual_file_at()
498 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
499 assert(max_size
<= READ_VIRTUAL_BYTES_MAX
|| max_size
== SIZE_MAX
);
501 _cleanup_close_
int fd
= -EBADF
;
502 if (isempty(filename
))
503 fd
= fd_reopen(ASSERT_FD(dir_fd
), O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
505 fd
= RET_NERRNO(openat(dir_fd
, filename
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
));
509 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
515 if (fstat(fd
, &st
) < 0)
518 if (!S_ISREG(st
.st_mode
))
521 /* Be prepared for files from /proc which generally report a file size of 0. */
522 assert_cc(READ_VIRTUAL_BYTES_MAX
< SSIZE_MAX
);
523 if (st
.st_size
> 0 && n_retries
> 1) {
524 /* Let's use the file size if we have more than 1 attempt left. On the last attempt
525 * we'll ignore the file size */
527 if (st
.st_size
> SSIZE_MAX
) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
529 if (max_size
== SIZE_MAX
)
534 size
= MIN((size_t) st
.st_size
, max_size
);
536 if (size
> READ_VIRTUAL_BYTES_MAX
)
541 } else if (n_retries
> 1) {
542 /* Files in /proc are generally smaller than the page size so let's start with
543 * a page size buffer from malloc and only use the max buffer on the final try. */
544 size
= MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX
, max_size
);
547 size
= MIN(READ_VIRTUAL_BYTES_MAX
, max_size
);
551 buf
= malloc(size
+ 1);
555 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
556 size
= MIN3(MALLOC_SIZEOF_SAFE(buf
) - 1, max_size
, READ_VIRTUAL_BYTES_MAX
);
561 /* Read one more byte so we can detect whether the content of the
562 * file has already changed or the guessed size for files from /proc
563 * wasn't large enough . */
564 k
= read(fd
, buf
, size
+ 1);
574 /* Consider a short read as EOF */
578 /* If a maximum size is specified and we already read more we know the file is larger, and
579 * can handle this as truncation case. Note that if the size of what we read equals the
580 * maximum size then this doesn't mean truncation, the file might or might not end on that
581 * byte. We need to rerun the loop in that case, with a larger buffer size, so that we read
582 * at least one more byte to be able to distinguish EOF from truncation. */
583 if (max_size
!= SIZE_MAX
&& n
> max_size
) {
584 n
= size
; /* Make sure we never use more than what we sized the buffer for (so that
585 * we have one free byte in it for the trailing NUL we add below). */
590 /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
594 /* Hmm... either we read too few bytes from /proc or less likely the content of the file
595 * might have been changed (and is now bigger) while we were processing, let's try again
596 * either with the new file size. */
598 if (lseek(fd
, 0, SEEK_SET
) < 0)
606 /* Safety check: if the caller doesn't want to know the size of what we just read it will
607 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
608 * operation as otherwise there'd be ambiguity about what we just read. */
609 if (!ret_size
&& memchr(buf
, 0, n
))
615 /* Return rest of the buffer to libc */
616 p
= realloc(buf
, n
+ 1);
623 *ret_contents
= TAKE_PTR(buf
);
632 int read_full_stream_full(
634 const char *filename
,
637 ReadFullFileFlags flags
,
641 _cleanup_free_
char *buf
= NULL
;
642 size_t n
, n_next
= 0, l
, expected_decoded_size
= size
;
646 assert(ret_contents
);
647 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
648 assert(size
!= SIZE_MAX
|| !FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
));
650 if (offset
!= UINT64_MAX
&& offset
> LONG_MAX
) /* fseek() can only deal with "long" offsets */
653 if ((flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) != 0) {
654 if (size
<= SIZE_MAX
/ READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY
)
655 size
*= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY
;
661 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
662 * fmemopen()), let's optimize our buffering */
665 if (fstat(fd
, &st
) < 0)
668 if (S_ISREG(st
.st_mode
)) {
670 /* Try to start with the right file size if we shall read the file in full. Note
671 * that we increase the size to read here by one, so that the first read attempt
672 * already makes us notice the EOF. If the reported size of the file is zero, we
673 * avoid this logic however, since quite likely it might be a virtual file in procfs
674 * that all report a zero file size. */
676 if (st
.st_size
> 0 &&
677 (size
== SIZE_MAX
|| FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
))) {
680 LESS_BY((uint64_t) st
.st_size
, offset
== UINT64_MAX
? 0 : offset
);
682 if (rsize
< SIZE_MAX
) /* overflow check */
686 if (flags
& READ_FULL_FILE_WARN_WORLD_READABLE
)
687 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
691 /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
692 * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
693 * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
694 * with LINE_MAX, under assumption the file is most likely much shorter. */
696 n_next
= size
!= SIZE_MAX
&& !FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) ? size
: LINE_MAX
;
698 /* Never read more than we need to determine that our own limit is hit */
699 if (n_next
> READ_FULL_BYTES_MAX
)
700 n_next
= READ_FULL_BYTES_MAX
+ 1;
702 if (offset
!= UINT64_MAX
&& fseek(f
, offset
, SEEK_SET
) < 0)
710 /* If we shall fail when reading overly large data, then read exactly one byte more than the
711 * specified size at max, since that'll tell us if there's anymore data beyond the limit. */
712 if (FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) && n_next
> size
)
715 if (flags
& READ_FULL_FILE_SECURE
) {
716 t
= malloc(n_next
+ 1);
721 memcpy_safe(t
, buf
, n
);
722 explicit_bzero_safe(buf
, n
);
725 t
= realloc(buf
, n_next
+ 1);
731 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
732 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
733 n
= size
== SIZE_MAX
? MALLOC_SIZEOF_SAFE(buf
) - 1 : n_next
;
736 k
= fread(buf
+ l
, 1, n
- l
, f
);
742 r
= errno_or_else(EIO
);
748 if (size
!= SIZE_MAX
&& !FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
)) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
753 assert(k
> 0); /* we can't have read zero bytes because that would have been EOF */
755 if (FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) && l
> size
) {
760 if (n
>= READ_FULL_BYTES_MAX
) {
765 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
768 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
769 _cleanup_free_
void *decoded
= NULL
;
773 if (flags
& READ_FULL_FILE_UNBASE64
)
774 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
776 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
780 if (flags
& READ_FULL_FILE_SECURE
)
781 explicit_bzero_safe(buf
, n
);
782 free_and_replace(buf
, decoded
);
783 n
= l
= decoded_size
;
785 if (FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) && l
> expected_decoded_size
) {
792 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
793 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
794 * there'd be ambiguity about what we just read. */
796 if (memchr(buf
, 0, l
)) {
803 *ret_contents
= TAKE_PTR(buf
);
811 if (flags
& READ_FULL_FILE_SECURE
)
812 explicit_bzero_safe(buf
, n
);
817 int read_full_file_full(
819 const char *filename
,
822 ReadFullFileFlags flags
,
823 const char *bind_name
,
827 _cleanup_fclose_
FILE *f
= NULL
;
828 XfopenFlags xflags
= XFOPEN_UNLOCKED
;
832 assert(ret_contents
);
834 if (FLAGS_SET(flags
, READ_FULL_FILE_CONNECT_SOCKET
) && /* If this is enabled, let's try to connect to it */
835 offset
== UINT64_MAX
) /* Seeking is not supported on AF_UNIX sockets */
836 xflags
|= XFOPEN_SOCKET
;
838 r
= xfopenat_full(dir_fd
, filename
, "re", 0, xflags
, bind_name
, &f
);
842 return read_full_stream_full(f
, filename
, offset
, size
, flags
, ret_contents
, ret_size
);
845 int script_get_shebang_interpreter(const char *path
, char **ret
) {
846 _cleanup_fclose_
FILE *f
= NULL
;
851 f
= fopen(path
, "re");
856 r
= safe_fgetc(f
, &c
);
863 r
= safe_fgetc(f
, &c
);
871 _cleanup_free_
char *line
= NULL
;
872 r
= read_line(f
, LONG_LINE_MAX
, &line
);
876 _cleanup_free_
char *p
= NULL
;
877 const char *s
= line
;
879 r
= extract_first_word(&s
, &p
, /* separators = */ NULL
, /* flags = */ 0);
890 int get_proc_field(const char *path
, const char *key
, char **ret
) {
891 _cleanup_fclose_
FILE *f
= NULL
;
894 /* Retrieve one field from a file like /proc/self/status. "key" matches the beginning of the line
895 * and should not include whitespace or the delimiter (':').
896 * Whitespaces after the ':' will be skipped. Only the first element is returned
897 * (i.e. for /proc/meminfo line "MemTotal: 1024 kB" -> return "1024"). */
902 r
= fopen_unlocked(path
, "re", &f
);
903 if (r
== -ENOENT
&& proc_mounted() == 0)
909 _cleanup_free_
char *line
= NULL
;
911 r
= read_line(f
, LONG_LINE_MAX
, &line
);
917 char *l
= startswith(line
, key
);
918 if (l
&& *l
== ':') {
920 char *s
= strdupcspn(skip_leading_chars(l
+ 1, " \t"), WHITESPACE
);
932 DIR* xopendirat(int dir_fd
, const char *name
, int flags
) {
933 _cleanup_close_
int fd
= -EBADF
;
935 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
937 assert(!(flags
& (O_CREAT
|O_TMPFILE
)));
939 if (dir_fd
== AT_FDCWD
&& flags
== 0)
940 return opendir(name
);
942 fd
= openat(dir_fd
, name
, O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
);
946 return take_fdopendir(&fd
);
949 int fopen_mode_to_flags(const char *mode
) {
955 if ((p
= startswith(mode
, "r+")))
957 else if ((p
= startswith(mode
, "r")))
959 else if ((p
= startswith(mode
, "w+")))
960 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
961 else if ((p
= startswith(mode
, "w")))
962 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
963 else if ((p
= startswith(mode
, "a+")))
964 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
965 else if ((p
= startswith(mode
, "a")))
966 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
970 for (; *p
!= 0; p
++) {
983 /* ignore this here, fdopen() might care later though */
986 case 'c': /* not sure what to do about this one */
995 static int xfopenat_regular(int dir_fd
, const char *path
, const char *mode
, int open_flags
, FILE **ret
) {
998 /* A combination of fopen() with openat() */
1000 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1005 if (dir_fd
== AT_FDCWD
&& open_flags
== 0)
1006 f
= fopen(path
, mode
);
1008 _cleanup_close_
int fd
= -EBADF
;
1011 mode_flags
= fopen_mode_to_flags(mode
);
1015 fd
= openat(dir_fd
, path
, mode_flags
| open_flags
);
1019 f
= take_fdopen(&fd
, mode
);
1028 static int xfopenat_unix_socket(int dir_fd
, const char *path
, const char *bind_name
, FILE **ret
) {
1029 _cleanup_close_
int sk
= -EBADF
;
1033 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1037 sk
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
1042 /* If the caller specified a socket name to bind to, do so before connecting. This is
1043 * useful to communicate some minor, short meta-information token from the client to
1045 union sockaddr_union bsa
;
1047 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
1051 if (bind(sk
, &bsa
.sa
, r
) < 0)
1055 r
= connect_unix_path(sk
, dir_fd
, path
);
1059 if (shutdown(sk
, SHUT_WR
) < 0)
1062 f
= take_fdopen(&sk
, "r");
1076 const char *bind_name
,
1079 FILE *f
= NULL
; /* avoid false maybe-uninitialized warning */
1082 assert(dir_fd
>= 0 || dir_fd
== AT_FDCWD
);
1087 r
= xfopenat_regular(dir_fd
, path
, mode
, open_flags
, &f
);
1088 if (r
== -ENXIO
&& FLAGS_SET(flags
, XFOPEN_SOCKET
)) {
1089 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
1090 r
= xfopenat_unix_socket(dir_fd
, path
, bind_name
, &f
);
1091 if (IN_SET(r
, -ENOTSOCK
, -EINVAL
))
1092 return -ENXIO
; /* propagate original error if this is not a socket after all */
1097 if (FLAGS_SET(flags
, XFOPEN_UNLOCKED
))
1098 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
1104 int fdopen_independent(int fd
, const char *mode
, FILE **ret
) {
1105 _cleanup_close_
int copy_fd
= -EBADF
;
1106 _cleanup_fclose_
FILE *f
= NULL
;
1113 /* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
1114 * returns a FILE* for it */
1116 mode_flags
= fopen_mode_to_flags(mode
);
1120 /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
1121 * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
1122 copy_fd
= fd_reopen(fd
, mode_flags
& ~O_CREAT
);
1126 f
= take_fdopen(©_fd
, mode
);
1134 static int search_and_open_internal(
1136 int mode
, /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1144 assert(!ret_fd
|| !FLAGS_SET(mode
, O_CREAT
)); /* We don't support O_CREAT for this */
1147 if (path_is_absolute(path
)) {
1148 _cleanup_close_
int fd
= -EBADF
;
1151 /* We only specify 0777 here to appease static analyzers, it's never used since we
1152 * don't support O_CREAT here */
1153 r
= fd
= RET_NERRNO(open(path
, mode
, 0777));
1155 r
= RET_NERRNO(access(path
, mode
));
1160 r
= path_simplify_alloc(path
, ret_path
);
1166 *ret_fd
= TAKE_FD(fd
);
1171 if (!path_strv_resolve_uniq(search
, root
))
1174 STRV_FOREACH(i
, search
) {
1175 _cleanup_close_
int fd
= -EBADF
;
1176 _cleanup_free_
char *p
= NULL
;
1178 p
= path_join(root
, *i
, path
);
1183 /* as above, 0777 is static analyzer appeasement */
1184 r
= fd
= RET_NERRNO(open(p
, mode
, 0777));
1186 r
= RET_NERRNO(access(p
, F_OK
));
1189 *ret_path
= path_simplify(TAKE_PTR(p
));
1192 *ret_fd
= TAKE_FD(fd
);
1203 int search_and_open(
1211 _cleanup_strv_free_
char **copy
= NULL
;
1215 copy
= strv_copy((char**) search
);
1219 return search_and_open_internal(path
, mode
, root
, copy
, ret_fd
, ret_path
);
1222 static int search_and_fopen_internal(
1230 _cleanup_free_
char *found_path
= NULL
;
1231 _cleanup_close_
int fd
= -EBADF
;
1235 assert(mode
|| !ret_file
);
1237 r
= search_and_open(
1239 mode
? fopen_mode_to_flags(mode
) : 0,
1242 ret_file
? &fd
: NULL
,
1243 ret_path
? &found_path
: NULL
);
1248 FILE *f
= take_fdopen(&fd
, mode
);
1256 *ret_path
= TAKE_PTR(found_path
);
1261 int search_and_fopen(
1265 const char **search
,
1269 _cleanup_strv_free_
char **copy
= NULL
;
1272 assert(mode
|| !ret_file
);
1274 copy
= strv_copy((char**) search
);
1278 return search_and_fopen_internal(path
, mode
, root
, copy
, ret_file
, ret_path
);
1281 int search_and_fopen_nulstr(
1289 _cleanup_strv_free_
char **l
= NULL
;
1292 assert(mode
|| !ret_file
);
1294 l
= strv_split_nulstr(search
);
1298 return search_and_fopen_internal(path
, mode
, root
, l
, ret_file
, ret_path
);
1301 int fflush_and_check(FILE *f
) {
1308 return errno_or_else(EIO
);
1313 int fflush_sync_and_check(FILE *f
) {
1318 r
= fflush_and_check(f
);
1322 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1323 * assume that in that case we need no explicit syncing */
1335 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1336 char ln
[DECIMAL_STR_MAX(n
)+2];
1338 /* Creates a "timestamp" file, that contains nothing but a
1339 * usec_t timestamp, formatted in ASCII. */
1341 if (!timestamp_is_set(n
))
1344 xsprintf(ln
, USEC_FMT
"\n", n
);
1346 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1349 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1350 _cleanup_free_
char *ln
= NULL
;
1354 r
= read_one_line_file(fn
, &ln
);
1358 r
= safe_atou64(ln
, &t
);
1362 if (!timestamp_is_set(t
))
1369 int fputs_with_separator(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1373 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator.
1374 * The *space parameter when specified shall initially point to a boolean variable initialized
1375 * to false. It is set to true after the first invocation. This call is supposed to be use in loops,
1376 * where a separator shall be inserted between each element, but not before the first one. */
1385 if (fputs(separator
, f
) < 0)
1390 if (fputs(s
, f
) < 0)
1396 int fputs_with_newline(FILE *f
, const char *s
) {
1398 /* This is like fputs() but outputs a trailing newline char, but only if the string isn't empty
1399 * and doesn't end in a newline already. Returns 0 in case we didn't append a newline, > 0 otherwise. */
1407 if (fputs(s
, f
) < 0)
1410 if (endswith(s
, "\n"))
1413 if (fputc('\n', f
) < 0)
1419 /* A bitmask of the EOL markers we know */
1420 typedef enum EndOfLineMarker
{
1422 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
1423 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
1424 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
1427 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
1429 if (!FLAGS_SET(flags
, READ_LINE_ONLY_NUL
)) {
1433 return EOL_THIRTEEN
;
1442 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile
, NULL
);
1444 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
1445 _cleanup_free_
char *buffer
= NULL
;
1446 size_t n
= 0, count
= 0;
1451 /* Something like a bounded version of getline().
1453 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1454 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1467 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1468 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1470 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1471 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1473 * If a line shall be skipped ret may be initialized as NULL. */
1476 if (!GREEDY_REALLOC(buffer
, 1))
1481 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1482 EndOfLineMarker previous_eol
= EOL_NONE
;
1486 EndOfLineMarker eol
;
1492 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1495 r
= safe_fgetc(f
, &c
);
1498 if (r
== 0) /* EOF is definitely EOL */
1501 eol
= categorize_eol(c
, flags
);
1503 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1504 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1505 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1506 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1507 * EOL marker has been seen right before? In either of these three cases we are
1508 * done. But first, let's put this character back in the queue. (Note that we have to
1509 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1510 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1511 * pass a negative value here. That said, to complicate things further ungetc() is
1512 * actually happy with most negative characters and implicitly casts them back to
1513 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1515 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1521 if (eol
!= EOL_NONE
) {
1522 /* If we are on a tty, we can't shouldn't wait for more input, because that
1523 * generally means waiting for the user, interactively. In the case of a TTY
1524 * we expect only \n as the single EOL marker, so we are in the lucky
1525 * position that there is no need to wait. We check this condition last, to
1526 * avoid isatty() check if not necessary. */
1528 if ((flags
& (READ_LINE_IS_A_TTY
|READ_LINE_NOT_A_TTY
)) == 0) {
1532 if (fd
< 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1533 * and don't call isatty() on an invalid fd */
1534 flags
|= READ_LINE_NOT_A_TTY
;
1536 flags
|= isatty_safe(fd
) ? READ_LINE_IS_A_TTY
: READ_LINE_NOT_A_TTY
;
1538 if (FLAGS_SET(flags
, READ_LINE_IS_A_TTY
))
1542 if (eol
!= EOL_NONE
) {
1543 previous_eol
|= eol
;
1548 if (!GREEDY_REALLOC(buffer
, n
+ 2))
1561 *ret
= TAKE_PTR(buffer
);
1567 int read_stripped_line(FILE *f
, size_t limit
, char **ret
) {
1568 _cleanup_free_
char *s
= NULL
;
1573 r
= read_line(f
, limit
, ret
? &s
: NULL
);
1578 const char *p
= strstrip(s
);
1582 k
= strdup_to(ret
, p
);
1588 return r
> 0; /* Return 1 if something was read. */
1591 int safe_fgetc(FILE *f
, char *ret
) {
1596 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1597 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1604 return errno_or_else(EIO
);
1618 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1625 if (stat(filename
, &_st
) < 0)
1630 if ((st
->st_mode
& S_IRWXO
) == 0)
1634 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1635 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1636 filename
, st
->st_mode
& 07777);
1638 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1639 filename
, st
->st_mode
& 07777);