]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/partition/makefs.c
basic/log: add concept of "synthethic errnos"
[thirdparty/systemd.git] / src / partition / makefs.c
1 /***
2 SPDX-License-Identifier: LGPL-2.1+
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"
14 #include "main-func.h"
15 #include "process-util.h"
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;
22 int r;
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
31 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
32 if (r < 0)
33 return r;
34 if (r == 0) {
35 const char *cmdline[3] = { mkfs, device, NULL };
36
37 /* Child */
38
39 execv(cmdline[0], (char**) cmdline);
40 _exit(EXIT_FAILURE);
41 }
42
43 return wait_for_terminate_and_check(mkfs, pid, WAIT_LOG);
44 }
45
46 static int run(int argc, char *argv[]) {
47 const char *device, *type;
48 _cleanup_free_ char *detected = NULL;
49 struct stat st;
50 int r;
51
52 log_setup_service();
53
54 if (argc != 3) {
55 log_error("This program expects two arguments.");
56 return -EINVAL;
57 }
58
59 type = argv[1];
60 device = argv[2];
61
62 if (stat(device, &st) < 0)
63 return log_error_errno(errno, "Failed to stat \"%s\": %m", device);
64
65 if (!S_ISBLK(st.st_mode))
66 log_info("%s is not a block device.", device);
67
68 r = probe_filesystem(device, &detected);
69 if (r < 0)
70 return log_warning_errno(r,
71 r == -EUCLEAN ?
72 "Cannot reliably determine probe \"%s\", refusing to proceed." :
73 "Failed to probe \"%s\": %m",
74 device);
75
76 if (detected) {
77 log_info("%s is not empty (type %s), exiting", device, detected);
78 return 0;
79 }
80
81 return makefs(type, device);
82 }
83
84 DEFINE_MAIN_FUNCTION(run);