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 write_string_stream_ts(
48 WriteStringFileFlags flags
,
49 struct timespec
*ts
) {
60 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
62 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
63 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
64 * that the write goes out in one go, instead of two */
66 line
= strjoina(line
, "\n");
70 if (fputs(line
, f
) == EOF
)
74 if (fputc('\n', f
) == EOF
)
77 if (flags
& WRITE_STRING_FILE_SYNC
)
78 r
= fflush_sync_and_check(f
);
80 r
= fflush_and_check(f
);
85 struct timespec twice
[2] = {*ts
, *ts
};
87 if (futimens(fileno(f
), twice
) < 0)
94 static int write_string_file_atomic(
97 WriteStringFileFlags flags
,
98 struct timespec
*ts
) {
100 _cleanup_fclose_
FILE *f
= NULL
;
101 _cleanup_free_
char *p
= NULL
;
107 r
= fopen_temporary(fn
, &f
, &p
);
111 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
112 (void) fchmod_umask(fileno(f
), 0644);
114 r
= write_string_stream_ts(f
, line
, flags
, ts
);
118 if (rename(p
, fn
) < 0) {
130 int write_string_file_ts(
133 WriteStringFileFlags flags
,
134 struct timespec
*ts
) {
136 _cleanup_fclose_
FILE *f
= NULL
;
142 /* We don't know how to verify whether the file contents was already on-disk. */
143 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
145 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
146 assert(flags
& WRITE_STRING_FILE_CREATE
);
148 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
156 if (flags
& WRITE_STRING_FILE_CREATE
) {
165 /* We manually build our own version of fopen(..., "we") that
166 * works without O_CREAT */
167 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
181 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
183 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
184 setvbuf(f
, NULL
, _IONBF
, 0);
186 r
= write_string_stream_ts(f
, line
, flags
, ts
);
193 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
198 /* OK, the operation failed, but let's see if the right
199 * contents in place already. If so, eat up the error. */
201 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
208 int write_string_filef(
210 WriteStringFileFlags flags
,
211 const char *format
, ...) {
213 _cleanup_free_
char *p
= NULL
;
217 va_start(ap
, format
);
218 r
= vasprintf(&p
, format
, ap
);
224 return write_string_file(fn
, p
, flags
);
227 int read_one_line_file(const char *fn
, char **line
) {
228 _cleanup_fclose_
FILE *f
= NULL
;
234 r
= fopen_unlocked(fn
, "re", &f
);
238 return read_line(f
, LONG_LINE_MAX
, line
);
241 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
242 _cleanup_fclose_
FILE *f
= NULL
;
243 _cleanup_free_
char *buf
= NULL
;
252 if (accept_extra_nl
&& endswith(blob
, "\n"))
253 accept_extra_nl
= false;
255 buf
= malloc(l
+ accept_extra_nl
+ 1);
259 r
= fopen_unlocked(fn
, "re", &f
);
263 /* We try to read one byte more than we need, so that we know whether we hit eof */
265 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
267 return errno
> 0 ? -errno
: -EIO
;
269 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
271 if (memcmp(buf
, blob
, l
) != 0)
273 if (k
> l
&& buf
[l
] != '\n')
279 int read_full_stream_full(
281 const char *filename
,
282 ReadFullFileFlags flags
,
286 _cleanup_free_
char *buf
= NULL
;
292 assert(ret_contents
);
293 assert(!(flags
& READ_FULL_FILE_UNBASE64
) || ret_size
);
295 n_next
= LINE_MAX
; /* Start size */
298 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
299 * optimize our buffering) */
301 if (fstat(fd
, &st
) < 0)
304 if (S_ISREG(st
.st_mode
)) {
307 if (st
.st_size
> READ_FULL_BYTES_MAX
)
310 /* Start with the right file size, but be prepared for files from /proc which generally report a file
311 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
312 * already makes us notice the EOF. */
314 n_next
= st
.st_size
+ 1;
316 if (flags
& READ_FULL_FILE_SECURE
)
317 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
326 if (flags
& READ_FULL_FILE_SECURE
) {
327 t
= malloc(n_next
+ 1);
332 memcpy_safe(t
, buf
, n
);
333 explicit_bzero_safe(buf
, n
);
335 t
= realloc(buf
, n_next
+ 1);
344 k
= fread(buf
+ l
, 1, n
- l
, f
);
349 r
= errno
> 0 ? -errno
: -EIO
;
356 /* We aren't expecting fread() to return a short read outside
357 * of (error && eof), assert buffer is full and enlarge buffer.
362 if (n
>= READ_FULL_BYTES_MAX
) {
367 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
370 if (flags
& READ_FULL_FILE_UNBASE64
) {
372 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
377 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
378 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
379 * there'd be ambiguity about what we just read. */
381 if (memchr(buf
, 0, l
)) {
388 *ret_contents
= TAKE_PTR(buf
);
396 if (flags
& READ_FULL_FILE_SECURE
)
397 explicit_bzero_safe(buf
, n
);
402 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
403 _cleanup_fclose_
FILE *f
= NULL
;
409 r
= fopen_unlocked(filename
, "re", &f
);
413 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
416 int executable_is_script(const char *path
, char **interpreter
) {
417 _cleanup_free_
char *line
= NULL
;
424 r
= read_one_line_file(path
, &line
);
425 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
430 if (!startswith(line
, "#!"))
433 ans
= strstrip(line
+ 2);
434 len
= strcspn(ans
, " \t");
439 ans
= strndup(ans
, len
);
448 * Retrieve one field from a file like /proc/self/status. pattern
449 * should not include whitespace or the delimiter (':'). pattern matches only
450 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
451 * zeros after the ':' will be skipped. field must be freed afterwards.
452 * terminator specifies the terminating characters of the field value (not
453 * included in the value).
455 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
456 _cleanup_free_
char *status
= NULL
;
466 r
= read_full_file(filename
, &status
, NULL
);
476 t
= strstr(t
, pattern
);
480 /* Check that pattern occurs in beginning of line. */
481 pattern_ok
= (t
== status
|| t
[-1] == '\n');
483 t
+= strlen(pattern
);
485 } while (!pattern_ok
);
487 t
+= strspn(t
, " \t");
496 t
+= strspn(t
, " \t");
498 /* Also skip zeros, because when this is used for
499 * capabilities, we don't want the zeros. This way the
500 * same capability set always maps to the same string,
501 * irrespective of the total capability set size. For
502 * other numbers it shouldn't matter. */
504 /* Back off one char if there's nothing but whitespace
506 if (!*t
|| isspace(*t
))
510 len
= strcspn(t
, terminator
);
520 DIR *xopendirat(int fd
, const char *name
, int flags
) {
524 assert(!(flags
& O_CREAT
));
526 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
539 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
546 if (!path_strv_resolve_uniq(search
, root
))
549 STRV_FOREACH(i
, search
) {
550 _cleanup_free_
char *p
= NULL
;
554 p
= strjoin(root
, *i
, "/", path
);
556 p
= strjoin(*i
, "/", path
);
573 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
574 _cleanup_strv_free_
char **copy
= NULL
;
580 if (path_is_absolute(path
)) {
583 f
= fopen(path
, mode
);
592 copy
= strv_copy((char**) search
);
596 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
599 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
600 _cleanup_strv_free_
char **s
= NULL
;
602 if (path_is_absolute(path
)) {
605 f
= fopen(path
, mode
);
614 s
= strv_split_nulstr(search
);
618 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
621 int fflush_and_check(FILE *f
) {
628 return errno
> 0 ? -errno
: -EIO
;
633 int fflush_sync_and_check(FILE *f
) {
638 r
= fflush_and_check(f
);
642 if (fsync(fileno(f
)) < 0)
645 r
= fsync_directory_of_file(fileno(f
));
652 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
653 char ln
[DECIMAL_STR_MAX(n
)+2];
655 /* Creates a "timestamp" file, that contains nothing but a
656 * usec_t timestamp, formatted in ASCII. */
658 if (n
<= 0 || n
>= USEC_INFINITY
)
661 xsprintf(ln
, USEC_FMT
"\n", n
);
663 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
666 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
667 _cleanup_free_
char *ln
= NULL
;
671 r
= read_one_line_file(fn
, &ln
);
675 r
= safe_atou64(ln
, &t
);
679 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
686 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
691 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
692 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
693 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
694 * element, but not before the first one. */
704 r
= fputs(separator
, f
);
715 /* A bitmask of the EOL markers we know */
716 typedef enum EndOfLineMarker
{
718 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
719 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
720 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
723 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
725 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
738 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
740 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
741 size_t n
= 0, allocated
= 0, count
= 0;
742 _cleanup_free_
char *buffer
= NULL
;
747 /* Something like a bounded version of getline().
749 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
750 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
763 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
764 * the number of characters in the returned string). When EOF is hit, 0 is returned.
766 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
767 * delimiters. If the limit is hit we fail and return -ENOBUFS.
769 * If a line shall be skipped ret may be initialized as NULL. */
772 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
777 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
778 EndOfLineMarker previous_eol
= EOL_NONE
;
788 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
791 r
= safe_fgetc(f
, &c
);
794 if (r
== 0) /* EOF is definitely EOL */
797 eol
= categorize_eol(c
, flags
);
799 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
800 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
801 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
802 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
803 * EOL marker has been seen right before? In either of these three cases we are
804 * done. But first, let's put this character back in the queue. (Note that we have to
805 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
806 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
807 * pass a negative value here. That said, to complicate things further ungetc() is
808 * actually happy with most negative characters and implicitly casts them back to
809 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
811 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
817 if (eol
!= EOL_NONE
) {
823 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
836 *ret
= TAKE_PTR(buffer
);
842 int safe_fgetc(FILE *f
, char *ret
) {
847 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
848 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
855 return errno
> 0 ? -errno
: -EIO
;
869 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
876 if (stat(filename
, &_st
) < 0)
881 if ((st
->st_mode
& S_IRWXO
) == 0)
885 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
886 "%s has %04o mode that is too permissive, please adjust the access mode.",
887 filename
, st
->st_mode
& 07777);
889 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
890 filename
, st
->st_mode
& 07777);