]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/partition/makefs.c
tree-wide: beautify remaining copyright statements
[thirdparty/systemd.git] / src / partition / makefs.c
CommitLineData
b7f28ac5
ZJS
1/***
2 SPDX-License-Identifier: LGPL-2.1+
3
96b2fb93 4 Copyright © 2017 Zbigniew Jędrzejewski-Szmek
b7f28ac5
ZJS
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"
dccca82b 16#include "process-util.h"
b7f28ac5
ZJS
17#include "signal-util.h"
18#include "string-util.h"
19
20static int makefs(const char *type, const char *device) {
21 const char *mkfs;
22 pid_t pid;
4c253ed1 23 int r;
b7f28ac5
ZJS
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
b6e1fff1 32 r = safe_fork("(fsck)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
4c253ed1 33 if (r < 0)
b6e1fff1 34 return r;
4c253ed1 35 if (r == 0) {
b7f28ac5
ZJS
36 const char *cmdline[3] = { mkfs, device, NULL };
37
38 /* Child */
39
b7f28ac5
ZJS
40 execv(cmdline[0], (char**) cmdline);
41 _exit(EXIT_FAILURE);
42 }
43
7d4904fe 44 return wait_for_terminate_and_check(mkfs, pid, WAIT_LOG);
b7f28ac5
ZJS
45}
46
47int 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) {
7cc84b2c
ZJS
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);
b7f28ac5
ZJS
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
90finish:
91 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
92}