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