Debian Codegraph @

src/growfs/makefs.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/file.h>
5 #include <sys/stat.h>
6
7 #include "alloc-util.h"
8 #include "blockdev-util.h"
9 #include "dissect-image.h"
10 #include "fd-util.h"
11 #include "log.h"
12 #include "main-func.h"
13 #include "mkfs-util.h"
14 #include "path-util.h"
15
16 static int run(int argc, char *argv[]) {
17 _cleanup_free_ char *device = NULL, *fstype = NULL, *detected = NULL, *label = NULL;
18 _cleanup_close_ int lock_fd = -EBADF;
19 sd_id128_t uuid;
20 struct stat st;
21 int r;
22
23 log_setup();
24
25 if (argc != 3)
26 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
27 "This program expects two arguments.");
28
29 /* type and device must be copied because makefs calls safe_fork, which clears argv[] */
30 fstype = strdup(argv[1]);
31 if (!fstype)
32 return log_oom();
33
34 device = strdup(argv[2]);
35 if (!device)
36 return log_oom();
37
38 if (stat(device, &st) < 0)
39 return log_error_errno(errno, "Failed to stat \"%s\": %m", device);
40
41 if (S_ISBLK(st.st_mode)) {
42 /* Lock the device so that udev doesn't interfere with our work */
43
44 lock_fd = lock_whole_block_device(st.st_rdev, O_WRONLY, LOCK_EX);
45 if (lock_fd < 0)
46 return log_error_errno(lock_fd, "Failed to lock whole block device of \"%s\": %m", device);
47 } else
48 log_debug("%s is not a block device, no need to lock.", device);
49
50 r = probe_filesystem(device, &detected);
51 if (r == -EUCLEAN)
52 return log_error_errno(r, "Ambiguous results of probing for file system on \"%s\", refusing to proceed.", device);
53 if (r < 0)
54 return log_error_errno(r, "Failed to probe \"%s\": %m", device);
55 if (detected) {
56 log_info("'%s' is not empty (contains file system of type %s), exiting.", device, detected);
57 return 0;
58 }
59
60 r = sd_id128_randomize(&uuid);
61 if (r < 0)
62 return log_error_errno(r, "Failed to generate UUID for file system: %m");
63
64 r = path_extract_filename(device, &label);
65 if (r < 0)
66 return log_error_errno(r, "Failed to extract file name from '%s': %m", device);
67
68 return make_filesystem(device,
69 fstype,
70 label,
71 /* root= */ NULL,
72 uuid,
73 MKFS_DISCARD | MKFS_QUIET,
74 /* sector_size= */ 0,
75 /* compression= */ NULL,
76 /* compression_level= */ NULL,
77 /* extra_mkfs_options= */ NULL);
78 }
79
80 DEFINE_MAIN_FUNCTION(run);