1 /* SPDX-License-Identifier: LGPL-2.1+ */
12 #include <sys/types.h>
15 #include "alloc-util.h"
19 #include "hexdecoct.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "stdio-util.h"
26 #include "string-util.h"
27 #include "tmpfile-util.h"
29 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
31 int fopen_unlocked(const char *path
, const char *options
, FILE **ret
) {
34 FILE *f
= fopen(path
, options
);
38 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
44 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
47 FILE *f
= fdopen(fd
, options
);
51 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
57 int take_fdopen_unlocked(int *fd
, const char *options
, FILE **ret
) {
62 r
= fdopen_unlocked(*fd
, options
, ret
);
71 FILE* take_fdopen(int *fd
, const char *options
) {
74 FILE *f
= fdopen(*fd
, options
);
83 DIR* take_fdopendir(int *dfd
) {
86 DIR *d
= fdopendir(*dfd
);
95 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
96 FILE *f
= open_memstream(ptr
, sizeloc
);
100 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
105 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
106 FILE *f
= fmemopen(buf
, size
, mode
);
110 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
115 int write_string_stream_ts(
118 WriteStringFileFlags flags
,
119 struct timespec
*ts
) {
130 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
132 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
133 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
134 * that the write goes out in one go, instead of two */
136 line
= strjoina(line
, "\n");
140 if (fputs(line
, f
) == EOF
)
144 if (fputc('\n', f
) == EOF
)
147 if (flags
& WRITE_STRING_FILE_SYNC
)
148 r
= fflush_sync_and_check(f
);
150 r
= fflush_and_check(f
);
155 struct timespec twice
[2] = {*ts
, *ts
};
157 if (futimens(fileno(f
), twice
) < 0)
164 static int write_string_file_atomic(
167 WriteStringFileFlags flags
,
168 struct timespec
*ts
) {
170 _cleanup_fclose_
FILE *f
= NULL
;
171 _cleanup_free_
char *p
= NULL
;
177 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
178 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
180 r
= fopen_temporary(fn
, &f
, &p
);
184 r
= write_string_stream_ts(f
, line
, flags
, ts
);
188 r
= fchmod_umask(fileno(f
), FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0644);
192 if (rename(p
, fn
) < 0) {
204 int write_string_file_ts(
207 WriteStringFileFlags flags
,
208 struct timespec
*ts
) {
210 _cleanup_fclose_
FILE *f
= NULL
;
216 /* We don't know how to verify whether the file contents was already on-disk. */
217 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
219 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
220 r
= mkdir_parents(fn
, 0755);
225 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
226 assert(flags
& WRITE_STRING_FILE_CREATE
);
228 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
236 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
237 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|
238 (FLAGS_SET(flags
, WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0) |
239 (FLAGS_SET(flags
, WRITE_STRING_FILE_CREATE
) ? O_CREAT
: 0),
240 (FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0666));
246 r
= fdopen_unlocked(fd
, "w", &f
);
252 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
253 setvbuf(f
, NULL
, _IONBF
, 0);
255 r
= write_string_stream_ts(f
, line
, flags
, ts
);
262 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
267 /* OK, the operation failed, but let's see if the right
268 * contents in place already. If so, eat up the error. */
270 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
277 int write_string_filef(
279 WriteStringFileFlags flags
,
280 const char *format
, ...) {
282 _cleanup_free_
char *p
= NULL
;
286 va_start(ap
, format
);
287 r
= vasprintf(&p
, format
, ap
);
293 return write_string_file(fn
, p
, flags
);
296 int read_one_line_file(const char *fn
, char **line
) {
297 _cleanup_fclose_
FILE *f
= NULL
;
303 r
= fopen_unlocked(fn
, "re", &f
);
307 return read_line(f
, LONG_LINE_MAX
, line
);
310 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
311 _cleanup_fclose_
FILE *f
= NULL
;
312 _cleanup_free_
char *buf
= NULL
;
321 if (accept_extra_nl
&& endswith(blob
, "\n"))
322 accept_extra_nl
= false;
324 buf
= malloc(l
+ accept_extra_nl
+ 1);
328 r
= fopen_unlocked(fn
, "re", &f
);
332 /* We try to read one byte more than we need, so that we know whether we hit eof */
334 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
336 return errno_or_else(EIO
);
338 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
340 if (memcmp(buf
, blob
, l
) != 0)
342 if (k
> l
&& buf
[l
] != '\n')
348 int read_full_virtual_file(const char *filename
, char **ret_contents
, size_t *ret_size
) {
349 _cleanup_free_
char *buf
= NULL
;
350 _cleanup_close_
int fd
= -1;
356 assert(ret_contents
);
358 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work
359 * with two sorts of virtual files. One sort uses "seq_file", and the results of
360 * the first read are buffered for the second read. The other sort uses "raw"
361 * reads which always go direct to the device. In the latter case, the content of
362 * the virtual file must be retrieved with a single read otherwise a second read
363 * might get the new value instead of finding EOF immediately. That's the reason
364 * why the usage of fread(3) is prohibited in this case as it always performs a
365 * second call to read(2) looking for EOF. See issue 13585. */
367 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
371 /* Start size for files in /proc which usually report a file size of 0. */
374 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
381 if (fstat(fd
, &st
) < 0)
384 if (!S_ISREG(st
.st_mode
))
387 /* Be prepared for files from /proc which generally report a file size of 0. */
388 if (st
.st_size
> 0) {
394 if (size
> READ_FULL_BYTES_MAX
)
397 p
= realloc(buf
, size
+ 1);
405 /* Read one more byte so we can detect whether the content of the
406 * file has already changed or the guessed size for files from /proc
407 * wasn't large enough . */
408 k
= read(fd
, buf
, size
+ 1);
418 /* Consider a short read as EOF */
422 /* Hmm... either we read too few bytes from /proc or less likely the content
423 * of the file might have been changed (and is now bigger) while we were
424 * processing, let's try again either with a bigger guessed size or the new
427 if (lseek(fd
, 0, SEEK_SET
) < 0)
432 p
= realloc(buf
, n
+ 1);
439 /* Safety check: if the caller doesn't want to know the size of what we
440 * just read it will rely on the trailing NUL byte. But if there's an
441 * embedded NUL byte, then we should refuse operation as otherwise
442 * there'd be ambiguity about what we just read. */
444 if (memchr(buf
, 0, n
))
450 *ret_contents
= TAKE_PTR(buf
);
455 int read_full_stream_full(
457 const char *filename
,
458 ReadFullFileFlags flags
,
462 _cleanup_free_
char *buf
= NULL
;
468 assert(ret_contents
);
469 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
470 assert(!(flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) || ret_size
);
472 n_next
= LINE_MAX
; /* Start size */
475 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
476 * optimize our buffering) */
478 if (fstat(fd
, &st
) < 0)
481 if (S_ISREG(st
.st_mode
)) {
484 if (st
.st_size
> READ_FULL_BYTES_MAX
)
487 /* Start with the right file size. Note that we increase the size
488 * to read here by one, so that the first read attempt already
489 * makes us notice the EOF. */
491 n_next
= st
.st_size
+ 1;
493 if (flags
& READ_FULL_FILE_SECURE
)
494 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
503 if (flags
& READ_FULL_FILE_SECURE
) {
504 t
= malloc(n_next
+ 1);
509 memcpy_safe(t
, buf
, n
);
510 explicit_bzero_safe(buf
, n
);
513 t
= realloc(buf
, n_next
+ 1);
522 k
= fread(buf
+ l
, 1, n
- l
, f
);
527 r
= errno_or_else(EIO
);
534 /* We aren't expecting fread() to return a short read outside
535 * of (error && eof), assert buffer is full and enlarge buffer.
540 if (n
>= READ_FULL_BYTES_MAX
) {
545 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
548 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
550 if (flags
& READ_FULL_FILE_UNBASE64
)
551 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
553 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
558 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
559 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
560 * there'd be ambiguity about what we just read. */
562 if (memchr(buf
, 0, l
)) {
569 *ret_contents
= TAKE_PTR(buf
);
577 if (flags
& READ_FULL_FILE_SECURE
)
578 explicit_bzero_safe(buf
, n
);
583 int read_full_file_full(int dir_fd
, const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
584 _cleanup_fclose_
FILE *f
= NULL
;
590 r
= xfopenat(dir_fd
, filename
, "re", 0, &f
);
594 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
596 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
599 int executable_is_script(const char *path
, char **interpreter
) {
600 _cleanup_free_
char *line
= NULL
;
607 r
= read_one_line_file(path
, &line
);
608 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
613 if (!startswith(line
, "#!"))
616 ans
= strstrip(line
+ 2);
617 len
= strcspn(ans
, " \t");
622 ans
= strndup(ans
, len
);
631 * Retrieve one field from a file like /proc/self/status. pattern
632 * should not include whitespace or the delimiter (':'). pattern matches only
633 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
634 * zeros after the ':' will be skipped. field must be freed afterwards.
635 * terminator specifies the terminating characters of the field value (not
636 * included in the value).
638 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
639 _cleanup_free_
char *status
= NULL
;
649 r
= read_full_virtual_file(filename
, &status
, NULL
);
659 t
= strstr(t
, pattern
);
663 /* Check that pattern occurs in beginning of line. */
664 pattern_ok
= (t
== status
|| t
[-1] == '\n');
666 t
+= strlen(pattern
);
668 } while (!pattern_ok
);
670 t
+= strspn(t
, " \t");
679 t
+= strspn(t
, " \t");
681 /* Also skip zeros, because when this is used for
682 * capabilities, we don't want the zeros. This way the
683 * same capability set always maps to the same string,
684 * irrespective of the total capability set size. For
685 * other numbers it shouldn't matter. */
687 /* Back off one char if there's nothing but whitespace
689 if (!*t
|| isspace(*t
))
693 len
= strcspn(t
, terminator
);
703 DIR *xopendirat(int fd
, const char *name
, int flags
) {
707 assert(!(flags
& O_CREAT
));
709 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
722 static int mode_to_flags(const char *mode
) {
726 if ((p
= startswith(mode
, "r+")))
728 else if ((p
= startswith(mode
, "r")))
730 else if ((p
= startswith(mode
, "w+")))
731 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
732 else if ((p
= startswith(mode
, "w")))
733 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
734 else if ((p
= startswith(mode
, "a+")))
735 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
736 else if ((p
= startswith(mode
, "a")))
737 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
741 for (; *p
!= 0; p
++) {
754 /* ignore this here, fdopen() might care later though */
757 case 'c': /* not sure what to do about this one */
766 int xfopenat(int dir_fd
, const char *path
, const char *mode
, int flags
, FILE **ret
) {
769 /* A combination of fopen() with openat() */
771 if (dir_fd
== AT_FDCWD
&& flags
== 0) {
772 f
= fopen(path
, mode
);
778 mode_flags
= mode_to_flags(mode
);
782 fd
= openat(dir_fd
, path
, mode_flags
| flags
);
786 f
= fdopen(fd
, mode
);
797 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
804 if (!path_strv_resolve_uniq(search
, root
))
807 STRV_FOREACH(i
, search
) {
808 _cleanup_free_
char *p
= NULL
;
811 p
= path_join(root
, *i
, path
);
828 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
829 _cleanup_strv_free_
char **copy
= NULL
;
835 if (path_is_absolute(path
)) {
838 f
= fopen(path
, mode
);
847 copy
= strv_copy((char**) search
);
851 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
854 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
855 _cleanup_strv_free_
char **s
= NULL
;
857 if (path_is_absolute(path
)) {
860 f
= fopen(path
, mode
);
869 s
= strv_split_nulstr(search
);
873 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
876 int fflush_and_check(FILE *f
) {
883 return errno_or_else(EIO
);
888 int fflush_sync_and_check(FILE *f
) {
893 r
= fflush_and_check(f
);
897 if (fsync(fileno(f
)) < 0)
900 r
= fsync_directory_of_file(fileno(f
));
907 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
908 char ln
[DECIMAL_STR_MAX(n
)+2];
910 /* Creates a "timestamp" file, that contains nothing but a
911 * usec_t timestamp, formatted in ASCII. */
913 if (n
<= 0 || n
>= USEC_INFINITY
)
916 xsprintf(ln
, USEC_FMT
"\n", n
);
918 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
921 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
922 _cleanup_free_
char *ln
= NULL
;
926 r
= read_one_line_file(fn
, &ln
);
930 r
= safe_atou64(ln
, &t
);
934 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
941 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
946 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
947 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
948 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
949 * element, but not before the first one. */
959 r
= fputs(separator
, f
);
970 /* A bitmask of the EOL markers we know */
971 typedef enum EndOfLineMarker
{
973 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
974 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
975 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
978 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
980 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
993 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
995 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
996 size_t n
= 0, allocated
= 0, count
= 0;
997 _cleanup_free_
char *buffer
= NULL
;
1002 /* Something like a bounded version of getline().
1004 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1005 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1018 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1019 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1021 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1022 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1024 * If a line shall be skipped ret may be initialized as NULL. */
1027 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1032 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1033 EndOfLineMarker previous_eol
= EOL_NONE
;
1037 EndOfLineMarker eol
;
1043 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1046 r
= safe_fgetc(f
, &c
);
1049 if (r
== 0) /* EOF is definitely EOL */
1052 eol
= categorize_eol(c
, flags
);
1054 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1055 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1056 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1057 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1058 * EOL marker has been seen right before? In either of these three cases we are
1059 * done. But first, let's put this character back in the queue. (Note that we have to
1060 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1061 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1062 * pass a negative value here. That said, to complicate things further ungetc() is
1063 * actually happy with most negative characters and implicitly casts them back to
1064 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1066 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1072 if (eol
!= EOL_NONE
) {
1073 /* If we are on a tty, we can't wait for more input. But we expect only
1074 * \n as the single EOL marker, so there is no need to wait. We check
1075 * this condition last to avoid isatty() check if not necessary. */
1078 tty
= isatty(fileno(f
));
1083 if (eol
!= EOL_NONE
) {
1084 previous_eol
|= eol
;
1089 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1102 *ret
= TAKE_PTR(buffer
);
1108 int safe_fgetc(FILE *f
, char *ret
) {
1113 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1114 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1121 return errno_or_else(EIO
);
1135 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1142 if (stat(filename
, &_st
) < 0)
1147 if ((st
->st_mode
& S_IRWXO
) == 0)
1151 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1152 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1153 filename
, st
->st_mode
& 07777);
1155 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1156 filename
, st
->st_mode
& 07777);