• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13935887515

18 Mar 2025 07:10PM UTC coverage: 71.913% (-0.03%) from 71.946%
13935887515

push

github

web-flow
Several fixes and cleanups around sd_listen_fds() (#36788)

15 of 24 new or added lines in 5 files covered. (62.5%)

993 existing lines in 54 files now uncovered.

296157 of 411825 relevant lines covered (71.91%)

710024.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.14
/src/core/manager.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <fcntl.h>
5
#include <linux/kd.h>
6
#include <sys/epoll.h>
7
#include <sys/inotify.h>
8
#include <sys/ioctl.h>
9
#include <sys/mount.h>
10
#include <sys/reboot.h>
11
#include <sys/timerfd.h>
12
#include <sys/wait.h>
13
#include <unistd.h>
14

15
#if HAVE_AUDIT
16
#include <libaudit.h>
17
#endif
18

19
#include "sd-daemon.h"
20
#include "sd-messages.h"
21
#include "sd-path.h"
22

23
#include "all-units.h"
24
#include "alloc-util.h"
25
#include "audit-fd.h"
26
#include "boot-timestamps.h"
27
#include "build-path.h"
28
#include "bus-common-errors.h"
29
#include "bus-error.h"
30
#include "bus-kernel.h"
31
#include "bus-util.h"
32
#include "clean-ipc.h"
33
#include "clock-util.h"
34
#include "common-signal.h"
35
#include "confidential-virt.h"
36
#include "constants.h"
37
#include "core-varlink.h"
38
#include "creds-util.h"
39
#include "daemon-util.h"
40
#include "dbus-job.h"
41
#include "dbus-manager.h"
42
#include "dbus-unit.h"
43
#include "dbus.h"
44
#include "dirent-util.h"
45
#include "env-util.h"
46
#include "escape.h"
47
#include "event-util.h"
48
#include "exec-util.h"
49
#include "execute.h"
50
#include "exit-status.h"
51
#include "fd-util.h"
52
#include "fileio.h"
53
#include "generator-setup.h"
54
#include "hashmap.h"
55
#include "initrd-util.h"
56
#include "inotify-util.h"
57
#include "install.h"
58
#include "io-util.h"
59
#include "iovec-util.h"
60
#include "label-util.h"
61
#include "load-fragment.h"
62
#include "locale-setup.h"
63
#include "log.h"
64
#include "macro.h"
65
#include "manager.h"
66
#include "manager-dump.h"
67
#include "manager-serialize.h"
68
#include "memory-util.h"
69
#include "mkdir-label.h"
70
#include "mount-util.h"
71
#include "notify-recv.h"
72
#include "os-util.h"
73
#include "parse-util.h"
74
#include "path-lookup.h"
75
#include "path-util.h"
76
#include "plymouth-util.h"
77
#include "pretty-print.h"
78
#include "process-util.h"
79
#include "psi-util.h"
80
#include "ratelimit.h"
81
#include "rlimit-util.h"
82
#include "rm-rf.h"
83
#include "selinux-util.h"
84
#include "serialize.h"
85
#include "signal-util.h"
86
#include "socket-util.h"
87
#include "special.h"
88
#include "stat-util.h"
89
#include "string-table.h"
90
#include "string-util.h"
91
#include "strv.h"
92
#include "strxcpyx.h"
93
#include "sysctl-util.h"
94
#include "syslog-util.h"
95
#include "taint.h"
96
#include "terminal-util.h"
97
#include "time-util.h"
98
#include "transaction.h"
99
#include "uid-range.h"
100
#include "umask-util.h"
101
#include "unit-name.h"
102
#include "user-util.h"
103
#include "virt.h"
104
#include "watchdog.h"
105

106
/* Make sure clients notifying us don't block */
107
#define MANAGER_SOCKET_RCVBUF_SIZE (8*U64_MB)
108

109
/* Initial delay and the interval for printing status messages about running jobs */
110
#define JOBS_IN_PROGRESS_WAIT_USEC (2*USEC_PER_SEC)
111
#define JOBS_IN_PROGRESS_QUIET_WAIT_USEC (25*USEC_PER_SEC)
112
#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
113
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
114

115
/* If there are more than 1K bus messages queue across our API and direct buses, then let's not add more on top until
116
 * the queue gets more empty. */
117
#define MANAGER_BUS_BUSY_THRESHOLD 1024LU
118

119
/* How many units and jobs to process of the bus queue before returning to the event loop. */
120
#define MANAGER_BUS_MESSAGE_BUDGET 100U
121

122
#define DEFAULT_TASKS_MAX ((CGroupTasksMax) { 15U, 100U }) /* 15% */
123

124
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
125
static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
126
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
127
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
128
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
129
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
130
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
131
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
132
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
133
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
134
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata);
135
static int manager_dispatch_timezone_change(sd_event_source *source, const struct inotify_event *event, void *userdata);
136
static int manager_run_environment_generators(Manager *m);
137
static int manager_run_generators(Manager *m);
138
static void manager_vacuum(Manager *m);
139

140
static usec_t manager_watch_jobs_next_time(Manager *m) {
13,071✔
141
        usec_t timeout;
13,071✔
142

143
        if (MANAGER_IS_USER(m))
13,071✔
144
                /* Let the user manager without a timeout show status quickly, so the system manager can make
145
                 * use of it, if it wants to. */
146
                timeout = JOBS_IN_PROGRESS_WAIT_USEC * 2 / 3;
147
        else if (show_status_on(m->show_status))
12,416✔
148
                /* When status is on, just use the usual timeout. */
149
                timeout = JOBS_IN_PROGRESS_WAIT_USEC;
150
        else
151
                timeout = JOBS_IN_PROGRESS_QUIET_WAIT_USEC;
152

153
        return usec_add(now(CLOCK_MONOTONIC), timeout);
13,071✔
154
}
155

156
static bool manager_is_confirm_spawn_disabled(Manager *m) {
5,811✔
157
        assert(m);
5,811✔
158

159
        if (!m->confirm_spawn)
5,811✔
160
                return true;
161

162
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
163
}
164

165
static void manager_watch_jobs_in_progress(Manager *m) {
5,811✔
166
        usec_t next;
5,811✔
167
        int r;
5,811✔
168

169
        assert(m);
5,811✔
170

171
        /* We do not want to show the cylon animation if the user
172
         * needs to confirm service executions otherwise confirmation
173
         * messages will be screwed by the cylon animation. */
174
        if (!manager_is_confirm_spawn_disabled(m))
5,811✔
175
                return;
176

177
        if (m->jobs_in_progress_event_source)
5,811✔
178
                return;
179

180
        next = manager_watch_jobs_next_time(m);
1,123✔
181
        r = sd_event_add_time(
1,123✔
182
                        m->event,
183
                        &m->jobs_in_progress_event_source,
184
                        CLOCK_MONOTONIC,
185
                        next, 0,
186
                        manager_dispatch_jobs_in_progress, m);
187
        if (r < 0)
1,123✔
188
                return;
189

190
        (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
1,123✔
191
}
192

193
static void manager_flip_auto_status(Manager *m, bool enable, const char *reason) {
546✔
194
        assert(m);
546✔
195

196
        if (enable) {
546✔
197
                if (m->show_status == SHOW_STATUS_AUTO)
403✔
198
                        manager_set_show_status(m, SHOW_STATUS_TEMPORARY, reason);
×
199
        } else {
200
                if (m->show_status == SHOW_STATUS_TEMPORARY)
143✔
201
                        manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
×
202
        }
203
}
546✔
204

205
static void manager_print_jobs_in_progress(Manager *m) {
403✔
206
        Job *j;
403✔
207
        unsigned counter = 0, print_nr;
403✔
208
        char cylon[6 + CYLON_BUFFER_EXTRA + 1];
403✔
209
        unsigned cylon_pos;
403✔
210
        uint64_t timeout = 0;
403✔
211

212
        assert(m);
403✔
213
        assert(m->n_running_jobs > 0);
403✔
214

215
        manager_flip_auto_status(m, true, "delay");
403✔
216

217
        print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
403✔
218

219
        HASHMAP_FOREACH(j, m->jobs)
406✔
220
                if (j->state == JOB_RUNNING && counter++ == print_nr)
406✔
221
                        break;
222

223
        /* m->n_running_jobs must be consistent with the contents of m->jobs,
224
         * so the above loop must have succeeded in finding j. */
225
        assert(counter == print_nr + 1);
403✔
226
        assert(j);
403✔
227

228
        cylon_pos = m->jobs_in_progress_iteration % 14;
403✔
229
        if (cylon_pos >= 8)
403✔
230
                cylon_pos = 14 - cylon_pos;
171✔
231
        draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
403✔
232

233
        m->jobs_in_progress_iteration++;
403✔
234

235
        char job_of_n[STRLEN("( of ) ") + DECIMAL_STR_MAX(unsigned)*2] = "";
403✔
236
        if (m->n_running_jobs > 1)
403✔
237
                xsprintf(job_of_n, "(%u of %u) ", counter, m->n_running_jobs);
×
238

239
        (void) job_get_timeout(j, &timeout);
403✔
240

241
        /* We want to use enough information for the user to identify previous lines talking about the same
242
         * unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting
243
         * foo.service - Description' were used, 'foo.service' is enough here. On the other hand, if we used
244
         * 'Starting Description' before, then we shall also use 'Description' here. So we pass NULL as the
245
         * second argument to unit_status_string(). */
246
        const char *ident = unit_status_string(j->unit, NULL);
403✔
247

248
        const char *time = FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
403✔
249
        const char *limit = timeout > 0 ? FORMAT_TIMESPAN(timeout - j->begin_usec, 1*USEC_PER_SEC) : "no limit";
403✔
250

251
        if (m->status_unit_format == STATUS_UNIT_FORMAT_DESCRIPTION)
403✔
252
                /* When using 'Description', we effectively don't have enough space to show the nested status
253
                 * without ellipsization, so let's not even try. */
254
                manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
×
255
                                      "%sA %s job is running for %s (%s / %s)",
256
                                      job_of_n,
257
                                      job_type_to_string(j->type),
×
258
                                      ident,
259
                                      time, limit);
260
        else {
261
                const char *status_text = unit_status_text(j->unit);
403✔
262

263
                manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
806✔
264
                                      "%sJob %s/%s running (%s / %s)%s%s",
265
                                      job_of_n,
266
                                      ident,
267
                                      job_type_to_string(j->type),
403✔
268
                                      time, limit,
269
                                      status_text ? ": " : "",
270
                                      strempty(status_text));
271
        }
272

273
        (void) sd_notifyf(/* unset_environment= */ false,
403✔
274
                          "STATUS=%sUser job %s/%s running (%s / %s)...",
275
                          job_of_n,
276
                          ident, job_type_to_string(j->type),
403✔
277
                          time, limit);
278
        m->status_ready = false;
403✔
279
}
403✔
280

281
static int have_ask_password(void) {
96✔
282
        _cleanup_closedir_ DIR *dir = NULL;
96✔
283

284
        dir = opendir("/run/systemd/ask-password");
96✔
285
        if (!dir) {
96✔
286
                if (errno == ENOENT)
×
287
                        return false;
288

289
                return -errno;
×
290
        }
291

292
        FOREACH_DIRENT_ALL(de, dir, return -errno) {
288✔
293
                if (!IN_SET(de->d_type, DT_REG, DT_UNKNOWN))
192✔
294
                        continue;
192✔
295

296
                if (startswith(de->d_name, "ask."))
×
297
                        return true;
298
        }
299

300
        return false;
301
}
302

303
static int manager_dispatch_ask_password_fd(sd_event_source *source,
96✔
304
                                            int fd, uint32_t revents, void *userdata) {
305
        Manager *m = ASSERT_PTR(userdata);
96✔
306

307
        (void) flush_fd(fd);
96✔
308

309
        m->have_ask_password = have_ask_password();
96✔
310
        if (m->have_ask_password < 0)
96✔
311
                /* Log error but continue. Negative have_ask_password is treated as unknown status. */
312
                log_warning_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password/, ignoring: %m");
×
313

314
        return 0;
96✔
315
}
316

317
static void manager_close_ask_password(Manager *m) {
851✔
318
        assert(m);
851✔
319

320
        m->ask_password_event_source = sd_event_source_disable_unref(m->ask_password_event_source);
851✔
321
        m->have_ask_password = -EINVAL;
851✔
322
}
851✔
323

324
static int manager_check_ask_password(Manager *m) {
16,295✔
325
        int r;
16,295✔
326

327
        assert(m);
16,295✔
328

329
        /* We only care about passwords prompts when running in system mode (because that's the only time we
330
         * manage a console) */
331
        if (!MANAGER_IS_SYSTEM(m))
16,295✔
332
                return 0;
333

334
        if (!m->ask_password_event_source) {
16,295✔
335
                _cleanup_close_ int inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
192✔
336
                if (inotify_fd < 0)
96✔
337
                        return log_error_errno(errno, "Failed to create inotify object: %m");
×
338

339
                (void) mkdir_label("/run/systemd/ask-password", 0755);
96✔
340
                r = inotify_add_watch_and_warn(inotify_fd, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_DELETE|IN_MOVED_TO|IN_ONLYDIR);
96✔
341
                if (r < 0)
96✔
342
                        return r;
343

344
                _cleanup_(sd_event_source_disable_unrefp) sd_event_source *event_source = NULL;
96✔
345
                r = sd_event_add_io(
96✔
346
                                m->event,
347
                                &event_source,
348
                                inotify_fd,
349
                                EPOLLIN,
350
                                manager_dispatch_ask_password_fd,
351
                                m);
352
                if (r < 0)
96✔
353
                        return log_error_errno(r, "Failed to add event source for /run/systemd/ask-password/: %m");
×
354

355
                r = sd_event_source_set_io_fd_own(event_source, true);
96✔
356
                if (r < 0)
96✔
357
                        return log_error_errno(r, "Failed to pass ownership of /run/systemd/ask-password/ inotify fd to event source: %m");
×
358
                TAKE_FD(inotify_fd);
96✔
359

360
                (void) sd_event_source_set_description(event_source, "manager-ask-password");
96✔
361

362
                m->ask_password_event_source = TAKE_PTR(event_source);
96✔
363

364
                /* Queries might have been added meanwhile... */
365
                (void) manager_dispatch_ask_password_fd(m->ask_password_event_source, sd_event_source_get_io_fd(m->ask_password_event_source), EPOLLIN, m);
96✔
366
        }
367

368
        return m->have_ask_password;
16,295✔
369
}
370

371
static int manager_watch_idle_pipe(Manager *m) {
603✔
372
        int r;
603✔
373

374
        assert(m);
603✔
375

376
        if (m->idle_pipe_event_source)
603✔
377
                return 0;
378

379
        if (m->idle_pipe[2] < 0)
41✔
380
                return 0;
381

382
        r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
41✔
383
        if (r < 0)
41✔
384
                return log_error_errno(r, "Failed to watch idle pipe: %m");
×
385

386
        (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
41✔
387

388
        return 0;
41✔
389
}
390

391
static void manager_close_idle_pipe(Manager *m) {
2,031✔
392
        assert(m);
2,031✔
393

394
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
2,031✔
395

396
        safe_close_pair(m->idle_pipe);
2,031✔
397
        safe_close_pair(m->idle_pipe + 2);
2,031✔
398
}
2,031✔
399

400
static int manager_setup_time_change(Manager *m) {
264✔
401
        int r;
264✔
402

403
        assert(m);
264✔
404

405
        if (MANAGER_IS_TEST_RUN(m))
264✔
406
                return 0;
407

408
        m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
252✔
409

410
        r = event_add_time_change(m->event, &m->time_change_event_source, manager_dispatch_time_change_fd, m);
252✔
411
        if (r < 0)
252✔
412
                return log_error_errno(r, "Failed to create time change event source: %m");
×
413

414
        /* Schedule this slightly earlier than the .timer event sources */
415
        r = sd_event_source_set_priority(m->time_change_event_source, EVENT_PRIORITY_TIME_CHANGE);
252✔
416
        if (r < 0)
252✔
417
                return log_error_errno(r, "Failed to set priority of time change event sources: %m");
×
418

419
        log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
252✔
420

421
        return 0;
422
}
423

424
static int manager_read_timezone_stat(Manager *m) {
293✔
425
        struct stat st;
293✔
426
        bool changed;
293✔
427

428
        assert(m);
293✔
429

430
        /* Read the current stat() data of /etc/localtime so that we detect changes */
431
        if (lstat("/etc/localtime", &st) < 0) {
293✔
432
                log_debug_errno(errno, "Failed to stat /etc/localtime, ignoring: %m");
80✔
433
                changed = m->etc_localtime_accessible;
80✔
434
                m->etc_localtime_accessible = false;
80✔
435
        } else {
436
                usec_t k;
213✔
437

438
                k = timespec_load(&st.st_mtim);
213✔
439
                changed = !m->etc_localtime_accessible || k != m->etc_localtime_mtime;
213✔
440

441
                m->etc_localtime_mtime = k;
213✔
442
                m->etc_localtime_accessible = true;
213✔
443
        }
444

445
        return changed;
293✔
446
}
447

448
static int manager_setup_timezone_change(Manager *m) {
274✔
449
        _cleanup_(sd_event_source_unrefp) sd_event_source *new_event = NULL;
274✔
450
        int r;
274✔
451

452
        assert(m);
274✔
453

454
        if (MANAGER_IS_TEST_RUN(m))
274✔
455
                return 0;
456

457
        /* We watch /etc/localtime for three events: change of the link count (which might mean removal from /etc even
458
         * though another link might be kept), renames, and file close operations after writing. Note we don't bother
459
         * with IN_DELETE_SELF, as that would just report when the inode is removed entirely, i.e. after the link count
460
         * went to zero and all fds to it are closed.
461
         *
462
         * Note that we never follow symlinks here. This is a simplification, but should cover almost all cases
463
         * correctly.
464
         *
465
         * Note that we create the new event source first here, before releasing the old one. This should optimize
466
         * behaviour as this way sd-event can reuse the old watch in case the inode didn't change. */
467

468
        r = sd_event_add_inotify(m->event, &new_event, "/etc/localtime",
262✔
469
                                 IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
470
        if (r == -ENOENT) {
262✔
471
                /* If the file doesn't exist yet, subscribe to /etc instead, and wait until it is created either by
472
                 * O_CREATE or by rename() */
473

474
                log_debug_errno(r, "/etc/localtime doesn't exist yet, watching /etc instead.");
66✔
475
                r = sd_event_add_inotify(m->event, &new_event, "/etc",
66✔
476
                                         IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
477
        }
478
        if (r < 0)
262✔
479
                return log_error_errno(r, "Failed to create timezone change event source: %m");
×
480

481
        /* Schedule this slightly earlier than the .timer event sources */
482
        r = sd_event_source_set_priority(new_event, EVENT_PRIORITY_TIME_ZONE);
262✔
483
        if (r < 0)
262✔
484
                return log_error_errno(r, "Failed to set priority of timezone change event sources: %m");
×
485

486
        sd_event_source_unref(m->timezone_change_event_source);
262✔
487
        m->timezone_change_event_source = TAKE_PTR(new_event);
262✔
488

489
        return 0;
262✔
490
}
491

492
static int manager_enable_special_signals(Manager *m) {
261✔
493
        _cleanup_close_ int fd = -EBADF;
261✔
494

495
        assert(m);
261✔
496

497
        if (!MANAGER_IS_SYSTEM(m) || MANAGER_IS_TEST_RUN(m))
261✔
498
                return 0;
499

500
        /* Enable that we get SIGINT on control-alt-del. In containers this will fail with EPERM (older) or
501
         * EINVAL (newer), so ignore that. */
502
        if (reboot(RB_DISABLE_CAD) < 0 && !IN_SET(errno, EPERM, EINVAL))
112✔
503
                log_warning_errno(errno, "Failed to enable ctrl-alt-del handling, ignoring: %m");
×
504

505
        fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
112✔
506
        if (fd < 0)
112✔
507
                /* Support systems without virtual console (ENOENT) gracefully */
508
                log_full_errno(fd == -ENOENT ? LOG_DEBUG : LOG_WARNING, fd, "Failed to open /dev/tty0, ignoring: %m");
40✔
509
        else {
510
                /* Enable that we get SIGWINCH on kbrequest */
511
                if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
72✔
512
                        log_warning_errno(errno, "Failed to enable kbrequest handling, ignoring: %m");
261✔
513
        }
514

515
        return 0;
516
}
517

518
#define RTSIG_IF_AVAILABLE(signum) (signum <= SIGRTMAX ? signum : -1)
519

520
static int manager_setup_signals(Manager *m) {
261✔
521
        static const struct sigaction sa = {
261✔
522
                .sa_handler = SIG_DFL,
523
                .sa_flags = SA_NOCLDSTOP|SA_RESTART,
524
        };
525
        sigset_t mask;
261✔
526
        int r;
261✔
527

528
        assert(m);
261✔
529

530
        assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
261✔
531

532
        /* We make liberal use of realtime signals here. On
533
         * Linux/glibc we have 30 of them (with the exception of Linux
534
         * on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
535
         * (aka SIGRTMAX). */
536

537
        assert_se(sigemptyset(&mask) == 0);
261✔
538
        sigset_add_many(&mask,
261✔
539
                        SIGCHLD,     /* Child died */
540
                        SIGTERM,     /* Reexecute daemon */
541
                        SIGHUP,      /* Reload configuration */
542
                        SIGUSR1,     /* systemd: reconnect to D-Bus */
543
                        SIGUSR2,     /* systemd: dump status */
544
                        SIGINT,      /* Kernel sends us this on control-alt-del */
545
                        SIGWINCH,    /* Kernel sends us this on kbrequest (alt-arrowup) */
546
                        SIGPWR,      /* Some kernel drivers and upsd send us this on power failure */
547

548
                        SIGRTMIN+0,  /* systemd: start default.target */
549
                        SIGRTMIN+1,  /* systemd: isolate rescue.target */
550
                        SIGRTMIN+2,  /* systemd: isolate emergency.target */
551
                        SIGRTMIN+3,  /* systemd: start halt.target */
552
                        SIGRTMIN+4,  /* systemd: start poweroff.target */
553
                        SIGRTMIN+5,  /* systemd: start reboot.target */
554
                        SIGRTMIN+6,  /* systemd: start kexec.target */
555
                        SIGRTMIN+7,  /* systemd: start soft-reboot.target */
556

557
                        /* ... space for more special targets ... */
558

559
                        SIGRTMIN+13, /* systemd: Immediate halt */
560
                        SIGRTMIN+14, /* systemd: Immediate poweroff */
561
                        SIGRTMIN+15, /* systemd: Immediate reboot */
562
                        SIGRTMIN+16, /* systemd: Immediate kexec */
563
                        SIGRTMIN+17, /* systemd: Immediate soft-reboot */
564
                        SIGRTMIN+18, /* systemd: control command */
565

566
                        /* ... space ... */
567

568
                        SIGRTMIN+20, /* systemd: enable status messages */
569
                        SIGRTMIN+21, /* systemd: disable status messages */
570
                        SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
571
                        SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
572
                        SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
573
                        SIGRTMIN+25, /* systemd: reexecute manager */
574

575
                        /* Apparently Linux on hppa had fewer RT signals until v3.18,
576
                         * SIGRTMAX was SIGRTMIN+25, and then SIGRTMIN was lowered,
577
                         * see commit v3.17-7614-g1f25df2eff.
578
                         *
579
                         * We cannot unconditionally make use of those signals here,
580
                         * so let's use a runtime check. Since these commands are
581
                         * accessible by different means and only really a safety
582
                         * net, the missing functionality on hppa shouldn't matter.
583
                         */
584

585
                        RTSIG_IF_AVAILABLE(SIGRTMIN+26), /* systemd: set log target to journal-or-kmsg */
586
                        RTSIG_IF_AVAILABLE(SIGRTMIN+27), /* systemd: set log target to console */
587
                        RTSIG_IF_AVAILABLE(SIGRTMIN+28), /* systemd: set log target to kmsg */
588
                        RTSIG_IF_AVAILABLE(SIGRTMIN+29), /* systemd: set log target to syslog-or-kmsg (obsolete) */
589

590
                        /* ... one free signal here SIGRTMIN+30 ... */
591
                        -1);
592
        assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
261✔
593

594
        m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
261✔
595
        if (m->signal_fd < 0)
261✔
596
                return -errno;
×
597

598
        r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
261✔
599
        if (r < 0)
261✔
600
                return r;
601

602
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
261✔
603

604
        /* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
605
         * notify processing can still figure out to which process/service a message belongs, before we reap the
606
         * process. Also, process this before handling cgroup notifications, so that we always collect child exit
607
         * status information before detecting that there's no process in a cgroup. */
608
        r = sd_event_source_set_priority(m->signal_event_source, EVENT_PRIORITY_SIGNALS);
261✔
609
        if (r < 0)
261✔
610
                return r;
611

612
        /* Report to supervisor that we now process the above signals. We report this as level "2", to
613
         * indicate that we support more than sysvinit's signals (of course, sysvinit never sent this
614
         * message, but conceptually it makes sense to consider level "1" to be equivalent to sysvinit's
615
         * signal handling). Also, by setting this to "2" people looking for this hopefully won't
616
         * misunderstand this as a boolean concept. Signal level 2 shall refer to the signals PID 1
617
         * understands at the time of release of systemd v256, i.e. including basic SIGRTMIN+18 handling for
618
         * memory pressure and stuff. When more signals are hooked up (or more SIGRTMIN+18 multiplex
619
         * operations added, this level should be increased). */
620
        (void) sd_notify(/* unset_environment= */ false,
261✔
621
                         "X_SYSTEMD_SIGNALS_LEVEL=2");
622

623
        return manager_enable_special_signals(m);
261✔
624
}
625

626
static char** sanitize_environment(char **l) {
1,253✔
627

628
        /* Let's remove some environment variables that we need ourselves to communicate with our clients */
629
        strv_env_unset_many(
1,253✔
630
                        l,
631
                        "CACHE_DIRECTORY",
632
                        "CONFIGURATION_DIRECTORY",
633
                        "CREDENTIALS_DIRECTORY",
634
                        "EXIT_CODE",
635
                        "EXIT_STATUS",
636
                        "INVOCATION_ID",
637
                        "JOURNAL_STREAM",
638
                        "LISTEN_FDNAMES",
639
                        "LISTEN_FDS",
640
                        "LISTEN_PID",
641
                        "LOGS_DIRECTORY",
642
                        "LOG_NAMESPACE",
643
                        "MAINPID",
644
                        "MANAGERPID",
645
                        "MEMORY_PRESSURE_WATCH",
646
                        "MEMORY_PRESSURE_WRITE",
647
                        "MONITOR_EXIT_CODE",
648
                        "MONITOR_EXIT_STATUS",
649
                        "MONITOR_INVOCATION_ID",
650
                        "MONITOR_SERVICE_RESULT",
651
                        "MONITOR_UNIT",
652
                        "NOTIFY_SOCKET",
653
                        "PIDFILE",
654
                        "REMOTE_ADDR",
655
                        "REMOTE_PORT",
656
                        "RUNTIME_DIRECTORY",
657
                        "SERVICE_RESULT",
658
                        "STATE_DIRECTORY",
659
                        "SYSTEMD_EXEC_PID",
660
                        "TRIGGER_PATH",
661
                        "TRIGGER_TIMER_MONOTONIC_USEC",
662
                        "TRIGGER_TIMER_REALTIME_USEC",
663
                        "TRIGGER_UNIT",
664
                        "WATCHDOG_PID",
665
                        "WATCHDOG_USEC");
666

667
        /* Let's order the environment alphabetically, just to make it pretty */
668
        return strv_sort(l);
1,253✔
669
}
670

671
int manager_default_environment(Manager *m) {
981✔
672
        assert(m);
981✔
673

674
        m->transient_environment = strv_free(m->transient_environment);
981✔
675

676
        if (MANAGER_IS_SYSTEM(m)) {
981✔
677
                /* The system manager always starts with a clean environment for its children. It does not
678
                 * import the kernel's or the parents' exported variables.
679
                 *
680
                 * The initial passed environment is untouched to keep /proc/self/environ valid; it is used
681
                 * for tagging the init process inside containers. */
682
                char *path = strjoin("PATH=", default_PATH());
686✔
683
                if (!path)
686✔
684
                        return log_oom();
×
685

686
                if (strv_consume(&m->transient_environment, path) < 0)
686✔
687
                        return log_oom();
×
688

689
                /* Import locale variables LC_*= from configuration */
690
                (void) locale_setup(&m->transient_environment);
686✔
691
        } else {
692
                /* The user manager passes its own environment along to its children, except for $PATH and
693
                 * session envs. */
694

695
                m->transient_environment = strv_copy(environ);
295✔
696
                if (!m->transient_environment)
295✔
697
                        return log_oom();
×
698

699
                char *path = strjoin("PATH=", default_user_PATH());
295✔
700
                if (!path)
295✔
701
                        return log_oom();
×
702

703
                if (strv_env_replace_consume(&m->transient_environment, path) < 0)
295✔
704
                        return log_oom();
×
705

706
                /* Envvars set for our 'manager' class session are private and should not be propagated
707
                 * to children. Also it's likely that the graphical session will set these on their own. */
708
                strv_env_unset_many(m->transient_environment,
295✔
709
                                    "XDG_SESSION_ID",
710
                                    "XDG_SESSION_CLASS",
711
                                    "XDG_SESSION_TYPE",
712
                                    "XDG_SESSION_DESKTOP",
713
                                    "XDG_SEAT",
714
                                    "XDG_VTNR");
715
        }
716

717
        sanitize_environment(m->transient_environment);
981✔
718
        return 0;
981✔
719
}
720

721
static int manager_setup_prefix(Manager *m) {
708✔
722
        struct table_entry {
708✔
723
                uint64_t type;
724
                const char *suffix;
725
        };
726

727
        static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
708✔
728
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_SYSTEM_RUNTIME,       NULL },
729
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
730
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_SYSTEM_STATE_CACHE,   NULL },
731
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_SYSTEM_STATE_LOGS,    NULL },
732
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
733
        };
734

735
        static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
708✔
736
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_USER_RUNTIME,       NULL  },
737
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_USER_STATE_PRIVATE, NULL  },
738
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_USER_STATE_CACHE,   NULL  },
739
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_USER_STATE_PRIVATE, "log" },
740
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL  },
741
        };
742

743
        assert(m);
708✔
744

745
        const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
708✔
746
        int r;
708✔
747

748
        for (ExecDirectoryType i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
4,248✔
749
                r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
3,540✔
750
                if (r < 0)
3,540✔
751
                        return log_warning_errno(r, "Failed to lookup %s path: %m",
×
752
                                                 exec_directory_type_to_string(i));
753
        }
754

755
        return 0;
756
}
757

758
static void manager_free_unit_name_maps(Manager *m) {
732✔
759
        m->unit_id_map = hashmap_free(m->unit_id_map);
732✔
760
        m->unit_name_map = hashmap_free(m->unit_name_map);
732✔
761
        m->unit_path_cache = set_free(m->unit_path_cache);
732✔
762
        m->unit_cache_timestamp_hash = 0;
732✔
763
}
732✔
764

765
static int manager_setup_run_queue(Manager *m) {
708✔
766
        int r;
708✔
767

768
        assert(m);
708✔
769
        assert(!m->run_queue_event_source);
708✔
770

771
        r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
708✔
772
        if (r < 0)
708✔
773
                return r;
774

775
        r = sd_event_source_set_priority(m->run_queue_event_source, EVENT_PRIORITY_RUN_QUEUE);
708✔
776
        if (r < 0)
708✔
777
                return r;
778

779
        r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
708✔
780
        if (r < 0)
708✔
781
                return r;
782

783
        (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
708✔
784

785
        return 0;
708✔
786
}
787

788
static int manager_setup_sigchld_event_source(Manager *m) {
261✔
789
        int r;
261✔
790

791
        assert(m);
261✔
792
        assert(!m->sigchld_event_source);
261✔
793

794
        r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
261✔
795
        if (r < 0)
261✔
796
                return r;
797

798
        r = sd_event_source_set_priority(m->sigchld_event_source, EVENT_PRIORITY_SIGCHLD);
261✔
799
        if (r < 0)
261✔
800
                return r;
801

802
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
261✔
803
        if (r < 0)
261✔
804
                return r;
805

806
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
261✔
807

808
        return 0;
261✔
809
}
810

811
int manager_setup_memory_pressure_event_source(Manager *m) {
539✔
812
        int r;
539✔
813

814
        assert(m);
539✔
815

816
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
539✔
817

818
        r = sd_event_add_memory_pressure(m->event, &m->memory_pressure_event_source, NULL, NULL);
539✔
819
        if (r < 0)
539✔
820
                log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_NOTICE, r,
×
821
                               "Failed to establish memory pressure event source, ignoring: %m");
822
        else if (m->defaults.memory_pressure_threshold_usec != USEC_INFINITY) {
539✔
823

824
                /* If there's a default memory pressure threshold set, also apply it to the service manager itself */
825
                r = sd_event_source_set_memory_pressure_period(
539✔
826
                                m->memory_pressure_event_source,
827
                                m->defaults.memory_pressure_threshold_usec,
828
                                MEMORY_PRESSURE_DEFAULT_WINDOW_USEC);
829
                if (r < 0)
539✔
830
                        log_warning_errno(r, "Failed to adjust memory pressure threshold, ignoring: %m");
12✔
831
        }
832

833
        return 0;
539✔
834
}
835

836
static int manager_find_credentials_dirs(Manager *m) {
708✔
837
        const char *e;
708✔
838
        int r;
708✔
839

840
        assert(m);
708✔
841

842
        r = get_credentials_dir(&e);
708✔
843
        if (r < 0) {
708✔
844
                if (r != -ENXIO)
596✔
845
                        log_debug_errno(r, "Failed to determine credentials directory, ignoring: %m");
×
846
        } else {
847
                m->received_credentials_directory = strdup(e);
112✔
848
                if (!m->received_credentials_directory)
112✔
849
                        return -ENOMEM;
708✔
850
        }
851

852
        r = get_encrypted_credentials_dir(&e);
708✔
853
        if (r < 0) {
708✔
854
                if (r != -ENXIO)
708✔
855
                        log_debug_errno(r, "Failed to determine encrypted credentials directory, ignoring: %m");
×
856
        } else {
857
                m->received_encrypted_credentials_directory = strdup(e);
×
858
                if (!m->received_encrypted_credentials_directory)
×
859
                        return -ENOMEM;
×
860
        }
861

862
        return 0;
863
}
864

865
void manager_set_switching_root(Manager *m, bool switching_root) {
1,016✔
866
        assert(m);
1,016✔
867

868
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
1,016✔
869
}
1,016✔
870

871
double manager_get_progress(Manager *m) {
17✔
872
        assert(m);
17✔
873

874
        if (MANAGER_IS_FINISHED(m) || m->n_installed_jobs == 0)
34✔
875
                return 1.0;
876

877
        return 1.0 - ((double) hashmap_size(m->jobs) / (double) m->n_installed_jobs);
17✔
878
}
879

880
static int compare_job_priority(const void *a, const void *b) {
440,067✔
881
        const Job *x = a, *y = b;
440,067✔
882

883
        return unit_compare_priority(x->unit, y->unit);
440,067✔
884
}
885

886
int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags, Manager **ret) {
708✔
887
        _cleanup_(manager_freep) Manager *m = NULL;
708✔
888
        int r;
708✔
889

890
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
708✔
891
        assert(ret);
708✔
892

893
        m = new(Manager, 1);
708✔
894
        if (!m)
708✔
895
                return -ENOMEM;
896

897
        *m = (Manager) {
708✔
898
                .runtime_scope = runtime_scope,
899
                .objective = _MANAGER_OBJECTIVE_INVALID,
900
                .previous_objective = _MANAGER_OBJECTIVE_INVALID,
901

902
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
903

904
                .original_log_level = -1,
905
                .original_log_target = _LOG_TARGET_INVALID,
906

907
                .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
908
                .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
909
                .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
910
                .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
911

912
                .show_status_overridden = _SHOW_STATUS_INVALID,
913

914
                .notify_fd = -EBADF,
915
                .cgroups_agent_fd = -EBADF,
916
                .signal_fd = -EBADF,
917
                .user_lookup_fds = EBADF_PAIR,
918
                .handoff_timestamp_fds = EBADF_PAIR,
919
                .pidref_transport_fds = EBADF_PAIR,
920
                .private_listen_fd = -EBADF,
921
                .dev_autofs_fd = -EBADF,
922
                .cgroup_inotify_fd = -EBADF,
923
                .pin_cgroupfs_fd = -EBADF,
924
                .idle_pipe = { -EBADF, -EBADF, -EBADF, -EBADF},
925

926
                 /* start as id #1, so that we can leave #0 around as "null-like" value */
927
                .current_job_id = 1,
928

929
                .have_ask_password = -EINVAL, /* we don't know */
930
                .first_boot = -1,
931
                .test_run_flags = test_run_flags,
932

933
                .dump_ratelimit = (const RateLimit) { .interval = 10 * USEC_PER_MINUTE, .burst = 10 },
934

935
                .executor_fd = -EBADF,
936
        };
937

938
        unit_defaults_init(&m->defaults, runtime_scope);
708✔
939

940
#if ENABLE_EFI
941
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
708✔
942
                boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
74✔
943
                                m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
74✔
944
                                m->timestamps + MANAGER_TIMESTAMP_LOADER);
74✔
945
#endif
946

947
        /* Prepare log fields we can use for structured logging */
948
        if (MANAGER_IS_SYSTEM(m)) {
708✔
949
                m->unit_log_field = "UNIT=";
552✔
950
                m->unit_log_format_string = "UNIT=%s";
552✔
951

952
                m->invocation_log_field = "INVOCATION_ID=";
552✔
953
                m->invocation_log_format_string = "INVOCATION_ID=%s";
552✔
954
        } else {
955
                m->unit_log_field = "USER_UNIT=";
156✔
956
                m->unit_log_format_string = "USER_UNIT=%s";
156✔
957

958
                m->invocation_log_field = "USER_INVOCATION_ID=";
156✔
959
                m->invocation_log_format_string = "USER_INVOCATION_ID=%s";
156✔
960
        }
961

962
        /* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
963
        m->ctrl_alt_del_ratelimit = (const RateLimit) { .interval = 2 * USEC_PER_SEC, .burst = 7 };
708✔
964

965
        r = manager_default_environment(m);
708✔
966
        if (r < 0)
708✔
967
                return r;
968

969
        r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
708✔
970
        if (r < 0)
708✔
971
                return r;
972

973
        r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
708✔
974
        if (r < 0)
708✔
975
                return r;
976

977
        r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
708✔
978
        if (r < 0)
708✔
979
                return r;
980

981
        r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
708✔
982
        if (r < 0)
708✔
983
                return r;
984

985
        r = manager_setup_prefix(m);
708✔
986
        if (r < 0)
708✔
987
                return r;
988

989
        r = manager_find_credentials_dirs(m);
708✔
990
        if (r < 0)
708✔
991
                return r;
992

993
        r = sd_event_default(&m->event);
708✔
994
        if (r < 0)
708✔
995
                return r;
996

997
        r = manager_setup_run_queue(m);
708✔
998
        if (r < 0)
708✔
999
                return r;
1000

1001
        if (FLAGS_SET(test_run_flags, MANAGER_TEST_RUN_MINIMAL)) {
708✔
1002
                m->cgroup_root = strdup("");
447✔
1003
                if (!m->cgroup_root)
447✔
1004
                        return -ENOMEM;
1005
        } else {
1006
                r = manager_setup_signals(m);
261✔
1007
                if (r < 0)
261✔
1008
                        return r;
1009

1010
                r = manager_setup_cgroup(m);
261✔
1011
                if (r < 0)
261✔
1012
                        return r;
1013

1014
                r = manager_setup_time_change(m);
261✔
1015
                if (r < 0)
261✔
1016
                        return r;
1017

1018
                r = manager_read_timezone_stat(m);
261✔
1019
                if (r < 0)
261✔
1020
                        return r;
1021

1022
                (void) manager_setup_timezone_change(m);
261✔
1023

1024
                r = manager_setup_sigchld_event_source(m);
261✔
1025
                if (r < 0)
261✔
1026
                        return r;
1027

1028
                r = manager_setup_memory_pressure_event_source(m);
261✔
1029
                if (r < 0)
261✔
1030
                        return r;
1031

1032
#if HAVE_LIBBPF
1033
                if (MANAGER_IS_SYSTEM(m) && bpf_restrict_fs_supported(/* initialize = */ true)) {
261✔
1034
                        r = bpf_restrict_fs_setup(m);
11✔
1035
                        if (r < 0)
11✔
1036
                                log_warning_errno(r, "Failed to setup LSM BPF, ignoring: %m");
×
1037
                }
1038
#endif
1039
        }
1040

1041
        if (test_run_flags == 0) {
708✔
1042
                if (MANAGER_IS_SYSTEM(m))
249✔
1043
                        r = mkdir_label("/run/systemd/units", 0755);
112✔
1044
                else {
1045
                        _cleanup_free_ char *units_path = NULL;
137✔
1046
                        r = xdg_user_runtime_dir("/systemd/units", &units_path);
137✔
1047
                        if (r < 0)
137✔
1048
                                return r;
×
1049

1050
                        r = mkdir_label(units_path, 0755);
137✔
1051
                }
1052
                if (r < 0 && r != -EEXIST)
249✔
1053
                        return r;
1054
        }
1055

1056
        if (!FLAGS_SET(test_run_flags, MANAGER_TEST_DONT_OPEN_EXECUTOR)) {
708✔
1057
                m->executor_fd = pin_callout_binary(SYSTEMD_EXECUTOR_BINARY_PATH);
268✔
1058
                if (m->executor_fd < 0)
268✔
1059
                        return log_debug_errno(m->executor_fd, "Failed to pin executor binary: %m");
×
1060

1061
                if (DEBUG_LOGGING) {
268✔
1062
                        _cleanup_free_ char *executor_path = NULL;
268✔
1063

1064
                        (void) fd_get_path(m->executor_fd, &executor_path);
268✔
1065
                        log_debug("Using systemd-executor binary from '%s'.", strna(executor_path));
268✔
1066
                }
1067
        }
1068

1069
        /* Note that we do not set up the notify fd here. We do that after deserialization,
1070
         * since they might have gotten serialized across the reexec. */
1071

1072
        *ret = TAKE_PTR(m);
708✔
1073

1074
        return 0;
708✔
1075
}
1076

1077
static int manager_setup_notify(Manager *m) {
730✔
1078
        int r;
730✔
1079

1080
        if (MANAGER_IS_TEST_RUN(m))
730✔
1081
                return 0;
1082

1083
        if (m->notify_fd < 0) {
273✔
1084
                _cleanup_close_ int fd = -EBADF;
215✔
1085
                union sockaddr_union sa;
215✔
1086
                socklen_t sa_len;
215✔
1087

1088
                /* First free all secondary fields */
1089
                m->notify_socket = mfree(m->notify_socket);
215✔
1090
                m->notify_event_source = sd_event_source_disable_unref(m->notify_event_source);
215✔
1091

1092
                fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
215✔
1093
                if (fd < 0)
215✔
1094
                        return log_error_errno(errno, "Failed to allocate notification socket: %m");
×
1095

1096
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
215✔
1097

1098
                m->notify_socket = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/notify");
215✔
1099
                if (!m->notify_socket)
215✔
1100
                        return log_oom();
×
1101

1102
                r = sockaddr_un_set_path(&sa.un, m->notify_socket);
215✔
1103
                if (r < 0)
215✔
1104
                        return log_error_errno(r, "Notify socket '%s' not valid for AF_UNIX socket address, refusing.",
×
1105
                                               m->notify_socket);
1106
                sa_len = r;
215✔
1107

1108
                (void) sockaddr_un_unlink(&sa.un);
215✔
1109

1110
                r = mac_selinux_bind(fd, &sa.sa, sa_len);
215✔
1111
                if (r < 0)
215✔
1112
                        return log_error_errno(r, "Failed to bind notify fd to '%s': %m", m->notify_socket);
×
1113

1114
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
215✔
1115
                if (r < 0)
215✔
1116
                        return log_error_errno(r, "Failed to enable SO_PASSCRED for notify socket: %m");
×
1117

1118
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
215✔
1119
                if (r < 0 && r != -ENOPROTOOPT)
215✔
1120
                        log_warning_errno(r, "Failed to enable SO_PASSPIDFD for notify socket, ignoring: %m");
×
1121
                // TODO: maybe enforce SO_PASSPIDFD?
1122

1123
                m->notify_fd = TAKE_FD(fd);
215✔
1124

1125
                log_debug("Using notification socket %s", m->notify_socket);
215✔
1126
        }
1127

1128
        if (!m->notify_event_source) {
273✔
1129
                r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
273✔
1130
                if (r < 0)
273✔
1131
                        return log_error_errno(r, "Failed to allocate notify event source: %m");
×
1132

1133
                /* Process notification messages a bit earlier than SIGCHLD, so that we can still identify to which
1134
                 * service an exit message belongs. */
1135
                r = sd_event_source_set_priority(m->notify_event_source, EVENT_PRIORITY_NOTIFY);
273✔
1136
                if (r < 0)
273✔
1137
                        return log_error_errno(r, "Failed to set priority of notify event source: %m");
×
1138

1139
                (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
273✔
1140
        }
1141

1142
        return 0;
1143
}
1144

1145
static int manager_setup_cgroups_agent(Manager *m) {
730✔
1146

1147
        static const union sockaddr_union sa = {
730✔
1148
                .un.sun_family = AF_UNIX,
1149
                .un.sun_path = "/run/systemd/cgroups-agent",
1150
        };
1151
        int r;
730✔
1152

1153
        /* This creates a listening socket we receive cgroups agent messages on. We do not use D-Bus for delivering
1154
         * these messages from the cgroups agent binary to PID 1, as the cgroups agent binary is very short-living, and
1155
         * each instance of it needs a new D-Bus connection. Since D-Bus connections are SOCK_STREAM/AF_UNIX, on
1156
         * overloaded systems the backlog of the D-Bus socket becomes relevant, as not more than the configured number
1157
         * of D-Bus connections may be queued until the kernel will start dropping further incoming connections,
1158
         * possibly resulting in lost cgroups agent messages. To avoid this, we'll use a private SOCK_DGRAM/AF_UNIX
1159
         * socket, where no backlog is relevant as communication may take place without an actual connect() cycle, and
1160
         * we thus won't lose messages.
1161
         *
1162
         * Note that PID 1 will forward the agent message to system bus, so that the user systemd instance may listen
1163
         * to it. The system instance hence listens on this special socket, but the user instances listen on the system
1164
         * bus for these messages. */
1165

1166
        if (MANAGER_IS_TEST_RUN(m))
730✔
1167
                return 0;
1168

1169
        if (!MANAGER_IS_SYSTEM(m))
273✔
1170
                return 0;
1171

1172
        r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
134✔
1173
        if (r < 0)
134✔
1174
                return log_error_errno(r, "Failed to determine whether unified cgroups hierarchy is used: %m");
×
1175
        if (r > 0) /* We don't need this anymore on the unified hierarchy */
134✔
1176
                return 0;
1177

1178
        if (m->cgroups_agent_fd < 0) {
×
1179
                _cleanup_close_ int fd = -EBADF;
730✔
1180

1181
                /* First free all secondary fields */
1182
                m->cgroups_agent_event_source = sd_event_source_disable_unref(m->cgroups_agent_event_source);
×
1183

1184
                fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
×
1185
                if (fd < 0)
×
1186
                        return log_error_errno(errno, "Failed to allocate cgroups agent socket: %m");
×
1187

1188
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
×
1189

1190
                (void) sockaddr_un_unlink(&sa.un);
×
1191

1192
                /* Only allow root to connect to this socket */
1193
                WITH_UMASK(0077)
×
1194
                        r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
×
1195
                if (r < 0)
×
1196
                        return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
×
1197

1198
                m->cgroups_agent_fd = TAKE_FD(fd);
×
1199
        }
1200

1201
        if (!m->cgroups_agent_event_source) {
×
1202
                r = sd_event_add_io(m->event, &m->cgroups_agent_event_source, m->cgroups_agent_fd, EPOLLIN, manager_dispatch_cgroups_agent_fd, m);
×
1203
                if (r < 0)
×
1204
                        return log_error_errno(r, "Failed to allocate cgroups agent event source: %m");
×
1205

1206
                /* Process cgroups notifications early. Note that when the agent notification is received
1207
                 * we'll just enqueue the unit in the cgroup empty queue, hence pick a high priority than
1208
                 * that. Also see handling of cgroup inotify for the unified cgroup stuff. */
1209
                r = sd_event_source_set_priority(m->cgroups_agent_event_source, EVENT_PRIORITY_CGROUP_AGENT);
×
1210
                if (r < 0)
×
1211
                        return log_error_errno(r, "Failed to set priority of cgroups agent event source: %m");
×
1212

1213
                (void) sd_event_source_set_description(m->cgroups_agent_event_source, "manager-cgroups-agent");
×
1214
        }
1215

1216
        return 0;
1217
}
1218

1219
static int manager_setup_user_lookup_fd(Manager *m) {
730✔
1220
        int r;
730✔
1221

1222
        assert(m);
730✔
1223

1224
        /* Set up the socket pair used for passing UID/GID resolution results from forked off processes to PID
1225
         * 1. Background: we can't do name lookups (NSS) from PID 1, since it might involve IPC and thus activation,
1226
         * and we might hence deadlock on ourselves. Hence we do all user/group lookups asynchronously from the forked
1227
         * off processes right before executing the binaries to start. In order to be able to clean up any IPC objects
1228
         * created by a unit (see RemoveIPC=) we need to know in PID 1 the used UID/GID of the executed processes,
1229
         * hence we establish this communication channel so that forked off processes can pass their UID/GID
1230
         * information back to PID 1. The forked off processes send their resolved UID/GID to PID 1 in a simple
1231
         * datagram, along with their unit name, so that we can share one communication socket pair among all units for
1232
         * this purpose.
1233
         *
1234
         * You might wonder why we need a communication channel for this that is independent of the usual notification
1235
         * socket scheme (i.e. $NOTIFY_SOCKET). The primary difference is about trust: data sent via the $NOTIFY_SOCKET
1236
         * channel is only accepted if it originates from the right unit and if reception was enabled for it. The user
1237
         * lookup socket OTOH is only accessible by PID 1 and its children until they exec(), and always available.
1238
         *
1239
         * Note that this function is called under two circumstances: when we first initialize (in which case we
1240
         * allocate both the socket pair and the event source to listen on it), and when we deserialize after a reload
1241
         * (in which case the socket pair already exists but we still need to allocate the event source for it). */
1242

1243
        if (m->user_lookup_fds[0] < 0) {
730✔
1244

1245
                /* Free all secondary fields */
1246
                safe_close_pair(m->user_lookup_fds);
672✔
1247
                m->user_lookup_event_source = sd_event_source_disable_unref(m->user_lookup_event_source);
672✔
1248

1249
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
672✔
1250
                        return log_error_errno(errno, "Failed to allocate user lookup socket: %m");
×
1251

1252
                (void) fd_increase_rxbuf(m->user_lookup_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
672✔
1253
        }
1254

1255
        if (!m->user_lookup_event_source) {
730✔
1256
                r = sd_event_add_io(m->event, &m->user_lookup_event_source, m->user_lookup_fds[0], EPOLLIN, manager_dispatch_user_lookup_fd, m);
730✔
1257
                if (r < 0)
730✔
1258
                        return log_error_errno(r, "Failed to allocate user lookup event source: %m");
×
1259

1260
                /* Process even earlier than the notify event source, so that we always know first about valid UID/GID
1261
                 * resolutions */
1262
                r = sd_event_source_set_priority(m->user_lookup_event_source, EVENT_PRIORITY_USER_LOOKUP);
730✔
1263
                if (r < 0)
730✔
1264
                        return log_error_errno(r, "Failed to set priority of user lookup event source: %m");
×
1265

1266
                (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
730✔
1267
        }
1268

1269
        return 0;
1270
}
1271

1272
static int manager_setup_handoff_timestamp_fd(Manager *m) {
730✔
1273
        int r;
730✔
1274

1275
        assert(m);
730✔
1276

1277
        /* Set up the socket pair used for passing timestamps back when the executor processes we fork
1278
         * off invokes execve(), i.e. when we hand off control to our payload processes. */
1279

1280
        if (m->handoff_timestamp_fds[0] < 0) {
730✔
1281
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
672✔
1282
                safe_close_pair(m->handoff_timestamp_fds);
672✔
1283

1284
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->handoff_timestamp_fds) < 0)
672✔
1285
                        return log_error_errno(errno, "Failed to allocate handoff timestamp socket: %m");
×
1286

1287
                /* Make sure children never have to block */
1288
                (void) fd_increase_rxbuf(m->handoff_timestamp_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
672✔
1289

1290
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSCRED, true);
672✔
1291
                if (r < 0)
672✔
1292
                        return log_error_errno(r, "SO_PASSCRED failed: %m");
×
1293

1294
                /* Mark the receiving socket as O_NONBLOCK (but leave sending side as-is) */
1295
                r = fd_nonblock(m->handoff_timestamp_fds[0], true);
672✔
1296
                if (r < 0)
672✔
1297
                        return log_error_errno(r, "Failed to make handoff timestamp socket O_NONBLOCK: %m");
×
1298
        }
1299

1300
        if (!m->handoff_timestamp_event_source) {
730✔
1301
                r = sd_event_add_io(m->event, &m->handoff_timestamp_event_source, m->handoff_timestamp_fds[0], EPOLLIN, manager_dispatch_handoff_timestamp_fd, m);
730✔
1302
                if (r < 0)
730✔
1303
                        return log_error_errno(r, "Failed to allocate handoff timestamp event source: %m");
×
1304

1305
                r = sd_event_source_set_priority(m->handoff_timestamp_event_source, EVENT_PRIORITY_HANDOFF_TIMESTAMP);
730✔
1306
                if (r < 0)
730✔
1307
                        return log_error_errno(r, "Failed to set priority of handoff timestamp event source: %m");
×
1308

1309
                (void) sd_event_source_set_description(m->handoff_timestamp_event_source, "handoff-timestamp");
730✔
1310
        }
1311

1312
        return 0;
1313
}
1314

1315
static int manager_setup_pidref_transport_fd(Manager *m) {
730✔
1316
        int r;
730✔
1317

1318
        assert(m);
730✔
1319

1320
        /* Set up the socket pair used for passing parent and child pidrefs back when the executor unshares
1321
         * a PID namespace and forks again when using PrivatePIDs=yes. */
1322

1323
        if (m->pidref_transport_fds[0] < 0) {
730✔
1324
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
706✔
1325
                safe_close_pair(m->pidref_transport_fds);
706✔
1326

1327
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->pidref_transport_fds) < 0)
706✔
1328
                        return log_error_errno(errno, "Failed to allocate pidref socket: %m");
×
1329

1330
                /* Make sure children never have to block */
1331
                (void) fd_increase_rxbuf(m->pidref_transport_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
706✔
1332

1333
                r = setsockopt_int(m->pidref_transport_fds[0], SOL_SOCKET, SO_PASSCRED, true);
706✔
1334
                if (r < 0)
706✔
1335
                        return log_error_errno(r, "Failed to enable SO_PASSCRED for pidref socket: %m");
×
1336

1337
                r = setsockopt_int(m->pidref_transport_fds[0], SOL_SOCKET, SO_PASSPIDFD, true);
706✔
1338
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
706✔
1339
                        log_debug("SO_PASSPIDFD is not supported for pidref socket, ignoring.");
×
1340
                else if (r < 0)
706✔
1341
                        log_warning_errno(r, "Failed to enable SO_PASSPIDFD for pidref socket, ignoring: %m");
×
1342

1343
                /* Mark the receiving socket as O_NONBLOCK (but leave sending side as-is) */
1344
                r = fd_nonblock(m->pidref_transport_fds[0], true);
706✔
1345
                if (r < 0)
706✔
1346
                        return log_error_errno(r, "Failed to make pidref socket O_NONBLOCK: %m");
×
1347
        }
1348

1349
        if (!m->pidref_event_source) {
730✔
1350
                r = sd_event_add_io(m->event, &m->pidref_event_source, m->pidref_transport_fds[0], EPOLLIN, manager_dispatch_pidref_transport_fd, m);
706✔
1351
                if (r < 0)
706✔
1352
                        return log_error_errno(r, "Failed to allocate pidref event source: %m");
×
1353

1354
                r = sd_event_source_set_priority(m->pidref_event_source, EVENT_PRIORITY_PIDREF);
706✔
1355
                if (r < 0)
706✔
1356
                        return log_error_errno(r, "Failed to set priority of pidref event source: %m");
×
1357

1358
                (void) sd_event_source_set_description(m->pidref_event_source, "pidref");
706✔
1359
        }
1360

1361
        return 0;
1362
}
1363

1364
static unsigned manager_dispatch_cleanup_queue(Manager *m) {
322,584✔
1365
        Unit *u;
322,584✔
1366
        unsigned n = 0;
322,584✔
1367

1368
        assert(m);
322,584✔
1369

1370
        while ((u = m->cleanup_queue)) {
350,788✔
1371
                assert(u->in_cleanup_queue);
28,204✔
1372

1373
                unit_free(u);
28,204✔
1374
                n++;
28,204✔
1375
        }
1376

1377
        return n;
322,584✔
1378
}
1379

1380
static unsigned manager_dispatch_release_resources_queue(Manager *m) {
312,926✔
1381
        unsigned n = 0;
312,926✔
1382
        Unit *u;
312,926✔
1383

1384
        assert(m);
312,926✔
1385

1386
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
315,165✔
1387
                assert(u->in_release_resources_queue);
2,239✔
1388
                u->in_release_resources_queue = false;
2,239✔
1389

1390
                n++;
2,239✔
1391

1392
                unit_release_resources(u);
2,239✔
1393
        }
1394

1395
        return n;
312,926✔
1396
}
1397

1398
enum {
1399
        GC_OFFSET_IN_PATH,  /* This one is on the path we were traveling */
1400
        GC_OFFSET_UNSURE,   /* No clue */
1401
        GC_OFFSET_GOOD,     /* We still need this unit */
1402
        GC_OFFSET_BAD,      /* We don't need this unit anymore */
1403
        _GC_OFFSET_MAX
1404
};
1405

1406
static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
80,812✔
1407
        Unit *other;
80,812✔
1408

1409
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
80,812✔
1410

1411
        /* Recursively mark referenced units as GOOD as well */
1412
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
715,685✔
1413
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
430,373✔
1414
                        unit_gc_mark_good(other, gc_marker);
3,163✔
1415
}
80,812✔
1416

1417
static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
135,309✔
1418
        Unit *other;
135,309✔
1419
        bool is_bad;
135,309✔
1420

1421
        assert(u);
135,309✔
1422

1423
        if (IN_SET(u->gc_marker - gc_marker,
135,309✔
1424
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1425
                return;
57,660✔
1426

1427
        if (u->in_cleanup_queue)
109,015✔
1428
                goto bad;
×
1429

1430
        if (!unit_may_gc(u))
109,015✔
1431
                goto good;
46,139✔
1432

1433
        u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
62,876✔
1434

1435
        is_bad = true;
62,876✔
1436

1437
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
138,644✔
1438
                unit_gc_sweep(other, gc_marker);
40,152✔
1439

1440
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
40,152✔
1441
                        goto good;
31,510✔
1442

1443
                if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
8,642✔
1444
                        is_bad = false;
7,777✔
1445
        }
1446

1447
        LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
31,876✔
1448
                unit_gc_sweep(ref->source, gc_marker);
510✔
1449

1450
                if (ref->source->gc_marker == gc_marker + GC_OFFSET_GOOD)
510✔
1451
                        goto good;
×
1452

1453
                if (ref->source->gc_marker != gc_marker + GC_OFFSET_BAD)
510✔
1454
                        is_bad = false;
510✔
1455
        }
1456

1457
        if (is_bad)
31,366✔
1458
                goto bad;
28,197✔
1459

1460
        /* We were unable to find anything out about this entry, so
1461
         * let's investigate it later */
1462
        u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
3,169✔
1463
        unit_add_to_gc_queue(u);
3,169✔
1464
        return;
1465

1466
bad:
28,197✔
1467
        /* We definitely know that this one is not useful anymore, so
1468
         * let's mark it for deletion */
1469
        u->gc_marker = gc_marker + GC_OFFSET_BAD;
28,197✔
1470
        unit_add_to_cleanup_queue(u);
28,197✔
1471
        return;
1472

1473
good:
77,649✔
1474
        unit_gc_mark_good(u, gc_marker);
77,649✔
1475
}
1476

1477
static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
333,577✔
1478
        unsigned n = 0, gc_marker;
333,577✔
1479
        Unit *u;
333,577✔
1480

1481
        assert(m);
333,577✔
1482

1483
        /* log_debug("Running GC..."); */
1484

1485
        m->gc_marker += _GC_OFFSET_MAX;
333,577✔
1486
        if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
333,577✔
1487
                m->gc_marker = 1;
×
1488

1489
        gc_marker = m->gc_marker;
333,577✔
1490

1491
        while ((u = LIST_POP(gc_queue, m->gc_unit_queue))) {
428,224✔
1492
                assert(u->in_gc_queue);
94,647✔
1493

1494
                unit_gc_sweep(u, gc_marker);
94,647✔
1495

1496
                u->in_gc_queue = false;
94,647✔
1497

1498
                n++;
94,647✔
1499

1500
                if (IN_SET(u->gc_marker - gc_marker,
94,647✔
1501
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1502
                        if (u->id)
28,203✔
1503
                                log_unit_debug(u, "Collecting.");
55,797✔
1504
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
28,203✔
1505
                        unit_add_to_cleanup_queue(u);
28,203✔
1506
                }
1507
        }
1508

1509
        return n;
333,577✔
1510
}
1511

1512
static unsigned manager_dispatch_gc_job_queue(Manager *m) {
333,633✔
1513
        unsigned n = 0;
333,633✔
1514
        Job *j;
333,633✔
1515

1516
        assert(m);
333,633✔
1517

1518
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
333,689✔
1519
                assert(j->in_gc_queue);
56✔
1520
                j->in_gc_queue = false;
56✔
1521

1522
                n++;
56✔
1523

1524
                if (!job_may_gc(j))
56✔
1525
                        continue;
56✔
1526

1527
                log_unit_debug(j->unit, "Collecting job.");
×
1528
                (void) job_finish_and_invalidate(j, JOB_COLLECTED, false, false);
×
1529
        }
1530

1531
        return n;
333,633✔
1532
}
1533

1534
static int manager_ratelimit_requeue(sd_event_source *s, uint64_t usec, void *userdata) {
×
1535
        Unit *u = userdata;
×
1536

1537
        assert(u);
×
1538
        assert(s == u->auto_start_stop_event_source);
×
1539

1540
        u->auto_start_stop_event_source = sd_event_source_unref(u->auto_start_stop_event_source);
×
1541

1542
        /* Re-queue to all queues, if the rate limit hit we might have been throttled on any of them. */
1543
        unit_submit_to_stop_when_unneeded_queue(u);
×
1544
        unit_submit_to_start_when_upheld_queue(u);
×
1545
        unit_submit_to_stop_when_bound_queue(u);
×
1546

1547
        return 0;
×
1548
}
1549

1550
static int manager_ratelimit_check_and_queue(Unit *u) {
10✔
1551
        int r;
10✔
1552

1553
        assert(u);
10✔
1554

1555
        if (ratelimit_below(&u->auto_start_stop_ratelimit))
10✔
1556
                return 1;
1557

1558
        /* Already queued, no need to requeue */
1559
        if (u->auto_start_stop_event_source)
×
1560
                return 0;
1561

1562
        r = sd_event_add_time(
×
1563
                        u->manager->event,
×
1564
                        &u->auto_start_stop_event_source,
1565
                        CLOCK_MONOTONIC,
1566
                        ratelimit_end(&u->auto_start_stop_ratelimit),
1567
                        0,
1568
                        manager_ratelimit_requeue,
1569
                        u);
1570
        if (r < 0)
×
1571
                return log_unit_error_errno(u, r, "Failed to queue timer on event loop: %m");
×
1572

1573
        return 0;
1574
}
1575

1576
static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
313,047✔
1577
        unsigned n = 0;
313,047✔
1578
        Unit *u;
313,047✔
1579
        int r;
313,047✔
1580

1581
        assert(m);
313,047✔
1582

1583
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
313,207✔
1584
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
160✔
1585

1586
                assert(u->in_stop_when_unneeded_queue);
160✔
1587
                u->in_stop_when_unneeded_queue = false;
160✔
1588

1589
                n++;
160✔
1590

1591
                if (!unit_is_unneeded(u))
160✔
1592
                        continue;
150✔
1593

1594
                log_unit_debug(u, "Unit is not needed anymore.");
20✔
1595

1596
                /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1597
                 * service being unnecessary after a while. */
1598

1599
                r = manager_ratelimit_check_and_queue(u);
10✔
1600
                if (r <= 0) {
10✔
1601
                        log_unit_warning(u,
×
1602
                                         "Unit not needed anymore, but not stopping since we tried this too often recently.%s",
1603
                                         r == 0 ? " Will retry later." : "");
1604
                        continue;
×
1605
                }
1606

1607
                /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1608
                r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, /* ret = */ NULL);
10✔
1609
                if (r < 0)
10✔
1610
                        log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
×
1611
        }
1612

1613
        return n;
313,047✔
1614
}
1615

1616
static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
313,216✔
1617
        unsigned n = 0;
313,216✔
1618
        Unit *u;
313,216✔
1619
        int r;
313,216✔
1620

1621
        assert(m);
313,216✔
1622

1623
        while ((u = LIST_POP(start_when_upheld_queue, m->start_when_upheld_queue))) {
313,216✔
1624
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1625
                Unit *culprit = NULL;
×
1626

1627
                assert(u->in_start_when_upheld_queue);
×
1628
                u->in_start_when_upheld_queue = false;
×
1629

1630
                n++;
×
1631

1632
                if (!unit_is_upheld_by_active(u, &culprit))
×
1633
                        continue;
×
1634

1635
                log_unit_debug(u, "Unit is started because upheld by active unit %s.", culprit->id);
×
1636

1637
                /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1638
                 * service being unnecessary after a while. */
1639

1640
                r = manager_ratelimit_check_and_queue(u);
×
1641
                if (r <= 0) {
×
1642
                        log_unit_warning(u,
×
1643
                                         "Unit needs to be started because active unit %s upholds it, but not starting since we tried this too often recently.%s",
1644
                                         culprit->id,
1645
                                         r == 0 ? " Will retry later." : "");
1646
                        continue;
×
1647
                }
1648

1649
                r = manager_add_job(u->manager, JOB_START, u, JOB_FAIL, &error, /* ret = */ NULL);
×
1650
                if (r < 0)
×
1651
                        log_unit_warning_errno(u, r, "Failed to enqueue start job, ignoring: %s", bus_error_message(&error, r));
×
1652
        }
1653

1654
        return n;
313,216✔
1655
}
1656

1657
static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
313,216✔
1658
        unsigned n = 0;
313,216✔
1659
        Unit *u;
313,216✔
1660
        int r;
313,216✔
1661

1662
        assert(m);
313,216✔
1663

1664
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
313,492✔
1665
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
276✔
1666
                Unit *culprit = NULL;
276✔
1667

1668
                assert(u->in_stop_when_bound_queue);
276✔
1669
                u->in_stop_when_bound_queue = false;
276✔
1670

1671
                n++;
276✔
1672

1673
                if (!unit_is_bound_by_inactive(u, &culprit))
276✔
1674
                        continue;
276✔
1675

1676
                log_unit_debug(u, "Unit is stopped because bound to inactive unit %s.", culprit->id);
×
1677

1678
                /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1679
                 * service being unnecessary after a while. */
1680

1681
                r = manager_ratelimit_check_and_queue(u);
×
1682
                if (r <= 0) {
×
1683
                        log_unit_warning(u,
×
1684
                                         "Unit needs to be stopped because it is bound to inactive unit %s it, but not stopping since we tried this too often recently.%s",
1685
                                         culprit->id,
1686
                                         r == 0 ? " Will retry later." : "");
1687
                        continue;
×
1688
                }
1689

1690
                r = manager_add_job(u->manager, JOB_STOP, u, JOB_REPLACE, &error, /* ret = */ NULL);
×
1691
                if (r < 0)
×
1692
                        log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
×
1693
        }
1694

1695
        return n;
313,216✔
1696
}
1697

1698
static void manager_clear_jobs_and_units(Manager *m) {
732✔
1699
        Unit *u;
732✔
1700

1701
        assert(m);
732✔
1702

1703
        while ((u = hashmap_first(m->units)))
54,245✔
1704
                unit_free(u);
53,513✔
1705

1706
        manager_dispatch_cleanup_queue(m);
732✔
1707

1708
        assert(!m->load_queue);
732✔
1709
        assert(prioq_isempty(m->run_queue));
732✔
1710
        assert(!m->dbus_unit_queue);
732✔
1711
        assert(!m->dbus_job_queue);
732✔
1712
        assert(!m->cleanup_queue);
732✔
1713
        assert(!m->gc_unit_queue);
732✔
1714
        assert(!m->gc_job_queue);
732✔
1715
        assert(!m->cgroup_realize_queue);
732✔
1716
        assert(!m->cgroup_empty_queue);
732✔
1717
        assert(!m->cgroup_oom_queue);
732✔
1718
        assert(!m->target_deps_queue);
732✔
1719
        assert(!m->stop_when_unneeded_queue);
732✔
1720
        assert(!m->start_when_upheld_queue);
732✔
1721
        assert(!m->stop_when_bound_queue);
732✔
1722
        assert(!m->release_resources_queue);
732✔
1723

1724
        assert(hashmap_isempty(m->jobs));
732✔
1725
        assert(hashmap_isempty(m->units));
732✔
1726

1727
        m->n_on_console = 0;
732✔
1728
        m->n_running_jobs = 0;
732✔
1729
        m->n_installed_jobs = 0;
732✔
1730
        m->n_failed_jobs = 0;
732✔
1731
}
732✔
1732

1733
Manager* manager_free(Manager *m) {
708✔
1734
        if (!m)
708✔
1735
                return NULL;
1736

1737
        manager_clear_jobs_and_units(m);
708✔
1738

1739
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
8,496✔
1740
                if (unit_vtable[c]->shutdown)
7,788✔
1741
                        unit_vtable[c]->shutdown(m);
2,832✔
1742

1743
        /* Keep the cgroup hierarchy in place except when we know we are going down for good */
1744
        manager_shutdown_cgroup(m, /* delete= */ IN_SET(m->objective, MANAGER_EXIT, MANAGER_REBOOT, MANAGER_POWEROFF, MANAGER_HALT, MANAGER_KEXEC));
708✔
1745

1746
        lookup_paths_flush_generator(&m->lookup_paths);
708✔
1747

1748
        bus_done(m);
708✔
1749
        manager_varlink_done(m);
708✔
1750

1751
        exec_shared_runtime_vacuum(m);
708✔
1752
        hashmap_free(m->exec_shared_runtime_by_id);
708✔
1753

1754
        dynamic_user_vacuum(m, false);
708✔
1755
        hashmap_free(m->dynamic_users);
708✔
1756

1757
        hashmap_free(m->units);
708✔
1758
        hashmap_free(m->units_by_invocation_id);
708✔
1759
        hashmap_free(m->jobs);
708✔
1760
        hashmap_free(m->watch_pids);
708✔
1761
        hashmap_free(m->watch_pids_more);
708✔
1762
        hashmap_free(m->watch_bus);
708✔
1763

1764
        prioq_free(m->run_queue);
708✔
1765

1766
        set_free(m->startup_units);
708✔
1767
        set_free(m->failed_units);
708✔
1768

1769
        sd_event_source_unref(m->signal_event_source);
708✔
1770
        sd_event_source_unref(m->sigchld_event_source);
708✔
1771
        sd_event_source_unref(m->notify_event_source);
708✔
1772
        sd_event_source_unref(m->cgroups_agent_event_source);
708✔
1773
        sd_event_source_unref(m->time_change_event_source);
708✔
1774
        sd_event_source_unref(m->timezone_change_event_source);
708✔
1775
        sd_event_source_unref(m->jobs_in_progress_event_source);
708✔
1776
        sd_event_source_unref(m->run_queue_event_source);
708✔
1777
        sd_event_source_unref(m->user_lookup_event_source);
708✔
1778
        sd_event_source_unref(m->handoff_timestamp_event_source);
708✔
1779
        sd_event_source_unref(m->pidref_event_source);
708✔
1780
        sd_event_source_unref(m->memory_pressure_event_source);
708✔
1781

1782
        safe_close(m->signal_fd);
708✔
1783
        safe_close(m->notify_fd);
708✔
1784
        safe_close(m->cgroups_agent_fd);
708✔
1785
        safe_close_pair(m->user_lookup_fds);
708✔
1786
        safe_close_pair(m->handoff_timestamp_fds);
708✔
1787
        safe_close_pair(m->pidref_transport_fds);
708✔
1788

1789
        manager_close_ask_password(m);
708✔
1790

1791
        manager_close_idle_pipe(m);
708✔
1792

1793
        sd_event_unref(m->event);
708✔
1794

1795
        free(m->notify_socket);
708✔
1796

1797
        lookup_paths_done(&m->lookup_paths);
708✔
1798
        strv_free(m->transient_environment);
708✔
1799
        strv_free(m->client_environment);
708✔
1800

1801
        hashmap_free(m->cgroup_unit);
708✔
1802
        manager_free_unit_name_maps(m);
708✔
1803

1804
        free(m->switch_root);
708✔
1805
        free(m->switch_root_init);
708✔
1806

1807
        sd_bus_track_unref(m->subscribed);
708✔
1808
        strv_free(m->subscribed_as_strv);
708✔
1809

1810
        unit_defaults_done(&m->defaults);
708✔
1811

1812
        FOREACH_ARRAY(map, m->units_needing_mounts_for, _UNIT_MOUNT_DEPENDENCY_TYPE_MAX) {
2,124✔
1813
                assert(hashmap_isempty(*map));
1,416✔
1814
                hashmap_free(*map);
1,416✔
1815
        }
1816

1817
        hashmap_free(m->uid_refs);
708✔
1818
        hashmap_free(m->gid_refs);
708✔
1819

1820
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
4,248✔
1821
                free(*i);
3,540✔
1822

1823
        free(m->received_credentials_directory);
708✔
1824
        free(m->received_encrypted_credentials_directory);
708✔
1825

1826
        free(m->watchdog_pretimeout_governor);
708✔
1827
        free(m->watchdog_pretimeout_governor_overridden);
708✔
1828

1829
        fw_ctx_free(m->fw_ctx);
708✔
1830

1831
#if BPF_FRAMEWORK
1832
        bpf_restrict_fs_destroy(m->restrict_fs);
708✔
1833
#endif
1834

1835
        safe_close(m->executor_fd);
708✔
1836

1837
        return mfree(m);
708✔
1838
}
1839

1840
static void manager_enumerate_perpetual(Manager *m) {
730✔
1841
        assert(m);
730✔
1842

1843
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
730✔
1844
                return;
1845

1846
        /* Let's ask every type to load all units from disk/kernel that it might know */
1847
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,420✔
1848
                if (!unit_type_supported(c)) {
3,135✔
1849
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
456✔
1850
                        continue;
456✔
1851
                }
1852

1853
                if (unit_vtable[c]->enumerate_perpetual)
2,679✔
1854
                        unit_vtable[c]->enumerate_perpetual(m);
855✔
1855
        }
1856
}
1857

1858
static void manager_enumerate(Manager *m) {
730✔
1859
        assert(m);
730✔
1860

1861
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
730✔
1862
                return;
1863

1864
        /* Let's ask every type to load all units from disk/kernel that it might know */
1865
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,420✔
1866
                if (!unit_type_supported(c)) {
3,135✔
1867
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
456✔
1868
                        continue;
456✔
1869
                }
1870

1871
                if (unit_vtable[c]->enumerate)
2,679✔
1872
                        unit_vtable[c]->enumerate(m);
551✔
1873
        }
1874

1875
        manager_dispatch_load_queue(m);
285✔
1876
}
1877

1878
static void manager_coldplug(Manager *m) {
730✔
1879
        Unit *u;
730✔
1880
        char *k;
730✔
1881
        int r;
730✔
1882

1883
        assert(m);
730✔
1884

1885
        log_debug("Invoking unit coldplug() handlers%s", glyph(GLYPH_ELLIPSIS));
1,062✔
1886

1887
        /* Let's place the units back into their deserialized state */
1888
        HASHMAP_FOREACH_KEY(u, k, m->units) {
50,869✔
1889

1890
                /* ignore aliases */
1891
                if (u->id != k)
49,409✔
1892
                        continue;
1,230✔
1893

1894
                r = unit_coldplug(u);
48,179✔
1895
                if (r < 0)
48,179✔
1896
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
50,139✔
1897
        }
1898
}
730✔
1899

1900
static void manager_catchup(Manager *m) {
730✔
1901
        Unit *u;
730✔
1902
        char *k;
730✔
1903

1904
        assert(m);
730✔
1905

1906
        log_debug("Invoking unit catchup() handlers%s", glyph(GLYPH_ELLIPSIS));
1,062✔
1907

1908
        /* Let's catch up on any state changes that happened while we were reloading/reexecing */
1909
        HASHMAP_FOREACH_KEY(u, k, m->units) {
50,139✔
1910

1911
                /* ignore aliases */
1912
                if (u->id != k)
49,409✔
1913
                        continue;
1,230✔
1914

1915
                unit_catchup(u);
48,179✔
1916
        }
1917
}
730✔
1918

1919
static void manager_distribute_fds(Manager *m, FDSet *fds) {
706✔
1920
        Unit *u;
706✔
1921

1922
        assert(m);
706✔
1923

1924
        HASHMAP_FOREACH(u, m->units) {
12,168✔
1925

1926
                if (fdset_isempty(fds))
11,689✔
1927
                        break;
1928

1929
                if (!UNIT_VTABLE(u)->distribute_fds)
11,462✔
1930
                        continue;
10,365✔
1931

1932
                UNIT_VTABLE(u)->distribute_fds(u, fds);
1,097✔
1933
        }
1934
}
706✔
1935

1936
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
59,827✔
1937
        Unit *u;
59,827✔
1938

1939
        assert(m);
59,827✔
1940

1941
        /* This checks whether the dbus instance we are supposed to expose our APIs on is up. We check both the socket
1942
         * and the service unit. If the 'deserialized' parameter is true we'll check the deserialized state of the unit
1943
         * rather than the current one. */
1944

1945
        if (MANAGER_IS_TEST_RUN(m))
59,827✔
1946
                return false;
1947

1948
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
58,983✔
1949
        if (!u)
58,983✔
1950
                return false;
1951
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
104,730✔
1952
                return false;
1953

1954
        u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
9,952✔
1955
        if (!u)
9,952✔
1956
                return false;
1957
        if (!IN_SET((deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state),
19,904✔
1958
                    SERVICE_RUNNING,
1959
                    SERVICE_MOUNTING,
1960
                    SERVICE_RELOAD,
1961
                    SERVICE_RELOAD_NOTIFY,
1962
                    SERVICE_RELOAD_SIGNAL))
1963
                return false;
794✔
1964

1965
        return true;
1966
}
1967

1968
static void manager_setup_bus(Manager *m) {
706✔
1969
        assert(m);
706✔
1970

1971
        if (MANAGER_IS_TEST_RUN(m))
706✔
1972
                return;
1973

1974
        /* Let's set up our private bus connection now, unconditionally */
1975
        (void) bus_init_private(m);
249✔
1976

1977
        /* If we are in --user mode also connect to the system bus now */
1978
        if (MANAGER_IS_USER(m))
249✔
1979
                (void) bus_init_system(m);
137✔
1980

1981
        /* Let's connect to the bus now, but only if the unit is supposed to be up */
1982
        if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
249✔
1983
                (void) bus_init_api(m);
28✔
1984

1985
                if (MANAGER_IS_SYSTEM(m))
28✔
1986
                        (void) bus_init_system(m);
27✔
1987
        }
1988
}
1989

1990
static void manager_preset_all(Manager *m) {
706✔
1991
        int r;
706✔
1992

1993
        assert(m);
706✔
1994

1995
        if (m->first_boot <= 0)
706✔
1996
                return;
1997

1998
        if (!MANAGER_IS_SYSTEM(m))
17✔
1999
                return;
2000

2001
        if (MANAGER_IS_TEST_RUN(m))
17✔
2002
                return;
2003

2004
        /* If this is the first boot, and we are in the host system, then preset everything */
2005
        UnitFilePresetMode mode =
17✔
2006
                ENABLE_FIRST_BOOT_FULL_PRESET ? UNIT_FILE_PRESET_FULL : UNIT_FILE_PRESET_ENABLE_ONLY;
2007

2008
        r = unit_file_preset_all(RUNTIME_SCOPE_SYSTEM, 0, NULL, mode, NULL, NULL);
17✔
2009
        if (r < 0)
17✔
2010
                log_full_errno(r == -EEXIST ? LOG_NOTICE : LOG_WARNING, r,
×
2011
                               "Failed to populate /etc with preset unit settings, ignoring: %m");
2012
        else
2013
                log_info("Populated /etc with preset unit settings.");
17✔
2014
}
2015

2016
static void manager_ready(Manager *m) {
730✔
2017
        assert(m);
730✔
2018

2019
        /* After having loaded everything, do the final round of catching up with what might have changed */
2020

2021
        m->objective = MANAGER_OK; /* Tell everyone we are up now */
730✔
2022

2023
        /* It might be safe to log to the journal now and connect to dbus */
2024
        manager_recheck_journal(m);
730✔
2025
        manager_recheck_dbus(m);
730✔
2026

2027
        /* Let's finally catch up with any changes that took place while we were reloading/reexecing */
2028
        manager_catchup(m);
730✔
2029

2030
        /* Create a file which will indicate when the manager started loading units the last time. */
2031
        if (MANAGER_IS_SYSTEM(m))
730✔
2032
                (void) touch_file("/run/systemd/systemd-units-load", false,
574✔
2033
                        m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].realtime ?: now(CLOCK_REALTIME),
574✔
2034
                        UID_INVALID, GID_INVALID, 0444);
2035
}
730✔
2036

2037
Manager* manager_reloading_start(Manager *m) {
239✔
2038
        m->n_reloading++;
239✔
2039
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
239✔
2040
        return m;
239✔
2041
}
2042

2043
void manager_reloading_stopp(Manager **m) {
911✔
2044
        if (*m) {
911✔
2045
                assert((*m)->n_reloading > 0);
215✔
2046
                (*m)->n_reloading--;
215✔
2047
        }
2048
}
911✔
2049

2050
static int manager_make_runtime_dir(Manager *m) {
706✔
2051
        int r;
706✔
2052

2053
        assert(m);
706✔
2054

2055
        _cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
1,412✔
2056
        if (!d)
706✔
2057
                return log_oom();
×
2058

2059
        r = mkdir_label(d, 0755);
706✔
2060
        if (r < 0 && r != -EEXIST)
706✔
2061
                return log_error_errno(r, "Failed to create directory '%s/': %m", d);
×
2062

2063
        return 0;
2064
}
2065

2066
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
706✔
2067
        int r;
706✔
2068

2069
        assert(m);
706✔
2070

2071
        r = manager_make_runtime_dir(m);
706✔
2072
        if (r < 0)
706✔
2073
                return r;
2074

2075
        /* If we are running in test mode, we still want to run the generators,
2076
         * but we should not touch the real generator directories. */
2077
        r = lookup_paths_init_or_warn(&m->lookup_paths, m->runtime_scope,
706✔
2078
                                      MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
706✔
2079
                                      root);
2080
        if (r < 0)
706✔
2081
                return r;
2082

2083
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
706✔
2084
        r = manager_run_environment_generators(m);
706✔
2085
        if (r >= 0)
706✔
2086
                r = manager_run_generators(m);
706✔
2087
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
706✔
2088
        if (r < 0)
706✔
2089
                return r;
2090

2091
        manager_preset_all(m);
706✔
2092

2093
        lookup_paths_log(&m->lookup_paths);
706✔
2094

2095
        {
2096
                /* This block is (optionally) done with the reloading counter bumped */
2097
                _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
706✔
2098

2099
                /* Make sure we don't have a left-over from a previous run */
2100
                if (!serialization)
706✔
2101
                        (void) rm_rf(m->lookup_paths.transient, 0);
672✔
2102

2103
                /* If we will deserialize make sure that during enumeration this is already known, so we increase the
2104
                 * counter here already */
2105
                if (serialization)
34✔
2106
                        reloading = manager_reloading_start(m);
34✔
2107

2108
                /* First, enumerate what we can from all config files */
2109
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
706✔
2110
                manager_enumerate_perpetual(m);
706✔
2111
                manager_enumerate(m);
706✔
2112
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
706✔
2113

2114
                /* Second, deserialize if there is something to deserialize */
2115
                if (serialization) {
706✔
2116
                        r = manager_deserialize(m, serialization, fds);
34✔
2117
                        if (r < 0)
34✔
2118
                                return log_error_errno(r, "Deserialization failed: %m");
×
2119
                }
2120

2121
                if (m->previous_objective >= 0) {
706✔
2122
                        if (IN_SET(m->previous_objective, MANAGER_REEXECUTE, MANAGER_SOFT_REBOOT, MANAGER_SWITCH_ROOT))
34✔
2123
                                log_debug("Launching as effect of a '%s' operation.",
34✔
2124
                                          manager_objective_to_string(m->previous_objective));
2125
                        else
2126
                                log_warning("Got unexpected previous objective '%s', ignoring.",
×
2127
                                            manager_objective_to_string(m->previous_objective));
2128
                }
2129

2130
                /* If we are in a new soft-reboot iteration bump the counter now before starting units, so
2131
                 * that they can reliably read it. We get the previous objective from serialized state. */
2132
                if (m->previous_objective == MANAGER_SOFT_REBOOT)
706✔
2133
                        m->soft_reboots_count++;
×
2134

2135
                /* Any fds left? Find some unit which wants them. This is useful to allow container managers to pass
2136
                 * some file descriptors to us pre-initialized. This enables socket-based activation of entire
2137
                 * containers. */
2138
                manager_distribute_fds(m, fds);
706✔
2139

2140
                /* We might have deserialized the notify fd, but if we didn't then let's create it now */
2141
                r = manager_setup_notify(m);
706✔
2142
                if (r < 0)
706✔
2143
                        /* No sense to continue without notifications, our children would fail anyway. */
2144
                        return r;
2145

2146
                r = manager_setup_cgroups_agent(m);
706✔
2147
                if (r < 0)
706✔
2148
                        /* Likewise, no sense to continue without empty cgroup notifications. */
2149
                        return r;
2150

2151
                r = manager_setup_user_lookup_fd(m);
706✔
2152
                if (r < 0)
706✔
2153
                        /* This shouldn't fail, except if things are really broken. */
2154
                        return r;
2155

2156
                r = manager_setup_handoff_timestamp_fd(m);
706✔
2157
                if (r < 0)
706✔
2158
                        /* This shouldn't fail, except if things are really broken. */
2159
                        return r;
2160

2161
                r = manager_setup_pidref_transport_fd(m);
706✔
2162
                if (r < 0)
706✔
2163
                        /* This shouldn't fail, except if things are really broken. */
2164
                        return r;
2165

2166
                /* Connect to the bus if we are good for it */
2167
                manager_setup_bus(m);
706✔
2168

2169
                r = manager_varlink_init(m);
706✔
2170
                if (r < 0)
706✔
2171
                        log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
×
2172

2173
                /* Third, fire things up! */
2174
                manager_coldplug(m);
706✔
2175

2176
                /* Clean up runtime objects */
2177
                manager_vacuum(m);
706✔
2178

2179
                if (serialization)
706✔
2180
                        /* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
2181
                         * reload is finished */
2182
                        m->send_reloading_done = true;
34✔
2183
        }
2184

2185
        manager_ready(m);
706✔
2186

2187
        manager_set_switching_root(m, false);
706✔
2188

2189
        return 0;
706✔
2190
}
2191

2192
int manager_add_job_full(
1,614✔
2193
                Manager *m,
2194
                JobType type,
2195
                Unit *unit,
2196
                JobMode mode,
2197
                TransactionAddFlags extra_flags,
2198
                Set *affected_jobs,
2199
                sd_bus_error *error,
2200
                Job **ret) {
2201

2202
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,614✔
2203
        int r;
1,614✔
2204

2205
        assert(m);
1,614✔
2206
        assert(type >= 0 && type < _JOB_TYPE_MAX);
1,614✔
2207
        assert(unit);
1,614✔
2208
        assert(mode >= 0 && mode < _JOB_MODE_MAX);
1,614✔
2209
        assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
1,614✔
2210

2211
        if (mode == JOB_ISOLATE && type != JOB_START)
1,614✔
2212
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
×
2213

2214
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,614✔
2215
                return sd_bus_error_set(error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
24✔
2216

2217
        if (mode == JOB_TRIGGERING && type != JOB_STOP)
1,590✔
2218
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
×
2219

2220
        if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
1,590✔
2221
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=restart-dependencies is only valid for start.");
×
2222

2223
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
2,795✔
2224

2225
        type = job_type_collapse(type, unit);
1,590✔
2226

2227
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1,590✔
2228
        if (!tr)
1,590✔
2229
                return -ENOMEM;
2230

2231
        r = transaction_add_job_and_dependencies(
4,770✔
2232
                        tr,
2233
                        type,
2234
                        unit,
2235
                        /* by= */ NULL,
2236
                        TRANSACTION_MATTERS |
2237
                        (IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
1,590✔
2238
                        (mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
1,590✔
2239
                        (mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
3,171✔
2240
                        extra_flags,
2241
                        error);
2242
        if (r < 0)
1,590✔
2243
                return r;
2244

2245
        if (mode == JOB_ISOLATE) {
1,584✔
2246
                r = transaction_add_isolate_jobs(tr, m);
258✔
2247
                if (r < 0)
258✔
2248
                        return r;
2249
        }
2250

2251
        if (mode == JOB_TRIGGERING) {
1,584✔
2252
                r = transaction_add_triggering_jobs(tr, unit);
×
2253
                if (r < 0)
×
2254
                        return r;
2255
        }
2256

2257
        r = transaction_activate(tr, m, mode, affected_jobs, error);
1,584✔
2258
        if (r < 0)
1,584✔
2259
                return r;
2260

2261
        log_unit_debug(unit,
2,775✔
2262
                       "Enqueued job %s/%s as %u", unit->id,
2263
                       job_type_to_string(type), (unsigned) tr->anchor_job->id);
2264

2265
        if (ret)
1,580✔
2266
                *ret = tr->anchor_job;
732✔
2267

2268
        tr = transaction_free(tr);
1,580✔
2269
        return 0;
1,580✔
2270
}
2271

2272
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
161✔
2273
        Unit *unit = NULL;  /* just to appease gcc, initialization is not really necessary */
161✔
2274
        int r;
161✔
2275

2276
        assert(m);
161✔
2277
        assert(type < _JOB_TYPE_MAX);
161✔
2278
        assert(name);
161✔
2279
        assert(mode < _JOB_MODE_MAX);
161✔
2280

2281
        r = manager_load_unit(m, name, NULL, NULL, &unit);
161✔
2282
        if (r < 0)
161✔
2283
                return r;
161✔
2284
        assert(unit);
161✔
2285

2286
        return manager_add_job_full(m, type, unit, mode, /* extra_flags = */ 0, affected_jobs, e, ret);
161✔
2287
}
2288

2289
int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
137✔
2290
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
137✔
2291
        int r;
137✔
2292

2293
        assert(m);
137✔
2294
        assert(type < _JOB_TYPE_MAX);
137✔
2295
        assert(name);
137✔
2296
        assert(mode < _JOB_MODE_MAX);
137✔
2297

2298
        r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
137✔
2299
        if (r < 0)
137✔
2300
                return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
×
2301

2302
        return r;
2303
}
2304

2305
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
9,130✔
2306
        int r;
9,130✔
2307
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
9,130✔
2308

2309
        assert(m);
9,130✔
2310
        assert(unit);
9,130✔
2311
        assert(mode < _JOB_MODE_MAX);
9,130✔
2312
        assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
9,130✔
2313

2314
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
9,130✔
2315
        if (!tr)
9,130✔
2316
                return -ENOMEM;
2317

2318
        /* We need an anchor job */
2319
        r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
9,130✔
2320
        if (r < 0)
9,130✔
2321
                return r;
2322

2323
        /* Failure in adding individual dependencies is ignored, so this always succeeds. */
2324
        transaction_add_propagate_reload_jobs(
9,130✔
2325
                        tr,
2326
                        unit,
2327
                        tr->anchor_job,
9,130✔
2328
                        mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0);
2329

2330
        r = transaction_activate(tr, m, mode, NULL, e);
9,130✔
2331
        if (r < 0)
9,130✔
2332
                return r;
2333

2334
        tr = transaction_free(tr);
9,130✔
2335
        return 0;
9,130✔
2336
}
2337

2338
Job *manager_get_job(Manager *m, uint32_t id) {
23,278✔
2339
        assert(m);
23,278✔
2340

2341
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
23,278✔
2342
}
2343

2344
Unit *manager_get_unit(Manager *m, const char *name) {
2,364,342✔
2345
        assert(m);
2,364,342✔
2346
        assert(name);
2,364,342✔
2347

2348
        return hashmap_get(m->units, name);
2,364,342✔
2349
}
2350

2351
static int manager_dispatch_target_deps_queue(Manager *m) {
345,559✔
2352
        Unit *u;
345,559✔
2353
        int r = 0;
345,559✔
2354

2355
        assert(m);
345,559✔
2356

2357
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
404,898✔
2358
                _cleanup_free_ Unit **targets = NULL;
59,339✔
2359
                int n_targets;
59,339✔
2360

2361
                assert(u->in_target_deps_queue);
59,339✔
2362

2363
                u->in_target_deps_queue = false;
59,339✔
2364

2365
                /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2366
                 * dependencies, and we can't have it that hash tables we iterate through are modified while
2367
                 * we are iterating through them. */
2368
                n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
59,339✔
2369
                if (n_targets < 0)
59,339✔
2370
                        return n_targets;
2371

2372
                FOREACH_ARRAY(i, targets, n_targets) {
128,357✔
2373
                        r = unit_add_default_target_dependency(u, *i);
69,018✔
2374
                        if (r < 0)
69,018✔
2375
                                return r;
2376
                }
2377
        }
2378

2379
        return r;
2380
}
2381

2382
unsigned manager_dispatch_load_queue(Manager *m) {
381,780✔
2383
        Unit *u;
381,780✔
2384
        unsigned n = 0;
381,780✔
2385

2386
        assert(m);
381,780✔
2387

2388
        /* Make sure we are not run recursively */
2389
        if (m->dispatching_load_queue)
381,780✔
2390
                return 0;
2391

2392
        m->dispatching_load_queue = true;
345,559✔
2393

2394
        /* Dispatches the load queue. Takes a unit from the queue and
2395
         * tries to load its data until the queue is empty */
2396

2397
        while ((u = m->load_queue)) {
427,378✔
2398
                assert(u->in_load_queue);
81,819✔
2399

2400
                unit_load(u);
81,819✔
2401
                n++;
81,819✔
2402
        }
2403

2404
        m->dispatching_load_queue = false;
345,559✔
2405

2406
        /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2407
         * should be loaded and have aliases resolved */
2408
        (void) manager_dispatch_target_deps_queue(m);
345,559✔
2409

2410
        return n;
345,559✔
2411
}
2412

2413
bool manager_unit_cache_should_retry_load(Unit *u) {
527,243✔
2414
        assert(u);
527,243✔
2415

2416
        /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2417
         * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2418
         * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
2419
        if (u->load_state != UNIT_NOT_FOUND)
527,243✔
2420
                return false;
2421

2422
        /* The cache has been updated since the last time we tried to load the unit. There might be new
2423
         * fragment paths to read. */
2424
        if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
2,820✔
2425
                return true;
2426

2427
        /* The cache needs to be updated because there are modifications on disk. */
2428
        return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
2,820✔
2429
}
2430

2431
int manager_load_unit_prepare(
586,444✔
2432
                Manager *m,
2433
                const char *name,
2434
                const char *path,
2435
                sd_bus_error *e,
2436
                Unit **ret) {
2437

2438
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2439
        _cleanup_free_ char *nbuf = NULL;
586,444✔
2440
        int r;
586,444✔
2441

2442
        assert(m);
586,444✔
2443
        assert(ret);
586,444✔
2444
        assert(name || path);
586,444✔
2445

2446
        /* This will prepare the unit for loading, but not actually load anything from disk. */
2447

2448
        if (path && !path_is_absolute(path))
586,444✔
2449
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2450

2451
        if (!name) {
586,444✔
2452
                r = path_extract_filename(path, &nbuf);
435✔
2453
                if (r < 0)
435✔
2454
                        return r;
2455
                if (r == O_DIRECTORY)
435✔
2456
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2457

2458
                name = nbuf;
435✔
2459
        }
2460

2461
        UnitType t = unit_name_to_type(name);
586,444✔
2462

2463
        if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
586,444✔
2464
                if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
×
2465
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
×
2466

2467
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
×
2468
        }
2469

2470
        Unit *unit = manager_get_unit(m, name);
586,444✔
2471
        if (unit) {
586,444✔
2472
                /* The time-based cache allows new units to be started without daemon-reload,
2473
                 * but if they are already referenced (because of dependencies or ordering)
2474
                 * then we have to force a load of the fragment. As an optimization, check
2475
                 * first if anything in the usual paths was modified since the last time
2476
                 * the cache was loaded. Also check if the last time an attempt to load the
2477
                 * unit was made was before the most recent cache refresh, so that we know
2478
                 * we need to try again — even if the cache is current, it might have been
2479
                 * updated in a different context before we had a chance to retry loading
2480
                 * this particular unit. */
2481
                if (manager_unit_cache_should_retry_load(unit))
526,543✔
UNCOV
2482
                        unit->load_state = UNIT_STUB;
×
2483
                else {
2484
                        *ret = unit;
526,543✔
2485
                        return 0;  /* The unit was already loaded */
526,543✔
2486
                }
2487
        } else {
2488
                unit = cleanup_unit = unit_new(m, unit_vtable[t]->object_size);
59,901✔
2489
                if (!unit)
59,901✔
2490
                        return -ENOMEM;
2491
        }
2492

2493
        if (path) {
59,901✔
2494
                r = free_and_strdup(&unit->fragment_path, path);
435✔
2495
                if (r < 0)
435✔
2496
                        return r;
2497
        }
2498

2499
        r = unit_add_name(unit, name);
59,901✔
2500
        if (r < 0)
59,901✔
2501
                return r;
2502

2503
        unit_add_to_load_queue(unit);
59,901✔
2504
        unit_add_to_dbus_queue(unit);
59,901✔
2505
        unit_add_to_gc_queue(unit);
59,901✔
2506

2507
        *ret = unit;
59,901✔
2508
        TAKE_PTR(cleanup_unit);
59,901✔
2509

2510
        return 1;  /* The unit was added the load queue */
59,901✔
2511
}
2512

2513
int manager_load_unit(
565,633✔
2514
                Manager *m,
2515
                const char *name,
2516
                const char *path,
2517
                sd_bus_error *e,
2518
                Unit **ret) {
2519
        int r;
565,633✔
2520

2521
        assert(m);
565,633✔
2522
        assert(ret);
565,633✔
2523

2524
        /* This will load the unit config, but not actually start any services or anything. */
2525

2526
        r = manager_load_unit_prepare(m, name, path, e, ret);
565,633✔
2527
        if (r <= 0)
565,633✔
2528
                return r;
2529

2530
        /* Unit was newly loaded */
2531
        manager_dispatch_load_queue(m);
39,106✔
2532
        *ret = unit_follow_merge(*ret);
39,106✔
2533
        return 0;
39,106✔
2534
}
2535

2536
int manager_load_startable_unit_or_warn(
694✔
2537
                Manager *m,
2538
                const char *name,
2539
                const char *path,
2540
                Unit **ret) {
2541

2542
        /* Load a unit, make sure it loaded fully and is not masked. */
2543

2544
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
694✔
2545
        Unit *unit;
694✔
2546
        int r;
694✔
2547

2548
        r = manager_load_unit(m, name, path, &error, &unit);
694✔
2549
        if (r < 0)
694✔
2550
                return log_error_errno(r, "Failed to load %s %s: %s",
×
2551
                                       name ? "unit" : "unit file", name ?: path,
2552
                                       bus_error_message(&error, r));
2553

2554
        r = bus_unit_validate_load_state(unit, &error);
694✔
2555
        if (r < 0)
694✔
2556
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2557

2558
        *ret = unit;
685✔
2559
        return 0;
685✔
2560
}
2561

2562
void manager_clear_jobs(Manager *m) {
425✔
2563
        Job *j;
425✔
2564

2565
        assert(m);
425✔
2566

2567
        while ((j = hashmap_first(m->jobs)))
452✔
2568
                /* No need to recurse. We're cancelling all jobs. */
2569
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
27✔
2570
}
425✔
2571

2572
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
3,822✔
2573
        assert(m);
3,822✔
2574

2575
        for (;;) {
×
2576
                Unit *u;
3,822✔
2577

2578
                u = manager_get_unit_by_pidref_watching(m, pid);
3,822✔
2579
                if (!u)
3,822✔
2580
                        break;
2581

2582
                unit_unwatch_pidref(u, pid);
×
2583
        }
2584
}
3,822✔
2585

2586
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
7,373✔
2587
        Manager *m = ASSERT_PTR(userdata);
7,373✔
2588
        Job *j;
7,373✔
2589

2590
        assert(source);
7,373✔
2591

2592
        while ((j = prioq_peek(m->run_queue))) {
69,266✔
2593
                assert(j->installed);
61,893✔
2594
                assert(j->in_run_queue);
61,893✔
2595

2596
                (void) job_run_and_invalidate(j);
61,893✔
2597
        }
2598

2599
        if (m->n_running_jobs > 0)
7,373✔
2600
                manager_watch_jobs_in_progress(m);
5,811✔
2601

2602
        if (m->n_on_console > 0)
7,373✔
2603
                manager_watch_idle_pipe(m);
603✔
2604

2605
        return 1;
7,373✔
2606
}
2607

2608
void manager_trigger_run_queue(Manager *m) {
64,082✔
2609
        int r;
64,082✔
2610

2611
        assert(m);
64,082✔
2612

2613
        r = sd_event_source_set_enabled(
128,071✔
2614
                        m->run_queue_event_source,
2615
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
64,082✔
2616
        if (r < 0)
64,082✔
2617
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2618
}
64,082✔
2619

2620
static unsigned manager_dispatch_dbus_queue(Manager *m) {
311,174✔
2621
        unsigned n = 0, budget;
311,174✔
2622
        Unit *u;
311,174✔
2623
        Job *j;
311,174✔
2624

2625
        assert(m);
311,174✔
2626

2627
        /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2628
         * as we can. There's no point in throttling generation of signals in that case. */
2629
        if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message)
311,174✔
2630
                budget = UINT_MAX; /* infinite budget in this case */
2631
        else {
2632
                /* Anything to do at all? */
2633
                if (!m->dbus_unit_queue && !m->dbus_job_queue)
311,116✔
2634
                        return 0;
2635

2636
                /* Do we have overly many messages queued at the moment? If so, let's not enqueue more on top, let's
2637
                 * sit this cycle out, and process things in a later cycle when the queues got a bit emptier. */
2638
                if (manager_bus_n_queued_write(m) > MANAGER_BUS_BUSY_THRESHOLD)
8,667✔
2639
                        return 0;
2640

2641
                /* Only process a certain number of units/jobs per event loop iteration. Even if the bus queue wasn't
2642
                 * overly full before this call we shouldn't increase it in size too wildly in one step, and we
2643
                 * shouldn't monopolize CPU time with generating these messages. Note the difference in counting of
2644
                 * this "budget" and the "threshold" above: the "budget" is decreased only once per generated message,
2645
                 * regardless how many buses/direct connections it is enqueued on, while the "threshold" is applied to
2646
                 * each queued instance of bus message, i.e. if the same message is enqueued to five buses/direct
2647
                 * connections it will be counted five times. This difference in counting ("references"
2648
                 * vs. "instances") is primarily a result of the fact that it's easier to implement it this way,
2649
                 * however it also reflects the thinking that the "threshold" should put a limit on used queue memory,
2650
                 * i.e. space, while the "budget" should put a limit on time. Also note that the "threshold" is
2651
                 * currently chosen much higher than the "budget". */
2652
                budget = MANAGER_BUS_MESSAGE_BUDGET;
2653
        }
2654

2655
        while (budget != 0 && (u = m->dbus_unit_queue)) {
45,199✔
2656

2657
                assert(u->in_dbus_queue);
36,474✔
2658

2659
                bus_unit_send_change_signal(u);
36,474✔
2660
                n++;
36,474✔
2661

2662
                if (budget != UINT_MAX)
36,474✔
2663
                        budget--;
25,064✔
2664
        }
2665

2666
        while (budget != 0 && (j = m->dbus_job_queue)) {
44,057✔
2667
                assert(j->in_dbus_queue);
35,332✔
2668

2669
                bus_job_send_change_signal(j);
35,332✔
2670
                n++;
35,332✔
2671

2672
                if (budget != UINT_MAX)
35,332✔
2673
                        budget--;
34,579✔
2674
        }
2675

2676
        if (m->send_reloading_done) {
8,725✔
2677
                m->send_reloading_done = false;
58✔
2678
                bus_manager_send_reloading(m, false);
58✔
2679
                n++;
58✔
2680
        }
2681

2682
        if (m->pending_reload_message) {
8,725✔
2683
                bus_send_pending_reload_message(m);
24✔
2684
                n++;
24✔
2685
        }
2686

2687
        return n;
2688
}
2689

2690
static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
×
2691
        Manager *m = userdata;
×
2692
        char buf[PATH_MAX];
×
2693
        ssize_t n;
×
2694

2695
        n = recv(fd, buf, sizeof(buf), 0);
×
2696
        if (n < 0)
×
2697
                return log_error_errno(errno, "Failed to read cgroups agent message: %m");
×
2698
        if (n == 0) {
×
2699
                log_error("Got zero-length cgroups agent message, ignoring.");
×
2700
                return 0;
×
2701
        }
2702
        if ((size_t) n >= sizeof(buf)) {
×
2703
                log_error("Got overly long cgroups agent message, ignoring.");
×
2704
                return 0;
×
2705
        }
2706

2707
        if (memchr(buf, 0, n)) {
×
2708
                log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
×
2709
                return 0;
×
2710
        }
2711
        buf[n] = 0;
×
2712

2713
        manager_notify_cgroup_empty(m, buf);
×
2714
        (void) bus_forward_agent_released(m, buf);
×
2715

2716
        return 0;
2717
}
2718

2719
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
7,838✔
2720

2721
        /* nothing else must be sent when using BARRIER=1 */
2722
        if (strv_contains(tags, "BARRIER=1")) {
7,838✔
2723
                if (strv_length(tags) != 1)
12✔
2724
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
×
2725
                else if (fdset_size(fds) != 1)
12✔
2726
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
×
2727

2728
                /* Drop the message if BARRIER=1 was found */
2729
                return true;
12✔
2730
        }
2731

2732
        return false;
2733
}
2734

2735
static void manager_invoke_notify_message(
15,579✔
2736
                Manager *m,
2737
                Unit *u,
2738
                PidRef *pidref,
2739
                const struct ucred *ucred,
2740
                char * const *tags,
2741
                FDSet *fds) {
2742

2743
        assert(m);
15,579✔
2744
        assert(u);
15,579✔
2745
        assert(pidref_is_set(pidref));
15,579✔
2746
        assert(ucred);
15,579✔
2747
        assert(pidref->pid == ucred->pid);
15,579✔
2748
        assert(tags);
15,579✔
2749

2750
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
15,579✔
2751
                return;
2752
        u->notifygen = m->notifygen;
7,826✔
2753

2754
        if (UNIT_VTABLE(u)->notify_message)
7,826✔
2755
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
7,826✔
2756

2757
        else if (DEBUG_LOGGING) {
×
2758
                _cleanup_free_ char *joined = strv_join(tags, ", ");
×
2759
                char buf[CELLESCAPE_DEFAULT_LENGTH];
×
2760

2761
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
×
2762
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
2763
        }
2764
}
2765

2766
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
20,812✔
2767
        /* Determine array of every unit that is interested in the specified process */
2768

2769
        assert(m);
20,812✔
2770
        assert(pidref_is_set(pidref));
20,812✔
2771

2772
        Unit *u1, *u2, **array;
20,812✔
2773
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
20,812✔
2774
        u2 = hashmap_get(m->watch_pids, pidref);
20,812✔
2775
        array = hashmap_get(m->watch_pids_more, pidref);
20,812✔
2776

2777
        size_t n = 0;
20,812✔
2778
        if (u1)
20,812✔
2779
                n++;
20,812✔
2780
        if (u2)
20,812✔
2781
                n++;
15,111✔
2782
        if (array)
20,812✔
2783
                for (size_t j = 0; array[j]; j++)
×
2784
                        n++;
×
2785

2786
        assert(n <= INT_MAX); /* Make sure we can reasonably return the counter as "int" */
20,812✔
2787

2788
        if (ret_units) {
20,812✔
2789
                _cleanup_free_ Unit **units = NULL;
×
2790

2791
                if (n > 0) {
20,812✔
2792
                        units = new(Unit*, n + 1);
20,812✔
2793
                        if (!units)
20,812✔
2794
                                return -ENOMEM;
×
2795

2796
                        /* We return a dense array, and put the "main" unit first, i.e. unit in whose cgroup
2797
                         * the process currently is. Note that we do not bother with filtering duplicates
2798
                         * here. */
2799

2800
                        size_t i = 0;
20,812✔
2801
                        if (u1)
20,812✔
2802
                                units[i++] = u1;
20,812✔
2803
                        if (u2)
20,812✔
2804
                                units[i++] = u2;
15,111✔
2805
                        if (array)
20,812✔
2806
                                for (size_t j = 0; array[j]; j++)
×
2807
                                        units[i++] = array[j];
×
2808
                        assert(i == n);
20,812✔
2809

2810
                        units[i] = NULL; /* end array in an extra NULL */
20,812✔
2811
                }
2812

2813
                *ret_units = TAKE_PTR(units);
20,812✔
2814
        }
2815

2816
        return (int) n;
20,812✔
2817
}
2818

2819
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
7,838✔
2820
        Manager *m = ASSERT_PTR(userdata);
7,838✔
2821
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
7,838✔
2822
        struct ucred ucred;
7,838✔
2823
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
7,838✔
2824
        int r;
7,838✔
2825

2826
        assert(m->notify_fd == fd);
7,838✔
2827

2828
        if (revents != EPOLLIN) {
7,838✔
2829
                log_warning("Got unexpected poll event for notify fd.");
×
2830
                return 0;
×
2831
        }
2832

2833
        _cleanup_strv_free_ char **tags = NULL;
7,838✔
2834
        r = notify_recv_with_fds_strv(m->notify_fd, &tags, &ucred, &pidref, &fds);
7,838✔
2835
        if (r == -EAGAIN)
7,838✔
2836
                return 0;
2837
        if (r < 0)
7,838✔
2838
                /* If this is any other, real error, then stop processing this socket. This of course means
2839
                 * we won't take notification messages anymore, but that's still better than busy looping:
2840
                 * being woken up over and over again, but being unable to actually read the message from the
2841
                 * socket. */
2842
                return r;
2843

2844
        /* Possibly a barrier fd, let's see. */
2845
        if (manager_process_barrier_fd(tags, fds)) {
7,838✔
2846
                log_debug("Received barrier notification message from PID " PID_FMT ".", pidref.pid);
12✔
2847
                return 0;
12✔
2848
        }
2849

2850
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
2851
        m->notifygen++;
7,826✔
2852

2853
        /* Notify every unit that might be interested, which might be multiple. */
2854
        _cleanup_free_ Unit **array = NULL;
7,826✔
2855

2856
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
7,826✔
2857
        if (n_array < 0) {
7,826✔
2858
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", pidref.pid);
×
2859
                return 0;
×
2860
        }
2861
        if (n_array == 0)
7,826✔
2862
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", pidref.pid);
×
2863
        else
2864
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
2865
                 * duplicate units – making sure we only invoke each unit's handler once. */
2866
                FOREACH_ARRAY(u, array, n_array)
23,405✔
2867
                        manager_invoke_notify_message(m, *u, &pidref, &ucred, tags, fds);
15,579✔
2868

2869
        if (!fdset_isempty(fds))
7,826✔
2870
                log_warning("Got extra auxiliary fds with notification message, closing them.");
7,826✔
2871

2872
        return 0;
2873
}
2874

2875
static void manager_invoke_sigchld_event(
12,742✔
2876
                Manager *m,
2877
                Unit *u,
2878
                const siginfo_t *si) {
2879

2880
        assert(m);
12,742✔
2881
        assert(u);
12,742✔
2882
        assert(si);
12,742✔
2883

2884
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2885
        if (u->sigchldgen == m->sigchldgen)
12,742✔
2886
                return;
2887
        u->sigchldgen = m->sigchldgen;
9,186✔
2888

2889
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
18,239✔
2890
        unit_unwatch_pid(u, si->si_pid);
9,186✔
2891

2892
        if (UNIT_VTABLE(u)->sigchld_event)
9,186✔
2893
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
7,927✔
2894
}
2895

2896
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
15,241✔
2897
        Manager *m = ASSERT_PTR(userdata);
15,241✔
2898
        siginfo_t si = {};
15,241✔
2899
        int r;
15,241✔
2900

2901
        assert(source);
15,241✔
2902

2903
        /* First we call waitid() for a PID and do not reap the zombie. That way we can still access
2904
         * /proc/$PID for it while it is a zombie. */
2905

2906
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
15,241✔
2907

2908
                if (errno != ECHILD)
188✔
2909
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
×
2910

2911
                goto turn_off;
188✔
2912
        }
2913

2914
        if (si.si_pid <= 0)
15,053✔
2915
                goto turn_off;
5,868✔
2916

2917
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
9,185✔
2918
                _cleanup_free_ char *name = NULL;
18,370✔
2919
                (void) pid_get_comm(si.si_pid, &name);
9,185✔
2920

2921
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
18,237✔
2922
                          si.si_pid, strna(name),
2923
                          sigchld_code_to_string(si.si_code),
2924
                          si.si_status,
2925
                          strna(si.si_code == CLD_EXITED
2926
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2927
                                : signal_to_string(si.si_status)));
2928

2929
                /* Increase the generation counter used for filtering out duplicate unit invocations */
2930
                m->sigchldgen++;
9,185✔
2931

2932
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
2933
                 * pidfd here any more even if we wanted (since the process just exited). */
2934
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
9,185✔
2935

2936
                /* And now figure out the units this belongs to, there might be multiple... */
2937
                _cleanup_free_ Unit **array = NULL;
9,185✔
2938
                int n_array = manager_get_units_for_pidref(m, &pidref, &array);
9,185✔
2939
                if (n_array < 0)
9,185✔
2940
                        log_warning_errno(n_array, "Failed to get units for process " PID_FMT ", ignoring: %m", si.si_pid);
×
2941
                else if (n_array == 0)
9,185✔
2942
                        log_debug("Got SIGCHLD for process " PID_FMT " we weren't interested in, ignoring.", si.si_pid);
9,185✔
2943
                else {
2944
                        /* We check for an OOM condition, in case we got SIGCHLD before the OOM notification.
2945
                         * We only do this for the cgroup the PID belonged to, which is the f */
2946
                        (void) unit_check_oom(array[0]);
9,185✔
2947

2948
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
2949
                        (void) unit_check_oomd_kill(array[0]);
9,185✔
2950

2951
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
2952
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
2953
                         * iteration. */
2954
                        FOREACH_ARRAY(u, array, n_array)
21,927✔
2955
                                manager_invoke_sigchld_event(m, *u, &si);
12,742✔
2956
                }
2957
        }
2958

2959
        /* And now, we actually reap the zombie. */
2960
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
9,185✔
2961
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
×
2962
                return 0;
15,241✔
2963
        }
2964

2965
        return 0;
2966

2967
turn_off:
6,056✔
2968
        /* All children processed for now, turn off event source */
2969

2970
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
6,056✔
2971
        if (r < 0)
6,056✔
2972
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
×
2973

2974
        return 0;
2975
}
2976

2977
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
136✔
2978
        Job *job;
136✔
2979

2980
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
136✔
2981
                return;
×
2982

2983
        const char *s = unit_status_string(job->unit, NULL);
136✔
2984

2985
        log_info("Activating special unit %s...", s);
136✔
2986

2987
        (void) sd_notifyf(/* unset_environment= */ false,
136✔
2988
                          "STATUS=Activating special unit %s...", s);
2989
        m->status_ready = false;
136✔
2990
}
2991

2992
static void manager_handle_ctrl_alt_del(Manager *m) {
×
2993
        assert(m);
×
2994

2995
        /* If the user presses C-A-D more than 7 times within 2s, we reboot/shutdown immediately,
2996
         * unless it was disabled in system.conf. */
2997

2998
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
×
2999
                manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
×
3000
        else
3001
                emergency_action(
×
3002
                                m,
3003
                                m->cad_burst_action,
3004
                                EMERGENCY_ACTION_WARN,
3005
                                /* reboot_arg= */ NULL,
3006
                                /* exit_status= */ -1,
3007
                                "Ctrl-Alt-Del was pressed more than 7 times within 2s");
3008
}
×
3009

3010
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
5,922✔
3011
        Manager *m = ASSERT_PTR(userdata);
5,922✔
3012
        ssize_t n;
5,922✔
3013
        struct signalfd_siginfo sfsi;
5,922✔
3014
        int r;
5,922✔
3015

3016
        assert(m->signal_fd == fd);
5,922✔
3017

3018
        if (revents != EPOLLIN) {
5,922✔
3019
                log_warning("Got unexpected events from signal file descriptor.");
×
3020
                return 0;
×
3021
        }
3022

3023
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
5,922✔
3024
        if (n < 0) {
5,922✔
3025
                if (ERRNO_IS_TRANSIENT(errno))
×
3026
                        return 0;
3027

3028
                /* We return an error here, which will kill this handler,
3029
                 * to avoid a busy loop on read error. */
3030
                return log_error_errno(errno, "Reading from signal fd failed: %m");
×
3031
        }
3032
        if (n != sizeof(sfsi)) {
5,922✔
3033
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
×
3034
                return 0;
×
3035
        }
3036

3037
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
6,058✔
3038
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
136✔
3039
                            ? LOG_DEBUG : LOG_INFO,
3040
                            &sfsi);
3041

3042
        switch (sfsi.ssi_signo) {
5,922✔
3043

3044
        case SIGCHLD:
5,786✔
3045
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
5,786✔
3046
                if (r < 0)
5,786✔
3047
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
×
3048

3049
                break;
3050

3051
        case SIGTERM:
136✔
3052
                if (MANAGER_IS_SYSTEM(m)) {
136✔
3053
                        /* This is for compatibility with the original sysvinit */
3054
                        m->objective = MANAGER_REEXECUTE;
×
3055
                        break;
×
3056
                }
3057

3058
                _fallthrough_;
136✔
3059
        case SIGINT:
3060
                if (MANAGER_IS_SYSTEM(m))
136✔
3061
                        manager_handle_ctrl_alt_del(m);
×
3062
                else
3063
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
136✔
3064
                break;
3065

3066
        case SIGWINCH:
×
3067
                /* This is a nop on non-init */
3068
                if (MANAGER_IS_SYSTEM(m))
×
3069
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
×
3070

3071
                break;
3072

3073
        case SIGPWR:
×
3074
                /* This is a nop on non-init */
3075
                if (MANAGER_IS_SYSTEM(m))
×
3076
                        manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
×
3077

3078
                break;
3079

3080
        case SIGUSR1:
×
3081
                if (manager_dbus_is_running(m, false)) {
×
3082
                        log_info("Trying to reconnect to bus...");
×
3083

3084
                        (void) bus_init_api(m);
×
3085

3086
                        if (MANAGER_IS_SYSTEM(m))
×
3087
                                (void) bus_init_system(m);
×
3088
                } else
3089
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
×
3090

3091
                break;
3092

3093
        case SIGUSR2: {
×
3094
                _cleanup_free_ char *dump = NULL;
×
3095

3096
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
×
3097
                if (r < 0) {
×
3098
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
×
3099
                        break;
3100
                }
3101

3102
                log_dump(LOG_INFO, dump);
×
3103
                break;
3104
        }
3105

3106
        case SIGHUP:
×
3107
                m->objective = MANAGER_RELOAD;
×
3108
                break;
×
3109

3110
        default: {
×
3111

3112
                if (MANAGER_IS_SYSTEM(m)) {
×
3113
                        /* Starting SIGRTMIN+0 */
3114
                        static const struct {
×
3115
                                const char *target;
3116
                                JobMode mode;
3117
                        } target_table[] = {
3118
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
3119
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
3120
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
3121
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
3122
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
3123
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
3124
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
3125
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
3126
                        };
3127

3128
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
3129
                        static const ManagerObjective objective_table[] = {
×
3130
                                [0] = MANAGER_HALT,
3131
                                [1] = MANAGER_POWEROFF,
3132
                                [2] = MANAGER_REBOOT,
3133
                                [3] = MANAGER_KEXEC,
3134
                                [4] = MANAGER_SOFT_REBOOT,
3135
                        };
3136

3137
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
×
3138
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
×
3139
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
×
3140
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
×
3141
                                break;
3142
                        }
3143

3144
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
×
3145
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
×
3146
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
×
3147
                                break;
×
3148
                        }
3149
                }
3150

3151
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3152

3153
                case 18: {
×
3154
                        bool generic = false;
×
3155

3156
                        if (sfsi.ssi_code != SI_QUEUE)
×
3157
                                generic = true;
3158
                        else {
3159
                                /* Override a few select commands by our own PID1-specific logic */
3160

3161
                                switch (sfsi.ssi_int) {
×
3162

3163
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
×
3164
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
×
3165
                                        break;
3166

3167
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3168
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3169
                                        break;
3170

3171
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3172
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3173
                                        break;
3174

3175
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3176
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3177
                                        break;
3178

3179
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3180
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3181
                                        break;
3182

3183
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3184
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3185

3186
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
×
3187
                                        if (r < 0) {
×
3188
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
×
3189
                                                break;
3190
                                        }
3191

3192
                                        log_dump(LOG_INFO, dump_jobs);
×
3193
                                        break;
3194
                                }
3195

3196
                                default:
3197
                                        generic = true;
3198
                                }
3199
                        }
3200

3201
                        if (generic)
×
3202
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3203

3204
                        break;
3205
                }
3206

3207
                case 20:
×
3208
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
×
3209
                        break;
3210

3211
                case 21:
×
3212
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
×
3213
                        break;
3214

3215
                case 22:
×
3216
                        manager_override_log_level(m, LOG_DEBUG);
×
3217
                        break;
3218

3219
                case 23:
×
3220
                        manager_restore_original_log_level(m);
×
3221
                        break;
3222

3223
                case 24:
×
3224
                        if (MANAGER_IS_USER(m)) {
×
3225
                                m->objective = MANAGER_EXIT;
×
3226
                                return 0;
×
3227
                        }
3228

3229
                        /* This is a nop on init */
3230
                        break;
3231

3232
                case 25:
×
3233
                        m->objective = MANAGER_REEXECUTE;
×
3234
                        break;
×
3235

3236
                case 26:
×
3237
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
3238
                        manager_restore_original_log_target(m);
×
3239
                        break;
3240

3241
                case 27:
×
3242
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3243
                        break;
3244

3245
                case 28:
×
3246
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3247
                        break;
3248

3249
                default:
3250
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
5,922✔
3251
                }
3252
        }}
3253

3254
        return 0;
3255
}
3256

3257
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
3258
        Manager *m = ASSERT_PTR(userdata);
3✔
3259
        Unit *u;
3✔
3260

3261
        log_struct(LOG_DEBUG,
3✔
3262
                   "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
3263
                   LOG_MESSAGE("Time has been changed"));
3264

3265
        /* Restart the watch */
3266
        (void) manager_setup_time_change(m);
3✔
3267

3268
        HASHMAP_FOREACH(u, m->units)
360✔
3269
                if (UNIT_VTABLE(u)->time_change)
354✔
3270
                        UNIT_VTABLE(u)->time_change(u);
3✔
3271

3272
        return 0;
3✔
3273
}
3274

3275
static int manager_dispatch_timezone_change(
32✔
3276
                sd_event_source *source,
3277
                const struct inotify_event *e,
3278
                void *userdata) {
3279

3280
        Manager *m = ASSERT_PTR(userdata);
32✔
3281
        int changed;
32✔
3282
        Unit *u;
32✔
3283

3284
        log_debug("inotify event for /etc/localtime");
32✔
3285

3286
        changed = manager_read_timezone_stat(m);
32✔
3287
        if (changed <= 0)
32✔
3288
                return changed;
32✔
3289

3290
        /* Something changed, restart the watch, to ensure we watch the new /etc/localtime if it changed */
3291
        (void) manager_setup_timezone_change(m);
13✔
3292

3293
        /* Read the new timezone */
3294
        tzset();
13✔
3295

3296
        log_debug("Timezone has been changed (now: %s).", tzname[daylight]);
13✔
3297

3298
        HASHMAP_FOREACH(u, m->units)
2,248✔
3299
                if (UNIT_VTABLE(u)->timezone_change)
2,222✔
3300
                        UNIT_VTABLE(u)->timezone_change(u);
23✔
3301

3302
        return 0;
13✔
3303
}
3304

3305
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
7✔
3306
        Manager *m = ASSERT_PTR(userdata);
7✔
3307

3308
        assert(m->idle_pipe[2] == fd);
7✔
3309

3310
        /* There's at least one Type=idle child that just gave up on us waiting for the boot process to
3311
         * complete. Let's now turn off any further console output if there's at least one service that needs
3312
         * console access, so that from now on our own output should not spill into that service's output
3313
         * anymore. After all, we support Type=idle only to beautify console output and it generally is set
3314
         * on services that want to own the console exclusively without our interference. */
3315
        m->no_console_output = m->n_on_console > 0;
7✔
3316

3317
        /* Acknowledge the child's request, and let all other children know too that they shouldn't wait
3318
         * any longer by closing the pipes towards them, which is what they are waiting for. */
3319
        manager_close_idle_pipe(m);
7✔
3320

3321
        return 0;
7✔
3322
}
3323

3324
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
403✔
3325
        Manager *m = ASSERT_PTR(userdata);
403✔
3326
        int r;
403✔
3327

3328
        assert(source);
403✔
3329

3330
        manager_print_jobs_in_progress(m);
403✔
3331

3332
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
403✔
3333
        if (r < 0)
403✔
3334
                return r;
3335

3336
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
403✔
3337
}
3338

3339
int manager_loop(Manager *m) {
273✔
3340
        RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
273✔
3341
        int r;
273✔
3342

3343
        assert(m);
273✔
3344
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
273✔
3345

3346
        manager_check_finished(m);
273✔
3347

3348
        /* There might still be some zombies hanging around from before we were exec()'ed. Let's reap them. */
3349
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
273✔
3350
        if (r < 0)
273✔
3351
                return log_error_errno(r, "Failed to enable SIGCHLD event source: %m");
×
3352

3353
        while (m->objective == MANAGER_OK) {
333,906✔
3354

3355
                (void) watchdog_ping();
333,633✔
3356

3357
                if (!ratelimit_below(&rl)) {
333,633✔
3358
                        /* Yay, something is going seriously wrong, pause a little */
3359
                        log_warning("Looping too fast. Throttling execution a little.");
×
3360
                        sleep(1);
×
3361
                }
3362

3363
                if (manager_dispatch_load_queue(m) > 0)
333,633✔
3364
                        continue;
×
3365

3366
                if (manager_dispatch_gc_job_queue(m) > 0)
333,633✔
3367
                        continue;
56✔
3368

3369
                if (manager_dispatch_gc_unit_queue(m) > 0)
333,577✔
3370
                        continue;
11,725✔
3371

3372
                if (manager_dispatch_cleanup_queue(m) > 0)
321,852✔
3373
                        continue;
5,131✔
3374

3375
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
316,721✔
3376
                        continue;
3,505✔
3377

3378
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
313,216✔
3379
                        continue;
×
3380

3381
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
313,216✔
3382
                        continue;
169✔
3383

3384
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
313,047✔
3385
                        continue;
121✔
3386

3387
                if (manager_dispatch_release_resources_queue(m) > 0)
312,926✔
3388
                        continue;
1,752✔
3389

3390
                if (manager_dispatch_dbus_queue(m) > 0)
311,174✔
3391
                        continue;
8,725✔
3392

3393
                /* Sleep for watchdog runtime wait time */
3394
                r = sd_event_run(m->event, watchdog_runtime_wait());
302,449✔
3395
                if (r < 0)
302,449✔
3396
                        return log_error_errno(r, "Failed to run event loop: %m");
×
3397
        }
3398

3399
        return m->objective;
3400
}
3401

3402
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
334,569✔
3403
        _cleanup_free_ char *n = NULL;
334,569✔
3404
        sd_id128_t invocation_id;
334,569✔
3405
        Unit *u;
334,569✔
3406
        int r;
334,569✔
3407

3408
        assert(m);
334,569✔
3409
        assert(s);
334,569✔
3410
        assert(_u);
334,569✔
3411

3412
        r = unit_name_from_dbus_path(s, &n);
334,569✔
3413
        if (r < 0)
334,569✔
3414
                return r;
3415

3416
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
3417
         * we use it as invocation ID. */
3418
        r = sd_id128_from_string(n, &invocation_id);
334,569✔
3419
        if (r >= 0) {
334,569✔
3420
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
×
3421
                if (u) {
×
3422
                        *_u = u;
×
3423
                        return 0;
×
3424
                }
3425

3426
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
×
3427
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3428
                                         SD_ID128_FORMAT_VAL(invocation_id));
×
3429
        }
3430

3431
        /* If this didn't work, we check if this is a unit name */
3432
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
334,569✔
3433
                _cleanup_free_ char *nn = NULL;
1✔
3434

3435
                nn = cescape(n);
1✔
3436
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
1✔
3437
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3438
        }
3439

3440
        r = manager_load_unit(m, n, NULL, e, &u);
334,568✔
3441
        if (r < 0)
334,568✔
3442
                return r;
3443

3444
        *_u = u;
334,568✔
3445
        return 0;
334,568✔
3446
}
3447

3448
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1,017✔
3449
        const char *p;
1,017✔
3450
        unsigned id;
1,017✔
3451
        Job *j;
1,017✔
3452
        int r;
1,017✔
3453

3454
        assert(m);
1,017✔
3455
        assert(s);
1,017✔
3456
        assert(_j);
1,017✔
3457

3458
        p = startswith(s, "/org/freedesktop/systemd1/job/");
1,017✔
3459
        if (!p)
1,017✔
3460
                return -EINVAL;
1,017✔
3461

3462
        r = safe_atou(p, &id);
1,017✔
3463
        if (r < 0)
1,017✔
3464
                return r;
3465

3466
        j = manager_get_job(m, id);
1,017✔
3467
        if (!j)
1,017✔
3468
                return -ENOENT;
3469

3470
        *_j = j;
1,017✔
3471

3472
        return 0;
1,017✔
3473
}
3474

3475
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
5,510✔
3476

3477
#if HAVE_AUDIT
3478
        _cleanup_free_ char *p = NULL;
5,510✔
3479
        const char *msg;
5,510✔
3480
        int audit_fd, r;
5,510✔
3481

3482
        assert(m);
5,510✔
3483
        assert(u);
5,510✔
3484

3485
        if (!MANAGER_IS_SYSTEM(m))
5,510✔
3486
                return;
3487

3488
        /* Don't generate audit events if the service was already started and we're just deserializing */
3489
        if (MANAGER_IS_RELOADING(m))
4,238✔
3490
                return;
3491

3492
        audit_fd = get_core_audit_fd();
4,238✔
3493
        if (audit_fd < 0)
4,238✔
3494
                return;
3495

3496
        r = unit_name_to_prefix_and_instance(u->id, &p);
3,270✔
3497
        if (r < 0) {
3,270✔
3498
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
×
3499
                return;
×
3500
        }
3501

3502
        msg = strjoina("unit=", p);
16,350✔
3503
        if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
3,270✔
3504
                if (ERRNO_IS_PRIVILEGE(errno)) {
×
3505
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
3506
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
×
3507
                        close_core_audit_fd();
×
3508
                } else
3509
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
3,270✔
3510
        }
3511
#endif
3512
}
3513

3514
void manager_send_unit_plymouth(Manager *m, Unit *u) {
30,937✔
3515
        _cleanup_free_ char *message = NULL;
30,937✔
3516
        int c, r;
30,937✔
3517

3518
        assert(m);
30,937✔
3519
        assert(u);
30,937✔
3520

3521
        if (!MANAGER_IS_SYSTEM(m))
30,937✔
3522
                return;
3523

3524
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
3525
        if (MANAGER_IS_RELOADING(m))
13,427✔
3526
                return;
3527

3528
        if (detect_container() > 0)
13,427✔
3529
                return;
3530

3531
        if (!UNIT_VTABLE(u)->notify_plymouth)
11,303✔
3532
                return;
3533

3534
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
2,050✔
3535
        if (c < 0)
2,050✔
3536
                return (void) log_oom();
×
3537

3538
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
3539
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
2,050✔
3540
        if (r < 0)
2,050✔
3541
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
2,050✔
3542
                               "Failed to communicate with plymouth: %m");
3543
}
3544

3545
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
46,933✔
3546
        assert(m);
46,933✔
3547
        assert(u);
46,933✔
3548

3549
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
3550
         * surrounding service manager. */
3551

3552
        if (MANAGER_IS_RELOADING(m))
46,933✔
3553
                return;
3554

3555
        if (!UNIT_VTABLE(u)->notify_supervisor)
46,933✔
3556
                return;
3557

3558
        if (in_initrd()) /* Only send these once we left the initrd */
6,084✔
3559
                return;
3560

3561
        (void) sd_notifyf(/* unset_environment= */ false,
4,158✔
3562
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
3563
                          u->id);
3564
}
3565

3566
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
566✔
3567
        assert(m);
566✔
3568

3569
        if (MANAGER_IS_USER(m))
566✔
3570
                return USEC_INFINITY;
3571

3572
        if (m->watchdog_overridden[t] != USEC_INFINITY)
292✔
3573
                return m->watchdog_overridden[t];
3574

3575
        return m->watchdog[t];
292✔
3576
}
3577

3578
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
1,092✔
3579

3580
        assert(m);
1,092✔
3581

3582
        if (MANAGER_IS_USER(m))
1,092✔
3583
                return;
3584

3585
        if (m->watchdog[t] == timeout)
536✔
3586
                return;
3587

3588
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
112✔
3589
                if (t == WATCHDOG_RUNTIME)
112✔
3590
                        (void) watchdog_setup(timeout);
×
3591
                else if (t == WATCHDOG_PRETIMEOUT)
112✔
3592
                        (void) watchdog_setup_pretimeout(timeout);
×
3593
        }
3594

3595
        m->watchdog[t] = timeout;
112✔
3596
}
3597

3598
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
×
3599
        usec_t usec;
×
3600

3601
        assert(m);
×
3602

3603
        if (MANAGER_IS_USER(m))
×
3604
                return;
3605

3606
        if (m->watchdog_overridden[t] == timeout)
×
3607
                return;
3608

3609
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
×
3610
        if (t == WATCHDOG_RUNTIME)
×
3611
                (void) watchdog_setup(usec);
×
3612
        else if (t == WATCHDOG_PRETIMEOUT)
×
3613
                (void) watchdog_setup_pretimeout(usec);
×
3614

3615
        m->watchdog_overridden[t] = timeout;
×
3616
}
3617

3618
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
273✔
3619
        _cleanup_free_ char *p = NULL;
273✔
3620
        int r;
273✔
3621

3622
        assert(m);
273✔
3623

3624
        if (MANAGER_IS_USER(m))
273✔
3625
                return 0;
3626

3627
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
134✔
3628
                return 0;
3629

3630
        p = strdup(governor);
×
3631
        if (!p)
×
3632
                return -ENOMEM;
3633

3634
        r = watchdog_setup_pretimeout_governor(governor);
×
3635
        if (r < 0)
×
3636
                return r;
3637

3638
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3639
}
3640

3641
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
×
3642
        _cleanup_free_ char *p = NULL;
×
3643
        int r;
×
3644

3645
        assert(m);
×
3646

3647
        if (MANAGER_IS_USER(m))
×
3648
                return 0;
3649

3650
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3651
                return 0;
3652

3653
        p = strdup(governor);
×
3654
        if (!p)
×
3655
                return -ENOMEM;
3656

3657
        r = watchdog_setup_pretimeout_governor(governor);
×
3658
        if (r < 0)
×
3659
                return r;
3660

3661
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3662
}
3663

3664
int manager_reload(Manager *m) {
24✔
3665
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
24✔
3666
        _cleanup_fdset_free_ FDSet *fds = NULL;
×
3667
        _cleanup_fclose_ FILE *f = NULL;
24✔
3668
        int r;
24✔
3669

3670
        assert(m);
24✔
3671

3672
        r = manager_open_serialization(m, &f);
24✔
3673
        if (r < 0)
24✔
3674
                return log_error_errno(r, "Failed to create serialization file: %m");
×
3675

3676
        fds = fdset_new();
24✔
3677
        if (!fds)
24✔
3678
                return log_oom();
×
3679

3680
        /* We are officially in reload mode from here on. */
3681
        reloading = manager_reloading_start(m);
24✔
3682

3683
        r = manager_serialize(m, f, fds, false);
24✔
3684
        if (r < 0)
24✔
3685
                return r;
3686

3687
        r = finish_serialization_file(f);
24✔
3688
        if (r < 0)
24✔
3689
                return log_error_errno(r, "Failed to finish serialization: %m");
×
3690

3691
        /* 💀 This is the point of no return, from here on there is no way back. 💀 */
3692
        reloading = NULL;
24✔
3693

3694
        bus_manager_send_reloading(m, true);
24✔
3695

3696
        /* Start by flushing out all jobs and units, all generated units, all runtime environments, all dynamic users
3697
         * and everything else that is worth flushing out. We'll get it all back from the serialization — if we need
3698
         * it. */
3699

3700
        manager_clear_jobs_and_units(m);
24✔
3701
        lookup_paths_flush_generator(&m->lookup_paths);
24✔
3702
        exec_shared_runtime_vacuum(m);
24✔
3703
        dynamic_user_vacuum(m, false);
24✔
3704
        m->uid_refs = hashmap_free(m->uid_refs);
24✔
3705
        m->gid_refs = hashmap_free(m->gid_refs);
24✔
3706

3707
        (void) manager_run_environment_generators(m);
24✔
3708
        (void) manager_run_generators(m);
24✔
3709

3710
        /* We flushed out generated files, for which we don't watch mtime, so we should flush the old map. */
3711
        manager_free_unit_name_maps(m);
24✔
3712
        m->unit_file_state_outdated = false;
24✔
3713

3714
        /* First, enumerate what we can from kernel and suchlike */
3715
        manager_enumerate_perpetual(m);
24✔
3716
        manager_enumerate(m);
24✔
3717

3718
        /* Second, deserialize our stored data */
3719
        r = manager_deserialize(m, f, fds);
24✔
3720
        if (r < 0)
24✔
3721
                log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
×
3722

3723
        /* We don't need the serialization anymore */
3724
        f = safe_fclose(f);
24✔
3725

3726
        /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3727
        (void) manager_setup_notify(m);
24✔
3728
        (void) manager_setup_cgroups_agent(m);
24✔
3729
        (void) manager_setup_user_lookup_fd(m);
24✔
3730
        (void) manager_setup_handoff_timestamp_fd(m);
24✔
3731
        (void) manager_setup_pidref_transport_fd(m);
24✔
3732

3733
        /* Clean up deserialized bus track information. They're never consumed during reload (as opposed to
3734
         * reexec) since we do not disconnect from the bus. */
3735
        m->subscribed_as_strv = strv_free(m->subscribed_as_strv);
24✔
3736
        m->deserialized_bus_id = SD_ID128_NULL;
24✔
3737

3738
        /* Third, fire things up! */
3739
        manager_coldplug(m);
24✔
3740

3741
        /* Clean up runtime objects no longer referenced */
3742
        manager_vacuum(m);
24✔
3743

3744
        /* Consider the reload process complete now. */
3745
        assert(m->n_reloading > 0);
24✔
3746
        m->n_reloading--;
24✔
3747

3748
        manager_ready(m);
24✔
3749

3750
        m->send_reloading_done = true;
24✔
3751
        return 0;
24✔
3752
}
3753

3754
void manager_reset_failed(Manager *m) {
×
3755
        Unit *u;
×
3756

3757
        assert(m);
×
3758

3759
        HASHMAP_FOREACH(u, m->units)
×
3760
                unit_reset_failed(u);
×
3761
}
×
3762

3763
bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
×
3764
        Unit *u;
×
3765

3766
        assert(m);
×
3767
        assert(name);
×
3768

3769
        /* Returns true if the unit is inactive or going down */
3770
        u = manager_get_unit(m, name);
×
3771
        if (!u)
×
3772
                return true;
3773

3774
        return unit_inactive_or_pending(u);
×
3775
}
3776

3777
static void log_taint_string(Manager *m) {
12,229✔
3778
        assert(m);
12,229✔
3779

3780
        if (MANAGER_IS_USER(m) || m->taint_logged)
12,229✔
3781
                return;
12,229✔
3782

3783
        m->taint_logged = true; /* only check for taint once */
79✔
3784

3785
        _cleanup_free_ char *taint = taint_string();
158✔
3786
        if (isempty(taint))
79✔
3787
                return;
79✔
3788

3789
        log_struct(LOG_NOTICE,
×
3790
                   LOG_MESSAGE("System is tainted: %s", taint),
3791
                   "TAINT=%s", taint,
3792
                   "MESSAGE_ID=" SD_MESSAGE_TAINTED_STR);
3793
}
3794

3795
static void manager_notify_finished(Manager *m) {
143✔
3796
        usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
143✔
3797

3798
        if (MANAGER_IS_TEST_RUN(m))
143✔
3799
                return;
3800

3801
        if (MANAGER_IS_SYSTEM(m) && m->soft_reboots_count > 0) {
136✔
3802
                /* The soft-reboot case, where we only report data for the last reboot */
3803
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
×
3804
                total_usec = userspace_usec = usec_sub_unsigned(m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic,
×
3805
                                                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START].monotonic);
3806

3807
                log_struct(LOG_INFO,
×
3808
                           "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3809
                           "USERSPACE_USEC="USEC_FMT, userspace_usec,
3810
                           LOG_MESSAGE("Soft-reboot finished in %s, counter is now at %u.",
3811
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC),
3812
                                       m->soft_reboots_count));
3813
        } else if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
136✔
3814
                char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
×
3815
                        = {};
3816
                char *p = buf;
×
3817
                size_t size = sizeof buf;
×
3818

3819
                /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3820
                 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
3821
                 * negative values. */
3822

3823
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
×
3824
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3825
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
×
3826
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
×
3827

3828
                if (firmware_usec > 0)
×
3829
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
3830
                if (loader_usec > 0)
×
3831
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3832

3833
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
×
3834

3835
                        /* The initrd case on bare-metal */
3836
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3837
                        initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
×
3838

3839
                        log_struct(LOG_INFO,
×
3840
                                   "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3841
                                   "KERNEL_USEC="USEC_FMT, kernel_usec,
3842
                                   "INITRD_USEC="USEC_FMT, initrd_usec,
3843
                                   "USERSPACE_USEC="USEC_FMT, userspace_usec,
3844
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3845
                                               buf,
3846
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3847
                                               FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3848
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3849
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3850
                } else {
3851
                        /* The initrd-less case on bare-metal */
3852

3853
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3854
                        initrd_usec = 0;
×
3855

3856
                        log_struct(LOG_INFO,
×
3857
                                   "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3858
                                   "KERNEL_USEC="USEC_FMT, kernel_usec,
3859
                                   "USERSPACE_USEC="USEC_FMT, userspace_usec,
3860
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3861
                                               buf,
3862
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3863
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3864
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3865
                }
3866
        } else {
3867
                /* The container and --user case */
3868
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
136✔
3869
                total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
136✔
3870

3871
                log_struct(LOG_INFO,
136✔
3872
                           "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR,
3873
                           "USERSPACE_USEC="USEC_FMT, userspace_usec,
3874
                           LOG_MESSAGE("Startup finished in %s.",
3875
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3876
        }
3877

3878
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
136✔
3879

3880
        log_taint_string(m);
136✔
3881
}
3882

3883
static void manager_send_ready_on_basic_target(Manager *m) {
12,093✔
3884
        int r;
12,093✔
3885

3886
        assert(m);
12,093✔
3887

3888
        /* We send READY=1 on reaching basic.target only when running in --user mode. */
3889
        if (!MANAGER_IS_USER(m) || m->ready_sent)
12,093✔
3890
                return;
3891

3892
        r = sd_notify(/* unset_environment= */ false,
145✔
3893
                      "READY=1\n"
3894
                      "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3895
        if (r < 0)
145✔
3896
                log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
×
3897

3898
        m->ready_sent = true;
145✔
3899
        m->status_ready = false;
145✔
3900
}
3901

3902
static void manager_send_ready_on_idle(Manager *m) {
1,316✔
3903
        int r;
1,316✔
3904

3905
        assert(m);
1,316✔
3906

3907
        /* Skip the notification if nothing changed. */
3908
        if (m->ready_sent && m->status_ready)
1,316✔
3909
                return;
3910

3911
        /* Note that for user managers, we might have already sent READY=1 in manager_send_ready_user_scope().
3912
         * But we still need to flush STATUS=. The second READY=1 will be treated as a noop so it doesn't
3913
         * hurt to send it twice. */
3914
        r = sd_notify(/* unset_environment= */ false,
146✔
3915
                      "READY=1\n"
3916
                      "STATUS=Ready.");
3917
        if (r < 0)
146✔
3918
                log_full_errno(m->ready_sent ? LOG_DEBUG : LOG_WARNING, r,
×
3919
                               "Failed to send readiness notification, ignoring: %m");
3920

3921
        m->ready_sent = m->status_ready = true;
146✔
3922
}
3923

3924
static void manager_check_basic_target(Manager *m) {
31,492✔
3925
        Unit *u;
31,492✔
3926

3927
        assert(m);
31,492✔
3928

3929
        /* Small shortcut */
3930
        if (m->ready_sent && m->taint_logged)
31,492✔
3931
                return;
3932

3933
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
31,492✔
3934
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
31,492✔
3935
                return;
19,399✔
3936

3937
        /* For user managers, send out READY=1 as soon as we reach basic.target */
3938
        manager_send_ready_on_basic_target(m);
12,093✔
3939

3940
        /* Log the taint string as soon as we reach basic.target */
3941
        log_taint_string(m);
12,093✔
3942
}
3943

3944
void manager_check_finished(Manager *m) {
31,642✔
3945
        assert(m);
31,642✔
3946

3947
        if (MANAGER_IS_RELOADING(m))
31,642✔
3948
                return;
3949

3950
        /* Verify that we have entered the event loop already, and not left it again. */
3951
        if (!MANAGER_IS_RUNNING(m))
31,642✔
3952
                return;
3953

3954
        manager_check_basic_target(m);
31,492✔
3955

3956
        if (!hashmap_isempty(m->jobs)) {
31,492✔
3957
                if (m->jobs_in_progress_event_source)
30,176✔
3958
                        /* Ignore any failure, this is only for feedback */
3959
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
11,948✔
3960
                                                        manager_watch_jobs_next_time(m));
3961
                return;
30,176✔
3962
        }
3963

3964
        /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
3965
           kill the hashmap if it is relatively large. */
3966
        if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
1,316✔
3967
                m->jobs = hashmap_free(m->jobs);
310✔
3968

3969
        manager_send_ready_on_idle(m);
1,316✔
3970

3971
        /* Notify Type=idle units that we are done now */
3972
        manager_close_idle_pipe(m);
1,316✔
3973

3974
        if (MANAGER_IS_FINISHED(m))
1,316✔
3975
                return;
3976

3977
        manager_flip_auto_status(m, false, "boot finished");
143✔
3978

3979
        /* Turn off confirm spawn now */
3980
        m->confirm_spawn = NULL;
143✔
3981

3982
        /* No need to update ask password status when we're going non-interactive */
3983
        manager_close_ask_password(m);
143✔
3984

3985
        /* This is no longer the first boot */
3986
        manager_set_first_boot(m, false);
143✔
3987

3988
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
143✔
3989

3990
        manager_notify_finished(m);
143✔
3991

3992
        manager_invalidate_startup_units(m);
143✔
3993
}
3994

3995
void manager_send_reloading(Manager *m) {
123✔
3996
        assert(m);
123✔
3997

3998
        /* Let whoever invoked us know that we are now reloading */
3999
        (void) notify_reloading_full(/* status = */ NULL);
123✔
4000

4001
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
4002
        m->ready_sent = false;
123✔
4003
}
123✔
4004

4005
static bool generator_path_any(char * const *paths) {
980✔
4006

4007
        /* Optimize by skipping the whole process by not creating output directories if no generators are found. */
4008

4009
        STRV_FOREACH(i, paths) {
3,920✔
4010
                if (access(*i, F_OK) >= 0)
3,920✔
4011
                        return true;
4012
                if (errno != ENOENT)
2,940✔
4013
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
2,940✔
4014
        }
4015

4016
        return false;
4017
}
4018

4019
static int manager_run_environment_generators(Manager *m) {
730✔
4020
        _cleanup_strv_free_ char **paths = NULL;
730✔
4021
        int r;
730✔
4022

4023
        assert(m);
730✔
4024

4025
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
730✔
4026
                return 0;
4027

4028
        paths = env_generator_binary_paths(m->runtime_scope);
707✔
4029
        if (!paths)
707✔
4030
                return log_oom();
×
4031

4032
        if (!generator_path_any(paths))
707✔
4033
                return 0;
4034

4035
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
707✔
4036
        void *args[_STDOUT_CONSUME_MAX] = {
707✔
4037
                [STDOUT_GENERATE] = &tmp,
4038
                [STDOUT_COLLECT]  = &tmp,
4039
                [STDOUT_CONSUME]  = &m->transient_environment,
707✔
4040
        };
4041

4042
        WITH_UMASK(0022)
1,414✔
4043
                r = execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC, gather_environment,
707✔
4044
                                        args, NULL, m->transient_environment,
4045
                                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
4046
        return r;
707✔
4047
}
4048

4049
static int build_generator_environment(Manager *m, char ***ret) {
139✔
4050
        _cleanup_strv_free_ char **nl = NULL;
139✔
4051
        Virtualization v;
139✔
4052
        ConfidentialVirtualization cv;
139✔
4053
        int r;
139✔
4054

4055
        assert(m);
139✔
4056
        assert(ret);
139✔
4057

4058
        /* Generators oftentimes want to know some basic facts about the environment they run in, in order to
4059
         * adjust generated units to that. Let's pass down some bits of information that are easy for us to
4060
         * determine (but a bit harder for generator scripts to determine), as environment variables. */
4061

4062
        nl = strv_copy(m->transient_environment);
139✔
4063
        if (!nl)
139✔
4064
                return -ENOMEM;
4065

4066
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
139✔
4067
        if (r < 0)
139✔
4068
                return r;
4069

4070
        if (MANAGER_IS_SYSTEM(m)) {
139✔
4071
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
4072
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
4073
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
4074
                 * same results (hopefully). */
4075
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
4076
                if (r < 0)
×
4077
                        return r;
4078

4079
                if (m->soft_reboots_count > 0) {
×
4080
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
4081
                        if (r < 0)
×
4082
                                return r;
4083
                }
4084

4085
                if (m->first_boot >= 0) {
×
4086
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4087
                        if (r < 0)
×
4088
                                return r;
4089
                }
4090
        }
4091

4092
        v = detect_virtualization();
139✔
4093
        if (v < 0)
139✔
4094
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4095
        else if (v > 0) {
139✔
4096
                const char *s;
139✔
4097

4098
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
695✔
4099
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4100
                             virtualization_to_string(v));
4101

4102
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
139✔
4103
                if (r < 0)
139✔
4104
                        return r;
4105
        }
4106

4107
        cv = detect_confidential_virtualization();
139✔
4108
        if (cv < 0)
139✔
4109
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4110
        else if (cv > 0) {
139✔
4111
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4112
                if (r < 0)
×
4113
                        return r;
4114
        }
4115

4116
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
139✔
4117
        if (r < 0)
139✔
4118
                return r;
4119

4120
        *ret = TAKE_PTR(nl);
139✔
4121
        return 0;
139✔
4122
}
4123

4124
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
139✔
4125
        _cleanup_strv_free_ char **ge = NULL;
139✔
4126
        int r;
139✔
4127

4128
        assert(m);
139✔
4129

4130
        r = build_generator_environment(m, &ge);
139✔
4131
        if (r < 0)
139✔
4132
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4133

4134
        if (remount_ro) {
139✔
4135
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4136
                 * checks whether it is read-only to detect containerized execution environments. We leave
4137
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4138
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4139
                 */
4140
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4141
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4142
                if (r < 0)
×
4143
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4144
        }
4145

4146
        const char *argv[] = {
139✔
4147
                NULL, /* Leave this empty, execute_directory() will fill something in */
4148
                m->lookup_paths.generator,
139✔
4149
                m->lookup_paths.generator_early,
139✔
4150
                m->lookup_paths.generator_late,
139✔
4151
                NULL,
4152
        };
4153

4154
        BLOCK_WITH_UMASK(0022);
278✔
4155
        return execute_directories(
139✔
4156
                        (const char* const*) paths,
4157
                        DEFAULT_TIMEOUT_USEC,
4158
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4159
                        (char**) argv,
4160
                        ge,
4161
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4162
}
4163

4164
static int manager_run_generators(Manager *m) {
730✔
4165
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
730✔
4166
        _cleanup_strv_free_ char **paths = NULL;
730✔
4167
        int r;
730✔
4168

4169
        assert(m);
730✔
4170

4171
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
730✔
4172
                return 0;
4173

4174
        paths = generator_binary_paths(m->runtime_scope);
273✔
4175
        if (!paths)
273✔
4176
                return log_oom();
×
4177

4178
        if (!generator_path_any(paths))
273✔
4179
                return 0;
4180

4181
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
273✔
4182
        if (r < 0) {
273✔
4183
                log_error_errno(r, "Failed to create generator directories: %m");
×
4184
                goto finish;
×
4185
        }
4186

4187
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4188
         * we are the user manager, let's just execute the generators directly. We might not have the
4189
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4190
         */
4191
        if (MANAGER_IS_USER(m)) {
273✔
4192
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
139✔
4193
                goto finish;
139✔
4194
        }
4195

4196
        /* On some systems /tmp/ doesn't exist, and on some other systems we cannot create it at all. Avoid
4197
         * trying to mount a private tmpfs on it as there's no one size fits all. */
4198
        if (is_dir("/tmp", /* follow= */ false) > 0 && !MANAGER_IS_TEST_RUN(m))
134✔
4199
                flags |= FORK_PRIVATE_TMP;
134✔
4200

4201
        r = safe_fork("(sd-gens)", flags, NULL);
134✔
4202
        if (r == 0) {
134✔
4203
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4204
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4205
        }
4206
        if (r < 0) {
134✔
4207
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4208
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4209
                        goto finish;
×
4210
                }
4211

4212
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4213
                 * seccomp or without capability.
4214
                 *
4215
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4216
                 *
4217
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4218
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4219
                 * https://github.com/systemd/systemd/issues/28901.
4220
                 */
4221
                log_debug_errno(r,
×
4222
                                "Failed to fork off sandboxing environment for executing generators. "
4223
                                "Falling back to execute generators without sandboxing: %m");
4224
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4225
        }
4226

4227
finish:
134✔
4228
        lookup_paths_trim_generator(&m->lookup_paths);
273✔
4229
        return r;
4230
}
4231

4232
int manager_transient_environment_add(Manager *m, char **plus) {
273✔
4233
        char **a;
273✔
4234

4235
        assert(m);
273✔
4236

4237
        if (strv_isempty(plus))
273✔
4238
                return 0;
273✔
4239

4240
        a = strv_env_merge(m->transient_environment, plus);
134✔
4241
        if (!a)
134✔
4242
                return log_oom();
×
4243

4244
        sanitize_environment(a);
134✔
4245

4246
        return strv_free_and_replace(m->transient_environment, a);
134✔
4247
}
4248

4249
int manager_client_environment_modify(
138✔
4250
                Manager *m,
4251
                char **minus,
4252
                char **plus) {
4253

4254
        char **a = NULL, **b = NULL, **l;
138✔
4255

4256
        assert(m);
138✔
4257

4258
        if (strv_isempty(minus) && strv_isempty(plus))
138✔
4259
                return 0;
4260

4261
        l = m->client_environment;
138✔
4262

4263
        if (!strv_isempty(minus)) {
138✔
4264
                a = strv_env_delete(l, 1, minus);
1✔
4265
                if (!a)
1✔
4266
                        return -ENOMEM;
4267

4268
                l = a;
4269
        }
4270

4271
        if (!strv_isempty(plus)) {
138✔
4272
                b = strv_env_merge(l, plus);
137✔
4273
                if (!b) {
137✔
4274
                        strv_free(a);
×
4275
                        return -ENOMEM;
×
4276
                }
4277

4278
                l = b;
4279
        }
4280

4281
        if (m->client_environment != l)
138✔
4282
                strv_free(m->client_environment);
138✔
4283

4284
        if (a != l)
138✔
4285
                strv_free(a);
137✔
4286
        if (b != l)
138✔
4287
                strv_free(b);
1✔
4288

4289
        m->client_environment = sanitize_environment(l);
138✔
4290
        return 0;
138✔
4291
}
4292

4293
int manager_get_effective_environment(Manager *m, char ***ret) {
29,434✔
4294
        char **l;
29,434✔
4295

4296
        assert(m);
29,434✔
4297
        assert(ret);
29,434✔
4298

4299
        l = strv_env_merge(m->transient_environment, m->client_environment);
29,434✔
4300
        if (!l)
29,434✔
4301
                return -ENOMEM;
4302

4303
        *ret = l;
29,434✔
4304
        return 0;
29,434✔
4305
}
4306

4307
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
273✔
4308
        _cleanup_free_ char *label = NULL;
273✔
4309
        struct rlimit *rlimit[_RLIMIT_MAX];
273✔
4310
        int r;
273✔
4311

4312
        assert(m);
273✔
4313
        assert(defaults);
273✔
4314

4315
        if (streq_ptr(defaults->smack_process_label, "/"))
273✔
4316
                label = NULL;
4317
        else  {
4318
                const char *l = defaults->smack_process_label;
273✔
4319
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4320
                if (!l)
4321
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4322
#endif
4323
                if (l) {
273✔
4324
                        label = strdup(l);
×
4325
                        if (!label)
×
4326
                                return -ENOMEM;
4327
                } else
4328
                        label = NULL;
4329
        }
4330

4331
        r = rlimit_copy_all(rlimit, defaults->rlimit);
273✔
4332
        if (r < 0)
273✔
4333
                return r;
4334

4335
        m->defaults.std_output = defaults->std_output;
273✔
4336
        m->defaults.std_error = defaults->std_error;
273✔
4337

4338
        m->defaults.restart_usec = defaults->restart_usec;
273✔
4339
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
273✔
4340
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
273✔
4341
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
273✔
4342
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
273✔
4343
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
273✔
4344

4345
        m->defaults.start_limit = defaults->start_limit;
273✔
4346

4347
        m->defaults.cpu_accounting = defaults->cpu_accounting;
273✔
4348
        m->defaults.memory_accounting = defaults->memory_accounting;
273✔
4349
        m->defaults.io_accounting = defaults->io_accounting;
273✔
4350
        m->defaults.blockio_accounting = defaults->blockio_accounting;
273✔
4351
        m->defaults.tasks_accounting = defaults->tasks_accounting;
273✔
4352
        m->defaults.ip_accounting = defaults->ip_accounting;
273✔
4353

4354
        m->defaults.tasks_max = defaults->tasks_max;
273✔
4355
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
273✔
4356

4357
        m->defaults.oom_policy = defaults->oom_policy;
273✔
4358
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
273✔
4359
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
273✔
4360

4361
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
273✔
4362
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
273✔
4363

4364
        free_and_replace(m->defaults.smack_process_label, label);
273✔
4365
        rlimit_free_all(m->defaults.rlimit);
273✔
4366
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
273✔
4367

4368
        return 0;
273✔
4369
}
4370

4371
void manager_recheck_dbus(Manager *m) {
67,366✔
4372
        assert(m);
67,366✔
4373

4374
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4375
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4376
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4377
         * of the system instance, while in the user instance we can assume it's already there. */
4378

4379
        if (MANAGER_IS_RELOADING(m))
67,366✔
4380
                return; /* don't check while we are reloading… */
4381

4382
        if (manager_dbus_is_running(m, false)) {
59,578✔
4383
                (void) bus_init_api(m);
9,130✔
4384

4385
                if (MANAGER_IS_SYSTEM(m))
9,130✔
4386
                        (void) bus_init_system(m);
8,302✔
4387
        } else {
4388
                (void) bus_done_api(m);
50,448✔
4389

4390
                if (MANAGER_IS_SYSTEM(m))
50,448✔
4391
                        (void) bus_done_system(m);
20,351✔
4392
        }
4393
}
4394

4395
static bool manager_journal_is_running(Manager *m) {
32,022✔
4396
        Unit *u;
32,022✔
4397

4398
        assert(m);
32,022✔
4399

4400
        if (MANAGER_IS_TEST_RUN(m))
32,022✔
4401
                return false;
4402

4403
        /* If we are the user manager we can safely assume that the journal is up */
4404
        if (!MANAGER_IS_SYSTEM(m))
32,022✔
4405
                return true;
4406

4407
        /* Check that the socket is not only up, but in RUNNING state */
4408
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
31,397✔
4409
        if (!u)
31,397✔
4410
                return false;
4411
        if (SOCKET(u)->state != SOCKET_RUNNING)
31,397✔
4412
                return false;
4413

4414
        /* Similar, check if the daemon itself is fully up, too */
4415
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
23,655✔
4416
        if (!u)
23,655✔
4417
                return false;
4418
        if (!IN_SET(SERVICE(u)->state, SERVICE_RELOAD, SERVICE_RUNNING))
23,655✔
4419
                return false;
1,867✔
4420

4421
        return true;
4422
}
4423

4424
void disable_printk_ratelimit(void) {
67✔
4425
        /* Disable kernel's printk ratelimit.
4426
         *
4427
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4428
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4429
         * setting takes precedence. */
4430
        int r;
67✔
4431

4432
        r = sysctl_write("kernel/printk_devkmsg", "on");
67✔
4433
        if (r < 0)
67✔
4434
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4435
}
67✔
4436

4437
void manager_recheck_journal(Manager *m) {
67,366✔
4438

4439
        assert(m);
67,366✔
4440

4441
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4442
        if (getpid_cached() != 1)
67,366✔
4443
                return;
4444

4445
        /* Don't check this while we are reloading, things might still change */
4446
        if (MANAGER_IS_RELOADING(m))
35,864✔
4447
                return;
4448

4449
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4450
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4451
         * might trigger an activation ourselves we can't fulfill. */
4452
        log_set_prohibit_ipc(!manager_journal_is_running(m));
28,213✔
4453
        log_open();
28,213✔
4454
}
4455

4456
static ShowStatus manager_get_show_status(Manager *m) {
16,311✔
4457
        assert(m);
16,311✔
4458

4459
        if (MANAGER_IS_USER(m))
16,311✔
4460
                return _SHOW_STATUS_INVALID;
4461

4462
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
16,311✔
4463
                return m->show_status_overridden;
4464

4465
        return m->show_status;
16,311✔
4466
}
4467

4468
bool manager_get_show_status_on(Manager *m) {
16,311✔
4469
        assert(m);
16,311✔
4470

4471
        return show_status_on(manager_get_show_status(m));
16,311✔
4472
}
4473

4474
static void set_show_status_marker(bool b) {
112✔
4475
        if (b)
112✔
4476
                (void) touch("/run/systemd/show-status");
×
4477
        else
4478
                (void) unlink("/run/systemd/show-status");
112✔
4479
}
112✔
4480

4481
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
273✔
4482
        assert(m);
273✔
4483
        assert(reason);
273✔
4484
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
273✔
4485

4486
        if (MANAGER_IS_USER(m))
273✔
4487
                return;
4488

4489
        if (mode == m->show_status)
134✔
4490
                return;
4491

4492
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
112✔
4493
                bool enabled;
112✔
4494

4495
                enabled = show_status_on(mode);
112✔
4496
                log_debug("%s (%s) showing of status (%s).",
224✔
4497
                          enabled ? "Enabling" : "Disabling",
4498
                          strna(show_status_to_string(mode)),
4499
                          reason);
4500

4501
                set_show_status_marker(enabled);
112✔
4502
        }
4503

4504
        m->show_status = mode;
112✔
4505
}
4506

4507
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
×
4508
        assert(m);
×
4509
        assert(mode < _SHOW_STATUS_MAX);
×
4510

4511
        if (MANAGER_IS_USER(m))
×
4512
                return;
4513

4514
        if (mode == m->show_status_overridden)
×
4515
                return;
4516

4517
        m->show_status_overridden = mode;
×
4518

4519
        if (mode == _SHOW_STATUS_INVALID)
×
4520
                mode = m->show_status;
×
4521

4522
        log_debug("%s (%s) showing of status (%s).",
×
4523
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4524
                  strna(show_status_to_string(mode)),
4525
                  reason);
4526

4527
        set_show_status_marker(show_status_on(mode));
×
4528
}
4529

4530
const char* manager_get_confirm_spawn(Manager *m) {
3,820✔
4531
        static int last_errno = 0;
3,820✔
4532
        struct stat st;
3,820✔
4533
        int r;
3,820✔
4534

4535
        assert(m);
3,820✔
4536

4537
        /* Here's the deal: we want to test the validity of the console but don't want
4538
         * PID1 to go through the whole console process which might block. But we also
4539
         * want to warn the user only once if something is wrong with the console so we
4540
         * cannot do the sanity checks after spawning our children. So here we simply do
4541
         * really basic tests to hopefully trap common errors.
4542
         *
4543
         * If the console suddenly disappear at the time our children will really it
4544
         * then they will simply fail to acquire it and a positive answer will be
4545
         * assumed. New children will fall back to /dev/console though.
4546
         *
4547
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4548
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4549
         * reason the configured console is not ready, we fall back to the default
4550
         * console. */
4551

4552
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
3,820✔
4553
                return m->confirm_spawn;
3,820✔
4554

4555
        if (stat(m->confirm_spawn, &st) < 0) {
×
4556
                r = -errno;
×
4557
                goto fail;
×
4558
        }
4559

4560
        if (!S_ISCHR(st.st_mode)) {
×
4561
                r = -ENOTTY;
×
4562
                goto fail;
×
4563
        }
4564

4565
        last_errno = 0;
×
4566
        return m->confirm_spawn;
×
4567

4568
fail:
×
4569
        if (last_errno != r)
×
4570
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4571

4572
        return "/dev/console";
4573
}
4574

4575
void manager_set_first_boot(Manager *m, bool b) {
392✔
4576
        assert(m);
392✔
4577

4578
        if (!MANAGER_IS_SYSTEM(m))
392✔
4579
                return;
4580

4581
        if (m->first_boot != (int) b) {
112✔
4582
                if (b)
112✔
4583
                        (void) touch("/run/systemd/first-boot");
17✔
4584
                else
4585
                        (void) unlink("/run/systemd/first-boot");
95✔
4586
        }
4587

4588
        m->first_boot = b;
112✔
4589
}
4590

4591
void manager_disable_confirm_spawn(void) {
×
4592
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4593
}
×
4594

4595
static bool manager_should_show_status(Manager *m, StatusType type) {
23,397✔
4596
        assert(m);
23,397✔
4597

4598
        if (!MANAGER_IS_SYSTEM(m))
23,397✔
4599
                return false;
4600

4601
        if (m->no_console_output)
16,766✔
4602
                return false;
4603

4604
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
16,295✔
4605
                return false;
4606

4607
        /* If we cannot find out the status properly, just proceed. */
4608
        if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
16,295✔
4609
                return false;
4610

4611
        if (type == STATUS_TYPE_NOTICE && m->show_status != SHOW_STATUS_NO)
16,295✔
4612
                return true;
4613

4614
        return manager_get_show_status_on(m);
16,294✔
4615
}
4616

4617
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
23,397✔
4618
        va_list ap;
23,397✔
4619

4620
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4621

4622
        if (m && !manager_should_show_status(m, type))
23,397✔
4623
                return;
23,396✔
4624

4625
        /* XXX We should totally drop the check for ephemeral here
4626
         * and thus effectively make 'Type=idle' pointless. */
4627
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
1✔
4628
                return;
4629

4630
        va_start(ap, format);
1✔
4631
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
2✔
4632
        va_end(ap);
1✔
4633
}
4634

4635
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
26,216✔
4636
        assert(m);
26,216✔
4637
        assert(path);
26,216✔
4638
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
26,216✔
4639

4640
        if (path_equal(path, "/"))
26,216✔
4641
                path = "";
1,406✔
4642

4643
        return hashmap_get(m->units_needing_mounts_for[t], path);
26,216✔
4644
}
4645

4646
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
148,366✔
4647
        unsigned size;
148,366✔
4648
        int r;
148,366✔
4649

4650
        assert(m);
148,366✔
4651
        assert(u->manager == m);
148,366✔
4652

4653
        size = set_size(m->failed_units);
148,366✔
4654

4655
        if (failed) {
148,366✔
4656
                r = set_ensure_put(&m->failed_units, NULL, u);
209✔
4657
                if (r < 0)
209✔
4658
                        return log_oom();
×
4659
        } else
4660
                (void) set_remove(m->failed_units, u);
148,157✔
4661

4662
        if (set_size(m->failed_units) != size)
148,366✔
4663
                bus_manager_send_change_signal(m);
418✔
4664

4665
        return 0;
4666
}
4667

4668
ManagerState manager_state(Manager *m) {
707,545✔
4669
        Unit *u;
707,545✔
4670

4671
        assert(m);
707,545✔
4672

4673
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4674
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
707,545✔
4675
        if (u && unit_active_or_pending(u))
707,545✔
4676
                return MANAGER_STOPPING;
4677

4678
        /* Did we ever finish booting? If not then we are still starting up */
4679
        if (!MANAGER_IS_FINISHED(m)) {
638,532✔
4680

4681
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
620,902✔
4682
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
620,902✔
4683
                        return MANAGER_INITIALIZING;
558,598✔
4684

4685
                return MANAGER_STARTING;
4686
        }
4687

4688
        if (MANAGER_IS_SYSTEM(m)) {
17,630✔
4689
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4690
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
×
4691
                if (u && unit_active_or_pending(u))
×
4692
                        return MANAGER_MAINTENANCE;
4693

4694
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
×
4695
                if (u && unit_active_or_pending(u))
×
4696
                        return MANAGER_MAINTENANCE;
4697
        }
4698

4699
        /* Are there any failed units? If so, we are in degraded mode */
4700
        if (!set_isempty(m->failed_units))
17,630✔
4701
                return MANAGER_DEGRADED;
1,009✔
4702

4703
        return MANAGER_RUNNING;
4704
}
4705

4706
static void manager_unref_uid_internal(
953✔
4707
                Hashmap *uid_refs,
4708
                uid_t uid,
4709
                bool destroy_now,
4710
                int (*_clean_ipc)(uid_t uid)) {
4711

4712
        uint32_t c, n;
953✔
4713

4714
        assert(uid_is_valid(uid));
953✔
4715
        assert(_clean_ipc);
953✔
4716

4717
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4718
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4719
         *
4720
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4721
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4722
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4723
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4724
         * counter drops to 0 again. */
4725

4726
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
953✔
4727
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
953✔
4728

4729
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
953✔
4730
                return;
4731

4732
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
891✔
4733

4734
        n = c & ~DESTROY_IPC_FLAG;
891✔
4735
        assert(n > 0);
891✔
4736
        n--;
891✔
4737

4738
        if (destroy_now && n == 0) {
891✔
4739
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
351✔
4740

4741
                if (c & DESTROY_IPC_FLAG) {
351✔
4742
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
3✔
4743
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4744
                                  uid);
4745
                        (void) _clean_ipc(uid);
2✔
4746
                }
4747
        } else {
4748
                c = n | (c & DESTROY_IPC_FLAG);
540✔
4749
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
540✔
4750
        }
4751
}
4752

4753
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
476✔
4754
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
476✔
4755
}
476✔
4756

4757
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
477✔
4758
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
477✔
4759
}
477✔
4760

4761
static int manager_ref_uid_internal(
953✔
4762
                Hashmap **uid_refs,
4763
                uid_t uid,
4764
                bool clean_ipc) {
4765

4766
        uint32_t c, n;
953✔
4767
        int r;
953✔
4768

4769
        assert(uid_refs);
953✔
4770
        assert(uid_is_valid(uid));
953✔
4771

4772
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4773
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4774
         * rules. */
4775

4776
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
953✔
4777
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
953✔
4778

4779
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
953✔
4780
                return 0;
4781

4782
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
891✔
4783
        if (r < 0)
891✔
4784
                return r;
4785

4786
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
891✔
4787

4788
        n = c & ~DESTROY_IPC_FLAG;
891✔
4789
        n++;
891✔
4790

4791
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
891✔
4792
                return -EOVERFLOW;
4793

4794
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
891✔
4795

4796
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
891✔
4797
}
4798

4799
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
476✔
4800
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
476✔
4801
}
4802

4803
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
477✔
4804
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
477✔
4805
}
4806

4807
static void manager_vacuum_uid_refs_internal(
1,460✔
4808
                Hashmap *uid_refs,
4809
                int (*_clean_ipc)(uid_t uid)) {
4810

4811
        void *p, *k;
1,460✔
4812

4813
        assert(_clean_ipc);
1,460✔
4814

4815
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
3,246✔
4816
                uint32_t c, n;
326✔
4817
                uid_t uid;
326✔
4818

4819
                uid = PTR_TO_UID(k);
326✔
4820
                c = PTR_TO_UINT32(p);
326✔
4821

4822
                n = c & ~DESTROY_IPC_FLAG;
326✔
4823
                if (n > 0)
326✔
4824
                        continue;
326✔
4825

4826
                if (c & DESTROY_IPC_FLAG) {
×
4827
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4828
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4829
                                  uid);
4830
                        (void) _clean_ipc(uid);
×
4831
                }
4832

4833
                assert_se(hashmap_remove(uid_refs, k) == p);
1,786✔
4834
        }
4835
}
1,460✔
4836

4837
static void manager_vacuum_uid_refs(Manager *m) {
730✔
4838
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
730✔
4839
}
730✔
4840

4841
static void manager_vacuum_gid_refs(Manager *m) {
730✔
4842
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
730✔
4843
}
730✔
4844

4845
static void manager_vacuum(Manager *m) {
730✔
4846
        assert(m);
730✔
4847

4848
        /* Release any dynamic users no longer referenced */
4849
        dynamic_user_vacuum(m, true);
730✔
4850

4851
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4852
        manager_vacuum_uid_refs(m);
730✔
4853
        manager_vacuum_gid_refs(m);
730✔
4854

4855
        /* Release any runtimes no longer referenced */
4856
        exec_shared_runtime_vacuum(m);
730✔
4857
}
730✔
4858

4859
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
253✔
4860
        struct buffer {
253✔
4861
                uid_t uid;
4862
                gid_t gid;
4863
                char unit_name[UNIT_NAME_MAX+1];
4864
        } _packed_ buffer;
4865

4866
        Manager *m = ASSERT_PTR(userdata);
253✔
4867
        ssize_t l;
253✔
4868
        size_t n;
253✔
4869
        Unit *u;
253✔
4870

4871
        assert(source);
253✔
4872

4873
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4874
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4875
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4876
         * reference counter drops to 0. */
4877

4878
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
253✔
4879
        if (l < 0) {
253✔
4880
                if (ERRNO_IS_TRANSIENT(errno))
×
4881
                        return 0;
253✔
4882

4883
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4884
        }
4885

4886
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
253✔
4887
                log_warning("Received too short user lookup message, ignoring.");
×
4888
                return 0;
×
4889
        }
4890

4891
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
253✔
4892
                log_warning("Received too long user lookup message, ignoring.");
×
4893
                return 0;
×
4894
        }
4895

4896
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
253✔
4897
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4898
                return 0;
×
4899
        }
4900

4901
        n = (size_t) l - offsetof(struct buffer, unit_name);
253✔
4902
        if (memchr(buffer.unit_name, 0, n)) {
253✔
4903
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4904
                return 0;
×
4905
        }
4906

4907
        buffer.unit_name[n] = 0;
253✔
4908
        u = manager_get_unit(m, buffer.unit_name);
253✔
4909
        if (!u) {
253✔
4910
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4911
                return 0;
×
4912
        }
4913

4914
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
506✔
4915

4916
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
253✔
4917
        return 0;
4918
}
4919

4920
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,801✔
4921
        Manager *m = ASSERT_PTR(userdata);
3,801✔
4922
        usec_t ts[2] = {};
3,801✔
4923
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
3,801✔
4924
        struct msghdr msghdr = {
3,801✔
4925
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
3,801✔
4926
                .msg_iovlen = 1,
4927
                .msg_control = &control,
4928
                .msg_controllen = sizeof(control),
4929
        };
4930
        ssize_t n;
3,801✔
4931

4932
        assert(source);
3,801✔
4933

4934
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
3,801✔
4935
        if (ERRNO_IS_NEG_TRANSIENT(n))
3,801✔
4936
                return 0; /* Spurious wakeup, try again */
3,801✔
4937
        if (n == -ECHRNG) {
3,801✔
4938
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4939
                return 0;
×
4940
        }
4941
        if (n == -EXFULL) {
3,801✔
4942
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4943
                return 0;
×
4944
        }
4945
        if (n < 0)
3,801✔
4946
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
4947

4948
        cmsg_close_all(&msghdr);
3,801✔
4949

4950
        if (n != sizeof(ts)) {
3,801✔
4951
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
4952
                return 0;
×
4953
        }
4954

4955
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
3,801✔
4956
        if (!ucred || !pid_is_valid(ucred->pid)) {
3,801✔
4957
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
4958
                return 0;
×
4959
        }
4960

4961
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
3,801✔
4962

4963
        _cleanup_free_ Unit **units = NULL;
3,801✔
4964
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
3,801✔
4965
        if (n_units < 0) {
3,801✔
4966
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
4967
                return 0;
×
4968
        }
4969
        if (n_units == 0) {
3,801✔
4970
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
4971
                return 0;
×
4972
        }
4973

4974
        dual_timestamp dt = {
3,801✔
4975
                .realtime = ts[0],
3,801✔
4976
                .monotonic = ts[1],
3,801✔
4977
        };
4978

4979
        FOREACH_ARRAY(u, units, n_units) {
11,403✔
4980
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
7,602✔
4981
                        continue;
1✔
4982

4983
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
7,601✔
4984
        }
4985

4986
        return 0;
4987
}
4988

4989
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2✔
4990
        Manager *m = ASSERT_PTR(userdata);
2✔
4991
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
2✔
4992
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
4✔
4993
        struct ucred *ucred = NULL;
2✔
4994
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
2✔
4995
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
2✔
4996
        struct msghdr msghdr = {
2✔
4997
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
2✔
4998
                .msg_iovlen = 1,
4999
                .msg_control = &control,
5000
                .msg_controllen = sizeof(control),
5001
        };
5002
        struct cmsghdr *cmsg;
2✔
5003
        ssize_t n;
2✔
5004
        int r;
2✔
5005

5006
        assert(source);
2✔
5007

5008
        /* Server expects:
5009
         * - Parent PID in ucreds enabled via SO_PASSCRED
5010
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
5011
         * - Child PIDFD in SCM_RIGHTS in message body
5012
         * - Child PID in message IOV
5013
         *
5014
         * SO_PASSPIDFD may not be supported by the kernel so we fall back to using parent PID from ucreds
5015
         * and accept some raciness. */
5016
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
2✔
5017
        if (ERRNO_IS_NEG_TRANSIENT(n))
4✔
5018
                return 0; /* Spurious wakeup, try again */
5019
        if (n == -ECHRNG) {
2✔
5020
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
5021
                return 0;
×
5022
        }
5023
        if (n == -EXFULL) {
2✔
5024
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
5025
                return 0;
×
5026
        }
5027
        if (n < 0)
2✔
5028
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
5029

5030
        if (n != sizeof(child_pid)) {
2✔
5031
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
5032
                return 0;
×
5033
        }
5034

5035
        CMSG_FOREACH(cmsg, &msghdr) {
16✔
5036
                if (cmsg->cmsg_level != SOL_SOCKET)
6✔
5037
                        continue;
×
5038

5039
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
6✔
5040
                        assert(!ucred);
2✔
5041
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
2✔
5042
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
4✔
5043
                        assert(parent_pidfd < 0);
2✔
5044
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
2✔
5045
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
2✔
5046
                        assert(child_pidfd < 0);
2✔
5047
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
2✔
5048
                }
5049
        }
5050

5051
        /* Verify and set parent pidref. */
5052
        if (!ucred || !pid_is_valid(ucred->pid)) {
2✔
5053
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
5054
                return 0;
×
5055
        }
5056

5057
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
5058
        if (parent_pidfd >= 0)
2✔
5059
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
2✔
5060
        else
5061
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
5062
        if (r < 0) {
2✔
5063
                if (r == -ESRCH)
×
5064
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5065
                else
5066
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5067
                return 0;
×
5068
        }
5069

5070
        if (parent_pidref.pid != ucred->pid) {
2✔
5071
                assert(parent_pidref.fd >= 0);
×
5072
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
5073
                            parent_pidref.pid, ucred->pid);
5074
                return 0;
×
5075
        }
5076

5077
        /* Verify and set child pidref. */
5078
        if (!pid_is_valid(child_pid)) {
2✔
5079
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
5080
                return 0;
×
5081
        }
5082

5083
        /* Need to handle kernels without PIDFD support. */
5084
        if (child_pidfd >= 0)
2✔
5085
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
2✔
5086
        else
5087
                r = pidref_set_pid(&child_pidref, child_pid);
×
5088
        if (r < 0) {
2✔
5089
                if (r == -ESRCH)
×
5090
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5091
                else
5092
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5093
                return 0;
×
5094
        }
5095

5096
        if (child_pidref.pid != child_pid) {
2✔
5097
                assert(child_pidref.fd >= 0);
×
5098
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5099
                            child_pidref.pid, child_pid);
5100
                return 0;
×
5101
        }
5102

5103
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
2✔
5104

5105
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5106
         * Then fall back to finding cgroup of the child process. */
5107
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
2✔
5108
        if (!u)
2✔
5109
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5110
        if (!u) {
×
5111
                log_debug("Got pidref for parent process " PID_FMT " and child process " PID_FMT " we are not interested in, ignoring.", parent_pidref.pid, child_pidref.pid);
×
5112
                return 0;
×
5113
        }
5114

5115
        if (!UNIT_VTABLE(u)->notify_pidref) {
2✔
5116
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5117
                return 0;
×
5118
        }
5119

5120
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
2✔
5121

5122
        return 0;
5123
}
5124

5125
void manager_ref_console(Manager *m) {
156✔
5126
        assert(m);
156✔
5127

5128
        m->n_on_console++;
156✔
5129
}
156✔
5130

5131
void manager_unref_console(Manager *m) {
156✔
5132

5133
        assert(m->n_on_console > 0);
156✔
5134
        m->n_on_console--;
156✔
5135

5136
        if (m->n_on_console == 0)
156✔
5137
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
90✔
5138
}
156✔
5139

5140
void manager_override_log_level(Manager *m, int level) {
48✔
5141
        _cleanup_free_ char *s = NULL;
96✔
5142
        assert(m);
48✔
5143

5144
        if (!m->log_level_overridden) {
48✔
5145
                m->original_log_level = log_get_max_level();
17✔
5146
                m->log_level_overridden = true;
17✔
5147
        }
5148

5149
        (void) log_level_to_string_alloc(level, &s);
48✔
5150
        log_info("Setting log level to %s.", strna(s));
48✔
5151

5152
        log_set_max_level(level);
48✔
5153
}
48✔
5154

5155
void manager_restore_original_log_level(Manager *m) {
×
5156
        _cleanup_free_ char *s = NULL;
×
5157
        assert(m);
×
5158

5159
        if (!m->log_level_overridden)
×
5160
                return;
×
5161

5162
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5163
        log_info("Restoring log level to original (%s).", strna(s));
×
5164

5165
        log_set_max_level(m->original_log_level);
×
5166
        m->log_level_overridden = false;
×
5167
}
5168

5169
void manager_override_log_target(Manager *m, LogTarget target) {
16✔
5170
        assert(m);
16✔
5171

5172
        if (!m->log_target_overridden) {
16✔
5173
                m->original_log_target = log_get_target();
11✔
5174
                m->log_target_overridden = true;
11✔
5175
        }
5176

5177
        log_info("Setting log target to %s.", log_target_to_string(target));
16✔
5178
        log_set_target(target);
16✔
5179
}
16✔
5180

5181
void manager_restore_original_log_target(Manager *m) {
×
5182
        assert(m);
×
5183

5184
        if (!m->log_target_overridden)
×
5185
                return;
5186

5187
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5188

5189
        log_set_target(m->original_log_target);
×
5190
        m->log_target_overridden = false;
×
5191
}
5192

5193
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
3,322✔
5194
        if (in_initrd() &&
3,322✔
5195
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
366✔
5196
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5197
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
366✔
5198
        return s;
5199
}
5200

5201
int manager_allocate_idle_pipe(Manager *m) {
10,710✔
5202
        int r;
10,710✔
5203

5204
        assert(m);
10,710✔
5205

5206
        if (m->idle_pipe[0] >= 0) {
10,710✔
5207
                assert(m->idle_pipe[1] >= 0);
8,750✔
5208
                assert(m->idle_pipe[2] >= 0);
8,750✔
5209
                assert(m->idle_pipe[3] >= 0);
8,750✔
5210
                return 0;
5211
        }
5212

5213
        assert(m->idle_pipe[1] < 0);
1,960✔
5214
        assert(m->idle_pipe[2] < 0);
1,960✔
5215
        assert(m->idle_pipe[3] < 0);
1,960✔
5216

5217
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
1,960✔
5218
        if (r < 0)
×
5219
                return r;
5220

5221
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
1,960✔
5222
        if (r < 0) {
×
5223
                safe_close_pair(m->idle_pipe + 0);
×
5224
                return r;
×
5225
        }
5226

5227
        return 1;
5228
}
5229

5230
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,117✔
5231
        assert(defaults);
1,117✔
5232
        assert(scope >= 0);
1,117✔
5233
        assert(scope < _RUNTIME_SCOPE_MAX);
1,117✔
5234

5235
        *defaults = (UnitDefaults) {
2,234✔
5236
                .std_output = EXEC_OUTPUT_JOURNAL,
5237
                .std_error = EXEC_OUTPUT_INHERIT,
5238
                .restart_usec = DEFAULT_RESTART_USEC,
5239
                .timeout_start_usec = manager_default_timeout(scope),
5240
                .timeout_stop_usec = manager_default_timeout(scope),
5241
                .timeout_abort_usec = manager_default_timeout(scope),
5242
                .timeout_abort_set = false,
5243
                .device_timeout_usec = manager_default_timeout(scope),
5244
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5245

5246
                /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
5247
                 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
5248
                .cpu_accounting = cpu_accounting_is_cheap(),
1,117✔
5249
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5250
                .io_accounting = false,
5251
                .blockio_accounting = false,
5252
                .tasks_accounting = true,
5253
                .ip_accounting = false,
5254

5255
                .tasks_max = DEFAULT_TASKS_MAX,
5256
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5257

5258
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5259
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5260

5261
                .oom_policy = OOM_STOP,
5262
                .oom_score_adjust_set = false,
5263
        };
5264
}
1,117✔
5265

5266
void unit_defaults_done(UnitDefaults *defaults) {
1,117✔
5267
        assert(defaults);
1,117✔
5268

5269
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,117✔
5270
        rlimit_free_all(defaults->rlimit);
1,117✔
5271
}
1,117✔
5272

5273
LogTarget manager_get_executor_log_target(Manager *m) {
3,820✔
5274
        assert(m);
3,820✔
5275

5276
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5277
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
3,820✔
5278
                return LOG_TARGET_KMSG;
5279

5280
        return log_get_target();
2,408✔
5281
}
5282

5283
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5284
        [MANAGER_INITIALIZING] = "initializing",
5285
        [MANAGER_STARTING]     = "starting",
5286
        [MANAGER_RUNNING]      = "running",
5287
        [MANAGER_DEGRADED]     = "degraded",
5288
        [MANAGER_MAINTENANCE]  = "maintenance",
5289
        [MANAGER_STOPPING]     = "stopping",
5290
};
5291

5292
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
75✔
5293

5294
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5295
        [MANAGER_OK]          = "ok",
5296
        [MANAGER_EXIT]        = "exit",
5297
        [MANAGER_RELOAD]      = "reload",
5298
        [MANAGER_REEXECUTE]   = "reexecute",
5299
        [MANAGER_REBOOT]      = "reboot",
5300
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5301
        [MANAGER_POWEROFF]    = "poweroff",
5302
        [MANAGER_HALT]        = "halt",
5303
        [MANAGER_KEXEC]       = "kexec",
5304
        [MANAGER_SWITCH_ROOT] = "switch-root",
5305
};
5306

5307
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
213✔
5308

5309
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5310
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5311
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5312
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5313
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5314
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5315
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5316
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5317
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5318
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5319
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5320
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5321
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5322
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5323
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5324
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5325
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5326
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5327
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5328
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5329
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5330
};
5331

5332
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
7,725✔
5333

5334
static const char* const oom_policy_table[_OOM_POLICY_MAX] = {
5335
        [OOM_CONTINUE] = "continue",
5336
        [OOM_STOP]     = "stop",
5337
        [OOM_KILL]     = "kill",
5338
};
5339

5340
DEFINE_STRING_TABLE_LOOKUP(oom_policy, OOMPolicy);
1,077✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc