1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <string.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <unistd.h>
8 
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-locator.h"
12 #include "bus-log-control-api.h"
13 #include "bus-polkit.h"
14 #include "cgroup-util.h"
15 #include "daemon-util.h"
16 #include "dirent-util.h"
17 #include "discover-image.h"
18 #include "fd-util.h"
19 #include "format-util.h"
20 #include "hostname-util.h"
21 #include "machined-varlink.h"
22 #include "machined.h"
23 #include "main-func.h"
24 #include "mkdir-label.h"
25 #include "process-util.h"
26 #include "service-util.h"
27 #include "signal-util.h"
28 #include "special.h"
29 
30 static Manager* manager_unref(Manager *m);
31 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_unref);
32 
33 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(machine_hash_ops, char, string_hash_func, string_compare_func, Machine, machine_free);
34 
manager_new(Manager ** ret)35 static int manager_new(Manager **ret) {
36         _cleanup_(manager_unrefp) Manager *m = NULL;
37         int r;
38 
39         assert(ret);
40 
41         m = new0(Manager, 1);
42         if (!m)
43                 return -ENOMEM;
44 
45         m->machines = hashmap_new(&machine_hash_ops);
46         m->machine_units = hashmap_new(&string_hash_ops);
47         m->machine_leaders = hashmap_new(NULL);
48 
49         if (!m->machines || !m->machine_units || !m->machine_leaders)
50                 return -ENOMEM;
51 
52         r = sd_event_default(&m->event);
53         if (r < 0)
54                 return r;
55 
56         r = sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
57         if (r < 0)
58                 return r;
59 
60         r = sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
61         if (r < 0)
62                 return r;
63 
64         (void) sd_event_set_watchdog(m->event, true);
65 
66         *ret = TAKE_PTR(m);
67         return 0;
68 }
69 
manager_unref(Manager * m)70 static Manager* manager_unref(Manager *m) {
71         if (!m)
72                 return NULL;
73 
74         while (m->operations)
75                 operation_free(m->operations);
76 
77         assert(m->n_operations == 0);
78 
79         hashmap_free(m->machines); /* This will free all machines, so that the machine_units/machine_leaders is empty */
80         hashmap_free(m->machine_units);
81         hashmap_free(m->machine_leaders);
82         hashmap_free(m->image_cache);
83 
84         sd_event_source_unref(m->image_cache_defer_event);
85 #if ENABLE_NSCD
86         sd_event_source_unref(m->nscd_cache_flush_event);
87 #endif
88 
89         bus_verify_polkit_async_registry_free(m->polkit_registry);
90 
91         manager_varlink_done(m);
92 
93         sd_bus_flush_close_unref(m->bus);
94         sd_event_unref(m->event);
95 
96         return mfree(m);
97 }
98 
manager_add_host_machine(Manager * m)99 static int manager_add_host_machine(Manager *m) {
100         _cleanup_free_ char *rd = NULL, *unit = NULL;
101         sd_id128_t mid;
102         Machine *t;
103         int r;
104 
105         if (m->host_machine)
106                 return 0;
107 
108         r = sd_id128_get_machine(&mid);
109         if (r < 0)
110                 return log_error_errno(r, "Failed to get machine ID: %m");
111 
112         rd = strdup("/");
113         if (!rd)
114                 return log_oom();
115 
116         unit = strdup(SPECIAL_ROOT_SLICE);
117         if (!unit)
118                 return log_oom();
119 
120         t = machine_new(m, MACHINE_HOST, ".host");
121         if (!t)
122                 return log_oom();
123 
124         t->leader = 1;
125         t->id = mid;
126 
127         t->root_directory = TAKE_PTR(rd);
128         t->unit = TAKE_PTR(unit);
129 
130         dual_timestamp_from_boottime(&t->timestamp, 0);
131 
132         m->host_machine = t;
133 
134         return 0;
135 }
136 
manager_enumerate_machines(Manager * m)137 static int manager_enumerate_machines(Manager *m) {
138         _cleanup_closedir_ DIR *d = NULL;
139         int r;
140 
141         assert(m);
142 
143         r = manager_add_host_machine(m);
144         if (r < 0)
145                 return r;
146 
147         /* Read in machine data stored on disk */
148         d = opendir("/run/systemd/machines");
149         if (!d) {
150                 if (errno == ENOENT)
151                         return 0;
152 
153                 return log_error_errno(errno, "Failed to open /run/systemd/machines: %m");
154         }
155 
156         FOREACH_DIRENT(de, d, return -errno) {
157                 struct Machine *machine;
158                 int k;
159 
160                 if (!dirent_is_file(de))
161                         continue;
162 
163                 /* Ignore symlinks that map the unit name to the machine */
164                 if (startswith(de->d_name, "unit:"))
165                         continue;
166 
167                 if (!hostname_is_valid(de->d_name, 0))
168                         continue;
169 
170                 k = manager_add_machine(m, de->d_name, &machine);
171                 if (k < 0) {
172                         r = log_error_errno(k, "Failed to add machine by file name %s: %m", de->d_name);
173                         continue;
174                 }
175 
176                 machine_add_to_gc_queue(machine);
177 
178                 k = machine_load(machine);
179                 if (k < 0)
180                         r = k;
181         }
182 
183         return r;
184 }
185 
manager_connect_bus(Manager * m)186 static int manager_connect_bus(Manager *m) {
187         int r;
188 
189         assert(m);
190         assert(!m->bus);
191 
192         r = sd_bus_default_system(&m->bus);
193         if (r < 0)
194                 return log_error_errno(r, "Failed to connect to system bus: %m");
195 
196         r = bus_add_implementation(m->bus, &manager_object, m);
197         if (r < 0)
198                 return r;
199 
200         r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "JobRemoved", match_job_removed, NULL, m);
201         if (r < 0)
202                 return log_error_errno(r, "Failed to add match for JobRemoved: %m");
203 
204         r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "UnitRemoved", match_unit_removed, NULL, m);
205         if (r < 0)
206                 return log_error_errno(r, "Failed to request match for UnitRemoved: %m");
207 
208         r = sd_bus_match_signal_async(
209                         m->bus,
210                         NULL,
211                         "org.freedesktop.systemd1",
212                         NULL,
213                         "org.freedesktop.DBus.Properties",
214                         "PropertiesChanged",
215                         match_properties_changed, NULL, m);
216         if (r < 0)
217                 return log_error_errno(r, "Failed to request match for PropertiesChanged: %m");
218 
219         r = bus_match_signal_async(m->bus, NULL, bus_systemd_mgr, "Reloading", match_reloading, NULL, m);
220         if (r < 0)
221                 return log_error_errno(r, "Failed to request match for Reloading: %m");
222 
223         r = bus_call_method_async(m->bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
224         if (r < 0)
225                 return log_error_errno(r, "Failed to enable subscription: %m");
226 
227         r = bus_log_control_api_register(m->bus);
228         if (r < 0)
229                 return r;
230 
231         r = sd_bus_request_name_async(m->bus, NULL, "org.freedesktop.machine1", 0, NULL, NULL);
232         if (r < 0)
233                 return log_error_errno(r, "Failed to request name: %m");
234 
235         r = sd_bus_attach_event(m->bus, m->event, 0);
236         if (r < 0)
237                 return log_error_errno(r, "Failed to attach bus to event loop: %m");
238 
239         return 0;
240 }
241 
manager_gc(Manager * m,bool drop_not_started)242 static void manager_gc(Manager *m, bool drop_not_started) {
243         Machine *machine;
244 
245         assert(m);
246 
247         while ((machine = m->machine_gc_queue)) {
248                 LIST_REMOVE(gc_queue, m->machine_gc_queue, machine);
249                 machine->in_gc_queue = false;
250 
251                 /* First, if we are not closing yet, initiate stopping */
252                 if (machine_may_gc(machine, drop_not_started) &&
253                     machine_get_state(machine) != MACHINE_CLOSING)
254                         machine_stop(machine);
255 
256                 /* Now, the stop probably made this referenced
257                  * again, but if it didn't, then it's time to let it
258                  * go entirely. */
259                 if (machine_may_gc(machine, drop_not_started)) {
260                         machine_finalize(machine);
261                         machine_free(machine);
262                 }
263         }
264 }
265 
manager_startup(Manager * m)266 static int manager_startup(Manager *m) {
267         Machine *machine;
268         int r;
269 
270         assert(m);
271 
272         /* Connect to the bus */
273         r = manager_connect_bus(m);
274         if (r < 0)
275                 return r;
276 
277         /* Set up Varlink service */
278         r = manager_varlink_init(m);
279         if (r < 0)
280                 return r;
281 
282         /* Deserialize state */
283         manager_enumerate_machines(m);
284 
285         /* Remove stale objects before we start them */
286         manager_gc(m, false);
287 
288         /* And start everything */
289         HASHMAP_FOREACH(machine, m->machines)
290                 machine_start(machine, NULL, NULL);
291 
292         return 0;
293 }
294 
check_idle(void * userdata)295 static bool check_idle(void *userdata) {
296         Manager *m = userdata;
297 
298         if (m->operations)
299                 return false;
300 
301         if (varlink_server_current_connections(m->varlink_server) > 0)
302                 return false;
303 
304         manager_gc(m, true);
305 
306         return hashmap_isempty(m->machines);
307 }
308 
manager_run(Manager * m)309 static int manager_run(Manager *m) {
310         assert(m);
311 
312         return bus_event_loop_with_idle(
313                         m->event,
314                         m->bus,
315                         "org.freedesktop.machine1",
316                         DEFAULT_EXIT_USEC,
317                         check_idle, m);
318 }
319 
run(int argc,char * argv[])320 static int run(int argc, char *argv[]) {
321         _cleanup_(manager_unrefp) Manager *m = NULL;
322         int r;
323 
324         log_set_facility(LOG_AUTH);
325         log_setup();
326 
327         r = service_parse_argv("systemd-machined.service",
328                                "Manage registrations of local VMs and containers.",
329                                BUS_IMPLEMENTATIONS(&manager_object,
330                                                    &log_control_object),
331                                argc, argv);
332         if (r <= 0)
333                 return r;
334 
335         umask(0022);
336 
337         /* Always create the directories people can create inotify watches in. Note that some applications might check
338          * for the existence of /run/systemd/machines/ to determine whether machined is available, so please always
339          * make sure this check stays in. */
340         (void) mkdir_label("/run/systemd/machines", 0755);
341 
342         assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, SIGTERM, SIGINT, -1) >= 0);
343 
344         r = manager_new(&m);
345         if (r < 0)
346                 return log_error_errno(r, "Failed to allocate manager object: %m");
347 
348         r = manager_startup(m);
349         if (r < 0)
350                 return log_error_errno(r, "Failed to fully start up daemon: %m");
351 
352         log_debug("systemd-machined running as pid "PID_FMT, getpid_cached());
353         r = sd_notify(false, NOTIFY_READY);
354         if (r < 0)
355                 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
356 
357         r = manager_run(m);
358 
359         (void) sd_notify(false, NOTIFY_STOPPING);
360         log_debug("systemd-machined stopped as pid "PID_FMT, getpid_cached());
361         return r;
362 }
363 
364 DEFINE_MAIN_FUNCTION(run);
365