1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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 "socket-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 int take_fdopen_unlocked(int *fd
, const char *options
, FILE **ret
) {
63 r
= fdopen_unlocked(*fd
, options
, ret
);
72 FILE* take_fdopen(int *fd
, const char *options
) {
75 FILE *f
= fdopen(*fd
, options
);
84 DIR* take_fdopendir(int *dfd
) {
87 DIR *d
= fdopendir(*dfd
);
96 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
97 FILE *f
= open_memstream(ptr
, sizeloc
);
101 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
106 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
107 FILE *f
= fmemopen(buf
, size
, mode
);
111 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
116 int write_string_stream_ts(
119 WriteStringFileFlags flags
,
120 const struct timespec
*ts
) {
132 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
133 * an fd. Let's fail early in that case. */
139 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
141 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
142 /* If STDIO buffering was disabled, then let's append the newline character to the string itself, so
143 * that the write goes out in one go, instead of two */
145 line
= strjoina(line
, "\n");
149 if (fputs(line
, f
) == EOF
)
153 if (fputc('\n', f
) == EOF
)
156 if (flags
& WRITE_STRING_FILE_SYNC
)
157 r
= fflush_sync_and_check(f
);
159 r
= fflush_and_check(f
);
164 const struct timespec twice
[2] = {*ts
, *ts
};
166 if (futimens(fd
, twice
) < 0)
173 static int write_string_file_atomic(
176 WriteStringFileFlags flags
,
177 const struct timespec
*ts
) {
179 _cleanup_fclose_
FILE *f
= NULL
;
180 _cleanup_free_
char *p
= NULL
;
186 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
187 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
189 r
= fopen_temporary(fn
, &f
, &p
);
193 r
= write_string_stream_ts(f
, line
, flags
, ts
);
197 r
= fchmod_umask(fileno(f
), FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0644);
201 if (rename(p
, fn
) < 0) {
206 if (FLAGS_SET(flags
, WRITE_STRING_FILE_SYNC
)) {
207 /* Sync the rename, too */
208 r
= fsync_directory_of_file(fileno(f
));
220 int write_string_file_ts(
223 WriteStringFileFlags flags
,
224 const struct timespec
*ts
) {
226 _cleanup_fclose_
FILE *f
= NULL
;
232 /* We don't know how to verify whether the file contents was already on-disk. */
233 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
235 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
236 r
= mkdir_parents(fn
, 0755);
241 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
242 assert(flags
& WRITE_STRING_FILE_CREATE
);
244 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
252 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
253 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|
254 (FLAGS_SET(flags
, WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0) |
255 (FLAGS_SET(flags
, WRITE_STRING_FILE_CREATE
) ? O_CREAT
: 0) |
256 (FLAGS_SET(flags
, WRITE_STRING_FILE_TRUNCATE
) ? O_TRUNC
: 0),
257 (FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0666));
263 r
= fdopen_unlocked(fd
, "w", &f
);
269 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
270 setvbuf(f
, NULL
, _IONBF
, 0);
272 r
= write_string_stream_ts(f
, line
, flags
, ts
);
279 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
284 /* OK, the operation failed, but let's see if the right
285 * contents in place already. If so, eat up the error. */
287 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
294 int write_string_filef(
296 WriteStringFileFlags flags
,
297 const char *format
, ...) {
299 _cleanup_free_
char *p
= NULL
;
303 va_start(ap
, format
);
304 r
= vasprintf(&p
, format
, ap
);
310 return write_string_file(fn
, p
, flags
);
313 int read_one_line_file(const char *fn
, char **line
) {
314 _cleanup_fclose_
FILE *f
= NULL
;
320 r
= fopen_unlocked(fn
, "re", &f
);
324 return read_line(f
, LONG_LINE_MAX
, line
);
327 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
328 _cleanup_fclose_
FILE *f
= NULL
;
329 _cleanup_free_
char *buf
= NULL
;
338 if (accept_extra_nl
&& endswith(blob
, "\n"))
339 accept_extra_nl
= false;
341 buf
= malloc(l
+ accept_extra_nl
+ 1);
345 r
= fopen_unlocked(fn
, "re", &f
);
349 /* We try to read one byte more than we need, so that we know whether we hit eof */
351 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
353 return errno_or_else(EIO
);
355 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
357 if (memcmp(buf
, blob
, l
) != 0)
359 if (k
> l
&& buf
[l
] != '\n')
365 int read_full_virtual_file(const char *filename
, char **ret_contents
, size_t *ret_size
) {
366 _cleanup_free_
char *buf
= NULL
;
367 _cleanup_close_
int fd
= -1;
373 assert(ret_contents
);
375 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work
376 * with two sorts of virtual files. One sort uses "seq_file", and the results of
377 * the first read are buffered for the second read. The other sort uses "raw"
378 * reads which always go direct to the device. In the latter case, the content of
379 * the virtual file must be retrieved with a single read otherwise a second read
380 * might get the new value instead of finding EOF immediately. That's the reason
381 * why the usage of fread(3) is prohibited in this case as it always performs a
382 * second call to read(2) looking for EOF. See issue 13585. */
384 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
388 /* Start size for files in /proc/ which usually report a file size of 0. (Files in /sys/ report a
389 * file size of 4K, which is probably OK for sizing our initial buffer, and sysfs attributes can't be
393 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
400 if (fstat(fd
, &st
) < 0)
403 if (!S_ISREG(st
.st_mode
))
406 /* Be prepared for files from /proc which generally report a file size of 0. */
407 if (st
.st_size
> 0) {
413 if (size
> READ_FULL_BYTES_MAX
)
416 p
= realloc(buf
, size
+ 1);
424 /* Read one more byte so we can detect whether the content of the
425 * file has already changed or the guessed size for files from /proc
426 * wasn't large enough . */
427 k
= read(fd
, buf
, size
+ 1);
437 /* Consider a short read as EOF */
441 /* Hmm... either we read too few bytes from /proc or less likely the content
442 * of the file might have been changed (and is now bigger) while we were
443 * processing, let's try again either with a bigger guessed size or the new
446 if (lseek(fd
, 0, SEEK_SET
) < 0)
451 p
= realloc(buf
, n
+ 1);
458 /* Safety check: if the caller doesn't want to know the size of what we
459 * just read it will rely on the trailing NUL byte. But if there's an
460 * embedded NUL byte, then we should refuse operation as otherwise
461 * there'd be ambiguity about what we just read. */
463 if (memchr(buf
, 0, n
))
469 *ret_contents
= TAKE_PTR(buf
);
474 int read_full_stream_full(
476 const char *filename
,
479 ReadFullFileFlags flags
,
483 _cleanup_free_
char *buf
= NULL
;
488 assert(ret_contents
);
489 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
491 if (offset
!= UINT64_MAX
&& offset
> LONG_MAX
)
494 n_next
= size
!= SIZE_MAX
? size
: LINE_MAX
; /* Start size */
497 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
498 * fmemopen()), let's optimize our buffering */
501 if (fstat(fd
, &st
) < 0)
504 if (S_ISREG(st
.st_mode
)) {
505 if (size
== SIZE_MAX
) {
507 LESS_BY((uint64_t) st
.st_size
, offset
== UINT64_MAX
? 0 : offset
);
510 if (rsize
> READ_FULL_BYTES_MAX
)
513 /* Start with the right file size. Note that we increase the size to read
514 * here by one, so that the first read attempt already makes us notice the
515 * EOF. If the reported size of the file is zero, we avoid this logic
516 * however, since quite likely it might be a virtual file in procfs that all
517 * report a zero file size. */
522 if (flags
& READ_FULL_FILE_WARN_WORLD_READABLE
)
523 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
527 if (offset
!= UINT64_MAX
&& fseek(f
, offset
, SEEK_SET
) < 0)
535 if (flags
& READ_FULL_FILE_SECURE
) {
536 t
= malloc(n_next
+ 1);
541 memcpy_safe(t
, buf
, n
);
542 explicit_bzero_safe(buf
, n
);
545 t
= realloc(buf
, n_next
+ 1);
554 k
= fread(buf
+ l
, 1, n
- l
, f
);
560 r
= errno_or_else(EIO
);
566 if (size
!= SIZE_MAX
) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
571 assert(k
> 0); /* we can't have read zero bytes because that would have been EOF */
574 if (n
>= READ_FULL_BYTES_MAX
) {
579 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
582 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
583 _cleanup_free_
void *decoded
= NULL
;
587 if (flags
& READ_FULL_FILE_UNBASE64
)
588 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
590 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
594 if (flags
& READ_FULL_FILE_SECURE
)
595 explicit_bzero_safe(buf
, n
);
596 free_and_replace(buf
, decoded
);
597 n
= l
= decoded_size
;
601 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
602 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
603 * there'd be ambiguity about what we just read. */
605 if (memchr(buf
, 0, l
)) {
612 *ret_contents
= TAKE_PTR(buf
);
620 if (flags
& READ_FULL_FILE_SECURE
)
621 explicit_bzero_safe(buf
, n
);
626 int read_full_file_full(
628 const char *filename
,
631 ReadFullFileFlags flags
,
632 const char *bind_name
,
636 _cleanup_fclose_
FILE *f
= NULL
;
640 assert(ret_contents
);
642 r
= xfopenat(dir_fd
, filename
, "re", 0, &f
);
644 _cleanup_close_
int dfd
= -1, sk
= -1;
645 union sockaddr_union sa
;
647 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
651 /* If this is enabled, let's try to connect to it */
652 if (!FLAGS_SET(flags
, READ_FULL_FILE_CONNECT_SOCKET
))
655 /* Seeking is not supported on AF_UNIX sockets */
656 if (offset
!= UINT64_MAX
)
659 if (dir_fd
== AT_FDCWD
)
660 r
= sockaddr_un_set_path(&sa
.un
, filename
);
662 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
664 /* If we shall operate relative to some directory, then let's use O_PATH first to
665 * open the socket inode, and then connect to it via /proc/self/fd/. We have to do
666 * this since there's not connectat() that takes a directory fd as first arg. */
668 dfd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
672 xsprintf(procfs_path
, "/proc/self/fd/%i", dfd
);
673 r
= sockaddr_un_set_path(&sa
.un
, procfs_path
);
678 sk
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
683 /* If the caller specified a socket name to bind to, do so before connecting. This is
684 * useful to communicate some minor, short meta-information token from the client to
686 union sockaddr_union bsa
;
688 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
692 if (bind(sk
, &bsa
.sa
, r
) < 0)
696 if (connect(sk
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
697 return errno
== ENOTSOCK
? -ENXIO
: -errno
; /* propagate original error if this is
698 * not a socket after all */
700 if (shutdown(sk
, SHUT_WR
) < 0)
710 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
712 return read_full_stream_full(f
, filename
, offset
, size
, flags
, ret_contents
, ret_size
);
715 int executable_is_script(const char *path
, char **interpreter
) {
716 _cleanup_free_
char *line
= NULL
;
723 r
= read_one_line_file(path
, &line
);
724 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
729 if (!startswith(line
, "#!"))
732 ans
= strstrip(line
+ 2);
733 len
= strcspn(ans
, " \t");
738 ans
= strndup(ans
, len
);
747 * Retrieve one field from a file like /proc/self/status. pattern
748 * should not include whitespace or the delimiter (':'). pattern matches only
749 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
750 * zeros after the ':' will be skipped. field must be freed afterwards.
751 * terminator specifies the terminating characters of the field value (not
752 * included in the value).
754 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
755 _cleanup_free_
char *status
= NULL
;
765 r
= read_full_virtual_file(filename
, &status
, NULL
);
775 t
= strstr(t
, pattern
);
779 /* Check that pattern occurs in beginning of line. */
780 pattern_ok
= (t
== status
|| t
[-1] == '\n');
782 t
+= strlen(pattern
);
784 } while (!pattern_ok
);
786 t
+= strspn(t
, " \t");
795 t
+= strspn(t
, " \t");
797 /* Also skip zeros, because when this is used for
798 * capabilities, we don't want the zeros. This way the
799 * same capability set always maps to the same string,
800 * irrespective of the total capability set size. For
801 * other numbers it shouldn't matter. */
803 /* Back off one char if there's nothing but whitespace
805 if (!*t
|| isspace(*t
))
809 len
= strcspn(t
, terminator
);
819 DIR *xopendirat(int fd
, const char *name
, int flags
) {
823 assert(!(flags
& O_CREAT
));
825 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
838 static int mode_to_flags(const char *mode
) {
842 if ((p
= startswith(mode
, "r+")))
844 else if ((p
= startswith(mode
, "r")))
846 else if ((p
= startswith(mode
, "w+")))
847 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
848 else if ((p
= startswith(mode
, "w")))
849 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
850 else if ((p
= startswith(mode
, "a+")))
851 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
852 else if ((p
= startswith(mode
, "a")))
853 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
857 for (; *p
!= 0; p
++) {
870 /* ignore this here, fdopen() might care later though */
873 case 'c': /* not sure what to do about this one */
882 int xfopenat(int dir_fd
, const char *path
, const char *mode
, int flags
, FILE **ret
) {
885 /* A combination of fopen() with openat() */
887 if (dir_fd
== AT_FDCWD
&& flags
== 0) {
888 f
= fopen(path
, mode
);
894 mode_flags
= mode_to_flags(mode
);
898 fd
= openat(dir_fd
, path
, mode_flags
| flags
);
902 f
= fdopen(fd
, mode
);
913 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
920 if (!path_strv_resolve_uniq(search
, root
))
923 STRV_FOREACH(i
, search
) {
924 _cleanup_free_
char *p
= NULL
;
927 p
= path_join(root
, *i
, path
);
944 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
945 _cleanup_strv_free_
char **copy
= NULL
;
951 if (path_is_absolute(path
)) {
954 f
= fopen(path
, mode
);
963 copy
= strv_copy((char**) search
);
967 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
970 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
971 _cleanup_strv_free_
char **s
= NULL
;
973 if (path_is_absolute(path
)) {
976 f
= fopen(path
, mode
);
985 s
= strv_split_nulstr(search
);
989 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
992 int chase_symlinks_and_fopen_unlocked(
995 unsigned chase_flags
,
996 const char *open_flags
,
1000 _cleanup_close_
int fd
= -1;
1001 _cleanup_free_
char *final_path
= NULL
;
1009 mode_flags
= mode_to_flags(open_flags
);
1013 fd
= chase_symlinks_and_open(path
, root
, chase_flags
, mode_flags
, ret_path
? &final_path
: NULL
);
1017 r
= fdopen_unlocked(fd
, open_flags
, &f
);
1024 *ret_path
= TAKE_PTR(final_path
);
1028 int fflush_and_check(FILE *f
) {
1035 return errno_or_else(EIO
);
1040 int fflush_sync_and_check(FILE *f
) {
1045 r
= fflush_and_check(f
);
1049 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1050 * assume that in that case we need no explicit syncing */
1058 r
= fsync_directory_of_file(fd
);
1065 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1066 char ln
[DECIMAL_STR_MAX(n
)+2];
1068 /* Creates a "timestamp" file, that contains nothing but a
1069 * usec_t timestamp, formatted in ASCII. */
1071 if (n
<= 0 || n
>= USEC_INFINITY
)
1074 xsprintf(ln
, USEC_FMT
"\n", n
);
1076 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1079 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1080 _cleanup_free_
char *ln
= NULL
;
1084 r
= read_one_line_file(fn
, &ln
);
1088 r
= safe_atou64(ln
, &t
);
1092 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1099 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1104 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1105 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1106 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1107 * element, but not before the first one. */
1117 r
= fputs(separator
, f
);
1128 /* A bitmask of the EOL markers we know */
1129 typedef enum EndOfLineMarker
{
1131 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
1132 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
1133 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
1136 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
1138 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
1142 return EOL_THIRTEEN
;
1151 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile
, NULL
);
1153 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
1154 size_t n
= 0, allocated
= 0, count
= 0;
1155 _cleanup_free_
char *buffer
= NULL
;
1160 /* Something like a bounded version of getline().
1162 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1163 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1176 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1177 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1179 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1180 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1182 * If a line shall be skipped ret may be initialized as NULL. */
1185 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1190 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1191 EndOfLineMarker previous_eol
= EOL_NONE
;
1195 EndOfLineMarker eol
;
1201 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1204 r
= safe_fgetc(f
, &c
);
1207 if (r
== 0) /* EOF is definitely EOL */
1210 eol
= categorize_eol(c
, flags
);
1212 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1213 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1214 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1215 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1216 * EOL marker has been seen right before? In either of these three cases we are
1217 * done. But first, let's put this character back in the queue. (Note that we have to
1218 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1219 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1220 * pass a negative value here. That said, to complicate things further ungetc() is
1221 * actually happy with most negative characters and implicitly casts them back to
1222 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1224 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1230 if (eol
!= EOL_NONE
) {
1231 /* If we are on a tty, we can't shouldn't wait for more input, because that
1232 * generally means waiting for the user, interactively. In the case of a TTY
1233 * we expect only \n as the single EOL marker, so we are in the lucky
1234 * position that there is no need to wait. We check this condition last, to
1235 * avoid isatty() check if not necessary. */
1237 if ((flags
& (READ_LINE_IS_A_TTY
|READ_LINE_NOT_A_TTY
)) == 0) {
1241 if (fd
< 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1242 * and don't call isatty() on an invalid fd */
1243 flags
|= READ_LINE_NOT_A_TTY
;
1245 flags
|= isatty(fd
) ? READ_LINE_IS_A_TTY
: READ_LINE_NOT_A_TTY
;
1247 if (FLAGS_SET(flags
, READ_LINE_IS_A_TTY
))
1251 if (eol
!= EOL_NONE
) {
1252 previous_eol
|= eol
;
1257 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1270 *ret
= TAKE_PTR(buffer
);
1276 int safe_fgetc(FILE *f
, char *ret
) {
1281 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1282 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1289 return errno_or_else(EIO
);
1303 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1310 if (stat(filename
, &_st
) < 0)
1315 if ((st
->st_mode
& S_IRWXO
) == 0)
1319 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1320 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1321 filename
, st
->st_mode
& 07777);
1323 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1324 filename
, st
->st_mode
& 07777);
1328 int sync_rights(int from
, int to
) {
1331 if (fstat(from
, &st
) < 0)
1334 return fchmod_and_chown(to
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
1337 int rename_and_apply_smack_floor_label(const char *from
, const char *to
) {
1339 if (rename(from
, to
) < 0)
1342 #ifdef SMACK_RUN_LABEL
1343 r
= mac_smack_apply(to
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);