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 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
59 FILE *f
= open_memstream(ptr
, sizeloc
);
63 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
68 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
69 FILE *f
= fmemopen(buf
, size
, mode
);
73 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
78 int write_string_stream_ts(
81 WriteStringFileFlags flags
,
82 struct timespec
*ts
) {
93 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
95 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
96 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
97 * that the write goes out in one go, instead of two */
99 line
= strjoina(line
, "\n");
103 if (fputs(line
, f
) == EOF
)
107 if (fputc('\n', f
) == EOF
)
110 if (flags
& WRITE_STRING_FILE_SYNC
)
111 r
= fflush_sync_and_check(f
);
113 r
= fflush_and_check(f
);
118 struct timespec twice
[2] = {*ts
, *ts
};
120 if (futimens(fileno(f
), twice
) < 0)
127 static int write_string_file_atomic(
130 WriteStringFileFlags flags
,
131 struct timespec
*ts
) {
133 _cleanup_fclose_
FILE *f
= NULL
;
134 _cleanup_free_
char *p
= NULL
;
140 r
= fopen_temporary(fn
, &f
, &p
);
144 (void) fchmod_umask(fileno(f
), 0644);
146 r
= write_string_stream_ts(f
, line
, flags
, ts
);
150 if (rename(p
, fn
) < 0) {
162 int write_string_file_ts(
165 WriteStringFileFlags flags
,
166 struct timespec
*ts
) {
168 _cleanup_fclose_
FILE *f
= NULL
;
174 /* We don't know how to verify whether the file contents was already on-disk. */
175 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
177 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
178 assert(flags
& WRITE_STRING_FILE_CREATE
);
180 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
188 if (flags
& WRITE_STRING_FILE_CREATE
) {
189 r
= fopen_unlocked(fn
, "we", &f
);
195 /* We manually build our own version of fopen(..., "we") that
196 * works without O_CREAT */
197 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
203 r
= fdopen_unlocked(fd
, "w", &f
);
210 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
211 setvbuf(f
, NULL
, _IONBF
, 0);
213 r
= write_string_stream_ts(f
, line
, flags
, ts
);
220 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
225 /* OK, the operation failed, but let's see if the right
226 * contents in place already. If so, eat up the error. */
228 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
235 int write_string_filef(
237 WriteStringFileFlags flags
,
238 const char *format
, ...) {
240 _cleanup_free_
char *p
= NULL
;
244 va_start(ap
, format
);
245 r
= vasprintf(&p
, format
, ap
);
251 return write_string_file(fn
, p
, flags
);
254 int read_one_line_file(const char *fn
, char **line
) {
255 _cleanup_fclose_
FILE *f
= NULL
;
261 r
= fopen_unlocked(fn
, "re", &f
);
265 return read_line(f
, LONG_LINE_MAX
, line
);
268 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
269 _cleanup_fclose_
FILE *f
= NULL
;
270 _cleanup_free_
char *buf
= NULL
;
279 if (accept_extra_nl
&& endswith(blob
, "\n"))
280 accept_extra_nl
= false;
282 buf
= malloc(l
+ accept_extra_nl
+ 1);
286 r
= fopen_unlocked(fn
, "re", &f
);
290 /* We try to read one byte more than we need, so that we know whether we hit eof */
292 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
294 return errno
> 0 ? -errno
: -EIO
;
296 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
298 if (memcmp(buf
, blob
, l
) != 0)
300 if (k
> l
&& buf
[l
] != '\n')
306 int read_full_stream_full(
308 const char *filename
,
309 ReadFullFileFlags flags
,
313 _cleanup_free_
char *buf
= NULL
;
319 assert(ret_contents
);
320 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
321 assert(!(flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) || ret_size
);
323 n_next
= LINE_MAX
; /* Start size */
326 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
327 * optimize our buffering) */
329 if (fstat(fd
, &st
) < 0)
332 if (S_ISREG(st
.st_mode
)) {
335 if (st
.st_size
> READ_FULL_BYTES_MAX
)
338 /* Start with the right file size, but be prepared for files from /proc which generally report a file
339 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
340 * already makes us notice the EOF. */
342 n_next
= st
.st_size
+ 1;
344 if (flags
& READ_FULL_FILE_SECURE
)
345 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
354 if (flags
& READ_FULL_FILE_SECURE
) {
355 t
= malloc(n_next
+ 1);
360 memcpy_safe(t
, buf
, n
);
361 explicit_bzero_safe(buf
, n
);
364 t
= realloc(buf
, n_next
+ 1);
373 k
= fread(buf
+ l
, 1, n
- l
, f
);
378 r
= errno
> 0 ? -errno
: -EIO
;
385 /* We aren't expecting fread() to return a short read outside
386 * of (error && eof), assert buffer is full and enlarge buffer.
391 if (n
>= READ_FULL_BYTES_MAX
) {
396 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
399 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
401 if (flags
& READ_FULL_FILE_UNBASE64
)
402 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
404 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
409 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
410 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
411 * there'd be ambiguity about what we just read. */
413 if (memchr(buf
, 0, l
)) {
420 *ret_contents
= TAKE_PTR(buf
);
428 if (flags
& READ_FULL_FILE_SECURE
)
429 explicit_bzero_safe(buf
, n
);
434 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
435 _cleanup_fclose_
FILE *f
= NULL
;
441 r
= fopen_unlocked(filename
, "re", &f
);
445 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
448 int executable_is_script(const char *path
, char **interpreter
) {
449 _cleanup_free_
char *line
= NULL
;
456 r
= read_one_line_file(path
, &line
);
457 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
462 if (!startswith(line
, "#!"))
465 ans
= strstrip(line
+ 2);
466 len
= strcspn(ans
, " \t");
471 ans
= strndup(ans
, len
);
480 * Retrieve one field from a file like /proc/self/status. pattern
481 * should not include whitespace or the delimiter (':'). pattern matches only
482 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
483 * zeros after the ':' will be skipped. field must be freed afterwards.
484 * terminator specifies the terminating characters of the field value (not
485 * included in the value).
487 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
488 _cleanup_free_
char *status
= NULL
;
498 r
= read_full_file(filename
, &status
, NULL
);
508 t
= strstr(t
, pattern
);
512 /* Check that pattern occurs in beginning of line. */
513 pattern_ok
= (t
== status
|| t
[-1] == '\n');
515 t
+= strlen(pattern
);
517 } while (!pattern_ok
);
519 t
+= strspn(t
, " \t");
528 t
+= strspn(t
, " \t");
530 /* Also skip zeros, because when this is used for
531 * capabilities, we don't want the zeros. This way the
532 * same capability set always maps to the same string,
533 * irrespective of the total capability set size. For
534 * other numbers it shouldn't matter. */
536 /* Back off one char if there's nothing but whitespace
538 if (!*t
|| isspace(*t
))
542 len
= strcspn(t
, terminator
);
552 DIR *xopendirat(int fd
, const char *name
, int flags
) {
556 assert(!(flags
& O_CREAT
));
558 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
571 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
578 if (!path_strv_resolve_uniq(search
, root
))
581 STRV_FOREACH(i
, search
) {
582 _cleanup_free_
char *p
= NULL
;
586 p
= strjoin(root
, *i
, "/", path
);
588 p
= strjoin(*i
, "/", path
);
605 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
606 _cleanup_strv_free_
char **copy
= NULL
;
612 if (path_is_absolute(path
)) {
615 f
= fopen(path
, mode
);
624 copy
= strv_copy((char**) search
);
628 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
631 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
632 _cleanup_strv_free_
char **s
= NULL
;
634 if (path_is_absolute(path
)) {
637 f
= fopen(path
, mode
);
646 s
= strv_split_nulstr(search
);
650 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
653 int fflush_and_check(FILE *f
) {
660 return errno
> 0 ? -errno
: -EIO
;
665 int fflush_sync_and_check(FILE *f
) {
670 r
= fflush_and_check(f
);
674 if (fsync(fileno(f
)) < 0)
677 r
= fsync_directory_of_file(fileno(f
));
684 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
685 char ln
[DECIMAL_STR_MAX(n
)+2];
687 /* Creates a "timestamp" file, that contains nothing but a
688 * usec_t timestamp, formatted in ASCII. */
690 if (n
<= 0 || n
>= USEC_INFINITY
)
693 xsprintf(ln
, USEC_FMT
"\n", n
);
695 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
698 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
699 _cleanup_free_
char *ln
= NULL
;
703 r
= read_one_line_file(fn
, &ln
);
707 r
= safe_atou64(ln
, &t
);
711 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
718 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
723 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
724 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
725 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
726 * element, but not before the first one. */
736 r
= fputs(separator
, f
);
747 /* A bitmask of the EOL markers we know */
748 typedef enum EndOfLineMarker
{
750 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
751 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
752 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
755 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
757 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
770 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
772 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
773 size_t n
= 0, allocated
= 0, count
= 0;
774 _cleanup_free_
char *buffer
= NULL
;
779 /* Something like a bounded version of getline().
781 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
782 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
795 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
796 * the number of characters in the returned string). When EOF is hit, 0 is returned.
798 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
799 * delimiters. If the limit is hit we fail and return -ENOBUFS.
801 * If a line shall be skipped ret may be initialized as NULL. */
804 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
809 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
810 EndOfLineMarker previous_eol
= EOL_NONE
;
820 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
823 r
= safe_fgetc(f
, &c
);
826 if (r
== 0) /* EOF is definitely EOL */
829 eol
= categorize_eol(c
, flags
);
831 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
832 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
833 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
834 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
835 * EOL marker has been seen right before? In either of these three cases we are
836 * done. But first, let's put this character back in the queue. (Note that we have to
837 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
838 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
839 * pass a negative value here. That said, to complicate things further ungetc() is
840 * actually happy with most negative characters and implicitly casts them back to
841 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
843 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
849 if (eol
!= EOL_NONE
) {
855 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
868 *ret
= TAKE_PTR(buffer
);
874 int safe_fgetc(FILE *f
, char *ret
) {
879 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
880 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
887 return errno
> 0 ? -errno
: -EIO
;
901 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
908 if (stat(filename
, &_st
) < 0)
913 if ((st
->st_mode
& S_IRWXO
) == 0)
917 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
918 "%s has %04o mode that is too permissive, please adjust the access mode.",
919 filename
, st
->st_mode
& 07777);
921 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
922 filename
, st
->st_mode
& 07777);