1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
12 #include <sys/types.h>
15 #include "alloc-util.h"
16 #include "chase-symlinks.h"
20 #include "hexdecoct.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "socket-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "sync-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*1024U*1024U - 1U)
35 /* The maximum size of virtual files (i.e. procfs, sysfs, and other virtual "API" files) we'll read in one go
36 * in read_virtual_file(). Note that this limit is different (and much lower) than the READ_FULL_BYTES_MAX
37 * limit. This reflects the fact that we use different strategies for reading virtual and regular files:
38 * virtual files we generally have to read in a single read() syscall since the kernel doesn't support
39 * continuation read()s for them. Thankfully they are somewhat size constrained. Thus we can allocate the
40 * full potential buffer in advance. Regular files OTOH can be much larger, and there we grow the allocations
41 * exponentially in a loop. We use a size limit of 4M-2 because 4M-1 is the maximum buffer that /proc/sys/
42 * allows us to read() (larger reads will fail with ENOMEM), and we want to read one extra byte so that we
44 #define READ_VIRTUAL_BYTES_MAX (4U*1024U*1024U - 2U)
46 int fopen_unlocked(const char *path
, const char *options
, FILE **ret
) {
49 FILE *f
= fopen(path
, options
);
53 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
59 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
62 FILE *f
= fdopen(fd
, options
);
66 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
72 int take_fdopen_unlocked(int *fd
, const char *options
, FILE **ret
) {
77 r
= fdopen_unlocked(*fd
, options
, ret
);
86 FILE* take_fdopen(int *fd
, const char *options
) {
89 FILE *f
= fdopen(*fd
, options
);
98 DIR* take_fdopendir(int *dfd
) {
101 DIR *d
= fdopendir(*dfd
);
110 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
111 FILE *f
= open_memstream(ptr
, sizeloc
);
115 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
120 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
121 FILE *f
= fmemopen(buf
, size
, mode
);
125 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
130 int write_string_stream_ts(
133 WriteStringFileFlags flags
,
134 const struct timespec
*ts
) {
146 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
147 * an fd. Let's fail early in that case. */
153 if (flags
& WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL
) {
154 _cleanup_free_
char *t
= NULL
;
156 /* If value to be written is same as that of the existing value, then suppress the write. */
164 /* Read an additional byte to detect cases where the prefix matches but the rest
165 * doesn't. Also, 0 returned by read_virtual_file_fd() means the read was truncated and
166 * it won't be equal to the new value. */
167 if (read_virtual_file_fd(fd
, strlen(line
)+1, &t
, NULL
) > 0 &&
168 streq_skip_trailing_chars(line
, t
, NEWLINE
)) {
169 log_debug("No change in value '%s', supressing write", line
);
173 if (lseek(fd
, 0, SEEK_SET
) < 0)
177 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
179 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
180 /* If STDIO buffering was disabled, then let's append the newline character to the string
181 * itself, so that the write goes out in one go, instead of two */
183 line
= strjoina(line
, "\n");
187 if (fputs(line
, f
) == EOF
)
191 if (fputc('\n', f
) == EOF
)
194 if (flags
& WRITE_STRING_FILE_SYNC
)
195 r
= fflush_sync_and_check(f
);
197 r
= fflush_and_check(f
);
202 const struct timespec twice
[2] = {*ts
, *ts
};
205 if (futimens(fd
, twice
) < 0)
212 static int write_string_file_atomic(
215 WriteStringFileFlags flags
,
216 const struct timespec
*ts
) {
218 _cleanup_fclose_
FILE *f
= NULL
;
219 _cleanup_free_
char *p
= NULL
;
225 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
226 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
228 r
= fopen_temporary(fn
, &f
, &p
);
232 r
= write_string_stream_ts(f
, line
, flags
, ts
);
236 r
= fchmod_umask(fileno(f
), FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0644);
240 if (rename(p
, fn
) < 0) {
245 if (FLAGS_SET(flags
, WRITE_STRING_FILE_SYNC
)) {
246 /* Sync the rename, too */
247 r
= fsync_directory_of_file(fileno(f
));
259 int write_string_file_ts(
262 WriteStringFileFlags flags
,
263 const struct timespec
*ts
) {
265 _cleanup_fclose_
FILE *f
= NULL
;
271 /* We don't know how to verify whether the file contents was already on-disk. */
272 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
274 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
275 r
= mkdir_parents(fn
, 0755);
280 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
281 assert(flags
& WRITE_STRING_FILE_CREATE
);
283 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
291 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
292 fd
= open(fn
, O_CLOEXEC
|O_NOCTTY
|
293 (FLAGS_SET(flags
, WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0) |
294 (FLAGS_SET(flags
, WRITE_STRING_FILE_CREATE
) ? O_CREAT
: 0) |
295 (FLAGS_SET(flags
, WRITE_STRING_FILE_TRUNCATE
) ? O_TRUNC
: 0) |
296 (FLAGS_SET(flags
, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL
) ? O_RDWR
: O_WRONLY
),
297 (FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0666));
303 r
= fdopen_unlocked(fd
, "w", &f
);
309 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
310 setvbuf(f
, NULL
, _IONBF
, 0);
312 r
= write_string_stream_ts(f
, line
, flags
, ts
);
319 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
324 /* OK, the operation failed, but let's see if the right
325 * contents in place already. If so, eat up the error. */
327 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) || (flags
& WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE
));
334 int write_string_filef(
336 WriteStringFileFlags flags
,
337 const char *format
, ...) {
339 _cleanup_free_
char *p
= NULL
;
343 va_start(ap
, format
);
344 r
= vasprintf(&p
, format
, ap
);
350 return write_string_file(fn
, p
, flags
);
353 int read_one_line_file(const char *fn
, char **line
) {
354 _cleanup_fclose_
FILE *f
= NULL
;
360 r
= fopen_unlocked(fn
, "re", &f
);
364 return read_line(f
, LONG_LINE_MAX
, line
);
367 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
368 _cleanup_fclose_
FILE *f
= NULL
;
369 _cleanup_free_
char *buf
= NULL
;
378 if (accept_extra_nl
&& endswith(blob
, "\n"))
379 accept_extra_nl
= false;
381 buf
= malloc(l
+ accept_extra_nl
+ 1);
385 r
= fopen_unlocked(fn
, "re", &f
);
389 /* We try to read one byte more than we need, so that we know whether we hit eof */
391 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
393 return errno_or_else(EIO
);
395 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
397 if (memcmp(buf
, blob
, l
) != 0)
399 if (k
> l
&& buf
[l
] != '\n')
405 int read_virtual_file_fd(int fd
, size_t max_size
, char **ret_contents
, size_t *ret_size
) {
406 _cleanup_free_
char *buf
= NULL
;
409 bool truncated
= false;
411 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
412 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
413 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
414 * case, the content of the virtual file must be retrieved with a single read otherwise a second read
415 * might get the new value instead of finding EOF immediately. That's the reason why the usage of
416 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
417 * EOF. See issue #13585.
419 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
420 * the full file is too large to read, an error is returned. For other values of max_size, *partial
421 * contents* may be returned. (Though the read is still done using one syscall.) Returns 0 on
422 * partial success, 1 if untruncated contents were read. */
425 assert(max_size
<= READ_VIRTUAL_BYTES_MAX
|| max_size
== SIZE_MAX
);
427 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
433 if (fstat(fd
, &st
) < 0)
436 if (!S_ISREG(st
.st_mode
))
439 /* Be prepared for files from /proc which generally report a file size of 0. */
440 assert_cc(READ_VIRTUAL_BYTES_MAX
< SSIZE_MAX
);
441 if (st
.st_size
> 0 && n_retries
> 1) {
442 /* Let's use the file size if we have more than 1 attempt left. On the last attempt
443 * we'll ignore the file size */
445 if (st
.st_size
> SSIZE_MAX
) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
447 if (max_size
== SIZE_MAX
)
452 size
= MIN((size_t) st
.st_size
, max_size
);
454 if (size
> READ_VIRTUAL_BYTES_MAX
)
459 } else if (n_retries
> 1) {
460 /* Files in /proc are generally smaller than the page size so let's start with
461 * a page size buffer from malloc and only use the max buffer on the final try. */
462 size
= MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX
, max_size
);
465 size
= MIN(READ_VIRTUAL_BYTES_MAX
, max_size
);
469 buf
= malloc(size
+ 1);
473 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
474 size
= MIN3(MALLOC_SIZEOF_SAFE(buf
) - 1, max_size
, READ_VIRTUAL_BYTES_MAX
);
479 /* Read one more byte so we can detect whether the content of the
480 * file has already changed or the guessed size for files from /proc
481 * wasn't large enough . */
482 k
= read(fd
, buf
, size
+ 1);
492 /* Consider a short read as EOF */
496 /* If a maximum size is specified and we already read more we know the file is larger, and
497 * can handle this as truncation case. Note that if the size of what we read equals the
498 * maximum size then this doesn't mean truncation, the file might or might not end on that
499 * byte. We need to rerun the loop in that case, with a larger buffer size, so that we read
500 * at least one more byte to be able to distinguish EOF from truncation. */
501 if (max_size
!= SIZE_MAX
&& n
> max_size
) {
502 n
= size
; /* Make sure we never use more than what we sized the buffer for (so that
503 * we have one free byte in it for the trailing NUL we add below).*/
508 /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
512 /* Hmm... either we read too few bytes from /proc or less likely the content of the file
513 * might have been changed (and is now bigger) while we were processing, let's try again
514 * either with the new file size. */
516 if (lseek(fd
, 0, SEEK_SET
) < 0)
524 /* Safety check: if the caller doesn't want to know the size of what we just read it will
525 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
526 * operation as otherwise there'd be ambiguity about what we just read. */
527 if (!ret_size
&& memchr(buf
, 0, n
))
533 /* Return rest of the buffer to libc */
534 p
= realloc(buf
, n
+ 1);
541 *ret_contents
= TAKE_PTR(buf
);
550 int read_virtual_file(const char *filename
, size_t max_size
, char **ret_contents
, size_t *ret_size
) {
551 _cleanup_close_
int fd
= -1;
555 fd
= open(filename
, O_RDONLY
| O_NOCTTY
| O_CLOEXEC
);
559 return read_virtual_file_fd(fd
, max_size
, ret_contents
, ret_size
);
562 int read_full_stream_full(
564 const char *filename
,
567 ReadFullFileFlags flags
,
571 _cleanup_free_
char *buf
= NULL
;
572 size_t n
, n_next
= 0, l
;
576 assert(ret_contents
);
577 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
578 assert(size
!= SIZE_MAX
|| !FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
));
580 if (offset
!= UINT64_MAX
&& offset
> LONG_MAX
) /* fseek() can only deal with "long" offsets */
584 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
585 * fmemopen()), let's optimize our buffering */
588 if (fstat(fd
, &st
) < 0)
591 if (S_ISREG(st
.st_mode
)) {
593 /* Try to start with the right file size if we shall read the file in full. Note
594 * that we increase the size to read here by one, so that the first read attempt
595 * already makes us notice the EOF. If the reported size of the file is zero, we
596 * avoid this logic however, since quite likely it might be a virtual file in procfs
597 * that all report a zero file size. */
599 if (st
.st_size
> 0 &&
600 (size
== SIZE_MAX
|| FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
))) {
603 LESS_BY((uint64_t) st
.st_size
, offset
== UINT64_MAX
? 0 : offset
);
605 if (rsize
< SIZE_MAX
) /* overflow check */
609 if (flags
& READ_FULL_FILE_WARN_WORLD_READABLE
)
610 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
614 /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
615 * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
616 * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
617 * with LINE_MAX, under assumption the file is most likely much shorter. */
619 n_next
= size
!= SIZE_MAX
&& !FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) ? size
: LINE_MAX
;
621 /* Never read more than we need to determine that our own limit is hit */
622 if (n_next
> READ_FULL_BYTES_MAX
)
623 n_next
= READ_FULL_BYTES_MAX
+ 1;
625 if (offset
!= UINT64_MAX
&& fseek(f
, offset
, SEEK_SET
) < 0)
633 /* If we shall fail when reading overly large data, then read exactly one byte more than the
634 * specified size at max, since that'll tell us if there's anymore data beyond the limit*/
635 if (FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) && n_next
> size
)
638 if (flags
& READ_FULL_FILE_SECURE
) {
639 t
= malloc(n_next
+ 1);
644 memcpy_safe(t
, buf
, n
);
645 explicit_bzero_safe(buf
, n
);
648 t
= realloc(buf
, n_next
+ 1);
654 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
655 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
656 n
= size
== SIZE_MAX
? MALLOC_SIZEOF_SAFE(buf
) - 1 : n_next
;
659 k
= fread(buf
+ l
, 1, n
- l
, f
);
665 r
= errno_or_else(EIO
);
671 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 */
676 assert(k
> 0); /* we can't have read zero bytes because that would have been EOF */
678 if (FLAGS_SET(flags
, READ_FULL_FILE_FAIL_WHEN_LARGER
) && l
> size
) {
683 if (n
>= READ_FULL_BYTES_MAX
) {
688 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
691 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
692 _cleanup_free_
void *decoded
= NULL
;
696 if (flags
& READ_FULL_FILE_UNBASE64
)
697 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
699 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
703 if (flags
& READ_FULL_FILE_SECURE
)
704 explicit_bzero_safe(buf
, n
);
705 free_and_replace(buf
, decoded
);
706 n
= l
= decoded_size
;
710 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
711 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
712 * there'd be ambiguity about what we just read. */
714 if (memchr(buf
, 0, l
)) {
721 *ret_contents
= TAKE_PTR(buf
);
729 if (flags
& READ_FULL_FILE_SECURE
)
730 explicit_bzero_safe(buf
, n
);
735 int read_full_file_full(
737 const char *filename
,
740 ReadFullFileFlags flags
,
741 const char *bind_name
,
745 _cleanup_fclose_
FILE *f
= NULL
;
749 assert(ret_contents
);
751 r
= xfopenat(dir_fd
, filename
, "re", 0, &f
);
753 _cleanup_close_
int dfd
= -1, sk
= -1;
754 union sockaddr_union sa
;
756 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
760 /* If this is enabled, let's try to connect to it */
761 if (!FLAGS_SET(flags
, READ_FULL_FILE_CONNECT_SOCKET
))
764 /* Seeking is not supported on AF_UNIX sockets */
765 if (offset
!= UINT64_MAX
)
768 if (dir_fd
== AT_FDCWD
)
769 r
= sockaddr_un_set_path(&sa
.un
, filename
);
771 /* If we shall operate relative to some directory, then let's use O_PATH first to
772 * open the socket inode, and then connect to it via /proc/self/fd/. We have to do
773 * this since there's not connectat() that takes a directory fd as first arg. */
775 dfd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
779 r
= sockaddr_un_set_path(&sa
.un
, FORMAT_PROC_FD_PATH(dfd
));
784 sk
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
789 /* If the caller specified a socket name to bind to, do so before connecting. This is
790 * useful to communicate some minor, short meta-information token from the client to
792 union sockaddr_union bsa
;
794 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
798 if (bind(sk
, &bsa
.sa
, r
) < 0)
802 if (connect(sk
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
803 return errno
== ENOTSOCK
? -ENXIO
: -errno
; /* propagate original error if this is
804 * not a socket after all */
806 if (shutdown(sk
, SHUT_WR
) < 0)
816 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
818 return read_full_stream_full(f
, filename
, offset
, size
, flags
, ret_contents
, ret_size
);
821 int executable_is_script(const char *path
, char **interpreter
) {
822 _cleanup_free_
char *line
= NULL
;
829 r
= read_one_line_file(path
, &line
);
830 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
835 if (!startswith(line
, "#!"))
838 ans
= strstrip(line
+ 2);
839 len
= strcspn(ans
, " \t");
844 ans
= strndup(ans
, len
);
853 * Retrieve one field from a file like /proc/self/status. pattern
854 * should not include whitespace or the delimiter (':'). pattern matches only
855 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
856 * zeros after the ':' will be skipped. field must be freed afterwards.
857 * terminator specifies the terminating characters of the field value (not
858 * included in the value).
860 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
861 _cleanup_free_
char *status
= NULL
;
871 r
= read_full_virtual_file(filename
, &status
, NULL
);
881 t
= strstr(t
, pattern
);
885 /* Check that pattern occurs in beginning of line. */
886 pattern_ok
= (t
== status
|| t
[-1] == '\n');
888 t
+= strlen(pattern
);
890 } while (!pattern_ok
);
892 t
+= strspn(t
, " \t");
901 t
+= strspn(t
, " \t");
903 /* Also skip zeros, because when this is used for
904 * capabilities, we don't want the zeros. This way the
905 * same capability set always maps to the same string,
906 * irrespective of the total capability set size. For
907 * other numbers it shouldn't matter. */
909 /* Back off one char if there's nothing but whitespace
911 if (!*t
|| isspace(*t
))
915 len
= strcspn(t
, terminator
);
925 DIR *xopendirat(int fd
, const char *name
, int flags
) {
929 assert(!(flags
& O_CREAT
));
931 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
944 static int mode_to_flags(const char *mode
) {
948 if ((p
= startswith(mode
, "r+")))
950 else if ((p
= startswith(mode
, "r")))
952 else if ((p
= startswith(mode
, "w+")))
953 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
954 else if ((p
= startswith(mode
, "w")))
955 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
956 else if ((p
= startswith(mode
, "a+")))
957 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
958 else if ((p
= startswith(mode
, "a")))
959 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
963 for (; *p
!= 0; p
++) {
976 /* ignore this here, fdopen() might care later though */
979 case 'c': /* not sure what to do about this one */
988 int xfopenat(int dir_fd
, const char *path
, const char *mode
, int flags
, FILE **ret
) {
991 /* A combination of fopen() with openat() */
993 if (dir_fd
== AT_FDCWD
&& flags
== 0) {
994 f
= fopen(path
, mode
);
1000 mode_flags
= mode_to_flags(mode
);
1004 fd
= openat(dir_fd
, path
, mode_flags
| flags
);
1008 f
= fdopen(fd
, mode
);
1019 static int search_and_fopen_internal(
1033 if (!path_strv_resolve_uniq(search
, root
))
1036 STRV_FOREACH(i
, search
) {
1037 _cleanup_free_
char *p
= NULL
;
1040 p
= path_join(root
, *i
, path
);
1047 *ret_path
= path_simplify(TAKE_PTR(p
));
1053 if (errno
!= ENOENT
)
1060 int search_and_fopen(
1061 const char *filename
,
1064 const char **search
,
1068 _cleanup_strv_free_
char **copy
= NULL
;
1074 if (path_is_absolute(filename
)) {
1075 _cleanup_fclose_
FILE *f
= NULL
;
1077 f
= fopen(filename
, mode
);
1084 p
= strdup(filename
);
1088 *ret_path
= path_simplify(p
);
1095 copy
= strv_copy((char**) search
);
1099 return search_and_fopen_internal(filename
, mode
, root
, copy
, ret
, ret_path
);
1102 int search_and_fopen_nulstr(
1103 const char *filename
,
1110 _cleanup_strv_free_
char **s
= NULL
;
1112 if (path_is_absolute(filename
)) {
1113 _cleanup_fclose_
FILE *f
= NULL
;
1115 f
= fopen(filename
, mode
);
1122 p
= strdup(filename
);
1126 *ret_path
= path_simplify(p
);
1133 s
= strv_split_nulstr(search
);
1137 return search_and_fopen_internal(filename
, mode
, root
, s
, ret
, ret_path
);
1140 int chase_symlinks_and_fopen_unlocked(
1143 unsigned chase_flags
,
1144 const char *open_flags
,
1148 _cleanup_close_
int fd
= -1;
1149 _cleanup_free_
char *final_path
= NULL
;
1156 mode_flags
= mode_to_flags(open_flags
);
1160 fd
= chase_symlinks_and_open(path
, root
, chase_flags
, mode_flags
, ret_path
? &final_path
: NULL
);
1164 r
= take_fdopen_unlocked(&fd
, open_flags
, ret_file
);
1169 *ret_path
= TAKE_PTR(final_path
);
1173 int fflush_and_check(FILE *f
) {
1180 return errno_or_else(EIO
);
1185 int fflush_sync_and_check(FILE *f
) {
1190 r
= fflush_and_check(f
);
1194 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1195 * assume that in that case we need no explicit syncing */
1207 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1208 char ln
[DECIMAL_STR_MAX(n
)+2];
1210 /* Creates a "timestamp" file, that contains nothing but a
1211 * usec_t timestamp, formatted in ASCII. */
1213 if (n
<= 0 || n
>= USEC_INFINITY
)
1216 xsprintf(ln
, USEC_FMT
"\n", n
);
1218 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1221 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1222 _cleanup_free_
char *ln
= NULL
;
1226 r
= read_one_line_file(fn
, &ln
);
1230 r
= safe_atou64(ln
, &t
);
1234 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1241 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1246 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1247 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1248 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1249 * element, but not before the first one. */
1259 r
= fputs(separator
, f
);
1270 /* A bitmask of the EOL markers we know */
1271 typedef enum EndOfLineMarker
{
1273 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
1274 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
1275 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
1278 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
1280 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
1284 return EOL_THIRTEEN
;
1293 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile
, NULL
);
1295 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
1296 _cleanup_free_
char *buffer
= NULL
;
1297 size_t n
= 0, count
= 0;
1302 /* Something like a bounded version of getline().
1304 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1305 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1318 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1319 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1321 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1322 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1324 * If a line shall be skipped ret may be initialized as NULL. */
1327 if (!GREEDY_REALLOC(buffer
, 1))
1332 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1333 EndOfLineMarker previous_eol
= EOL_NONE
;
1337 EndOfLineMarker eol
;
1343 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1346 r
= safe_fgetc(f
, &c
);
1349 if (r
== 0) /* EOF is definitely EOL */
1352 eol
= categorize_eol(c
, flags
);
1354 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1355 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1356 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1357 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1358 * EOL marker has been seen right before? In either of these three cases we are
1359 * done. But first, let's put this character back in the queue. (Note that we have to
1360 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1361 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1362 * pass a negative value here. That said, to complicate things further ungetc() is
1363 * actually happy with most negative characters and implicitly casts them back to
1364 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1366 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1372 if (eol
!= EOL_NONE
) {
1373 /* If we are on a tty, we can't shouldn't wait for more input, because that
1374 * generally means waiting for the user, interactively. In the case of a TTY
1375 * we expect only \n as the single EOL marker, so we are in the lucky
1376 * position that there is no need to wait. We check this condition last, to
1377 * avoid isatty() check if not necessary. */
1379 if ((flags
& (READ_LINE_IS_A_TTY
|READ_LINE_NOT_A_TTY
)) == 0) {
1383 if (fd
< 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1384 * and don't call isatty() on an invalid fd */
1385 flags
|= READ_LINE_NOT_A_TTY
;
1387 flags
|= isatty(fd
) ? READ_LINE_IS_A_TTY
: READ_LINE_NOT_A_TTY
;
1389 if (FLAGS_SET(flags
, READ_LINE_IS_A_TTY
))
1393 if (eol
!= EOL_NONE
) {
1394 previous_eol
|= eol
;
1399 if (!GREEDY_REALLOC(buffer
, n
+ 2))
1412 *ret
= TAKE_PTR(buffer
);
1418 int safe_fgetc(FILE *f
, char *ret
) {
1423 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1424 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1431 return errno_or_else(EIO
);
1445 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1452 if (stat(filename
, &_st
) < 0)
1457 if ((st
->st_mode
& S_IRWXO
) == 0)
1461 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1462 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1463 filename
, st
->st_mode
& 07777);
1465 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1466 filename
, st
->st_mode
& 07777);