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 /* The maximum size of the file we'll read in one go. */
31 #define READ_FULL_BYTES_MAX (4U*1024U*1024U - 1)
33 int fopen_unlocked(const char *path
, const char *options
, FILE **ret
) {
36 FILE *f
= fopen(path
, options
);
40 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
46 int fdopen_unlocked(int fd
, const char *options
, FILE **ret
) {
49 FILE *f
= fdopen(fd
, options
);
53 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
59 int take_fdopen_unlocked(int *fd
, const char *options
, FILE **ret
) {
64 r
= fdopen_unlocked(*fd
, options
, ret
);
73 FILE* take_fdopen(int *fd
, const char *options
) {
76 FILE *f
= fdopen(*fd
, options
);
85 DIR* take_fdopendir(int *dfd
) {
88 DIR *d
= fdopendir(*dfd
);
97 FILE* open_memstream_unlocked(char **ptr
, size_t *sizeloc
) {
98 FILE *f
= open_memstream(ptr
, sizeloc
);
102 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
107 FILE* fmemopen_unlocked(void *buf
, size_t size
, const char *mode
) {
108 FILE *f
= fmemopen(buf
, size
, mode
);
112 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
117 int write_string_stream_ts(
120 WriteStringFileFlags flags
,
121 const struct timespec
*ts
) {
133 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
134 * an fd. Let's fail early in that case. */
140 needs_nl
= !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) && !endswith(line
, "\n");
142 if (needs_nl
&& (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)) {
143 /* If STDIO buffering was disabled, then let's append the newline character to the string
144 * itself, so that the write goes out in one go, instead of two */
146 line
= strjoina(line
, "\n");
150 if (fputs(line
, f
) == EOF
)
154 if (fputc('\n', f
) == EOF
)
157 if (flags
& WRITE_STRING_FILE_SYNC
)
158 r
= fflush_sync_and_check(f
);
160 r
= fflush_and_check(f
);
165 const struct timespec twice
[2] = {*ts
, *ts
};
168 if (futimens(fd
, twice
) < 0)
175 static int write_string_file_atomic(
178 WriteStringFileFlags flags
,
179 const struct timespec
*ts
) {
181 _cleanup_fclose_
FILE *f
= NULL
;
182 _cleanup_free_
char *p
= NULL
;
188 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
189 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
191 r
= fopen_temporary(fn
, &f
, &p
);
195 r
= write_string_stream_ts(f
, line
, flags
, ts
);
199 r
= fchmod_umask(fileno(f
), FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0644);
203 if (rename(p
, fn
) < 0) {
208 if (FLAGS_SET(flags
, WRITE_STRING_FILE_SYNC
)) {
209 /* Sync the rename, too */
210 r
= fsync_directory_of_file(fileno(f
));
222 int write_string_file_ts(
225 WriteStringFileFlags flags
,
226 const struct timespec
*ts
) {
228 _cleanup_fclose_
FILE *f
= NULL
;
234 /* We don't know how to verify whether the file contents was already on-disk. */
235 assert(!((flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
) && (flags
& WRITE_STRING_FILE_SYNC
)));
237 if (flags
& WRITE_STRING_FILE_MKDIR_0755
) {
238 r
= mkdir_parents(fn
, 0755);
243 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
244 assert(flags
& WRITE_STRING_FILE_CREATE
);
246 r
= write_string_file_atomic(fn
, line
, flags
, ts
);
254 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
255 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
|
256 (FLAGS_SET(flags
, WRITE_STRING_FILE_NOFOLLOW
) ? O_NOFOLLOW
: 0) |
257 (FLAGS_SET(flags
, WRITE_STRING_FILE_CREATE
) ? O_CREAT
: 0) |
258 (FLAGS_SET(flags
, WRITE_STRING_FILE_TRUNCATE
) ? O_TRUNC
: 0),
259 (FLAGS_SET(flags
, WRITE_STRING_FILE_MODE_0600
) ? 0600 : 0666));
265 r
= fdopen_unlocked(fd
, "w", &f
);
271 if (flags
& WRITE_STRING_FILE_DISABLE_BUFFER
)
272 setvbuf(f
, NULL
, _IONBF
, 0);
274 r
= write_string_stream_ts(f
, line
, flags
, ts
);
281 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
286 /* OK, the operation failed, but let's see if the right
287 * contents in place already. If so, eat up the error. */
289 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
) || (flags
& WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE
));
296 int write_string_filef(
298 WriteStringFileFlags flags
,
299 const char *format
, ...) {
301 _cleanup_free_
char *p
= NULL
;
305 va_start(ap
, format
);
306 r
= vasprintf(&p
, format
, ap
);
312 return write_string_file(fn
, p
, flags
);
315 int read_one_line_file(const char *fn
, char **line
) {
316 _cleanup_fclose_
FILE *f
= NULL
;
322 r
= fopen_unlocked(fn
, "re", &f
);
326 return read_line(f
, LONG_LINE_MAX
, line
);
329 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
330 _cleanup_fclose_
FILE *f
= NULL
;
331 _cleanup_free_
char *buf
= NULL
;
340 if (accept_extra_nl
&& endswith(blob
, "\n"))
341 accept_extra_nl
= false;
343 buf
= malloc(l
+ accept_extra_nl
+ 1);
347 r
= fopen_unlocked(fn
, "re", &f
);
351 /* We try to read one byte more than we need, so that we know whether we hit eof */
353 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
355 return errno_or_else(EIO
);
357 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
359 if (memcmp(buf
, blob
, l
) != 0)
361 if (k
> l
&& buf
[l
] != '\n')
367 int read_full_virtual_file(const char *filename
, char **ret_contents
, size_t *ret_size
) {
368 _cleanup_free_
char *buf
= NULL
;
369 _cleanup_close_
int fd
= -1;
374 assert(ret_contents
);
376 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work
377 * with two sorts of virtual files. One sort uses "seq_file", and the results of
378 * the first read are buffered for the second read. The other sort uses "raw"
379 * reads which always go direct to the device. In the latter case, the content of
380 * the virtual file must be retrieved with a single read otherwise a second read
381 * might get the new value instead of finding EOF immediately. That's the reason
382 * why the usage of fread(3) is prohibited in this case as it always performs a
383 * second call to read(2) looking for EOF. See issue 13585. */
385 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
389 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
393 if (fstat(fd
, &st
) < 0)
396 if (!S_ISREG(st
.st_mode
))
399 /* Be prepared for files from /proc which generally report a file size of 0. */
400 assert_cc(READ_FULL_BYTES_MAX
< SSIZE_MAX
);
401 if (st
.st_size
> 0) {
402 if (st
.st_size
> READ_FULL_BYTES_MAX
)
408 size
= READ_FULL_BYTES_MAX
;
412 buf
= malloc(size
+ 1);
415 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
416 size
= MIN(malloc_usable_size(buf
) - 1, READ_FULL_BYTES_MAX
);
421 /* Read one more byte so we can detect whether the content of the
422 * file has already changed or the guessed size for files from /proc
423 * wasn't large enough . */
424 k
= read(fd
, buf
, size
+ 1);
434 /* Consider a short read as EOF */
438 /* Hmm... either we read too few bytes from /proc or less likely the content
439 * of the file might have been changed (and is now bigger) while we were
440 * processing, let's try again either with a bigger guessed size or the new
444 return st
.st_size
> 0 ? -EIO
: -EFBIG
;
446 if (lseek(fd
, 0, SEEK_SET
) < 0)
455 /* Return rest of the buffer to libc */
456 p
= realloc(buf
, n
+ 1);
464 else if (memchr(buf
, 0, n
))
465 /* Safety check: if the caller doesn't want to know the size of what we just read it will
466 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
467 * operation as otherwise there'd be ambiguity about what we just read. */
471 *ret_contents
= TAKE_PTR(buf
);
476 int read_full_stream_full(
478 const char *filename
,
481 ReadFullFileFlags flags
,
485 _cleanup_free_
char *buf
= NULL
;
490 assert(ret_contents
);
491 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
493 if (offset
!= UINT64_MAX
&& offset
> LONG_MAX
)
496 n_next
= size
!= SIZE_MAX
? size
: LINE_MAX
; /* Start size */
499 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
500 * fmemopen()), let's optimize our buffering */
503 if (fstat(fd
, &st
) < 0)
506 if (S_ISREG(st
.st_mode
)) {
507 if (size
== SIZE_MAX
) {
509 LESS_BY((uint64_t) st
.st_size
, offset
== UINT64_MAX
? 0 : offset
);
512 if (rsize
> READ_FULL_BYTES_MAX
)
515 /* Start with the right file size. Note that we increase the size to read
516 * here by one, so that the first read attempt already makes us notice the
517 * EOF. If the reported size of the file is zero, we avoid this logic
518 * however, since quite likely it might be a virtual file in procfs that all
519 * report a zero file size. */
524 if (flags
& READ_FULL_FILE_WARN_WORLD_READABLE
)
525 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
529 if (offset
!= UINT64_MAX
&& fseek(f
, offset
, SEEK_SET
) < 0)
537 if (flags
& READ_FULL_FILE_SECURE
) {
538 t
= malloc(n_next
+ 1);
543 memcpy_safe(t
, buf
, n
);
544 explicit_bzero_safe(buf
, n
);
547 t
= realloc(buf
, n_next
+ 1);
553 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
554 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
555 n
= size
== SIZE_MAX
? malloc_usable_size(buf
) - 1 : n_next
;
558 k
= fread(buf
+ l
, 1, n
- l
, f
);
564 r
= errno_or_else(EIO
);
570 if (size
!= SIZE_MAX
) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
575 assert(k
> 0); /* we can't have read zero bytes because that would have been EOF */
578 if (n
>= READ_FULL_BYTES_MAX
) {
583 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
586 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
587 _cleanup_free_
void *decoded
= NULL
;
591 if (flags
& READ_FULL_FILE_UNBASE64
)
592 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
594 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
598 if (flags
& READ_FULL_FILE_SECURE
)
599 explicit_bzero_safe(buf
, n
);
600 free_and_replace(buf
, decoded
);
601 n
= l
= decoded_size
;
605 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
606 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
607 * there'd be ambiguity about what we just read. */
609 if (memchr(buf
, 0, l
)) {
616 *ret_contents
= TAKE_PTR(buf
);
624 if (flags
& READ_FULL_FILE_SECURE
)
625 explicit_bzero_safe(buf
, n
);
630 int read_full_file_full(
632 const char *filename
,
635 ReadFullFileFlags flags
,
636 const char *bind_name
,
640 _cleanup_fclose_
FILE *f
= NULL
;
644 assert(ret_contents
);
646 r
= xfopenat(dir_fd
, filename
, "re", 0, &f
);
648 _cleanup_close_
int dfd
= -1, sk
= -1;
649 union sockaddr_union sa
;
651 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
655 /* If this is enabled, let's try to connect to it */
656 if (!FLAGS_SET(flags
, READ_FULL_FILE_CONNECT_SOCKET
))
659 /* Seeking is not supported on AF_UNIX sockets */
660 if (offset
!= UINT64_MAX
)
663 if (dir_fd
== AT_FDCWD
)
664 r
= sockaddr_un_set_path(&sa
.un
, filename
);
666 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
668 /* If we shall operate relative to some directory, then let's use O_PATH first to
669 * open the socket inode, and then connect to it via /proc/self/fd/. We have to do
670 * this since there's not connectat() that takes a directory fd as first arg. */
672 dfd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
676 xsprintf(procfs_path
, "/proc/self/fd/%i", dfd
);
677 r
= sockaddr_un_set_path(&sa
.un
, procfs_path
);
682 sk
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
687 /* If the caller specified a socket name to bind to, do so before connecting. This is
688 * useful to communicate some minor, short meta-information token from the client to
690 union sockaddr_union bsa
;
692 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
696 if (bind(sk
, &bsa
.sa
, r
) < 0)
700 if (connect(sk
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
701 return errno
== ENOTSOCK
? -ENXIO
: -errno
; /* propagate original error if this is
702 * not a socket after all */
704 if (shutdown(sk
, SHUT_WR
) < 0)
714 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
716 return read_full_stream_full(f
, filename
, offset
, size
, flags
, ret_contents
, ret_size
);
719 int executable_is_script(const char *path
, char **interpreter
) {
720 _cleanup_free_
char *line
= NULL
;
727 r
= read_one_line_file(path
, &line
);
728 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
733 if (!startswith(line
, "#!"))
736 ans
= strstrip(line
+ 2);
737 len
= strcspn(ans
, " \t");
742 ans
= strndup(ans
, len
);
751 * Retrieve one field from a file like /proc/self/status. pattern
752 * should not include whitespace or the delimiter (':'). pattern matches only
753 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
754 * zeros after the ':' will be skipped. field must be freed afterwards.
755 * terminator specifies the terminating characters of the field value (not
756 * included in the value).
758 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
759 _cleanup_free_
char *status
= NULL
;
769 r
= read_full_virtual_file(filename
, &status
, NULL
);
779 t
= strstr(t
, pattern
);
783 /* Check that pattern occurs in beginning of line. */
784 pattern_ok
= (t
== status
|| t
[-1] == '\n');
786 t
+= strlen(pattern
);
788 } while (!pattern_ok
);
790 t
+= strspn(t
, " \t");
799 t
+= strspn(t
, " \t");
801 /* Also skip zeros, because when this is used for
802 * capabilities, we don't want the zeros. This way the
803 * same capability set always maps to the same string,
804 * irrespective of the total capability set size. For
805 * other numbers it shouldn't matter. */
807 /* Back off one char if there's nothing but whitespace
809 if (!*t
|| isspace(*t
))
813 len
= strcspn(t
, terminator
);
823 DIR *xopendirat(int fd
, const char *name
, int flags
) {
827 assert(!(flags
& O_CREAT
));
829 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
842 static int mode_to_flags(const char *mode
) {
846 if ((p
= startswith(mode
, "r+")))
848 else if ((p
= startswith(mode
, "r")))
850 else if ((p
= startswith(mode
, "w+")))
851 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
852 else if ((p
= startswith(mode
, "w")))
853 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
854 else if ((p
= startswith(mode
, "a+")))
855 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
856 else if ((p
= startswith(mode
, "a")))
857 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
861 for (; *p
!= 0; p
++) {
874 /* ignore this here, fdopen() might care later though */
877 case 'c': /* not sure what to do about this one */
886 int xfopenat(int dir_fd
, const char *path
, const char *mode
, int flags
, FILE **ret
) {
889 /* A combination of fopen() with openat() */
891 if (dir_fd
== AT_FDCWD
&& flags
== 0) {
892 f
= fopen(path
, mode
);
898 mode_flags
= mode_to_flags(mode
);
902 fd
= openat(dir_fd
, path
, mode_flags
| flags
);
906 f
= fdopen(fd
, mode
);
917 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
924 if (!path_strv_resolve_uniq(search
, root
))
927 STRV_FOREACH(i
, search
) {
928 _cleanup_free_
char *p
= NULL
;
931 p
= path_join(root
, *i
, path
);
948 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
949 _cleanup_strv_free_
char **copy
= NULL
;
955 if (path_is_absolute(path
)) {
958 f
= fopen(path
, mode
);
967 copy
= strv_copy((char**) search
);
971 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
974 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
975 _cleanup_strv_free_
char **s
= NULL
;
977 if (path_is_absolute(path
)) {
980 f
= fopen(path
, mode
);
989 s
= strv_split_nulstr(search
);
993 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
996 int chase_symlinks_and_fopen_unlocked(
999 unsigned chase_flags
,
1000 const char *open_flags
,
1004 _cleanup_close_
int fd
= -1;
1005 _cleanup_free_
char *final_path
= NULL
;
1013 mode_flags
= mode_to_flags(open_flags
);
1017 fd
= chase_symlinks_and_open(path
, root
, chase_flags
, mode_flags
, ret_path
? &final_path
: NULL
);
1021 r
= fdopen_unlocked(fd
, open_flags
, &f
);
1028 *ret_path
= TAKE_PTR(final_path
);
1032 int fflush_and_check(FILE *f
) {
1039 return errno_or_else(EIO
);
1044 int fflush_sync_and_check(FILE *f
) {
1049 r
= fflush_and_check(f
);
1053 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1054 * assume that in that case we need no explicit syncing */
1062 r
= fsync_directory_of_file(fd
);
1069 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1070 char ln
[DECIMAL_STR_MAX(n
)+2];
1072 /* Creates a "timestamp" file, that contains nothing but a
1073 * usec_t timestamp, formatted in ASCII. */
1075 if (n
<= 0 || n
>= USEC_INFINITY
)
1078 xsprintf(ln
, USEC_FMT
"\n", n
);
1080 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1083 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1084 _cleanup_free_
char *ln
= NULL
;
1088 r
= read_one_line_file(fn
, &ln
);
1092 r
= safe_atou64(ln
, &t
);
1096 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1103 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1108 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1109 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1110 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1111 * element, but not before the first one. */
1121 r
= fputs(separator
, f
);
1132 /* A bitmask of the EOL markers we know */
1133 typedef enum EndOfLineMarker
{
1135 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
1136 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
1137 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
1140 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
1142 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
1146 return EOL_THIRTEEN
;
1155 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile
, NULL
);
1157 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
1158 size_t n
= 0, allocated
= 0, count
= 0;
1159 _cleanup_free_
char *buffer
= NULL
;
1164 /* Something like a bounded version of getline().
1166 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1167 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1180 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1181 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1183 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1184 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1186 * If a line shall be skipped ret may be initialized as NULL. */
1189 if (!GREEDY_REALLOC(buffer
, allocated
, 1))
1194 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1195 EndOfLineMarker previous_eol
= EOL_NONE
;
1199 EndOfLineMarker eol
;
1205 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1208 r
= safe_fgetc(f
, &c
);
1211 if (r
== 0) /* EOF is definitely EOL */
1214 eol
= categorize_eol(c
, flags
);
1216 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1217 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1218 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1219 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1220 * EOL marker has been seen right before? In either of these three cases we are
1221 * done. But first, let's put this character back in the queue. (Note that we have to
1222 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1223 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1224 * pass a negative value here. That said, to complicate things further ungetc() is
1225 * actually happy with most negative characters and implicitly casts them back to
1226 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1228 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1234 if (eol
!= EOL_NONE
) {
1235 /* If we are on a tty, we can't shouldn't wait for more input, because that
1236 * generally means waiting for the user, interactively. In the case of a TTY
1237 * we expect only \n as the single EOL marker, so we are in the lucky
1238 * position that there is no need to wait. We check this condition last, to
1239 * avoid isatty() check if not necessary. */
1241 if ((flags
& (READ_LINE_IS_A_TTY
|READ_LINE_NOT_A_TTY
)) == 0) {
1245 if (fd
< 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1246 * and don't call isatty() on an invalid fd */
1247 flags
|= READ_LINE_NOT_A_TTY
;
1249 flags
|= isatty(fd
) ? READ_LINE_IS_A_TTY
: READ_LINE_NOT_A_TTY
;
1251 if (FLAGS_SET(flags
, READ_LINE_IS_A_TTY
))
1255 if (eol
!= EOL_NONE
) {
1256 previous_eol
|= eol
;
1261 if (!GREEDY_REALLOC(buffer
, allocated
, n
+ 2))
1274 *ret
= TAKE_PTR(buffer
);
1280 int safe_fgetc(FILE *f
, char *ret
) {
1285 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1286 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1293 return errno_or_else(EIO
);
1307 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1314 if (stat(filename
, &_st
) < 0)
1319 if ((st
->st_mode
& S_IRWXO
) == 0)
1323 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1324 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1325 filename
, st
->st_mode
& 07777);
1327 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1328 filename
, st
->st_mode
& 07777);
1332 int rename_and_apply_smack_floor_label(const char *from
, const char *to
) {
1334 if (rename(from
, to
) < 0)
1337 #ifdef SMACK_RUN_LABEL
1338 r
= mac_smack_apply(to
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);