]>
Commit | Line | Data |
---|---|---|
a032b68d | 1 | /* SPDX-License-Identifier: LGPL-2.1-or-later */ |
663996b3 | 2 | |
6e866b33 | 3 | #include <ctype.h> |
4c89c718 MP |
4 | #include <errno.h> |
5 | #include <fcntl.h> | |
6 | #include <limits.h> | |
7 | #include <stdarg.h> | |
8 | #include <stdint.h> | |
52ad194e | 9 | #include <stdio_ext.h> |
4c89c718 | 10 | #include <stdlib.h> |
4c89c718 MP |
11 | #include <sys/stat.h> |
12 | #include <sys/types.h> | |
663996b3 | 13 | #include <unistd.h> |
f47781d8 | 14 | |
db2df898 | 15 | #include "alloc-util.h" |
ea0999c9 | 16 | #include "chase-symlinks.h" |
db2df898 | 17 | #include "fd-util.h" |
f47781d8 | 18 | #include "fileio.h" |
db2df898 | 19 | #include "fs-util.h" |
bb4f798a | 20 | #include "hexdecoct.h" |
4c89c718 MP |
21 | #include "log.h" |
22 | #include "macro.h" | |
f2dec872 | 23 | #include "mkdir.h" |
db2df898 MP |
24 | #include "parse-util.h" |
25 | #include "path-util.h" | |
a10f5d05 | 26 | #include "socket-util.h" |
db2df898 MP |
27 | #include "stdio-util.h" |
28 | #include "string-util.h" | |
ea0999c9 | 29 | #include "sync-util.h" |
6e866b33 | 30 | #include "tmpfile-util.h" |
663996b3 | 31 | |
8b3d4ff0 MB |
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 | ||
ce5f39bd MB |
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) | |
8a584da2 | 45 | |
f2dec872 BR |
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 | ||
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 | ||
a10f5d05 | 72 | int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) { |
5b5a102a | 73 | int r; |
a10f5d05 MB |
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 | ||
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 | ||
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 | ||
f2dec872 BR |
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 | ||
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 | ||
f5e65279 MB |
130 | int write_string_stream_ts( |
131 | FILE *f, | |
132 | const char *line, | |
133 | WriteStringFileFlags flags, | |
a032b68d | 134 | const struct timespec *ts) { |
5fd56512 | 135 | |
1d42b86d | 136 | bool needs_nl; |
8b3d4ff0 | 137 | int r, fd = -1; |
1d42b86d | 138 | |
e842803a MB |
139 | assert(f); |
140 | assert(line); | |
141 | ||
1d42b86d MB |
142 | if (ferror(f)) |
143 | return -EIO; | |
144 | ||
d0648cfe MB |
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 | ||
ea0999c9 MB |
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 | ||
1d42b86d MB |
177 | needs_nl = !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) && !endswith(line, "\n"); |
178 | ||
179 | if (needs_nl && (flags & WRITE_STRING_FILE_DISABLE_BUFFER)) { | |
8b3d4ff0 MB |
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 */ | |
1d42b86d MB |
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; | |
663996b3 | 193 | |
b012e921 MB |
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 | ||
81c58355 | 201 | if (ts) { |
a032b68d | 202 | const struct timespec twice[2] = {*ts, *ts}; |
81c58355 | 203 | |
8b3d4ff0 | 204 | assert(fd >= 0); |
d0648cfe | 205 | if (futimens(fd, twice) < 0) |
81c58355 MB |
206 | return -errno; |
207 | } | |
208 | ||
b012e921 | 209 | return 0; |
663996b3 MS |
210 | } |
211 | ||
f5e65279 MB |
212 | static int write_string_file_atomic( |
213 | const char *fn, | |
214 | const char *line, | |
215 | WriteStringFileFlags flags, | |
a032b68d | 216 | const struct timespec *ts) { |
f5e65279 | 217 | |
663996b3 MS |
218 | _cleanup_fclose_ FILE *f = NULL; |
219 | _cleanup_free_ char *p = NULL; | |
220 | int r; | |
221 | ||
222 | assert(fn); | |
223 | assert(line); | |
224 | ||
46cdbd49 BR |
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 | ||
663996b3 MS |
228 | r = fopen_temporary(fn, &f, &p); |
229 | if (r < 0) | |
230 | return r; | |
231 | ||
f5e65279 MB |
232 | r = write_string_stream_ts(f, line, flags, ts); |
233 | if (r < 0) | |
234 | goto fail; | |
235 | ||
46cdbd49 BR |
236 | r = fchmod_umask(fileno(f), FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0600) ? 0600 : 0644); |
237 | if (r < 0) | |
238 | goto fail; | |
239 | ||
f5e65279 MB |
240 | if (rename(p, fn) < 0) { |
241 | r = -errno; | |
242 | goto fail; | |
663996b3 MS |
243 | } |
244 | ||
a10f5d05 MB |
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 | ||
f5e65279 | 252 | return 0; |
663996b3 | 253 | |
f5e65279 MB |
254 | fail: |
255 | (void) unlink(p); | |
663996b3 MS |
256 | return r; |
257 | } | |
258 | ||
f5e65279 MB |
259 | int write_string_file_ts( |
260 | const char *fn, | |
261 | const char *line, | |
262 | WriteStringFileFlags flags, | |
a032b68d | 263 | const struct timespec *ts) { |
f5e65279 | 264 | |
7035cd9e | 265 | _cleanup_fclose_ FILE *f = NULL; |
46cdbd49 | 266 | int q, r, fd; |
7035cd9e MP |
267 | |
268 | assert(fn); | |
269 | assert(line); | |
270 | ||
f5e65279 MB |
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 | ||
f2dec872 BR |
274 | if (flags & WRITE_STRING_FILE_MKDIR_0755) { |
275 | r = mkdir_parents(fn, 0755); | |
276 | if (r < 0) | |
277 | return r; | |
278 | } | |
279 | ||
7035cd9e MP |
280 | if (flags & WRITE_STRING_FILE_ATOMIC) { |
281 | assert(flags & WRITE_STRING_FILE_CREATE); | |
282 | ||
f5e65279 | 283 | r = write_string_file_atomic(fn, line, flags, ts); |
db2df898 MP |
284 | if (r < 0) |
285 | goto fail; | |
286 | ||
287 | return r; | |
81c58355 | 288 | } else |
52ad194e | 289 | assert(!ts); |
7035cd9e | 290 | |
46cdbd49 | 291 | /* We manually build our own version of fopen(..., "we") that works without O_CREAT and with O_NOFOLLOW if needed. */ |
ea0999c9 | 292 | fd = open(fn, O_CLOEXEC|O_NOCTTY | |
46cdbd49 | 293 | (FLAGS_SET(flags, WRITE_STRING_FILE_NOFOLLOW) ? O_NOFOLLOW : 0) | |
a032b68d | 294 | (FLAGS_SET(flags, WRITE_STRING_FILE_CREATE) ? O_CREAT : 0) | |
ea0999c9 MB |
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), | |
46cdbd49 BR |
297 | (FLAGS_SET(flags, WRITE_STRING_FILE_MODE_0600) ? 0600 : 0666)); |
298 | if (fd < 0) { | |
299 | r = -errno; | |
300 | goto fail; | |
301 | } | |
7035cd9e | 302 | |
46cdbd49 BR |
303 | r = fdopen_unlocked(fd, "w", &f); |
304 | if (r < 0) { | |
305 | safe_close(fd); | |
306 | goto fail; | |
7035cd9e MP |
307 | } |
308 | ||
52ad194e MB |
309 | if (flags & WRITE_STRING_FILE_DISABLE_BUFFER) |
310 | setvbuf(f, NULL, _IONBF, 0); | |
311 | ||
f5e65279 | 312 | r = write_string_stream_ts(f, line, flags, ts); |
db2df898 MP |
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 | ||
8b3d4ff0 | 327 | q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE) || (flags & WRITE_STRING_FILE_VERIFY_IGNORE_NEWLINE)); |
db2df898 MP |
328 | if (q <= 0) |
329 | return r; | |
330 | ||
331 | return 0; | |
7035cd9e MP |
332 | } |
333 | ||
b012e921 MB |
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 | ||
663996b3 MS |
353 | int read_one_line_file(const char *fn, char **line) { |
354 | _cleanup_fclose_ FILE *f = NULL; | |
f2dec872 | 355 | int r; |
663996b3 MS |
356 | |
357 | assert(fn); | |
358 | assert(line); | |
359 | ||
f2dec872 BR |
360 | r = fopen_unlocked(fn, "re", &f); |
361 | if (r < 0) | |
362 | return r; | |
52ad194e | 363 | |
bb4f798a | 364 | return read_line(f, LONG_LINE_MAX, line); |
663996b3 MS |
365 | } |
366 | ||
db2df898 MP |
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; | |
f2dec872 | 371 | int r; |
fb183854 | 372 | |
db2df898 MP |
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; | |
fb183854 | 384 | |
f2dec872 BR |
385 | r = fopen_unlocked(fn, "re", &f); |
386 | if (r < 0) | |
387 | return r; | |
52ad194e | 388 | |
db2df898 MP |
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)) | |
f2dec872 | 393 | return errno_or_else(EIO); |
db2df898 MP |
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; | |
fb183854 MP |
403 | } |
404 | ||
ea0999c9 | 405 | int read_virtual_file_fd(int fd, size_t max_size, char **ret_contents, size_t *ret_size) { |
e1f67bc7 | 406 | _cleanup_free_ char *buf = NULL; |
e1f67bc7 MB |
407 | size_t n, size; |
408 | int n_retries; | |
8b3d4ff0 MB |
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. */ | |
e1f67bc7 | 423 | |
ea0999c9 | 424 | assert(fd >= 0); |
8b3d4ff0 MB |
425 | assert(max_size <= READ_VIRTUAL_BYTES_MAX || max_size == SIZE_MAX); |
426 | ||
e1f67bc7 MB |
427 | /* Limit the number of attempts to read the number of bytes returned by fstat(). */ |
428 | n_retries = 3; | |
429 | ||
430 | for (;;) { | |
8b3d4ff0 MB |
431 | struct stat st; |
432 | ||
e1f67bc7 MB |
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. */ | |
8b3d4ff0 MB |
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 | } | |
3a6ce677 | 457 | |
e1f67bc7 | 458 | n_retries--; |
ce5f39bd | 459 | } else if (n_retries > 1) { |
ea0999c9 MB |
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. */ | |
ce5f39bd MB |
462 | size = MIN3(page_size() - 1, READ_VIRTUAL_BYTES_MAX, max_size); |
463 | n_retries = 1; | |
3a6ce677 | 464 | } else { |
8b3d4ff0 | 465 | size = MIN(READ_VIRTUAL_BYTES_MAX, max_size); |
3a6ce677 BR |
466 | n_retries = 0; |
467 | } | |
e1f67bc7 | 468 | |
3a6ce677 BR |
469 | buf = malloc(size + 1); |
470 | if (!buf) | |
e1f67bc7 | 471 | return -ENOMEM; |
8b3d4ff0 | 472 | |
3a6ce677 | 473 | /* Use a bigger allocation if we got it anyway, but not more than the limit. */ |
8b3d4ff0 | 474 | size = MIN3(MALLOC_SIZEOF_SAFE(buf) - 1, max_size, READ_VIRTUAL_BYTES_MAX); |
e1f67bc7 MB |
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 | ||
20a6e51f | 488 | if (errno != EINTR) |
e1f67bc7 MB |
489 | return -errno; |
490 | } | |
491 | ||
492 | /* Consider a short read as EOF */ | |
493 | if (n <= size) | |
494 | break; | |
495 | ||
ce5f39bd MB |
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).*/ | |
8b3d4ff0 MB |
504 | truncated = true; |
505 | break; | |
506 | } | |
e1f67bc7 | 507 | |
8b3d4ff0 | 508 | /* We have no further attempts left? Then the file is apparently larger than our limits. Give up. */ |
3a6ce677 | 509 | if (n_retries <= 0) |
8b3d4ff0 MB |
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. */ | |
3a6ce677 | 515 | |
e1f67bc7 MB |
516 | if (lseek(fd, 0, SEEK_SET) < 0) |
517 | return -errno; | |
3a6ce677 BR |
518 | |
519 | buf = mfree(buf); | |
e1f67bc7 MB |
520 | } |
521 | ||
8b3d4ff0 | 522 | if (ret_contents) { |
3a6ce677 | 523 | |
3a6ce677 BR |
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. */ | |
8b3d4ff0 MB |
527 | if (!ret_size && memchr(buf, 0, n)) |
528 | return -EBADMSG; | |
e1f67bc7 | 529 | |
8b3d4ff0 MB |
530 | if (n < size) { |
531 | char *p; | |
e1f67bc7 | 532 | |
8b3d4ff0 MB |
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; | |
e1f67bc7 MB |
548 | } |
549 | ||
ea0999c9 MB |
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 | ||
bb4f798a | 575 | int read_full_stream_full( |
6e866b33 | 576 | FILE *f, |
bb4f798a | 577 | const char *filename, |
3a6ce677 BR |
578 | uint64_t offset, |
579 | size_t size, | |
bb4f798a | 580 | ReadFullFileFlags flags, |
6e866b33 MB |
581 | char **ret_contents, |
582 | size_t *ret_size) { | |
583 | ||
663996b3 | 584 | _cleanup_free_ char *buf = NULL; |
ea0999c9 | 585 | size_t n, n_next = 0, l; |
bb4f798a | 586 | int fd, r; |
663996b3 | 587 | |
e842803a | 588 | assert(f); |
6e866b33 | 589 | assert(ret_contents); |
f2dec872 | 590 | assert(!FLAGS_SET(flags, READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)); |
ea0999c9 | 591 | assert(size != SIZE_MAX || !FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER)); |
663996b3 | 592 | |
ea0999c9 | 593 | if (offset != UINT64_MAX && offset > LONG_MAX) /* fseek() can only deal with "long" offsets */ |
3a6ce677 BR |
594 | return -ERANGE; |
595 | ||
b012e921 | 596 | fd = fileno(f); |
3a6ce677 BR |
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; | |
e842803a | 600 | |
bb4f798a | 601 | if (fstat(fd, &st) < 0) |
b012e921 MB |
602 | return -errno; |
603 | ||
604 | if (S_ISREG(st.st_mode)) { | |
ea0999c9 MB |
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 | ||
3a6ce677 BR |
615 | uint64_t rsize = |
616 | LESS_BY((uint64_t) st.st_size, offset == UINT64_MAX ? 0 : offset); | |
617 | ||
ea0999c9 | 618 | if (rsize < SIZE_MAX) /* overflow check */ |
3a6ce677 BR |
619 | n_next = rsize + 1; |
620 | } | |
bb4f798a | 621 | |
a10f5d05 | 622 | if (flags & READ_FULL_FILE_WARN_WORLD_READABLE) |
bb4f798a | 623 | (void) warn_file_is_world_accessible(filename, &st, NULL, 0); |
b012e921 | 624 | } |
e842803a | 625 | } |
663996b3 | 626 | |
ea0999c9 MB |
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 | ||
3a6ce677 BR |
638 | if (offset != UINT64_MAX && fseek(f, offset, SEEK_SET) < 0) |
639 | return -errno; | |
640 | ||
bb4f798a | 641 | n = l = 0; |
663996b3 MS |
642 | for (;;) { |
643 | char *t; | |
644 | size_t k; | |
645 | ||
ea0999c9 MB |
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 | ||
bb4f798a MB |
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); | |
8b3d4ff0 | 659 | free(buf); |
bb4f798a MB |
660 | } else { |
661 | t = realloc(buf, n_next + 1); | |
662 | if (!t) | |
663 | return -ENOMEM; | |
664 | } | |
663996b3 MS |
665 | |
666 | buf = t; | |
3a6ce677 BR |
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) */ | |
8b3d4ff0 | 669 | n = size == SIZE_MAX ? MALLOC_SIZEOF_SAFE(buf) - 1 : n_next; |
bb4f798a | 670 | |
f5e65279 | 671 | errno = 0; |
663996b3 | 672 | k = fread(buf + l, 1, n - l, f); |
a10f5d05 MB |
673 | |
674 | assert(k <= n - l); | |
675 | l += k; | |
663996b3 | 676 | |
bb4f798a | 677 | if (ferror(f)) { |
f2dec872 | 678 | r = errno_or_else(EIO); |
bb4f798a MB |
679 | goto finalize; |
680 | } | |
8a584da2 | 681 | if (feof(f)) |
663996b3 | 682 | break; |
663996b3 | 683 | |
ea0999c9 | 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 */ |
3a6ce677 BR |
685 | assert(l == size); |
686 | break; | |
687 | } | |
688 | ||
a10f5d05 | 689 | assert(k > 0); /* we can't have read zero bytes because that would have been EOF */ |
663996b3 | 690 | |
ea0999c9 MB |
691 | if (FLAGS_SET(flags, READ_FULL_FILE_FAIL_WHEN_LARGER) && l > size) { |
692 | r = -E2BIG; | |
693 | goto finalize; | |
694 | } | |
695 | ||
bb4f798a MB |
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 | } | |
8a584da2 | 703 | |
f2dec872 | 704 | if (flags & (READ_FULL_FILE_UNBASE64 | READ_FULL_FILE_UNHEX)) { |
a10f5d05 MB |
705 | _cleanup_free_ void *decoded = NULL; |
706 | size_t decoded_size; | |
707 | ||
bb4f798a | 708 | buf[l++] = 0; |
f2dec872 | 709 | if (flags & READ_FULL_FILE_UNBASE64) |
a10f5d05 | 710 | r = unbase64mem_full(buf, l, flags & READ_FULL_FILE_SECURE, &decoded, &decoded_size); |
f2dec872 | 711 | else |
a10f5d05 MB |
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; | |
663996b3 MS |
720 | } |
721 | ||
6e866b33 MB |
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 | ||
bb4f798a MB |
727 | if (memchr(buf, 0, l)) { |
728 | r = -EBADMSG; | |
729 | goto finalize; | |
730 | } | |
6e866b33 MB |
731 | } |
732 | ||
663996b3 | 733 | buf[l] = 0; |
6e866b33 | 734 | *ret_contents = TAKE_PTR(buf); |
663996b3 | 735 | |
6e866b33 MB |
736 | if (ret_size) |
737 | *ret_size = l; | |
663996b3 MS |
738 | |
739 | return 0; | |
bb4f798a MB |
740 | |
741 | finalize: | |
742 | if (flags & READ_FULL_FILE_SECURE) | |
743 | explicit_bzero_safe(buf, n); | |
744 | ||
745 | return r; | |
663996b3 MS |
746 | } |
747 | ||
a032b68d MB |
748 | int read_full_file_full( |
749 | int dir_fd, | |
750 | const char *filename, | |
3a6ce677 BR |
751 | uint64_t offset, |
752 | size_t size, | |
a032b68d MB |
753 | ReadFullFileFlags flags, |
754 | const char *bind_name, | |
3a6ce677 BR |
755 | char **ret_contents, |
756 | size_t *ret_size) { | |
a032b68d | 757 | |
e842803a | 758 | _cleanup_fclose_ FILE *f = NULL; |
f2dec872 | 759 | int r; |
e842803a | 760 | |
bb4f798a | 761 | assert(filename); |
3a6ce677 | 762 | assert(ret_contents); |
e842803a | 763 | |
46cdbd49 | 764 | r = xfopenat(dir_fd, filename, "re", 0, &f); |
a10f5d05 | 765 | if (r < 0) { |
086111aa | 766 | _cleanup_close_ int sk = -1; |
a10f5d05 MB |
767 | |
768 | /* ENXIO is what Linux returns if we open a node that is an AF_UNIX socket */ | |
769 | if (r != -ENXIO) | |
770 | return r; | |
771 | ||
772 | /* If this is enabled, let's try to connect to it */ | |
773 | if (!FLAGS_SET(flags, READ_FULL_FILE_CONNECT_SOCKET)) | |
774 | return -ENXIO; | |
775 | ||
3a6ce677 BR |
776 | /* Seeking is not supported on AF_UNIX sockets */ |
777 | if (offset != UINT64_MAX) | |
b3e21333 | 778 | return -ENXIO; |
3a6ce677 | 779 | |
a10f5d05 MB |
780 | sk = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); |
781 | if (sk < 0) | |
782 | return -errno; | |
783 | ||
a032b68d MB |
784 | if (bind_name) { |
785 | /* If the caller specified a socket name to bind to, do so before connecting. This is | |
786 | * useful to communicate some minor, short meta-information token from the client to | |
787 | * the server. */ | |
788 | union sockaddr_union bsa; | |
789 | ||
790 | r = sockaddr_un_set_path(&bsa.un, bind_name); | |
791 | if (r < 0) | |
792 | return r; | |
793 | ||
794 | if (bind(sk, &bsa.sa, r) < 0) | |
b3e21333 | 795 | return -errno; |
a032b68d MB |
796 | } |
797 | ||
086111aa LB |
798 | r = connect_unix_path(sk, dir_fd, filename); |
799 | if (IN_SET(r, -ENOTSOCK, -EINVAL)) /* propagate original error if this is not a socket after all */ | |
800 | return -ENXIO; | |
801 | if (r < 0) | |
802 | return r; | |
a10f5d05 MB |
803 | |
804 | if (shutdown(sk, SHUT_WR) < 0) | |
805 | return -errno; | |
806 | ||
807 | f = fdopen(sk, "r"); | |
808 | if (!f) | |
809 | return -errno; | |
810 | ||
811 | TAKE_FD(sk); | |
812 | } | |
52ad194e | 813 | |
46cdbd49 BR |
814 | (void) __fsetlocking(f, FSETLOCKING_BYCALLER); |
815 | ||
3a6ce677 | 816 | return read_full_stream_full(f, filename, offset, size, flags, ret_contents, ret_size); |
e842803a MB |
817 | } |
818 | ||
14228c0d | 819 | int executable_is_script(const char *path, char **interpreter) { |
e842803a | 820 | _cleanup_free_ char *line = NULL; |
1d42b86d | 821 | size_t len; |
14228c0d | 822 | char *ans; |
1d42b86d | 823 | int r; |
14228c0d MB |
824 | |
825 | assert(path); | |
826 | ||
827 | r = read_one_line_file(path, &line); | |
1d42b86d MB |
828 | if (r == -ENOBUFS) /* First line overly long? if so, then it's not a script */ |
829 | return 0; | |
14228c0d MB |
830 | if (r < 0) |
831 | return r; | |
832 | ||
833 | if (!startswith(line, "#!")) | |
834 | return 0; | |
835 | ||
836 | ans = strstrip(line + 2); | |
837 | len = strcspn(ans, " \t"); | |
838 | ||
839 | if (len == 0) | |
840 | return 0; | |
841 | ||
842 | ans = strndup(ans, len); | |
843 | if (!ans) | |
844 | return -ENOMEM; | |
845 | ||
846 | *interpreter = ans; | |
847 | return 1; | |
848 | } | |
849 | ||
850 | /** | |
851 | * Retrieve one field from a file like /proc/self/status. pattern | |
6300502b MP |
852 | * should not include whitespace or the delimiter (':'). pattern matches only |
853 | * the beginning of a line. Whitespace before ':' is skipped. Whitespace and | |
854 | * zeros after the ':' will be skipped. field must be freed afterwards. | |
855 | * terminator specifies the terminating characters of the field value (not | |
856 | * included in the value). | |
14228c0d | 857 | */ |
6300502b | 858 | int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) { |
14228c0d | 859 | _cleanup_free_ char *status = NULL; |
7035cd9e | 860 | char *t, *f; |
14228c0d MB |
861 | size_t len; |
862 | int r; | |
863 | ||
6300502b | 864 | assert(terminator); |
14228c0d | 865 | assert(filename); |
60f067b4 | 866 | assert(pattern); |
14228c0d MB |
867 | assert(field); |
868 | ||
e1f67bc7 | 869 | r = read_full_virtual_file(filename, &status, NULL); |
14228c0d MB |
870 | if (r < 0) |
871 | return r; | |
872 | ||
6300502b MP |
873 | t = status; |
874 | ||
875 | do { | |
876 | bool pattern_ok; | |
877 | ||
878 | do { | |
879 | t = strstr(t, pattern); | |
880 | if (!t) | |
881 | return -ENOENT; | |
882 | ||
883 | /* Check that pattern occurs in beginning of line. */ | |
884 | pattern_ok = (t == status || t[-1] == '\n'); | |
885 | ||
886 | t += strlen(pattern); | |
887 | ||
888 | } while (!pattern_ok); | |
889 | ||
890 | t += strspn(t, " \t"); | |
891 | if (!*t) | |
892 | return -ENOENT; | |
893 | ||
894 | } while (*t != ':'); | |
895 | ||
896 | t++; | |
14228c0d | 897 | |
14228c0d MB |
898 | if (*t) { |
899 | t += strspn(t, " \t"); | |
900 | ||
901 | /* Also skip zeros, because when this is used for | |
902 | * capabilities, we don't want the zeros. This way the | |
903 | * same capability set always maps to the same string, | |
904 | * irrespective of the total capability set size. For | |
905 | * other numbers it shouldn't matter. */ | |
906 | t += strspn(t, "0"); | |
907 | /* Back off one char if there's nothing but whitespace | |
908 | and zeros */ | |
909 | if (!*t || isspace(*t)) | |
aa27b158 | 910 | t--; |
14228c0d MB |
911 | } |
912 | ||
6300502b | 913 | len = strcspn(t, terminator); |
14228c0d | 914 | |
7035cd9e MP |
915 | f = strndup(t, len); |
916 | if (!f) | |
14228c0d MB |
917 | return -ENOMEM; |
918 | ||
7035cd9e | 919 | *field = f; |
14228c0d MB |
920 | return 0; |
921 | } | |
db2df898 MP |
922 | |
923 | DIR *xopendirat(int fd, const char *name, int flags) { | |
924 | int nfd; | |
925 | DIR *d; | |
926 | ||
927 | assert(!(flags & O_CREAT)); | |
928 | ||
ea0999c9 MB |
929 | if (fd == AT_FDCWD && flags == 0) |
930 | return opendir(name); | |
931 | ||
db2df898 MP |
932 | nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0); |
933 | if (nfd < 0) | |
934 | return NULL; | |
935 | ||
936 | d = fdopendir(nfd); | |
937 | if (!d) { | |
938 | safe_close(nfd); | |
939 | return NULL; | |
940 | } | |
941 | ||
942 | return d; | |
943 | } | |
944 | ||
ea0999c9 | 945 | int fopen_mode_to_flags(const char *mode) { |
46cdbd49 BR |
946 | const char *p; |
947 | int flags; | |
948 | ||
ea0999c9 MB |
949 | assert(mode); |
950 | ||
46cdbd49 BR |
951 | if ((p = startswith(mode, "r+"))) |
952 | flags = O_RDWR; | |
953 | else if ((p = startswith(mode, "r"))) | |
954 | flags = O_RDONLY; | |
955 | else if ((p = startswith(mode, "w+"))) | |
956 | flags = O_RDWR|O_CREAT|O_TRUNC; | |
957 | else if ((p = startswith(mode, "w"))) | |
958 | flags = O_WRONLY|O_CREAT|O_TRUNC; | |
959 | else if ((p = startswith(mode, "a+"))) | |
960 | flags = O_RDWR|O_CREAT|O_APPEND; | |
961 | else if ((p = startswith(mode, "a"))) | |
962 | flags = O_WRONLY|O_CREAT|O_APPEND; | |
963 | else | |
964 | return -EINVAL; | |
965 | ||
966 | for (; *p != 0; p++) { | |
967 | ||
968 | switch (*p) { | |
969 | ||
970 | case 'e': | |
971 | flags |= O_CLOEXEC; | |
972 | break; | |
973 | ||
974 | case 'x': | |
975 | flags |= O_EXCL; | |
976 | break; | |
977 | ||
978 | case 'm': | |
979 | /* ignore this here, fdopen() might care later though */ | |
980 | break; | |
981 | ||
982 | case 'c': /* not sure what to do about this one */ | |
983 | default: | |
984 | return -EINVAL; | |
985 | } | |
986 | } | |
987 | ||
988 | return flags; | |
989 | } | |
990 | ||
991 | int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **ret) { | |
992 | FILE *f; | |
993 | ||
994 | /* A combination of fopen() with openat() */ | |
995 | ||
996 | if (dir_fd == AT_FDCWD && flags == 0) { | |
997 | f = fopen(path, mode); | |
998 | if (!f) | |
999 | return -errno; | |
1000 | } else { | |
1001 | int fd, mode_flags; | |
1002 | ||
ea0999c9 | 1003 | mode_flags = fopen_mode_to_flags(mode); |
46cdbd49 BR |
1004 | if (mode_flags < 0) |
1005 | return mode_flags; | |
1006 | ||
1007 | fd = openat(dir_fd, path, mode_flags | flags); | |
1008 | if (fd < 0) | |
1009 | return -errno; | |
1010 | ||
1011 | f = fdopen(fd, mode); | |
1012 | if (!f) { | |
1013 | safe_close(fd); | |
1014 | return -errno; | |
1015 | } | |
1016 | } | |
1017 | ||
1018 | *ret = f; | |
1019 | return 0; | |
1020 | } | |
1021 | ||
8b3d4ff0 MB |
1022 | static int search_and_fopen_internal( |
1023 | const char *path, | |
1024 | const char *mode, | |
1025 | const char *root, | |
1026 | char **search, | |
1027 | FILE **ret, | |
1028 | char **ret_path) { | |
1029 | ||
db2df898 MP |
1030 | assert(path); |
1031 | assert(mode); | |
8b3d4ff0 | 1032 | assert(ret); |
db2df898 MP |
1033 | |
1034 | if (!path_strv_resolve_uniq(search, root)) | |
1035 | return -ENOMEM; | |
1036 | ||
1037 | STRV_FOREACH(i, search) { | |
1038 | _cleanup_free_ char *p = NULL; | |
1039 | FILE *f; | |
1040 | ||
f2dec872 | 1041 | p = path_join(root, *i, path); |
db2df898 MP |
1042 | if (!p) |
1043 | return -ENOMEM; | |
1044 | ||
1045 | f = fopen(p, mode); | |
1046 | if (f) { | |
8b3d4ff0 MB |
1047 | if (ret_path) |
1048 | *ret_path = path_simplify(TAKE_PTR(p)); | |
1049 | ||
1050 | *ret = f; | |
db2df898 MP |
1051 | return 0; |
1052 | } | |
1053 | ||
1054 | if (errno != ENOENT) | |
1055 | return -errno; | |
1056 | } | |
1057 | ||
1058 | return -ENOENT; | |
1059 | } | |
1060 | ||
8b3d4ff0 MB |
1061 | int search_and_fopen( |
1062 | const char *filename, | |
1063 | const char *mode, | |
1064 | const char *root, | |
1065 | const char **search, | |
1066 | FILE **ret, | |
1067 | char **ret_path) { | |
1068 | ||
db2df898 MP |
1069 | _cleanup_strv_free_ char **copy = NULL; |
1070 | ||
8b3d4ff0 | 1071 | assert(filename); |
db2df898 | 1072 | assert(mode); |
8b3d4ff0 | 1073 | assert(ret); |
db2df898 | 1074 | |
8b3d4ff0 MB |
1075 | if (path_is_absolute(filename)) { |
1076 | _cleanup_fclose_ FILE *f = NULL; | |
db2df898 | 1077 | |
8b3d4ff0 MB |
1078 | f = fopen(filename, mode); |
1079 | if (!f) | |
1080 | return -errno; | |
1081 | ||
1082 | if (ret_path) { | |
1083 | char *p; | |
1084 | ||
1085 | p = strdup(filename); | |
1086 | if (!p) | |
1087 | return -ENOMEM; | |
1088 | ||
1089 | *ret_path = path_simplify(p); | |
db2df898 MP |
1090 | } |
1091 | ||
8b3d4ff0 MB |
1092 | *ret = TAKE_PTR(f); |
1093 | return 0; | |
db2df898 MP |
1094 | } |
1095 | ||
1096 | copy = strv_copy((char**) search); | |
1097 | if (!copy) | |
1098 | return -ENOMEM; | |
1099 | ||
8b3d4ff0 | 1100 | return search_and_fopen_internal(filename, mode, root, copy, ret, ret_path); |
db2df898 MP |
1101 | } |
1102 | ||
8b3d4ff0 MB |
1103 | int search_and_fopen_nulstr( |
1104 | const char *filename, | |
1105 | const char *mode, | |
1106 | const char *root, | |
1107 | const char *search, | |
1108 | FILE **ret, | |
1109 | char **ret_path) { | |
1110 | ||
db2df898 MP |
1111 | _cleanup_strv_free_ char **s = NULL; |
1112 | ||
8b3d4ff0 MB |
1113 | if (path_is_absolute(filename)) { |
1114 | _cleanup_fclose_ FILE *f = NULL; | |
db2df898 | 1115 | |
8b3d4ff0 MB |
1116 | f = fopen(filename, mode); |
1117 | if (!f) | |
1118 | return -errno; | |
1119 | ||
1120 | if (ret_path) { | |
1121 | char *p; | |
1122 | ||
1123 | p = strdup(filename); | |
1124 | if (!p) | |
1125 | return -ENOMEM; | |
1126 | ||
1127 | *ret_path = path_simplify(p); | |
db2df898 MP |
1128 | } |
1129 | ||
8b3d4ff0 MB |
1130 | *ret = TAKE_PTR(f); |
1131 | return 0; | |
db2df898 MP |
1132 | } |
1133 | ||
1134 | s = strv_split_nulstr(search); | |
1135 | if (!s) | |
1136 | return -ENOMEM; | |
1137 | ||
8b3d4ff0 | 1138 | return search_and_fopen_internal(filename, mode, root, s, ret, ret_path); |
db2df898 MP |
1139 | } |
1140 | ||
db2df898 MP |
1141 | int fflush_and_check(FILE *f) { |
1142 | assert(f); | |
1143 | ||
1144 | errno = 0; | |
1145 | fflush(f); | |
1146 | ||
1147 | if (ferror(f)) | |
f2dec872 | 1148 | return errno_or_else(EIO); |
db2df898 MP |
1149 | |
1150 | return 0; | |
1151 | } | |
1152 | ||
f5e65279 | 1153 | int fflush_sync_and_check(FILE *f) { |
d0648cfe | 1154 | int r, fd; |
f5e65279 MB |
1155 | |
1156 | assert(f); | |
1157 | ||
1158 | r = fflush_and_check(f); | |
1159 | if (r < 0) | |
1160 | return r; | |
1161 | ||
d0648cfe MB |
1162 | /* Not all file streams have an fd associated (think: fmemopen()), let's handle this gracefully and |
1163 | * assume that in that case we need no explicit syncing */ | |
1164 | fd = fileno(f); | |
1165 | if (fd < 0) | |
1166 | return 0; | |
1167 | ||
ea0999c9 | 1168 | r = fsync_full(fd); |
98393f85 MB |
1169 | if (r < 0) |
1170 | return r; | |
1171 | ||
f5e65279 MB |
1172 | return 0; |
1173 | } | |
1174 | ||
db2df898 MP |
1175 | int write_timestamp_file_atomic(const char *fn, usec_t n) { |
1176 | char ln[DECIMAL_STR_MAX(n)+2]; | |
1177 | ||
1178 | /* Creates a "timestamp" file, that contains nothing but a | |
1179 | * usec_t timestamp, formatted in ASCII. */ | |
1180 | ||
f5caa8fa | 1181 | if (!timestamp_is_set(n)) |
db2df898 MP |
1182 | return -ERANGE; |
1183 | ||
1184 | xsprintf(ln, USEC_FMT "\n", n); | |
1185 | ||
1186 | return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC); | |
1187 | } | |
1188 | ||
1189 | int read_timestamp_file(const char *fn, usec_t *ret) { | |
1190 | _cleanup_free_ char *ln = NULL; | |
1191 | uint64_t t; | |
1192 | int r; | |
1193 | ||
1194 | r = read_one_line_file(fn, &ln); | |
1195 | if (r < 0) | |
1196 | return r; | |
1197 | ||
1198 | r = safe_atou64(ln, &t); | |
1199 | if (r < 0) | |
1200 | return r; | |
1201 | ||
f5caa8fa | 1202 | if (!timestamp_is_set(t)) |
db2df898 MP |
1203 | return -ERANGE; |
1204 | ||
1205 | *ret = (usec_t) t; | |
1206 | return 0; | |
1207 | } | |
4c89c718 MP |
1208 | |
1209 | int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) { | |
1210 | int r; | |
1211 | ||
1212 | assert(s); | |
1213 | ||
1214 | /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter | |
1215 | * when specified shall initially point to a boolean variable initialized to false. It is set to true after the | |
1216 | * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each | |
1217 | * element, but not before the first one. */ | |
1218 | ||
1219 | if (!f) | |
1220 | f = stdout; | |
1221 | ||
1222 | if (space) { | |
1223 | if (!separator) | |
1224 | separator = " "; | |
1225 | ||
1226 | if (*space) { | |
1227 | r = fputs(separator, f); | |
1228 | if (r < 0) | |
1229 | return r; | |
1230 | } | |
1231 | ||
1232 | *space = true; | |
1233 | } | |
1234 | ||
1235 | return fputs(s, f); | |
1236 | } | |
aa27b158 | 1237 | |
6e866b33 MB |
1238 | /* A bitmask of the EOL markers we know */ |
1239 | typedef enum EndOfLineMarker { | |
1240 | EOL_NONE = 0, | |
1241 | EOL_ZERO = 1 << 0, /* \0 (aka NUL) */ | |
1242 | EOL_TEN = 1 << 1, /* \n (aka NL, aka LF) */ | |
1243 | EOL_THIRTEEN = 1 << 2, /* \r (aka CR) */ | |
1244 | } EndOfLineMarker; | |
aa27b158 | 1245 | |
6e866b33 | 1246 | static EndOfLineMarker categorize_eol(char c, ReadLineFlags flags) { |
aa27b158 | 1247 | |
6e866b33 MB |
1248 | if (!IN_SET(flags, READ_LINE_ONLY_NUL)) { |
1249 | if (c == '\n') | |
1250 | return EOL_TEN; | |
1251 | if (c == '\r') | |
1252 | return EOL_THIRTEEN; | |
aa27b158 | 1253 | } |
aa27b158 | 1254 | |
6e866b33 MB |
1255 | if (c == '\0') |
1256 | return EOL_ZERO; | |
2897b343 | 1257 | |
6e866b33 | 1258 | return EOL_NONE; |
2897b343 | 1259 | } |
f5e65279 | 1260 | |
3a6ce677 | 1261 | DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, funlockfile, NULL); |
f5e65279 | 1262 | |
6e866b33 | 1263 | int read_line_full(FILE *f, size_t limit, ReadLineFlags flags, char **ret) { |
6e866b33 | 1264 | _cleanup_free_ char *buffer = NULL; |
8b3d4ff0 | 1265 | size_t n = 0, count = 0; |
d0648cfe | 1266 | int r; |
f5e65279 MB |
1267 | |
1268 | assert(f); | |
1269 | ||
1270 | /* Something like a bounded version of getline(). | |
1271 | * | |
6e866b33 MB |
1272 | * Considers EOF, \n, \r and \0 end of line delimiters (or combinations of these), and does not include these |
1273 | * delimiters in the string returned. Specifically, recognizes the following combinations of markers as line | |
1274 | * endings: | |
1275 | * | |
1276 | * • \n (UNIX) | |
1277 | * • \r (old MacOS) | |
1278 | * • \0 (C strings) | |
1279 | * • \n\0 | |
1280 | * • \r\0 | |
1281 | * • \r\n (Windows) | |
1282 | * • \n\r | |
1283 | * • \r\n\0 | |
1284 | * • \n\r\0 | |
f5e65279 MB |
1285 | * |
1286 | * Returns the number of bytes read from the files (i.e. including delimiters — this hence usually differs from | |
1287 | * the number of characters in the returned string). When EOF is hit, 0 is returned. | |
1288 | * | |
1289 | * The input parameter limit is the maximum numbers of characters in the returned string, i.e. excluding | |
1290 | * delimiters. If the limit is hit we fail and return -ENOBUFS. | |
1291 | * | |
1292 | * If a line shall be skipped ret may be initialized as NULL. */ | |
1293 | ||
1294 | if (ret) { | |
8b3d4ff0 | 1295 | if (!GREEDY_REALLOC(buffer, 1)) |
f5e65279 MB |
1296 | return -ENOMEM; |
1297 | } | |
1298 | ||
1299 | { | |
52ad194e | 1300 | _unused_ _cleanup_(funlockfilep) FILE *flocked = f; |
6e866b33 | 1301 | EndOfLineMarker previous_eol = EOL_NONE; |
f5e65279 MB |
1302 | flockfile(f); |
1303 | ||
1304 | for (;;) { | |
6e866b33 MB |
1305 | EndOfLineMarker eol; |
1306 | char c; | |
f5e65279 MB |
1307 | |
1308 | if (n >= limit) | |
1309 | return -ENOBUFS; | |
1310 | ||
6e866b33 MB |
1311 | if (count >= INT_MAX) /* We couldn't return the counter anymore as "int", hence refuse this */ |
1312 | return -ENOBUFS; | |
f5e65279 | 1313 | |
6e866b33 MB |
1314 | r = safe_fgetc(f, &c); |
1315 | if (r < 0) | |
1316 | return r; | |
1317 | if (r == 0) /* EOF is definitely EOL */ | |
1318 | break; | |
1319 | ||
1320 | eol = categorize_eol(c, flags); | |
1321 | ||
1322 | if (FLAGS_SET(previous_eol, EOL_ZERO) || | |
1323 | (eol == EOL_NONE && previous_eol != EOL_NONE) || | |
1324 | (eol != EOL_NONE && (previous_eol & eol) != 0)) { | |
1325 | /* Previous char was a NUL? This is not an EOL, but the previous char was? This type of | |
1326 | * EOL marker has been seen right before? In either of these three cases we are | |
1327 | * done. But first, let's put this character back in the queue. (Note that we have to | |
1328 | * cast this to (unsigned char) here as ungetc() expects a positive 'int', and if we | |
1329 | * are on an architecture where 'char' equals 'signed char' we need to ensure we don't | |
1330 | * pass a negative value here. That said, to complicate things further ungetc() is | |
1331 | * actually happy with most negative characters and implicitly casts them back to | |
1332 | * positive ones as needed, except for \xff (aka -1, aka EOF), which it refuses. What a | |
1333 | * godawful API!) */ | |
1334 | assert_se(ungetc((unsigned char) c, f) != EOF); | |
f5e65279 MB |
1335 | break; |
1336 | } | |
1337 | ||
1338 | count++; | |
1339 | ||
f2dec872 | 1340 | if (eol != EOL_NONE) { |
d0648cfe MB |
1341 | /* If we are on a tty, we can't shouldn't wait for more input, because that |
1342 | * generally means waiting for the user, interactively. In the case of a TTY | |
1343 | * we expect only \n as the single EOL marker, so we are in the lucky | |
1344 | * position that there is no need to wait. We check this condition last, to | |
1345 | * avoid isatty() check if not necessary. */ | |
1346 | ||
1347 | if ((flags & (READ_LINE_IS_A_TTY|READ_LINE_NOT_A_TTY)) == 0) { | |
1348 | int fd; | |
1349 | ||
1350 | fd = fileno(f); | |
1351 | if (fd < 0) /* Maybe an fmemopen() stream? Handle this gracefully, | |
1352 | * and don't call isatty() on an invalid fd */ | |
1353 | flags |= READ_LINE_NOT_A_TTY; | |
1354 | else | |
1355 | flags |= isatty(fd) ? READ_LINE_IS_A_TTY : READ_LINE_NOT_A_TTY; | |
1356 | } | |
1357 | if (FLAGS_SET(flags, READ_LINE_IS_A_TTY)) | |
f2dec872 BR |
1358 | break; |
1359 | } | |
1360 | ||
6e866b33 MB |
1361 | if (eol != EOL_NONE) { |
1362 | previous_eol |= eol; | |
1363 | continue; | |
1364 | } | |
f5e65279 MB |
1365 | |
1366 | if (ret) { | |
8b3d4ff0 | 1367 | if (!GREEDY_REALLOC(buffer, n + 2)) |
f5e65279 MB |
1368 | return -ENOMEM; |
1369 | ||
6e866b33 | 1370 | buffer[n] = c; |
f5e65279 MB |
1371 | } |
1372 | ||
1373 | n++; | |
1374 | } | |
1375 | } | |
1376 | ||
1377 | if (ret) { | |
1378 | buffer[n] = 0; | |
1379 | ||
b012e921 | 1380 | *ret = TAKE_PTR(buffer); |
f5e65279 MB |
1381 | } |
1382 | ||
1383 | return (int) count; | |
1384 | } | |
6e866b33 MB |
1385 | |
1386 | int safe_fgetc(FILE *f, char *ret) { | |
1387 | int k; | |
1388 | ||
1389 | assert(f); | |
1390 | ||
1391 | /* A safer version of plain fgetc(): let's propagate the error that happened while reading as such, and | |
1392 | * separate the EOF condition from the byte read, to avoid those confusion signed/unsigned issues fgetc() | |
1393 | * has. */ | |
1394 | ||
1395 | errno = 0; | |
1396 | k = fgetc(f); | |
1397 | if (k == EOF) { | |
1398 | if (ferror(f)) | |
f2dec872 | 1399 | return errno_or_else(EIO); |
6e866b33 MB |
1400 | |
1401 | if (ret) | |
1402 | *ret = 0; | |
1403 | ||
1404 | return 0; | |
1405 | } | |
1406 | ||
1407 | if (ret) | |
1408 | *ret = k; | |
1409 | ||
1410 | return 1; | |
1411 | } | |
bb4f798a MB |
1412 | |
1413 | int warn_file_is_world_accessible(const char *filename, struct stat *st, const char *unit, unsigned line) { | |
1414 | struct stat _st; | |
1415 | ||
1416 | if (!filename) | |
1417 | return 0; | |
1418 | ||
1419 | if (!st) { | |
1420 | if (stat(filename, &_st) < 0) | |
1421 | return -errno; | |
1422 | st = &_st; | |
1423 | } | |
1424 | ||
1425 | if ((st->st_mode & S_IRWXO) == 0) | |
1426 | return 0; | |
1427 | ||
1428 | if (unit) | |
1429 | log_syntax(unit, LOG_WARNING, filename, line, 0, | |
e1f67bc7 | 1430 | "%s has %04o mode that is too permissive, please adjust the ownership and access mode.", |
bb4f798a MB |
1431 | filename, st->st_mode & 07777); |
1432 | else | |
e1f67bc7 | 1433 | log_warning("%s has %04o mode that is too permissive, please adjust the ownership and access mode.", |
bb4f798a MB |
1434 | filename, st->st_mode & 07777); |
1435 | return 0; | |
1436 | } |