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_virtual_file(const char *filename
, size_t max_size
, char **ret_contents
, size_t *ret_size
) {
368 _cleanup_free_
char *buf
= NULL
;
369 _cleanup_close_
int fd
= -1;
372 bool truncated
= false;
374 assert(ret_contents
);
376 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
377 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
378 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
379 * case, the content of 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 why the usage of
381 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
382 * EOF. See issue #13585.
384 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
385 * the the full file is too large to read, an error is returned. For other values of max_size,
386 * *partial contents* may be returned. (Though the read is still done using one syscall.)
387 * Returns 0 on partial success, 1 if untruncated contents were read. */
389 fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
393 assert(max_size
<= READ_FULL_BYTES_MAX
|| max_size
== SIZE_MAX
);
395 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
401 if (fstat(fd
, &st
) < 0)
404 if (!S_ISREG(st
.st_mode
))
407 /* Be prepared for files from /proc which generally report a file size of 0. */
408 assert_cc(READ_FULL_BYTES_MAX
< SSIZE_MAX
);
409 if (st
.st_size
> 0) {
410 if (st
.st_size
> SSIZE_MAX
) /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
413 size
= MIN((size_t) st
.st_size
, max_size
);
414 if (size
> READ_FULL_BYTES_MAX
)
419 size
= MIN(READ_FULL_BYTES_MAX
, max_size
);
423 buf
= malloc(size
+ 1);
426 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
427 size
= MIN3(MALLOC_SIZEOF_SAFE(buf
) - 1, max_size
, READ_FULL_BYTES_MAX
);
432 /* Read one more byte so we can detect whether the content of the
433 * file has already changed or the guessed size for files from /proc
434 * wasn't large enough . */
435 k
= read(fd
, buf
, size
+ 1);
445 /* Consider a short read as EOF */
449 /* Hmm... either we read too few bytes from /proc or less likely the content
450 * of the file might have been changed (and is now bigger) while we were
451 * processing, let's try again either with a bigger guessed size or the new
454 if (n_retries
<= 0) {
455 if (max_size
== SIZE_MAX
)
456 return st
.st_size
> 0 ? -EIO
: -EFBIG
;
458 /* Accept a short read, but truncate it appropropriately. */
459 n
= MIN(n
, max_size
);
464 if (lseek(fd
, 0, SEEK_SET
) < 0)
473 /* Return rest of the buffer to libc */
474 p
= realloc(buf
, n
+ 1);
482 else if (memchr(buf
, 0, n
))
483 /* Safety check: if the caller doesn't want to know the size of what we just read it will
484 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
485 * operation as otherwise there'd be ambiguity about what we just read. */
489 *ret_contents
= TAKE_PTR(buf
);
494 int read_full_stream_full(
496 const char *filename
,
499 ReadFullFileFlags flags
,
503 _cleanup_free_
char *buf
= NULL
;
508 assert(ret_contents
);
509 assert(!FLAGS_SET(flags
, READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
));
511 if (offset
!= UINT64_MAX
&& offset
> LONG_MAX
)
514 n_next
= size
!= SIZE_MAX
? size
: LINE_MAX
; /* Start size */
517 if (fd
>= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
518 * fmemopen()), let's optimize our buffering */
521 if (fstat(fd
, &st
) < 0)
524 if (S_ISREG(st
.st_mode
)) {
525 if (size
== SIZE_MAX
) {
527 LESS_BY((uint64_t) st
.st_size
, offset
== UINT64_MAX
? 0 : offset
);
530 if (rsize
> READ_FULL_BYTES_MAX
)
533 /* Start with the right file size. Note that we increase the size to read
534 * here by one, so that the first read attempt already makes us notice the
535 * EOF. If the reported size of the file is zero, we avoid this logic
536 * however, since quite likely it might be a virtual file in procfs that all
537 * report a zero file size. */
542 if (flags
& READ_FULL_FILE_WARN_WORLD_READABLE
)
543 (void) warn_file_is_world_accessible(filename
, &st
, NULL
, 0);
547 if (offset
!= UINT64_MAX
&& fseek(f
, offset
, SEEK_SET
) < 0)
555 if (flags
& READ_FULL_FILE_SECURE
) {
556 t
= malloc(n_next
+ 1);
561 memcpy_safe(t
, buf
, n
);
562 explicit_bzero_safe(buf
, n
);
565 t
= realloc(buf
, n_next
+ 1);
571 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
572 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
573 n
= size
== SIZE_MAX
? MALLOC_SIZEOF_SAFE(buf
) - 1 : n_next
;
576 k
= fread(buf
+ l
, 1, n
- l
, f
);
582 r
= errno_or_else(EIO
);
588 if (size
!= SIZE_MAX
) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
593 assert(k
> 0); /* we can't have read zero bytes because that would have been EOF */
596 if (n
>= READ_FULL_BYTES_MAX
) {
601 n_next
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
604 if (flags
& (READ_FULL_FILE_UNBASE64
| READ_FULL_FILE_UNHEX
)) {
605 _cleanup_free_
void *decoded
= NULL
;
609 if (flags
& READ_FULL_FILE_UNBASE64
)
610 r
= unbase64mem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
612 r
= unhexmem_full(buf
, l
, flags
& READ_FULL_FILE_SECURE
, &decoded
, &decoded_size
);
616 if (flags
& READ_FULL_FILE_SECURE
)
617 explicit_bzero_safe(buf
, n
);
618 free_and_replace(buf
, decoded
);
619 n
= l
= decoded_size
;
623 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
624 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
625 * there'd be ambiguity about what we just read. */
627 if (memchr(buf
, 0, l
)) {
634 *ret_contents
= TAKE_PTR(buf
);
642 if (flags
& READ_FULL_FILE_SECURE
)
643 explicit_bzero_safe(buf
, n
);
648 int read_full_file_full(
650 const char *filename
,
653 ReadFullFileFlags flags
,
654 const char *bind_name
,
658 _cleanup_fclose_
FILE *f
= NULL
;
662 assert(ret_contents
);
664 r
= xfopenat(dir_fd
, filename
, "re", 0, &f
);
666 _cleanup_close_
int dfd
= -1, sk
= -1;
667 union sockaddr_union sa
;
669 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
673 /* If this is enabled, let's try to connect to it */
674 if (!FLAGS_SET(flags
, READ_FULL_FILE_CONNECT_SOCKET
))
677 /* Seeking is not supported on AF_UNIX sockets */
678 if (offset
!= UINT64_MAX
)
681 if (dir_fd
== AT_FDCWD
)
682 r
= sockaddr_un_set_path(&sa
.un
, filename
);
684 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
686 /* If we shall operate relative to some directory, then let's use O_PATH first to
687 * open the socket inode, and then connect to it via /proc/self/fd/. We have to do
688 * this since there's not connectat() that takes a directory fd as first arg. */
690 dfd
= openat(dir_fd
, filename
, O_PATH
|O_CLOEXEC
);
694 xsprintf(procfs_path
, "/proc/self/fd/%i", dfd
);
695 r
= sockaddr_un_set_path(&sa
.un
, procfs_path
);
700 sk
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
705 /* If the caller specified a socket name to bind to, do so before connecting. This is
706 * useful to communicate some minor, short meta-information token from the client to
708 union sockaddr_union bsa
;
710 r
= sockaddr_un_set_path(&bsa
.un
, bind_name
);
714 if (bind(sk
, &bsa
.sa
, r
) < 0)
718 if (connect(sk
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
)) < 0)
719 return errno
== ENOTSOCK
? -ENXIO
: -errno
; /* propagate original error if this is
720 * not a socket after all */
722 if (shutdown(sk
, SHUT_WR
) < 0)
732 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
734 return read_full_stream_full(f
, filename
, offset
, size
, flags
, ret_contents
, ret_size
);
737 int executable_is_script(const char *path
, char **interpreter
) {
738 _cleanup_free_
char *line
= NULL
;
745 r
= read_one_line_file(path
, &line
);
746 if (r
== -ENOBUFS
) /* First line overly long? if so, then it's not a script */
751 if (!startswith(line
, "#!"))
754 ans
= strstrip(line
+ 2);
755 len
= strcspn(ans
, " \t");
760 ans
= strndup(ans
, len
);
769 * Retrieve one field from a file like /proc/self/status. pattern
770 * should not include whitespace or the delimiter (':'). pattern matches only
771 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
772 * zeros after the ':' will be skipped. field must be freed afterwards.
773 * terminator specifies the terminating characters of the field value (not
774 * included in the value).
776 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
777 _cleanup_free_
char *status
= NULL
;
787 r
= read_full_virtual_file(filename
, &status
, NULL
);
797 t
= strstr(t
, pattern
);
801 /* Check that pattern occurs in beginning of line. */
802 pattern_ok
= (t
== status
|| t
[-1] == '\n');
804 t
+= strlen(pattern
);
806 } while (!pattern_ok
);
808 t
+= strspn(t
, " \t");
817 t
+= strspn(t
, " \t");
819 /* Also skip zeros, because when this is used for
820 * capabilities, we don't want the zeros. This way the
821 * same capability set always maps to the same string,
822 * irrespective of the total capability set size. For
823 * other numbers it shouldn't matter. */
825 /* Back off one char if there's nothing but whitespace
827 if (!*t
|| isspace(*t
))
831 len
= strcspn(t
, terminator
);
841 DIR *xopendirat(int fd
, const char *name
, int flags
) {
845 assert(!(flags
& O_CREAT
));
847 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
860 static int mode_to_flags(const char *mode
) {
864 if ((p
= startswith(mode
, "r+")))
866 else if ((p
= startswith(mode
, "r")))
868 else if ((p
= startswith(mode
, "w+")))
869 flags
= O_RDWR
|O_CREAT
|O_TRUNC
;
870 else if ((p
= startswith(mode
, "w")))
871 flags
= O_WRONLY
|O_CREAT
|O_TRUNC
;
872 else if ((p
= startswith(mode
, "a+")))
873 flags
= O_RDWR
|O_CREAT
|O_APPEND
;
874 else if ((p
= startswith(mode
, "a")))
875 flags
= O_WRONLY
|O_CREAT
|O_APPEND
;
879 for (; *p
!= 0; p
++) {
892 /* ignore this here, fdopen() might care later though */
895 case 'c': /* not sure what to do about this one */
904 int xfopenat(int dir_fd
, const char *path
, const char *mode
, int flags
, FILE **ret
) {
907 /* A combination of fopen() with openat() */
909 if (dir_fd
== AT_FDCWD
&& flags
== 0) {
910 f
= fopen(path
, mode
);
916 mode_flags
= mode_to_flags(mode
);
920 fd
= openat(dir_fd
, path
, mode_flags
| flags
);
924 f
= fdopen(fd
, mode
);
935 static int search_and_fopen_internal(
949 if (!path_strv_resolve_uniq(search
, root
))
952 STRV_FOREACH(i
, search
) {
953 _cleanup_free_
char *p
= NULL
;
956 p
= path_join(root
, *i
, path
);
963 *ret_path
= path_simplify(TAKE_PTR(p
), true);
976 int search_and_fopen(
977 const char *filename
,
984 _cleanup_strv_free_
char **copy
= NULL
;
990 if (path_is_absolute(filename
)) {
991 _cleanup_fclose_
FILE *f
= NULL
;
993 f
= fopen(filename
, mode
);
1000 p
= strdup(filename
);
1004 *ret_path
= path_simplify(p
, true);
1011 copy
= strv_copy((char**) search
);
1015 return search_and_fopen_internal(filename
, mode
, root
, copy
, ret
, ret_path
);
1018 int search_and_fopen_nulstr(
1019 const char *filename
,
1026 _cleanup_strv_free_
char **s
= NULL
;
1028 if (path_is_absolute(filename
)) {
1029 _cleanup_fclose_
FILE *f
= NULL
;
1031 f
= fopen(filename
, mode
);
1038 p
= strdup(filename
);
1042 *ret_path
= path_simplify(p
, true);
1049 s
= strv_split_nulstr(search
);
1053 return search_and_fopen_internal(filename
, mode
, root
, s
, ret
, ret_path
);
1056 int chase_symlinks_and_fopen_unlocked(
1059 unsigned chase_flags
,
1060 const char *open_flags
,
1064 _cleanup_close_
int fd
= -1;
1065 _cleanup_free_
char *final_path
= NULL
;
1072 mode_flags
= mode_to_flags(open_flags
);
1076 fd
= chase_symlinks_and_open(path
, root
, chase_flags
, mode_flags
, ret_path
? &final_path
: NULL
);
1080 r
= take_fdopen_unlocked(&fd
, open_flags
, ret_file
);
1085 *ret_path
= TAKE_PTR(final_path
);
1089 int fflush_and_check(FILE *f
) {
1096 return errno_or_else(EIO
);
1101 int fflush_sync_and_check(FILE *f
) {
1106 r
= fflush_and_check(f
);
1110 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1111 * assume that in that case we need no explicit syncing */
1119 r
= fsync_directory_of_file(fd
);
1126 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1127 char ln
[DECIMAL_STR_MAX(n
)+2];
1129 /* Creates a "timestamp" file, that contains nothing but a
1130 * usec_t timestamp, formatted in ASCII. */
1132 if (n
<= 0 || n
>= USEC_INFINITY
)
1135 xsprintf(ln
, USEC_FMT
"\n", n
);
1137 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1140 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1141 _cleanup_free_
char *ln
= NULL
;
1145 r
= read_one_line_file(fn
, &ln
);
1149 r
= safe_atou64(ln
, &t
);
1153 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1160 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1165 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1166 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1167 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1168 * element, but not before the first one. */
1178 r
= fputs(separator
, f
);
1189 /* A bitmask of the EOL markers we know */
1190 typedef enum EndOfLineMarker
{
1192 EOL_ZERO
= 1 << 0, /* \0 (aka NUL) */
1193 EOL_TEN
= 1 << 1, /* \n (aka NL, aka LF) */
1194 EOL_THIRTEEN
= 1 << 2, /* \r (aka CR) */
1197 static EndOfLineMarker
categorize_eol(char c
, ReadLineFlags flags
) {
1199 if (!IN_SET(flags
, READ_LINE_ONLY_NUL
)) {
1203 return EOL_THIRTEEN
;
1212 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile
, NULL
);
1214 int read_line_full(FILE *f
, size_t limit
, ReadLineFlags flags
, char **ret
) {
1215 _cleanup_free_
char *buffer
= NULL
;
1216 size_t n
= 0, count
= 0;
1221 /* Something like a bounded version of getline().
1223 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1224 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1237 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1238 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1240 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1241 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1243 * If a line shall be skipped ret may be initialized as NULL. */
1246 if (!GREEDY_REALLOC(buffer
, 1))
1251 _unused_
_cleanup_(funlockfilep
) FILE *flocked
= f
;
1252 EndOfLineMarker previous_eol
= EOL_NONE
;
1256 EndOfLineMarker eol
;
1262 if (count
>= INT_MAX
) /* We couldn't return the counter anymore as "int", hence refuse this */
1265 r
= safe_fgetc(f
, &c
);
1268 if (r
== 0) /* EOF is definitely EOL */
1271 eol
= categorize_eol(c
, flags
);
1273 if (FLAGS_SET(previous_eol
, EOL_ZERO
) ||
1274 (eol
== EOL_NONE
&& previous_eol
!= EOL_NONE
) ||
1275 (eol
!= EOL_NONE
&& (previous_eol
& eol
) != 0)) {
1276 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1277 * EOL marker has been seen right before? In either of these three cases we are
1278 * done. But first, let's put this character back in the queue. (Note that we have to
1279 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1280 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1281 * pass a negative value here. That said, to complicate things further ungetc() is
1282 * actually happy with most negative characters and implicitly casts them back to
1283 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1285 assert_se(ungetc((unsigned char) c
, f
) != EOF
);
1291 if (eol
!= EOL_NONE
) {
1292 /* If we are on a tty, we can't shouldn't wait for more input, because that
1293 * generally means waiting for the user, interactively. In the case of a TTY
1294 * we expect only \n as the single EOL marker, so we are in the lucky
1295 * position that there is no need to wait. We check this condition last, to
1296 * avoid isatty() check if not necessary. */
1298 if ((flags
& (READ_LINE_IS_A_TTY
|READ_LINE_NOT_A_TTY
)) == 0) {
1302 if (fd
< 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1303 * and don't call isatty() on an invalid fd */
1304 flags
|= READ_LINE_NOT_A_TTY
;
1306 flags
|= isatty(fd
) ? READ_LINE_IS_A_TTY
: READ_LINE_NOT_A_TTY
;
1308 if (FLAGS_SET(flags
, READ_LINE_IS_A_TTY
))
1312 if (eol
!= EOL_NONE
) {
1313 previous_eol
|= eol
;
1318 if (!GREEDY_REALLOC(buffer
, n
+ 2))
1331 *ret
= TAKE_PTR(buffer
);
1337 int safe_fgetc(FILE *f
, char *ret
) {
1342 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1343 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1350 return errno_or_else(EIO
);
1364 int warn_file_is_world_accessible(const char *filename
, struct stat
*st
, const char *unit
, unsigned line
) {
1371 if (stat(filename
, &_st
) < 0)
1376 if ((st
->st_mode
& S_IRWXO
) == 0)
1380 log_syntax(unit
, LOG_WARNING
, filename
, line
, 0,
1381 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1382 filename
, st
->st_mode
& 07777);
1384 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1385 filename
, st
->st_mode
& 07777);
1389 int rename_and_apply_smack_floor_label(const char *from
, const char *to
) {
1391 if (rename(from
, to
) < 0)
1394 #if HAVE_SMACK_RUN_LABEL
1395 r
= mac_smack_apply(to
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);