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 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
58 FILE *f
= open_memstream(ptr
, sizeloc
);
62 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
67 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
68 FILE *f
= fmemopen(buf
, size
, mode
);
72 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
77 int write_string_stream_ts(
80 WriteStringFileFlags flags
,
81 struct timespec
*ts
) {
92 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
94 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
95 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
96 * that the write goes out in one go, instead of two */
98 line
= strjoina(line
, "\n");
102 if (fputs(line
, f
) == EOF
)
106 if (fputc('\n', f
) == EOF
)
109 if (flags
& WRITE_STRING_FILE_SYNC
)
110 r
= fflush_sync_and_check(f
);
112 r
= fflush_and_check(f
);
117 struct timespec twice
[2] = {*ts
, *ts
};
119 if (futimens(fileno(f
), twice
) < 0)
126 static int write_string_file_atomic(
129 WriteStringFileFlags flags
,
130 struct timespec
*ts
) {
132 _cleanup_fclose_
FILE *f
= NULL
;
133 _cleanup_free_
char *p
= NULL
;
139 r
= fopen_temporary(fn
, &f
, &p
);
143 (void) fchmod_umask(fileno(f
), 0644);
145 r
= write_string_stream_ts(f
, line
, flags
, ts
);
149 if (rename(p
, fn
) < 0) {
161 int write_string_file_ts(
164 WriteStringFileFlags flags
,
165 struct timespec
*ts
) {
167 _cleanup_fclose_
FILE *f
= NULL
;
173 /* We don't know how to verify whether the file contents was already on-disk. */
174 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
176 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
177 r
= mkdir_parents(fn
, 0755);
182 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
183 assert(flags
& WRITE_STRING_FILE_CREATE
);
185 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
193 if (flags
& WRITE_STRING_FILE_CREATE
) {
194 r
= fopen_unlocked(fn
, "we", &f
);
200 /* We manually build our own version of fopen(..., "we") that
201 * works without O_CREAT */
202 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
208 r
= fdopen_unlocked(fd
, "w", &f
);
215 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
216 setvbuf(f
, NULL
, _IONBF
, 0);
218 r
= write_string_stream_ts(f
, line
, flags
, ts
);
225 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
230 /* OK, the operation failed, but let's see if the right
231 * contents in place already. If so, eat up the error. */
233 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
240 int write_string_filef(
242 WriteStringFileFlags flags
,
243 const char *format
, ...) {
245 _cleanup_free_
char *p
= NULL
;
249 va_start(ap
, format
);
250 r
= vasprintf(&p
, format
, ap
);
256 return write_string_file(fn
, p
, flags
);
259 int read_one_line_file(const char *fn
, char **line
) {
260 _cleanup_fclose_
FILE *f
= NULL
;
266 r
= fopen_unlocked(fn
, "re", &f
);
270 return read_line(f
, LONG_LINE_MAX
, line
);
273 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
274 _cleanup_fclose_
FILE *f
= NULL
;
275 _cleanup_free_
char *buf
= NULL
;
284 if (accept_extra_nl
&& endswith(blob
, "\n"))
285 accept_extra_nl
= false;
287 buf
= malloc(l
+ accept_extra_nl
+ 1);
291 r
= fopen_unlocked(fn
, "re", &f
);
295 /* We try to read one byte more than we need, so that we know whether we hit eof */
297 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
299 return errno_or_else(EIO
);
301 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
303 if (memcmp(buf
, blob
, l
) != 0)
305 if (k
> l
&& buf
[l
] != '\n')
311 int read_full_virtual_file(const char *filename
, char **ret_contents
, size_t *ret_size
) {
312 _cleanup_free_
char *buf
= NULL
;
313 _cleanup_close_
int fd
= -1;
319 assert(ret_contents
);
321 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work
322 * with two sorts of virtual files. One sort uses "seq_file", and the results of
323 * the first read are buffered for the second read. The other sort uses "raw"
324 * reads which always go direct to the device. In the latter case, the content of
325 * the virtual file must be retrieved with a single read otherwise a second read
326 * might get the new value instead of finding EOF immediately. That's the reason
327 * why the usage of fread(3) is prohibited in this case as it always performs a
328 * second call to read(2) looking for EOF. See issue 13585. */
330 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
334 /* Start size for files in /proc which usually report a file size of 0. */
337 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
344 if (fstat(fd
, &st
) < 0)
347 if (!S_ISREG(st
.st_mode
))
350 /* Be prepared for files from /proc which generally report a file size of 0. */
351 if (st
.st_size
> 0) {
357 if (size
> READ_FULL_BYTES_MAX
)
360 p
= realloc(buf
, size
+ 1);
368 /* Read one more byte so we can detect whether the content of the
369 * file has already changed or the guessed size for files from /proc
370 * wasn't large enough . */
371 k
= read(fd
, buf
, size
+ 1);
381 /* Consider a short read as EOF */
385 /* Hmm... either we read too few bytes from /proc or less likely the content
386 * of the file might have been changed (and is now bigger) while we were
387 * processing, let's try again either with a bigger guessed size or the new
390 if (lseek(fd
, 0, SEEK_SET
) < 0)
395 p
= realloc(buf
, n
+ 1);
402 /* Safety check: if the caller doesn't want to know the size of what we
403 * just read it will rely on the trailing NUL byte. But if there's an
404 * embedded NUL byte, then we should refuse operation as otherwise
405 * there'd be ambiguity about what we just read. */
407 if (memchr(buf
, 0, n
))
413 *ret_contents
= TAKE_PTR(buf
);
418 int read_full_stream_full(
420 const char *filename
,
421 ReadFullFileFlags flags
,
425 _cleanup_free_
char *buf
= NULL
;
431 assert(ret_contents
);
432 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
433 assert(!(flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) || ret_size
);
435 n_next
= LINE_MAX
; /* Start size */
438 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
439 * optimize our buffering) */
441 if (fstat(fd
, &st
) < 0)
444 if (S_ISREG(st
.st_mode
)) {
447 if (st
.st_size
> READ_FULL_BYTES_MAX
)
450 /* Start with the right file size. Note that we increase the size
451 * to read here by one, so that the first read attempt already
452 * makes us notice the EOF. */
454 n_next
= st
.st_size
+ 1;
456 if (flags
& READ_FULL_FILE_SECURE
)
457 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
466 if (flags
& READ_FULL_FILE_SECURE
) {
467 t
= malloc(n_next
+ 1);
472 memcpy_safe(t
, buf
, n
);
473 explicit_bzero_safe(buf
, n
);
476 t
= realloc(buf
, n_next
+ 1);
485 k
= fread(buf
+ l
, 1, n
- l
, f
);
490 r
= errno_or_else(EIO
);
497 /* We aren't expecting fread() to return a short read outside
498 * of (error && eof), assert buffer is full and enlarge buffer.
503 if (n
>= READ_FULL_BYTES_MAX
) {
508 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
511 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
513 if (flags
& READ_FULL_FILE_UNBASE64
)
514 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
516 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, (void **) ret_contents
, ret_size
);
521 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
522 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
523 * there'd be ambiguity about what we just read. */
525 if (memchr(buf
, 0, l
)) {
532 *ret_contents
= TAKE_PTR(buf
);
540 if (flags
& READ_FULL_FILE_SECURE
)
541 explicit_bzero_safe(buf
, n
);
546 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
547 _cleanup_fclose_
FILE *f
= NULL
;
553 r
= fopen_unlocked(filename
, "re", &f
);
557 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
560 int executable_is_script(const char *path
, char **interpreter
) {
561 _cleanup_free_
char *line
= NULL
;
568 r
= read_one_line_file(path
, &line
);
569 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
574 if (!startswith(line
, "#!"))
577 ans
= strstrip(line
+ 2);
578 len
= strcspn(ans
, " \t");
583 ans
= strndup(ans
, len
);
592 * Retrieve one field from a file like /proc/self/status. pattern
593 * should not include whitespace or the delimiter (':'). pattern matches only
594 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
595 * zeros after the ':' will be skipped. field must be freed afterwards.
596 * terminator specifies the terminating characters of the field value (not
597 * included in the value).
599 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
600 _cleanup_free_
char *status
= NULL
;
610 r
= read_full_virtual_file(filename
, &status
, NULL
);
620 t
= strstr(t
, pattern
);
624 /* Check that pattern occurs in beginning of line. */
625 pattern_ok
= (t
== status
|| t
[-1] == '\n');
627 t
+= strlen(pattern
);
629 } while (!pattern_ok
);
631 t
+= strspn(t
, " \t");
640 t
+= strspn(t
, " \t");
642 /* Also skip zeros, because when this is used for
643 * capabilities, we don't want the zeros. This way the
644 * same capability set always maps to the same string,
645 * irrespective of the total capability set size. For
646 * other numbers it shouldn't matter. */
648 /* Back off one char if there's nothing but whitespace
650 if (!*t
|| isspace(*t
))
654 len
= strcspn(t
, terminator
);
664 DIR *xopendirat(int fd
, const char *name
, int flags
) {
668 assert(!(flags
& O_CREAT
));
670 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
683 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
690 if (!path_strv_resolve_uniq(search
, root
))
693 STRV_FOREACH(i
, search
) {
694 _cleanup_free_
char *p
= NULL
;
697 p
= path_join(root
, *i
, path
);
714 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
715 _cleanup_strv_free_
char **copy
= NULL
;
721 if (path_is_absolute(path
)) {
724 f
= fopen(path
, mode
);
733 copy
= strv_copy((char**) search
);
737 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
740 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
741 _cleanup_strv_free_
char **s
= NULL
;
743 if (path_is_absolute(path
)) {
746 f
= fopen(path
, mode
);
755 s
= strv_split_nulstr(search
);
759 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
762 int fflush_and_check(FILE *f
) {
769 return errno_or_else(EIO
);
774 int fflush_sync_and_check(FILE *f
) {
779 r
= fflush_and_check(f
);
783 if (fsync(fileno(f
)) < 0)
786 r
= fsync_directory_of_file(fileno(f
));
793 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
794 char ln
[DECIMAL_STR_MAX(n
)+2];
796 /* Creates a "timestamp" file, that contains nothing but a
797 * usec_t timestamp, formatted in ASCII. */
799 if (n
<= 0 || n
>= USEC_INFINITY
)
802 xsprintf(ln
, USEC_FMT
"\n", n
);
804 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
807 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
808 _cleanup_free_
char *ln
= NULL
;
812 r
= read_one_line_file(fn
, &ln
);
816 r
= safe_atou64(ln
, &t
);
820 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
827 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
832 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
833 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
834 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
835 * element, but not before the first one. */
845 r
= fputs(separator
, f
);
856 /* A bitmask of the EOL markers we know */
857 typedef enum EndOfLineMarker
{
859 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
860 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
861 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
864 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
866 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
879 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
881 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
882 size_t n
= 0, allocated
= 0, count
= 0;
883 _cleanup_free_
char *buffer
= NULL
;
888 /* Something like a bounded version of getline().
890 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
891 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
904 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
905 * the number of characters in the returned string). When EOF is hit, 0 is returned.
907 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
908 * delimiters. If the limit is hit we fail and return -ENOBUFS.
910 * If a line shall be skipped ret may be initialized as NULL. */
913 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
918 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
919 EndOfLineMarker previous_eol
= EOL_NONE
;
929 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
932 r
= safe_fgetc(f
, &c
);
935 if (r
== 0) /* EOF is definitely EOL */
938 eol
= categorize_eol(c
, flags
);
940 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
941 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
942 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
943 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
944 * EOL marker has been seen right before? In either of these three cases we are
945 * done. But first, let's put this character back in the queue. (Note that we have to
946 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
947 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
948 * pass a negative value here. That said, to complicate things further ungetc() is
949 * actually happy with most negative characters and implicitly casts them back to
950 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
952 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
958 if (eol
!= EOL_NONE
) {
959 /* If we are on a tty, we can't wait for more input. But we expect only
960 * \n as the single EOL marker, so there is no need to wait. We check
961 * this condition last to avoid isatty() check if not necessary. */
964 tty
= isatty(fileno(f
));
969 if (eol
!= EOL_NONE
) {
975 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
988 *ret
= TAKE_PTR(buffer
);
994 int safe_fgetc(FILE *f
, char *ret
) {
999 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1000 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1007 return errno_or_else(EIO
);
1021 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1028 if (stat(filename
, &_st
) < 0)
1033 if ((st
->st_mode
& S_IRWXO
) == 0)
1037 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1038 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1039 filename
, st
->st_mode
& 07777);
1041 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1042 filename
, st
->st_mode
& 07777);