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

systemd / systemd / 13380515387

17 Feb 2025 09:20PM UTC coverage: 71.822% (+0.1%) from 71.714%
13380515387

push

github

DaanDeMeyer
ukify: print all remaining log-like output to stderr

We want to be able to capture stdout for json and such, so convert
all remaining logging to stderr.

293883 of 409184 relevant lines covered (71.82%)

716959.33 hits per line

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

77.12
/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 "os-util.h"
72
#include "parse-util.h"
73
#include "path-lookup.h"
74
#include "path-util.h"
75
#include "plymouth-util.h"
76
#include "pretty-print.h"
77
#include "process-util.h"
78
#include "psi-util.h"
79
#include "ratelimit.h"
80
#include "rlimit-util.h"
81
#include "rm-rf.h"
82
#include "selinux-util.h"
83
#include "serialize.h"
84
#include "signal-util.h"
85
#include "socket-util.h"
86
#include "special.h"
87
#include "stat-util.h"
88
#include "string-table.h"
89
#include "string-util.h"
90
#include "strv.h"
91
#include "strxcpyx.h"
92
#include "sysctl-util.h"
93
#include "syslog-util.h"
94
#include "taint.h"
95
#include "terminal-util.h"
96
#include "time-util.h"
97
#include "transaction.h"
98
#include "uid-range.h"
99
#include "umask-util.h"
100
#include "unit-name.h"
101
#include "user-util.h"
102
#include "virt.h"
103
#include "watchdog.h"
104

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

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

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

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

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

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

139
static usec_t manager_watch_jobs_next_time(Manager *m) {
12,829✔
140
        usec_t timeout;
12,829✔
141

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

152
        return usec_add(now(CLOCK_MONOTONIC), timeout);
12,829✔
153
}
154

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

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

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

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

168
        assert(m);
5,696✔
169

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

176
        if (m->jobs_in_progress_event_source)
5,696✔
177
                return;
178

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

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

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

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

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

211
        assert(m);
×
212
        assert(m->n_running_jobs > 0);
×
213

214
        manager_flip_auto_status(m, true, "delay");
×
215

216
        print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
×
217

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

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

227
        cylon_pos = m->jobs_in_progress_iteration % 14;
×
228
        if (cylon_pos >= 8)
×
229
                cylon_pos = 14 - cylon_pos;
×
230
        draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
×
231

232
        m->jobs_in_progress_iteration++;
×
233

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

238
        (void) job_get_timeout(j, &timeout);
×
239

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

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

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

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

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

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

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

288
                return -errno;
×
289
        }
290

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

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

299
        return false;
300
}
301

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

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

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

313
        return 0;
96✔
314
}
315

316
static void manager_close_ask_password(Manager *m) {
755✔
317
        assert(m);
755✔
318

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

323
static int manager_check_ask_password(Manager *m) {
15,661✔
324
        int r;
15,661✔
325

326
        assert(m);
15,661✔
327

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

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

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

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

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

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

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

363
                /* Queries might have been added meanwhile... */
364
                (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✔
365
        }
366

367
        return m->have_ask_password;
15,661✔
368
}
369

370
static int manager_watch_idle_pipe(Manager *m) {
619✔
371
        int r;
619✔
372

373
        assert(m);
619✔
374

375
        if (m->idle_pipe_event_source)
619✔
376
                return 0;
377

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

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

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

387
        return 0;
43✔
388
}
389

390
static void manager_close_idle_pipe(Manager *m) {
1,923✔
391
        assert(m);
1,923✔
392

393
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
1,923✔
394

395
        safe_close_pair(m->idle_pipe);
1,923✔
396
        safe_close_pair(m->idle_pipe + 2);
1,923✔
397
}
1,923✔
398

399
static int manager_setup_time_change(Manager *m) {
265✔
400
        int r;
265✔
401

402
        assert(m);
265✔
403

404
        if (MANAGER_IS_TEST_RUN(m))
265✔
405
                return 0;
406

407
        m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
253✔
408

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

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

418
        log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
253✔
419

420
        return 0;
421
}
422

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

427
        assert(m);
293✔
428

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

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

440
                m->etc_localtime_mtime = k;
215✔
441
                m->etc_localtime_accessible = true;
215✔
442
        }
443

444
        return changed;
293✔
445
}
446

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

451
        assert(m);
275✔
452

453
        if (MANAGER_IS_TEST_RUN(m))
275✔
454
                return 0;
455

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

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

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

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

485
        sd_event_source_unref(m->timezone_change_event_source);
263✔
486
        m->timezone_change_event_source = TAKE_PTR(new_event);
263✔
487

488
        return 0;
263✔
489
}
490

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

494
        assert(m);
262✔
495

496
        if (!MANAGER_IS_SYSTEM(m) || MANAGER_IS_TEST_RUN(m))
262✔
497
                return 0;
498

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

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

514
        return 0;
515
}
516

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

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

527
        assert(m);
262✔
528

529
        assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
262✔
530

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

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

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

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

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

565
                        /* ... space ... */
566

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

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

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

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

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

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

601
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
262✔
602

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

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

622
        return manager_enable_special_signals(m);
262✔
623
}
624

625
static char** sanitize_environment(char **l) {
1,158✔
626

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

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

670
int manager_default_environment(Manager *m) {
886✔
671
        assert(m);
886✔
672

673
        m->transient_environment = strv_free(m->transient_environment);
886✔
674

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

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

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

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

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

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

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

716
        sanitize_environment(m->transient_environment);
886✔
717
        return 0;
886✔
718
}
719

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

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

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

742
        assert(m);
612✔
743

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

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

754
        return 0;
755
}
756

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

764
static int manager_setup_run_queue(Manager *m) {
612✔
765
        int r;
612✔
766

767
        assert(m);
612✔
768
        assert(!m->run_queue_event_source);
612✔
769

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

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

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

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

784
        return 0;
612✔
785
}
786

787
static int manager_setup_sigchld_event_source(Manager *m) {
262✔
788
        int r;
262✔
789

790
        assert(m);
262✔
791
        assert(!m->sigchld_event_source);
262✔
792

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

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

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

805
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
262✔
806

807
        return 0;
262✔
808
}
809

810
int manager_setup_memory_pressure_event_source(Manager *m) {
541✔
811
        int r;
541✔
812

813
        assert(m);
541✔
814

815
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
541✔
816

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

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

832
        return 0;
541✔
833
}
834

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

839
        assert(m);
612✔
840

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

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

861
        return 0;
862
}
863

864
void manager_set_switching_root(Manager *m, bool switching_root) {
921✔
865
        assert(m);
921✔
866

867
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
921✔
868
}
921✔
869

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

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

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

879
static int compare_job_priority(const void *a, const void *b) {
430,751✔
880
        const Job *x = a, *y = b;
430,751✔
881

882
        return unit_compare_priority(x->unit, y->unit);
430,751✔
883
}
884

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

889
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
612✔
890
        assert(ret);
612✔
891

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

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

901
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
902

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

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

911
                .show_status_overridden = _SHOW_STATUS_INVALID,
912

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

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

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

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

934
                .executor_fd = -EBADF,
935
        };
936

937
        unit_defaults_init(&m->defaults, runtime_scope);
612✔
938

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

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

951
                m->invocation_log_field = "INVOCATION_ID=";
455✔
952
                m->invocation_log_format_string = "INVOCATION_ID=%s";
455✔
953
        } else {
954
                m->unit_log_field = "USER_UNIT=";
157✔
955
                m->unit_log_format_string = "USER_UNIT=%s";
157✔
956

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

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

964
        r = manager_default_environment(m);
612✔
965
        if (r < 0)
612✔
966
                return r;
967

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

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

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

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

984
        r = manager_setup_prefix(m);
612✔
985
        if (r < 0)
612✔
986
                return r;
987

988
        r = manager_find_credentials_dirs(m);
612✔
989
        if (r < 0)
612✔
990
                return r;
991

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

996
        r = manager_setup_run_queue(m);
612✔
997
        if (r < 0)
612✔
998
                return r;
999

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

1009
                r = manager_setup_cgroup(m);
262✔
1010
                if (r < 0)
262✔
1011
                        return r;
1012

1013
                r = manager_setup_time_change(m);
262✔
1014
                if (r < 0)
262✔
1015
                        return r;
1016

1017
                r = manager_read_timezone_stat(m);
262✔
1018
                if (r < 0)
262✔
1019
                        return r;
1020

1021
                (void) manager_setup_timezone_change(m);
262✔
1022

1023
                r = manager_setup_sigchld_event_source(m);
262✔
1024
                if (r < 0)
262✔
1025
                        return r;
1026

1027
                r = manager_setup_memory_pressure_event_source(m);
262✔
1028
                if (r < 0)
262✔
1029
                        return r;
1030

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

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

1049
                        r = mkdir_p_label(units_path, 0755);
138✔
1050
                }
1051
                if (r < 0 && r != -EEXIST)
250✔
1052
                        return r;
1053
        }
1054

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

1060
                if (DEBUG_LOGGING) {
269✔
1061
                        _cleanup_free_ char *executor_path = NULL;
269✔
1062

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

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

1071
        *ret = TAKE_PTR(m);
612✔
1072

1073
        return 0;
612✔
1074
}
1075

1076
static int manager_setup_notify(Manager *m) {
634✔
1077
        int r;
634✔
1078

1079
        if (MANAGER_IS_TEST_RUN(m))
634✔
1080
                return 0;
1081

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

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

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

1095
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
216✔
1096

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

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

1107
                (void) mkdir_parents_label(m->notify_socket, 0755);
216✔
1108
                (void) sockaddr_un_unlink(&sa.un);
216✔
1109

1110
                r = mac_selinux_bind(fd, &sa.sa, sa_len);
216✔
1111
                if (r < 0)
216✔
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);
216✔
1115
                if (r < 0)
216✔
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);
216✔
1119
                if (r < 0 && r != -ENOPROTOOPT)
216✔
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);
216✔
1124

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

1128
        if (!m->notify_event_source) {
274✔
1129
                r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
274✔
1130
                if (r < 0)
274✔
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);
274✔
1136
                if (r < 0)
274✔
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");
274✔
1140
        }
1141

1142
        return 0;
1143
}
1144

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

1147
        static const union sockaddr_union sa = {
634✔
1148
                .un.sun_family = AF_UNIX,
1149
                .un.sun_path = "/run/systemd/cgroups-agent",
1150
        };
1151
        int r;
634✔
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))
634✔
1167
                return 0;
1168

1169
        if (!MANAGER_IS_SYSTEM(m))
274✔
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;
634✔
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) {
634✔
1220
        int r;
634✔
1221

1222
        assert(m);
634✔
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) {
634✔
1244

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

1249
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
576✔
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);
576✔
1253
        }
1254

1255
        if (!m->user_lookup_event_source) {
634✔
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);
634✔
1257
                if (r < 0)
634✔
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);
634✔
1263
                if (r < 0)
634✔
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");
634✔
1267
        }
1268

1269
        return 0;
1270
}
1271

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

1275
        assert(m);
634✔
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) {
634✔
1281
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
576✔
1282
                safe_close_pair(m->handoff_timestamp_fds);
576✔
1283

1284
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->handoff_timestamp_fds) < 0)
576✔
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);
576✔
1289

1290
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSCRED, true);
576✔
1291
                if (r < 0)
576✔
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);
576✔
1296
                if (r < 0)
576✔
1297
                        return log_error_errno(r, "Failed to make handoff timestamp socket O_NONBLOCK: %m");
×
1298
        }
1299

1300
        if (!m->handoff_timestamp_event_source) {
634✔
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);
634✔
1302
                if (r < 0)
634✔
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);
634✔
1306
                if (r < 0)
634✔
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");
634✔
1310
        }
1311

1312
        return 0;
1313
}
1314

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

1318
        assert(m);
634✔
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) {
634✔
1324
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
610✔
1325
                safe_close_pair(m->pidref_transport_fds);
610✔
1326

1327
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->pidref_transport_fds) < 0)
610✔
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);
610✔
1332

1333
                r = setsockopt_int(m->pidref_transport_fds[0], SOL_SOCKET, SO_PASSCRED, true);
610✔
1334
                if (r < 0)
610✔
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);
610✔
1338
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
610✔
1339
                        log_debug("SO_PASSPIDFD is not supported for pidref socket, ignoring.");
×
1340
                else if (r < 0)
610✔
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);
610✔
1345
                if (r < 0)
610✔
1346
                        return log_error_errno(r, "Failed to make pidref socket O_NONBLOCK: %m");
×
1347
        }
1348

1349
        if (!m->pidref_event_source) {
634✔
1350
                r = sd_event_add_io(m->event, &m->pidref_event_source, m->pidref_transport_fds[0], EPOLLIN, manager_dispatch_pidref_transport_fd, m);
610✔
1351
                if (r < 0)
610✔
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);
610✔
1355
                if (r < 0)
610✔
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");
610✔
1359
        }
1360

1361
        return 0;
1362
}
1363

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

1368
        assert(m);
320,765✔
1369

1370
        while ((u = m->cleanup_queue)) {
348,412✔
1371
                assert(u->in_cleanup_queue);
27,647✔
1372

1373
                unit_free(u);
27,647✔
1374
                n++;
27,647✔
1375
        }
1376

1377
        return n;
320,765✔
1378
}
1379

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

1384
        assert(m);
311,268✔
1385

1386
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
313,492✔
1387
                assert(u->in_release_resources_queue);
2,224✔
1388
                u->in_release_resources_queue = false;
2,224✔
1389

1390
                n++;
2,224✔
1391

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

1395
        return n;
311,268✔
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) {
79,902✔
1407
        Unit *other;
79,902✔
1408

1409
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
79,902✔
1410

1411
        /* Recursively mark referenced units as GOOD as well */
1412
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
707,619✔
1413
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
425,345✔
1414
                        unit_gc_mark_good(other, gc_marker);
2,942✔
1415
}
79,902✔
1416

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

1421
        assert(u);
132,773✔
1422

1423
        if (IN_SET(u->gc_marker - gc_marker,
132,773✔
1424
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1425
                return;
55,813✔
1426

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

1430
        if (!unit_may_gc(u))
107,548✔
1431
                goto good;
45,161✔
1432

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

1435
        is_bad = true;
62,387✔
1436

1437
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
136,824✔
1438
                unit_gc_sweep(other, gc_marker);
39,899✔
1439

1440
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
39,899✔
1441
                        goto good;
31,799✔
1442

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

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

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

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

1457
        if (is_bad)
30,588✔
1458
                goto bad;
27,640✔
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;
2,948✔
1463
        unit_add_to_gc_queue(u);
2,948✔
1464
        return;
1465

1466
bad:
27,640✔
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;
27,640✔
1470
        unit_add_to_cleanup_queue(u);
27,640✔
1471
        return;
1472

1473
good:
76,960✔
1474
        unit_gc_mark_good(u, gc_marker);
76,960✔
1475
}
1476

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

1481
        assert(m);
331,662✔
1482

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

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

1489
        gc_marker = m->gc_marker;
331,662✔
1490

1491
        while ((u = LIST_POP(gc_queue, m->gc_unit_queue))) {
424,028✔
1492
                assert(u->in_gc_queue);
92,366✔
1493

1494
                unit_gc_sweep(u, gc_marker);
92,366✔
1495

1496
                u->in_gc_queue = false;
92,366✔
1497

1498
                n++;
92,366✔
1499

1500
                if (IN_SET(u->gc_marker - gc_marker,
92,366✔
1501
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1502
                        if (u->id)
27,646✔
1503
                                log_unit_debug(u, "Collecting.");
54,697✔
1504
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
27,646✔
1505
                        unit_add_to_cleanup_queue(u);
27,646✔
1506
                }
1507
        }
1508

1509
        return n;
331,662✔
1510
}
1511

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

1516
        assert(m);
331,679✔
1517

1518
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
331,697✔
1519
                assert(j->in_gc_queue);
18✔
1520
                j->in_gc_queue = false;
18✔
1521

1522
                n++;
18✔
1523

1524
                if (!job_may_gc(j))
18✔
1525
                        continue;
18✔
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;
331,679✔
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) {
311,389✔
1577
        unsigned n = 0;
311,389✔
1578
        Unit *u;
311,389✔
1579
        int r;
311,389✔
1580

1581
        assert(m);
311,389✔
1582

1583
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
311,549✔
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;
311,389✔
1614
}
1615

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

1621
        assert(m);
311,558✔
1622

1623
        while ((u = LIST_POP(start_when_upheld_queue, m->start_when_upheld_queue))) {
311,558✔
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;
311,558✔
1655
}
1656

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

1662
        assert(m);
311,558✔
1663

1664
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
311,834✔
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;
311,558✔
1696
}
1697

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

1701
        assert(m);
636✔
1702

1703
        while ((u = hashmap_first(m->units)))
52,621✔
1704
                unit_free(u);
51,985✔
1705

1706
        manager_dispatch_cleanup_queue(m);
636✔
1707

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

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

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

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

1737
        manager_clear_jobs_and_units(m);
612✔
1738

1739
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
7,344✔
1740
                if (unit_vtable[c]->shutdown)
6,732✔
1741
                        unit_vtable[c]->shutdown(m);
2,448✔
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));
612✔
1745

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

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

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

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

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

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

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

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

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

1789
        manager_close_ask_password(m);
612✔
1790

1791
        manager_close_idle_pipe(m);
612✔
1792

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

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

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

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

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

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

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

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

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

1820
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
3,672✔
1821
                free(*i);
3,060✔
1822

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

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

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

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

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

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

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

1843
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
634✔
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,432✔
1848
                if (!unit_type_supported(c)) {
3,146✔
1849
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
459✔
1850
                        continue;
459✔
1851
                }
1852

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

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

1861
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
634✔
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,432✔
1866
                if (!unit_type_supported(c)) {
3,146✔
1867
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
459✔
1868
                        continue;
459✔
1869
                }
1870

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

1875
        manager_dispatch_load_queue(m);
286✔
1876
}
1877

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

1883
        assert(m);
634✔
1884

1885
        log_debug("Invoking unit coldplug() handlers%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
967✔
1886

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

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

1894
                r = unit_coldplug(u);
47,165✔
1895
                if (r < 0)
47,165✔
1896
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
49,029✔
1897
        }
1898
}
634✔
1899

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

1904
        assert(m);
634✔
1905

1906
        log_debug("Invoking unit catchup() handlers%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
967✔
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) {
49,029✔
1910

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

1915
                unit_catchup(u);
47,165✔
1916
        }
1917
}
634✔
1918

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

1922
        assert(m);
610✔
1923

1924
        HASHMAP_FOREACH(u, m->units) {
11,824✔
1925

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

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

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

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

1939
        assert(m);
58,883✔
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))
58,883✔
1946
                return false;
1947

1948
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
57,776✔
1949
        if (!u)
57,776✔
1950
                return false;
1951
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
102,258✔
1952
                return false;
1953

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

1965
        return true;
1966
}
1967

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

1971
        /* Let's set up our private bus connection now, unconditionally */
1972
        (void) bus_init_private(m);
610✔
1973

1974
        /* If we are in --user mode also connect to the system bus now */
1975
        if (MANAGER_IS_USER(m))
610✔
1976
                (void) bus_init_system(m);
155✔
1977

1978
        /* Let's connect to the bus now, but only if the unit is supposed to be up */
1979
        if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
610✔
1980
                (void) bus_init_api(m);
28✔
1981

1982
                if (MANAGER_IS_SYSTEM(m))
28✔
1983
                        (void) bus_init_system(m);
27✔
1984
        }
1985
}
610✔
1986

1987
static void manager_preset_all(Manager *m) {
610✔
1988
        int r;
610✔
1989

1990
        assert(m);
610✔
1991

1992
        if (m->first_boot <= 0)
610✔
1993
                return;
1994

1995
        if (!MANAGER_IS_SYSTEM(m))
17✔
1996
                return;
1997

1998
        if (MANAGER_IS_TEST_RUN(m))
17✔
1999
                return;
2000

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

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

2013
static void manager_ready(Manager *m) {
634✔
2014
        assert(m);
634✔
2015

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

2018
        m->objective = MANAGER_OK; /* Tell everyone we are up now */
634✔
2019

2020
        /* It might be safe to log to the journal now and connect to dbus */
2021
        manager_recheck_journal(m);
634✔
2022
        manager_recheck_dbus(m);
634✔
2023

2024
        /* Let's finally catch up with any changes that took place while we were reloading/reexecing */
2025
        manager_catchup(m);
634✔
2026

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

2034
Manager* manager_reloading_start(Manager *m) {
239✔
2035
        m->n_reloading++;
239✔
2036
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
239✔
2037
        return m;
239✔
2038
}
2039

2040
void manager_reloading_stopp(Manager **m) {
815✔
2041
        if (*m) {
815✔
2042
                assert((*m)->n_reloading > 0);
215✔
2043
                (*m)->n_reloading--;
215✔
2044
        }
2045
}
815✔
2046

2047
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
610✔
2048
        int r;
610✔
2049

2050
        assert(m);
610✔
2051

2052
        /* If we are running in test mode, we still want to run the generators,
2053
         * but we should not touch the real generator directories. */
2054
        r = lookup_paths_init_or_warn(&m->lookup_paths, m->runtime_scope,
610✔
2055
                                      MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
610✔
2056
                                      root);
2057
        if (r < 0)
610✔
2058
                return r;
2059

2060
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
610✔
2061
        r = manager_run_environment_generators(m);
610✔
2062
        if (r >= 0)
610✔
2063
                r = manager_run_generators(m);
610✔
2064
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
610✔
2065
        if (r < 0)
610✔
2066
                return r;
2067

2068
        manager_preset_all(m);
610✔
2069

2070
        lookup_paths_log(&m->lookup_paths);
610✔
2071

2072
        {
2073
                /* This block is (optionally) done with the reloading counter bumped */
2074
                _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
610✔
2075

2076
                /* Make sure we don't have a left-over from a previous run */
2077
                if (!serialization)
610✔
2078
                        (void) rm_rf(m->lookup_paths.transient, 0);
576✔
2079

2080
                /* If we will deserialize make sure that during enumeration this is already known, so we increase the
2081
                 * counter here already */
2082
                if (serialization)
34✔
2083
                        reloading = manager_reloading_start(m);
34✔
2084

2085
                /* First, enumerate what we can from all config files */
2086
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
610✔
2087
                manager_enumerate_perpetual(m);
610✔
2088
                manager_enumerate(m);
610✔
2089
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
610✔
2090

2091
                /* Second, deserialize if there is something to deserialize */
2092
                if (serialization) {
610✔
2093
                        r = manager_deserialize(m, serialization, fds);
34✔
2094
                        if (r < 0)
34✔
2095
                                return log_error_errno(r, "Deserialization failed: %m");
×
2096
                }
2097

2098
                if (m->previous_objective >= 0) {
610✔
2099
                        if (IN_SET(m->previous_objective, MANAGER_REEXECUTE, MANAGER_SOFT_REBOOT, MANAGER_SWITCH_ROOT))
34✔
2100
                                log_debug("Launching as effect of a '%s' operation.",
34✔
2101
                                          manager_objective_to_string(m->previous_objective));
2102
                        else
2103
                                log_warning("Got unexpected previous objective '%s', ignoring.",
×
2104
                                            manager_objective_to_string(m->previous_objective));
2105
                }
2106

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

2112
                /* Any fds left? Find some unit which wants them. This is useful to allow container managers to pass
2113
                 * some file descriptors to us pre-initialized. This enables socket-based activation of entire
2114
                 * containers. */
2115
                manager_distribute_fds(m, fds);
610✔
2116

2117
                /* We might have deserialized the notify fd, but if we didn't then let's create it now */
2118
                r = manager_setup_notify(m);
610✔
2119
                if (r < 0)
610✔
2120
                        /* No sense to continue without notifications, our children would fail anyway. */
2121
                        return r;
2122

2123
                r = manager_setup_cgroups_agent(m);
610✔
2124
                if (r < 0)
610✔
2125
                        /* Likewise, no sense to continue without empty cgroup notifications. */
2126
                        return r;
2127

2128
                r = manager_setup_user_lookup_fd(m);
610✔
2129
                if (r < 0)
610✔
2130
                        /* This shouldn't fail, except if things are really broken. */
2131
                        return r;
2132

2133
                r = manager_setup_handoff_timestamp_fd(m);
610✔
2134
                if (r < 0)
610✔
2135
                        /* This shouldn't fail, except if things are really broken. */
2136
                        return r;
2137

2138
                r = manager_setup_pidref_transport_fd(m);
610✔
2139
                if (r < 0)
610✔
2140
                        /* This shouldn't fail, except if things are really broken. */
2141
                        return r;
2142

2143
                /* Connect to the bus if we are good for it */
2144
                manager_setup_bus(m);
610✔
2145

2146
                r = manager_varlink_init(m);
610✔
2147
                if (r < 0)
610✔
2148
                        log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
×
2149

2150
                /* Third, fire things up! */
2151
                manager_coldplug(m);
610✔
2152

2153
                /* Clean up runtime objects */
2154
                manager_vacuum(m);
610✔
2155

2156
                if (serialization)
610✔
2157
                        /* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
2158
                         * reload is finished */
2159
                        m->send_reloading_done = true;
34✔
2160
        }
2161

2162
        manager_ready(m);
610✔
2163

2164
        manager_set_switching_root(m, false);
610✔
2165

2166
        return 0;
610✔
2167
}
2168

2169
int manager_add_job_full(
1,519✔
2170
                Manager *m,
2171
                JobType type,
2172
                Unit *unit,
2173
                JobMode mode,
2174
                TransactionAddFlags extra_flags,
2175
                Set *affected_jobs,
2176
                sd_bus_error *error,
2177
                Job **ret) {
2178

2179
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,519✔
2180
        int r;
1,519✔
2181

2182
        assert(m);
1,519✔
2183
        assert(type >= 0 && type < _JOB_TYPE_MAX);
1,519✔
2184
        assert(unit);
1,519✔
2185
        assert(mode >= 0 && mode < _JOB_MODE_MAX);
1,519✔
2186
        assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
1,519✔
2187

2188
        if (mode == JOB_ISOLATE && type != JOB_START)
1,519✔
2189
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
×
2190

2191
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,519✔
2192
                return sd_bus_error_set(error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
24✔
2193

2194
        if (mode == JOB_TRIGGERING && type != JOB_STOP)
1,495✔
2195
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
×
2196

2197
        if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
1,495✔
2198
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=restart-dependencies is only valid for start.");
×
2199

2200
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
2,702✔
2201

2202
        type = job_type_collapse(type, unit);
1,495✔
2203

2204
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1,495✔
2205
        if (!tr)
1,495✔
2206
                return -ENOMEM;
2207

2208
        r = transaction_add_job_and_dependencies(
4,485✔
2209
                        tr,
2210
                        type,
2211
                        unit,
2212
                        /* by= */ NULL,
2213
                        TRANSACTION_MATTERS |
2214
                        (IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
1,495✔
2215
                        (mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
1,495✔
2216
                        (mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
2,981✔
2217
                        extra_flags,
2218
                        error);
2219
        if (r < 0)
1,495✔
2220
                return r;
2221

2222
        if (mode == JOB_ISOLATE) {
1,489✔
2223
                r = transaction_add_isolate_jobs(tr, m);
259✔
2224
                if (r < 0)
259✔
2225
                        return r;
2226
        }
2227

2228
        if (mode == JOB_TRIGGERING) {
1,489✔
2229
                r = transaction_add_triggering_jobs(tr, unit);
×
2230
                if (r < 0)
×
2231
                        return r;
2232
        }
2233

2234
        r = transaction_activate(tr, m, mode, affected_jobs, error);
1,489✔
2235
        if (r < 0)
1,489✔
2236
                return r;
2237

2238
        log_unit_debug(unit,
2,682✔
2239
                       "Enqueued job %s/%s as %u", unit->id,
2240
                       job_type_to_string(type), (unsigned) tr->anchor_job->id);
2241

2242
        if (ret)
1,485✔
2243
                *ret = tr->anchor_job;
734✔
2244

2245
        tr = transaction_free(tr);
1,485✔
2246
        return 0;
1,485✔
2247
}
2248

2249
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
162✔
2250
        Unit *unit = NULL;  /* just to appease gcc, initialization is not really necessary */
162✔
2251
        int r;
162✔
2252

2253
        assert(m);
162✔
2254
        assert(type < _JOB_TYPE_MAX);
162✔
2255
        assert(name);
162✔
2256
        assert(mode < _JOB_MODE_MAX);
162✔
2257

2258
        r = manager_load_unit(m, name, NULL, NULL, &unit);
162✔
2259
        if (r < 0)
162✔
2260
                return r;
162✔
2261
        assert(unit);
162✔
2262

2263
        return manager_add_job_full(m, type, unit, mode, /* extra_flags = */ 0, affected_jobs, e, ret);
162✔
2264
}
2265

2266
int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
138✔
2267
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
138✔
2268
        int r;
138✔
2269

2270
        assert(m);
138✔
2271
        assert(type < _JOB_TYPE_MAX);
138✔
2272
        assert(name);
138✔
2273
        assert(mode < _JOB_MODE_MAX);
138✔
2274

2275
        r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
138✔
2276
        if (r < 0)
138✔
2277
                return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
×
2278

2279
        return r;
2280
}
2281

2282
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
9,000✔
2283
        int r;
9,000✔
2284
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
9,000✔
2285

2286
        assert(m);
9,000✔
2287
        assert(unit);
9,000✔
2288
        assert(mode < _JOB_MODE_MAX);
9,000✔
2289
        assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
9,000✔
2290

2291
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
9,000✔
2292
        if (!tr)
9,000✔
2293
                return -ENOMEM;
2294

2295
        /* We need an anchor job */
2296
        r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
9,000✔
2297
        if (r < 0)
9,000✔
2298
                return r;
2299

2300
        /* Failure in adding individual dependencies is ignored, so this always succeeds. */
2301
        transaction_add_propagate_reload_jobs(
9,000✔
2302
                        tr,
2303
                        unit,
2304
                        tr->anchor_job,
9,000✔
2305
                        mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0);
2306

2307
        r = transaction_activate(tr, m, mode, NULL, e);
9,000✔
2308
        if (r < 0)
9,000✔
2309
                return r;
2310

2311
        tr = transaction_free(tr);
9,000✔
2312
        return 0;
9,000✔
2313
}
2314

2315
Job *manager_get_job(Manager *m, uint32_t id) {
22,718✔
2316
        assert(m);
22,718✔
2317

2318
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
22,718✔
2319
}
2320

2321
Unit *manager_get_unit(Manager *m, const char *name) {
2,328,297✔
2322
        assert(m);
2,328,297✔
2323
        assert(name);
2,328,297✔
2324

2325
        return hashmap_get(m->units, name);
2,328,297✔
2326
}
2327

2328
static int manager_dispatch_target_deps_queue(Manager *m) {
343,284✔
2329
        Unit *u;
343,284✔
2330
        int r = 0;
343,284✔
2331

2332
        assert(m);
343,284✔
2333

2334
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
400,891✔
2335
                _cleanup_free_ Unit **targets = NULL;
57,607✔
2336
                int n_targets;
57,607✔
2337

2338
                assert(u->in_target_deps_queue);
57,607✔
2339

2340
                u->in_target_deps_queue = false;
57,607✔
2341

2342
                /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2343
                 * dependencies, and we can't have it that hash tables we iterate through are modified while
2344
                 * we are iterating through them. */
2345
                n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
57,607✔
2346
                if (n_targets < 0)
57,607✔
2347
                        return n_targets;
2348

2349
                FOREACH_ARRAY(i, targets, n_targets) {
125,091✔
2350
                        r = unit_add_default_target_dependency(u, *i);
67,484✔
2351
                        if (r < 0)
67,484✔
2352
                                return r;
2353
                }
2354
        }
2355

2356
        return r;
2357
}
2358

2359
unsigned manager_dispatch_load_queue(Manager *m) {
378,359✔
2360
        Unit *u;
378,359✔
2361
        unsigned n = 0;
378,359✔
2362

2363
        assert(m);
378,359✔
2364

2365
        /* Make sure we are not run recursively */
2366
        if (m->dispatching_load_queue)
378,359✔
2367
                return 0;
2368

2369
        m->dispatching_load_queue = true;
343,284✔
2370

2371
        /* Dispatches the load queue. Takes a unit from the queue and
2372
         * tries to load its data until the queue is empty */
2373

2374
        while ((u = m->load_queue)) {
423,018✔
2375
                assert(u->in_load_queue);
79,734✔
2376

2377
                unit_load(u);
79,734✔
2378
                n++;
79,734✔
2379
        }
2380

2381
        m->dispatching_load_queue = false;
343,284✔
2382

2383
        /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2384
         * should be loaded and have aliases resolved */
2385
        (void) manager_dispatch_target_deps_queue(m);
343,284✔
2386

2387
        return n;
343,284✔
2388
}
2389

2390
bool manager_unit_cache_should_retry_load(Unit *u) {
509,653✔
2391
        assert(u);
509,653✔
2392

2393
        /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2394
         * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2395
         * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
2396
        if (u->load_state != UNIT_NOT_FOUND)
509,653✔
2397
                return false;
2398

2399
        /* The cache has been updated since the last time we tried to load the unit. There might be new
2400
         * fragment paths to read. */
2401
        if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
2,828✔
2402
                return true;
2403

2404
        /* The cache needs to be updated because there are modifications on disk. */
2405
        return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
2,828✔
2406
}
2407

2408
int manager_load_unit_prepare(
567,101✔
2409
                Manager *m,
2410
                const char *name,
2411
                const char *path,
2412
                sd_bus_error *e,
2413
                Unit **ret) {
2414

2415
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2416
        _cleanup_free_ char *nbuf = NULL;
567,101✔
2417
        int r;
567,101✔
2418

2419
        assert(m);
567,101✔
2420
        assert(ret);
567,101✔
2421
        assert(name || path);
567,101✔
2422

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

2425
        if (path && !path_is_absolute(path))
567,101✔
2426
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2427

2428
        if (!name) {
567,101✔
2429
                r = path_extract_filename(path, &nbuf);
338✔
2430
                if (r < 0)
338✔
2431
                        return r;
2432
                if (r == O_DIRECTORY)
338✔
2433
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2434

2435
                name = nbuf;
338✔
2436
        }
2437

2438
        UnitType t = unit_name_to_type(name);
567,101✔
2439

2440
        if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
567,101✔
2441
                if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
×
2442
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
×
2443

2444
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
×
2445
        }
2446

2447
        Unit *unit = manager_get_unit(m, name);
567,101✔
2448
        if (unit) {
567,101✔
2449
                /* The time-based cache allows new units to be started without daemon-reload,
2450
                 * but if they are already referenced (because of dependencies or ordering)
2451
                 * then we have to force a load of the fragment. As an optimization, check
2452
                 * first if anything in the usual paths was modified since the last time
2453
                 * the cache was loaded. Also check if the last time an attempt to load the
2454
                 * unit was made was before the most recent cache refresh, so that we know
2455
                 * we need to try again — even if the cache is current, it might have been
2456
                 * updated in a different context before we had a chance to retry loading
2457
                 * this particular unit. */
2458
                if (manager_unit_cache_should_retry_load(unit))
508,950✔
2459
                        unit->load_state = UNIT_STUB;
×
2460
                else {
2461
                        *ret = unit;
508,950✔
2462
                        return 0;  /* The unit was already loaded */
508,950✔
2463
                }
2464
        } else {
2465
                unit = cleanup_unit = unit_new(m, unit_vtable[t]->object_size);
58,151✔
2466
                if (!unit)
58,151✔
2467
                        return -ENOMEM;
2468
        }
2469

2470
        if (path) {
58,151✔
2471
                r = free_and_strdup(&unit->fragment_path, path);
338✔
2472
                if (r < 0)
338✔
2473
                        return r;
2474
        }
2475

2476
        r = unit_add_name(unit, name);
58,151✔
2477
        if (r < 0)
58,151✔
2478
                return r;
2479

2480
        unit_add_to_load_queue(unit);
58,151✔
2481
        unit_add_to_dbus_queue(unit);
58,151✔
2482
        unit_add_to_gc_queue(unit);
58,151✔
2483

2484
        *ret = unit;
58,151✔
2485
        TAKE_PTR(cleanup_unit);
58,151✔
2486

2487
        return 1;  /* The unit was added the load queue */
58,151✔
2488
}
2489

2490
int manager_load_unit(
546,698✔
2491
                Manager *m,
2492
                const char *name,
2493
                const char *path,
2494
                sd_bus_error *e,
2495
                Unit **ret) {
2496
        int r;
546,698✔
2497

2498
        assert(m);
546,698✔
2499
        assert(ret);
546,698✔
2500

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

2503
        r = manager_load_unit_prepare(m, name, path, e, ret);
546,698✔
2504
        if (r <= 0)
546,698✔
2505
                return r;
2506

2507
        /* Unit was newly loaded */
2508
        manager_dispatch_load_queue(m);
37,764✔
2509
        *ret = unit_follow_merge(*ret);
37,764✔
2510
        return 0;
37,764✔
2511
}
2512

2513
int manager_load_startable_unit_or_warn(
598✔
2514
                Manager *m,
2515
                const char *name,
2516
                const char *path,
2517
                Unit **ret) {
2518

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

2521
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
598✔
2522
        Unit *unit;
598✔
2523
        int r;
598✔
2524

2525
        r = manager_load_unit(m, name, path, &error, &unit);
598✔
2526
        if (r < 0)
598✔
2527
                return log_error_errno(r, "Failed to load %s %s: %s",
×
2528
                                       name ? "unit" : "unit file", name ?: path,
2529
                                       bus_error_message(&error, r));
2530

2531
        r = bus_unit_validate_load_state(unit, &error);
598✔
2532
        if (r < 0)
598✔
2533
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2534

2535
        *ret = unit;
589✔
2536
        return 0;
589✔
2537
}
2538

2539
void manager_clear_jobs(Manager *m) {
328✔
2540
        Job *j;
328✔
2541

2542
        assert(m);
328✔
2543

2544
        while ((j = hashmap_first(m->jobs)))
355✔
2545
                /* No need to recurse. We're cancelling all jobs. */
2546
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
27✔
2547
}
328✔
2548

2549
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
3,822✔
2550
        assert(m);
3,822✔
2551

2552
        for (;;) {
×
2553
                Unit *u;
3,822✔
2554

2555
                u = manager_get_unit_by_pidref_watching(m, pid);
3,822✔
2556
                if (!u)
3,822✔
2557
                        break;
2558

2559
                unit_unwatch_pidref(u, pid);
×
2560
        }
2561
}
3,822✔
2562

2563
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
7,244✔
2564
        Manager *m = ASSERT_PTR(userdata);
7,244✔
2565
        Job *j;
7,244✔
2566

2567
        assert(source);
7,244✔
2568

2569
        while ((j = prioq_peek(m->run_queue))) {
68,183✔
2570
                assert(j->installed);
60,939✔
2571
                assert(j->in_run_queue);
60,939✔
2572

2573
                (void) job_run_and_invalidate(j);
60,939✔
2574
        }
2575

2576
        if (m->n_running_jobs > 0)
7,244✔
2577
                manager_watch_jobs_in_progress(m);
5,696✔
2578

2579
        if (m->n_on_console > 0)
7,244✔
2580
                manager_watch_idle_pipe(m);
619✔
2581

2582
        return 1;
7,244✔
2583
}
2584

2585
void manager_trigger_run_queue(Manager *m) {
63,022✔
2586
        int r;
63,022✔
2587

2588
        assert(m);
63,022✔
2589

2590
        r = sd_event_source_set_enabled(
125,964✔
2591
                        m->run_queue_event_source,
2592
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
63,022✔
2593
        if (r < 0)
63,022✔
2594
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2595
}
63,022✔
2596

2597
static unsigned manager_dispatch_dbus_queue(Manager *m) {
309,520✔
2598
        unsigned n = 0, budget;
309,520✔
2599
        Unit *u;
309,520✔
2600
        Job *j;
309,520✔
2601

2602
        assert(m);
309,520✔
2603

2604
        /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2605
         * as we can. There's no point in throttling generation of signals in that case. */
2606
        if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message)
309,520✔
2607
                budget = UINT_MAX; /* infinite budget in this case */
2608
        else {
2609
                /* Anything to do at all? */
2610
                if (!m->dbus_unit_queue && !m->dbus_job_queue)
309,462✔
2611
                        return 0;
2612

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

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

2632
        while (budget != 0 && (u = m->dbus_unit_queue)) {
43,782✔
2633

2634
                assert(u->in_dbus_queue);
35,232✔
2635

2636
                bus_unit_send_change_signal(u);
35,232✔
2637
                n++;
35,232✔
2638

2639
                if (budget != UINT_MAX)
35,232✔
2640
                        budget--;
24,185✔
2641
        }
2642

2643
        while (budget != 0 && (j = m->dbus_job_queue)) {
43,154✔
2644
                assert(j->in_dbus_queue);
34,604✔
2645

2646
                bus_job_send_change_signal(j);
34,604✔
2647
                n++;
34,604✔
2648

2649
                if (budget != UINT_MAX)
34,604✔
2650
                        budget--;
33,875✔
2651
        }
2652

2653
        if (m->send_reloading_done) {
8,550✔
2654
                m->send_reloading_done = false;
58✔
2655
                bus_manager_send_reloading(m, false);
58✔
2656
                n++;
58✔
2657
        }
2658

2659
        if (m->pending_reload_message) {
8,550✔
2660
                bus_send_pending_reload_message(m);
24✔
2661
                n++;
24✔
2662
        }
2663

2664
        return n;
2665
}
2666

2667
static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
×
2668
        Manager *m = userdata;
×
2669
        char buf[PATH_MAX];
×
2670
        ssize_t n;
×
2671

2672
        n = recv(fd, buf, sizeof(buf), 0);
×
2673
        if (n < 0)
×
2674
                return log_error_errno(errno, "Failed to read cgroups agent message: %m");
×
2675
        if (n == 0) {
×
2676
                log_error("Got zero-length cgroups agent message, ignoring.");
×
2677
                return 0;
×
2678
        }
2679
        if ((size_t) n >= sizeof(buf)) {
×
2680
                log_error("Got overly long cgroups agent message, ignoring.");
×
2681
                return 0;
×
2682
        }
2683

2684
        if (memchr(buf, 0, n)) {
×
2685
                log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
×
2686
                return 0;
×
2687
        }
2688
        buf[n] = 0;
×
2689

2690
        manager_notify_cgroup_empty(m, buf);
×
2691
        (void) bus_forward_agent_released(m, buf);
×
2692

2693
        return 0;
2694
}
2695

2696
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
7,824✔
2697

2698
        /* nothing else must be sent when using BARRIER=1 */
2699
        if (strv_contains(tags, "BARRIER=1")) {
7,824✔
2700
                if (strv_length(tags) != 1)
12✔
2701
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
×
2702
                else if (fdset_size(fds) != 1)
12✔
2703
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
×
2704

2705
                /* Drop the message if BARRIER=1 was found */
2706
                return true;
12✔
2707
        }
2708

2709
        return false;
2710
}
2711

2712
static void manager_invoke_notify_message(
15,551✔
2713
                Manager *m,
2714
                Unit *u,
2715
                PidRef *pidref,
2716
                const struct ucred *ucred,
2717
                char * const *tags,
2718
                FDSet *fds) {
2719

2720
        assert(m);
15,551✔
2721
        assert(u);
15,551✔
2722
        assert(pidref_is_set(pidref));
15,551✔
2723
        assert(ucred);
15,551✔
2724
        assert(pidref->pid == ucred->pid);
15,551✔
2725
        assert(tags);
15,551✔
2726

2727
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
15,551✔
2728
                return;
2729
        u->notifygen = m->notifygen;
7,812✔
2730

2731
        if (UNIT_VTABLE(u)->notify_message)
7,812✔
2732
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
7,812✔
2733

2734
        else if (DEBUG_LOGGING) {
×
2735
                _cleanup_free_ char *joined = strv_join(tags, ", ");
×
2736
                char buf[CELLESCAPE_DEFAULT_LENGTH];
×
2737

2738
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
×
2739
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
2740
        }
2741
}
2742

2743
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
20,587✔
2744
        /* Determine array of every unit that is interested in the specified process */
2745

2746
        assert(m);
20,587✔
2747
        assert(pidref_is_set(pidref));
20,587✔
2748

2749
        Unit *u1, *u2, **array;
20,587✔
2750
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
20,587✔
2751
        u2 = hashmap_get(m->watch_pids, pidref);
20,587✔
2752
        array = hashmap_get(m->watch_pids_more, pidref);
20,587✔
2753

2754
        size_t n = 0;
20,587✔
2755
        if (u1)
20,587✔
2756
                n++;
20,587✔
2757
        if (u2)
20,587✔
2758
                n++;
15,099✔
2759
        if (array)
20,587✔
2760
                for (size_t j = 0; array[j]; j++)
×
2761
                        n++;
×
2762

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

2765
        if (ret_units) {
20,587✔
2766
                _cleanup_free_ Unit **units = NULL;
×
2767

2768
                if (n > 0) {
20,587✔
2769
                        units = new(Unit*, n + 1);
20,587✔
2770
                        if (!units)
20,587✔
2771
                                return -ENOMEM;
×
2772

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

2777
                        size_t i = 0;
20,587✔
2778
                        if (u1)
20,587✔
2779
                                units[i++] = u1;
20,587✔
2780
                        if (u2)
20,587✔
2781
                                units[i++] = u2;
15,099✔
2782
                        if (array)
20,587✔
2783
                                for (size_t j = 0; array[j]; j++)
×
2784
                                        units[i++] = array[j];
×
2785
                        assert(i == n);
20,587✔
2786

2787
                        units[i] = NULL; /* end array in an extra NULL */
20,587✔
2788
                }
2789

2790
                *ret_units = TAKE_PTR(units);
20,587✔
2791
        }
2792

2793
        return (int) n;
20,587✔
2794
}
2795

2796
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
7,824✔
2797
        Manager *m = ASSERT_PTR(userdata);
7,824✔
2798
        char buf[NOTIFY_BUFFER_MAX+1];
7,824✔
2799
        struct iovec iovec = {
7,824✔
2800
                .iov_base = buf,
2801
                .iov_len = sizeof(buf)-1,
2802
        };
2803
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) /* SCM_PIDFD */ +
7,824✔
2804
                         CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)) control;
2805
        struct msghdr msghdr = {
7,824✔
2806
                .msg_iov = &iovec,
2807
                .msg_iovlen = 1,
2808
                .msg_control = &control,
2809
                .msg_controllen = sizeof(control),
2810
        };
2811
        ssize_t n;
7,824✔
2812
        int r;
7,824✔
2813

2814
        assert(m->notify_fd == fd);
7,824✔
2815

2816
        if (revents != EPOLLIN) {
7,824✔
2817
                log_warning("Got unexpected poll event for notify fd.");
×
2818
                return 0;
×
2819
        }
2820

2821
        n = recvmsg_safe(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
7,824✔
2822
        if (ERRNO_IS_NEG_TRANSIENT(n))
7,824✔
2823
                return 0; /* Spurious wakeup, try again */
2824
        if (n == -ECHRNG) {
7,824✔
2825
                log_warning_errno(n, "Got message with truncated control data (too many fds sent?), ignoring.");
×
2826
                return 0;
×
2827
        }
2828
        if (n == -EXFULL) {
7,824✔
2829
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
2830
                return 0;
×
2831
        }
2832
        if (n < 0)
7,824✔
2833
                /* If this is any other, real error, then stop processing this socket. This of course means
2834
                 * we won't take notification messages anymore, but that's still better than busy looping:
2835
                 * being woken up over and over again, but being unable to actually read the message from the
2836
                 * socket. */
2837
                return log_error_errno(n, "Failed to receive notification message: %m");
×
2838

2839
        _cleanup_close_ int pidfd = -EBADF;
7,824✔
2840
        struct ucred *ucred = NULL;
7,824✔
2841
        int *fd_array = NULL;
7,824✔
2842
        size_t n_fds = 0;
7,824✔
2843

2844
        struct cmsghdr *cmsg;
7,824✔
2845
        CMSG_FOREACH(cmsg, &msghdr) {
53,304✔
2846
                if (cmsg->cmsg_level != SOL_SOCKET)
18,828✔
2847
                        continue;
×
2848

2849
                if (cmsg->cmsg_type == SCM_RIGHTS) {
18,828✔
2850
                        assert(!fd_array);
3,180✔
2851
                        fd_array = CMSG_TYPED_DATA(cmsg, int);
3,180✔
2852
                        n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
3,180✔
2853
                } else if (cmsg->cmsg_type == SCM_CREDENTIALS &&
15,648✔
2854
                           cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
7,824✔
2855

2856
                        assert(!ucred);
7,824✔
2857
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
7,824✔
2858
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
7,824✔
2859
                        assert(pidfd < 0);
7,824✔
2860
                        pidfd = *CMSG_TYPED_DATA(cmsg, int);
7,824✔
2861
                }
2862
        }
2863

2864
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
7,824✔
2865

2866
        if (n_fds > 0) {
7,824✔
2867
                assert(fd_array);
3,180✔
2868

2869
                r = fdset_new_array(&fds, fd_array, n_fds);
3,180✔
2870
                if (r < 0) {
3,180✔
2871
                        close_many(fd_array, n_fds);
×
2872
                        log_oom_warning();
×
2873
                        return 0;
2874
                }
2875
        }
2876

2877
        if (!ucred || !pid_is_valid(ucred->pid)) {
7,824✔
2878
                log_warning("Received notify message without valid credentials. Ignoring.");
×
2879
                return 0;
×
2880
        }
2881

2882
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
7,824✔
2883

2884
        if (pidfd >= 0)
7,824✔
2885
                r = pidref_set_pidfd_consume(&pidref, TAKE_FD(pidfd));
7,824✔
2886
        else
2887
                r = pidref_set_pid(&pidref, ucred->pid);
×
2888
        if (r < 0) {
7,824✔
2889
                if (r == -ESRCH)
×
2890
                        log_debug_errno(r, "Notify sender died before message is processed. Ignoring.");
×
2891
                else
2892
                        log_warning_errno(r, "Failed to pin notify sender, ignoring message: %m");
×
2893
                return 0;
×
2894
        }
2895

2896
        if (pidref.pid != ucred->pid) {
7,824✔
2897
                assert(pidref.fd >= 0);
×
2898

2899
                log_warning("Got SCM_PIDFD for process " PID_FMT " but SCM_CREDENTIALS for process " PID_FMT ". Ignoring.",
×
2900
                            pidref.pid, ucred->pid);
2901
                return 0;
×
2902
        }
2903

2904
        /* As extra safety check, let's make sure the string we get doesn't contain embedded NUL bytes.
2905
         * We permit one trailing NUL byte in the message, but don't expect it. */
2906
        if (n > 1 && memchr(buf, 0, n-1)) {
7,824✔
2907
                log_warning("Received notify message with embedded NUL bytes. Ignoring.");
×
2908
                return 0;
×
2909
        }
2910

2911
        /* Make sure it's NUL-terminated, then parse it to obtain the tags list. */
2912
        buf[n] = 0;
7,824✔
2913

2914
        _cleanup_strv_free_ char **tags = strv_split_newlines(buf);
15,648✔
2915
        if (!tags) {
7,824✔
2916
                log_oom_warning();
×
2917
                return 0;
2918
        }
2919

2920
        /* Possibly a barrier fd, let's see. */
2921
        if (manager_process_barrier_fd(tags, fds)) {
7,824✔
2922
                log_debug("Received barrier notification message from PID " PID_FMT ".", ucred->pid);
12✔
2923
                return 0;
12✔
2924
        }
2925

2926
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
2927
        m->notifygen++;
7,812✔
2928

2929
        /* Notify every unit that might be interested, which might be multiple. */
2930
        _cleanup_free_ Unit **array = NULL;
7,812✔
2931

2932
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
7,812✔
2933
        if (n_array < 0) {
7,812✔
2934
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
2935
                return 0;
×
2936
        }
2937
        if (n_array == 0)
7,812✔
2938
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", ucred->pid);
×
2939
        else
2940
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
2941
                 * duplicate units – making sure we only invoke each unit's handler once. */
2942
                FOREACH_ARRAY(u, array, n_array)
23,363✔
2943
                        manager_invoke_notify_message(m, *u, &pidref, ucred, tags, fds);
15,551✔
2944

2945
        if (!fdset_isempty(fds))
7,812✔
2946
                log_warning("Got extra auxiliary fds with notification message, closing them.");
7,812✔
2947

2948
        return 0;
2949
}
2950

2951
static void manager_invoke_sigchld_event(
12,529✔
2952
                Manager *m,
2953
                Unit *u,
2954
                const siginfo_t *si) {
2955

2956
        assert(m);
12,529✔
2957
        assert(u);
12,529✔
2958
        assert(si);
12,529✔
2959

2960
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2961
        if (u->sigchldgen == m->sigchldgen)
12,529✔
2962
                return;
2963
        u->sigchldgen = m->sigchldgen;
8,973✔
2964

2965
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
17,827✔
2966
        unit_unwatch_pid(u, si->si_pid);
8,973✔
2967

2968
        if (UNIT_VTABLE(u)->sigchld_event)
8,973✔
2969
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
7,735✔
2970
}
2971

2972
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
14,970✔
2973
        Manager *m = ASSERT_PTR(userdata);
14,970✔
2974
        siginfo_t si = {};
14,970✔
2975
        int r;
14,970✔
2976

2977
        assert(source);
14,970✔
2978

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

2982
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
14,970✔
2983

2984
                if (errno != ECHILD)
185✔
2985
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
×
2986

2987
                goto turn_off;
185✔
2988
        }
2989

2990
        if (si.si_pid <= 0)
14,785✔
2991
                goto turn_off;
5,813✔
2992

2993
        if (IN_SET(si.si_code, CLD_EXITED, CLD_KILLED, CLD_DUMPED)) {
8,972✔
2994
                _cleanup_free_ char *name = NULL;
17,944✔
2995
                (void) pid_get_comm(si.si_pid, &name);
8,972✔
2996

2997
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
17,825✔
2998
                          si.si_pid, strna(name),
2999
                          sigchld_code_to_string(si.si_code),
3000
                          si.si_status,
3001
                          strna(si.si_code == CLD_EXITED
3002
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
3003
                                : signal_to_string(si.si_status)));
3004

3005
                /* Increase the generation counter used for filtering out duplicate unit invocations */
3006
                m->sigchldgen++;
8,972✔
3007

3008
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
3009
                 * pidfd here any more even if we wanted (since the process just exited). */
3010
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
8,972✔
3011

3012
                /* And now figure out the units this belongs to, there might be multiple... */
3013
                _cleanup_free_ Unit **array = NULL;
8,972✔
3014
                int n_array = manager_get_units_for_pidref(m, &pidref, &array);
8,972✔
3015
                if (n_array < 0)
8,972✔
3016
                        log_warning_errno(n_array, "Failed to get units for process " PID_FMT ", ignoring: %m", si.si_pid);
×
3017
                else if (n_array == 0)
8,972✔
3018
                        log_debug("Got SIGCHLD for process " PID_FMT " we weren't interested in, ignoring.", si.si_pid);
8,972✔
3019
                else {
3020
                        /* We check for an OOM condition, in case we got SIGCHLD before the OOM notification.
3021
                         * We only do this for the cgroup the PID belonged to, which is the f */
3022
                        (void) unit_check_oom(array[0]);
8,972✔
3023

3024
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
3025
                        (void) unit_check_oomd_kill(array[0]);
8,972✔
3026

3027
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
3028
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
3029
                         * iteration. */
3030
                        FOREACH_ARRAY(u, array, n_array)
21,501✔
3031
                                manager_invoke_sigchld_event(m, *u, &si);
12,529✔
3032
                }
3033
        }
3034

3035
        /* And now, we actually reap the zombie. */
3036
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
8,972✔
3037
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
×
3038
                return 0;
14,970✔
3039
        }
3040

3041
        return 0;
3042

3043
turn_off:
5,998✔
3044
        /* All children processed for now, turn off event source */
3045

3046
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
5,998✔
3047
        if (r < 0)
5,998✔
3048
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
×
3049

3050
        return 0;
3051
}
3052

3053
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
137✔
3054
        Job *job;
137✔
3055

3056
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
137✔
3057
                return;
×
3058

3059
        const char *s = unit_status_string(job->unit, NULL);
137✔
3060

3061
        log_info("Activating special unit %s...", s);
137✔
3062

3063
        (void) sd_notifyf(/* unset_environment= */ false,
137✔
3064
                          "STATUS=Activating special unit %s...", s);
3065
        m->status_ready = false;
137✔
3066
}
3067

3068
static void manager_handle_ctrl_alt_del(Manager *m) {
×
3069
        assert(m);
×
3070

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

3074
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
×
3075
                manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
×
3076
        else
3077
                emergency_action(m, m->cad_burst_action, EMERGENCY_ACTION_WARN, NULL, -1,
×
3078
                                 "Ctrl-Alt-Del was pressed more than 7 times within 2s");
3079
}
×
3080

3081
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
5,866✔
3082
        Manager *m = ASSERT_PTR(userdata);
5,866✔
3083
        ssize_t n;
5,866✔
3084
        struct signalfd_siginfo sfsi;
5,866✔
3085
        int r;
5,866✔
3086

3087
        assert(m->signal_fd == fd);
5,866✔
3088

3089
        if (revents != EPOLLIN) {
5,866✔
3090
                log_warning("Got unexpected events from signal file descriptor.");
×
3091
                return 0;
×
3092
        }
3093

3094
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
5,866✔
3095
        if (n < 0) {
5,866✔
3096
                if (ERRNO_IS_TRANSIENT(errno))
×
3097
                        return 0;
3098

3099
                /* We return an error here, which will kill this handler,
3100
                 * to avoid a busy loop on read error. */
3101
                return log_error_errno(errno, "Reading from signal fd failed: %m");
×
3102
        }
3103
        if (n != sizeof(sfsi)) {
5,866✔
3104
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
×
3105
                return 0;
×
3106
        }
3107

3108
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
6,003✔
3109
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
137✔
3110
                            ? LOG_DEBUG : LOG_INFO,
3111
                            &sfsi);
3112

3113
        switch (sfsi.ssi_signo) {
5,866✔
3114

3115
        case SIGCHLD:
5,729✔
3116
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
5,729✔
3117
                if (r < 0)
5,729✔
3118
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
×
3119

3120
                break;
3121

3122
        case SIGTERM:
137✔
3123
                if (MANAGER_IS_SYSTEM(m)) {
137✔
3124
                        /* This is for compatibility with the original sysvinit */
3125
                        m->objective = MANAGER_REEXECUTE;
×
3126
                        break;
×
3127
                }
3128

3129
                _fallthrough_;
137✔
3130
        case SIGINT:
3131
                if (MANAGER_IS_SYSTEM(m))
137✔
3132
                        manager_handle_ctrl_alt_del(m);
×
3133
                else
3134
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
137✔
3135
                break;
3136

3137
        case SIGWINCH:
×
3138
                /* This is a nop on non-init */
3139
                if (MANAGER_IS_SYSTEM(m))
×
3140
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
×
3141

3142
                break;
3143

3144
        case SIGPWR:
×
3145
                /* This is a nop on non-init */
3146
                if (MANAGER_IS_SYSTEM(m))
×
3147
                        manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
×
3148

3149
                break;
3150

3151
        case SIGUSR1:
×
3152
                if (manager_dbus_is_running(m, false)) {
×
3153
                        log_info("Trying to reconnect to bus...");
×
3154

3155
                        (void) bus_init_api(m);
×
3156

3157
                        if (MANAGER_IS_SYSTEM(m))
×
3158
                                (void) bus_init_system(m);
×
3159
                } else
3160
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
×
3161

3162
                break;
3163

3164
        case SIGUSR2: {
×
3165
                _cleanup_free_ char *dump = NULL;
×
3166

3167
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
×
3168
                if (r < 0) {
×
3169
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
×
3170
                        break;
3171
                }
3172

3173
                log_dump(LOG_INFO, dump);
×
3174
                break;
3175
        }
3176

3177
        case SIGHUP:
×
3178
                m->objective = MANAGER_RELOAD;
×
3179
                break;
×
3180

3181
        default: {
×
3182

3183
                if (MANAGER_IS_SYSTEM(m)) {
×
3184
                        /* Starting SIGRTMIN+0 */
3185
                        static const struct {
×
3186
                                const char *target;
3187
                                JobMode mode;
3188
                        } target_table[] = {
3189
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
3190
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
3191
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
3192
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
3193
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
3194
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
3195
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
3196
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
3197
                        };
3198

3199
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
3200
                        static const ManagerObjective objective_table[] = {
×
3201
                                [0] = MANAGER_HALT,
3202
                                [1] = MANAGER_POWEROFF,
3203
                                [2] = MANAGER_REBOOT,
3204
                                [3] = MANAGER_KEXEC,
3205
                                [4] = MANAGER_SOFT_REBOOT,
3206
                        };
3207

3208
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
×
3209
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
×
3210
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
×
3211
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
×
3212
                                break;
3213
                        }
3214

3215
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
×
3216
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
×
3217
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
×
3218
                                break;
×
3219
                        }
3220
                }
3221

3222
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3223

3224
                case 18: {
×
3225
                        bool generic = false;
×
3226

3227
                        if (sfsi.ssi_code != SI_QUEUE)
×
3228
                                generic = true;
3229
                        else {
3230
                                /* Override a few select commands by our own PID1-specific logic */
3231

3232
                                switch (sfsi.ssi_int) {
×
3233

3234
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
×
3235
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
×
3236
                                        break;
3237

3238
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3239
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3240
                                        break;
3241

3242
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3243
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3244
                                        break;
3245

3246
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3247
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3248
                                        break;
3249

3250
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3251
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3252
                                        break;
3253

3254
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3255
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3256

3257
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
×
3258
                                        if (r < 0) {
×
3259
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
×
3260
                                                break;
3261
                                        }
3262

3263
                                        log_dump(LOG_INFO, dump_jobs);
×
3264
                                        break;
3265
                                }
3266

3267
                                default:
3268
                                        generic = true;
3269
                                }
3270
                        }
3271

3272
                        if (generic)
×
3273
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3274

3275
                        break;
3276
                }
3277

3278
                case 20:
×
3279
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
×
3280
                        break;
3281

3282
                case 21:
×
3283
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
×
3284
                        break;
3285

3286
                case 22:
×
3287
                        manager_override_log_level(m, LOG_DEBUG);
×
3288
                        break;
3289

3290
                case 23:
×
3291
                        manager_restore_original_log_level(m);
×
3292
                        break;
3293

3294
                case 24:
×
3295
                        if (MANAGER_IS_USER(m)) {
×
3296
                                m->objective = MANAGER_EXIT;
×
3297
                                return 0;
×
3298
                        }
3299

3300
                        /* This is a nop on init */
3301
                        break;
3302

3303
                case 25:
×
3304
                        m->objective = MANAGER_REEXECUTE;
×
3305
                        break;
×
3306

3307
                case 26:
×
3308
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
3309
                        manager_restore_original_log_target(m);
×
3310
                        break;
3311

3312
                case 27:
×
3313
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3314
                        break;
3315

3316
                case 28:
×
3317
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3318
                        break;
3319

3320
                default:
3321
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
5,866✔
3322
                }
3323
        }}
3324

3325
        return 0;
3326
}
3327

3328
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
3329
        Manager *m = ASSERT_PTR(userdata);
3✔
3330
        Unit *u;
3✔
3331

3332
        log_struct(LOG_DEBUG,
3✔
3333
                   "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
3334
                   LOG_MESSAGE("Time has been changed"));
3335

3336
        /* Restart the watch */
3337
        (void) manager_setup_time_change(m);
3✔
3338

3339
        HASHMAP_FOREACH(u, m->units)
360✔
3340
                if (UNIT_VTABLE(u)->time_change)
354✔
3341
                        UNIT_VTABLE(u)->time_change(u);
3✔
3342

3343
        return 0;
3✔
3344
}
3345

3346
static int manager_dispatch_timezone_change(
31✔
3347
                sd_event_source *source,
3348
                const struct inotify_event *e,
3349
                void *userdata) {
3350

3351
        Manager *m = ASSERT_PTR(userdata);
31✔
3352
        int changed;
31✔
3353
        Unit *u;
31✔
3354

3355
        log_debug("inotify event for /etc/localtime");
31✔
3356

3357
        changed = manager_read_timezone_stat(m);
31✔
3358
        if (changed <= 0)
31✔
3359
                return changed;
31✔
3360

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

3364
        /* Read the new timezone */
3365
        tzset();
13✔
3366

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

3369
        HASHMAP_FOREACH(u, m->units)
2,220✔
3370
                if (UNIT_VTABLE(u)->timezone_change)
2,194✔
3371
                        UNIT_VTABLE(u)->timezone_change(u);
23✔
3372

3373
        return 0;
13✔
3374
}
3375

3376
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
9✔
3377
        Manager *m = ASSERT_PTR(userdata);
9✔
3378

3379
        assert(m->idle_pipe[2] == fd);
9✔
3380

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

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

3392
        return 0;
9✔
3393
}
3394

3395
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
×
3396
        Manager *m = ASSERT_PTR(userdata);
×
3397
        int r;
×
3398

3399
        assert(source);
×
3400

3401
        manager_print_jobs_in_progress(m);
×
3402

3403
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
×
3404
        if (r < 0)
×
3405
                return r;
3406

3407
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
×
3408
}
3409

3410
int manager_loop(Manager *m) {
274✔
3411
        RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
274✔
3412
        int r;
274✔
3413

3414
        assert(m);
274✔
3415
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
274✔
3416

3417
        manager_check_finished(m);
274✔
3418

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

3424
        while (m->objective == MANAGER_OK) {
331,953✔
3425

3426
                (void) watchdog_ping();
331,679✔
3427

3428
                if (!ratelimit_below(&rl)) {
331,679✔
3429
                        /* Yay, something is going seriously wrong, pause a little */
3430
                        log_warning("Looping too fast. Throttling execution a little.");
×
3431
                        sleep(1);
×
3432
                }
3433

3434
                if (manager_dispatch_load_queue(m) > 0)
331,679✔
3435
                        continue;
×
3436

3437
                if (manager_dispatch_gc_job_queue(m) > 0)
331,679✔
3438
                        continue;
17✔
3439

3440
                if (manager_dispatch_gc_unit_queue(m) > 0)
331,662✔
3441
                        continue;
11,533✔
3442

3443
                if (manager_dispatch_cleanup_queue(m) > 0)
320,129✔
3444
                        continue;
5,082✔
3445

3446
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
315,047✔
3447
                        continue;
3,489✔
3448

3449
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
311,558✔
3450
                        continue;
×
3451

3452
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
311,558✔
3453
                        continue;
169✔
3454

3455
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
311,389✔
3456
                        continue;
121✔
3457

3458
                if (manager_dispatch_release_resources_queue(m) > 0)
311,268✔
3459
                        continue;
1,748✔
3460

3461
                if (manager_dispatch_dbus_queue(m) > 0)
309,520✔
3462
                        continue;
8,550✔
3463

3464
                /* Sleep for watchdog runtime wait time */
3465
                r = sd_event_run(m->event, watchdog_runtime_wait());
300,970✔
3466
                if (r < 0)
300,970✔
3467
                        return log_error_errno(r, "Failed to run event loop: %m");
×
3468
        }
3469

3470
        return m->objective;
3471
}
3472

3473
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
320,341✔
3474
        _cleanup_free_ char *n = NULL;
320,341✔
3475
        sd_id128_t invocation_id;
320,341✔
3476
        Unit *u;
320,341✔
3477
        int r;
320,341✔
3478

3479
        assert(m);
320,341✔
3480
        assert(s);
320,341✔
3481
        assert(_u);
320,341✔
3482

3483
        r = unit_name_from_dbus_path(s, &n);
320,341✔
3484
        if (r < 0)
320,341✔
3485
                return r;
3486

3487
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
3488
         * we use it as invocation ID. */
3489
        r = sd_id128_from_string(n, &invocation_id);
320,341✔
3490
        if (r >= 0) {
320,341✔
3491
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
×
3492
                if (u) {
×
3493
                        *_u = u;
×
3494
                        return 0;
×
3495
                }
3496

3497
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
×
3498
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3499
                                         SD_ID128_FORMAT_VAL(invocation_id));
×
3500
        }
3501

3502
        /* If this didn't work, we check if this is a unit name */
3503
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
320,341✔
3504
                _cleanup_free_ char *nn = NULL;
1✔
3505

3506
                nn = cescape(n);
1✔
3507
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
1✔
3508
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3509
        }
3510

3511
        r = manager_load_unit(m, n, NULL, e, &u);
320,340✔
3512
        if (r < 0)
320,340✔
3513
                return r;
3514

3515
        *_u = u;
320,340✔
3516
        return 0;
320,340✔
3517
}
3518

3519
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1,009✔
3520
        const char *p;
1,009✔
3521
        unsigned id;
1,009✔
3522
        Job *j;
1,009✔
3523
        int r;
1,009✔
3524

3525
        assert(m);
1,009✔
3526
        assert(s);
1,009✔
3527
        assert(_j);
1,009✔
3528

3529
        p = startswith(s, "/org/freedesktop/systemd1/job/");
1,009✔
3530
        if (!p)
1,009✔
3531
                return -EINVAL;
1,009✔
3532

3533
        r = safe_atou(p, &id);
1,009✔
3534
        if (r < 0)
1,009✔
3535
                return r;
3536

3537
        j = manager_get_job(m, id);
1,009✔
3538
        if (!j)
1,009✔
3539
                return -ENOENT;
3540

3541
        *_j = j;
1,009✔
3542

3543
        return 0;
1,009✔
3544
}
3545

3546
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
5,512✔
3547

3548
#if HAVE_AUDIT
3549
        _cleanup_free_ char *p = NULL;
5,512✔
3550
        const char *msg;
5,512✔
3551
        int audit_fd, r;
5,512✔
3552

3553
        assert(m);
5,512✔
3554
        assert(u);
5,512✔
3555

3556
        if (!MANAGER_IS_SYSTEM(m))
5,512✔
3557
                return;
3558

3559
        /* Don't generate audit events if the service was already started and we're just deserializing */
3560
        if (MANAGER_IS_RELOADING(m))
4,238✔
3561
                return;
3562

3563
        audit_fd = get_core_audit_fd();
4,238✔
3564
        if (audit_fd < 0)
4,238✔
3565
                return;
3566

3567
        r = unit_name_to_prefix_and_instance(u->id, &p);
3,270✔
3568
        if (r < 0) {
3,270✔
3569
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
×
3570
                return;
×
3571
        }
3572

3573
        msg = strjoina("unit=", p);
16,350✔
3574
        if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
3,270✔
3575
                if (ERRNO_IS_PRIVILEGE(errno)) {
×
3576
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
3577
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
×
3578
                        close_core_audit_fd();
×
3579
                } else
3580
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
3,270✔
3581
        }
3582
#endif
3583
}
3584

3585
void manager_send_unit_plymouth(Manager *m, Unit *u) {
30,241✔
3586
        _cleanup_free_ char *message = NULL;
30,241✔
3587
        int c, r;
30,241✔
3588

3589
        assert(m);
30,241✔
3590
        assert(u);
30,241✔
3591

3592
        if (!MANAGER_IS_SYSTEM(m))
30,241✔
3593
                return;
3594

3595
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
3596
        if (MANAGER_IS_RELOADING(m))
12,911✔
3597
                return;
3598

3599
        if (detect_container() > 0)
12,911✔
3600
                return;
3601

3602
        if (!UNIT_VTABLE(u)->notify_plymouth)
10,859✔
3603
                return;
3604

3605
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
2,049✔
3606
        if (c < 0)
2,049✔
3607
                return (void) log_oom();
×
3608

3609
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
3610
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
2,049✔
3611
        if (r < 0)
2,049✔
3612
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
2,049✔
3613
                               "Failed to communicate with plymouth: %m");
3614
}
3615

3616
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
45,813✔
3617
        assert(m);
45,813✔
3618
        assert(u);
45,813✔
3619

3620
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
3621
         * surrounding service manager. */
3622

3623
        if (MANAGER_IS_RELOADING(m))
45,813✔
3624
                return;
3625

3626
        if (!UNIT_VTABLE(u)->notify_supervisor)
45,813✔
3627
                return;
3628

3629
        if (in_initrd()) /* Only send these once we left the initrd */
5,728✔
3630
                return;
3631

3632
        (void) sd_notifyf(/* unset_environment= */ false,
4,004✔
3633
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
3634
                          u->id);
3635
}
3636

3637
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
568✔
3638
        assert(m);
568✔
3639

3640
        if (MANAGER_IS_USER(m))
568✔
3641
                return USEC_INFINITY;
3642

3643
        if (m->watchdog_overridden[t] != USEC_INFINITY)
292✔
3644
                return m->watchdog_overridden[t];
3645

3646
        return m->watchdog[t];
292✔
3647
}
3648

3649
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
1,096✔
3650

3651
        assert(m);
1,096✔
3652

3653
        if (MANAGER_IS_USER(m))
1,096✔
3654
                return;
3655

3656
        if (m->watchdog[t] == timeout)
536✔
3657
                return;
3658

3659
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
112✔
3660
                if (t == WATCHDOG_RUNTIME)
112✔
3661
                        (void) watchdog_setup(timeout);
×
3662
                else if (t == WATCHDOG_PRETIMEOUT)
112✔
3663
                        (void) watchdog_setup_pretimeout(timeout);
×
3664
        }
3665

3666
        m->watchdog[t] = timeout;
112✔
3667
}
3668

3669
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
×
3670
        usec_t usec;
×
3671

3672
        assert(m);
×
3673

3674
        if (MANAGER_IS_USER(m))
×
3675
                return;
3676

3677
        if (m->watchdog_overridden[t] == timeout)
×
3678
                return;
3679

3680
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
×
3681
        if (t == WATCHDOG_RUNTIME)
×
3682
                (void) watchdog_setup(usec);
×
3683
        else if (t == WATCHDOG_PRETIMEOUT)
×
3684
                (void) watchdog_setup_pretimeout(usec);
×
3685

3686
        m->watchdog_overridden[t] = timeout;
×
3687
}
3688

3689
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
274✔
3690
        _cleanup_free_ char *p = NULL;
274✔
3691
        int r;
274✔
3692

3693
        assert(m);
274✔
3694

3695
        if (MANAGER_IS_USER(m))
274✔
3696
                return 0;
3697

3698
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
134✔
3699
                return 0;
3700

3701
        p = strdup(governor);
×
3702
        if (!p)
×
3703
                return -ENOMEM;
3704

3705
        r = watchdog_setup_pretimeout_governor(governor);
×
3706
        if (r < 0)
×
3707
                return r;
3708

3709
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3710
}
3711

3712
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
×
3713
        _cleanup_free_ char *p = NULL;
×
3714
        int r;
×
3715

3716
        assert(m);
×
3717

3718
        if (MANAGER_IS_USER(m))
×
3719
                return 0;
3720

3721
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3722
                return 0;
3723

3724
        p = strdup(governor);
×
3725
        if (!p)
×
3726
                return -ENOMEM;
3727

3728
        r = watchdog_setup_pretimeout_governor(governor);
×
3729
        if (r < 0)
×
3730
                return r;
3731

3732
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3733
}
3734

3735
int manager_reload(Manager *m) {
24✔
3736
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
24✔
3737
        _cleanup_fdset_free_ FDSet *fds = NULL;
×
3738
        _cleanup_fclose_ FILE *f = NULL;
24✔
3739
        int r;
24✔
3740

3741
        assert(m);
24✔
3742

3743
        r = manager_open_serialization(m, &f);
24✔
3744
        if (r < 0)
24✔
3745
                return log_error_errno(r, "Failed to create serialization file: %m");
×
3746

3747
        fds = fdset_new();
24✔
3748
        if (!fds)
24✔
3749
                return log_oom();
×
3750

3751
        /* We are officially in reload mode from here on. */
3752
        reloading = manager_reloading_start(m);
24✔
3753

3754
        r = manager_serialize(m, f, fds, false);
24✔
3755
        if (r < 0)
24✔
3756
                return r;
3757

3758
        r = finish_serialization_file(f);
24✔
3759
        if (r < 0)
24✔
3760
                return log_error_errno(r, "Failed to finish serialization: %m");
×
3761

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

3765
        bus_manager_send_reloading(m, true);
24✔
3766

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

3771
        manager_clear_jobs_and_units(m);
24✔
3772
        lookup_paths_flush_generator(&m->lookup_paths);
24✔
3773
        exec_shared_runtime_vacuum(m);
24✔
3774
        dynamic_user_vacuum(m, false);
24✔
3775
        m->uid_refs = hashmap_free(m->uid_refs);
24✔
3776
        m->gid_refs = hashmap_free(m->gid_refs);
24✔
3777

3778
        (void) manager_run_environment_generators(m);
24✔
3779
        (void) manager_run_generators(m);
24✔
3780

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

3785
        /* First, enumerate what we can from kernel and suchlike */
3786
        manager_enumerate_perpetual(m);
24✔
3787
        manager_enumerate(m);
24✔
3788

3789
        /* Second, deserialize our stored data */
3790
        r = manager_deserialize(m, f, fds);
24✔
3791
        if (r < 0)
24✔
3792
                log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
×
3793

3794
        /* We don't need the serialization anymore */
3795
        f = safe_fclose(f);
24✔
3796

3797
        /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3798
        (void) manager_setup_notify(m);
24✔
3799
        (void) manager_setup_cgroups_agent(m);
24✔
3800
        (void) manager_setup_user_lookup_fd(m);
24✔
3801
        (void) manager_setup_handoff_timestamp_fd(m);
24✔
3802
        (void) manager_setup_pidref_transport_fd(m);
24✔
3803

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

3809
        /* Third, fire things up! */
3810
        manager_coldplug(m);
24✔
3811

3812
        /* Clean up runtime objects no longer referenced */
3813
        manager_vacuum(m);
24✔
3814

3815
        /* Consider the reload process complete now. */
3816
        assert(m->n_reloading > 0);
24✔
3817
        m->n_reloading--;
24✔
3818

3819
        manager_ready(m);
24✔
3820

3821
        m->send_reloading_done = true;
24✔
3822
        return 0;
24✔
3823
}
3824

3825
void manager_reset_failed(Manager *m) {
×
3826
        Unit *u;
×
3827

3828
        assert(m);
×
3829

3830
        HASHMAP_FOREACH(u, m->units)
×
3831
                unit_reset_failed(u);
×
3832
}
×
3833

3834
bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
×
3835
        Unit *u;
×
3836

3837
        assert(m);
×
3838
        assert(name);
×
3839

3840
        /* Returns true if the unit is inactive or going down */
3841
        u = manager_get_unit(m, name);
×
3842
        if (!u)
×
3843
                return true;
3844

3845
        return unit_inactive_or_pending(u);
×
3846
}
3847

3848
static void log_taint_string(Manager *m) {
12,248✔
3849
        assert(m);
12,248✔
3850

3851
        if (MANAGER_IS_USER(m) || m->taint_logged)
12,248✔
3852
                return;
12,248✔
3853

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

3856
        _cleanup_free_ char *taint = taint_string();
158✔
3857
        if (isempty(taint))
79✔
3858
                return;
79✔
3859

3860
        log_struct(LOG_NOTICE,
×
3861
                   LOG_MESSAGE("System is tainted: %s", taint),
3862
                   "TAINT=%s", taint,
3863
                   "MESSAGE_ID=" SD_MESSAGE_TAINTED_STR);
3864
}
3865

3866
static void manager_notify_finished(Manager *m) {
143✔
3867
        usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
143✔
3868

3869
        if (MANAGER_IS_TEST_RUN(m))
143✔
3870
                return;
3871

3872
        if (MANAGER_IS_SYSTEM(m) && m->soft_reboots_count > 0) {
136✔
3873
                /* The soft-reboot case, where we only report data for the last reboot */
3874
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
×
3875
                total_usec = userspace_usec = usec_sub_unsigned(m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic,
×
3876
                                                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START].monotonic);
3877

3878
                log_struct(LOG_INFO,
×
3879
                           "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3880
                           "USERSPACE_USEC="USEC_FMT, userspace_usec,
3881
                           LOG_MESSAGE("Soft-reboot finished in %s, counter is now at %u.",
3882
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC),
3883
                                       m->soft_reboots_count));
3884
        } else if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
136✔
3885
                char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
×
3886
                        = {};
3887
                char *p = buf;
×
3888
                size_t size = sizeof buf;
×
3889

3890
                /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3891
                 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
3892
                 * negative values. */
3893

3894
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
×
3895
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3896
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
×
3897
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
×
3898

3899
                if (firmware_usec > 0)
×
3900
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
3901
                if (loader_usec > 0)
×
3902
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3903

3904
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
×
3905

3906
                        /* The initrd case on bare-metal */
3907
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3908
                        initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
×
3909

3910
                        log_struct(LOG_INFO,
×
3911
                                   "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3912
                                   "KERNEL_USEC="USEC_FMT, kernel_usec,
3913
                                   "INITRD_USEC="USEC_FMT, initrd_usec,
3914
                                   "USERSPACE_USEC="USEC_FMT, userspace_usec,
3915
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3916
                                               buf,
3917
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3918
                                               FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3919
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3920
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3921
                } else {
3922
                        /* The initrd-less case on bare-metal */
3923

3924
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3925
                        initrd_usec = 0;
×
3926

3927
                        log_struct(LOG_INFO,
×
3928
                                   "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
3929
                                   "KERNEL_USEC="USEC_FMT, kernel_usec,
3930
                                   "USERSPACE_USEC="USEC_FMT, userspace_usec,
3931
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3932
                                               buf,
3933
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3934
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3935
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3936
                }
3937
        } else {
3938
                /* The container and --user case */
3939
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
136✔
3940
                total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
136✔
3941

3942
                log_struct(LOG_INFO,
136✔
3943
                           "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR,
3944
                           "USERSPACE_USEC="USEC_FMT, userspace_usec,
3945
                           LOG_MESSAGE("Startup finished in %s.",
3946
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3947
        }
3948

3949
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
136✔
3950

3951
        log_taint_string(m);
136✔
3952
}
3953

3954
static void manager_send_ready_on_basic_target(Manager *m) {
12,112✔
3955
        int r;
12,112✔
3956

3957
        assert(m);
12,112✔
3958

3959
        /* We send READY=1 on reaching basic.target only when running in --user mode. */
3960
        if (!MANAGER_IS_USER(m) || m->ready_sent)
12,112✔
3961
                return;
3962

3963
        r = sd_notify(/* unset_environment= */ false,
145✔
3964
                      "READY=1\n"
3965
                      "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3966
        if (r < 0)
145✔
3967
                log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
×
3968

3969
        m->ready_sent = true;
145✔
3970
        m->status_ready = false;
145✔
3971
}
3972

3973
static void manager_send_ready_on_idle(Manager *m) {
1,302✔
3974
        int r;
1,302✔
3975

3976
        assert(m);
1,302✔
3977

3978
        /* Skip the notification if nothing changed. */
3979
        if (m->ready_sent && m->status_ready)
1,302✔
3980
                return;
3981

3982
        /* Note that for user managers, we might have already sent READY=1 in manager_send_ready_user_scope().
3983
         * But we still need to flush STATUS=. The second READY=1 will be treated as a noop so it doesn't
3984
         * hurt to send it twice. */
3985
        r = sd_notify(/* unset_environment= */ false,
146✔
3986
                      "READY=1\n"
3987
                      "STATUS=Ready.");
3988
        if (r < 0)
146✔
3989
                log_full_errno(m->ready_sent ? LOG_DEBUG : LOG_WARNING, r,
×
3990
                               "Failed to send readiness notification, ignoring: %m");
3991

3992
        m->ready_sent = m->status_ready = true;
146✔
3993
}
3994

3995
static void manager_check_basic_target(Manager *m) {
30,832✔
3996
        Unit *u;
30,832✔
3997

3998
        assert(m);
30,832✔
3999

4000
        /* Small shortcut */
4001
        if (m->ready_sent && m->taint_logged)
30,832✔
4002
                return;
4003

4004
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
30,832✔
4005
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
30,832✔
4006
                return;
18,720✔
4007

4008
        /* For user managers, send out READY=1 as soon as we reach basic.target */
4009
        manager_send_ready_on_basic_target(m);
12,112✔
4010

4011
        /* Log the taint string as soon as we reach basic.target */
4012
        log_taint_string(m);
12,112✔
4013
}
4014

4015
void manager_check_finished(Manager *m) {
30,983✔
4016
        assert(m);
30,983✔
4017

4018
        if (MANAGER_IS_RELOADING(m))
30,983✔
4019
                return;
4020

4021
        /* Verify that we have entered the event loop already, and not left it again. */
4022
        if (!MANAGER_IS_RUNNING(m))
30,983✔
4023
                return;
4024

4025
        manager_check_basic_target(m);
30,832✔
4026

4027
        if (!hashmap_isempty(m->jobs)) {
30,832✔
4028
                if (m->jobs_in_progress_event_source)
29,530✔
4029
                        /* Ignore any failure, this is only for feedback */
4030
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
11,717✔
4031
                                                        manager_watch_jobs_next_time(m));
4032
                return;
29,530✔
4033
        }
4034

4035
        /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
4036
           kill the hashmap if it is relatively large. */
4037
        if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
1,302✔
4038
                m->jobs = hashmap_free(m->jobs);
306✔
4039

4040
        manager_send_ready_on_idle(m);
1,302✔
4041

4042
        /* Notify Type=idle units that we are done now */
4043
        manager_close_idle_pipe(m);
1,302✔
4044

4045
        if (MANAGER_IS_FINISHED(m))
1,302✔
4046
                return;
4047

4048
        manager_flip_auto_status(m, false, "boot finished");
143✔
4049

4050
        /* Turn off confirm spawn now */
4051
        m->confirm_spawn = NULL;
143✔
4052

4053
        /* No need to update ask password status when we're going non-interactive */
4054
        manager_close_ask_password(m);
143✔
4055

4056
        /* This is no longer the first boot */
4057
        manager_set_first_boot(m, false);
143✔
4058

4059
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
143✔
4060

4061
        manager_notify_finished(m);
143✔
4062

4063
        manager_invalidate_startup_units(m);
143✔
4064
}
4065

4066
void manager_send_reloading(Manager *m) {
123✔
4067
        assert(m);
123✔
4068

4069
        /* Let whoever invoked us know that we are now reloading */
4070
        (void) notify_reloading_full(/* status = */ NULL);
123✔
4071

4072
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
4073
        m->ready_sent = false;
123✔
4074
}
123✔
4075

4076
static bool generator_path_any(char * const *paths) {
885✔
4077

4078
        /* Optimize by skipping the whole process by not creating output directories if no generators are found. */
4079

4080
        STRV_FOREACH(i, paths) {
3,540✔
4081
                if (access(*i, F_OK) >= 0)
3,540✔
4082
                        return true;
4083
                if (errno != ENOENT)
2,655✔
4084
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
2,655✔
4085
        }
4086

4087
        return false;
4088
}
4089

4090
static int manager_run_environment_generators(Manager *m) {
634✔
4091
        _cleanup_strv_free_ char **paths = NULL;
634✔
4092
        int r;
634✔
4093

4094
        assert(m);
634✔
4095

4096
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
634✔
4097
                return 0;
4098

4099
        paths = env_generator_binary_paths(m->runtime_scope);
611✔
4100
        if (!paths)
611✔
4101
                return log_oom();
×
4102

4103
        if (!generator_path_any(paths))
611✔
4104
                return 0;
4105

4106
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
611✔
4107
        void *args[_STDOUT_CONSUME_MAX] = {
611✔
4108
                [STDOUT_GENERATE] = &tmp,
4109
                [STDOUT_COLLECT]  = &tmp,
4110
                [STDOUT_CONSUME]  = &m->transient_environment,
611✔
4111
        };
4112

4113
        WITH_UMASK(0022)
1,222✔
4114
                r = execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC, gather_environment,
611✔
4115
                                        args, NULL, m->transient_environment,
4116
                                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
4117
        return r;
611✔
4118
}
4119

4120
static int build_generator_environment(Manager *m, char ***ret) {
140✔
4121
        _cleanup_strv_free_ char **nl = NULL;
140✔
4122
        Virtualization v;
140✔
4123
        ConfidentialVirtualization cv;
140✔
4124
        int r;
140✔
4125

4126
        assert(m);
140✔
4127
        assert(ret);
140✔
4128

4129
        /* Generators oftentimes want to know some basic facts about the environment they run in, in order to
4130
         * adjust generated units to that. Let's pass down some bits of information that are easy for us to
4131
         * determine (but a bit harder for generator scripts to determine), as environment variables. */
4132

4133
        nl = strv_copy(m->transient_environment);
140✔
4134
        if (!nl)
140✔
4135
                return -ENOMEM;
4136

4137
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
140✔
4138
        if (r < 0)
140✔
4139
                return r;
4140

4141
        if (MANAGER_IS_SYSTEM(m)) {
140✔
4142
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
4143
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
4144
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
4145
                 * same results (hopefully). */
4146
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
4147
                if (r < 0)
×
4148
                        return r;
4149

4150
                if (m->soft_reboots_count > 0) {
×
4151
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
4152
                        if (r < 0)
×
4153
                                return r;
4154
                }
4155

4156
                if (m->first_boot >= 0) {
×
4157
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4158
                        if (r < 0)
×
4159
                                return r;
4160
                }
4161
        }
4162

4163
        v = detect_virtualization();
140✔
4164
        if (v < 0)
140✔
4165
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4166
        else if (v > 0) {
140✔
4167
                const char *s;
140✔
4168

4169
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
700✔
4170
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4171
                             virtualization_to_string(v));
4172

4173
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
140✔
4174
                if (r < 0)
140✔
4175
                        return r;
4176
        }
4177

4178
        cv = detect_confidential_virtualization();
140✔
4179
        if (cv < 0)
140✔
4180
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4181
        else if (cv > 0) {
140✔
4182
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4183
                if (r < 0)
×
4184
                        return r;
4185
        }
4186

4187
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
140✔
4188
        if (r < 0)
140✔
4189
                return r;
4190

4191
        *ret = TAKE_PTR(nl);
140✔
4192
        return 0;
140✔
4193
}
4194

4195
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
140✔
4196
        _cleanup_strv_free_ char **ge = NULL;
140✔
4197
        int r;
140✔
4198

4199
        assert(m);
140✔
4200

4201
        r = build_generator_environment(m, &ge);
140✔
4202
        if (r < 0)
140✔
4203
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4204

4205
        if (remount_ro) {
140✔
4206
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4207
                 * checks whether it is read-only to detect containerized execution environments. We leave
4208
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4209
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4210
                 */
4211
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4212
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4213
                if (r < 0)
×
4214
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4215
        }
4216

4217
        const char *argv[] = {
140✔
4218
                NULL, /* Leave this empty, execute_directory() will fill something in */
4219
                m->lookup_paths.generator,
140✔
4220
                m->lookup_paths.generator_early,
140✔
4221
                m->lookup_paths.generator_late,
140✔
4222
                NULL,
4223
        };
4224

4225
        BLOCK_WITH_UMASK(0022);
280✔
4226
        return execute_directories(
140✔
4227
                        (const char* const*) paths,
4228
                        DEFAULT_TIMEOUT_USEC,
4229
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4230
                        (char**) argv,
4231
                        ge,
4232
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4233
}
4234

4235
static int manager_run_generators(Manager *m) {
634✔
4236
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
634✔
4237
        _cleanup_strv_free_ char **paths = NULL;
634✔
4238
        int r;
634✔
4239

4240
        assert(m);
634✔
4241

4242
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
634✔
4243
                return 0;
4244

4245
        paths = generator_binary_paths(m->runtime_scope);
274✔
4246
        if (!paths)
274✔
4247
                return log_oom();
×
4248

4249
        if (!generator_path_any(paths))
274✔
4250
                return 0;
4251

4252
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
274✔
4253
        if (r < 0) {
274✔
4254
                log_error_errno(r, "Failed to create generator directories: %m");
×
4255
                goto finish;
×
4256
        }
4257

4258
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4259
         * we are the user manager, let's just execute the generators directly. We might not have the
4260
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4261
         */
4262
        if (MANAGER_IS_USER(m)) {
274✔
4263
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
140✔
4264
                goto finish;
140✔
4265
        }
4266

4267
        /* On some systems /tmp/ doesn't exist, and on some other systems we cannot create it at all. Avoid
4268
         * trying to mount a private tmpfs on it as there's no one size fits all. */
4269
        if (is_dir("/tmp", /* follow= */ false) > 0 && !MANAGER_IS_TEST_RUN(m))
134✔
4270
                flags |= FORK_PRIVATE_TMP;
134✔
4271

4272
        r = safe_fork("(sd-gens)", flags, NULL);
134✔
4273
        if (r == 0) {
134✔
4274
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4275
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4276
        }
4277
        if (r < 0) {
134✔
4278
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4279
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4280
                        goto finish;
×
4281
                }
4282

4283
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4284
                 * seccomp or without capability.
4285
                 *
4286
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4287
                 *
4288
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4289
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4290
                 * https://github.com/systemd/systemd/issues/28901.
4291
                 */
4292
                log_debug_errno(r,
×
4293
                                "Failed to fork off sandboxing environment for executing generators. "
4294
                                "Falling back to execute generators without sandboxing: %m");
4295
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4296
        }
4297

4298
finish:
134✔
4299
        lookup_paths_trim_generator(&m->lookup_paths);
274✔
4300
        return r;
4301
}
4302

4303
int manager_transient_environment_add(Manager *m, char **plus) {
274✔
4304
        char **a;
274✔
4305

4306
        assert(m);
274✔
4307

4308
        if (strv_isempty(plus))
274✔
4309
                return 0;
274✔
4310

4311
        a = strv_env_merge(m->transient_environment, plus);
134✔
4312
        if (!a)
134✔
4313
                return log_oom();
×
4314

4315
        sanitize_environment(a);
134✔
4316

4317
        return strv_free_and_replace(m->transient_environment, a);
134✔
4318
}
4319

4320
int manager_client_environment_modify(
138✔
4321
                Manager *m,
4322
                char **minus,
4323
                char **plus) {
4324

4325
        char **a = NULL, **b = NULL, **l;
138✔
4326

4327
        assert(m);
138✔
4328

4329
        if (strv_isempty(minus) && strv_isempty(plus))
138✔
4330
                return 0;
4331

4332
        l = m->client_environment;
138✔
4333

4334
        if (!strv_isempty(minus)) {
138✔
4335
                a = strv_env_delete(l, 1, minus);
1✔
4336
                if (!a)
1✔
4337
                        return -ENOMEM;
4338

4339
                l = a;
4340
        }
4341

4342
        if (!strv_isempty(plus)) {
138✔
4343
                b = strv_env_merge(l, plus);
137✔
4344
                if (!b) {
137✔
4345
                        strv_free(a);
×
4346
                        return -ENOMEM;
×
4347
                }
4348

4349
                l = b;
4350
        }
4351

4352
        if (m->client_environment != l)
138✔
4353
                strv_free(m->client_environment);
138✔
4354

4355
        if (a != l)
138✔
4356
                strv_free(a);
137✔
4357
        if (b != l)
138✔
4358
                strv_free(b);
1✔
4359

4360
        m->client_environment = sanitize_environment(l);
138✔
4361
        return 0;
138✔
4362
}
4363

4364
int manager_get_effective_environment(Manager *m, char ***ret) {
28,758✔
4365
        char **l;
28,758✔
4366

4367
        assert(m);
28,758✔
4368
        assert(ret);
28,758✔
4369

4370
        l = strv_env_merge(m->transient_environment, m->client_environment);
28,758✔
4371
        if (!l)
28,758✔
4372
                return -ENOMEM;
4373

4374
        *ret = l;
28,758✔
4375
        return 0;
28,758✔
4376
}
4377

4378
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
274✔
4379
        _cleanup_free_ char *label = NULL;
274✔
4380
        struct rlimit *rlimit[_RLIMIT_MAX];
274✔
4381
        int r;
274✔
4382

4383
        assert(m);
274✔
4384
        assert(defaults);
274✔
4385

4386
        if (streq_ptr(defaults->smack_process_label, "/"))
274✔
4387
                label = NULL;
4388
        else  {
4389
                const char *l = defaults->smack_process_label;
274✔
4390
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4391
                if (!l)
4392
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4393
#endif
4394
                if (l) {
274✔
4395
                        label = strdup(l);
×
4396
                        if (!label)
×
4397
                                return -ENOMEM;
4398
                } else
4399
                        label = NULL;
4400
        }
4401

4402
        r = rlimit_copy_all(rlimit, defaults->rlimit);
274✔
4403
        if (r < 0)
274✔
4404
                return r;
4405

4406
        m->defaults.std_output = defaults->std_output;
274✔
4407
        m->defaults.std_error = defaults->std_error;
274✔
4408

4409
        m->defaults.restart_usec = defaults->restart_usec;
274✔
4410
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
274✔
4411
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
274✔
4412
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
274✔
4413
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
274✔
4414
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
274✔
4415

4416
        m->defaults.start_limit = defaults->start_limit;
274✔
4417

4418
        m->defaults.cpu_accounting = defaults->cpu_accounting;
274✔
4419
        m->defaults.memory_accounting = defaults->memory_accounting;
274✔
4420
        m->defaults.io_accounting = defaults->io_accounting;
274✔
4421
        m->defaults.blockio_accounting = defaults->blockio_accounting;
274✔
4422
        m->defaults.tasks_accounting = defaults->tasks_accounting;
274✔
4423
        m->defaults.ip_accounting = defaults->ip_accounting;
274✔
4424

4425
        m->defaults.tasks_max = defaults->tasks_max;
274✔
4426
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
274✔
4427

4428
        m->defaults.oom_policy = defaults->oom_policy;
274✔
4429
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
274✔
4430
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
274✔
4431

4432
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
274✔
4433
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
274✔
4434

4435
        free_and_replace(m->defaults.smack_process_label, label);
274✔
4436
        rlimit_free_all(m->defaults.rlimit);
274✔
4437
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
274✔
4438

4439
        return 0;
274✔
4440
}
4441

4442
void manager_recheck_dbus(Manager *m) {
65,818✔
4443
        assert(m);
65,818✔
4444

4445
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4446
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4447
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4448
         * of the system instance, while in the user instance we can assume it's already there. */
4449

4450
        if (MANAGER_IS_RELOADING(m))
65,818✔
4451
                return; /* don't check while we are reloading… */
4452

4453
        if (manager_dbus_is_running(m, false)) {
58,273✔
4454
                (void) bus_init_api(m);
8,592✔
4455

4456
                if (MANAGER_IS_SYSTEM(m))
8,592✔
4457
                        (void) bus_init_system(m);
7,782✔
4458
        } else {
4459
                (void) bus_done_api(m);
49,681✔
4460

4461
                if (MANAGER_IS_SYSTEM(m))
49,681✔
4462
                        (void) bus_done_system(m);
19,933✔
4463
        }
4464
}
4465

4466
static bool manager_journal_is_running(Manager *m) {
31,181✔
4467
        Unit *u;
31,181✔
4468

4469
        assert(m);
31,181✔
4470

4471
        if (MANAGER_IS_TEST_RUN(m))
31,181✔
4472
                return false;
4473

4474
        /* If we are the user manager we can safely assume that the journal is up */
4475
        if (!MANAGER_IS_SYSTEM(m))
31,181✔
4476
                return true;
4477

4478
        /* Check that the socket is not only up, but in RUNNING state */
4479
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
30,556✔
4480
        if (!u)
30,556✔
4481
                return false;
4482
        if (SOCKET(u)->state != SOCKET_RUNNING)
30,556✔
4483
                return false;
4484

4485
        /* Similar, check if the daemon itself is fully up, too */
4486
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
23,138✔
4487
        if (!u)
23,138✔
4488
                return false;
4489
        if (!IN_SET(SERVICE(u)->state, SERVICE_RELOAD, SERVICE_RUNNING))
23,138✔
4490
                return false;
1,805✔
4491

4492
        return true;
4493
}
4494

4495
void disable_printk_ratelimit(void) {
67✔
4496
        /* Disable kernel's printk ratelimit.
4497
         *
4498
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4499
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4500
         * setting takes precedence. */
4501
        int r;
67✔
4502

4503
        r = sysctl_write("kernel/printk_devkmsg", "on");
67✔
4504
        if (r < 0)
67✔
4505
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4506
}
67✔
4507

4508
void manager_recheck_journal(Manager *m) {
65,818✔
4509

4510
        assert(m);
65,818✔
4511

4512
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4513
        if (getpid_cached() != 1)
65,818✔
4514
                return;
4515

4516
        /* Don't check this while we are reloading, things might still change */
4517
        if (MANAGER_IS_RELOADING(m))
34,775✔
4518
                return;
4519

4520
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4521
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4522
         * might trigger an activation ourselves we can't fulfill. */
4523
        log_set_prohibit_ipc(!manager_journal_is_running(m));
27,372✔
4524
        log_open();
27,372✔
4525
}
4526

4527
static ShowStatus manager_get_show_status(Manager *m) {
15,677✔
4528
        assert(m);
15,677✔
4529

4530
        if (MANAGER_IS_USER(m))
15,677✔
4531
                return _SHOW_STATUS_INVALID;
4532

4533
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
15,677✔
4534
                return m->show_status_overridden;
4535

4536
        return m->show_status;
15,677✔
4537
}
4538

4539
bool manager_get_show_status_on(Manager *m) {
15,677✔
4540
        assert(m);
15,677✔
4541

4542
        return show_status_on(manager_get_show_status(m));
15,677✔
4543
}
4544

4545
static void set_show_status_marker(bool b) {
112✔
4546
        if (b)
112✔
4547
                (void) touch("/run/systemd/show-status");
×
4548
        else
4549
                (void) unlink("/run/systemd/show-status");
112✔
4550
}
112✔
4551

4552
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
274✔
4553
        assert(m);
274✔
4554
        assert(reason);
274✔
4555
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
274✔
4556

4557
        if (MANAGER_IS_USER(m))
274✔
4558
                return;
4559

4560
        if (mode == m->show_status)
134✔
4561
                return;
4562

4563
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
112✔
4564
                bool enabled;
112✔
4565

4566
                enabled = show_status_on(mode);
112✔
4567
                log_debug("%s (%s) showing of status (%s).",
224✔
4568
                          enabled ? "Enabling" : "Disabling",
4569
                          strna(show_status_to_string(mode)),
4570
                          reason);
4571

4572
                set_show_status_marker(enabled);
112✔
4573
        }
4574

4575
        m->show_status = mode;
112✔
4576
}
4577

4578
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
×
4579
        assert(m);
×
4580
        assert(mode < _SHOW_STATUS_MAX);
×
4581

4582
        if (MANAGER_IS_USER(m))
×
4583
                return;
4584

4585
        if (mode == m->show_status_overridden)
×
4586
                return;
4587

4588
        m->show_status_overridden = mode;
×
4589

4590
        if (mode == _SHOW_STATUS_INVALID)
×
4591
                mode = m->show_status;
×
4592

4593
        log_debug("%s (%s) showing of status (%s).",
×
4594
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4595
                  strna(show_status_to_string(mode)),
4596
                  reason);
4597

4598
        set_show_status_marker(show_status_on(mode));
×
4599
}
4600

4601
const char* manager_get_confirm_spawn(Manager *m) {
3,820✔
4602
        static int last_errno = 0;
3,820✔
4603
        struct stat st;
3,820✔
4604
        int r;
3,820✔
4605

4606
        assert(m);
3,820✔
4607

4608
        /* Here's the deal: we want to test the validity of the console but don't want
4609
         * PID1 to go through the whole console process which might block. But we also
4610
         * want to warn the user only once if something is wrong with the console so we
4611
         * cannot do the sanity checks after spawning our children. So here we simply do
4612
         * really basic tests to hopefully trap common errors.
4613
         *
4614
         * If the console suddenly disappear at the time our children will really it
4615
         * then they will simply fail to acquire it and a positive answer will be
4616
         * assumed. New children will fall back to /dev/console though.
4617
         *
4618
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4619
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4620
         * reason the configured console is not ready, we fall back to the default
4621
         * console. */
4622

4623
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
3,820✔
4624
                return m->confirm_spawn;
3,820✔
4625

4626
        if (stat(m->confirm_spawn, &st) < 0) {
×
4627
                r = -errno;
×
4628
                goto fail;
×
4629
        }
4630

4631
        if (!S_ISCHR(st.st_mode)) {
×
4632
                r = -ENOTTY;
×
4633
                goto fail;
×
4634
        }
4635

4636
        last_errno = 0;
×
4637
        return m->confirm_spawn;
×
4638

4639
fail:
×
4640
        if (last_errno != r)
×
4641
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4642

4643
        return "/dev/console";
4644
}
4645

4646
void manager_set_first_boot(Manager *m, bool b) {
393✔
4647
        assert(m);
393✔
4648

4649
        if (!MANAGER_IS_SYSTEM(m))
393✔
4650
                return;
4651

4652
        if (m->first_boot != (int) b) {
112✔
4653
                if (b)
112✔
4654
                        (void) touch("/run/systemd/first-boot");
17✔
4655
                else
4656
                        (void) unlink("/run/systemd/first-boot");
95✔
4657
        }
4658

4659
        m->first_boot = b;
112✔
4660
}
4661

4662
void manager_disable_confirm_spawn(void) {
×
4663
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4664
}
×
4665

4666
static bool manager_should_show_status(Manager *m, StatusType type) {
22,359✔
4667
        assert(m);
22,359✔
4668

4669
        if (!MANAGER_IS_SYSTEM(m))
22,359✔
4670
                return false;
4671

4672
        if (m->no_console_output)
15,725✔
4673
                return false;
4674

4675
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
15,661✔
4676
                return false;
4677

4678
        /* If we cannot find out the status properly, just proceed. */
4679
        if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
15,661✔
4680
                return false;
4681

4682
        if (type == STATUS_TYPE_NOTICE && m->show_status != SHOW_STATUS_NO)
15,661✔
4683
                return true;
4684

4685
        return manager_get_show_status_on(m);
15,660✔
4686
}
4687

4688
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
22,359✔
4689
        va_list ap;
22,359✔
4690

4691
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4692

4693
        if (m && !manager_should_show_status(m, type))
22,359✔
4694
                return;
22,358✔
4695

4696
        /* XXX We should totally drop the check for ephemeral here
4697
         * and thus effectively make 'Type=idle' pointless. */
4698
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
1✔
4699
                return;
4700

4701
        va_start(ap, format);
1✔
4702
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
2✔
4703
        va_end(ap);
1✔
4704
}
4705

4706
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
26,076✔
4707
        assert(m);
26,076✔
4708
        assert(path);
26,076✔
4709
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
26,076✔
4710

4711
        if (path_equal(path, "/"))
26,076✔
4712
                path = "";
1,330✔
4713

4714
        return hashmap_get(m->units_needing_mounts_for[t], path);
26,076✔
4715
}
4716

4717
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
144,829✔
4718
        unsigned size;
144,829✔
4719
        int r;
144,829✔
4720

4721
        assert(m);
144,829✔
4722
        assert(u->manager == m);
144,829✔
4723

4724
        size = set_size(m->failed_units);
144,829✔
4725

4726
        if (failed) {
144,829✔
4727
                r = set_ensure_put(&m->failed_units, NULL, u);
193✔
4728
                if (r < 0)
193✔
4729
                        return log_oom();
×
4730
        } else
4731
                (void) set_remove(m->failed_units, u);
144,636✔
4732

4733
        if (set_size(m->failed_units) != size)
144,829✔
4734
                bus_manager_send_change_signal(m);
386✔
4735

4736
        return 0;
4737
}
4738

4739
ManagerState manager_state(Manager *m) {
704,061✔
4740
        Unit *u;
704,061✔
4741

4742
        assert(m);
704,061✔
4743

4744
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4745
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
704,061✔
4746
        if (u && unit_active_or_pending(u))
704,061✔
4747
                return MANAGER_STOPPING;
4748

4749
        /* Did we ever finish booting? If not then we are still starting up */
4750
        if (!MANAGER_IS_FINISHED(m)) {
634,813✔
4751

4752
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
617,202✔
4753
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
617,202✔
4754
                        return MANAGER_INITIALIZING;
552,697✔
4755

4756
                return MANAGER_STARTING;
4757
        }
4758

4759
        if (MANAGER_IS_SYSTEM(m)) {
17,611✔
4760
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4761
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
×
4762
                if (u && unit_active_or_pending(u))
×
4763
                        return MANAGER_MAINTENANCE;
4764

4765
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
×
4766
                if (u && unit_active_or_pending(u))
×
4767
                        return MANAGER_MAINTENANCE;
4768
        }
4769

4770
        /* Are there any failed units? If so, we are in degraded mode */
4771
        if (!set_isempty(m->failed_units))
17,611✔
4772
                return MANAGER_DEGRADED;
1,013✔
4773

4774
        return MANAGER_RUNNING;
4775
}
4776

4777
static void manager_unref_uid_internal(
953✔
4778
                Hashmap *uid_refs,
4779
                uid_t uid,
4780
                bool destroy_now,
4781
                int (*_clean_ipc)(uid_t uid)) {
4782

4783
        uint32_t c, n;
953✔
4784

4785
        assert(uid_is_valid(uid));
953✔
4786
        assert(_clean_ipc);
953✔
4787

4788
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4789
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4790
         *
4791
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4792
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4793
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4794
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4795
         * counter drops to 0 again. */
4796

4797
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
953✔
4798
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
953✔
4799

4800
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
953✔
4801
                return;
4802

4803
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
891✔
4804

4805
        n = c & ~DESTROY_IPC_FLAG;
891✔
4806
        assert(n > 0);
891✔
4807
        n--;
891✔
4808

4809
        if (destroy_now && n == 0) {
891✔
4810
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
351✔
4811

4812
                if (c & DESTROY_IPC_FLAG) {
351✔
4813
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
3✔
4814
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4815
                                  uid);
4816
                        (void) _clean_ipc(uid);
2✔
4817
                }
4818
        } else {
4819
                c = n | (c & DESTROY_IPC_FLAG);
540✔
4820
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
540✔
4821
        }
4822
}
4823

4824
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
476✔
4825
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
476✔
4826
}
476✔
4827

4828
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
477✔
4829
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
477✔
4830
}
477✔
4831

4832
static int manager_ref_uid_internal(
953✔
4833
                Hashmap **uid_refs,
4834
                uid_t uid,
4835
                bool clean_ipc) {
4836

4837
        uint32_t c, n;
953✔
4838
        int r;
953✔
4839

4840
        assert(uid_refs);
953✔
4841
        assert(uid_is_valid(uid));
953✔
4842

4843
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4844
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4845
         * rules. */
4846

4847
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
953✔
4848
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
953✔
4849

4850
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
953✔
4851
                return 0;
4852

4853
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
891✔
4854
        if (r < 0)
891✔
4855
                return r;
4856

4857
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
891✔
4858

4859
        n = c & ~DESTROY_IPC_FLAG;
891✔
4860
        n++;
891✔
4861

4862
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
891✔
4863
                return -EOVERFLOW;
4864

4865
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
891✔
4866

4867
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
891✔
4868
}
4869

4870
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
476✔
4871
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
476✔
4872
}
4873

4874
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
477✔
4875
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
477✔
4876
}
4877

4878
static void manager_vacuum_uid_refs_internal(
1,268✔
4879
                Hashmap *uid_refs,
4880
                int (*_clean_ipc)(uid_t uid)) {
4881

4882
        void *p, *k;
1,268✔
4883

4884
        assert(_clean_ipc);
1,268✔
4885

4886
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
2,862✔
4887
                uint32_t c, n;
326✔
4888
                uid_t uid;
326✔
4889

4890
                uid = PTR_TO_UID(k);
326✔
4891
                c = PTR_TO_UINT32(p);
326✔
4892

4893
                n = c & ~DESTROY_IPC_FLAG;
326✔
4894
                if (n > 0)
326✔
4895
                        continue;
326✔
4896

4897
                if (c & DESTROY_IPC_FLAG) {
×
4898
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4899
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4900
                                  uid);
4901
                        (void) _clean_ipc(uid);
×
4902
                }
4903

4904
                assert_se(hashmap_remove(uid_refs, k) == p);
1,594✔
4905
        }
4906
}
1,268✔
4907

4908
static void manager_vacuum_uid_refs(Manager *m) {
634✔
4909
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
634✔
4910
}
634✔
4911

4912
static void manager_vacuum_gid_refs(Manager *m) {
634✔
4913
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
634✔
4914
}
634✔
4915

4916
static void manager_vacuum(Manager *m) {
634✔
4917
        assert(m);
634✔
4918

4919
        /* Release any dynamic users no longer referenced */
4920
        dynamic_user_vacuum(m, true);
634✔
4921

4922
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4923
        manager_vacuum_uid_refs(m);
634✔
4924
        manager_vacuum_gid_refs(m);
634✔
4925

4926
        /* Release any runtimes no longer referenced */
4927
        exec_shared_runtime_vacuum(m);
634✔
4928
}
634✔
4929

4930
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
253✔
4931
        struct buffer {
253✔
4932
                uid_t uid;
4933
                gid_t gid;
4934
                char unit_name[UNIT_NAME_MAX+1];
4935
        } _packed_ buffer;
4936

4937
        Manager *m = ASSERT_PTR(userdata);
253✔
4938
        ssize_t l;
253✔
4939
        size_t n;
253✔
4940
        Unit *u;
253✔
4941

4942
        assert(source);
253✔
4943

4944
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4945
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4946
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4947
         * reference counter drops to 0. */
4948

4949
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
253✔
4950
        if (l < 0) {
253✔
4951
                if (ERRNO_IS_TRANSIENT(errno))
×
4952
                        return 0;
253✔
4953

4954
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4955
        }
4956

4957
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
253✔
4958
                log_warning("Received too short user lookup message, ignoring.");
×
4959
                return 0;
×
4960
        }
4961

4962
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
253✔
4963
                log_warning("Received too long user lookup message, ignoring.");
×
4964
                return 0;
×
4965
        }
4966

4967
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
253✔
4968
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4969
                return 0;
×
4970
        }
4971

4972
        n = (size_t) l - offsetof(struct buffer, unit_name);
253✔
4973
        if (memchr(buffer.unit_name, 0, n)) {
253✔
4974
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4975
                return 0;
×
4976
        }
4977

4978
        buffer.unit_name[n] = 0;
253✔
4979
        u = manager_get_unit(m, buffer.unit_name);
253✔
4980
        if (!u) {
253✔
4981
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4982
                return 0;
×
4983
        }
4984

4985
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
506✔
4986

4987
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
253✔
4988
        return 0;
4989
}
4990

4991
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,803✔
4992
        Manager *m = ASSERT_PTR(userdata);
3,803✔
4993
        usec_t ts[2] = {};
3,803✔
4994
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
3,803✔
4995
        struct msghdr msghdr = {
3,803✔
4996
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
3,803✔
4997
                .msg_iovlen = 1,
4998
                .msg_control = &control,
4999
                .msg_controllen = sizeof(control),
5000
        };
5001
        ssize_t n;
3,803✔
5002

5003
        assert(source);
3,803✔
5004

5005
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
3,803✔
5006
        if (ERRNO_IS_NEG_TRANSIENT(n))
3,803✔
5007
                return 0; /* Spurious wakeup, try again */
3,803✔
5008
        if (n == -ECHRNG) {
3,803✔
5009
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
5010
                return 0;
×
5011
        }
5012
        if (n == -EXFULL) {
3,803✔
5013
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
5014
                return 0;
×
5015
        }
5016
        if (n < 0)
3,803✔
5017
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
5018

5019
        cmsg_close_all(&msghdr);
3,803✔
5020

5021
        if (n != sizeof(ts)) {
3,803✔
5022
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
5023
                return 0;
×
5024
        }
5025

5026
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
3,803✔
5027
        if (!ucred || !pid_is_valid(ucred->pid)) {
3,803✔
5028
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
5029
                return 0;
×
5030
        }
5031

5032
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
3,803✔
5033

5034
        _cleanup_free_ Unit **units = NULL;
3,803✔
5035
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
3,803✔
5036
        if (n_units < 0) {
3,803✔
5037
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
5038
                return 0;
×
5039
        }
5040
        if (n_units == 0) {
3,803✔
5041
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
5042
                return 0;
×
5043
        }
5044

5045
        dual_timestamp dt = {
3,803✔
5046
                .realtime = ts[0],
3,803✔
5047
                .monotonic = ts[1],
3,803✔
5048
        };
5049

5050
        FOREACH_ARRAY(u, units, n_units) {
11,409✔
5051
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
7,606✔
5052
                        continue;
1✔
5053

5054
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
7,605✔
5055
        }
5056

5057
        return 0;
5058
}
5059

5060
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2✔
5061
        Manager *m = ASSERT_PTR(userdata);
2✔
5062
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
2✔
5063
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
4✔
5064
        struct ucred *ucred = NULL;
2✔
5065
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
2✔
5066
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
2✔
5067
        struct msghdr msghdr = {
2✔
5068
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
2✔
5069
                .msg_iovlen = 1,
5070
                .msg_control = &control,
5071
                .msg_controllen = sizeof(control),
5072
        };
5073
        struct cmsghdr *cmsg;
2✔
5074
        ssize_t n;
2✔
5075
        int r;
2✔
5076

5077
        assert(source);
2✔
5078

5079
        /* Server expects:
5080
         * - Parent PID in ucreds enabled via SO_PASSCRED
5081
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
5082
         * - Child PIDFD in SCM_RIGHTS in message body
5083
         * - Child PID in message IOV
5084
         *
5085
         * SO_PASSPIDFD may not be supported by the kernel so we fall back to using parent PID from ucreds
5086
         * and accept some raciness. */
5087
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
2✔
5088
        if (ERRNO_IS_NEG_TRANSIENT(n))
4✔
5089
                return 0; /* Spurious wakeup, try again */
5090
        if (n == -ECHRNG) {
2✔
5091
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
5092
                return 0;
×
5093
        }
5094
        if (n == -EXFULL) {
2✔
5095
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
5096
                return 0;
×
5097
        }
5098
        if (n < 0)
2✔
5099
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
5100

5101
        if (n != sizeof(child_pid)) {
2✔
5102
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
5103
                return 0;
×
5104
        }
5105

5106
        CMSG_FOREACH(cmsg, &msghdr) {
16✔
5107
                if (cmsg->cmsg_level != SOL_SOCKET)
6✔
5108
                        continue;
×
5109

5110
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
6✔
5111
                        assert(!ucred);
2✔
5112
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
2✔
5113
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
4✔
5114
                        assert(parent_pidfd < 0);
2✔
5115
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
2✔
5116
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
2✔
5117
                        assert(child_pidfd < 0);
2✔
5118
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
2✔
5119
                }
5120
        }
5121

5122
        /* Verify and set parent pidref. */
5123
        if (!ucred || !pid_is_valid(ucred->pid)) {
2✔
5124
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
5125
                return 0;
×
5126
        }
5127

5128
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
5129
        if (parent_pidfd >= 0)
2✔
5130
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
2✔
5131
        else
5132
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
5133
        if (r < 0) {
2✔
5134
                if (r == -ESRCH)
×
5135
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5136
                else
5137
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5138
                return 0;
×
5139
        }
5140

5141
        if (parent_pidref.pid != ucred->pid) {
2✔
5142
                assert(parent_pidref.fd >= 0);
×
5143
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
5144
                            parent_pidref.pid, ucred->pid);
5145
                return 0;
×
5146
        }
5147

5148
        /* Verify and set child pidref. */
5149
        if (!pid_is_valid(child_pid)) {
2✔
5150
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
5151
                return 0;
×
5152
        }
5153

5154
        /* Need to handle kernels without PIDFD support. */
5155
        if (child_pidfd >= 0)
2✔
5156
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
2✔
5157
        else
5158
                r = pidref_set_pid(&child_pidref, child_pid);
×
5159
        if (r < 0) {
2✔
5160
                if (r == -ESRCH)
×
5161
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5162
                else
5163
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5164
                return 0;
×
5165
        }
5166

5167
        if (child_pidref.pid != child_pid) {
2✔
5168
                assert(child_pidref.fd >= 0);
×
5169
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5170
                            child_pidref.pid, child_pid);
5171
                return 0;
×
5172
        }
5173

5174
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
2✔
5175

5176
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5177
         * Then fall back to finding cgroup of the child process. */
5178
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
2✔
5179
        if (!u)
2✔
5180
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5181
        if (!u) {
×
5182
                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);
×
5183
                return 0;
×
5184
        }
5185

5186
        if (!UNIT_VTABLE(u)->notify_pidref) {
2✔
5187
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5188
                return 0;
×
5189
        }
5190

5191
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
2✔
5192

5193
        return 0;
5194
}
5195

5196
void manager_ref_console(Manager *m) {
156✔
5197
        assert(m);
156✔
5198

5199
        m->n_on_console++;
156✔
5200
}
156✔
5201

5202
void manager_unref_console(Manager *m) {
156✔
5203

5204
        assert(m->n_on_console > 0);
156✔
5205
        m->n_on_console--;
156✔
5206

5207
        if (m->n_on_console == 0)
156✔
5208
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
90✔
5209
}
156✔
5210

5211
void manager_override_log_level(Manager *m, int level) {
48✔
5212
        _cleanup_free_ char *s = NULL;
96✔
5213
        assert(m);
48✔
5214

5215
        if (!m->log_level_overridden) {
48✔
5216
                m->original_log_level = log_get_max_level();
17✔
5217
                m->log_level_overridden = true;
17✔
5218
        }
5219

5220
        (void) log_level_to_string_alloc(level, &s);
48✔
5221
        log_info("Setting log level to %s.", strna(s));
48✔
5222

5223
        log_set_max_level(level);
48✔
5224
}
48✔
5225

5226
void manager_restore_original_log_level(Manager *m) {
×
5227
        _cleanup_free_ char *s = NULL;
×
5228
        assert(m);
×
5229

5230
        if (!m->log_level_overridden)
×
5231
                return;
×
5232

5233
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5234
        log_info("Restoring log level to original (%s).", strna(s));
×
5235

5236
        log_set_max_level(m->original_log_level);
×
5237
        m->log_level_overridden = false;
×
5238
}
5239

5240
void manager_override_log_target(Manager *m, LogTarget target) {
16✔
5241
        assert(m);
16✔
5242

5243
        if (!m->log_target_overridden) {
16✔
5244
                m->original_log_target = log_get_target();
11✔
5245
                m->log_target_overridden = true;
11✔
5246
        }
5247

5248
        log_info("Setting log target to %s.", log_target_to_string(target));
16✔
5249
        log_set_target(target);
16✔
5250
}
16✔
5251

5252
void manager_restore_original_log_target(Manager *m) {
×
5253
        assert(m);
×
5254

5255
        if (!m->log_target_overridden)
×
5256
                return;
5257

5258
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5259

5260
        log_set_target(m->original_log_target);
×
5261
        m->log_target_overridden = false;
×
5262
}
5263

5264
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
2,940✔
5265
        if (in_initrd() &&
2,940✔
5266
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
366✔
5267
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5268
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
366✔
5269
        return s;
5270
}
5271

5272
int manager_allocate_idle_pipe(Manager *m) {
10,485✔
5273
        int r;
10,485✔
5274

5275
        assert(m);
10,485✔
5276

5277
        if (m->idle_pipe[0] >= 0) {
10,485✔
5278
                assert(m->idle_pipe[1] >= 0);
8,633✔
5279
                assert(m->idle_pipe[2] >= 0);
8,633✔
5280
                assert(m->idle_pipe[3] >= 0);
8,633✔
5281
                return 0;
5282
        }
5283

5284
        assert(m->idle_pipe[1] < 0);
1,852✔
5285
        assert(m->idle_pipe[2] < 0);
1,852✔
5286
        assert(m->idle_pipe[3] < 0);
1,852✔
5287

5288
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
1,852✔
5289
        if (r < 0)
×
5290
                return r;
5291

5292
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
1,852✔
5293
        if (r < 0) {
×
5294
                safe_close_pair(m->idle_pipe + 0);
×
5295
                return r;
×
5296
        }
5297

5298
        return 1;
5299
}
5300

5301
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,023✔
5302
        assert(defaults);
1,023✔
5303
        assert(scope >= 0);
1,023✔
5304
        assert(scope < _RUNTIME_SCOPE_MAX);
1,023✔
5305

5306
        *defaults = (UnitDefaults) {
2,046✔
5307
                .std_output = EXEC_OUTPUT_JOURNAL,
5308
                .std_error = EXEC_OUTPUT_INHERIT,
5309
                .restart_usec = DEFAULT_RESTART_USEC,
5310
                .timeout_start_usec = manager_default_timeout(scope),
5311
                .timeout_stop_usec = manager_default_timeout(scope),
5312
                .timeout_abort_usec = manager_default_timeout(scope),
5313
                .timeout_abort_set = false,
5314
                .device_timeout_usec = manager_default_timeout(scope),
5315
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5316

5317
                /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
5318
                 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
5319
                .cpu_accounting = cpu_accounting_is_cheap(),
1,023✔
5320
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5321
                .io_accounting = false,
5322
                .blockio_accounting = false,
5323
                .tasks_accounting = true,
5324
                .ip_accounting = false,
5325

5326
                .tasks_max = DEFAULT_TASKS_MAX,
5327
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5328

5329
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5330
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5331

5332
                .oom_policy = OOM_STOP,
5333
                .oom_score_adjust_set = false,
5334
        };
5335
}
1,023✔
5336

5337
void unit_defaults_done(UnitDefaults *defaults) {
1,023✔
5338
        assert(defaults);
1,023✔
5339

5340
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,023✔
5341
        rlimit_free_all(defaults->rlimit);
1,023✔
5342
}
1,023✔
5343

5344
LogTarget manager_get_executor_log_target(Manager *m) {
3,820✔
5345
        assert(m);
3,820✔
5346

5347
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5348
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
3,820✔
5349
                return LOG_TARGET_KMSG;
5350

5351
        return log_get_target();
2,411✔
5352
}
5353

5354
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5355
        [MANAGER_INITIALIZING] = "initializing",
5356
        [MANAGER_STARTING]     = "starting",
5357
        [MANAGER_RUNNING]      = "running",
5358
        [MANAGER_DEGRADED]     = "degraded",
5359
        [MANAGER_MAINTENANCE]  = "maintenance",
5360
        [MANAGER_STOPPING]     = "stopping",
5361
};
5362

5363
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
75✔
5364

5365
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5366
        [MANAGER_OK]          = "ok",
5367
        [MANAGER_EXIT]        = "exit",
5368
        [MANAGER_RELOAD]      = "reload",
5369
        [MANAGER_REEXECUTE]   = "reexecute",
5370
        [MANAGER_REBOOT]      = "reboot",
5371
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5372
        [MANAGER_POWEROFF]    = "poweroff",
5373
        [MANAGER_HALT]        = "halt",
5374
        [MANAGER_KEXEC]       = "kexec",
5375
        [MANAGER_SWITCH_ROOT] = "switch-root",
5376
};
5377

5378
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
213✔
5379

5380
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5381
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5382
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5383
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5384
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5385
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5386
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5387
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5388
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5389
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5390
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5391
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5392
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5393
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5394
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5395
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5396
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5397
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5398
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5399
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5400
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5401
};
5402

5403
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
7,725✔
5404

5405
static const char* const oom_policy_table[_OOM_POLICY_MAX] = {
5406
        [OOM_CONTINUE] = "continue",
5407
        [OOM_STOP]     = "stop",
5408
        [OOM_KILL]     = "kill",
5409
};
5410

5411
DEFINE_STRING_TABLE_LOOKUP(oom_policy, OOMPolicy);
1,109✔
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