]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/systemctl/fuzz-systemctl-parse-argv.c
Merge pull request #18007 from fw-strlen/ipv6_masq_and_dnat
[thirdparty/systemd.git] / src / systemctl / fuzz-systemctl-parse-argv.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdio.h>
4 #include <unistd.h>
5
6 #include "env-util.h"
7 #include "fd-util.h"
8 #include "fuzz.h"
9 #include "selinux-util.h"
10 #include "static-destruct.h"
11 #include "stdio-util.h"
12 #include "strv.h"
13 #include "systemctl.h"
14 #include "systemctl-util.h"
15
16 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
17 _cleanup_strv_free_ char **argv = NULL;
18 _cleanup_close_ int orig_stdout_fd = -1;
19 int r;
20
21 /* We don't want to fill the logs with messages about parse errors.
22 * Disable most logging if not running standalone */
23 if (!getenv("SYSTEMD_LOG_LEVEL"))
24 log_set_max_level(LOG_CRIT);
25
26 arg_pager_flags = PAGER_DISABLE; /* We shouldn't execute the pager */
27
28 argv = strv_parse_nulstr((const char *)data, size);
29 if (!argv)
30 return log_oom();
31
32 if (!argv[0])
33 return 0; /* argv[0] should always be present, but may be zero-length. */
34
35 if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0) {
36 orig_stdout_fd = fcntl(fileno(stdout), F_DUPFD_CLOEXEC, 3);
37 if (orig_stdout_fd < 0)
38 log_warning_errno(orig_stdout_fd, "Failed to duplicate fd 1: %m");
39 else
40 assert_se(freopen("/dev/null", "w", stdout));
41
42 opterr = 0; /* do not print errors */
43 }
44
45 optind = 0; /* this tells the getopt machinery to reinitialize */
46
47 r = systemctl_dispatch_parse_argv(strv_length(argv), argv);
48 if (r < 0)
49 log_error_errno(r, "Failed to parse args: %m");
50 else
51 log_info(r == 0 ? "Done!" : "Action!");
52
53 if (orig_stdout_fd >= 0) {
54 char path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
55
56 xsprintf(path, "/proc/self/fd/%d", orig_stdout_fd);
57 assert_se(freopen(path, "w", stdout));
58 }
59
60 release_busses(); /* We open the bus for communication with logind.
61 * It needs to be closed to avoid apparent leaks. */
62
63 mac_selinux_finish();
64
65 /* Call static destructors to do global state cleanup. We do it here, and not in fuzz-main.c so that
66 * any global state is destoyed between fuzzer runs. */
67 static_destruct();
68
69 return 0;
70 }