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