]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine-id-setup/machine-id-setup-main.c
4471d5fe524197f63eeb76f94b2d28511cb0831c
[thirdparty/systemd.git] / src / machine-id-setup / machine-id-setup-main.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2010 Lennart Poettering
4 ***/
5
6 #include <errno.h>
7 #include <getopt.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 #include "id128-util.h"
12 #include "log.h"
13 #include "machine-id-setup.h"
14 #include "path-util.h"
15 #include "util.h"
16
17 static char *arg_root = NULL;
18 static bool arg_commit = false;
19 static bool arg_print = false;
20
21 static void help(void) {
22 printf("%s [OPTIONS...]\n\n"
23 "Initialize /etc/machine-id from a random source.\n\n"
24 " -h --help Show this help\n"
25 " --version Show package version\n"
26 " --root=ROOT Filesystem root\n"
27 " --commit Commit transient ID\n"
28 " --print Print used machine ID\n"
29 , program_invocation_short_name);
30 }
31
32 static int parse_argv(int argc, char *argv[]) {
33
34 enum {
35 ARG_VERSION = 0x100,
36 ARG_ROOT,
37 ARG_COMMIT,
38 ARG_PRINT,
39 };
40
41 static const struct option options[] = {
42 { "help", no_argument, NULL, 'h' },
43 { "version", no_argument, NULL, ARG_VERSION },
44 { "root", required_argument, NULL, ARG_ROOT },
45 { "commit", no_argument, NULL, ARG_COMMIT },
46 { "print", no_argument, NULL, ARG_PRINT },
47 {}
48 };
49
50 int c, r;
51
52 assert(argc >= 0);
53 assert(argv);
54
55 while ((c = getopt_long(argc, argv, "hqcv", options, NULL)) >= 0)
56
57 switch (c) {
58
59 case 'h':
60 help();
61 return 0;
62
63 case ARG_VERSION:
64 return version();
65
66 case ARG_ROOT:
67 r = parse_path_argument_and_warn(optarg, true, &arg_root);
68 if (r < 0)
69 return r;
70 break;
71
72 case ARG_COMMIT:
73 arg_commit = true;
74 break;
75
76 case ARG_PRINT:
77 arg_print = true;
78 break;
79
80 case '?':
81 return -EINVAL;
82
83 default:
84 assert_not_reached("Unhandled option");
85 }
86
87 if (optind < argc) {
88 log_error("Extraneous arguments");
89 return -EINVAL;
90 }
91
92 return 1;
93 }
94
95 int main(int argc, char *argv[]) {
96 char buf[SD_ID128_STRING_MAX];
97 sd_id128_t id;
98 int r;
99
100 log_parse_environment();
101 log_open();
102
103 r = parse_argv(argc, argv);
104 if (r <= 0)
105 goto finish;
106
107 if (arg_commit) {
108 const char *etc_machine_id;
109
110 r = machine_id_commit(arg_root);
111 if (r < 0)
112 goto finish;
113
114 etc_machine_id = prefix_roota(arg_root, "/etc/machine-id");
115 r = id128_read(etc_machine_id, ID128_PLAIN, &id);
116 if (r < 0) {
117 log_error_errno(r, "Failed to read machine ID back: %m");
118 goto finish;
119 }
120 } else {
121 r = machine_id_setup(arg_root, SD_ID128_NULL, &id);
122 if (r < 0)
123 goto finish;
124 }
125
126 if (arg_print)
127 puts(sd_id128_to_string(id, buf));
128
129 finish:
130 free(arg_root);
131 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
132 }