]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/partition/makefs.c
tree-wide: beautify remaining copyright statements
[thirdparty/systemd.git] / src / partition / makefs.c
1 /***
2 SPDX-License-Identifier: LGPL-2.1+
3
4 Copyright © 2017 Zbigniew Jędrzejewski-Szmek
5 ***/
6
7 #include <fcntl.h>
8 #include <signal.h>
9 #include <sys/prctl.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13
14 #include "alloc-util.h"
15 #include "dissect-image.h"
16 #include "process-util.h"
17 #include "signal-util.h"
18 #include "string-util.h"
19
20 static int makefs(const char *type, const char *device) {
21 const char *mkfs;
22 pid_t pid;
23 int r;
24
25 if (streq(type, "swap"))
26 mkfs = "/sbin/mkswap";
27 else
28 mkfs = strjoina("/sbin/mkfs.", type);
29 if (access(mkfs, X_OK) != 0)
30 return log_error_errno(errno, "%s is not executable: %m", mkfs);
31
32 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
33 if (r < 0)
34 return r;
35 if (r == 0) {
36 const char *cmdline[3] = { mkfs, device, NULL };
37
38 /* Child */
39
40 execv(cmdline[0], (char**) cmdline);
41 _exit(EXIT_FAILURE);
42 }
43
44 return wait_for_terminate_and_check(mkfs, pid, WAIT_LOG);
45 }
46
47 int main(int argc, char *argv[]) {
48 const char *device, *type;
49 _cleanup_free_ char *detected = NULL;
50 struct stat st;
51 int r;
52
53 log_set_target(LOG_TARGET_AUTO);
54 log_parse_environment();
55 log_open();
56
57 if (argc != 3) {
58 log_error("This program expects two arguments.");
59 return EXIT_FAILURE;
60 }
61
62 type = argv[1];
63 device = argv[2];
64
65 if (stat(device, &st) < 0) {
66 r = log_error_errno(errno, "Failed to stat \"%s\": %m", device);
67 goto finish;
68 }
69
70 if (!S_ISBLK(st.st_mode))
71 log_info("%s is not a block device.", device);
72
73 r = probe_filesystem(device, &detected);
74 if (r < 0) {
75 log_warning_errno(r,
76 r == -EUCLEAN ?
77 "Cannot reliably determine probe \"%s\", refusing to proceed." :
78 "Failed to probe \"%s\": %m",
79 device);
80 goto finish;
81 }
82
83 if (detected) {
84 log_info("%s is not empty (type %s), exiting", device, detected);
85 goto finish;
86 }
87
88 r = makefs(type, device);
89
90 finish:
91 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
92 }