]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-fd-util.c
df6ca13785faa5a1c5138ba8b5f49962488511a9
[thirdparty/systemd.git] / src / test / test-fd-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/eventfd.h>
5 #include <unistd.h>
6
7 #include "alloc-util.h"
8 #include "data-fd-util.h"
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "macro.h"
12 #include "memory-util.h"
13 #include "missing_syscall.h"
14 #include "mount-util.h"
15 #include "path-util.h"
16 #include "process-util.h"
17 #include "random-util.h"
18 #include "rlimit-util.h"
19 #include "seccomp-util.h"
20 #include "serialize.h"
21 #include "string-util.h"
22 #include "tests.h"
23 #include "tmpfile-util.h"
24
25 TEST(close_many) {
26 int fds[3];
27 char name0[] = "/tmp/test-close-many.XXXXXX";
28 char name1[] = "/tmp/test-close-many.XXXXXX";
29 char name2[] = "/tmp/test-close-many.XXXXXX";
30
31 fds[0] = mkostemp_safe(name0);
32 fds[1] = mkostemp_safe(name1);
33 fds[2] = mkostemp_safe(name2);
34
35 close_many(fds, 2);
36
37 assert_se(fcntl(fds[0], F_GETFD) == -1);
38 assert_se(fcntl(fds[1], F_GETFD) == -1);
39 assert_se(fcntl(fds[2], F_GETFD) >= 0);
40
41 safe_close(fds[2]);
42
43 unlink(name0);
44 unlink(name1);
45 unlink(name2);
46 }
47
48 TEST(close_nointr) {
49 char name[] = "/tmp/test-test-close_nointr.XXXXXX";
50 int fd;
51
52 fd = mkostemp_safe(name);
53 assert_se(fd >= 0);
54 assert_se(close_nointr(fd) >= 0);
55 assert_se(close_nointr(fd) < 0);
56
57 unlink(name);
58 }
59
60 TEST(same_fd) {
61 _cleanup_close_pair_ int p[2] = { -1, -1 };
62 _cleanup_close_ int a = -1, b = -1, c = -1;
63
64 assert_se(pipe2(p, O_CLOEXEC) >= 0);
65 assert_se((a = fcntl(p[0], F_DUPFD, 3)) >= 0);
66 assert_se((b = open("/dev/null", O_RDONLY|O_CLOEXEC)) >= 0);
67 assert_se((c = fcntl(a, F_DUPFD, 3)) >= 0);
68
69 assert_se(same_fd(p[0], p[0]) > 0);
70 assert_se(same_fd(p[1], p[1]) > 0);
71 assert_se(same_fd(a, a) > 0);
72 assert_se(same_fd(b, b) > 0);
73
74 assert_se(same_fd(a, p[0]) > 0);
75 assert_se(same_fd(p[0], a) > 0);
76 assert_se(same_fd(c, p[0]) > 0);
77 assert_se(same_fd(p[0], c) > 0);
78 assert_se(same_fd(a, c) > 0);
79 assert_se(same_fd(c, a) > 0);
80
81 assert_se(same_fd(p[0], p[1]) == 0);
82 assert_se(same_fd(p[1], p[0]) == 0);
83 assert_se(same_fd(p[0], b) == 0);
84 assert_se(same_fd(b, p[0]) == 0);
85 assert_se(same_fd(p[1], a) == 0);
86 assert_se(same_fd(a, p[1]) == 0);
87 assert_se(same_fd(p[1], b) == 0);
88 assert_se(same_fd(b, p[1]) == 0);
89
90 assert_se(same_fd(a, b) == 0);
91 assert_se(same_fd(b, a) == 0);
92 }
93
94 TEST(open_serialization_fd) {
95 _cleanup_close_ int fd = -1;
96
97 fd = open_serialization_fd("test");
98 assert_se(fd >= 0);
99
100 assert_se(write(fd, "test\n", 5) == 5);
101 }
102
103 TEST(fd_move_above_stdio) {
104 int original_stdin, new_fd;
105
106 original_stdin = fcntl(0, F_DUPFD, 3);
107 assert_se(original_stdin >= 3);
108 assert_se(close_nointr(0) != EBADF);
109
110 new_fd = open("/dev/null", O_RDONLY);
111 assert_se(new_fd == 0);
112
113 new_fd = fd_move_above_stdio(new_fd);
114 assert_se(new_fd >= 3);
115
116 assert_se(dup(original_stdin) == 0);
117 assert_se(close_nointr(original_stdin) != EBADF);
118 assert_se(close_nointr(new_fd) != EBADF);
119 }
120
121 TEST(rearrange_stdio) {
122 pid_t pid;
123 int r;
124
125 r = safe_fork("rearrange", FORK_WAIT|FORK_LOG, &pid);
126 assert_se(r >= 0);
127
128 if (r == 0) {
129 _cleanup_free_ char *path = NULL;
130 char buffer[10];
131
132 /* Child */
133
134 safe_close(STDERR_FILENO); /* Let's close an fd < 2, to make it more interesting */
135
136 assert_se(rearrange_stdio(-1, -1, -1) >= 0);
137
138 assert_se(fd_get_path(STDIN_FILENO, &path) >= 0);
139 assert_se(path_equal(path, "/dev/null"));
140 path = mfree(path);
141
142 assert_se(fd_get_path(STDOUT_FILENO, &path) >= 0);
143 assert_se(path_equal(path, "/dev/null"));
144 path = mfree(path);
145
146 assert_se(fd_get_path(STDOUT_FILENO, &path) >= 0);
147 assert_se(path_equal(path, "/dev/null"));
148 path = mfree(path);
149
150 safe_close(STDIN_FILENO);
151 safe_close(STDOUT_FILENO);
152 safe_close(STDERR_FILENO);
153
154 {
155 int pair[2];
156 assert_se(pipe(pair) >= 0);
157 assert_se(pair[0] == 0);
158 assert_se(pair[1] == 1);
159 assert_se(fd_move_above_stdio(0) == 3);
160 }
161 assert_se(open("/dev/full", O_WRONLY|O_CLOEXEC) == 0);
162 assert_se(acquire_data_fd("foobar", 6, 0) == 2);
163
164 assert_se(rearrange_stdio(2, 0, 1) >= 0);
165
166 assert_se(write(1, "x", 1) < 0 && errno == ENOSPC);
167 assert_se(write(2, "z", 1) == 1);
168 assert_se(read(3, buffer, sizeof(buffer)) == 1);
169 assert_se(buffer[0] == 'z');
170 assert_se(read(0, buffer, sizeof(buffer)) == 6);
171 assert_se(memcmp(buffer, "foobar", 6) == 0);
172
173 assert_se(rearrange_stdio(-1, 1, 2) >= 0);
174 assert_se(write(1, "a", 1) < 0 && errno == ENOSPC);
175 assert_se(write(2, "y", 1) == 1);
176 assert_se(read(3, buffer, sizeof(buffer)) == 1);
177 assert_se(buffer[0] == 'y');
178
179 assert_se(fd_get_path(0, &path) >= 0);
180 assert_se(path_equal(path, "/dev/null"));
181 path = mfree(path);
182
183 _exit(EXIT_SUCCESS);
184 }
185 }
186
187 TEST(read_nr_open) {
188 log_info("nr-open: %i", read_nr_open());
189 }
190
191 static size_t validate_fds(
192 bool opened,
193 const int *fds,
194 size_t n_fds) {
195
196 size_t c = 0;
197
198 /* Validates that fds in the specified array are one of the following three:
199 *
200 * 1. < 0 (test is skipped) or
201 * 2. opened (if 'opened' param is true) or
202 * 3. closed (if 'opened' param is false)
203 */
204
205 for (size_t i = 0; i < n_fds; i++) {
206 if (fds[i] < 0)
207 continue;
208
209 if (opened)
210 assert_se(fcntl(fds[i], F_GETFD) >= 0);
211 else
212 assert_se(fcntl(fds[i], F_GETFD) < 0 && errno == EBADF);
213
214 c++;
215 }
216
217 return c; /* Return number of fds >= 0 in the array */
218 }
219
220 static void test_close_all_fds_inner(void) {
221 _cleanup_free_ int *fds = NULL, *keep = NULL;
222 size_t n_fds, n_keep;
223 int max_fd;
224
225 log_info("/* %s */", __func__);
226
227 rlimit_nofile_bump(-1);
228
229 max_fd = get_max_fd();
230 assert_se(max_fd > 10);
231
232 if (max_fd > 7000) {
233 /* If the worst fallback is activated we need to iterate through all possible fds, hence,
234 * let's lower the limit a small bit, so that we don't run for too long. Yes, this undoes the
235 * rlimit_nofile_bump() call above partially. */
236
237 (void) setrlimit_closest(RLIMIT_NOFILE, &(struct rlimit) { 7000, 7000 });
238 max_fd = 7000;
239 }
240
241 /* Try to use 5000 fds, but when we can't bump the rlimit to make that happen use the whole limit minus 10 */
242 n_fds = MIN(((size_t) max_fd & ~1U) - 10U, 5000U);
243 assert_se((n_fds & 1U) == 0U); /* make sure even number of fds */
244
245 /* Allocate the determined number of fds, always two at a time */
246 assert_se(fds = new(int, n_fds));
247 for (size_t i = 0; i < n_fds; i += 2)
248 assert_se(pipe2(fds + i, O_CLOEXEC) >= 0);
249
250 /* Validate this worked */
251 assert_se(validate_fds(true, fds, n_fds) == n_fds);
252
253 /* Randomized number of fds to keep, but at most every second */
254 n_keep = (random_u64() % (n_fds / 2));
255
256 /* Now randomly select a number of fds from the array above to keep */
257 assert_se(keep = new(int, n_keep));
258 for (size_t k = 0; k < n_keep; k++) {
259 for (;;) {
260 size_t p;
261
262 p = random_u64() % n_fds;
263 if (fds[p] >= 0) {
264 keep[k] = TAKE_FD(fds[p]);
265 break;
266 }
267 }
268 }
269
270 /* Check that all fds from both arrays are still open, and test how many in each are >= 0 */
271 assert_se(validate_fds(true, fds, n_fds) == n_fds - n_keep);
272 assert_se(validate_fds(true, keep, n_keep) == n_keep);
273
274 /* Close logging fd first, so that we don't confuse it by closing its fd */
275 log_close();
276 log_set_open_when_needed(true);
277
278 /* Close all but the ones to keep */
279 assert_se(close_all_fds(keep, n_keep) >= 0);
280
281 assert_se(validate_fds(false, fds, n_fds) == n_fds - n_keep);
282 assert_se(validate_fds(true, keep, n_keep) == n_keep);
283
284 /* Close everything else too! */
285 assert_se(close_all_fds(NULL, 0) >= 0);
286
287 assert_se(validate_fds(false, fds, n_fds) == n_fds - n_keep);
288 assert_se(validate_fds(false, keep, n_keep) == n_keep);
289
290 log_set_open_when_needed(false);
291 log_open();
292 }
293
294 static int seccomp_prohibit_close_range(void) {
295 #if HAVE_SECCOMP && defined(__SNR_close_range)
296 _cleanup_(seccomp_releasep) scmp_filter_ctx seccomp = NULL;
297 int r;
298
299 r = seccomp_init_for_arch(&seccomp, SCMP_ARCH_NATIVE, SCMP_ACT_ALLOW);
300 if (r < 0)
301 return log_warning_errno(r, "Failed to acquire seccomp context, ignoring: %m");
302
303 r = seccomp_rule_add_exact(
304 seccomp,
305 SCMP_ACT_ERRNO(EPERM),
306 SCMP_SYS(close_range),
307 0);
308 if (r < 0)
309 return log_warning_errno(r, "Failed to add close_range() rule, ignoring: %m");
310
311 r = seccomp_load(seccomp);
312 if (r < 0)
313 return log_warning_errno(r, "Failed to apply close_range() restrictions, ignoring: %m");
314
315 return 0;
316 #else
317 return log_warning_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Seccomp support or close_range() syscall definition not available.");
318 #endif
319 }
320
321 TEST(close_all_fds) {
322 int r;
323
324 /* Runs the test four times. Once as is. Once with close_range() syscall blocked via seccomp, once
325 * with /proc/ overmounted, and once with the combination of both. This should trigger all fallbacks
326 * in the close_range_all() function. */
327
328 r = safe_fork("(caf-plain)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
329 if (r == 0) {
330 test_close_all_fds_inner();
331 _exit(EXIT_SUCCESS);
332 }
333 assert_se(r >= 0);
334
335 if (geteuid() != 0)
336 return (void) log_tests_skipped("Lacking privileges for test with close_range() blocked and /proc/ overmounted");
337
338 r = safe_fork("(caf-noproc)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, NULL);
339 if (r == 0) {
340 r = mount_nofollow_verbose(LOG_WARNING, "tmpfs", "/proc", "tmpfs", 0, NULL);
341 if (r < 0)
342 log_notice("Overmounting /proc/ didn't work, skipping close_all_fds() with masked /proc/.");
343 else
344 test_close_all_fds_inner();
345 _exit(EXIT_SUCCESS);
346 }
347 assert_se(r >= 0);
348
349 if (!is_seccomp_available())
350 return (void) log_tests_skipped("Seccomp not available");
351
352 r = safe_fork("(caf-seccomp)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
353 if (r == 0) {
354 r = seccomp_prohibit_close_range();
355 if (r < 0)
356 log_notice("Applying seccomp filter didn't work, skipping close_all_fds() test with masked close_range().");
357 else
358 test_close_all_fds_inner();
359
360 _exit(EXIT_SUCCESS);
361 }
362 assert_se(r >= 0);
363
364 r = safe_fork("(caf-scnp)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, NULL);
365 if (r == 0) {
366 r = seccomp_prohibit_close_range();
367 if (r < 0)
368 log_notice("Applying seccomp filter didn't work, skipping close_all_fds() test with masked close_range().");
369 else {
370 r = mount_nofollow_verbose(LOG_WARNING, "tmpfs", "/proc", "tmpfs", 0, NULL);
371 if (r < 0)
372 log_notice("Overmounting /proc/ didn't work, skipping close_all_fds() with masked /proc/.");
373 else
374 test_close_all_fds_inner();
375 }
376
377 test_close_all_fds_inner();
378 _exit(EXIT_SUCCESS);
379 }
380 assert_se(r >= 0);
381 }
382
383 TEST(format_proc_fd_path) {
384 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(0), "/proc/self/fd/0"));
385 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(1), "/proc/self/fd/1"));
386 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2), "/proc/self/fd/2"));
387 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(3), "/proc/self/fd/3"));
388 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2147483647), "/proc/self/fd/2147483647"));
389 }
390
391 TEST(fd_reopen) {
392 _cleanup_close_ int fd1 = -1, fd2 = -1;
393 struct stat st1, st2;
394 int fl;
395
396 /* Test this with a directory */
397 fd1 = open("/proc", O_DIRECTORY|O_PATH|O_CLOEXEC);
398 assert_se(fd1 >= 0);
399
400 assert_se(fstat(fd1, &st1) >= 0);
401 assert_se(S_ISDIR(st1.st_mode));
402
403 fl = fcntl(fd1, F_GETFL);
404 assert_se(fl >= 0);
405 assert_se(FLAGS_SET(fl, O_DIRECTORY));
406 assert_se(FLAGS_SET(fl, O_PATH));
407
408 fd2 = fd_reopen(fd1, O_RDONLY|O_DIRECTORY|O_CLOEXEC); /* drop the O_PATH */
409 assert_se(fd2 >= 0);
410
411 assert_se(fstat(fd2, &st2) >= 0);
412 assert_se(S_ISDIR(st2.st_mode));
413 assert_se(st1.st_ino == st2.st_ino);
414 assert_se(st1.st_rdev == st2.st_rdev);
415
416 fl = fcntl(fd2, F_GETFL);
417 assert_se(fl >= 0);
418 assert_se(FLAGS_SET(fl, O_DIRECTORY));
419 assert_se(!FLAGS_SET(fl, O_PATH));
420
421 safe_close(fd1);
422
423 fd1 = fd_reopen(fd2, O_DIRECTORY|O_PATH|O_CLOEXEC); /* reacquire the O_PATH */
424 assert_se(fd1 >= 0);
425
426 assert_se(fstat(fd1, &st1) >= 0);
427 assert_se(S_ISDIR(st1.st_mode));
428 assert_se(st1.st_ino == st2.st_ino);
429 assert_se(st1.st_rdev == st2.st_rdev);
430
431 fl = fcntl(fd1, F_GETFL);
432 assert_se(fl >= 0);
433 assert_se(FLAGS_SET(fl, O_DIRECTORY));
434 assert_se(FLAGS_SET(fl, O_PATH));
435
436 safe_close(fd1);
437
438 /* And now, test this with a file. */
439 fd1 = open("/proc/version", O_PATH|O_CLOEXEC);
440 assert_se(fd1 >= 0);
441
442 assert_se(fstat(fd1, &st1) >= 0);
443 assert_se(S_ISREG(st1.st_mode));
444
445 fl = fcntl(fd1, F_GETFL);
446 assert_se(fl >= 0);
447 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
448 assert_se(FLAGS_SET(fl, O_PATH));
449
450 assert_se(fd_reopen(fd1, O_RDONLY|O_DIRECTORY|O_CLOEXEC) == -ENOTDIR);
451 fd2 = fd_reopen(fd1, O_RDONLY|O_CLOEXEC); /* drop the O_PATH */
452 assert_se(fd2 >= 0);
453
454 assert_se(fstat(fd2, &st2) >= 0);
455 assert_se(S_ISREG(st2.st_mode));
456 assert_se(st1.st_ino == st2.st_ino);
457 assert_se(st1.st_rdev == st2.st_rdev);
458
459 fl = fcntl(fd2, F_GETFL);
460 assert_se(fl >= 0);
461 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
462 assert_se(!FLAGS_SET(fl, O_PATH));
463
464 safe_close(fd1);
465
466 assert_se(fd_reopen(fd2, O_DIRECTORY|O_PATH|O_CLOEXEC) == -ENOTDIR);
467 fd1 = fd_reopen(fd2, O_PATH|O_CLOEXEC); /* reacquire the O_PATH */
468 assert_se(fd1 >= 0);
469
470 assert_se(fstat(fd1, &st1) >= 0);
471 assert_se(S_ISREG(st1.st_mode));
472 assert_se(st1.st_ino == st2.st_ino);
473 assert_se(st1.st_rdev == st2.st_rdev);
474
475 fl = fcntl(fd1, F_GETFL);
476 assert_se(fl >= 0);
477 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
478 assert_se(FLAGS_SET(fl, O_PATH));
479
480 /* Also check the right error is generated if the fd is already closed */
481 safe_close(fd1);
482 assert_se(fd_reopen(fd1, O_RDONLY|O_CLOEXEC) == -EBADF);
483 fd1 = -1;
484 }
485
486 TEST(fd_reopen_condition) {
487 _cleanup_close_ int fd1 = -1, fd3 = -1;
488 int fd2, fl;
489
490 /* Open without O_PATH */
491 fd1 = open("/usr/", O_RDONLY|O_DIRECTORY|O_CLOEXEC);
492 assert_se(fd1 >= 0);
493
494 fl = fcntl(fd1, F_GETFL);
495 assert_se(FLAGS_SET(fl, O_DIRECTORY));
496 assert_se(!FLAGS_SET(fl, O_PATH));
497
498 fd2 = fd_reopen_condition(fd1, O_DIRECTORY, O_DIRECTORY|O_PATH, &fd3);
499 assert_se(fd2 == fd1);
500 assert_se(fd3 < 0);
501
502 /* Switch on O_PATH */
503 fd2 = fd_reopen_condition(fd1, O_DIRECTORY|O_PATH, O_DIRECTORY|O_PATH, &fd3);
504 assert_se(fd2 != fd1);
505 assert_se(fd3 == fd2);
506
507 fl = fcntl(fd2, F_GETFL);
508 assert_se(FLAGS_SET(fl, O_DIRECTORY));
509 assert_se(FLAGS_SET(fl, O_PATH));
510
511 close_and_replace(fd1, fd3);
512
513 fd2 = fd_reopen_condition(fd1, O_DIRECTORY|O_PATH, O_DIRECTORY|O_PATH, &fd3);
514 assert_se(fd2 == fd1);
515 assert_se(fd3 < 0);
516
517 /* Switch off O_PATH again */
518 fd2 = fd_reopen_condition(fd1, O_DIRECTORY, O_DIRECTORY|O_PATH, &fd3);
519 assert_se(fd2 != fd1);
520 assert_se(fd3 == fd2);
521
522 fl = fcntl(fd2, F_GETFL);
523 assert_se(FLAGS_SET(fl, O_DIRECTORY));
524 assert_se(!FLAGS_SET(fl, O_PATH));
525
526 close_and_replace(fd1, fd3);
527
528 fd2 = fd_reopen_condition(fd1, O_DIRECTORY, O_DIRECTORY|O_PATH, &fd3);
529 assert_se(fd2 == fd1);
530 assert_se(fd3 < 0);
531 }
532
533 TEST(take_fd) {
534 _cleanup_close_ int fd1 = -1, fd2 = -1;
535 int array[2] = { -1, -1 }, i = 0;
536
537 assert_se(fd1 == -1);
538 assert_se(fd2 == -1);
539
540 fd1 = eventfd(0, EFD_CLOEXEC);
541 assert_se(fd1 >= 0);
542
543 fd2 = TAKE_FD(fd1);
544 assert_se(fd1 == -1);
545 assert_se(fd2 >= 0);
546
547 assert_se(array[0] == -1);
548 assert_se(array[1] == -1);
549
550 array[0] = TAKE_FD(fd2);
551 assert_se(fd1 == -1);
552 assert_se(fd2 == -1);
553 assert_se(array[0] >= 0);
554 assert_se(array[1] == -1);
555
556 array[1] = TAKE_FD(array[i]);
557 assert_se(array[0] == -1);
558 assert_se(array[1] >= 0);
559
560 i = 1 - i;
561 array[0] = TAKE_FD(*(array + i));
562 assert_se(array[0] >= 0);
563 assert_se(array[1] == -1);
564
565 i = 1 - i;
566 fd1 = TAKE_FD(array[i]);
567 assert_se(fd1 >= 0);
568 assert_se(array[0] == -1);
569 assert_se(array[1] == -1);
570 }
571
572 DEFINE_TEST_MAIN(LOG_DEBUG);