1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/types.h>
16 #include "alloc-util.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 write_string_stream_ts(
34 WriteStringFileFlags flags
,
35 struct timespec
*ts
) {
46 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
48 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
49 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
50 * that the write goes out in one go, instead of two */
52 line
= strjoina(line
, "\n");
56 if (fputs(line
, f
) == EOF
)
60 if (fputc('\n', f
) == EOF
)
63 if (flags
& WRITE_STRING_FILE_SYNC
)
64 r
= fflush_sync_and_check(f
);
66 r
= fflush_and_check(f
);
71 struct timespec twice
[2] = {*ts
, *ts
};
73 if (futimens(fileno(f
), twice
) < 0)
80 static int write_string_file_atomic(
83 WriteStringFileFlags flags
,
84 struct timespec
*ts
) {
86 _cleanup_fclose_
FILE *f
= NULL
;
87 _cleanup_free_
char *p
= NULL
;
93 r
= fopen_temporary(fn
, &f
, &p
);
97 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
98 (void) fchmod_umask(fileno(f
), 0644);
100 r
= write_string_stream_ts(f
, line
, flags
, ts
);
104 if (rename(p
, fn
) < 0) {
116 int write_string_file_ts(
119 WriteStringFileFlags flags
,
120 struct timespec
*ts
) {
122 _cleanup_fclose_
FILE *f
= NULL
;
128 /* We don't know how to verify whether the file contents was already on-disk. */
129 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
131 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
132 assert(flags
& WRITE_STRING_FILE_CREATE
);
134 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
142 if (flags
& WRITE_STRING_FILE_CREATE
) {
151 /* We manually build our own version of fopen(..., "we") that
152 * works without O_CREAT */
153 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
| ((flags
& WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0));
167 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
169 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
170 setvbuf(f
, NULL
, _IONBF
, 0);
172 r
= write_string_stream_ts(f
, line
, flags
, ts
);
179 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
184 /* OK, the operation failed, but let's see if the right
185 * contents in place already. If so, eat up the error. */
187 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
194 int write_string_filef(
196 WriteStringFileFlags flags
,
197 const char *format
, ...) {
199 _cleanup_free_
char *p
= NULL
;
203 va_start(ap
, format
);
204 r
= vasprintf(&p
, format
, ap
);
210 return write_string_file(fn
, p
, flags
);
213 int read_one_line_file(const char *fn
, char **line
) {
214 _cleanup_fclose_
FILE *f
= NULL
;
223 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
225 return read_line(f
, LONG_LINE_MAX
, line
);
228 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
229 _cleanup_fclose_
FILE *f
= NULL
;
230 _cleanup_free_
char *buf
= NULL
;
238 if (accept_extra_nl
&& endswith(blob
, "\n"))
239 accept_extra_nl
= false;
241 buf
= malloc(l
+ accept_extra_nl
+ 1);
249 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
251 /* We try to read one byte more than we need, so that we know whether we hit eof */
253 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
255 return errno
> 0 ? -errno
: -EIO
;
257 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
259 if (memcmp(buf
, blob
, l
) != 0)
261 if (k
> l
&& buf
[l
] != '\n')
267 int read_full_stream_full(
269 const char *filename
,
270 ReadFullFileFlags flags
,
274 _cleanup_free_
char *buf
= NULL
;
280 assert(ret_contents
);
282 n_next
= LINE_MAX
; /* Start size */
285 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
286 * optimize our buffering) */
288 if (fstat(fd
, &st
) < 0)
291 if (S_ISREG(st
.st_mode
)) {
294 if (st
.st_size
> READ_FULL_BYTES_MAX
)
297 /* Start with the right file size, but be prepared for files from /proc which generally report a file
298 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
299 * already makes us notice the EOF. */
301 n_next
= st
.st_size
+ 1;
303 if (flags
& READ_FULL_FILE_SECURE
)
304 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
313 if (flags
& READ_FULL_FILE_SECURE
) {
314 t
= malloc(n_next
+ 1);
319 memcpy_safe(t
, buf
, n
);
320 explicit_bzero_safe(buf
, n
);
322 t
= realloc(buf
, n_next
+ 1);
331 k
= fread(buf
+ l
, 1, n
- l
, f
);
336 r
= errno
> 0 ? -errno
: -EIO
;
343 /* We aren't expecting fread() to return a short read outside
344 * of (error && eof), assert buffer is full and enlarge buffer.
349 if (n
>= READ_FULL_BYTES_MAX
) {
354 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
358 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
359 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
360 * there'd be ambiguity about what we just read. */
362 if (memchr(buf
, 0, l
)) {
369 *ret_contents
= TAKE_PTR(buf
);
377 if (flags
& READ_FULL_FILE_SECURE
)
378 explicit_bzero_safe(buf
, n
);
383 int read_full_file_full(const char *filename
, ReadFullFileFlags flags
, char **contents
, size_t *size
) {
384 _cleanup_fclose_
FILE *f
= NULL
;
389 f
= fopen(filename
, "re");
393 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
395 return read_full_stream_full(f
, filename
, flags
, contents
, size
);
398 int executable_is_script(const char *path
, char **interpreter
) {
399 _cleanup_free_
char *line
= NULL
;
406 r
= read_one_line_file(path
, &line
);
407 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
412 if (!startswith(line
, "#!"))
415 ans
= strstrip(line
+ 2);
416 len
= strcspn(ans
, " \t");
421 ans
= strndup(ans
, len
);
430 * Retrieve one field from a file like /proc/self/status. pattern
431 * should not include whitespace or the delimiter (':'). pattern matches only
432 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
433 * zeros after the ':' will be skipped. field must be freed afterwards.
434 * terminator specifies the terminating characters of the field value (not
435 * included in the value).
437 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
438 _cleanup_free_
char *status
= NULL
;
448 r
= read_full_file(filename
, &status
, NULL
);
458 t
= strstr(t
, pattern
);
462 /* Check that pattern occurs in beginning of line. */
463 pattern_ok
= (t
== status
|| t
[-1] == '\n');
465 t
+= strlen(pattern
);
467 } while (!pattern_ok
);
469 t
+= strspn(t
, " \t");
478 t
+= strspn(t
, " \t");
480 /* Also skip zeros, because when this is used for
481 * capabilities, we don't want the zeros. This way the
482 * same capability set always maps to the same string,
483 * irrespective of the total capability set size. For
484 * other numbers it shouldn't matter. */
486 /* Back off one char if there's nothing but whitespace
488 if (!*t
|| isspace(*t
))
492 len
= strcspn(t
, terminator
);
502 DIR *xopendirat(int fd
, const char *name
, int flags
) {
506 assert(!(flags
& O_CREAT
));
508 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
521 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
528 if (!path_strv_resolve_uniq(search
, root
))
531 STRV_FOREACH(i
, search
) {
532 _cleanup_free_
char *p
= NULL
;
536 p
= strjoin(root
, *i
, "/", path
);
538 p
= strjoin(*i
, "/", path
);
555 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
556 _cleanup_strv_free_
char **copy
= NULL
;
562 if (path_is_absolute(path
)) {
565 f
= fopen(path
, mode
);
574 copy
= strv_copy((char**) search
);
578 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
581 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
582 _cleanup_strv_free_
char **s
= NULL
;
584 if (path_is_absolute(path
)) {
587 f
= fopen(path
, mode
);
596 s
= strv_split_nulstr(search
);
600 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
603 int fflush_and_check(FILE *f
) {
610 return errno
> 0 ? -errno
: -EIO
;
615 int fflush_sync_and_check(FILE *f
) {
620 r
= fflush_and_check(f
);
624 if (fsync(fileno(f
)) < 0)
627 r
= fsync_directory_of_file(fileno(f
));
634 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
635 char ln
[DECIMAL_STR_MAX(n
)+2];
637 /* Creates a "timestamp" file, that contains nothing but a
638 * usec_t timestamp, formatted in ASCII. */
640 if (n
<= 0 || n
>= USEC_INFINITY
)
643 xsprintf(ln
, USEC_FMT
"\n", n
);
645 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
648 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
649 _cleanup_free_
char *ln
= NULL
;
653 r
= read_one_line_file(fn
, &ln
);
657 r
= safe_atou64(ln
, &t
);
661 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
668 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
673 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
674 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
675 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
676 * element, but not before the first one. */
686 r
= fputs(separator
, f
);
697 /* A bitmask of the EOL markers we know */
698 typedef enum EndOfLineMarker
{
700 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
701 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
702 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
705 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
707 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
720 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
722 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
723 size_t n
= 0, allocated
= 0, count
= 0;
724 _cleanup_free_
char *buffer
= NULL
;
729 /* Something like a bounded version of getline().
731 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
732 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
745 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
746 * the number of characters in the returned string). When EOF is hit, 0 is returned.
748 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
749 * delimiters. If the limit is hit we fail and return -ENOBUFS.
751 * If a line shall be skipped ret may be initialized as NULL. */
754 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
759 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
760 EndOfLineMarker previous_eol
= EOL_NONE
;
770 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
773 r
= safe_fgetc(f
, &c
);
776 if (r
== 0) /* EOF is definitely EOL */
779 eol
= categorize_eol(c
, flags
);
781 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
782 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
783 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
784 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
785 * EOL marker has been seen right before? In either of these three cases we are
786 * done. But first, let's put this character back in the queue. (Note that we have to
787 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
788 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
789 * pass a negative value here. That said, to complicate things further ungetc() is
790 * actually happy with most negative characters and implicitly casts them back to
791 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
793 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
799 if (eol
!= EOL_NONE
) {
805 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
818 *ret
= TAKE_PTR(buffer
);
824 int safe_fgetc(FILE *f
, char *ret
) {
829 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
830 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
837 return errno
> 0 ? -errno
: -EIO
;
851 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
858 if (stat(filename
, &_st
) < 0)
863 if ((st
->st_mode
& S_IRWXO
) == 0)
867 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
868 "%s has %04o mode that is too permissive, please adjust the access mode.",
869 filename
, st
->st_mode
& 07777);
871 log_warning("%s has %04o mode that is too permissive, please adjust the access mode.",
872 filename
, st
->st_mode
& 07777);