]>
Commit | Line | Data |
---|---|---|
b7f28ac5 ZJS |
1 | /*** |
2 | SPDX-License-Identifier: LGPL-2.1+ | |
b7f28ac5 ZJS |
3 | ***/ |
4 | ||
5 | #include <fcntl.h> | |
6 | #include <signal.h> | |
7 | #include <sys/prctl.h> | |
8 | #include <sys/stat.h> | |
9 | #include <sys/types.h> | |
10 | #include <unistd.h> | |
11 | ||
12 | #include "alloc-util.h" | |
13 | #include "dissect-image.h" | |
5e332028 | 14 | #include "main-func.h" |
dccca82b | 15 | #include "process-util.h" |
b7f28ac5 ZJS |
16 | #include "signal-util.h" |
17 | #include "string-util.h" | |
18 | ||
19 | static int makefs(const char *type, const char *device) { | |
20 | const char *mkfs; | |
21 | pid_t pid; | |
4c253ed1 | 22 | int r; |
b7f28ac5 ZJS |
23 | |
24 | if (streq(type, "swap")) | |
25 | mkfs = "/sbin/mkswap"; | |
26 | else | |
27 | mkfs = strjoina("/sbin/mkfs.", type); | |
28 | if (access(mkfs, X_OK) != 0) | |
29 | return log_error_errno(errno, "%s is not executable: %m", mkfs); | |
30 | ||
ae188906 | 31 | r = safe_fork("(mkfs)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); |
4c253ed1 | 32 | if (r < 0) |
b6e1fff1 | 33 | return r; |
4c253ed1 | 34 | if (r == 0) { |
b7f28ac5 ZJS |
35 | const char *cmdline[3] = { mkfs, device, NULL }; |
36 | ||
37 | /* Child */ | |
38 | ||
b7f28ac5 ZJS |
39 | execv(cmdline[0], (char**) cmdline); |
40 | _exit(EXIT_FAILURE); | |
41 | } | |
42 | ||
7d4904fe | 43 | return wait_for_terminate_and_check(mkfs, pid, WAIT_LOG); |
b7f28ac5 ZJS |
44 | } |
45 | ||
fb1fa5a8 | 46 | static int run(int argc, char *argv[]) { |
b7f28ac5 ZJS |
47 | const char *device, *type; |
48 | _cleanup_free_ char *detected = NULL; | |
49 | struct stat st; | |
50 | int r; | |
51 | ||
6bf3c61c | 52 | log_setup_service(); |
b7f28ac5 | 53 | |
baaa35ad ZJS |
54 | if (argc != 3) |
55 | return log_error_errno(SYNTHETIC_ERRNO(EINVAL), | |
56 | "This program expects two arguments."); | |
b7f28ac5 ZJS |
57 | |
58 | type = argv[1]; | |
59 | device = argv[2]; | |
60 | ||
fb1fa5a8 ZJS |
61 | if (stat(device, &st) < 0) |
62 | return log_error_errno(errno, "Failed to stat \"%s\": %m", device); | |
b7f28ac5 ZJS |
63 | |
64 | if (!S_ISBLK(st.st_mode)) | |
65 | log_info("%s is not a block device.", device); | |
66 | ||
67 | r = probe_filesystem(device, &detected); | |
fb1fa5a8 ZJS |
68 | if (r < 0) |
69 | return log_warning_errno(r, | |
70 | r == -EUCLEAN ? | |
71 | "Cannot reliably determine probe \"%s\", refusing to proceed." : | |
72 | "Failed to probe \"%s\": %m", | |
73 | device); | |
b7f28ac5 ZJS |
74 | |
75 | if (detected) { | |
76 | log_info("%s is not empty (type %s), exiting", device, detected); | |
fb1fa5a8 | 77 | return 0; |
b7f28ac5 ZJS |
78 | } |
79 | ||
fb1fa5a8 | 80 | return makefs(type, device); |
b7f28ac5 | 81 | } |
fb1fa5a8 ZJS |
82 | |
83 | DEFINE_MAIN_FUNCTION(run); |