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(
272 _cleanup_free_
char *buf
= NULL
;
278 assert(ret_contents
);
280 n
= LINE_MAX
; /* Start size */
283 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
284 * optimize our buffering) */
286 if (fstat(fileno(f
), &st
) < 0)
289 if (S_ISREG(st
.st_mode
)) {
292 if (st
.st_size
> READ_FULL_BYTES_MAX
)
295 /* Start with the right file size, but be prepared for files from /proc which generally report a file
296 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
297 * already makes us notice the EOF. */
308 t
= realloc(buf
, n
+ 1);
314 k
= fread(buf
+ l
, 1, n
- l
, f
);
319 return errno
> 0 ? -errno
: -EIO
;
324 /* We aren't expecting fread() to return a short read outside
325 * of (error && eof), assert buffer is full and enlarge buffer.
330 if (n
>= READ_FULL_BYTES_MAX
)
333 n
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
337 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
338 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
339 * there'd be ambiguity about what we just read. */
341 if (memchr(buf
, 0, l
))
346 *ret_contents
= TAKE_PTR(buf
);
354 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
355 _cleanup_fclose_
FILE *f
= NULL
;
364 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
366 return read_full_stream(f
, contents
, size
);
369 int executable_is_script(const char *path
, char **interpreter
) {
370 _cleanup_free_
char *line
= NULL
;
377 r
= read_one_line_file(path
, &line
);
378 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
383 if (!startswith(line
, "#!"))
386 ans
= strstrip(line
+ 2);
387 len
= strcspn(ans
, " \t");
392 ans
= strndup(ans
, len
);
401 * Retrieve one field from a file like /proc/self/status. pattern
402 * should not include whitespace or the delimiter (':'). pattern matches only
403 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
404 * zeros after the ':' will be skipped. field must be freed afterwards.
405 * terminator specifies the terminating characters of the field value (not
406 * included in the value).
408 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
409 _cleanup_free_
char *status
= NULL
;
419 r
= read_full_file(filename
, &status
, NULL
);
429 t
= strstr(t
, pattern
);
433 /* Check that pattern occurs in beginning of line. */
434 pattern_ok
= (t
== status
|| t
[-1] == '\n');
436 t
+= strlen(pattern
);
438 } while (!pattern_ok
);
440 t
+= strspn(t
, " \t");
449 t
+= strspn(t
, " \t");
451 /* Also skip zeros, because when this is used for
452 * capabilities, we don't want the zeros. This way the
453 * same capability set always maps to the same string,
454 * irrespective of the total capability set size. For
455 * other numbers it shouldn't matter. */
457 /* Back off one char if there's nothing but whitespace
459 if (!*t
|| isspace(*t
))
463 len
= strcspn(t
, terminator
);
473 DIR *xopendirat(int fd
, const char *name
, int flags
) {
477 assert(!(flags
& O_CREAT
));
479 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
492 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
499 if (!path_strv_resolve_uniq(search
, root
))
502 STRV_FOREACH(i
, search
) {
503 _cleanup_free_
char *p
= NULL
;
507 p
= strjoin(root
, *i
, "/", path
);
509 p
= strjoin(*i
, "/", path
);
526 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
527 _cleanup_strv_free_
char **copy
= NULL
;
533 if (path_is_absolute(path
)) {
536 f
= fopen(path
, mode
);
545 copy
= strv_copy((char**) search
);
549 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
552 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
553 _cleanup_strv_free_
char **s
= NULL
;
555 if (path_is_absolute(path
)) {
558 f
= fopen(path
, mode
);
567 s
= strv_split_nulstr(search
);
571 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
574 int fflush_and_check(FILE *f
) {
581 return errno
> 0 ? -errno
: -EIO
;
586 int fflush_sync_and_check(FILE *f
) {
591 r
= fflush_and_check(f
);
595 if (fsync(fileno(f
)) < 0)
598 r
= fsync_directory_of_file(fileno(f
));
605 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
606 char ln
[DECIMAL_STR_MAX(n
)+2];
608 /* Creates a "timestamp" file, that contains nothing but a
609 * usec_t timestamp, formatted in ASCII. */
611 if (n
<= 0 || n
>= USEC_INFINITY
)
614 xsprintf(ln
, USEC_FMT
"\n", n
);
616 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
619 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
620 _cleanup_free_
char *ln
= NULL
;
624 r
= read_one_line_file(fn
, &ln
);
628 r
= safe_atou64(ln
, &t
);
632 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
639 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
644 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
645 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
646 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
647 * element, but not before the first one. */
657 r
= fputs(separator
, f
);
668 /* A bitmask of the EOL markers we know */
669 typedef enum EndOfLineMarker
{
671 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
672 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
673 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
676 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
678 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
691 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
693 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
694 size_t n
= 0, allocated
= 0, count
= 0;
695 _cleanup_free_
char *buffer
= NULL
;
700 /* Something like a bounded version of getline().
702 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
703 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
716 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
717 * the number of characters in the returned string). When EOF is hit, 0 is returned.
719 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
720 * delimiters. If the limit is hit we fail and return -ENOBUFS.
722 * If a line shall be skipped ret may be initialized as NULL. */
725 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
730 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
731 EndOfLineMarker previous_eol
= EOL_NONE
;
741 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
744 r
= safe_fgetc(f
, &c
);
747 if (r
== 0) /* EOF is definitely EOL */
750 eol
= categorize_eol(c
, flags
);
752 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
753 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
754 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
755 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
756 * EOL marker has been seen right before? In either of these three cases we are
757 * done. But first, let's put this character back in the queue. (Note that we have to
758 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
759 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
760 * pass a negative value here. That said, to complicate things further ungetc() is
761 * actually happy with most negative characters and implicitly casts them back to
762 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
764 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
770 if (eol
!= EOL_NONE
) {
776 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
789 *ret
= TAKE_PTR(buffer
);
795 int safe_fgetc(FILE *f
, char *ret
) {
800 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
801 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
808 return errno
> 0 ? -errno
: -EIO
;