]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/machine/machine.c
tree-wide: drop string.h when string-util.h or friends are included
[thirdparty/systemd.git] / src / machine / machine.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <unistd.h>
5 #include <sys/stat.h>
6
7 #include "sd-messages.h"
8
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-util.h"
12 #include "env-file.h"
13 #include "errno-util.h"
14 #include "escape.h"
15 #include "extract-word.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "format-util.h"
19 #include "hashmap.h"
20 #include "machine-dbus.h"
21 #include "machine.h"
22 #include "mkdir.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
26 #include "serialize.h"
27 #include "special.h"
28 #include "stdio-util.h"
29 #include "string-table.h"
30 #include "terminal-util.h"
31 #include "tmpfile-util.h"
32 #include "unit-name.h"
33 #include "user-util.h"
34 #include "util.h"
35
36 Machine* machine_new(Manager *manager, MachineClass class, const char *name) {
37 Machine *m;
38
39 assert(manager);
40 assert(class < _MACHINE_CLASS_MAX);
41 assert(name);
42
43 /* Passing class == _MACHINE_CLASS_INVALID here is fine. It
44 * means as much as "we don't know yet", and that we'll figure
45 * it out later when loading the state file. */
46
47 m = new0(Machine, 1);
48 if (!m)
49 return NULL;
50
51 m->name = strdup(name);
52 if (!m->name)
53 goto fail;
54
55 if (class != MACHINE_HOST) {
56 m->state_file = path_join("/run/systemd/machines", m->name);
57 if (!m->state_file)
58 goto fail;
59 }
60
61 m->class = class;
62
63 if (hashmap_put(manager->machines, m->name, m) < 0)
64 goto fail;
65
66 m->manager = manager;
67
68 return m;
69
70 fail:
71 free(m->state_file);
72 free(m->name);
73 return mfree(m);
74 }
75
76 Machine* machine_free(Machine *m) {
77 if (!m)
78 return NULL;
79
80 while (m->operations)
81 operation_free(m->operations);
82
83 if (m->in_gc_queue)
84 LIST_REMOVE(gc_queue, m->manager->machine_gc_queue, m);
85
86 machine_release_unit(m);
87
88 free(m->scope_job);
89
90 (void) hashmap_remove(m->manager->machines, m->name);
91
92 if (m->manager->host_machine == m)
93 m->manager->host_machine = NULL;
94
95 if (m->leader > 0)
96 (void) hashmap_remove_value(m->manager->machine_leaders, PID_TO_PTR(m->leader), m);
97
98 sd_bus_message_unref(m->create_message);
99
100 free(m->name);
101 free(m->state_file);
102 free(m->service);
103 free(m->root_directory);
104 free(m->netif);
105 return mfree(m);
106 }
107
108 int machine_save(Machine *m) {
109 _cleanup_free_ char *temp_path = NULL;
110 _cleanup_fclose_ FILE *f = NULL;
111 int r;
112
113 assert(m);
114
115 if (!m->state_file)
116 return 0;
117
118 if (!m->started)
119 return 0;
120
121 r = mkdir_safe_label("/run/systemd/machines", 0755, 0, 0, MKDIR_WARN_MODE);
122 if (r < 0)
123 goto fail;
124
125 r = fopen_temporary(m->state_file, &f, &temp_path);
126 if (r < 0)
127 goto fail;
128
129 (void) fchmod(fileno(f), 0644);
130
131 fprintf(f,
132 "# This is private data. Do not parse.\n"
133 "NAME=%s\n",
134 m->name);
135
136 if (m->unit) {
137 _cleanup_free_ char *escaped;
138
139 escaped = cescape(m->unit);
140 if (!escaped) {
141 r = -ENOMEM;
142 goto fail;
143 }
144
145 fprintf(f, "SCOPE=%s\n", escaped); /* We continue to call this "SCOPE=" because it is internal only, and we want to stay compatible with old files */
146 }
147
148 if (m->scope_job)
149 fprintf(f, "SCOPE_JOB=%s\n", m->scope_job);
150
151 if (m->service) {
152 _cleanup_free_ char *escaped;
153
154 escaped = cescape(m->service);
155 if (!escaped) {
156 r = -ENOMEM;
157 goto fail;
158 }
159 fprintf(f, "SERVICE=%s\n", escaped);
160 }
161
162 if (m->root_directory) {
163 _cleanup_free_ char *escaped;
164
165 escaped = cescape(m->root_directory);
166 if (!escaped) {
167 r = -ENOMEM;
168 goto fail;
169 }
170 fprintf(f, "ROOT=%s\n", escaped);
171 }
172
173 if (!sd_id128_is_null(m->id))
174 fprintf(f, "ID=" SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->id));
175
176 if (m->leader != 0)
177 fprintf(f, "LEADER="PID_FMT"\n", m->leader);
178
179 if (m->class != _MACHINE_CLASS_INVALID)
180 fprintf(f, "CLASS=%s\n", machine_class_to_string(m->class));
181
182 if (dual_timestamp_is_set(&m->timestamp))
183 fprintf(f,
184 "REALTIME="USEC_FMT"\n"
185 "MONOTONIC="USEC_FMT"\n",
186 m->timestamp.realtime,
187 m->timestamp.monotonic);
188
189 if (m->n_netif > 0) {
190 size_t i;
191
192 fputs("NETIF=", f);
193
194 for (i = 0; i < m->n_netif; i++) {
195 if (i != 0)
196 fputc(' ', f);
197
198 fprintf(f, "%i", m->netif[i]);
199 }
200
201 fputc('\n', f);
202 }
203
204 r = fflush_and_check(f);
205 if (r < 0)
206 goto fail;
207
208 if (rename(temp_path, m->state_file) < 0) {
209 r = -errno;
210 goto fail;
211 }
212
213 if (m->unit) {
214 char *sl;
215
216 /* Create a symlink from the unit name to the machine
217 * name, so that we can quickly find the machine for
218 * each given unit. Ignore error. */
219 sl = strjoina("/run/systemd/machines/unit:", m->unit);
220 (void) symlink(m->name, sl);
221 }
222
223 return 0;
224
225 fail:
226 (void) unlink(m->state_file);
227
228 if (temp_path)
229 (void) unlink(temp_path);
230
231 return log_error_errno(r, "Failed to save machine data %s: %m", m->state_file);
232 }
233
234 static void machine_unlink(Machine *m) {
235 assert(m);
236
237 if (m->unit) {
238 char *sl;
239
240 sl = strjoina("/run/systemd/machines/unit:", m->unit);
241 (void) unlink(sl);
242 }
243
244 if (m->state_file)
245 (void) unlink(m->state_file);
246 }
247
248 int machine_load(Machine *m) {
249 _cleanup_free_ char *realtime = NULL, *monotonic = NULL, *id = NULL, *leader = NULL, *class = NULL, *netif = NULL;
250 int r;
251
252 assert(m);
253
254 if (!m->state_file)
255 return 0;
256
257 r = parse_env_file(NULL, m->state_file,
258 "SCOPE", &m->unit,
259 "SCOPE_JOB", &m->scope_job,
260 "SERVICE", &m->service,
261 "ROOT", &m->root_directory,
262 "ID", &id,
263 "LEADER", &leader,
264 "CLASS", &class,
265 "REALTIME", &realtime,
266 "MONOTONIC", &monotonic,
267 "NETIF", &netif);
268 if (r < 0) {
269 if (r == -ENOENT)
270 return 0;
271
272 return log_error_errno(r, "Failed to read %s: %m", m->state_file);
273 }
274
275 if (id)
276 sd_id128_from_string(id, &m->id);
277
278 if (leader)
279 parse_pid(leader, &m->leader);
280
281 if (class) {
282 MachineClass c;
283
284 c = machine_class_from_string(class);
285 if (c >= 0)
286 m->class = c;
287 }
288
289 if (realtime)
290 (void) deserialize_usec(realtime, &m->timestamp.realtime);
291 if (monotonic)
292 (void) deserialize_usec(monotonic, &m->timestamp.monotonic);
293
294 if (netif) {
295 size_t allocated = 0, nr = 0;
296 const char *p;
297 int *ni = NULL;
298
299 p = netif;
300 for (;;) {
301 _cleanup_free_ char *word = NULL;
302 int ifi;
303
304 r = extract_first_word(&p, &word, NULL, 0);
305 if (r == 0)
306 break;
307 if (r == -ENOMEM)
308 return log_oom();
309 if (r < 0) {
310 log_warning_errno(r, "Failed to parse NETIF: %s", netif);
311 break;
312 }
313
314 if (parse_ifindex(word, &ifi) < 0)
315 continue;
316
317 if (!GREEDY_REALLOC(ni, allocated, nr+1)) {
318 free(ni);
319 return log_oom();
320 }
321
322 ni[nr++] = ifi;
323 }
324
325 free(m->netif);
326 m->netif = ni;
327 m->n_netif = nr;
328 }
329
330 return r;
331 }
332
333 static int machine_start_scope(Machine *m, sd_bus_message *properties, sd_bus_error *error) {
334 assert(m);
335 assert(m->class != MACHINE_HOST);
336
337 if (!m->unit) {
338 _cleanup_free_ char *escaped = NULL, *scope = NULL;
339 char *description, *job = NULL;
340 int r;
341
342 escaped = unit_name_escape(m->name);
343 if (!escaped)
344 return log_oom();
345
346 scope = strjoin("machine-", escaped, ".scope");
347 if (!scope)
348 return log_oom();
349
350 description = strjoina(m->class == MACHINE_VM ? "Virtual Machine " : "Container ", m->name);
351
352 r = manager_start_scope(m->manager, scope, m->leader, SPECIAL_MACHINE_SLICE, description, properties, error, &job);
353 if (r < 0)
354 return log_error_errno(r, "Failed to start machine scope: %s", bus_error_message(error, r));
355
356 m->unit = TAKE_PTR(scope);
357 m->referenced = true;
358 free_and_replace(m->scope_job, job);
359 }
360
361 if (m->unit)
362 hashmap_put(m->manager->machine_units, m->unit, m);
363
364 return 0;
365 }
366
367 int machine_start(Machine *m, sd_bus_message *properties, sd_bus_error *error) {
368 int r;
369
370 assert(m);
371
372 if (!IN_SET(m->class, MACHINE_CONTAINER, MACHINE_VM))
373 return -EOPNOTSUPP;
374
375 if (m->started)
376 return 0;
377
378 r = hashmap_put(m->manager->machine_leaders, PID_TO_PTR(m->leader), m);
379 if (r < 0)
380 return r;
381
382 /* Create cgroup */
383 r = machine_start_scope(m, properties, error);
384 if (r < 0)
385 return r;
386
387 log_struct(LOG_INFO,
388 "MESSAGE_ID=" SD_MESSAGE_MACHINE_START_STR,
389 "NAME=%s", m->name,
390 "LEADER="PID_FMT, m->leader,
391 LOG_MESSAGE("New machine %s.", m->name));
392
393 if (!dual_timestamp_is_set(&m->timestamp))
394 dual_timestamp_get(&m->timestamp);
395
396 m->started = true;
397
398 /* Save new machine data */
399 machine_save(m);
400
401 machine_send_signal(m, true);
402 (void) manager_enqueue_nscd_cache_flush(m->manager);
403
404 return 0;
405 }
406
407 static int machine_stop_scope(Machine *m) {
408 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
409 char *job = NULL;
410 int r, q;
411
412 assert(m);
413 assert(m->class != MACHINE_HOST);
414
415 if (!m->unit)
416 return 0;
417
418 r = manager_stop_unit(m->manager, m->unit, &error, &job);
419 if (r < 0) {
420 log_error_errno(r, "Failed to stop machine scope: %s", bus_error_message(&error, r));
421 sd_bus_error_free(&error);
422 } else
423 free_and_replace(m->scope_job, job);
424
425 if (m->referenced) {
426 q = manager_unref_unit(m->manager, m->unit, &error);
427 if (q < 0)
428 log_warning_errno(q, "Failed to drop reference to machine scope, ignoring: %s", bus_error_message(&error, r));
429 m->referenced = false;
430 }
431
432 return r;
433 }
434
435 int machine_stop(Machine *m) {
436 int r;
437 assert(m);
438
439 if (!IN_SET(m->class, MACHINE_CONTAINER, MACHINE_VM))
440 return -EOPNOTSUPP;
441
442 r = machine_stop_scope(m);
443
444 m->stopping = true;
445
446 machine_save(m);
447 (void) manager_enqueue_nscd_cache_flush(m->manager);
448
449 return r;
450 }
451
452 int machine_finalize(Machine *m) {
453 assert(m);
454
455 if (m->started) {
456 log_struct(LOG_INFO,
457 "MESSAGE_ID=" SD_MESSAGE_MACHINE_STOP_STR,
458 "NAME=%s", m->name,
459 "LEADER="PID_FMT, m->leader,
460 LOG_MESSAGE("Machine %s terminated.", m->name));
461
462 m->stopping = true; /* The machine is supposed to be going away. Don't try to kill it. */
463 }
464
465 machine_unlink(m);
466 machine_add_to_gc_queue(m);
467
468 if (m->started) {
469 machine_send_signal(m, false);
470 m->started = false;
471 }
472
473 return 0;
474 }
475
476 bool machine_may_gc(Machine *m, bool drop_not_started) {
477 assert(m);
478
479 if (m->class == MACHINE_HOST)
480 return false;
481
482 if (drop_not_started && !m->started)
483 return true;
484
485 if (m->scope_job && manager_job_is_active(m->manager, m->scope_job))
486 return false;
487
488 if (m->unit && manager_unit_is_active(m->manager, m->unit))
489 return false;
490
491 return true;
492 }
493
494 void machine_add_to_gc_queue(Machine *m) {
495 assert(m);
496
497 if (m->in_gc_queue)
498 return;
499
500 LIST_PREPEND(gc_queue, m->manager->machine_gc_queue, m);
501 m->in_gc_queue = true;
502 }
503
504 MachineState machine_get_state(Machine *s) {
505 assert(s);
506
507 if (s->class == MACHINE_HOST)
508 return MACHINE_RUNNING;
509
510 if (s->stopping)
511 return MACHINE_CLOSING;
512
513 if (s->scope_job)
514 return MACHINE_OPENING;
515
516 return MACHINE_RUNNING;
517 }
518
519 int machine_kill(Machine *m, KillWho who, int signo) {
520 assert(m);
521
522 if (!IN_SET(m->class, MACHINE_VM, MACHINE_CONTAINER))
523 return -EOPNOTSUPP;
524
525 if (!m->unit)
526 return -ESRCH;
527
528 if (who == KILL_LEADER) {
529 /* If we shall simply kill the leader, do so directly */
530
531 if (kill(m->leader, signo) < 0)
532 return -errno;
533
534 return 0;
535 }
536
537 /* Otherwise, make PID 1 do it for us, for the entire cgroup */
538 return manager_kill_unit(m->manager, m->unit, signo, NULL);
539 }
540
541 int machine_openpt(Machine *m, int flags, char **ret_slave) {
542 assert(m);
543
544 switch (m->class) {
545
546 case MACHINE_HOST:
547
548 return openpt_allocate(flags, ret_slave);
549
550 case MACHINE_CONTAINER:
551 if (m->leader <= 0)
552 return -EINVAL;
553
554 return openpt_allocate_in_namespace(m->leader, flags, ret_slave);
555
556 default:
557 return -EOPNOTSUPP;
558 }
559 }
560
561 int machine_open_terminal(Machine *m, const char *path, int mode) {
562 assert(m);
563
564 switch (m->class) {
565
566 case MACHINE_HOST:
567 return open_terminal(path, mode);
568
569 case MACHINE_CONTAINER:
570 if (m->leader <= 0)
571 return -EINVAL;
572
573 return open_terminal_in_namespace(m->leader, path, mode);
574
575 default:
576 return -EOPNOTSUPP;
577 }
578 }
579
580 void machine_release_unit(Machine *m) {
581 assert(m);
582
583 if (!m->unit)
584 return;
585
586 (void) hashmap_remove(m->manager->machine_units, m->unit);
587 m->unit = mfree(m->unit);
588 }
589
590 int machine_get_uid_shift(Machine *m, uid_t *ret) {
591 char p[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t) + 1];
592 uid_t uid_base, uid_shift, uid_range;
593 gid_t gid_base, gid_shift, gid_range;
594 _cleanup_fclose_ FILE *f = NULL;
595 int k, r;
596
597 assert(m);
598 assert(ret);
599
600 /* Return the base UID/GID of the specified machine. Note that this only works for containers with simple
601 * mappings. In most cases setups should be simple like this, and administrators should only care about the
602 * basic offset a container has relative to the host. This is what this function exposes.
603 *
604 * If we encounter any more complex mappings we politely refuse this with ENXIO. */
605
606 if (m->class == MACHINE_HOST) {
607 *ret = 0;
608 return 0;
609 }
610
611 if (m->class != MACHINE_CONTAINER)
612 return -EOPNOTSUPP;
613
614 xsprintf(p, "/proc/" PID_FMT "/uid_map", m->leader);
615 f = fopen(p, "re");
616 if (!f) {
617 if (errno == ENOENT) {
618 /* If the file doesn't exist, user namespacing is off in the kernel, return a zero mapping hence. */
619 *ret = 0;
620 return 0;
621 }
622
623 return -errno;
624 }
625
626 /* Read the first line. There's at least one. */
627 errno = 0;
628 k = fscanf(f, UID_FMT " " UID_FMT " " UID_FMT "\n", &uid_base, &uid_shift, &uid_range);
629 if (k != 3) {
630 if (ferror(f))
631 return errno_or_else(EIO);
632
633 return -EBADMSG;
634 }
635
636 /* Not a mapping starting at 0? Then it's a complex mapping we can't expose here. */
637 if (uid_base != 0)
638 return -ENXIO;
639 /* Insist that at least the nobody user is mapped, everything else is weird, and hence complex, and we don't support it */
640 if (uid_range < UID_NOBODY)
641 return -ENXIO;
642
643 /* If there's more than one line, then we don't support this mapping. */
644 r = safe_fgetc(f, NULL);
645 if (r < 0)
646 return r;
647 if (r != 0) /* Insist on EOF */
648 return -ENXIO;
649
650 fclose(f);
651
652 xsprintf(p, "/proc/" PID_FMT "/gid_map", m->leader);
653 f = fopen(p, "re");
654 if (!f)
655 return -errno;
656
657 /* Read the first line. There's at least one. */
658 errno = 0;
659 k = fscanf(f, GID_FMT " " GID_FMT " " GID_FMT "\n", &gid_base, &gid_shift, &gid_range);
660 if (k != 3) {
661 if (ferror(f))
662 return errno_or_else(EIO);
663
664 return -EBADMSG;
665 }
666
667 /* If there's more than one line, then we don't support this file. */
668 r = safe_fgetc(f, NULL);
669 if (r < 0)
670 return r;
671 if (r != 0) /* Insist on EOF */
672 return -ENXIO;
673
674 /* If the UID and GID mapping doesn't match, we don't support this mapping. */
675 if (uid_base != (uid_t) gid_base)
676 return -ENXIO;
677 if (uid_shift != (uid_t) gid_shift)
678 return -ENXIO;
679 if (uid_range != (uid_t) gid_range)
680 return -ENXIO;
681
682 *ret = uid_shift;
683 return 0;
684 }
685
686 static const char* const machine_class_table[_MACHINE_CLASS_MAX] = {
687 [MACHINE_CONTAINER] = "container",
688 [MACHINE_VM] = "vm",
689 [MACHINE_HOST] = "host",
690 };
691
692 DEFINE_STRING_TABLE_LOOKUP(machine_class, MachineClass);
693
694 static const char* const machine_state_table[_MACHINE_STATE_MAX] = {
695 [MACHINE_OPENING] = "opening",
696 [MACHINE_RUNNING] = "running",
697 [MACHINE_CLOSING] = "closing"
698 };
699
700 DEFINE_STRING_TABLE_LOOKUP(machine_state, MachineState);
701
702 static const char* const kill_who_table[_KILL_WHO_MAX] = {
703 [KILL_LEADER] = "leader",
704 [KILL_ALL] = "all"
705 };
706
707 DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);