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
;
224 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
226 r
= read_line(f
, LONG_LINE_MAX
, line
);
227 return r
< 0 ? r
: 0;
230 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
231 _cleanup_fclose_
FILE *f
= NULL
;
232 _cleanup_free_
char *buf
= NULL
;
240 if (accept_extra_nl
&& endswith(blob
, "\n"))
241 accept_extra_nl
= false;
243 buf
= malloc(l
+ accept_extra_nl
+ 1);
251 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
253 /* We try to read one byte more than we need, so that we know whether we hit eof */
255 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
257 return errno
> 0 ? -errno
: -EIO
;
259 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
261 if (memcmp(buf
, blob
, l
) != 0)
263 if (k
> l
&& buf
[l
] != '\n')
269 int read_full_stream(FILE *f
, char **contents
, size_t *size
) {
270 _cleanup_free_
char *buf
= NULL
;
281 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see fmemopen(), let's
282 * optimize our buffering) */
284 if (fstat(fileno(f
), &st
) < 0)
287 if (S_ISREG(st
.st_mode
)) {
290 if (st
.st_size
> READ_FULL_BYTES_MAX
)
293 /* Start with the right file size, but be prepared for files from /proc which generally report a file
294 * size of 0. Note that we increase the size to read here by one, so that the first read attempt
295 * already makes us notice the EOF. */
306 t
= realloc(buf
, n
+ 1);
312 k
= fread(buf
+ l
, 1, n
- l
, f
);
317 return errno
> 0 ? -errno
: -EIO
;
322 /* We aren't expecting fread() to return a short read outside
323 * of (error && eof), assert buffer is full and enlarge buffer.
328 if (n
>= READ_FULL_BYTES_MAX
)
331 n
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
335 *contents
= TAKE_PTR(buf
);
343 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
344 _cleanup_fclose_
FILE *f
= NULL
;
353 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
355 return read_full_stream(f
, contents
, size
);
358 int executable_is_script(const char *path
, char **interpreter
) {
359 _cleanup_free_
char *line
= NULL
;
366 r
= read_one_line_file(path
, &line
);
367 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
372 if (!startswith(line
, "#!"))
375 ans
= strstrip(line
+ 2);
376 len
= strcspn(ans
, " \t");
381 ans
= strndup(ans
, len
);
390 * Retrieve one field from a file like /proc/self/status. pattern
391 * should not include whitespace or the delimiter (':'). pattern matches only
392 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
393 * zeros after the ':' will be skipped. field must be freed afterwards.
394 * terminator specifies the terminating characters of the field value (not
395 * included in the value).
397 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
398 _cleanup_free_
char *status
= NULL
;
408 r
= read_full_file(filename
, &status
, NULL
);
418 t
= strstr(t
, pattern
);
422 /* Check that pattern occurs in beginning of line. */
423 pattern_ok
= (t
== status
|| t
[-1] == '\n');
425 t
+= strlen(pattern
);
427 } while (!pattern_ok
);
429 t
+= strspn(t
, " \t");
438 t
+= strspn(t
, " \t");
440 /* Also skip zeros, because when this is used for
441 * capabilities, we don't want the zeros. This way the
442 * same capability set always maps to the same string,
443 * irrespective of the total capability set size. For
444 * other numbers it shouldn't matter. */
446 /* Back off one char if there's nothing but whitespace
448 if (!*t
|| isspace(*t
))
452 len
= strcspn(t
, terminator
);
462 DIR *xopendirat(int fd
, const char *name
, int flags
) {
466 assert(!(flags
& O_CREAT
));
468 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
481 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
488 if (!path_strv_resolve_uniq(search
, root
))
491 STRV_FOREACH(i
, search
) {
492 _cleanup_free_
char *p
= NULL
;
496 p
= strjoin(root
, *i
, "/", path
);
498 p
= strjoin(*i
, "/", path
);
515 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
516 _cleanup_strv_free_
char **copy
= NULL
;
522 if (path_is_absolute(path
)) {
525 f
= fopen(path
, mode
);
534 copy
= strv_copy((char**) search
);
538 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
541 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
542 _cleanup_strv_free_
char **s
= NULL
;
544 if (path_is_absolute(path
)) {
547 f
= fopen(path
, mode
);
556 s
= strv_split_nulstr(search
);
560 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
563 int fflush_and_check(FILE *f
) {
570 return errno
> 0 ? -errno
: -EIO
;
575 int fflush_sync_and_check(FILE *f
) {
580 r
= fflush_and_check(f
);
584 if (fsync(fileno(f
)) < 0)
587 r
= fsync_directory_of_file(fileno(f
));
594 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
595 char ln
[DECIMAL_STR_MAX(n
)+2];
597 /* Creates a "timestamp" file, that contains nothing but a
598 * usec_t timestamp, formatted in ASCII. */
600 if (n
<= 0 || n
>= USEC_INFINITY
)
603 xsprintf(ln
, USEC_FMT
"\n", n
);
605 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
608 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
609 _cleanup_free_
char *ln
= NULL
;
613 r
= read_one_line_file(fn
, &ln
);
617 r
= safe_atou64(ln
, &t
);
621 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
628 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
633 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
634 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
635 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
636 * element, but not before the first one. */
646 r
= fputs(separator
, f
);
657 int read_nul_string(FILE *f
, char **ret
) {
658 _cleanup_free_
char *x
= NULL
;
659 size_t allocated
= 0, n
= 0;
664 /* Reads a NUL-terminated string from the specified file. */
669 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
673 if (c
== 0) /* Terminate at NUL byte */
678 break; /* Terminate at EOF */
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
) {
716 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, funlockfile
);
718 int read_line(FILE *f
, size_t limit
, char **ret
) {
719 size_t n
= 0, allocated
= 0, count
= 0;
720 _cleanup_free_
char *buffer
= NULL
;
724 /* Something like a bounded version of getline().
726 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
727 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
740 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
741 * the number of characters in the returned string). When EOF is hit, 0 is returned.
743 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
744 * delimiters. If the limit is hit we fail and return -ENOBUFS.
746 * If a line shall be skipped ret may be initialized as NULL. */
749 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
754 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
755 EndOfLineMarker previous_eol
= EOL_NONE
;
766 c
= fgetc_unlocked(f
);
768 /* if we read an error, and have no data to return, then propagate the error */
769 if (ferror_unlocked(f
) && n
== 0)
770 return errno
> 0 ? -errno
: -EIO
;
772 /* EOF is line ending too. */
778 eol
= categorize_eol(c
);
780 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
781 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
782 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
783 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
784 * EOL marker has been seen right before? In either of these three cases we are
785 * done. But first, let's put this character back in the queue. */
786 assert_se(ungetc(c
, f
) != EOF
);
791 if (eol
!= EOL_NONE
) {
797 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
800 buffer
[n
] = (char) c
;
810 *ret
= TAKE_PTR(buffer
);