1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/types.h>
16 #include "alloc-util.h"
20 #include "hexdecoct.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "stdio-util.h"
27 #include "string-util.h"
28 #include "tmpfile-util.h"
30 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
32 int fopen_unlocked(const char *path
, const char *options
, FILE **ret
) {
35 FILE *f
= fopen(path
, options
);
39 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
45 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
48 FILE *f
= fdopen(fd
, options
);
52 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
58 int write_string_stream_ts(
61 WriteStringFileFlags flags
,
62 struct timespec
*ts
) {
73 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
75 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
76 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
77 * that the write goes out in one go, instead of two */
79 line
= strjoina(line
, "\n");
83 if (fputs(line
, f
) == EOF
)
87 if (fputc('\n', f
) == EOF
)
90 if (flags
& WRITE_STRING_FILE_SYNC
)
91 r
= fflush_sync_and_check(f
);
93 r
= fflush_and_check(f
);
98 struct timespec twice
[2] = {*ts
, *ts
};
100 if (futimens(fileno(f
), twice
) < 0)
107 static int write_string_file_atomic(
110 WriteStringFileFlags flags
,
111 struct timespec
*ts
) {
113 _cleanup_fclose_
FILE *f
= NULL
;
114 _cleanup_free_
char *p
= NULL
;
120 r
= fopen_temporary(fn
, &f
, &p
);
124 (void) fchmod_umask(fileno(f
), 0644);
126 r
= write_string_stream_ts(f
, line
, flags
, ts
);
130 if (rename(p
, fn
) < 0) {
142 int write_string_file_ts(
145 WriteStringFileFlags flags
,
146 struct timespec
*ts
) {
148 _cleanup_fclose_
FILE *f
= NULL
;
154 /* We don't know how to verify whether the file contents was already on-disk. */
155 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
157 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
158 assert(flags
& WRITE_STRING_FILE_CREATE
);
160 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
168 if (flags
& WRITE_STRING_FILE_CREATE
) {
169 r
= fopen_unlocked(fn
, "we", &f
);
175 /* We manually build our own version of fopen(..., "we") that
176 * works without O_CREAT */
177 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
183 r
= fdopen_unlocked(fd
, "w", &f
);
190 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
191 setvbuf(f
, NULL
, _IONBF
, 0);
193 r
= write_string_stream_ts(f
, line
, flags
, ts
);
200 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
205 /* OK, the operation failed, but let's see if the right
206 * contents in place already. If so, eat up the error. */
208 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
215 int write_string_filef(
217 WriteStringFileFlags flags
,
218 const char *format
, ...) {
220 _cleanup_free_
char *p
= NULL
;
224 va_start(ap
, format
);
225 r
= vasprintf(&p
, format
, ap
);
231 return write_string_file(fn
, p
, flags
);
234 int read_one_line_file(const char *fn
, char **line
) {
235 _cleanup_fclose_
FILE *f
= NULL
;
241 r
= fopen_unlocked(fn
, "re", &f
);
245 return read_line(f
, LONG_LINE_MAX
, line
);
248 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
249 _cleanup_fclose_
FILE *f
= NULL
;
250 _cleanup_free_
char *buf
= NULL
;
259 if (accept_extra_nl
&& endswith(blob
, "\n"))
260 accept_extra_nl
= false;
262 buf
= malloc(l
+ accept_extra_nl
+ 1);
266 r
= fopen_unlocked(fn
, "re", &f
);
270 /* We try to read one byte more than we need, so that we know whether we hit eof */
272 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
274 return errno
> 0 ? -errno
: -EIO
;
276 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
278 if (memcmp(buf
, blob
, l
) != 0)
280 if (k
> l
&& buf
[l
] != '\n')
286 int read_full_stream_full(
288 const char *filename
,
289 ReadFullFileFlags flags
,
293 _cleanup_free_
char *buf
= NULL
;
299 assert(ret_contents
);
300 assert(!(flags
& READ_FULL_FILE_UNBASE64
) || ret_size
);
302 n_next
= LINE_MAX
; /* Start size */
305 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
306 * optimize our buffering) */
308 if (fstat(fd
, &st
) < 0)
311 if (S_ISREG(st
.st_mode
)) {
314 if (st
.st_size
> READ_FULL_BYTES_MAX
)
317 /* Start with the right file size, but be prepared for files from /proc which generally report a file
318 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
319 * already makes us notice the EOF. */
321 n_next
= st
.st_size
+ 1;
323 if (flags
& READ_FULL_FILE_SECURE
)
324 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
333 if (flags
& READ_FULL_FILE_SECURE
) {
334 t
= malloc(n_next
+ 1);
339 memcpy_safe(t
, buf
, n
);
340 explicit_bzero_safe(buf
, n
);
342 t
= realloc(buf
, n_next
+ 1);
351 k
= fread(buf
+ l
, 1, n
- l
, f
);
356 r
= errno
> 0 ? -errno
: -EIO
;
363 /* We aren't expecting fread() to return a short read outside
364 * of (error && eof), assert buffer is full and enlarge buffer.
369 if (n
>= READ_FULL_BYTES_MAX
) {
374 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
377 if (flags
& READ_FULL_FILE_UNBASE64
) {
379 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
384 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
385 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
386 * there'd be ambiguity about what we just read. */
388 if (memchr(buf
, 0, l
)) {
395 *ret_contents
= TAKE_PTR(buf
);
403 if (flags
& READ_FULL_FILE_SECURE
)
404 explicit_bzero_safe(buf
, n
);
409 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
410 _cleanup_fclose_
FILE *f
= NULL
;
416 r
= fopen_unlocked(filename
, "re", &f
);
420 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
423 int executable_is_script(const char *path
, char **interpreter
) {
424 _cleanup_free_
char *line
= NULL
;
431 r
= read_one_line_file(path
, &line
);
432 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
437 if (!startswith(line
, "#!"))
440 ans
= strstrip(line
+ 2);
441 len
= strcspn(ans
, " \t");
446 ans
= strndup(ans
, len
);
455 * Retrieve one field from a file like /proc/self/status. pattern
456 * should not include whitespace or the delimiter (':'). pattern matches only
457 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
458 * zeros after the ':' will be skipped. field must be freed afterwards.
459 * terminator specifies the terminating characters of the field value (not
460 * included in the value).
462 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
463 _cleanup_free_
char *status
= NULL
;
473 r
= read_full_file(filename
, &status
, NULL
);
483 t
= strstr(t
, pattern
);
487 /* Check that pattern occurs in beginning of line. */
488 pattern_ok
= (t
== status
|| t
[-1] == '\n');
490 t
+= strlen(pattern
);
492 } while (!pattern_ok
);
494 t
+= strspn(t
, " \t");
503 t
+= strspn(t
, " \t");
505 /* Also skip zeros, because when this is used for
506 * capabilities, we don't want the zeros. This way the
507 * same capability set always maps to the same string,
508 * irrespective of the total capability set size. For
509 * other numbers it shouldn't matter. */
511 /* Back off one char if there's nothing but whitespace
513 if (!*t
|| isspace(*t
))
517 len
= strcspn(t
, terminator
);
527 DIR *xopendirat(int fd
, const char *name
, int flags
) {
531 assert(!(flags
& O_CREAT
));
533 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
546 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
553 if (!path_strv_resolve_uniq(search
, root
))
556 STRV_FOREACH(i
, search
) {
557 _cleanup_free_
char *p
= NULL
;
561 p
= strjoin(root
, *i
, "/", path
);
563 p
= strjoin(*i
, "/", path
);
580 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
581 _cleanup_strv_free_
char **copy
= NULL
;
587 if (path_is_absolute(path
)) {
590 f
= fopen(path
, mode
);
599 copy
= strv_copy((char**) search
);
603 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
606 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
607 _cleanup_strv_free_
char **s
= NULL
;
609 if (path_is_absolute(path
)) {
612 f
= fopen(path
, mode
);
621 s
= strv_split_nulstr(search
);
625 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
628 int fflush_and_check(FILE *f
) {
635 return errno
> 0 ? -errno
: -EIO
;
640 int fflush_sync_and_check(FILE *f
) {
645 r
= fflush_and_check(f
);
649 if (fsync(fileno(f
)) < 0)
652 r
= fsync_directory_of_file(fileno(f
));
659 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
660 char ln
[DECIMAL_STR_MAX(n
)+2];
662 /* Creates a "timestamp" file, that contains nothing but a
663 * usec_t timestamp, formatted in ASCII. */
665 if (n
<= 0 || n
>= USEC_INFINITY
)
668 xsprintf(ln
, USEC_FMT
"\n", n
);
670 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
673 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
674 _cleanup_free_
char *ln
= NULL
;
678 r
= read_one_line_file(fn
, &ln
);
682 r
= safe_atou64(ln
, &t
);
686 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
693 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
698 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
699 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
700 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
701 * element, but not before the first one. */
711 r
= fputs(separator
, f
);
722 /* A bitmask of the EOL markers we know */
723 typedef enum EndOfLineMarker
{
725 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
726 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
727 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
730 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
732 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
745 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
747 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
748 size_t n
= 0, allocated
= 0, count
= 0;
749 _cleanup_free_
char *buffer
= NULL
;
754 /* Something like a bounded version of getline().
756 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
757 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
770 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
771 * the number of characters in the returned string). When EOF is hit, 0 is returned.
773 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
774 * delimiters. If the limit is hit we fail and return -ENOBUFS.
776 * If a line shall be skipped ret may be initialized as NULL. */
779 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
784 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
785 EndOfLineMarker previous_eol
= EOL_NONE
;
795 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
798 r
= safe_fgetc(f
, &c
);
801 if (r
== 0) /* EOF is definitely EOL */
804 eol
= categorize_eol(c
, flags
);
806 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
807 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
808 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
809 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
810 * EOL marker has been seen right before? In either of these three cases we are
811 * done. But first, let's put this character back in the queue. (Note that we have to
812 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
813 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
814 * pass a negative value here. That said, to complicate things further ungetc() is
815 * actually happy with most negative characters and implicitly casts them back to
816 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
818 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
824 if (eol
!= EOL_NONE
) {
830 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
843 *ret
= TAKE_PTR(buffer
);
849 int safe_fgetc(FILE *f
, char *ret
) {
854 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
855 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
862 return errno
> 0 ? -errno
: -EIO
;
876 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
883 if (stat(filename
, &_st
) < 0)
888 if ((st
->st_mode
& S_IRWXO
) == 0)
892 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
893 "%s has %04o mode that is too permissive, please adjust the access mode.",
894 filename
, st
->st_mode
& 07777);
896 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
897 filename
, st
->st_mode
& 07777);