]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fileio.c
97f92213da57966583ca34903dc37e1dd2fa2fe2
[thirdparty/systemd.git] / src / basic / fileio.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <stdio_ext.h>
5 #include <stdlib.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8
9 #include "alloc-util.h"
10 #include "errno-util.h"
11 #include "extract-word.h"
12 #include "fd-util.h"
13 #include "fileio.h"
14 #include "fs-util.h"
15 #include "hexdecoct.h"
16 #include "label.h"
17 #include "log.h"
18 #include "mkdir.h"
19 #include "nulstr-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "socket-util.h"
23 #include "stat-util.h"
24 #include "stdio-util.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "sync-util.h"
28 #include "terminal-util.h"
29 #include "time-util.h"
30 #include "tmpfile-util.h"
31
32 /* The maximum size of the file we'll read in one go in read_full_file() (64M). */
33 #define READ_FULL_BYTES_MAX (64U * U64_MB - UINT64_C(1))
34 /* Used when a size is specified for read_full_file() with READ_FULL_FILE_UNBASE64 or _UNHEX */
35 #define READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY 3
36
37 /* The maximum size of virtual files (i.e. procfs, sysfs, and other virtual "API" files) we'll read in one go
38 * in read_virtual_file(). Note that this limit is different (and much lower) than the READ_FULL_BYTES_MAX
39 * limit. This reflects the fact that we use different strategies for reading virtual and regular files:
40 * virtual files we generally have to read in a single read() syscall since the kernel doesn't support
41 * continuation read()s for them. Thankfully they are somewhat size constrained. Thus we can allocate the
42 * full potential buffer in advance. Regular files OTOH can be much larger, and there we grow the allocations
43 * exponentially in a loop. We use a size limit of 4M-2 because 4M-1 is the maximum buffer that /proc/sys/
44 * allows us to read() (larger reads will fail with ENOMEM), and we want to read one extra byte so that we
45 * can detect EOFs. */
46 #define READ_VIRTUAL_BYTES_MAX (4U * U64_MB - UINT64_C(2))
47
48 int fdopen_unlocked(int fd, const char *options, FILE **ret) {
49 assert(ret);
50
51 FILE *f = fdopen(fd, options);
52 if (!f)
53 return -errno;
54
55 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
56
57 *ret = f;
58 return 0;
59 }
60
61 int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) {
62 int r;
63
64 assert(fd);
65
66 r = fdopen_unlocked(*fd, options, ret);
67 if (r < 0)
68 return r;
69
70 *fd = -EBADF;
71
72 return 0;
73 }
74
75 FILE* take_fdopen(int *fd, const char *options) {
76 assert(fd);
77
78 FILE *f = fdopen(*fd, options);
79 if (!f)
80 return NULL;
81
82 *fd = -EBADF;
83
84 return f;
85 }
86
87 DIR* take_fdopendir(int *dfd) {
88 assert(dfd);
89
90 DIR *d = fdopendir(*dfd);
91 if (!d)
92 return NULL;
93
94 *dfd = -EBADF;
95
96 return d;
97 }
98
99 FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
100 FILE *f = open_memstream(ptr, sizeloc);
101 if (!f)
102 return NULL;
103
104 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
105
106 return f;
107 }
108
109 FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode) {
110 FILE *f = fmemopen(buf, size, mode);
111 if (!f)
112 return NULL;
113
114 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
115
116 return f;
117 }
118
119 int write_string_stream_full(
120 FILE *f,
121 const char *line,
122 WriteStringFileFlags flags,
123 const struct timespec *ts) {
124
125 bool needs_nl;
126 int r, fd = -EBADF;
127
128 assert(f);
129 assert(line);
130
131 if (ferror(f))
132 return -EIO;
133
134 if (ts) {
135 /* If we shall set the timestamp we need the fd. But fmemopen() streams generally don't have
136 * an fd. Let's fail early in that case. */
137 fd = fileno(f);
138 if (fd < 0)
139 return -EBADF;
140 }
141
142 if (flags & WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) {
143 _cleanup_free_ char *t = NULL;
144
145 /* If value to be written is same as that of the existing value, then suppress the write. */
146
147 if (fd < 0) {
148 fd = fileno(f);
149 if (fd < 0)
150 return -EBADF;
151 }
152
153 /* Read an additional byte to detect cases where the prefix matches but the rest
154 * doesn't. Also, 0 returned by read_virtual_file_fd() means the read was truncated and
155 * it won't be equal to the new value. */
156 if (read_virtual_file_fd(fd, strlen(line)+1, &t, NULL) > 0 &&
157 streq_skip_trailing_chars(line, t, NEWLINE)) {
158 log_debug("No change in value '%s', suppressing write", line);
159 return 0;
160 }
161
162 if (lseek(fd, 0, SEEK_SET) < 0)
163 return -errno;
164 }
165
166 needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n");
167
168 if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) {
169 /* If STDIO buffering was disabled, then let's append the newline character to the string
170 * itself, so that the write goes out in one go, instead of two */
171
172 line = strjoina(line, "\n");
173 needs_nl = false;
174 }
175
176 if (fputs(line, f) == EOF)
177 return -errno;
178
179 if (needs_nl)
180 if (fputc('\n', f) == EOF)
181 return -errno;
182
183 if (flags & WRITE_STRING_FILE_SYNC)
184 r = fflush_sync_and_check(f);
185 else
186 r = fflush_and_check(f);
187 if (r < 0)
188 return r;
189
190 if (ts) {
191 const struct timespec twice[2] = {*ts, *ts};
192
193 assert(fd >= 0);
194 if (futimens(fd, twice) < 0)
195 return -errno;
196 }
197
198 return 0;
199 }
200
201 static mode_t write_string_file_flags_to_mode(WriteStringFileFlags flags) {
202
203 /* We support three different modes, that are the ones that really make sense for text files like this:
204 *
205 * → 0600 (i.e. root-only)
206 * → 0444 (i.e. read-only)
207 * → 0644 (i.e. writable for root, readable for everyone else)
208 */
209
210 return FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0600) ? 0600 :
211 FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0444) ? 0444 : 0644;
212 }
213
214 static int write_string_file_atomic_at(
215 int dir_fd,
216 const char *fn,
217 const char *line,
218 WriteStringFileFlags flags,
219 const struct timespec *ts) {
220
221 _cleanup_fclose_ FILE *f = NULL;
222 _cleanup_free_ char *p = NULL;
223 int r;
224
225 assert(fn);
226 assert(line);
227
228 /* Note that we'd really like to use O_TMPFILE here, but can't really, since we want replacement
229 * semantics here, and O_TMPFILE can't offer that. i.e. rename() replaces but linkat() doesn't. */
230
231 mode_t mode = write_string_file_flags_to_mode(flags);
232
233 bool call_label_ops_post = false;
234 if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL)) {
235 r = label_ops_pre(dir_fd, fn, mode);
236 if (r < 0)
237 return r;
238
239 call_label_ops_post = true;
240 }
241
242 r = fopen_temporary_at(dir_fd, fn, &f, &p);
243 if (call_label_ops_post)
244 /* If fopen_temporary_at() failed in the above, propagate the error code, and ignore failures
245 * in label_ops_post(). */
246 RET_GATHER(r, label_ops_post(f ? fileno(f) : dir_fd, f ? NULL : fn, /* created= */ !!f));
247 if (r < 0)
248 goto fail;
249
250 r = write_string_stream_full(f, line, flags, ts);
251 if (r < 0)
252 goto fail;
253
254 r = fchmod_umask(fileno(f), mode);
255 if (r < 0)
256 goto fail;
257
258 r = RET_NERRNO(renameat(dir_fd, p, dir_fd, fn));
259 if (r < 0)
260 goto fail;
261
262 if (FLAGS_SET(flags, WRITE_STRING_FILE_SYNC)) {
263 /* Sync the rename, too */
264 r = fsync_directory_of_file(fileno(f));
265 if (r < 0)
266 return r;
267 }
268
269 return 0;
270
271 fail:
272 if (f)
273 (void) unlinkat(dir_fd, p, 0);
274 return r;
275 }
276
277 int write_string_file_full(
278 int dir_fd,
279 const char *fn,
280 const char *line,
281 WriteStringFileFlags flags,
282 const struct timespec *ts,
283 const char *label_fn) {
284
285 bool made_file = false;
286 _cleanup_fclose_ FILE *f = NULL;
287 _cleanup_close_ int fd = -EBADF;
288 int r;
289
290 assert(dir_fd == AT_FDCWD || dir_fd >= 0);
291 assert(line);
292
293 /* We don't know how to verify whether the file contents was already on-disk. */
294 assert(!((flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE) && (flags & WRITE_STRING_FILE_SYNC)));
295
296 if (flags & WRITE_STRING_FILE_MKDIR_0755) {
297 assert(fn);
298
299 r = mkdirat_parents(dir_fd, fn, 0755);
300 if (r < 0)
301 return r;
302 }
303
304 if (flags & WRITE_STRING_FILE_ATOMIC) {
305 assert(fn);
306 assert(flags & WRITE_STRING_FILE_CREATE);
307
308 r = write_string_file_atomic_at(dir_fd, fn, line, flags, ts);
309 if (r < 0)
310 goto fail;
311
312 return r;
313 }
314
315 /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */
316 if (isempty(fn))
317 r = fd = fd_reopen(
318 ASSERT_FD(dir_fd), O_CLOEXEC | O_NOCTTY |
319 (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
320 (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
321 (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0));
322 else {
323 mode_t mode = write_string_file_flags_to_mode(flags);
324 bool call_label_ops_post = false;
325
326 if (FLAGS_SET(flags, WRITE_STRING_FILE_LABEL|WRITE_STRING_FILE_CREATE)) {
327 r = label_ops_pre(dir_fd, label_fn ?: fn, mode);
328 if (r < 0)
329 goto fail;
330
331 call_label_ops_post = true;
332 }
333
334 r = fd = openat_report_new(
335 dir_fd, fn, O_CLOEXEC | O_NOCTTY |
336 (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) |
337 (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) |
338 (FLAGS_SET(flags, WRITE_STRING_FILE_TRUNCATE) ? O_TRUNC : 0) |
339 (FLAGS_SET(flags, WRITE_STRING_FILE_SUPPRESS_REDUNDANT_VIRTUAL) ? O_RDWR : O_WRONLY) |
340 (FLAGS_SET(flags, WRITE_STRING_FILE_OPEN_NONBLOCKING) ? O_NONBLOCK : 0),
341 mode,
342 &made_file);
343 if (call_label_ops_post)
344 /* If openat_report_new() failed in the above, propagate the error code, and ignore
345 * failures in label_ops_post(). */
346 RET_GATHER(r, label_ops_post(fd >= 0 ? fd : dir_fd, fd >= 0 ? NULL : fn, made_file));
347 }
348 if (r < 0)
349 goto fail;
350
351 r = take_fdopen_unlocked(&fd, "w", &f);
352 if (r < 0)
353 goto fail;
354
355 if (flags & WRITE_STRING_FILE_DISABLE_BUFFER)
356 setvbuf(f, NULL, _IONBF, 0);
357
358 r = write_string_stream_full(f, line, flags, ts);
359 if (r < 0)
360 goto fail;
361
362 return 0;
363
364 fail:
365 if (made_file)
366 (void) unlinkat(dir_fd, fn, 0);
367
368 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
369 return r;
370
371 f = safe_fclose(f);
372 fd = safe_close(fd);
373
374 /* OK, the operation failed, but let's see if the right contents in place already. If so, eat up the
375 * error. */
376 if (verify_file_at(dir_fd, fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) || (flags & WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE)) > 0)
377 return 0;
378
379 return r;
380 }
381
382 int write_string_filef(
383 const char *fn,
384 WriteStringFileFlags flags,
385 const char *format, ...) {
386
387 _cleanup_free_ char *p = NULL;
388 va_list ap;
389 int r;
390
391 va_start(ap, format);
392 r = vasprintf(&p, format, ap);
393 va_end(ap);
394
395 if (r < 0)
396 return -ENOMEM;
397
398 return write_string_file(fn, p, flags);
399 }
400
401 int write_base64_file_at(
402 int dir_fd,
403 const char *fn,
404 const struct iovec *data,
405 WriteStringFileFlags flags) {
406
407 _cleanup_free_ char *encoded = NULL;
408 ssize_t n;
409
410 n = base64mem_full(data ? data->iov_base : NULL, data ? data->iov_len : 0, 79, &encoded);
411 if (n < 0)
412 return n;
413
414 return write_string_file_at(dir_fd, fn, encoded, flags);
415 }
416
417 int read_one_line_file_at(int dir_fd, const char *filename, char **ret) {
418 _cleanup_fclose_ FILE *f = NULL;
419 int r;
420
421 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
422 assert(filename);
423 assert(ret);
424
425 r = fopen_unlocked_at(dir_fd, filename, "re", 0, &f);
426 if (r < 0)
427 return r;
428
429 return read_line(f, LONG_LINE_MAX, ret);
430 }
431
432 int verify_file_at(int dir_fd, const char *fn, const char *blob, bool accept_extra_nl) {
433 _cleanup_fclose_ FILE *f = NULL;
434 _cleanup_free_ char *buf = NULL;
435 size_t l, k;
436 int r;
437
438 assert(blob);
439
440 l = strlen(blob);
441
442 if (accept_extra_nl && endswith(blob, "\n"))
443 accept_extra_nl = false;
444
445 buf = malloc(l + accept_extra_nl + 1);
446 if (!buf)
447 return -ENOMEM;
448
449 r = fopen_unlocked_at(dir_fd, strempty(fn), "re", 0, &f);
450 if (r < 0)
451 return r;
452
453 /* We try to read one byte more than we need, so that we know whether we hit eof */
454 errno = 0;
455 k = fread(buf, 1, l + accept_extra_nl + 1, f);
456 if (ferror(f))
457 return errno_or_else(EIO);
458
459 if (k != l && k != l + accept_extra_nl)
460 return 0;
461 if (memcmp(buf, blob, l) != 0)
462 return 0;
463 if (k > l && buf[l] != '\n')
464 return 0;
465
466 return 1;
467 }
468
469 int read_virtual_file_at(
470 int dir_fd,
471 const char *filename,
472 size_t max_size,
473 char **ret_contents,
474 size_t *ret_size) {
475
476 _cleanup_free_ char *buf = NULL;
477 size_t n, size;
478 int n_retries;
479 bool truncated = false;
480
481 /* Virtual filesystems such as sysfs or procfs use kernfs, and kernfs can work with two sorts of
482 * virtual files. One sort uses "seq_file", and the results of the first read are buffered for the
483 * second read. The other sort uses "raw" reads which always go direct to the device. In the latter
484 * case, the content of the virtual file must be retrieved with a single read otherwise a second read
485 * might get the new value instead of finding EOF immediately. That's the reason why the usage of
486 * fread(3) is prohibited in this case as it always performs a second call to read(2) looking for
487 * EOF. See issue #13585.
488 *
489 * max_size specifies a limit on the bytes read. If max_size is SIZE_MAX, the full file is read. If
490 * the full file is too large to read, an error is returned. For other values of max_size, *partial
491 * contents* may be returned. (Though the read is still done using one syscall.) Returns 0 on
492 * partial success, 1 if untruncated contents were read.
493 *
494 * Rule: for kernfs files using "seq_file" → use regular read_full_file_at()
495 * for kernfs files using "raw" → use read_virtual_file_at()
496 */
497
498 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
499 assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX);
500
501 _cleanup_close_ int fd = -EBADF;
502 if (isempty(filename))
503 fd = fd_reopen(ASSERT_FD(dir_fd), O_RDONLY | O_NOCTTY | O_CLOEXEC);
504 else
505 fd = RET_NERRNO(openat(dir_fd, filename, O_RDONLY | O_NOCTTY | O_CLOEXEC));
506 if (fd < 0)
507 return fd;
508
509 /* Limit the number of attempts to read the number of bytes returned by fstat(). */
510 n_retries = 3;
511
512 for (;;) {
513 struct stat st;
514
515 if (fstat(fd, &st) < 0)
516 return -errno;
517
518 if (!S_ISREG(st.st_mode))
519 return -EBADF;
520
521 /* Be prepared for files from /proc which generally report a file size of 0. */
522 assert_cc(READ_VIRTUAL_BYTES_MAX < SSIZE_MAX);
523 if (st.st_size > 0 && n_retries > 1) {
524 /* Let's use the file size if we have more than 1 attempt left. On the last attempt
525 * we'll ignore the file size */
526
527 if (st.st_size > SSIZE_MAX) { /* Avoid overflow with 32-bit size_t and 64-bit off_t. */
528
529 if (max_size == SIZE_MAX)
530 return -EFBIG;
531
532 size = max_size;
533 } else {
534 size = MIN((size_t) st.st_size, max_size);
535
536 if (size > READ_VIRTUAL_BYTES_MAX)
537 return -EFBIG;
538 }
539
540 n_retries--;
541 } else if (n_retries > 1) {
542 /* Files in /proc are generally smaller than the page size so let's start with
543 * a page size buffer from malloc and only use the max buffer on the final try. */
544 size = MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX, max_size);
545 n_retries = 1;
546 } else {
547 size = MIN(READ_VIRTUAL_BYTES_MAX, max_size);
548 n_retries = 0;
549 }
550
551 buf = malloc(size + 1);
552 if (!buf)
553 return -ENOMEM;
554
555 /* Use a bigger allocation if we got it anyway, but not more than the limit. */
556 size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_VIRTUAL_BYTES_MAX);
557
558 for (;;) {
559 ssize_t k;
560
561 /* Read one more byte so we can detect whether the content of the
562 * file has already changed or the guessed size for files from /proc
563 * wasn't large enough . */
564 k = read(fd, buf, size + 1);
565 if (k >= 0) {
566 n = k;
567 break;
568 }
569
570 if (errno != EINTR)
571 return -errno;
572 }
573
574 /* Consider a short read as EOF */
575 if (n <= size)
576 break;
577
578 /* If a maximum size is specified and we already read more we know the file is larger, and
579 * can handle this as truncation case. Note that if the size of what we read equals the
580 * maximum size then this doesn't mean truncation, the file might or might not end on that
581 * byte. We need to rerun the loop in that case, with a larger buffer size, so that we read
582 * at least one more byte to be able to distinguish EOF from truncation. */
583 if (max_size != SIZE_MAX && n > max_size) {
584 n = size; /* Make sure we never use more than what we sized the buffer for (so that
585 * we have one free byte in it for the trailing NUL we add below). */
586 truncated = true;
587 break;
588 }
589
590 /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */
591 if (n_retries <= 0)
592 return -EFBIG;
593
594 /* Hmm... either we read too few bytes from /proc or less likely the content of the file
595 * might have been changed (and is now bigger) while we were processing, let's try again
596 * either with the new file size. */
597
598 if (lseek(fd, 0, SEEK_SET) < 0)
599 return -errno;
600
601 buf = mfree(buf);
602 }
603
604 if (ret_contents) {
605
606 /* Safety check: if the caller doesn't want to know the size of what we just read it will
607 * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
608 * operation as otherwise there'd be ambiguity about what we just read. */
609 if (!ret_size && memchr(buf, 0, n))
610 return -EBADMSG;
611
612 if (n < size) {
613 char *p;
614
615 /* Return rest of the buffer to libc */
616 p = realloc(buf, n + 1);
617 if (!p)
618 return -ENOMEM;
619 buf = p;
620 }
621
622 buf[n] = 0;
623 *ret_contents = TAKE_PTR(buf);
624 }
625
626 if (ret_size)
627 *ret_size = n;
628
629 return !truncated;
630 }
631
632 int read_full_stream_full(
633 FILE *f,
634 const char *filename,
635 uint64_t offset,
636 size_t size,
637 ReadFullFileFlags flags,
638 char **ret_contents,
639 size_t *ret_size) {
640
641 _cleanup_free_ char *buf = NULL;
642 size_t n, n_next = 0, l, expected_decoded_size = size;
643 int fd, r;
644
645 assert(f);
646 assert(ret_contents);
647 assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX));
648 assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER));
649
650 if (offset != UINT64_MAX && offset > LONG_MAX) /* fseek() can only deal with "long" offsets */
651 return -ERANGE;
652
653 if ((flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) != 0) {
654 if (size <= SIZE_MAX / READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY)
655 size *= READ_FULL_FILE_ENCODED_STRING_AMPLIFICATION_BOUNDARY;
656 else
657 size = SIZE_MAX;
658 }
659
660 fd = fileno(f);
661 if (fd >= 0) { /* If the FILE* object is backed by an fd (as opposed to memory or such, see
662 * fmemopen()), let's optimize our buffering */
663 struct stat st;
664
665 if (fstat(fd, &st) < 0)
666 return -errno;
667
668 if (S_ISREG(st.st_mode)) {
669
670 /* Try to start with the right file size if we shall read the file in full. Note
671 * that we increase the size to read here by one, so that the first read attempt
672 * already makes us notice the EOF. If the reported size of the file is zero, we
673 * avoid this logic however, since quite likely it might be a virtual file in procfs
674 * that all report a zero file size. */
675
676 if (st.st_size > 0 &&
677 (size == SIZE_MAX || FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER))) {
678
679 uint64_t rsize =
680 LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset);
681
682 if (rsize < SIZE_MAX) /* overflow check */
683 n_next = rsize + 1;
684 }
685
686 if (flags & READ_FULL_FILE_WARN_WORLD_READABLE)
687 (void) warn_file_is_world_accessible(filename, &st, NULL, 0);
688 }
689 }
690
691 /* If we don't know how much to read, figure it out now. If we shall read a part of the file, then
692 * allocate the requested size. If we shall load the full file start with LINE_MAX. Note that if
693 * READ_FULL_FILE_FAIL_WHEN_LARGER we consider the specified size a safety limit, and thus also start
694 * with LINE_MAX, under assumption the file is most likely much shorter. */
695 if (n_next == 0)
696 n_next = size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) ? size : LINE_MAX;
697
698 /* Never read more than we need to determine that our own limit is hit */
699 if (n_next > READ_FULL_BYTES_MAX)
700 n_next = READ_FULL_BYTES_MAX + 1;
701
702 if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0)
703 return -errno;
704
705 n = l = 0;
706 for (;;) {
707 char *t;
708 size_t k;
709
710 /* If we shall fail when reading overly large data, then read exactly one byte more than the
711 * specified size at max, since that'll tell us if there's anymore data beyond the limit. */
712 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && n_next > size)
713 n_next = size + 1;
714
715 if (flags & READ_FULL_FILE_SECURE) {
716 t = malloc(n_next + 1);
717 if (!t) {
718 r = -ENOMEM;
719 goto finalize;
720 }
721 memcpy_safe(t, buf, n);
722 explicit_bzero_safe(buf, n);
723 free(buf);
724 } else {
725 t = realloc(buf, n_next + 1);
726 if (!t)
727 return -ENOMEM;
728 }
729
730 buf = t;
731 /* Unless a size has been explicitly specified, try to read as much as fits into the memory
732 * we allocated (minus 1, to leave one byte for the safety NUL byte) */
733 n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next;
734
735 errno = 0;
736 k = fread(buf + l, 1, n - l, f);
737
738 assert(k <= n - l);
739 l += k;
740
741 if (ferror(f)) {
742 r = errno_or_else(EIO);
743 goto finalize;
744 }
745 if (feof(f))
746 break;
747
748 if (size != SIZE_MAX && !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER)) { /* If we got asked to read some specific size, we already sized the buffer right, hence leave */
749 assert(l == size);
750 break;
751 }
752
753 assert(k > 0); /* we can't have read zero bytes because that would have been EOF */
754
755 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) {
756 r = -E2BIG;
757 goto finalize;
758 }
759
760 if (n >= READ_FULL_BYTES_MAX) {
761 r = -E2BIG;
762 goto finalize;
763 }
764
765 n_next = MIN(n * 2, READ_FULL_BYTES_MAX);
766 }
767
768 if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) {
769 _cleanup_free_ void *decoded = NULL;
770 size_t decoded_size;
771
772 buf[l++] = 0;
773 if (flags & READ_FULL_FILE_UNBASE64)
774 r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
775 else
776 r = unhexmem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size);
777 if (r < 0)
778 goto finalize;
779
780 if (flags & READ_FULL_FILE_SECURE)
781 explicit_bzero_safe(buf, n);
782 free_and_replace(buf, decoded);
783 n = l = decoded_size;
784
785 if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > expected_decoded_size) {
786 r = -E2BIG;
787 goto finalize;
788 }
789 }
790
791 if (!ret_size) {
792 /* Safety check: if the caller doesn't want to know the size of what we just read it will rely on the
793 * trailing NUL byte. But if there's an embedded NUL byte, then we should refuse operation as otherwise
794 * there'd be ambiguity about what we just read. */
795
796 if (memchr(buf, 0, l)) {
797 r = -EBADMSG;
798 goto finalize;
799 }
800 }
801
802 buf[l] = 0;
803 *ret_contents = TAKE_PTR(buf);
804
805 if (ret_size)
806 *ret_size = l;
807
808 return 0;
809
810 finalize:
811 if (flags & READ_FULL_FILE_SECURE)
812 explicit_bzero_safe(buf, n);
813
814 return r;
815 }
816
817 int read_full_file_full(
818 int dir_fd,
819 const char *filename,
820 uint64_t offset,
821 size_t size,
822 ReadFullFileFlags flags,
823 const char *bind_name,
824 char **ret_contents,
825 size_t *ret_size) {
826
827 _cleanup_fclose_ FILE *f = NULL;
828 XfopenFlags xflags = XFOPEN_UNLOCKED;
829 int r;
830
831 assert(filename);
832 assert(ret_contents);
833
834 if (FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET) && /* If this is enabled, let's try to connect to it */
835 offset == UINT64_MAX) /* Seeking is not supported on AF_UNIX sockets */
836 xflags |= XFOPEN_SOCKET;
837
838 r = xfopenat_full(dir_fd, filename, "re", 0, xflags, bind_name, &f);
839 if (r < 0)
840 return r;
841
842 return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size);
843 }
844
845 int script_get_shebang_interpreter(const char *path, char **ret) {
846 _cleanup_fclose_ FILE *f = NULL;
847 int r;
848
849 assert(path);
850
851 f = fopen(path, "re");
852 if (!f)
853 return -errno;
854
855 char c;
856 r = safe_fgetc(f, &c);
857 if (r < 0)
858 return r;
859 if (r == 0)
860 return -EBADMSG;
861 if (c != '#')
862 return -EMEDIUMTYPE;
863 r = safe_fgetc(f, &c);
864 if (r < 0)
865 return r;
866 if (r == 0)
867 return -EBADMSG;
868 if (c != '!')
869 return -EMEDIUMTYPE;
870
871 _cleanup_free_ char *line = NULL;
872 r = read_line(f, LONG_LINE_MAX, &line);
873 if (r < 0)
874 return r;
875
876 _cleanup_free_ char *p = NULL;
877 const char *s = line;
878
879 r = extract_first_word(&s, &p, /* separators = */ NULL, /* flags = */ 0);
880 if (r < 0)
881 return r;
882 if (r == 0)
883 return -ENOEXEC;
884
885 if (ret)
886 *ret = TAKE_PTR(p);
887 return 0;
888 }
889
890 int get_proc_field(const char *path, const char *key, char **ret) {
891 _cleanup_fclose_ FILE *f = NULL;
892 int r;
893
894 /* Retrieve one field from a file like /proc/self/status. "key" matches the beginning of the line
895 * and should not include whitespace or the delimiter (':').
896 * Whitespaces after the ':' will be skipped. Only the first element is returned
897 * (i.e. for /proc/meminfo line "MemTotal: 1024 kB" -> return "1024"). */
898
899 assert(path);
900 assert(key);
901
902 r = fopen_unlocked(path, "re", &f);
903 if (r == -ENOENT && proc_mounted() == 0)
904 return -ENOSYS;
905 if (r < 0)
906 return r;
907
908 for (;;) {
909 _cleanup_free_ char *line = NULL;
910
911 r = read_line(f, LONG_LINE_MAX, &line);
912 if (r < 0)
913 return r;
914 if (r == 0)
915 return -ENODATA;
916
917 char *l = startswith(line, key);
918 if (l && *l == ':') {
919 if (ret) {
920 char *s = strdupcspn(skip_leading_chars(l + 1, " \t"), WHITESPACE);
921 if (!s)
922 return -ENOMEM;
923
924 *ret = s;
925 }
926
927 return 0;
928 }
929 }
930 }
931
932 DIR* xopendirat(int dir_fd, const char *name, int flags) {
933 _cleanup_close_ int fd = -EBADF;
934
935 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
936 assert(name);
937 assert(!(flags & (O_CREAT|O_TMPFILE)));
938
939 if (dir_fd == AT_FDCWD && flags == 0)
940 return opendir(name);
941
942 fd = openat(dir_fd, name, O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
943 if (fd < 0)
944 return NULL;
945
946 return take_fdopendir(&fd);
947 }
948
949 int fopen_mode_to_flags(const char *mode) {
950 const char *p;
951 int flags;
952
953 assert(mode);
954
955 if ((p = startswith(mode, "r+")))
956 flags = O_RDWR;
957 else if ((p = startswith(mode, "r")))
958 flags = O_RDONLY;
959 else if ((p = startswith(mode, "w+")))
960 flags = O_RDWR|O_CREAT|O_TRUNC;
961 else if ((p = startswith(mode, "w")))
962 flags = O_WRONLY|O_CREAT|O_TRUNC;
963 else if ((p = startswith(mode, "a+")))
964 flags = O_RDWR|O_CREAT|O_APPEND;
965 else if ((p = startswith(mode, "a")))
966 flags = O_WRONLY|O_CREAT|O_APPEND;
967 else
968 return -EINVAL;
969
970 for (; *p != 0; p++) {
971
972 switch (*p) {
973
974 case 'e':
975 flags |= O_CLOEXEC;
976 break;
977
978 case 'x':
979 flags |= O_EXCL;
980 break;
981
982 case 'm':
983 /* ignore this here, fdopen() might care later though */
984 break;
985
986 case 'c': /* not sure what to do about this one */
987 default:
988 return -EINVAL;
989 }
990 }
991
992 return flags;
993 }
994
995 static int xfopenat_regular(int dir_fd, const char *path, const char *mode, int open_flags, FILE **ret) {
996 FILE *f;
997
998 /* A combination of fopen() with openat() */
999
1000 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1001 assert(path);
1002 assert(mode);
1003 assert(ret);
1004
1005 if (dir_fd == AT_FDCWD && open_flags == 0)
1006 f = fopen(path, mode);
1007 else {
1008 _cleanup_close_ int fd = -EBADF;
1009 int mode_flags;
1010
1011 mode_flags = fopen_mode_to_flags(mode);
1012 if (mode_flags < 0)
1013 return mode_flags;
1014
1015 fd = openat(dir_fd, path, mode_flags | open_flags);
1016 if (fd < 0)
1017 return -errno;
1018
1019 f = take_fdopen(&fd, mode);
1020 }
1021 if (!f)
1022 return -errno;
1023
1024 *ret = f;
1025 return 0;
1026 }
1027
1028 static int xfopenat_unix_socket(int dir_fd, const char *path, const char *bind_name, FILE **ret) {
1029 _cleanup_close_ int sk = -EBADF;
1030 FILE *f;
1031 int r;
1032
1033 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1034 assert(path);
1035 assert(ret);
1036
1037 sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
1038 if (sk < 0)
1039 return -errno;
1040
1041 if (bind_name) {
1042 /* If the caller specified a socket name to bind to, do so before connecting. This is
1043 * useful to communicate some minor, short meta-information token from the client to
1044 * the server. */
1045 union sockaddr_union bsa;
1046
1047 r = sockaddr_un_set_path(&bsa.un, bind_name);
1048 if (r < 0)
1049 return r;
1050
1051 if (bind(sk, &bsa.sa, r) < 0)
1052 return -errno;
1053 }
1054
1055 r = connect_unix_path(sk, dir_fd, path);
1056 if (r < 0)
1057 return r;
1058
1059 if (shutdown(sk, SHUT_WR) < 0)
1060 return -errno;
1061
1062 f = take_fdopen(&sk, "r");
1063 if (!f)
1064 return -errno;
1065
1066 *ret = f;
1067 return 0;
1068 }
1069
1070 int xfopenat_full(
1071 int dir_fd,
1072 const char *path,
1073 const char *mode,
1074 int open_flags,
1075 XfopenFlags flags,
1076 const char *bind_name,
1077 FILE **ret) {
1078
1079 FILE *f = NULL; /* avoid false maybe-uninitialized warning */
1080 int r;
1081
1082 assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
1083 assert(path);
1084 assert(mode);
1085 assert(ret);
1086
1087 r = xfopenat_regular(dir_fd, path, mode, open_flags, &f);
1088 if (r == -ENXIO && FLAGS_SET(flags, XFOPEN_SOCKET)) {
1089 /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */
1090 r = xfopenat_unix_socket(dir_fd, path, bind_name, &f);
1091 if (IN_SET(r, -ENOTSOCK, -EINVAL))
1092 return -ENXIO; /* propagate original error if this is not a socket after all */
1093 }
1094 if (r < 0)
1095 return r;
1096
1097 if (FLAGS_SET(flags, XFOPEN_UNLOCKED))
1098 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1099
1100 *ret = f;
1101 return 0;
1102 }
1103
1104 int fdopen_independent(int fd, const char *mode, FILE **ret) {
1105 _cleanup_close_ int copy_fd = -EBADF;
1106 _cleanup_fclose_ FILE *f = NULL;
1107 int mode_flags;
1108
1109 assert(fd >= 0);
1110 assert(mode);
1111 assert(ret);
1112
1113 /* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
1114 * returns a FILE* for it */
1115
1116 mode_flags = fopen_mode_to_flags(mode);
1117 if (mode_flags < 0)
1118 return mode_flags;
1119
1120 /* Flags returned by fopen_mode_to_flags might contain O_CREAT, but it doesn't make sense for fd_reopen
1121 * since we're working on an existing fd anyway. Let's drop it here to avoid triggering assertion. */
1122 copy_fd = fd_reopen(fd, mode_flags & ~O_CREAT);
1123 if (copy_fd < 0)
1124 return copy_fd;
1125
1126 f = take_fdopen(&copy_fd, mode);
1127 if (!f)
1128 return -errno;
1129
1130 *ret = TAKE_PTR(f);
1131 return 0;
1132 }
1133
1134 static int search_and_open_internal(
1135 const char *path,
1136 int mode, /* if ret_fd is NULL this is an [FRWX]_OK mode for access(), otherwise an open mode for open() */
1137 const char *root,
1138 char **search,
1139 int *ret_fd,
1140 char **ret_path) {
1141
1142 int r;
1143
1144 assert(!ret_fd || !FLAGS_SET(mode, O_CREAT)); /* We don't support O_CREAT for this */
1145 assert(path);
1146
1147 if (path_is_absolute(path)) {
1148 _cleanup_close_ int fd = -EBADF;
1149
1150 if (ret_fd)
1151 /* We only specify 0777 here to appease static analyzers, it's never used since we
1152 * don't support O_CREAT here */
1153 r = fd = RET_NERRNO(open(path, mode, 0777));
1154 else
1155 r = RET_NERRNO(access(path, mode));
1156 if (r < 0)
1157 return r;
1158
1159 if (ret_path) {
1160 r = path_simplify_alloc(path, ret_path);
1161 if (r < 0)
1162 return r;
1163 }
1164
1165 if (ret_fd)
1166 *ret_fd = TAKE_FD(fd);
1167
1168 return 0;
1169 }
1170
1171 if (!path_strv_resolve_uniq(search, root))
1172 return -ENOMEM;
1173
1174 STRV_FOREACH(i, search) {
1175 _cleanup_close_ int fd = -EBADF;
1176 _cleanup_free_ char *p = NULL;
1177
1178 p = path_join(root, *i, path);
1179 if (!p)
1180 return -ENOMEM;
1181
1182 if (ret_fd)
1183 /* as above, 0777 is static analyzer appeasement */
1184 r = fd = RET_NERRNO(open(p, mode, 0777));
1185 else
1186 r = RET_NERRNO(access(p, F_OK));
1187 if (r >= 0) {
1188 if (ret_path)
1189 *ret_path = path_simplify(TAKE_PTR(p));
1190
1191 if (ret_fd)
1192 *ret_fd = TAKE_FD(fd);
1193
1194 return 0;
1195 }
1196 if (r != -ENOENT)
1197 return r;
1198 }
1199
1200 return -ENOENT;
1201 }
1202
1203 int search_and_open(
1204 const char *path,
1205 int mode,
1206 const char *root,
1207 char **search,
1208 int *ret_fd,
1209 char **ret_path) {
1210
1211 _cleanup_strv_free_ char **copy = NULL;
1212
1213 assert(path);
1214
1215 copy = strv_copy((char**) search);
1216 if (!copy)
1217 return -ENOMEM;
1218
1219 return search_and_open_internal(path, mode, root, copy, ret_fd, ret_path);
1220 }
1221
1222 static int search_and_fopen_internal(
1223 const char *path,
1224 const char *mode,
1225 const char *root,
1226 char **search,
1227 FILE **ret_file,
1228 char **ret_path) {
1229
1230 _cleanup_free_ char *found_path = NULL;
1231 _cleanup_close_ int fd = -EBADF;
1232 int r;
1233
1234 assert(path);
1235 assert(mode || !ret_file);
1236
1237 r = search_and_open(
1238 path,
1239 mode ? fopen_mode_to_flags(mode) : 0,
1240 root,
1241 search,
1242 ret_file ? &fd : NULL,
1243 ret_path ? &found_path : NULL);
1244 if (r < 0)
1245 return r;
1246
1247 if (ret_file) {
1248 FILE *f = take_fdopen(&fd, mode);
1249 if (!f)
1250 return -errno;
1251
1252 *ret_file = f;
1253 }
1254
1255 if (ret_path)
1256 *ret_path = TAKE_PTR(found_path);
1257
1258 return 0;
1259 }
1260
1261 int search_and_fopen(
1262 const char *path,
1263 const char *mode,
1264 const char *root,
1265 const char **search,
1266 FILE **ret_file,
1267 char **ret_path) {
1268
1269 _cleanup_strv_free_ char **copy = NULL;
1270
1271 assert(path);
1272 assert(mode || !ret_file);
1273
1274 copy = strv_copy((char**) search);
1275 if (!copy)
1276 return -ENOMEM;
1277
1278 return search_and_fopen_internal(path, mode, root, copy, ret_file, ret_path);
1279 }
1280
1281 int search_and_fopen_nulstr(
1282 const char *path,
1283 const char *mode,
1284 const char *root,
1285 const char *search,
1286 FILE **ret_file,
1287 char **ret_path) {
1288
1289 _cleanup_strv_free_ char **l = NULL;
1290
1291 assert(path);
1292 assert(mode || !ret_file);
1293
1294 l = strv_split_nulstr(search);
1295 if (!l)
1296 return -ENOMEM;
1297
1298 return search_and_fopen_internal(path, mode, root, l, ret_file, ret_path);
1299 }
1300
1301 int fflush_and_check(FILE *f) {
1302 assert(f);
1303
1304 errno = 0;
1305 fflush(f);
1306
1307 if (ferror(f))
1308 return errno_or_else(EIO);
1309
1310 return 0;
1311 }
1312
1313 int fflush_sync_and_check(FILE *f) {
1314 int r, fd;
1315
1316 assert(f);
1317
1318 r = fflush_and_check(f);
1319 if (r < 0)
1320 return r;
1321
1322 /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and
1323 * assume that in that case we need no explicit syncing */
1324 fd = fileno(f);
1325 if (fd < 0)
1326 return 0;
1327
1328 r = fsync_full(fd);
1329 if (r < 0)
1330 return r;
1331
1332 return 0;
1333 }
1334
1335 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1336 char ln[DECIMAL_STR_MAX(n)+2];
1337
1338 /* Creates a "timestamp" file, that contains nothing but a
1339 * usec_t timestamp, formatted in ASCII. */
1340
1341 if (!timestamp_is_set(n))
1342 return -ERANGE;
1343
1344 xsprintf(ln, USEC_FMT "\n", n);
1345
1346 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1347 }
1348
1349 int read_timestamp_file(const char *fn, usec_t *ret) {
1350 _cleanup_free_ char *ln = NULL;
1351 uint64_t t;
1352 int r;
1353
1354 r = read_one_line_file(fn, &ln);
1355 if (r < 0)
1356 return r;
1357
1358 r = safe_atou64(ln, &t);
1359 if (r < 0)
1360 return r;
1361
1362 if (!timestamp_is_set(t))
1363 return -ERANGE;
1364
1365 *ret = (usec_t) t;
1366 return 0;
1367 }
1368
1369 int fputs_with_separator(FILE *f, const char *s, const char *separator, bool *space) {
1370 assert(s);
1371 assert(space);
1372
1373 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator.
1374 * The *space parameter when specified shall initially point to a boolean variable initialized
1375 * to false. It is set to true after the first invocation. This call is supposed to be use in loops,
1376 * where a separator shall be inserted between each element, but not before the first one. */
1377
1378 if (!f)
1379 f = stdout;
1380
1381 if (!separator)
1382 separator = " ";
1383
1384 if (*space)
1385 if (fputs(separator, f) < 0)
1386 return -EIO;
1387
1388 *space = true;
1389
1390 if (fputs(s, f) < 0)
1391 return -EIO;
1392
1393 return 0;
1394 }
1395
1396 int fputs_with_newline(FILE *f, const char *s) {
1397
1398 /* This is like fputs() but outputs a trailing newline char, but only if the string isn't empty
1399 * and doesn't end in a newline already. Returns 0 in case we didn't append a newline, > 0 otherwise. */
1400
1401 if (isempty(s))
1402 return 0;
1403
1404 if (!f)
1405 f = stdout;
1406
1407 if (fputs(s, f) < 0)
1408 return -EIO;
1409
1410 if (endswith(s, "\n"))
1411 return 0;
1412
1413 if (fputc('\n', f) < 0)
1414 return -EIO;
1415
1416 return 1;
1417 }
1418
1419 /* A bitmask of the EOL markers we know */
1420 typedef enum EndOfLineMarker {
1421 EOL_NONE = 0,
1422 EOL_ZERO = 1 << 0, /* \0 (aka NUL) */
1423 EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */
1424 EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */
1425 } EndOfLineMarker;
1426
1427 static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) {
1428
1429 if (!FLAGS_SET(flags, READ_LINE_ONLY_NUL)) {
1430 if (c == '\n')
1431 return EOL_TEN;
1432 if (c == '\r')
1433 return EOL_THIRTEEN;
1434 }
1435
1436 if (c == '\0')
1437 return EOL_ZERO;
1438
1439 return EOL_NONE;
1440 }
1441
1442 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL);
1443
1444 int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) {
1445 _cleanup_free_ char *buffer = NULL;
1446 size_t n = 0, count = 0;
1447 int r;
1448
1449 assert(f);
1450
1451 /* Something like a bounded version of getline().
1452 *
1453 * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these
1454 * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line
1455 * endings:
1456 *
1457 * • \n (UNIX)
1458 * • \r (old MacOS)
1459 * • \0 (C strings)
1460 * • \n\0
1461 * • \r\0
1462 * • \r\n (Windows)
1463 * • \n\r
1464 * • \r\n\0
1465 * • \n\r\0
1466 *
1467 * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from
1468 * the number of characters in the returned string). When EOF is hit, 0 is returned.
1469 *
1470 * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding
1471 * delimiters. If the limit is hit we fail and return -ENOBUFS.
1472 *
1473 * If a line shall be skipped ret may be initialized as NULL. */
1474
1475 if (ret) {
1476 if (!GREEDY_REALLOC(buffer, 1))
1477 return -ENOMEM;
1478 }
1479
1480 {
1481 _unused_ _cleanup_(funlockfilep) FILE *flocked = f;
1482 EndOfLineMarker previous_eol = EOL_NONE;
1483 flockfile(f);
1484
1485 for (;;) {
1486 EndOfLineMarker eol;
1487 char c;
1488
1489 if (n >= limit)
1490 return -ENOBUFS;
1491
1492 if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */
1493 return -ENOBUFS;
1494
1495 r = safe_fgetc(f, &c);
1496 if (r < 0)
1497 return r;
1498 if (r == 0) /* EOF is definitely EOL */
1499 break;
1500
1501 eol = categorize_eol(c, flags);
1502
1503 if (FLAGS_SET(previous_eol, EOL_ZERO) ||
1504 (eol == EOL_NONE && previous_eol != EOL_NONE) ||
1505 (eol != EOL_NONE && (previous_eol & eol) != 0)) {
1506 /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of
1507 * EOL marker has been seen right before? In either of these three cases we are
1508 * done. But first, let's put this character back in the queue. (Note that we have to
1509 * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we
1510 * are on an architecture where 'char' equals 'signed char' we need to ensure we don't
1511 * pass a negative value here. That said, to complicate things further ungetc() is
1512 * actually happy with most negative characters and implicitly casts them back to
1513 * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a
1514 * godawful API!) */
1515 assert_se(ungetc((unsigned char) c, f) != EOF);
1516 break;
1517 }
1518
1519 count++;
1520
1521 if (eol != EOL_NONE) {
1522 /* If we are on a tty, we can't shouldn't wait for more input, because that
1523 * generally means waiting for the user, interactively. In the case of a TTY
1524 * we expect only \n as the single EOL marker, so we are in the lucky
1525 * position that there is no need to wait. We check this condition last, to
1526 * avoid isatty() check if not necessary. */
1527
1528 if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) {
1529 int fd;
1530
1531 fd = fileno(f);
1532 if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully,
1533 * and don't call isatty() on an invalid fd */
1534 flags |= READ_LINE_NOT_A_TTY;
1535 else
1536 flags |= isatty_safe(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY;
1537 }
1538 if (FLAGS_SET(flags, READ_LINE_IS_A_TTY))
1539 break;
1540 }
1541
1542 if (eol != EOL_NONE) {
1543 previous_eol |= eol;
1544 continue;
1545 }
1546
1547 if (ret) {
1548 if (!GREEDY_REALLOC(buffer, n + 2))
1549 return -ENOMEM;
1550
1551 buffer[n] = c;
1552 }
1553
1554 n++;
1555 }
1556 }
1557
1558 if (ret) {
1559 buffer[n] = 0;
1560
1561 *ret = TAKE_PTR(buffer);
1562 }
1563
1564 return (int) count;
1565 }
1566
1567 int read_stripped_line(FILE *f, size_t limit, char **ret) {
1568 _cleanup_free_ char *s = NULL;
1569 int r, k;
1570
1571 assert(f);
1572
1573 r = read_line(f, limit, ret ? &s : NULL);
1574 if (r < 0)
1575 return r;
1576
1577 if (ret) {
1578 const char *p = strstrip(s);
1579 if (p == s)
1580 *ret = TAKE_PTR(s);
1581 else {
1582 k = strdup_to(ret, p);
1583 if (k < 0)
1584 return k;
1585 }
1586 }
1587
1588 return r > 0; /* Return 1 if something was read. */
1589 }
1590
1591 int safe_fgetc(FILE *f, char *ret) {
1592 int k;
1593
1594 assert(f);
1595
1596 /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and
1597 * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc()
1598 * has. */
1599
1600 errno = 0;
1601 k = fgetc(f);
1602 if (k == EOF) {
1603 if (ferror(f))
1604 return errno_or_else(EIO);
1605
1606 if (ret)
1607 *ret = 0;
1608
1609 return 0;
1610 }
1611
1612 if (ret)
1613 *ret = k;
1614
1615 return 1;
1616 }
1617
1618 int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) {
1619 struct stat _st;
1620
1621 if (!filename)
1622 return 0;
1623
1624 if (!st) {
1625 if (stat(filename, &_st) < 0)
1626 return -errno;
1627 st = &_st;
1628 }
1629
1630 if ((st->st_mode & S_IRWXO) == 0)
1631 return 0;
1632
1633 if (unit)
1634 log_syntax(unit, LOG_WARNING, filename, line, 0,
1635 "%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1636 filename, st->st_mode & 07777);
1637 else
1638 log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.",
1639 filename, st->st_mode & 07777);
1640 return 0;
1641 }