1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/types.h>
16 #include "alloc-util.h"
20 #include "hexdecoct.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "tmpfile-util.h"
31 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
33 int fopen_unlocked(const char *path
, const char *options
, FILE **ret
) {
36 FILE *f
= fopen(path
, options
);
40 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
46 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
49 FILE *f
= fdopen(fd
, options
);
53 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
59 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
60 FILE *f
= open_memstream(ptr
, sizeloc
);
64 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
69 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
70 FILE *f
= fmemopen(buf
, size
, mode
);
74 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
79 int write_string_stream_ts(
82 WriteStringFileFlags flags
,
83 struct timespec
*ts
) {
94 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
96 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
97 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
98 * that the write goes out in one go, instead of two */
100 line
= strjoina(line
, "\n");
104 if (fputs(line
, f
) == EOF
)
108 if (fputc('\n', f
) == EOF
)
111 if (flags
& WRITE_STRING_FILE_SYNC
)
112 r
= fflush_sync_and_check(f
);
114 r
= fflush_and_check(f
);
119 struct timespec twice
[2] = {*ts
, *ts
};
121 if (futimens(fileno(f
), twice
) < 0)
128 static int write_string_file_atomic(
131 WriteStringFileFlags flags
,
132 struct timespec
*ts
) {
134 _cleanup_fclose_
FILE *f
= NULL
;
135 _cleanup_free_
char *p
= NULL
;
141 r
= fopen_temporary(fn
, &f
, &p
);
145 (void) fchmod_umask(fileno(f
), 0644);
147 r
= write_string_stream_ts(f
, line
, flags
, ts
);
151 if (rename(p
, fn
) < 0) {
163 int write_string_file_ts(
166 WriteStringFileFlags flags
,
167 struct timespec
*ts
) {
169 _cleanup_fclose_
FILE *f
= NULL
;
175 /* We don't know how to verify whether the file contents was already on-disk. */
176 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
178 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
179 r
= mkdir_parents(fn
, 0755);
184 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
185 assert(flags
& WRITE_STRING_FILE_CREATE
);
187 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
195 if (flags
& WRITE_STRING_FILE_CREATE
) {
196 r
= fopen_unlocked(fn
, "we", &f
);
202 /* We manually build our own version of fopen(..., "we") that
203 * works without O_CREAT */
204 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
210 r
= fdopen_unlocked(fd
, "w", &f
);
217 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
218 setvbuf(f
, NULL
, _IONBF
, 0);
220 r
= write_string_stream_ts(f
, line
, flags
, ts
);
227 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
232 /* OK, the operation failed, but let's see if the right
233 * contents in place already. If so, eat up the error. */
235 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
242 int write_string_filef(
244 WriteStringFileFlags flags
,
245 const char *format
, ...) {
247 _cleanup_free_
char *p
= NULL
;
251 va_start(ap
, format
);
252 r
= vasprintf(&p
, format
, ap
);
258 return write_string_file(fn
, p
, flags
);
261 int read_one_line_file(const char *fn
, char **line
) {
262 _cleanup_fclose_
FILE *f
= NULL
;
268 r
= fopen_unlocked(fn
, "re", &f
);
272 return read_line(f
, LONG_LINE_MAX
, line
);
275 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
276 _cleanup_fclose_
FILE *f
= NULL
;
277 _cleanup_free_
char *buf
= NULL
;
286 if (accept_extra_nl
&& endswith(blob
, "\n"))
287 accept_extra_nl
= false;
289 buf
= malloc(l
+ accept_extra_nl
+ 1);
293 r
= fopen_unlocked(fn
, "re", &f
);
297 /* We try to read one byte more than we need, so that we know whether we hit eof */
299 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
301 return errno_or_else(EIO
);
303 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
305 if (memcmp(buf
, blob
, l
) != 0)
307 if (k
> l
&& buf
[l
] != '\n')
313 int read_full_stream_full(
315 const char *filename
,
316 ReadFullFileFlags flags
,
320 _cleanup_free_
char *buf
= NULL
;
326 assert(ret_contents
);
327 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
328 assert(!(flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) || ret_size
);
330 n_next
= LINE_MAX
; /* Start size */
333 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
334 * optimize our buffering) */
336 if (fstat(fd
, &st
) < 0)
339 if (S_ISREG(st
.st_mode
)) {
342 if (st
.st_size
> READ_FULL_BYTES_MAX
)
345 /* Start with the right file size, but be prepared for files from /proc which generally report a file
346 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
347 * already makes us notice the EOF. */
349 n_next
= st
.st_size
+ 1;
351 if (flags
& READ_FULL_FILE_SECURE
)
352 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
361 if (flags
& READ_FULL_FILE_SECURE
) {
362 t
= malloc(n_next
+ 1);
367 memcpy_safe(t
, buf
, n
);
368 explicit_bzero_safe(buf
, n
);
371 t
= realloc(buf
, n_next
+ 1);
380 k
= fread(buf
+ l
, 1, n
- l
, f
);
385 r
= errno_or_else(EIO
);
392 /* We aren't expecting fread() to return a short read outside
393 * of (error && eof), assert buffer is full and enlarge buffer.
398 if (n
>= READ_FULL_BYTES_MAX
) {
403 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
406 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
408 if (flags
& READ_FULL_FILE_UNBASE64
)
409 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
411 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
416 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
417 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
418 * there'd be ambiguity about what we just read. */
420 if (memchr(buf
, 0, l
)) {
427 *ret_contents
= TAKE_PTR(buf
);
435 if (flags
& READ_FULL_FILE_SECURE
)
436 explicit_bzero_safe(buf
, n
);
441 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
442 _cleanup_fclose_
FILE *f
= NULL
;
448 r
= fopen_unlocked(filename
, "re", &f
);
452 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
455 int executable_is_script(const char *path
, char **interpreter
) {
456 _cleanup_free_
char *line
= NULL
;
463 r
= read_one_line_file(path
, &line
);
464 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
469 if (!startswith(line
, "#!"))
472 ans
= strstrip(line
+ 2);
473 len
= strcspn(ans
, " \t");
478 ans
= strndup(ans
, len
);
487 * Retrieve one field from a file like /proc/self/status. pattern
488 * should not include whitespace or the delimiter (':'). pattern matches only
489 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
490 * zeros after the ':' will be skipped. field must be freed afterwards.
491 * terminator specifies the terminating characters of the field value (not
492 * included in the value).
494 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
495 _cleanup_free_
char *status
= NULL
;
505 r
= read_full_file(filename
, &status
, NULL
);
515 t
= strstr(t
, pattern
);
519 /* Check that pattern occurs in beginning of line. */
520 pattern_ok
= (t
== status
|| t
[-1] == '\n');
522 t
+= strlen(pattern
);
524 } while (!pattern_ok
);
526 t
+= strspn(t
, " \t");
535 t
+= strspn(t
, " \t");
537 /* Also skip zeros, because when this is used for
538 * capabilities, we don't want the zeros. This way the
539 * same capability set always maps to the same string,
540 * irrespective of the total capability set size. For
541 * other numbers it shouldn't matter. */
543 /* Back off one char if there's nothing but whitespace
545 if (!*t
|| isspace(*t
))
549 len
= strcspn(t
, terminator
);
559 DIR *xopendirat(int fd
, const char *name
, int flags
) {
563 assert(!(flags
& O_CREAT
));
565 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
578 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
585 if (!path_strv_resolve_uniq(search
, root
))
588 STRV_FOREACH(i
, search
) {
589 _cleanup_free_
char *p
= NULL
;
592 p
= path_join(root
, *i
, path
);
609 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
610 _cleanup_strv_free_
char **copy
= NULL
;
616 if (path_is_absolute(path
)) {
619 f
= fopen(path
, mode
);
628 copy
= strv_copy((char**) search
);
632 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
635 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
636 _cleanup_strv_free_
char **s
= NULL
;
638 if (path_is_absolute(path
)) {
641 f
= fopen(path
, mode
);
650 s
= strv_split_nulstr(search
);
654 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
657 int fflush_and_check(FILE *f
) {
664 return errno_or_else(EIO
);
669 int fflush_sync_and_check(FILE *f
) {
674 r
= fflush_and_check(f
);
678 if (fsync(fileno(f
)) < 0)
681 r
= fsync_directory_of_file(fileno(f
));
688 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
689 char ln
[DECIMAL_STR_MAX(n
)+2];
691 /* Creates a "timestamp" file, that contains nothing but a
692 * usec_t timestamp, formatted in ASCII. */
694 if (n
<= 0 || n
>= USEC_INFINITY
)
697 xsprintf(ln
, USEC_FMT
"\n", n
);
699 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
702 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
703 _cleanup_free_
char *ln
= NULL
;
707 r
= read_one_line_file(fn
, &ln
);
711 r
= safe_atou64(ln
, &t
);
715 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
722 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
727 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
728 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
729 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
730 * element, but not before the first one. */
740 r
= fputs(separator
, f
);
751 /* A bitmask of the EOL markers we know */
752 typedef enum EndOfLineMarker
{
754 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
755 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
756 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
759 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
761 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
774 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
776 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
777 size_t n
= 0, allocated
= 0, count
= 0;
778 _cleanup_free_
char *buffer
= NULL
;
783 /* Something like a bounded version of getline().
785 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
786 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
799 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
800 * the number of characters in the returned string). When EOF is hit, 0 is returned.
802 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
803 * delimiters. If the limit is hit we fail and return -ENOBUFS.
805 * If a line shall be skipped ret may be initialized as NULL. */
808 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
813 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
814 EndOfLineMarker previous_eol
= EOL_NONE
;
824 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
827 r
= safe_fgetc(f
, &c
);
830 if (r
== 0) /* EOF is definitely EOL */
833 eol
= categorize_eol(c
, flags
);
835 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
836 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
837 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
838 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
839 * EOL marker has been seen right before? In either of these three cases we are
840 * done. But first, let's put this character back in the queue. (Note that we have to
841 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
842 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
843 * pass a negative value here. That said, to complicate things further ungetc() is
844 * actually happy with most negative characters and implicitly casts them back to
845 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
847 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
853 if (eol
!= EOL_NONE
) {
854 /* If we are on a tty, we can't wait for more input. But we expect only
855 * \n as the single EOL marker, so there is no need to wait. We check
856 * this condition last to avoid isatty() check if not necessary. */
859 tty
= isatty(fileno(f
));
864 if (eol
!= EOL_NONE
) {
870 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
883 *ret
= TAKE_PTR(buffer
);
889 int safe_fgetc(FILE *f
, char *ret
) {
894 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
895 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
902 return errno_or_else(EIO
);
916 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
923 if (stat(filename
, &_st
) < 0)
928 if ((st
->st_mode
& S_IRWXO
) == 0)
932 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
933 "%s has %04o mode that is too permissive, please adjust the access mode.",
934 filename
, st
->st_mode
& 07777);
936 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
937 filename
, st
->st_mode
& 07777);