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

systemd / systemd / 23927985597

02 Apr 2026 07:45PM UTC coverage: 72.362% (+0.02%) from 72.343%
23927985597

push

github

daandemeyer
ci: Drop base64 encoding in claude review workflow

Doesn't seem to work nearly as good as the previous solution which
just told claude not to escape stuff.

319121 of 441004 relevant lines covered (72.36%)

1167673.48 hits per line

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

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

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

12
#include "sd-bus.h"
13
#include "sd-daemon.h"
14
#include "sd-messages.h"
15
#include "sd-netlink.h"
16
#include "sd-path.h"
17

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

100
/* Make sure clients notifying us don't block */
101
#define MANAGER_SOCKET_RCVBUF_SIZE (8*U64_MB)
102

103
/* Initial delay and the interval for printing status messages about running jobs */
104
#define JOBS_IN_PROGRESS_WAIT_USEC (2*USEC_PER_SEC)
105
#define JOBS_IN_PROGRESS_QUIET_WAIT_USEC (25*USEC_PER_SEC)
106
#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
107
#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
108

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

113
/* How many units and jobs to process of the bus queue before returning to the event loop. */
114
#define MANAGER_BUS_MESSAGE_BUDGET 100U
115

116
#define DEFAULT_TASKS_MAX ((const CGroupTasksMax) { 15U, 100U }) /* 15% */
117

118
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
119
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
120
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
121
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
122
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
123
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
124
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
125
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
126
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
127
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata);
128
static int manager_dispatch_timezone_change(sd_event_source *source, const struct inotify_event *event, void *userdata);
129
static int manager_run_environment_generators(Manager *m);
130
static int manager_run_generators(Manager *m);
131
static void manager_vacuum(Manager *m);
132

133
static usec_t manager_watch_jobs_next_time(Manager *m) {
4,788✔
134
        usec_t timeout;
4,788✔
135

136
        if (MANAGER_IS_USER(m))
4,788✔
137
                /* Let the user manager without a timeout show status quickly, so the system manager can make
138
                 * use of it, if it wants to. */
139
                timeout = JOBS_IN_PROGRESS_WAIT_USEC * 2 / 3;
140
        else if (manager_get_show_status_on(m))
3,996✔
141
                /* When status is on, just use the usual timeout. */
142
                timeout = JOBS_IN_PROGRESS_WAIT_USEC;
143
        else
144
                timeout = JOBS_IN_PROGRESS_QUIET_WAIT_USEC;
3,996✔
145

146
        return usec_add(now(CLOCK_MONOTONIC), timeout);
4,788✔
147
}
148

149
static bool manager_is_confirm_spawn_disabled(Manager *m) {
3,662✔
150
        assert(m);
3,662✔
151

152
        if (!m->confirm_spawn)
3,662✔
153
                return true;
154

155
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
156
}
157

158
static void manager_watch_jobs_in_progress(Manager *m) {
3,662✔
159
        usec_t next;
3,662✔
160
        int r;
3,662✔
161

162
        assert(m);
3,662✔
163

164
        /* We do not want to show the cylon animation if the user
165
         * needs to confirm service executions otherwise confirmation
166
         * messages will be screwed by the cylon animation. */
167
        if (!manager_is_confirm_spawn_disabled(m))
3,662✔
168
                return;
169

170
        if (m->jobs_in_progress_event_source)
3,662✔
171
                return;
172

173
        next = manager_watch_jobs_next_time(m);
826✔
174
        r = sd_event_add_time(
826✔
175
                        m->event,
176
                        &m->jobs_in_progress_event_source,
177
                        CLOCK_MONOTONIC,
178
                        next, 0,
179
                        manager_dispatch_jobs_in_progress, m);
180
        if (r < 0)
826✔
181
                return;
182

183
        (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
826✔
184
}
185

186
static void manager_flip_auto_status(Manager *m, bool enable, const char *reason) {
201✔
187
        assert(m);
201✔
188

189
        if (enable) {
201✔
190
                if (m->show_status == SHOW_STATUS_AUTO)
3✔
191
                        manager_set_show_status(m, SHOW_STATUS_TEMPORARY, reason);
×
192
        } else {
193
                if (m->show_status == SHOW_STATUS_TEMPORARY)
198✔
194
                        manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
×
195
        }
196
}
201✔
197

198
static void manager_print_jobs_in_progress(Manager *m) {
3✔
199
        Job *j;
3✔
200
        unsigned counter = 0, print_nr;
3✔
201
        char cylon[6 + CYLON_BUFFER_EXTRA + 1];
3✔
202
        unsigned cylon_pos;
3✔
203
        uint64_t timeout = 0;
3✔
204

205
        assert(m);
3✔
206
        assert(m->n_running_jobs > 0);
3✔
207

208
        manager_flip_auto_status(m, true, "delay");
3✔
209

210
        print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
3✔
211

212
        HASHMAP_FOREACH(j, m->jobs)
42✔
213
                if (j->state == JOB_RUNNING && counter++ == print_nr)
42✔
214
                        break;
215

216
        /* m->n_running_jobs must be consistent with the contents of m->jobs,
217
         * so the above loop must have succeeded in finding j. */
218
        assert(counter == print_nr + 1);
3✔
219
        assert(j);
3✔
220

221
        cylon_pos = m->jobs_in_progress_iteration % 14;
3✔
222
        if (cylon_pos >= 8)
3✔
223
                cylon_pos = 14 - cylon_pos;
×
224
        draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
3✔
225

226
        m->jobs_in_progress_iteration++;
3✔
227

228
        char job_of_n[STRLEN("( of ) ") + DECIMAL_STR_MAX(unsigned)*2] = "";
3✔
229
        if (m->n_running_jobs > 1)
3✔
230
                xsprintf(job_of_n, "(%u of %u) ", counter, m->n_running_jobs);
3✔
231

232
        (void) job_get_timeout(j, &timeout);
3✔
233

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

241
        const char *time = FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
3✔
242
        const char *limit = timeout > 0 ? FORMAT_TIMESPAN(timeout - j->begin_usec, 1*USEC_PER_SEC) : "no limit";
3✔
243

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

256
                manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
6✔
257
                                      "%sJob %s/%s running (%s / %s)%s%s",
258
                                      job_of_n,
259
                                      ident,
260
                                      job_type_to_string(j->type),
3✔
261
                                      time, limit,
262
                                      status_text ? ": " : "",
263
                                      strempty(status_text));
264
        }
265

266
        (void) sd_notifyf(/* unset_environment= */ false,
3✔
267
                          "STATUS=%sUser job %s/%s running (%s / %s)...",
268
                          job_of_n,
269
                          ident, job_type_to_string(j->type),
3✔
270
                          time, limit);
271
        m->status_ready = false;
3✔
272
}
3✔
273

274
static int have_ask_password(void) {
48✔
275
        _cleanup_closedir_ DIR *dir = NULL;
48✔
276

277
        dir = opendir("/run/systemd/ask-password");
48✔
278
        if (!dir) {
48✔
279
                if (errno == ENOENT)
×
280
                        return false;
281

282
                return -errno;
×
283
        }
284

285
        FOREACH_DIRENT_ALL(de, dir, return -errno) {
144✔
286
                if (!IN_SET(de->d_type, DT_REG, DT_UNKNOWN))
96✔
287
                        continue;
96✔
288

289
                if (startswith(de->d_name, "ask."))
×
290
                        return true;
291
        }
292

293
        return false;
294
}
295

296
static int manager_dispatch_ask_password_fd(sd_event_source *source,
48✔
297
                                            int fd, uint32_t revents, void *userdata) {
298
        Manager *m = ASSERT_PTR(userdata);
48✔
299

300
        (void) flush_fd(fd);
48✔
301

302
        m->have_ask_password = have_ask_password();
48✔
303
        if (m->have_ask_password < 0)
48✔
304
                /* Log error but continue. Negative have_ask_password is treated as unknown status. */
305
                log_warning_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password/, ignoring: %m");
×
306

307
        return 0;
48✔
308
}
309

310
static void manager_close_ask_password(Manager *m) {
962✔
311
        assert(m);
962✔
312

313
        m->ask_password_event_source = sd_event_source_disable_unref(m->ask_password_event_source);
962✔
314
        m->have_ask_password = -EINVAL;
962✔
315
}
962✔
316

317
static int manager_check_ask_password(Manager *m) {
8,030✔
318
        int r;
8,030✔
319

320
        assert(m);
8,030✔
321

322
        /* We only care about passwords prompts when running in system mode (because that's the only time we
323
         * manage a console) */
324
        if (!MANAGER_IS_SYSTEM(m))
8,030✔
325
                return 0;
326

327
        if (!m->ask_password_event_source) {
8,030✔
328
                _cleanup_close_ int inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
92✔
329
                if (inotify_fd < 0)
46✔
330
                        return log_error_errno(errno, "Failed to create inotify object: %m");
×
331

332
                (void) mkdir_label("/run/systemd/ask-password", 0755);
46✔
333
                r = inotify_add_watch_and_warn(inotify_fd, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_DELETE|IN_MOVED_TO|IN_ONLYDIR);
46✔
334
                if (r < 0)
46✔
335
                        return r;
336

337
                _cleanup_(sd_event_source_disable_unrefp) sd_event_source *event_source = NULL;
46✔
338
                r = sd_event_add_io(
46✔
339
                                m->event,
340
                                &event_source,
341
                                inotify_fd,
342
                                EPOLLIN,
343
                                manager_dispatch_ask_password_fd,
344
                                m);
345
                if (r < 0)
46✔
346
                        return log_error_errno(r, "Failed to add event source for /run/systemd/ask-password/: %m");
×
347

348
                r = sd_event_source_set_io_fd_own(event_source, true);
46✔
349
                if (r < 0)
46✔
350
                        return log_error_errno(r, "Failed to pass ownership of /run/systemd/ask-password/ inotify fd to event source: %m");
×
351
                TAKE_FD(inotify_fd);
46✔
352

353
                (void) sd_event_source_set_description(event_source, "manager-ask-password");
46✔
354

355
                m->ask_password_event_source = TAKE_PTR(event_source);
46✔
356

357
                /* Queries might have been added meanwhile... */
358
                (void) manager_dispatch_ask_password_fd(m->ask_password_event_source, sd_event_source_get_io_fd(m->ask_password_event_source), EPOLLIN, m);
46✔
359
        }
360

361
        return m->have_ask_password;
8,030✔
362
}
363

364
static int manager_watch_idle_pipe(Manager *m) {
822✔
365
        int r;
822✔
366

367
        assert(m);
822✔
368

369
        if (m->idle_pipe_event_source)
822✔
370
                return 0;
371

372
        if (m->idle_pipe[2] < 0)
40✔
373
                return 0;
374

375
        r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
40✔
376
        if (r < 0)
40✔
377
                return log_error_errno(r, "Failed to watch idle pipe: %m");
×
378

379
        (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
40✔
380

381
        return 0;
40✔
382
}
383

384
static void manager_close_idle_pipe(Manager *m) {
1,182✔
385
        assert(m);
1,182✔
386

387
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
1,182✔
388

389
        safe_close_pair(m->idle_pipe);
1,182✔
390
        safe_close_pair(m->idle_pipe + 2);
1,182✔
391
}
1,182✔
392

393
static int manager_setup_time_change(Manager *m) {
267✔
394
        int r;
267✔
395

396
        assert(m);
267✔
397

398
        if (MANAGER_IS_TEST_RUN(m))
267✔
399
                return 0;
400

401
        m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
256✔
402

403
        r = event_add_time_change(m->event, &m->time_change_event_source, manager_dispatch_time_change_fd, m);
256✔
404
        if (r < 0)
256✔
405
                return log_error_errno(r, "Failed to create time change event source: %m");
×
406

407
        /* Schedule this slightly earlier than the .timer event sources */
408
        r = sd_event_source_set_priority(m->time_change_event_source, EVENT_PRIORITY_TIME_CHANGE);
256✔
409
        if (r < 0)
256✔
410
                return log_error_errno(r, "Failed to set priority of time change event sources: %m");
×
411

412
        log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
256✔
413

414
        return 0;
415
}
416

417
static int manager_read_timezone_stat(Manager *m) {
312✔
418
        struct stat st;
312✔
419
        bool changed;
312✔
420

421
        assert(m);
312✔
422

423
        /* Read the current stat() data of /etc/localtime so that we detect changes */
424
        if (lstat(etc_localtime(), &st) < 0) {
312✔
425
                log_debug_errno(errno, "Failed to stat /etc/localtime, ignoring: %m");
69✔
426
                changed = m->etc_localtime_accessible;
69✔
427
                m->etc_localtime_accessible = false;
69✔
428
        } else {
429
                usec_t k;
243✔
430

431
                k = timespec_load(&st.st_mtim);
243✔
432
                changed = !m->etc_localtime_accessible || k != m->etc_localtime_mtime;
243✔
433

434
                m->etc_localtime_mtime = k;
243✔
435
                m->etc_localtime_accessible = true;
243✔
436
        }
437

438
        return changed;
312✔
439
}
440

441
static int manager_setup_timezone_change(Manager *m) {
287✔
442
        _cleanup_(sd_event_source_unrefp) sd_event_source *new_event = NULL;
287✔
443
        int r;
287✔
444

445
        assert(m);
287✔
446

447
        if (MANAGER_IS_TEST_RUN(m))
287✔
448
                return 0;
449

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

461
        r = sd_event_add_inotify(m->event, &new_event, etc_localtime(),
276✔
462
                                 IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
463
        if (r == -ENOENT) {
276✔
464
                /* If the file doesn't exist yet, subscribe to /etc instead, and wait until it is created either by
465
                 * O_CREATE or by rename() */
466
                _cleanup_free_ char *localtime_dir = NULL;
47✔
467

468
                int dir_r = path_extract_directory(etc_localtime(), &localtime_dir);
47✔
469
                if (dir_r < 0)
47✔
470
                        return log_error_errno(dir_r, "Failed to extract directory from path '%s': %m", etc_localtime());
×
471

472
                log_debug_errno(r, "%s doesn't exist yet, watching %s instead.", etc_localtime(), localtime_dir);
47✔
473

474
                r = sd_event_add_inotify(m->event, &new_event, localtime_dir,
47✔
475
                                         IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
476
        }
477
        if (r < 0)
276✔
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);
276✔
482
        if (r < 0)
276✔
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);
276✔
486
        m->timezone_change_event_source = TAKE_PTR(new_event);
276✔
487

488
        return 0;
276✔
489
}
490

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

494
        assert(m);
256✔
495

496
        if (!MANAGER_IS_SYSTEM(m) || MANAGER_IS_TEST_RUN(m))
256✔
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))
52✔
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);
52✔
505
        if (fd < 0)
52✔
506
                /* Support systems without virtual console (ENOENT) gracefully */
507
                log_full_errno(fd == -ENOENT ? LOG_DEBUG : LOG_WARNING, fd, "Failed to open %s, ignoring: %m", "/dev/tty0");
30✔
508
        else {
509
                /* Enable that we get SIGWINCH on kbrequest */
510
                if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
22✔
511
                        log_warning_errno(errno, "Failed to enable kbrequest handling, ignoring: %m");
256✔
512
        }
513

514
        return 0;
515
}
516

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

525
        assert(m);
256✔
526

527
        assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
256✔
528

529
        /* We make liberal use of realtime signals here. On Linux we have 29 of them, between
530
         * SIGRTMIN+0 ... SIGRTMIN+29. The glibc has one more (SIGRTMAX is SIGRTMIN+30),
531
         * but musl does not (SIGRTMAX is SIGRTMIN+29). */
532

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

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

553
                        /* ... space for more special targets ... */
554

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

562
                        /* ... space ... */
563

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

571
                        SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
572
                        SIGRTMIN+27, /* systemd: set log target to console */
573
                        SIGRTMIN+28, /* systemd: set log target to kmsg */
574
                        SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg (obsolete) */
575

576
                        /* ... one free signal here SIGRTMIN+30 (glibc only) ... */
577
                        -1);
578
        assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
256✔
579

580
        m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
256✔
581
        if (m->signal_fd < 0)
256✔
582
                return -errno;
×
583

584
        r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
256✔
585
        if (r < 0)
256✔
586
                return r;
587

588
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
256✔
589

590
        /* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
591
         * notify processing can still figure out to which process/service a message belongs, before we reap the
592
         * process. Also, process this before handling cgroup notifications, so that we always collect child exit
593
         * status information before detecting that there's no process in a cgroup. */
594
        r = sd_event_source_set_priority(m->signal_event_source, EVENT_PRIORITY_SIGNALS);
256✔
595
        if (r < 0)
256✔
596
                return r;
597

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

609
        return manager_enable_special_signals(m);
256✔
610
}
611

612
static char** sanitize_environment(char **l) {
1,354✔
613

614
        /* Let's remove some environment variables that we need ourselves to communicate with our clients */
615
        strv_env_unset_many(
1,354✔
616
                        l,
617
                        "CACHE_DIRECTORY",
618
                        "CONFIGURATION_DIRECTORY",
619
                        "CREDENTIALS_DIRECTORY",
620
                        "EXIT_CODE",
621
                        "EXIT_STATUS",
622
                        "INVOCATION_ID",
623
                        "JOURNAL_STREAM",
624
                        "LISTEN_FDNAMES",
625
                        "LISTEN_FDS",
626
                        "LISTEN_PID",
627
                        "LISTEN_PIDFDID",
628
                        "LOGS_DIRECTORY",
629
                        "LOG_NAMESPACE",
630
                        "MAINPID",
631
                        "MANAGERPID",
632
                        "MEMORY_PRESSURE_WATCH",
633
                        "MEMORY_PRESSURE_WRITE",
634
                        "MONITOR_EXIT_CODE",
635
                        "MONITOR_EXIT_STATUS",
636
                        "MONITOR_INVOCATION_ID",
637
                        "MONITOR_SERVICE_RESULT",
638
                        "MONITOR_UNIT",
639
                        "NOTIFY_SOCKET",
640
                        "PIDFILE",
641
                        "REMOTE_ADDR",
642
                        "REMOTE_PORT",
643
                        "RUNTIME_DIRECTORY",
644
                        "SERVICE_RESULT",
645
                        "STATE_DIRECTORY",
646
                        "SYSTEMD_EXEC_PID",
647
                        "TRIGGER_PATH",
648
                        "TRIGGER_TIMER_MONOTONIC_USEC",
649
                        "TRIGGER_TIMER_REALTIME_USEC",
650
                        "TRIGGER_UNIT",
651
                        "WATCHDOG_PID",
652
                        "WATCHDOG_USEC");
653

654
        /* Let's order the environment alphabetically, just to make it pretty */
655
        return strv_sort(l);
1,354✔
656
}
657

658
int manager_default_environment(Manager *m) {
1,075✔
659
        assert(m);
1,075✔
660

661
        m->transient_environment = strv_free(m->transient_environment);
1,075✔
662

663
        if (MANAGER_IS_SYSTEM(m)) {
1,075✔
664
                /* The system manager always starts with a clean environment for its children. It does not
665
                 * import the kernel's or the parents' exported variables.
666
                 *
667
                 * The initial passed environment is untouched to keep /proc/self/environ valid; it is used
668
                 * for tagging the init process inside containers. */
669
                char *path = strjoin("PATH=", default_PATH());
638✔
670
                if (!path)
638✔
671
                        return log_oom();
×
672

673
                if (strv_consume(&m->transient_environment, path) < 0)
638✔
674
                        return log_oom();
×
675

676
                /* Import locale variables LC_*= from configuration */
677
                (void) locale_setup(&m->transient_environment);
638✔
678
        } else {
679
                /* The user manager passes its own environment along to its children, except for $PATH and
680
                 * session envs. */
681

682
                m->transient_environment = strv_copy(environ);
437✔
683
                if (!m->transient_environment)
437✔
684
                        return log_oom();
×
685

686
                char *path = strjoin("PATH=", default_user_PATH());
437✔
687
                if (!path)
437✔
688
                        return log_oom();
×
689

690
                if (strv_env_replace_consume(&m->transient_environment, path) < 0)
437✔
691
                        return log_oom();
×
692

693
                /* Envvars set for our 'manager' class session are private and should not be propagated
694
                 * to children. Also it's likely that the graphical session will set these on their own. */
695
                strv_env_unset_many(m->transient_environment,
437✔
696
                                    "XDG_SESSION_ID",
697
                                    "XDG_SESSION_CLASS",
698
                                    "XDG_SESSION_TYPE",
699
                                    "XDG_SESSION_DESKTOP",
700
                                    "XDG_SESSION_EXTRA_DEVICE_ACCESS",
701
                                    "XDG_SEAT",
702
                                    "XDG_VTNR");
703
        }
704

705
        sanitize_environment(m->transient_environment);
1,075✔
706
        return 0;
1,075✔
707
}
708

709
static int manager_setup_prefix(Manager *m) {
764✔
710
        struct table_entry {
764✔
711
                uint64_t type;
712
                const char *suffix;
713
        };
714

715
        static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
764✔
716
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_SYSTEM_RUNTIME,       NULL },
717
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
718
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_SYSTEM_STATE_CACHE,   NULL },
719
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_SYSTEM_STATE_LOGS,    NULL },
720
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
721
        };
722

723
        static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
764✔
724
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_USER_RUNTIME,       NULL  },
725
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_USER_STATE_PRIVATE, NULL  },
726
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_USER_STATE_CACHE,   NULL  },
727
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_USER_STATE_PRIVATE, "log" },
728
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL  },
729
        };
730

731
        assert(m);
764✔
732

733
        const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
764✔
734
        int r;
764✔
735

736
        for (ExecDirectoryType i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
4,584✔
737
                r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
3,820✔
738
                if (r < 0)
3,820✔
739
                        return log_warning_errno(r, "Failed to lookup %s path: %m",
×
740
                                                 exec_directory_type_to_string(i));
741
        }
742

743
        return 0;
744
}
745

746
static void manager_free_unit_name_maps(Manager *m) {
830✔
747
        m->unit_id_map = hashmap_free(m->unit_id_map);
830✔
748
        m->unit_name_map = hashmap_free(m->unit_name_map);
830✔
749
        m->unit_path_cache = set_free(m->unit_path_cache);
830✔
750
        m->unit_cache_timestamp_hash = 0;
830✔
751
}
830✔
752

753
static int manager_setup_run_queue(Manager *m) {
764✔
754
        int r;
764✔
755

756
        assert(m);
764✔
757
        assert(!m->run_queue_event_source);
764✔
758

759
        r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
764✔
760
        if (r < 0)
764✔
761
                return r;
762

763
        r = sd_event_source_set_priority(m->run_queue_event_source, EVENT_PRIORITY_RUN_QUEUE);
764✔
764
        if (r < 0)
764✔
765
                return r;
766

767
        r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
764✔
768
        if (r < 0)
764✔
769
                return r;
770

771
        (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
764✔
772

773
        return 0;
764✔
774
}
775

776
static int manager_setup_sigchld_event_source(Manager *m) {
256✔
777
        int r;
256✔
778

779
        assert(m);
256✔
780
        assert(!m->sigchld_event_source);
256✔
781

782
        r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
256✔
783
        if (r < 0)
256✔
784
                return r;
785

786
        r = sd_event_source_set_priority(m->sigchld_event_source, EVENT_PRIORITY_SIGCHLD);
256✔
787
        if (r < 0)
256✔
788
                return r;
789

790
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
256✔
791
        if (r < 0)
256✔
792
                return r;
793

794
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
256✔
795

796
        return 0;
256✔
797
}
798

799
int manager_setup_memory_pressure_event_source(Manager *m) {
568✔
800
        int r;
568✔
801

802
        assert(m);
568✔
803

804
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
568✔
805

806
        r = sd_event_add_memory_pressure(m->event, &m->memory_pressure_event_source, NULL, NULL);
568✔
807
        if (r < 0)
568✔
808
                log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) || ERRNO_IS_PRIVILEGE(r) || (r == -EHOSTDOWN) ? LOG_DEBUG : LOG_NOTICE, r,
×
809
                               "Failed to establish memory pressure event source, ignoring: %m");
810
        else if (m->defaults.memory_pressure_threshold_usec != USEC_INFINITY) {
568✔
811

812
                /* If there's a default memory pressure threshold set, also apply it to the service manager itself */
813
                r = sd_event_source_set_memory_pressure_period(
568✔
814
                                m->memory_pressure_event_source,
815
                                m->defaults.memory_pressure_threshold_usec,
816
                                MEMORY_PRESSURE_DEFAULT_WINDOW_USEC);
817
                if (r < 0)
568✔
818
                        log_warning_errno(r, "Failed to adjust memory pressure threshold, ignoring: %m");
11✔
819
        }
820

821
        return 0;
568✔
822
}
823

824
static int manager_find_credentials_dirs(Manager *m) {
764✔
825
        const char *e;
764✔
826
        int r;
764✔
827

828
        assert(m);
764✔
829

830
        r = get_credentials_dir(&e);
764✔
831
        if (r < 0) {
764✔
832
                if (r != -ENXIO)
712✔
833
                        log_debug_errno(r, "Failed to determine credentials directory, ignoring: %m");
×
834
        } else {
835
                m->received_credentials_directory = strdup(e);
52✔
836
                if (!m->received_credentials_directory)
52✔
837
                        return -ENOMEM;
764✔
838
        }
839

840
        r = get_encrypted_credentials_dir(&e);
764✔
841
        if (r < 0) {
764✔
842
                if (r != -ENXIO)
764✔
843
                        log_debug_errno(r, "Failed to determine encrypted credentials directory, ignoring: %m");
×
844
        } else {
845
                m->received_encrypted_credentials_directory = strdup(e);
×
846
                if (!m->received_encrypted_credentials_directory)
×
847
                        return -ENOMEM;
×
848
        }
849

850
        return 0;
851
}
852

853
void manager_set_switching_root(Manager *m, bool switching_root) {
1,018✔
854
        assert(m);
1,018✔
855

856
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
1,018✔
857
}
1,018✔
858

859
double manager_get_progress(Manager *m) {
21✔
860
        assert(m);
21✔
861

862
        if (MANAGER_IS_FINISHED(m) || m->n_installed_jobs == 0)
41✔
863
                return 1.0;
864

865
        return 1.0 - ((double) hashmap_size(m->jobs) / (double) m->n_installed_jobs);
20✔
866
}
867

868
static int compare_job_priority(const void *a, const void *b) {
322,777✔
869
        const Job *x = a, *y = b;
322,777✔
870

871
        return unit_compare_priority(x->unit, y->unit);
322,777✔
872
}
873

874
usec_t manager_default_timeout(RuntimeScope scope) {
5,068✔
875
        return scope == RUNTIME_SCOPE_SYSTEM ? DEFAULT_TIMEOUT_USEC : DEFAULT_USER_TIMEOUT_USEC;
5,068✔
876
}
877

878
int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags, Manager **ret) {
764✔
879
        _cleanup_(manager_freep) Manager *m = NULL;
764✔
880
        int r;
764✔
881

882
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
764✔
883
        assert(ret);
764✔
884

885
        m = new(Manager, 1);
764✔
886
        if (!m)
764✔
887
                return -ENOMEM;
888

889
        *m = (Manager) {
764✔
890
                .runtime_scope = runtime_scope,
891
                .objective = _MANAGER_OBJECTIVE_INVALID,
892
                .previous_objective = _MANAGER_OBJECTIVE_INVALID,
893

894
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
895

896
                .original_log_level = -1,
897
                .original_log_target = _LOG_TARGET_INVALID,
898

899
                .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
900
                .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
901
                .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
902
                .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
903

904
                .show_status_overridden = _SHOW_STATUS_INVALID,
905

906
                .notify_fd = -EBADF,
907
                .signal_fd = -EBADF,
908
                .user_lookup_fds = EBADF_PAIR,
909
                .handoff_timestamp_fds = EBADF_PAIR,
910
                .pidref_transport_fds = EBADF_PAIR,
911
                .private_listen_fd = -EBADF,
912
                .dev_autofs_fd = -EBADF,
913
                .cgroup_inotify_fd = -EBADF,
914
                .pin_cgroupfs_fd = -EBADF,
915
                .idle_pipe = { -EBADF, -EBADF, -EBADF, -EBADF},
916

917
                 /* start as id #1, so that we can leave #0 around as "null-like" value */
918
                .current_job_id = 1,
919

920
                .have_ask_password = -EINVAL, /* we don't know */
921
                .first_boot = -1,
922
                .test_run_flags = test_run_flags,
923

924
                .dump_ratelimit = (const RateLimit) { .interval = 10 * USEC_PER_MINUTE, .burst = 10 },
925

926
                .executor_fd = -EBADF,
927
        };
928

929
        unit_defaults_init(&m->defaults, runtime_scope);
764✔
930

931
#if ENABLE_EFI
932
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
764✔
933
                boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
25✔
934
                                m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
25✔
935
                                m->timestamps + MANAGER_TIMESTAMP_LOADER);
25✔
936
#endif
937

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

941
        r = manager_default_environment(m);
764✔
942
        if (r < 0)
764✔
943
                return r;
944

945
        r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
764✔
946
        if (r < 0)
764✔
947
                return r;
948

949
        r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
764✔
950
        if (r < 0)
764✔
951
                return r;
952

953
        r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
764✔
954
        if (r < 0)
764✔
955
                return r;
956

957
        r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
764✔
958
        if (r < 0)
764✔
959
                return r;
960

961
        r = manager_setup_prefix(m);
764✔
962
        if (r < 0)
764✔
963
                return r;
964

965
        r = manager_find_credentials_dirs(m);
764✔
966
        if (r < 0)
764✔
967
                return r;
968

969
        r = sd_event_default(&m->event);
764✔
970
        if (r < 0)
764✔
971
                return r;
972

973
        r = manager_setup_run_queue(m);
764✔
974
        if (r < 0)
764✔
975
                return r;
976

977
        if (FLAGS_SET(test_run_flags, MANAGER_TEST_RUN_MINIMAL)) {
764✔
978
                m->cgroup_root = strdup("");
508✔
979
                if (!m->cgroup_root)
508✔
980
                        return -ENOMEM;
981
        } else {
982
                r = manager_setup_signals(m);
256✔
983
                if (r < 0)
256✔
984
                        return r;
985

986
                r = manager_setup_cgroup(m);
256✔
987
                if (r < 0)
256✔
988
                        return r;
989

990
                r = manager_setup_time_change(m);
256✔
991
                if (r < 0)
256✔
992
                        return r;
993

994
                r = manager_read_timezone_stat(m);
256✔
995
                if (r < 0)
256✔
996
                        return r;
997

998
                (void) manager_setup_timezone_change(m);
256✔
999

1000
                r = manager_setup_sigchld_event_source(m);
256✔
1001
                if (r < 0)
256✔
1002
                        return r;
1003

1004
                r = manager_setup_memory_pressure_event_source(m);
256✔
1005
                if (r < 0)
256✔
1006
                        return r;
1007

1008
#if HAVE_LIBBPF
1009
                if (MANAGER_IS_SYSTEM(m) && bpf_restrict_fs_supported(/* initialize= */ true)) {
256✔
1010
                        r = bpf_restrict_fs_setup(m);
11✔
1011
                        if (r < 0)
11✔
1012
                                log_warning_errno(r, "Failed to setup LSM BPF, ignoring: %m");
×
1013
                }
1014
#endif
1015
        }
1016

1017
        if (test_run_flags == 0) {
764✔
1018
                if (MANAGER_IS_SYSTEM(m))
245✔
1019
                        r = mkdir_label("/run/systemd/units", 0755);
52✔
1020
                else {
1021
                        _cleanup_free_ char *units_path = NULL;
193✔
1022
                        r = xdg_user_runtime_dir("/systemd/units", &units_path);
193✔
1023
                        if (r < 0)
193✔
1024
                                return r;
×
1025

1026
                        r = mkdir_label(units_path, 0755);
193✔
1027
                }
1028
                if (r < 0 && r != -EEXIST)
245✔
1029
                        return r;
1030
        }
1031

1032
        if (!FLAGS_SET(test_run_flags, MANAGER_TEST_DONT_OPEN_EXECUTOR)) {
764✔
1033
                m->executor_fd = pin_callout_binary(SYSTEMD_EXECUTOR_BINARY_PATH, &m->executor_path);
264✔
1034
                if (m->executor_fd < 0)
264✔
1035
                        return log_debug_errno(m->executor_fd, "Failed to pin executor binary: %m");
×
1036

1037
                log_debug("Using systemd-executor binary from '%s'.", m->executor_path);
264✔
1038
        }
1039

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

1043
        *ret = TAKE_PTR(m);
764✔
1044

1045
        return 0;
764✔
1046
}
1047

1048
static int manager_setup_notify(Manager *m) {
828✔
1049
        int r;
828✔
1050

1051
        if (MANAGER_IS_TEST_RUN(m))
828✔
1052
                return 0;
1053

1054
        if (m->notify_fd < 0) {
311✔
1055
                _cleanup_close_ int fd = -EBADF;
225✔
1056
                union sockaddr_union sa;
225✔
1057
                socklen_t sa_len;
225✔
1058

1059
                /* First free all secondary fields */
1060
                m->notify_socket = mfree(m->notify_socket);
225✔
1061
                m->notify_event_source = sd_event_source_disable_unref(m->notify_event_source);
225✔
1062

1063
                fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
225✔
1064
                if (fd < 0)
225✔
1065
                        return log_error_errno(errno, "Failed to allocate notification socket: %m");
×
1066

1067
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
225✔
1068

1069
                m->notify_socket = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/notify");
225✔
1070
                if (!m->notify_socket)
225✔
1071
                        return log_oom();
×
1072

1073
                r = sockaddr_un_set_path(&sa.un, m->notify_socket);
225✔
1074
                if (r < 0)
225✔
1075
                        return log_error_errno(r, "Notify socket '%s' not valid for AF_UNIX socket address, refusing.",
×
1076
                                               m->notify_socket);
1077
                sa_len = r;
225✔
1078

1079
                (void) sockaddr_un_unlink(&sa.un);
225✔
1080

1081
                r = mac_selinux_bind(fd, &sa.sa, sa_len);
225✔
1082
                if (r < 0)
225✔
1083
                        return log_error_errno(r, "Failed to bind notify fd to '%s': %m", m->notify_socket);
×
1084

1085
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
225✔
1086
                if (r < 0)
225✔
1087
                        return log_error_errno(r, "Failed to enable SO_PASSCRED for notify socket: %m");
×
1088

1089
                // TODO: enforce SO_PASSPIDFD when our baseline of the kernel version is bumped to >= 6.5.
1090
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
225✔
1091
                if (r < 0 && r != -ENOPROTOOPT)
225✔
1092
                        log_warning_errno(r, "Failed to enable SO_PASSPIDFD for notify socket, ignoring: %m");
×
1093

1094
                m->notify_fd = TAKE_FD(fd);
225✔
1095

1096
                log_debug("Using notification socket %s", m->notify_socket);
225✔
1097
        }
1098

1099
        if (!m->notify_event_source) {
311✔
1100
                r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
311✔
1101
                if (r < 0)
311✔
1102
                        return log_error_errno(r, "Failed to allocate notify event source: %m");
×
1103

1104
                /* Process notification messages a bit earlier than SIGCHLD, so that we can still identify to which
1105
                 * service an exit message belongs. */
1106
                r = sd_event_source_set_priority(m->notify_event_source, EVENT_PRIORITY_NOTIFY);
311✔
1107
                if (r < 0)
311✔
1108
                        return log_error_errno(r, "Failed to set priority of notify event source: %m");
×
1109

1110
                (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
311✔
1111
        }
1112

1113
        return 0;
1114
}
1115

1116
static int manager_setup_user_lookup_fd(Manager *m) {
828✔
1117
        int r;
828✔
1118

1119
        assert(m);
828✔
1120

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

1140
        if (m->user_lookup_fds[0] < 0) {
828✔
1141

1142
                /* Free all secondary fields */
1143
                safe_close_pair(m->user_lookup_fds);
742✔
1144
                m->user_lookup_event_source = sd_event_source_disable_unref(m->user_lookup_event_source);
742✔
1145

1146
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
742✔
1147
                        return log_error_errno(errno, "Failed to allocate user lookup socket: %m");
×
1148

1149
                r = setsockopt_int(m->user_lookup_fds[0], SOL_SOCKET, SO_PASSRIGHTS, false);
742✔
1150
                if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
742✔
1151
                        log_warning_errno(r, "Failed to turn off SO_PASSRIGHTS on user lookup socket, ignoring: %m");
×
1152

1153
                (void) fd_increase_rxbuf(m->user_lookup_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
742✔
1154
        }
1155

1156
        if (!m->user_lookup_event_source) {
828✔
1157
                r = sd_event_add_io(m->event, &m->user_lookup_event_source, m->user_lookup_fds[0], EPOLLIN, manager_dispatch_user_lookup_fd, m);
828✔
1158
                if (r < 0)
828✔
1159
                        return log_error_errno(r, "Failed to allocate user lookup event source: %m");
×
1160

1161
                /* Process even earlier than the notify event source, so that we always know first about valid UID/GID
1162
                 * resolutions */
1163
                r = sd_event_source_set_priority(m->user_lookup_event_source, EVENT_PRIORITY_USER_LOOKUP);
828✔
1164
                if (r < 0)
828✔
1165
                        return log_error_errno(r, "Failed to set priority of user lookup event source: %m");
×
1166

1167
                (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
828✔
1168
        }
1169

1170
        return 0;
1171
}
1172

1173
static int manager_setup_handoff_timestamp_fd(Manager *m) {
828✔
1174
        int r;
828✔
1175

1176
        assert(m);
828✔
1177

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

1181
        if (m->handoff_timestamp_fds[0] < 0) {
828✔
1182
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
742✔
1183
                safe_close_pair(m->handoff_timestamp_fds);
742✔
1184

1185
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->handoff_timestamp_fds) < 0)
742✔
1186
                        return log_error_errno(errno, "Failed to allocate handoff timestamp socket: %m");
×
1187

1188
                /* Make sure children never have to block */
1189
                (void) fd_increase_rxbuf(m->handoff_timestamp_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
742✔
1190

1191
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSCRED, true);
742✔
1192
                if (r < 0)
742✔
1193
                        return log_error_errno(r, "Failed to enable SO_PASSCRED on handoff timestamp socket: %m");
×
1194

1195
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSRIGHTS, false);
742✔
1196
                if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
742✔
1197
                        log_warning_errno(r, "Failed to turn off SO_PASSRIGHTS on handoff timestamp socket, ignoring: %m");
×
1198

1199
                /* Mark the receiving socket as O_NONBLOCK (but leave sending side as-is) */
1200
                r = fd_nonblock(m->handoff_timestamp_fds[0], true);
742✔
1201
                if (r < 0)
742✔
1202
                        return log_error_errno(r, "Failed to make handoff timestamp socket O_NONBLOCK: %m");
×
1203
        }
1204

1205
        if (!m->handoff_timestamp_event_source) {
828✔
1206
                r = sd_event_add_io(m->event, &m->handoff_timestamp_event_source, m->handoff_timestamp_fds[0], EPOLLIN, manager_dispatch_handoff_timestamp_fd, m);
828✔
1207
                if (r < 0)
828✔
1208
                        return log_error_errno(r, "Failed to allocate handoff timestamp event source: %m");
×
1209

1210
                r = sd_event_source_set_priority(m->handoff_timestamp_event_source, EVENT_PRIORITY_HANDOFF_TIMESTAMP);
828✔
1211
                if (r < 0)
828✔
1212
                        return log_error_errno(r, "Failed to set priority of handoff timestamp event source: %m");
×
1213

1214
                (void) sd_event_source_set_description(m->handoff_timestamp_event_source, "handoff-timestamp");
828✔
1215
        }
1216

1217
        return 0;
1218
}
1219

1220
static int manager_setup_pidref_transport_fd(Manager *m) {
828✔
1221
        int r;
828✔
1222

1223
        assert(m);
828✔
1224

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

1228
        if (m->pidref_transport_fds[0] < 0) {
828✔
1229
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
762✔
1230
                safe_close_pair(m->pidref_transport_fds);
762✔
1231

1232
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->pidref_transport_fds) < 0)
762✔
1233
                        return log_error_errno(errno, "Failed to allocate pidref socket: %m");
×
1234

1235
                /* Make sure children never have to block */
1236
                (void) fd_increase_rxbuf(m->pidref_transport_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
762✔
1237

1238
                r = setsockopt_int(m->pidref_transport_fds[0], SOL_SOCKET, SO_PASSCRED, true);
762✔
1239
                if (r < 0)
762✔
1240
                        return log_error_errno(r, "Failed to enable SO_PASSCRED for pidref socket: %m");
×
1241

1242
                r = setsockopt_int(m->pidref_transport_fds[0], SOL_SOCKET, SO_PASSPIDFD, true);
762✔
1243
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
762✔
1244
                        log_debug_errno(r, "SO_PASSPIDFD is not supported for pidref socket, ignoring.");
×
1245
                else if (r < 0)
762✔
1246
                        log_warning_errno(r, "Failed to enable SO_PASSPIDFD for pidref socket, ignoring: %m");
×
1247

1248
                /* Mark the receiving socket as O_NONBLOCK (but leave sending side as-is) */
1249
                r = fd_nonblock(m->pidref_transport_fds[0], true);
762✔
1250
                if (r < 0)
762✔
1251
                        return log_error_errno(r, "Failed to make pidref socket O_NONBLOCK: %m");
×
1252
        }
1253

1254
        if (!m->pidref_event_source) {
828✔
1255
                r = sd_event_add_io(m->event, &m->pidref_event_source, m->pidref_transport_fds[0], EPOLLIN, manager_dispatch_pidref_transport_fd, m);
762✔
1256
                if (r < 0)
762✔
1257
                        return log_error_errno(r, "Failed to allocate pidref event source: %m");
×
1258

1259
                r = sd_event_source_set_priority(m->pidref_event_source, EVENT_PRIORITY_PIDREF);
762✔
1260
                if (r < 0)
762✔
1261
                        return log_error_errno(r, "Failed to set priority of pidref event source: %m");
×
1262

1263
                (void) sd_event_source_set_description(m->pidref_event_source, "pidref");
762✔
1264
        }
1265

1266
        return 0;
1267
}
1268

1269
static unsigned manager_dispatch_cleanup_queue(Manager *m) {
219,665✔
1270
        Unit *u;
219,665✔
1271
        unsigned n = 0;
219,665✔
1272

1273
        assert(m);
219,665✔
1274

1275
        while ((u = m->cleanup_queue)) {
267,717✔
1276
                assert(u->in_cleanup_queue);
48,052✔
1277

1278
                unit_free(u);
48,052✔
1279
                n++;
48,052✔
1280
        }
1281

1282
        return n;
219,665✔
1283
}
1284

1285
static unsigned manager_dispatch_release_resources_queue(Manager *m) {
202,426✔
1286
        unsigned n = 0;
202,426✔
1287
        Unit *u;
202,426✔
1288

1289
        assert(m);
202,426✔
1290

1291
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
203,810✔
1292
                assert(u->in_release_resources_queue);
1,384✔
1293
                u->in_release_resources_queue = false;
1,384✔
1294

1295
                n++;
1,384✔
1296

1297
                unit_release_resources(u);
1,384✔
1298
        }
1299

1300
        return n;
202,426✔
1301
}
1302

1303
enum {
1304
        GC_OFFSET_IN_PATH,  /* This one is on the path we were traveling */
1305
        GC_OFFSET_UNSURE,   /* No clue */
1306
        GC_OFFSET_GOOD,     /* We still need this unit */
1307
        GC_OFFSET_BAD,      /* We don't need this unit anymore */
1308
        _GC_OFFSET_MAX
1309
};
1310

1311
static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
86,269✔
1312
        Unit *other;
86,269✔
1313

1314
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
86,269✔
1315

1316
        /* Recursively mark referenced units as GOOD as well */
1317
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
582,748✔
1318
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
313,650✔
1319
                        unit_gc_mark_good(other, gc_marker);
1,286✔
1320
}
86,269✔
1321

1322
static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
151,730✔
1323
        Unit *other;
151,730✔
1324
        bool is_bad;
151,730✔
1325

1326
        assert(u);
151,730✔
1327

1328
        if (IN_SET(u->gc_marker - gc_marker,
151,730✔
1329
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1330
                return;
66,747✔
1331

1332
        if (u->in_cleanup_queue)
134,320✔
1333
                goto bad;
×
1334

1335
        if (!unit_may_gc(u))
134,320✔
1336
                goto good;
62,930✔
1337

1338
        u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
71,390✔
1339

1340
        is_bad = true;
71,390✔
1341

1342
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
150,461✔
1343
                unit_gc_sweep(other, gc_marker);
26,774✔
1344

1345
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
26,774✔
1346
                        goto good;
22,053✔
1347

1348
                if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
4,721✔
1349
                        is_bad = false;
3,740✔
1350
        }
1351

1352
        LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
49,749✔
1353
                unit_gc_sweep(ref->source, gc_marker);
412✔
1354

1355
                if (ref->source->gc_marker == gc_marker + GC_OFFSET_GOOD)
412✔
1356
                        goto good;
×
1357

1358
                if (ref->source->gc_marker != gc_marker + GC_OFFSET_BAD)
412✔
1359
                        is_bad = false;
411✔
1360
        }
1361

1362
        if (is_bad)
49,337✔
1363
                goto bad;
47,671✔
1364

1365
        /* We were unable to find anything out about this entry, so
1366
         * let's investigate it later */
1367
        u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
1,666✔
1368
        unit_add_to_gc_queue(u);
1,666✔
1369
        return;
1370

1371
bad:
47,671✔
1372
        /* We definitely know that this one is not useful anymore, so
1373
         * let's mark it for deletion */
1374
        u->gc_marker = gc_marker + GC_OFFSET_BAD;
47,671✔
1375
        unit_add_to_cleanup_queue(u);
47,671✔
1376
        return;
1377

1378
good:
84,983✔
1379
        unit_gc_mark_good(u, gc_marker);
84,983✔
1380
}
1381

1382
static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
239,249✔
1383
        unsigned n = 0, gc_marker;
239,249✔
1384

1385
        assert(m);
239,249✔
1386

1387
        /* log_debug("Running GC..."); */
1388

1389
        m->gc_marker += _GC_OFFSET_MAX;
239,249✔
1390
        if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
239,249✔
1391
                m->gc_marker = 1;
×
1392

1393
        gc_marker = m->gc_marker;
239,249✔
1394

1395
        Unit *u;
239,249✔
1396
        while ((u = m->gc_unit_queue)) {
363,793✔
1397
                assert(u->in_gc_queue);
124,544✔
1398

1399
                unit_gc_sweep(u, gc_marker);
124,544✔
1400

1401
                LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
124,544✔
1402
                u->in_gc_queue = false;
124,544✔
1403

1404
                n++;
124,544✔
1405

1406
                if (IN_SET(u->gc_marker - gc_marker,
124,544✔
1407
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1408
                        if (u->id)
48,051✔
1409
                                log_unit_debug(u, "Collecting.");
48,051✔
1410
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
48,051✔
1411
                        unit_add_to_cleanup_queue(u);
48,051✔
1412
                }
1413
        }
1414

1415
        return n;
239,249✔
1416
}
1417

1418
static unsigned manager_dispatch_gc_job_queue(Manager *m) {
239,261✔
1419
        unsigned n = 0;
239,261✔
1420
        Job *j;
239,261✔
1421

1422
        assert(m);
239,261✔
1423

1424
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
239,275✔
1425
                assert(j->in_gc_queue);
14✔
1426
                j->in_gc_queue = false;
14✔
1427

1428
                n++;
14✔
1429

1430
                if (!job_may_gc(j))
14✔
1431
                        continue;
14✔
1432

1433
                log_unit_debug(j->unit, "Collecting job.");
×
1434
                (void) job_finish_and_invalidate(j, JOB_COLLECTED, false, false);
×
1435
        }
1436

1437
        return n;
239,261✔
1438
}
1439

1440
static int manager_ratelimit_requeue(sd_event_source *s, uint64_t usec, void *userdata) {
×
1441
        Unit *u = userdata;
×
1442

1443
        assert(u);
×
1444
        assert(s == u->auto_start_stop_event_source);
×
1445

1446
        u->auto_start_stop_event_source = sd_event_source_unref(u->auto_start_stop_event_source);
×
1447

1448
        /* Re-queue to all queues, if the rate limit hit we might have been throttled on any of them. */
1449
        unit_submit_to_stop_when_unneeded_queue(u);
×
1450
        unit_submit_to_start_when_upheld_queue(u);
×
1451
        unit_submit_to_stop_when_bound_queue(u);
×
1452

1453
        return 0;
×
1454
}
1455

1456
static int manager_ratelimit_check_and_queue(Unit *u) {
18✔
1457
        int r;
18✔
1458

1459
        assert(u);
18✔
1460

1461
        if (ratelimit_below(&u->auto_start_stop_ratelimit))
18✔
1462
                return 1;
1463

1464
        /* Already queued, no need to requeue */
1465
        if (u->auto_start_stop_event_source)
×
1466
                return 0;
1467

1468
        r = sd_event_add_time(
×
1469
                        u->manager->event,
×
1470
                        &u->auto_start_stop_event_source,
1471
                        CLOCK_MONOTONIC,
1472
                        ratelimit_end(&u->auto_start_stop_ratelimit),
×
1473
                        0,
1474
                        manager_ratelimit_requeue,
1475
                        u);
1476
        if (r < 0)
×
1477
                return log_unit_error_errno(u, r, "Failed to queue timer on event loop: %m");
×
1478

1479
        return 0;
1480
}
1481

1482
static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
202,693✔
1483
        unsigned n = 0;
202,693✔
1484
        Unit *u;
202,693✔
1485
        int r;
202,693✔
1486

1487
        assert(m);
202,693✔
1488

1489
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
203,059✔
1490
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
366✔
1491

1492
                assert(u->in_stop_when_unneeded_queue);
366✔
1493
                u->in_stop_when_unneeded_queue = false;
366✔
1494

1495
                n++;
366✔
1496

1497
                if (!unit_is_unneeded(u))
366✔
1498
                        continue;
351✔
1499

1500
                log_unit_debug(u, "Unit is not needed anymore.");
15✔
1501

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

1505
                r = manager_ratelimit_check_and_queue(u);
15✔
1506
                if (r <= 0) {
15✔
1507
                        log_unit_warning(u,
×
1508
                                         "Unit not needed anymore, but not stopping since we tried this too often recently.%s",
1509
                                         r == 0 ? " Will retry later." : "");
1510
                        continue;
×
1511
                }
1512

1513
                /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1514
                r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, /* ret= */ NULL);
15✔
1515
                if (r < 0)
15✔
1516
                        log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
×
1517
        }
1518

1519
        return n;
202,693✔
1520
}
1521

1522
static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
202,849✔
1523
        unsigned n = 0;
202,849✔
1524
        Unit *u;
202,849✔
1525
        int r;
202,849✔
1526

1527
        assert(m);
202,849✔
1528

1529
        while ((u = LIST_POP(start_when_upheld_queue, m->start_when_upheld_queue))) {
202,849✔
1530
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1531
                Unit *culprit = NULL;
×
1532

1533
                assert(u->in_start_when_upheld_queue);
×
1534
                u->in_start_when_upheld_queue = false;
×
1535

1536
                n++;
×
1537

1538
                if (!unit_is_upheld_by_active(u, &culprit))
×
1539
                        continue;
×
1540

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

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

1546
                r = manager_ratelimit_check_and_queue(u);
×
1547
                if (r <= 0) {
×
1548
                        log_unit_warning(u,
×
1549
                                         "Unit needs to be started because active unit %s upholds it, but not starting since we tried this too often recently.%s",
1550
                                         culprit->id,
1551
                                         r == 0 ? " Will retry later." : "");
1552
                        continue;
×
1553
                }
1554

1555
                r = manager_add_job(u->manager, JOB_START, u, JOB_FAIL, &error, /* ret= */ NULL);
×
1556
                if (r < 0)
×
1557
                        log_unit_warning_errno(u, r, "Failed to enqueue start job, ignoring: %s", bus_error_message(&error, r));
×
1558
        }
1559

1560
        return n;
202,849✔
1561
}
1562

1563
static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
202,849✔
1564
        unsigned n = 0;
202,849✔
1565
        Unit *u;
202,849✔
1566
        int r;
202,849✔
1567

1568
        assert(m);
202,849✔
1569

1570
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
203,124✔
1571
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
275✔
1572
                Unit *culprit = NULL;
275✔
1573

1574
                assert(u->in_stop_when_bound_queue);
275✔
1575
                u->in_stop_when_bound_queue = false;
275✔
1576

1577
                n++;
275✔
1578

1579
                if (!unit_is_bound_by_inactive(u, &culprit))
275✔
1580
                        continue;
272✔
1581

1582
                log_unit_debug(u, "Unit is stopped because bound to inactive unit %s.", culprit->id);
3✔
1583

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

1587
                r = manager_ratelimit_check_and_queue(u);
3✔
1588
                if (r <= 0) {
3✔
1589
                        log_unit_warning(u,
×
1590
                                         "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",
1591
                                         culprit->id,
1592
                                         r == 0 ? " Will retry later." : "");
1593
                        continue;
×
1594
                }
1595

1596
                r = manager_add_job(u->manager, JOB_STOP, u, JOB_REPLACE, &error, /* ret= */ NULL);
3✔
1597
                if (r < 0)
3✔
1598
                        log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
×
1599
        }
1600

1601
        return n;
202,849✔
1602
}
1603

1604
static unsigned manager_dispatch_stop_notify_queue(Manager *m) {
201,207✔
1605
        unsigned n = 0;
201,207✔
1606

1607
        assert(m);
201,207✔
1608

1609
        if (m->may_dispatch_stop_notify_queue < 0)
201,207✔
1610
                m->may_dispatch_stop_notify_queue = hashmap_isempty(m->jobs);
3,305✔
1611

1612
        if (!m->may_dispatch_stop_notify_queue)
201,207✔
1613
                return 0;
1614

1615
        m->may_dispatch_stop_notify_queue = false;
9,107✔
1616

1617
        LIST_FOREACH(stop_notify_queue, u, m->stop_notify_queue) {
9,111✔
1618
                assert(u->in_stop_notify_queue);
4✔
1619

1620
                assert(UNIT_VTABLE(u)->stop_notify);
4✔
1621
                if (UNIT_VTABLE(u)->stop_notify(u)) {
4✔
1622
                        assert(!u->in_stop_notify_queue);
×
1623
                        n++;
×
1624
                }
1625
        }
1626

1627
        return n;
1628
}
1629

1630
static void manager_clear_jobs_and_units(Manager *m) {
830✔
1631
        Unit *u;
830✔
1632

1633
        assert(m);
830✔
1634

1635
        while ((u = hashmap_first(m->units)))
58,711✔
1636
                unit_free(u);
57,881✔
1637

1638
        manager_dispatch_cleanup_queue(m);
830✔
1639

1640
        assert(!m->load_queue);
830✔
1641
        assert(prioq_isempty(m->run_queue));
830✔
1642
        assert(!m->dbus_unit_queue);
830✔
1643
        assert(!m->dbus_job_queue);
830✔
1644
        assert(!m->cleanup_queue);
830✔
1645
        assert(!m->gc_unit_queue);
830✔
1646
        assert(!m->gc_job_queue);
830✔
1647
        assert(!m->cgroup_realize_queue);
830✔
1648
        assert(!m->cgroup_empty_queue);
830✔
1649
        assert(!m->cgroup_oom_queue);
830✔
1650
        assert(!m->target_deps_queue);
830✔
1651
        assert(!m->stop_when_unneeded_queue);
830✔
1652
        assert(!m->start_when_upheld_queue);
830✔
1653
        assert(!m->stop_when_bound_queue);
830✔
1654
        assert(!m->release_resources_queue);
830✔
1655

1656
        assert(hashmap_isempty(m->jobs));
830✔
1657
        assert(hashmap_isempty(m->units));
830✔
1658
        assert(hashmap_isempty(m->units_by_invocation_id));
830✔
1659

1660
        m->n_on_console = 0;
830✔
1661
        m->n_running_jobs = 0;
830✔
1662
        m->n_installed_jobs = 0;
830✔
1663
        m->n_failed_jobs = 0;
830✔
1664

1665
        m->transactions_with_cycle = set_free(m->transactions_with_cycle);
830✔
1666
}
830✔
1667

1668
Manager* manager_free(Manager *m) {
764✔
1669
        if (!m)
764✔
1670
                return NULL;
1671

1672
        manager_clear_jobs_and_units(m);
764✔
1673

1674
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
9,168✔
1675
                if (unit_vtable[c]->shutdown)
8,404✔
1676
                        unit_vtable[c]->shutdown(m);
3,056✔
1677

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

1681
        lookup_paths_flush_generator(&m->lookup_paths);
764✔
1682

1683
        bus_done(m);
764✔
1684
        manager_varlink_done(m);
764✔
1685

1686
        exec_shared_runtime_vacuum(m);
764✔
1687
        hashmap_free(m->exec_shared_runtime_by_id);
764✔
1688

1689
        dynamic_user_vacuum(m, false);
764✔
1690
        hashmap_free(m->dynamic_users);
764✔
1691

1692
        hashmap_free(m->units);
764✔
1693
        hashmap_free(m->units_by_invocation_id);
764✔
1694
        hashmap_free(m->jobs);
764✔
1695
        hashmap_free(m->watch_pids);
764✔
1696
        hashmap_free(m->watch_pids_more);
764✔
1697
        hashmap_free(m->watch_bus);
764✔
1698

1699
        prioq_free(m->run_queue);
764✔
1700

1701
        set_free(m->startup_units);
764✔
1702
        set_free(m->failed_units);
764✔
1703

1704
        sd_event_source_unref(m->signal_event_source);
764✔
1705
        sd_event_source_unref(m->sigchld_event_source);
764✔
1706
        sd_event_source_unref(m->notify_event_source);
764✔
1707
        sd_event_source_unref(m->time_change_event_source);
764✔
1708
        sd_event_source_unref(m->timezone_change_event_source);
764✔
1709
        sd_event_source_unref(m->jobs_in_progress_event_source);
764✔
1710
        sd_event_source_unref(m->run_queue_event_source);
764✔
1711
        sd_event_source_unref(m->user_lookup_event_source);
764✔
1712
        sd_event_source_unref(m->handoff_timestamp_event_source);
764✔
1713
        sd_event_source_unref(m->pidref_event_source);
764✔
1714
        sd_event_source_unref(m->memory_pressure_event_source);
764✔
1715

1716
        safe_close(m->signal_fd);
764✔
1717
        safe_close(m->notify_fd);
764✔
1718
        safe_close_pair(m->user_lookup_fds);
764✔
1719
        safe_close_pair(m->handoff_timestamp_fds);
764✔
1720
        safe_close_pair(m->pidref_transport_fds);
764✔
1721

1722
        manager_close_ask_password(m);
764✔
1723

1724
        manager_close_idle_pipe(m);
764✔
1725

1726
        sd_event_unref(m->event);
764✔
1727

1728
        free(m->notify_socket);
764✔
1729

1730
        lookup_paths_done(&m->lookup_paths);
764✔
1731
        strv_free(m->transient_environment);
764✔
1732
        strv_free(m->client_environment);
764✔
1733

1734
        hashmap_free(m->cgroup_unit);
764✔
1735
        manager_free_unit_name_maps(m);
764✔
1736

1737
        free(m->switch_root);
764✔
1738
        free(m->switch_root_init);
764✔
1739

1740
        sd_bus_track_unref(m->subscribed);
764✔
1741
        strv_free(m->subscribed_as_strv);
764✔
1742

1743
        unit_defaults_done(&m->defaults);
764✔
1744

1745
        FOREACH_ARRAY(map, m->units_needing_mounts_for, _UNIT_MOUNT_DEPENDENCY_TYPE_MAX) {
2,292✔
1746
                assert(hashmap_isempty(*map));
1,528✔
1747
                hashmap_free(*map);
1,528✔
1748
        }
1749

1750
        hashmap_free(m->uid_refs);
764✔
1751
        hashmap_free(m->gid_refs);
764✔
1752

1753
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
4,584✔
1754
                free(*i);
3,820✔
1755

1756
        free(m->received_credentials_directory);
764✔
1757
        free(m->received_encrypted_credentials_directory);
764✔
1758

1759
        free(m->watchdog_pretimeout_governor);
764✔
1760
        free(m->watchdog_pretimeout_governor_overridden);
764✔
1761

1762
        sd_netlink_unref(m->nfnl);
764✔
1763

1764
#if BPF_FRAMEWORK
1765
        bpf_restrict_fs_destroy(m->restrict_fs);
764✔
1766
#endif
1767

1768
        safe_close(m->executor_fd);
764✔
1769
        free(m->executor_path);
764✔
1770

1771
        return mfree(m);
764✔
1772
}
1773

1774
static void manager_enumerate_perpetual(Manager *m) {
828✔
1775
        assert(m);
828✔
1776

1777
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
828✔
1778
                return;
1779

1780
        /* Let's ask every type to load all units from disk/kernel that it might know */
1781
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,864✔
1782
                if (!unit_type_supported(c)) {
3,542✔
1783
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
504✔
1784
                        continue;
504✔
1785
                }
1786

1787
                if (unit_vtable[c]->enumerate_perpetual)
3,038✔
1788
                        unit_vtable[c]->enumerate_perpetual(m);
966✔
1789
        }
1790
}
1791

1792
static void manager_enumerate(Manager *m) {
828✔
1793
        assert(m);
828✔
1794

1795
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
828✔
1796
                return;
1797

1798
        /* Let's ask every type to load all units from disk/kernel that it might know */
1799
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,864✔
1800
                if (!unit_type_supported(c)) {
3,542✔
1801
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
504✔
1802
                        continue;
504✔
1803
                }
1804

1805
                if (unit_vtable[c]->enumerate)
3,038✔
1806
                        unit_vtable[c]->enumerate(m);
630✔
1807
        }
1808

1809
        manager_dispatch_load_queue(m);
322✔
1810
}
1811

1812
static void manager_coldplug(Manager *m) {
828✔
1813
        Unit *u;
828✔
1814
        char *k;
828✔
1815
        int r;
828✔
1816

1817
        assert(m);
828✔
1818

1819
        log_debug("Invoking unit coldplug() handlers%s", glyph(GLYPH_ELLIPSIS));
1,210✔
1820

1821
        /* Let's place the units back into their deserialized state */
1822
        HASHMAP_FOREACH_KEY(u, k, m->units) {
54,047✔
1823

1824
                /* ignore aliases */
1825
                if (u->id != k)
52,391✔
1826
                        continue;
1,288✔
1827

1828
                r = unit_coldplug(u);
51,103✔
1829
                if (r < 0)
51,103✔
1830
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
53,219✔
1831
        }
1832
}
828✔
1833

1834
static void manager_catchup(Manager *m) {
828✔
1835
        Unit *u;
828✔
1836
        char *k;
828✔
1837

1838
        assert(m);
828✔
1839

1840
        log_debug("Invoking unit catchup() handlers%s", glyph(GLYPH_ELLIPSIS));
1,210✔
1841

1842
        /* Let's catch up on any state changes that happened while we were reloading/reexecing */
1843
        HASHMAP_FOREACH_KEY(u, k, m->units) {
53,219✔
1844

1845
                /* ignore aliases */
1846
                if (u->id != k)
52,391✔
1847
                        continue;
1,288✔
1848

1849
                unit_catchup(u);
51,103✔
1850
        }
1851
}
828✔
1852

1853
static void manager_distribute_fds(Manager *m, FDSet *fds) {
762✔
1854
        Unit *u;
762✔
1855

1856
        assert(m);
762✔
1857

1858
        HASHMAP_FOREACH(u, m->units) {
8,466✔
1859

1860
                if (fdset_isempty(fds))
7,940✔
1861
                        break;
1862

1863
                if (!UNIT_VTABLE(u)->distribute_fds)
7,704✔
1864
                        continue;
6,853✔
1865

1866
                UNIT_VTABLE(u)->distribute_fds(u, fds);
851✔
1867
        }
1868
}
762✔
1869

1870
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
85,995✔
1871
        Unit *u;
85,995✔
1872

1873
        assert(m);
85,995✔
1874

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

1879
        if (MANAGER_IS_TEST_RUN(m))
85,995✔
1880
                return false;
1881

1882
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
85,069✔
1883
        if (!u)
85,069✔
1884
                return false;
1885
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
144,566✔
1886
                return false;
1887

1888
        u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
10,635✔
1889
        if (!u)
10,635✔
1890
                return false;
1891
        if (!IN_SET(deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state,
21,270✔
1892
                    SERVICE_RUNNING,
1893
                    SERVICE_REFRESH_EXTENSIONS,
1894
                    SERVICE_REFRESH_CREDENTIALS,
1895
                    SERVICE_RELOAD,
1896
                    SERVICE_RELOAD_SIGNAL,
1897
                    SERVICE_RELOAD_NOTIFY,
1898
                    SERVICE_RELOAD_POST,
1899
                    SERVICE_MOUNTING))
1900
                return false;
398✔
1901

1902
        return true;
1903
}
1904

1905
static void manager_setup_bus(Manager *m) {
762✔
1906
        assert(m);
762✔
1907

1908
        if (MANAGER_IS_TEST_RUN(m))
762✔
1909
                return;
1910

1911
        /* Let's set up our private bus connection now, unconditionally */
1912
        (void) bus_init_private(m);
245✔
1913

1914
        /* If we are in --user mode also connect to the system bus now */
1915
        if (MANAGER_IS_USER(m))
245✔
1916
                (void) bus_init_system(m);
193✔
1917

1918
        /* Let's connect to the bus now, but only if the unit is supposed to be up */
1919
        if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
245✔
1920
                (void) bus_init_api(m);
17✔
1921

1922
                if (MANAGER_IS_SYSTEM(m))
17✔
1923
                        (void) bus_init_system(m);
16✔
1924
        }
1925
}
1926

1927
static void manager_preset_all(Manager *m) {
762✔
1928
        int r;
762✔
1929

1930
        assert(m);
762✔
1931

1932
        if (m->first_boot <= 0)
762✔
1933
                return;
744✔
1934

1935
        if (!MANAGER_IS_SYSTEM(m))
18✔
1936
                return;
1937

1938
        if (MANAGER_IS_TEST_RUN(m))
18✔
1939
                return;
1940

1941
        /* If this is the first boot, and we are in the host system, then preset everything */
1942
        UnitFilePresetMode mode =
18✔
1943
                ENABLE_FIRST_BOOT_FULL_PRESET ? UNIT_FILE_PRESET_FULL : UNIT_FILE_PRESET_ENABLE_ONLY;
1944
        InstallChange *changes = NULL;
18✔
1945
        size_t n_changes = 0;
18✔
1946

1947
        CLEANUP_ARRAY(changes, n_changes, install_changes_free);
18✔
1948

1949
        log_info("Applying preset policy.");
18✔
1950
        r = unit_file_preset_all(RUNTIME_SCOPE_SYSTEM, /* file_flags= */ 0,
18✔
1951
                                 /* root_dir= */ NULL, mode, &changes, &n_changes);
1952
        r = install_changes_dump(r, "preset all", changes, n_changes, /* quiet= */ false);
18✔
1953
        if (r >= 0)
18✔
1954
                log_info("Populated /etc with preset unit settings.");
×
1955
}
1956

1957
static void manager_ready(Manager *m) {
828✔
1958
        assert(m);
828✔
1959

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

1962
        m->objective = MANAGER_OK; /* Tell everyone we are up now */
828✔
1963

1964
        /* It might be safe to log to the journal now and connect to dbus */
1965
        manager_recheck_journal(m);
828✔
1966
        manager_recheck_dbus(m);
828✔
1967

1968
        /* Let's finally catch up with any changes that took place while we were reloading/reexecing */
1969
        manager_catchup(m);
828✔
1970

1971
        /* Create a file which will indicate when the manager started loading units the last time. */
1972
        if (MANAGER_IS_SYSTEM(m))
828✔
1973
                (void) touch_file("/run/systemd/systemd-units-load", false,
586✔
1974
                        m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].realtime ?: now(CLOCK_REALTIME),
586✔
1975
                        UID_INVALID, GID_INVALID, 0444);
1976
}
828✔
1977

1978
Manager* manager_reloading_start(Manager *m) {
277✔
1979
        m->n_reloading++;
277✔
1980
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
277✔
1981
        return m;
277✔
1982
}
1983

1984
void manager_reloading_stopp(Manager **m) {
1,019✔
1985
        assert(m);
1,019✔
1986

1987
        if (*m) {
1,019✔
1988
                assert((*m)->n_reloading > 0);
211✔
1989
                (*m)->n_reloading--;
211✔
1990
        }
1991
}
1,019✔
1992

1993
static int manager_make_runtime_dir(Manager *m) {
762✔
1994
        int r;
762✔
1995

1996
        assert(m);
762✔
1997

1998
        _cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
1,524✔
1999
        if (!d)
762✔
2000
                return log_oom();
×
2001

2002
        r = mkdir_label(d, 0755);
762✔
2003
        if (r < 0 && r != -EEXIST)
762✔
2004
                return log_error_errno(r, "Failed to create directory '%s/': %m", d);
×
2005

2006
        return 0;
2007
}
2008

2009
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
762✔
2010
        int r;
762✔
2011

2012
        assert(m);
762✔
2013

2014
        r = manager_make_runtime_dir(m);
762✔
2015
        if (r < 0)
762✔
2016
                return r;
2017

2018
        /* If we are running in test mode, we still want to run the generators,
2019
         * but we should not touch the real generator directories. */
2020
        r = lookup_paths_init_or_warn(&m->lookup_paths, m->runtime_scope,
762✔
2021
                                      MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
762✔
2022
                                      root);
2023
        if (r < 0)
762✔
2024
                return r;
2025

2026
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
762✔
2027
        r = manager_run_environment_generators(m);
762✔
2028
        if (r >= 0)
762✔
2029
                r = manager_run_generators(m);
762✔
2030
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
762✔
2031
        if (r < 0)
762✔
2032
                return r;
2033

2034
        manager_preset_all(m);
762✔
2035

2036
        lookup_paths_log(&m->lookup_paths);
762✔
2037

2038
        {
2039
                /* This block is (optionally) done with the reloading counter bumped */
2040
                _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
762✔
2041

2042
                /* Make sure we don't have a left-over from a previous run */
2043
                if (!serialization)
762✔
2044
                        (void) rm_rf(m->lookup_paths.transient, 0);
742✔
2045

2046
                /* If we will deserialize make sure that during enumeration this is already known, so we increase the
2047
                 * counter here already */
2048
                if (serialization)
20✔
2049
                        reloading = manager_reloading_start(m);
20✔
2050

2051
                /* First, enumerate what we can from all config files */
2052
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
762✔
2053
                manager_enumerate_perpetual(m);
762✔
2054
                manager_enumerate(m);
762✔
2055
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
762✔
2056

2057
                /* Second, deserialize if there is something to deserialize */
2058
                if (serialization) {
762✔
2059
                        r = manager_deserialize(m, serialization, fds);
20✔
2060
                        if (r < 0)
20✔
2061
                                return log_error_errno(r, "Deserialization failed: %m");
×
2062
                }
2063

2064
                if (m->previous_objective >= 0) {
762✔
2065
                        if (IN_SET(m->previous_objective, MANAGER_REEXECUTE, MANAGER_SOFT_REBOOT, MANAGER_SWITCH_ROOT))
20✔
2066
                                log_debug("Launching as effect of a '%s' operation.",
20✔
2067
                                          manager_objective_to_string(m->previous_objective));
2068
                        else
2069
                                log_warning("Got unexpected previous objective '%s', ignoring.",
×
2070
                                            manager_objective_to_string(m->previous_objective));
2071
                }
2072

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

2078
                /* Any fds left? Find some unit which wants them. This is useful to allow container managers to pass
2079
                 * some file descriptors to us pre-initialized. This enables socket-based activation of entire
2080
                 * containers. */
2081
                manager_distribute_fds(m, fds);
762✔
2082

2083
                /* We might have deserialized the notify fd, but if we didn't then let's create it now */
2084
                r = manager_setup_notify(m);
762✔
2085
                if (r < 0)
762✔
2086
                        /* No sense to continue without notifications, our children would fail anyway. */
2087
                        return r;
2088

2089
                r = manager_setup_user_lookup_fd(m);
762✔
2090
                if (r < 0)
762✔
2091
                        /* This shouldn't fail, except if things are really broken. */
2092
                        return r;
2093

2094
                r = manager_setup_handoff_timestamp_fd(m);
762✔
2095
                if (r < 0)
762✔
2096
                        /* This shouldn't fail, except if things are really broken. */
2097
                        return r;
2098

2099
                r = manager_setup_pidref_transport_fd(m);
762✔
2100
                if (r < 0)
762✔
2101
                        /* This shouldn't fail, except if things are really broken. */
2102
                        return r;
2103

2104
                /* Connect to the bus if we are good for it */
2105
                manager_setup_bus(m);
762✔
2106

2107
                r = manager_varlink_init(m);
762✔
2108
                if (r < 0)
762✔
2109
                        log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
×
2110

2111
                /* Third, fire things up! */
2112
                manager_coldplug(m);
762✔
2113

2114
                /* Clean up runtime objects */
2115
                manager_vacuum(m);
762✔
2116

2117
                if (serialization)
762✔
2118
                        /* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
2119
                         * reload is finished */
2120
                        m->send_reloading_done = true;
20✔
2121
        }
2122

2123
        manager_ready(m);
762✔
2124

2125
        manager_set_switching_root(m, false);
762✔
2126

2127
        return 0;
762✔
2128
}
2129

2130
int manager_add_job_full(
1,965✔
2131
                Manager *m,
2132
                JobType type,
2133
                Unit *unit,
2134
                JobMode mode,
2135
                TransactionAddFlags extra_flags,
2136
                Set *affected_jobs,
2137
                sd_bus_error *reterr_error,
2138
                Job **ret) {
2139

2140
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,965✔
2141
        int r;
1,965✔
2142

2143
        assert(m);
1,965✔
2144
        assert(type >= 0 && type < _JOB_TYPE_MAX);
1,965✔
2145
        assert(unit);
1,965✔
2146
        assert(mode >= 0 && mode < _JOB_MODE_MAX);
1,965✔
2147
        assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
1,965✔
2148

2149
        if (mode == JOB_ISOLATE && type != JOB_START)
1,965✔
2150
                return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
×
2151

2152
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,965✔
2153
                return sd_bus_error_set(reterr_error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
25✔
2154

2155
        if (mode == JOB_TRIGGERING && type != JOB_STOP)
1,940✔
2156
                return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
×
2157

2158
        if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
1,940✔
2159
                return sd_bus_error_set(reterr_error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=restart-dependencies is only valid for start.");
×
2160

2161
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
1,940✔
2162
        if (!tr)
1,940✔
2163
                return -ENOMEM;
2164

2165
        LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
3,880✔
2166

2167
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1,940✔
2168

2169
        type = job_type_collapse(type, unit);
1,940✔
2170

2171
        r = transaction_add_job_and_dependencies(
5,820✔
2172
                        tr,
2173
                        type,
2174
                        unit,
2175
                        /* by= */ NULL,
2176
                        TRANSACTION_MATTERS |
2177
                        (IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
1,940✔
2178
                        (mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
1,940✔
2179
                        (mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
3,875✔
2180
                        extra_flags,
2181
                        reterr_error);
2182
        if (r < 0)
1,940✔
2183
                return r;
2184

2185
        if (mode == JOB_ISOLATE) {
1,927✔
2186
                r = transaction_add_isolate_jobs(tr, m);
214✔
2187
                if (r < 0)
214✔
2188
                        return r;
2189
        }
2190

2191
        if (mode == JOB_TRIGGERING) {
1,927✔
2192
                r = transaction_add_triggering_jobs(tr, unit);
×
2193
                if (r < 0)
×
2194
                        return r;
2195
        }
2196

2197
        r = transaction_activate(tr, m, mode, affected_jobs, reterr_error);
1,927✔
2198
        if (r < 0)
1,927✔
2199
                return r;
2200

2201
        log_unit_debug(unit,
1,915✔
2202
                       "Enqueued job %s/%s as %u", unit->id,
2203
                       job_type_to_string(type), (unsigned) tr->anchor_job->id);
2204

2205
        if (ret)
1,915✔
2206
                *ret = tr->anchor_job;
1,129✔
2207

2208
        tr = transaction_free(tr);
1,915✔
2209
        return 0;
1,915✔
2210
}
2211

2212
int manager_add_job(
1,064✔
2213
        Manager *m,
2214
        JobType type,
2215
        Unit *unit,
2216
        JobMode mode,
2217
        sd_bus_error *reterr_error,
2218
        Job **ret) {
2219

2220
        return manager_add_job_full(m, type, unit, mode, 0, NULL, reterr_error, ret);
1,064✔
2221
}
2222

2223
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
208✔
2224
        Unit *unit = NULL;  /* just to appease gcc, initialization is not really necessary */
208✔
2225
        int r;
208✔
2226

2227
        assert(m);
208✔
2228
        assert(type < _JOB_TYPE_MAX);
208✔
2229
        assert(name);
208✔
2230
        assert(mode < _JOB_MODE_MAX);
208✔
2231

2232
        r = manager_load_unit(m, name, NULL, NULL, &unit);
208✔
2233
        if (r < 0)
208✔
2234
                return r;
208✔
2235
        assert(unit);
208✔
2236

2237
        return manager_add_job_full(m, type, unit, mode, /* extra_flags= */ 0, affected_jobs, e, ret);
208✔
2238
}
2239

2240
int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
193✔
2241
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
193✔
2242
        int r;
193✔
2243

2244
        assert(m);
193✔
2245
        assert(type < _JOB_TYPE_MAX);
193✔
2246
        assert(name);
193✔
2247
        assert(mode < _JOB_MODE_MAX);
193✔
2248

2249
        r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
193✔
2250
        if (r < 0)
193✔
2251
                return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
×
2252

2253
        return r;
2254
}
2255

2256
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
30,846✔
2257
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
30,846✔
2258
        int r;
30,846✔
2259

2260
        assert(m);
30,846✔
2261
        assert(unit);
30,846✔
2262
        assert(mode < _JOB_MODE_MAX);
30,846✔
2263
        assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
30,846✔
2264

2265
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
30,846✔
2266
        if (!tr)
30,846✔
2267
                return -ENOMEM;
2268

2269
        LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
61,692✔
2270

2271
        /* We need an anchor job */
2272
        r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
30,846✔
2273
        if (r < 0)
30,846✔
2274
                return r;
2275

2276
        /* Failure in adding individual dependencies is ignored, so this always succeeds. */
2277
        transaction_add_propagate_reload_jobs(
30,846✔
2278
                        tr,
2279
                        unit,
2280
                        tr->anchor_job,
30,846✔
2281
                        mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0);
2282

2283
        /* Only activate the transaction if it contains jobs other than NOP anchor.
2284
         * Short-circuiting here avoids unnecessary processing, such as emitting D-Bus signals. */
2285
        if (hashmap_size(tr->jobs) <= 1)
30,846✔
2286
                return 0;
2287

2288
        r = transaction_activate(tr, m, mode, NULL, e);
×
2289
        if (r < 0)
×
2290
                return r;
2291

2292
        tr = transaction_free(tr);
×
2293
        return 0;
×
2294
}
2295

2296
Job *manager_get_job(Manager *m, uint32_t id) {
18,827✔
2297
        assert(m);
18,827✔
2298

2299
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
18,827✔
2300
}
2301

2302
Unit *manager_get_unit(Manager *m, const char *name) {
2,139,412✔
2303
        assert(m);
2,139,412✔
2304
        assert(name);
2,139,412✔
2305

2306
        return hashmap_get(m->units, name);
2,139,412✔
2307
}
2308

2309
static int manager_dispatch_target_deps_queue(Manager *m) {
260,706✔
2310
        Unit *u;
260,706✔
2311
        int r = 0;
260,706✔
2312

2313
        assert(m);
260,706✔
2314

2315
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
339,426✔
2316
                _cleanup_free_ Unit **targets = NULL;
78,720✔
2317
                int n_targets;
78,720✔
2318

2319
                assert(u->in_target_deps_queue);
78,720✔
2320

2321
                u->in_target_deps_queue = false;
78,720✔
2322

2323
                /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2324
                 * dependencies, and we can't have it that hash tables we iterate through are modified while
2325
                 * we are iterating through them. */
2326
                n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
78,720✔
2327
                if (n_targets < 0)
78,720✔
2328
                        return n_targets;
2329

2330
                FOREACH_ARRAY(i, targets, n_targets) {
147,638✔
2331
                        r = unit_add_default_target_dependency(u, *i);
68,918✔
2332
                        if (r < 0)
68,918✔
2333
                                return r;
2334
                }
2335
        }
2336

2337
        return r;
2338
}
2339

2340
unsigned manager_dispatch_load_queue(Manager *m) {
294,530✔
2341
        Unit *u;
294,530✔
2342
        unsigned n = 0;
294,530✔
2343

2344
        assert(m);
294,530✔
2345

2346
        /* Make sure we are not run recursively */
2347
        if (m->dispatching_load_queue)
294,530✔
2348
                return 0;
2349

2350
        m->dispatching_load_queue = true;
260,706✔
2351

2352
        /* Dispatches the load queue. Takes a unit from the queue and
2353
         * tries to load its data until the queue is empty */
2354

2355
        while ((u = m->load_queue)) {
367,056✔
2356
                assert(u->in_load_queue);
106,350✔
2357

2358
                unit_load(u);
106,350✔
2359
                n++;
106,350✔
2360
        }
2361

2362
        m->dispatching_load_queue = false;
260,706✔
2363

2364
        /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2365
         * should be loaded and have aliases resolved */
2366
        (void) manager_dispatch_target_deps_queue(m);
260,706✔
2367

2368
        return n;
260,706✔
2369
}
2370

2371
bool manager_unit_cache_should_retry_load(Unit *u) {
692,175✔
2372
        assert(u);
692,175✔
2373

2374
        /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2375
         * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2376
         * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
2377
        if (u->load_state != UNIT_NOT_FOUND)
692,175✔
2378
                return false;
2379

2380
        /* The cache has been updated since the last time we tried to load the unit. There might be new
2381
         * fragment paths to read. */
2382
        if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
2,501✔
2383
                return true;
2384

2385
        /* The cache needs to be updated because there are modifications on disk. */
2386
        return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
2,501✔
2387
}
2388

2389
int manager_load_unit_prepare(
629,945✔
2390
                Manager *m,
2391
                const char *name,
2392
                const char *path,
2393
                sd_bus_error *e,
2394
                Unit **ret) {
2395

2396
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2397
        _cleanup_free_ char *nbuf = NULL;
629,945✔
2398
        int r;
629,945✔
2399

2400
        assert(m);
629,945✔
2401
        assert(ret);
629,945✔
2402
        assert(name || path);
629,945✔
2403

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

2406
        if (path && !path_is_absolute(path))
629,945✔
2407
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2408

2409
        if (!name) {
629,945✔
2410
                r = path_extract_filename(path, &nbuf);
491✔
2411
                if (r < 0)
491✔
2412
                        return r;
2413
                if (r == O_DIRECTORY)
491✔
2414
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2415

2416
                name = nbuf;
491✔
2417
        }
2418

2419
        UnitType t = unit_name_to_type(name);
629,945✔
2420

2421
        if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
629,945✔
2422
                if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
×
2423
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
×
2424

2425
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
×
2426
        }
2427

2428
        Unit *unit = manager_get_unit(m, name);
629,945✔
2429
        if (unit) {
629,945✔
2430
                /* The time-based cache allows new units to be started without daemon-reload,
2431
                 * but if they are already referenced (because of dependencies or ordering)
2432
                 * then we have to force a load of the fragment. As an optimization, check
2433
                 * first if anything in the usual paths was modified since the last time
2434
                 * the cache was loaded. Also check if the last time an attempt to load the
2435
                 * unit was made was before the most recent cache refresh, so that we know
2436
                 * we need to try again — even if the cache is current, it might have been
2437
                 * updated in a different context before we had a chance to retry loading
2438
                 * this particular unit. */
2439
                if (manager_unit_cache_should_retry_load(unit))
566,053✔
2440
                        unit->load_state = UNIT_STUB;
×
2441
                else {
2442
                        *ret = unit;
566,053✔
2443
                        return 0;  /* The unit was already loaded */
566,053✔
2444
                }
2445
        } else {
2446
                unit = cleanup_unit = unit_new(m, unit_vtable[t]->object_size);
63,892✔
2447
                if (!unit)
63,892✔
2448
                        return -ENOMEM;
2449
        }
2450

2451
        if (path) {
63,892✔
2452
                r = free_and_strdup(&unit->fragment_path, path);
491✔
2453
                if (r < 0)
491✔
2454
                        return r;
2455
        }
2456

2457
        r = unit_add_name(unit, name);
63,892✔
2458
        if (r < 0)
63,892✔
2459
                return r;
2460

2461
        unit_add_to_load_queue(unit);
63,892✔
2462
        unit_add_to_dbus_queue(unit);
63,892✔
2463
        unit_add_to_gc_queue(unit);
63,892✔
2464

2465
        *ret = unit;
63,892✔
2466
        TAKE_PTR(cleanup_unit);
63,892✔
2467

2468
        return 1;  /* The unit was added the load queue */
63,892✔
2469
}
2470

2471
int manager_load_unit(
603,481✔
2472
                Manager *m,
2473
                const char *name,
2474
                const char *path,
2475
                sd_bus_error *e,
2476
                Unit **ret) {
2477
        int r;
603,481✔
2478

2479
        assert(m);
603,481✔
2480
        assert(ret);
603,481✔
2481

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

2484
        r = manager_load_unit_prepare(m, name, path, e, ret);
603,481✔
2485
        if (r <= 0)
603,481✔
2486
                return r;
2487

2488
        /* Unit was newly loaded */
2489
        manager_dispatch_load_queue(m);
37,828✔
2490
        *ret = unit_follow_merge(*ret);
37,828✔
2491
        return 0;
37,828✔
2492
}
2493

2494
int manager_load_startable_unit_or_warn(
748✔
2495
                Manager *m,
2496
                const char *name,
2497
                const char *path,
2498
                Unit **ret) {
2499

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

2502
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
748✔
2503
        Unit *unit;
748✔
2504
        int r;
748✔
2505

2506
        r = manager_load_unit(m, name, path, &error, &unit);
748✔
2507
        if (r < 0)
748✔
2508
                return log_error_errno(r, "Failed to load %s %s: %s",
×
2509
                                       name ? "unit" : "unit file", name ?: path,
2510
                                       bus_error_message(&error, r));
2511

2512
        r = bus_unit_validate_load_state(unit, &error);
748✔
2513
        if (r < 0)
748✔
2514
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2515

2516
        *ret = unit;
739✔
2517
        return 0;
739✔
2518
}
2519

2520
void manager_clear_jobs(Manager *m) {
481✔
2521
        Job *j;
481✔
2522

2523
        assert(m);
481✔
2524

2525
        while ((j = hashmap_first(m->jobs)))
502✔
2526
                /* No need to recurse. We're cancelling all jobs. */
2527
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
21✔
2528
}
481✔
2529

2530
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
2,602✔
2531
        assert(m);
2,602✔
2532

2533
        for (;;) {
×
2534
                Unit *u;
2,602✔
2535

2536
                u = manager_get_unit_by_pidref_watching(m, pid);
2,602✔
2537
                if (!u)
2,602✔
2538
                        break;
2539

2540
                unit_unwatch_pidref(u, pid);
×
2541
        }
2542
}
2,602✔
2543

2544
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
4,359✔
2545
        Manager *m = ASSERT_PTR(userdata);
4,359✔
2546
        Job *j;
4,359✔
2547

2548
        assert(source);
4,359✔
2549

2550
        while ((j = prioq_peek(m->run_queue))) {
47,905✔
2551
                assert(j->installed);
43,546✔
2552
                assert(j->in_run_queue);
43,546✔
2553

2554
                (void) job_run_and_invalidate(j);
43,546✔
2555
        }
2556

2557
        if (m->n_running_jobs > 0)
4,359✔
2558
                manager_watch_jobs_in_progress(m);
3,662✔
2559

2560
        if (m->n_on_console > 0)
4,359✔
2561
                manager_watch_idle_pipe(m);
822✔
2562

2563
        return 1;
4,359✔
2564
}
2565

2566
void manager_trigger_run_queue(Manager *m) {
46,196✔
2567
        int r;
46,196✔
2568

2569
        assert(m);
46,196✔
2570

2571
        r = sd_event_source_set_enabled(
92,175✔
2572
                        m->run_queue_event_source,
2573
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
46,196✔
2574
        if (r < 0)
46,196✔
2575
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2576
}
46,196✔
2577

2578
static unsigned manager_dispatch_dbus_queue(Manager *m) {
201,207✔
2579
        unsigned n = 0, budget;
201,207✔
2580
        Unit *u;
201,207✔
2581
        Job *j;
201,207✔
2582

2583
        assert(m);
201,207✔
2584

2585
        /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2586
         * as we can. There's no point in throttling generation of signals in that case. */
2587
        if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message_dbus || m->pending_reload_message_vl)
201,207✔
2588
                budget = UINT_MAX; /* infinite budget in this case */
2589
        else {
2590
                /* Anything to do at all? */
2591
                if (!m->dbus_unit_queue && !m->dbus_job_queue)
201,121✔
2592
                        return 0;
2593

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

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

2613
        while (budget != 0 && (u = m->dbus_unit_queue)) {
50,996✔
2614

2615
                assert(u->in_dbus_queue);
42,832✔
2616

2617
                bus_unit_send_change_signal(u);
42,832✔
2618
                n++;
42,832✔
2619

2620
                if (budget != UINT_MAX)
42,832✔
2621
                        budget--;
21,773✔
2622
        }
2623

2624
        while (budget != 0 && (j = m->dbus_job_queue)) {
27,711✔
2625
                assert(j->in_dbus_queue);
19,547✔
2626

2627
                bus_job_send_change_signal(j);
19,547✔
2628
                n++;
19,547✔
2629

2630
                if (budget != UINT_MAX)
19,547✔
2631
                        budget--;
19,136✔
2632
        }
2633

2634
        if (m->send_reloading_done) {
8,164✔
2635
                m->send_reloading_done = false;
86✔
2636
                bus_manager_send_reloading(m, false);
86✔
2637
                n++;
86✔
2638
        }
2639

2640
        if (m->pending_reload_message_dbus) {
8,164✔
2641
                bus_send_pending_reload_message(m);
65✔
2642
                n++;
65✔
2643
        }
2644

2645
        if (m->pending_reload_message_vl) {
8,164✔
2646
                manager_varlink_send_pending_reload_message(m);
1✔
2647
                n++;
1✔
2648
        }
2649

2650
        return n;
2651
}
2652

2653
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
3,844✔
2654

2655
        /* nothing else must be sent when using BARRIER=1 */
2656
        if (strv_contains(tags, "BARRIER=1")) {
3,844✔
2657
                if (strv_length(tags) != 1)
15✔
2658
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
×
2659
                else if (fdset_size(fds) != 1)
15✔
2660
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
×
2661

2662
                /* Drop the message if BARRIER=1 was found */
2663
                return true;
15✔
2664
        }
2665

2666
        return false;
2667
}
2668

2669
static void manager_invoke_notify_message(
7,507✔
2670
                Manager *m,
2671
                Unit *u,
2672
                PidRef *pidref,
2673
                const struct ucred *ucred,
2674
                char * const *tags,
2675
                FDSet *fds) {
2676

2677
        assert(m);
7,507✔
2678
        assert(u);
7,507✔
2679
        assert(pidref_is_set(pidref));
7,507✔
2680
        assert(ucred);
7,507✔
2681
        assert(pidref->pid == ucred->pid);
7,507✔
2682
        assert(tags);
7,507✔
2683

2684
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
7,507✔
2685
                return;
2686
        u->notifygen = m->notifygen;
3,824✔
2687

2688
        if (UNIT_VTABLE(u)->notify_message)
3,824✔
2689
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
3,824✔
2690

2691
        else if (DEBUG_LOGGING) {
×
2692
                _cleanup_free_ char *joined = strv_join(tags, ", ");
×
2693
                char buf[CELLESCAPE_DEFAULT_LENGTH];
×
2694

2695
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
×
2696
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
2697
        }
2698
}
2699

2700
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
12,493✔
2701
        /* Determine array of every unit that is interested in the specified process */
2702

2703
        assert(m);
12,493✔
2704
        assert(pidref_is_set(pidref));
12,493✔
2705

2706
        Unit *u1, *u2, **array;
12,493✔
2707
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
12,493✔
2708
        u2 = hashmap_get(m->watch_pids, pidref);
12,493✔
2709
        array = hashmap_get(m->watch_pids_more, pidref);
12,493✔
2710

2711
        size_t n = 0;
12,493✔
2712
        if (u1)
12,493✔
2713
                n++;
12,488✔
2714
        if (u2)
12,493✔
2715
                n++;
8,633✔
2716
        if (array)
12,493✔
2717
                for (size_t j = 0; array[j]; j++)
×
2718
                        n++;
×
2719

2720
        assert(n <= INT_MAX); /* Make sure we can reasonably return the counter as "int" */
×
2721

2722
        if (ret_units) {
12,493✔
2723
                _cleanup_free_ Unit **units = NULL;
×
2724

2725
                if (n > 0) {
12,493✔
2726
                        units = new(Unit*, n + 1);
12,488✔
2727
                        if (!units)
12,488✔
2728
                                return -ENOMEM;
×
2729

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

2734
                        size_t i = 0;
12,488✔
2735
                        if (u1)
12,488✔
2736
                                units[i++] = u1;
12,488✔
2737
                        if (u2)
12,488✔
2738
                                units[i++] = u2;
8,633✔
2739
                        if (array)
12,488✔
2740
                                for (size_t j = 0; array[j]; j++)
×
2741
                                        units[i++] = array[j];
×
2742
                        assert(i == n);
12,488✔
2743

2744
                        units[i] = NULL; /* end array in an extra NULL */
12,488✔
2745
                }
2746

2747
                *ret_units = TAKE_PTR(units);
12,493✔
2748
        }
2749

2750
        return (int) n;
12,493✔
2751
}
2752

2753
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,844✔
2754
        Manager *m = ASSERT_PTR(userdata);
3,844✔
2755
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3,844✔
2756
        struct ucred ucred;
3,844✔
2757
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
3,844✔
2758
        int r;
3,844✔
2759

2760
        assert(m->notify_fd == fd);
3,844✔
2761

2762
        if (revents != EPOLLIN) {
3,844✔
2763
                log_warning("Got unexpected poll event for notify fd.");
×
2764
                return 0;
×
2765
        }
2766

2767
        _cleanup_strv_free_ char **tags = NULL;
3,844✔
2768
        r = notify_recv_with_fds_strv(m->notify_fd, &tags, &ucred, &pidref, &fds);
3,844✔
2769
        if (r == -EAGAIN)
3,844✔
2770
                return 0;
2771
        if (r < 0)
3,844✔
2772
                /* If this is any other, real error, then stop processing this socket. This of course means
2773
                 * we won't take notification messages anymore, but that's still better than busy looping:
2774
                 * being woken up over and over again, but being unable to actually read the message from the
2775
                 * socket. */
2776
                return r;
2777

2778
        /* Possibly a barrier fd, let's see. */
2779
        if (manager_process_barrier_fd(tags, fds)) {
3,844✔
2780
                log_debug("Received barrier notification message from PID " PID_FMT ".", pidref.pid);
15✔
2781
                return 0;
15✔
2782
        }
2783

2784
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
2785
        m->notifygen++;
3,829✔
2786

2787
        /* Notify every unit that might be interested, which might be multiple. */
2788
        _cleanup_free_ Unit **array = NULL;
3,829✔
2789

2790
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
3,829✔
2791
        if (n_array < 0) {
3,829✔
2792
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", pidref.pid);
×
2793
                return 0;
×
2794
        }
2795
        if (n_array == 0)
3,829✔
2796
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", pidref.pid);
5✔
2797
        else
2798
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
2799
                 * duplicate units – making sure we only invoke each unit's handler once. */
2800
                FOREACH_ARRAY(u, array, n_array)
11,331✔
2801
                        manager_invoke_notify_message(m, *u, &pidref, &ucred, tags, fds);
7,507✔
2802

2803
        if (!fdset_isempty(fds))
3,829✔
2804
                log_warning("Got extra auxiliary fds with notification message, closing them.");
×
2805

2806
        return 0;
2807
}
2808

2809
static void manager_invoke_sigchld_event(
8,544✔
2810
                Manager *m,
2811
                Unit *u,
2812
                const siginfo_t *si) {
2813

2814
        assert(m);
8,544✔
2815
        assert(u);
8,544✔
2816
        assert(si);
8,544✔
2817

2818
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2819
        if (u->sigchldgen == m->sigchldgen)
8,544✔
2820
                return;
2,314✔
2821
        u->sigchldgen = m->sigchldgen;
6,230✔
2822

2823
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
6,230✔
2824
        unit_unwatch_pidref(u, &PIDREF_MAKE_FROM_PID(si->si_pid));
6,230✔
2825

2826
        if (UNIT_VTABLE(u)->sigchld_event)
6,230✔
2827
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
6,106✔
2828
}
2829

2830
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
10,855✔
2831
        Manager *m = ASSERT_PTR(userdata);
10,855✔
2832
        siginfo_t si = {};
10,855✔
2833
        int r;
10,855✔
2834

2835
        assert(source);
10,855✔
2836

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

2840
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
10,855✔
2841

2842
                if (errno != ECHILD)
86✔
2843
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
×
2844

2845
                goto turn_off;
86✔
2846
        }
2847

2848
        if (si.si_pid <= 0)
10,769✔
2849
                goto turn_off;
4,640✔
2850

2851
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
6,129✔
2852
                _cleanup_free_ char *name = NULL;
12,258✔
2853
                (void) pid_get_comm(si.si_pid, &name);
6,129✔
2854

2855
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
12,258✔
2856
                          si.si_pid, strna(name),
2857
                          sigchld_code_to_string(si.si_code),
2858
                          si.si_status,
2859
                          strna(si.si_code == CLD_EXITED
2860
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2861
                                : signal_to_string(si.si_status)));
2862

2863
                /* Increase the generation counter used for filtering out duplicate unit invocations */
2864
                m->sigchldgen++;
6,129✔
2865

2866
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
2867
                 * pidfd here any more even if we wanted (since the process just exited). */
2868
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
6,129✔
2869

2870
                /* And now figure out the units this belongs to, there might be multiple... */
2871
                _cleanup_free_ Unit **array = NULL;
6,129✔
2872
                int n_array = manager_get_units_for_pidref(m, &pidref, &array);
6,129✔
2873
                if (n_array < 0)
6,129✔
2874
                        log_warning_errno(n_array, "Failed to get units for process " PID_FMT ", ignoring: %m", si.si_pid);
6,129✔
2875
                else if (n_array == 0)
6,129✔
2876
                        log_debug("Got SIGCHLD for process " PID_FMT " we weren't interested in, ignoring.", si.si_pid);
×
2877
                else {
2878
                        /* We check for an OOM condition, in case we got SIGCHLD before the OOM notification.
2879
                         * We only do this for the cgroup the PID belonged to, which is the f */
2880
                        (void) unit_check_oom(array[0]);
6,129✔
2881

2882
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
2883
                        (void) unit_check_oomd_kill(array[0]);
6,129✔
2884

2885
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
2886
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
2887
                         * iteration. */
2888
                        FOREACH_ARRAY(u, array, n_array)
14,673✔
2889
                                manager_invoke_sigchld_event(m, *u, &si);
8,544✔
2890
                }
2891
        }
2892

2893
        /* And now, we actually reap the zombie. */
2894
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
6,129✔
2895
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
×
2896
                return 0;
10,855✔
2897
        }
2898

2899
        return 0;
2900

2901
turn_off:
4,726✔
2902
        /* All children processed for now, turn off event source */
2903

2904
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
4,726✔
2905
        if (r < 0)
4,726✔
2906
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
×
2907

2908
        return 0;
2909
}
2910

2911
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
192✔
2912
        Job *job;
192✔
2913

2914
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
192✔
2915
                return;
×
2916

2917
        const char *s = unit_status_string(job->unit, NULL);
192✔
2918

2919
        log_info("Activating special unit %s...", s);
192✔
2920

2921
        (void) sd_notifyf(/* unset_environment= */ false,
192✔
2922
                          "STATUS=Activating special unit %s...", s);
2923
        m->status_ready = false;
192✔
2924
}
2925

2926
static void manager_handle_ctrl_alt_del(Manager *m) {
×
2927
        assert(m);
×
2928

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

2932
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
×
2933
                manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
×
2934
        else
2935
                emergency_action(
×
2936
                                m,
2937
                                m->cad_burst_action,
2938
                                EMERGENCY_ACTION_WARN,
2939
                                /* reboot_arg= */ NULL,
2940
                                /* exit_status= */ -1,
2941
                                "Ctrl-Alt-Del was pressed more than 7 times within 2s");
2942
}
×
2943

2944
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
4,610✔
2945
        Manager *m = ASSERT_PTR(userdata);
4,610✔
2946
        ssize_t n;
4,610✔
2947
        struct signalfd_siginfo sfsi;
4,610✔
2948
        int r;
4,610✔
2949

2950
        assert(m->signal_fd == fd);
4,610✔
2951

2952
        if (revents != EPOLLIN) {
4,610✔
2953
                log_warning("Got unexpected events from signal file descriptor.");
×
2954
                return 0;
×
2955
        }
2956

2957
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
4,610✔
2958
        if (n < 0) {
4,610✔
2959
                if (ERRNO_IS_TRANSIENT(errno))
×
2960
                        return 0;
2961

2962
                /* We return an error here, which will kill this handler,
2963
                 * to avoid a busy loop on read error. */
2964
                return log_error_errno(errno, "Reading from signal fd failed: %m");
×
2965
        }
2966
        if (n != sizeof(sfsi)) {
4,610✔
2967
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
×
2968
                return 0;
×
2969
        }
2970

2971
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
4,802✔
2972
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
192✔
2973
                            ? LOG_DEBUG : LOG_INFO,
2974
                            &sfsi);
2975

2976
        switch (sfsi.ssi_signo) {
4,610✔
2977

2978
        case SIGCHLD:
4,418✔
2979
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
4,418✔
2980
                if (r < 0)
4,418✔
2981
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
4,610✔
2982

2983
                break;
2984

2985
        case SIGTERM:
192✔
2986
                if (MANAGER_IS_SYSTEM(m)) {
192✔
2987
                        /* This is for compatibility with the original sysvinit */
2988
                        m->objective = MANAGER_REEXECUTE;
×
2989
                        break;
×
2990
                }
2991

2992
                _fallthrough_;
192✔
2993
        case SIGINT:
2994
                if (MANAGER_IS_SYSTEM(m))
192✔
2995
                        manager_handle_ctrl_alt_del(m);
×
2996
                else
2997
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
192✔
2998
                break;
2999

3000
        case SIGWINCH:
×
3001
                /* This is a nop on non-init */
3002
                if (MANAGER_IS_SYSTEM(m))
×
3003
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
×
3004

3005
                break;
3006

3007
        case SIGPWR:
×
3008
                /* This is a nop on non-init */
3009
                if (MANAGER_IS_SYSTEM(m))
×
3010
                        manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
×
3011

3012
                break;
3013

3014
        case SIGUSR1:
×
3015
                if (manager_dbus_is_running(m, false)) {
×
3016
                        log_info("Trying to reconnect to bus...");
×
3017

3018
                        (void) bus_init_api(m);
×
3019

3020
                        if (MANAGER_IS_SYSTEM(m))
×
3021
                                (void) bus_init_system(m);
×
3022
                } else
3023
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
×
3024

3025
                break;
3026

3027
        case SIGUSR2: {
×
3028
                _cleanup_free_ char *dump = NULL;
×
3029

3030
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
×
3031
                if (r < 0) {
×
3032
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
×
3033
                        break;
3034
                }
3035

3036
                log_dump(LOG_INFO, dump);
×
3037
                break;
3038
        }
3039

3040
        case SIGHUP:
×
3041
                m->objective = MANAGER_RELOAD;
×
3042
                break;
×
3043

3044
        default: {
×
3045

3046
                if (MANAGER_IS_SYSTEM(m)) {
×
3047
                        /* Starting SIGRTMIN+0 */
3048
                        static const struct {
×
3049
                                const char *target;
3050
                                JobMode mode;
3051
                        } target_table[] = {
3052
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
3053
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
3054
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
3055
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
3056
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
3057
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
3058
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
3059
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
3060
                        };
3061

3062
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
3063
                        static const ManagerObjective objective_table[] = {
×
3064
                                [0] = MANAGER_HALT,
3065
                                [1] = MANAGER_POWEROFF,
3066
                                [2] = MANAGER_REBOOT,
3067
                                [3] = MANAGER_KEXEC,
3068
                                [4] = MANAGER_SOFT_REBOOT,
3069
                        };
3070

3071
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
×
3072
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
×
3073
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
×
3074
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
×
3075
                                break;
3076
                        }
3077

3078
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
×
3079
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
×
3080
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
×
3081
                                break;
×
3082
                        }
3083
                }
3084

3085
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3086

3087
                case 18: {
×
3088
                        bool generic = false;
×
3089

3090
                        if (sfsi.ssi_code != SI_QUEUE)
×
3091
                                generic = true;
3092
                        else {
3093
                                /* Override a few select commands by our own PID1-specific logic */
3094

3095
                                switch (sfsi.ssi_int) {
×
3096

3097
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
×
3098
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
×
3099
                                        break;
3100

3101
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3102
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3103
                                        break;
3104

3105
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3106
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3107
                                        break;
3108

3109
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3110
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3111
                                        break;
3112

3113
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3114
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3115
                                        break;
3116

3117
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3118
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3119

3120
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
×
3121
                                        if (r < 0) {
×
3122
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
×
3123
                                                break;
3124
                                        }
3125

3126
                                        log_dump(LOG_INFO, dump_jobs);
×
3127
                                        break;
3128
                                }
3129

3130
                                default:
3131
                                        generic = true;
3132
                                }
3133
                        }
3134

3135
                        if (generic)
×
3136
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3137

3138
                        break;
3139
                }
3140

3141
                case 20:
×
3142
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
×
3143
                        break;
3144

3145
                case 21:
×
3146
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
×
3147
                        break;
3148

3149
                case 22:
×
3150
                        manager_override_log_level(m, LOG_DEBUG);
×
3151
                        break;
3152

3153
                case 23:
×
3154
                        manager_restore_original_log_level(m);
×
3155
                        break;
3156

3157
                case 24:
×
3158
                        if (MANAGER_IS_USER(m)) {
×
3159
                                m->objective = MANAGER_EXIT;
×
3160
                                return 0;
×
3161
                        }
3162

3163
                        /* This is a nop on init */
3164
                        break;
3165

3166
                case 25:
×
3167
                        m->objective = MANAGER_REEXECUTE;
×
3168
                        break;
×
3169

3170
                case 26:
×
3171
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
3172
                        manager_restore_original_log_target(m);
×
3173
                        break;
3174

3175
                case 27:
×
3176
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3177
                        break;
3178

3179
                case 28:
×
3180
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3181
                        break;
3182

3183
                default:
3184
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
×
3185
                }
3186
        }}
3187

3188
        return 0;
3189
}
3190

3191
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
11✔
3192
        Manager *m = ASSERT_PTR(userdata);
11✔
3193
        Unit *u;
11✔
3194

3195
        log_struct(LOG_DEBUG,
11✔
3196
                   LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
3197
                   LOG_MESSAGE("Time has been changed"));
3198

3199
        /* Restart the watch */
3200
        (void) manager_setup_time_change(m);
11✔
3201

3202
        HASHMAP_FOREACH(u, m->units)
1,541✔
3203
                if (UNIT_VTABLE(u)->time_change)
1,519✔
3204
                        UNIT_VTABLE(u)->time_change(u);
11✔
3205

3206
        return 0;
11✔
3207
}
3208

3209
static int manager_dispatch_timezone_change(
56✔
3210
                sd_event_source *source,
3211
                const struct inotify_event *e,
3212
                void *userdata) {
3213

3214
        Manager *m = ASSERT_PTR(userdata);
56✔
3215
        int changed;
56✔
3216
        Unit *u;
56✔
3217

3218
        log_debug("inotify event for /etc/localtime");
56✔
3219

3220
        changed = manager_read_timezone_stat(m);
56✔
3221
        if (changed <= 0)
56✔
3222
                return changed;
56✔
3223

3224
        /* Something changed, restart the watch, to ensure we watch the new /etc/localtime if it changed */
3225
        (void) manager_setup_timezone_change(m);
31✔
3226

3227
        /* Read the new timezone */
3228
        tzset();
31✔
3229

3230
        log_debug("Timezone has been changed (now: %s).", get_tzname(daylight));
31✔
3231

3232
        HASHMAP_FOREACH(u, m->units)
6,683✔
3233
                if (UNIT_VTABLE(u)->timezone_change)
6,621✔
3234
                        UNIT_VTABLE(u)->timezone_change(u);
67✔
3235

3236
        return 0;
31✔
3237
}
3238

3239
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
9✔
3240
        Manager *m = ASSERT_PTR(userdata);
9✔
3241

3242
        assert(m->idle_pipe[2] == fd);
9✔
3243

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

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

3255
        return 0;
9✔
3256
}
3257

3258
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
3✔
3259
        Manager *m = ASSERT_PTR(userdata);
3✔
3260
        int r;
3✔
3261

3262
        assert(source);
3✔
3263

3264
        manager_print_jobs_in_progress(m);
3✔
3265

3266
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
3✔
3267
        if (r < 0)
3✔
3268
                return r;
3269

3270
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
3✔
3271
}
3272

3273
int manager_loop(Manager *m) {
311✔
3274
        RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
311✔
3275
        int r;
311✔
3276

3277
        assert(m);
311✔
3278
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
311✔
3279

3280
        manager_check_finished(m);
311✔
3281

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

3287
        while (m->objective == MANAGER_OK) {
239,573✔
3288

3289
                if (!ratelimit_below(&rl)) {
239,262✔
3290
                        /* Yay, something is going seriously wrong, pause a little */
3291
                        log_warning("Looping too fast. Throttling execution a little.");
×
3292
                        sleep(1);
×
3293
                }
3294

3295
                (void) watchdog_ping();
239,262✔
3296

3297
                if (manager_dispatch_load_queue(m) > 0)
239,262✔
3298
                        continue;
1✔
3299

3300
                if (manager_dispatch_gc_job_queue(m) > 0)
239,261✔
3301
                        continue;
12✔
3302

3303
                if (manager_dispatch_gc_unit_queue(m) > 0)
239,249✔
3304
                        continue;
20,414✔
3305

3306
                if (manager_dispatch_cleanup_queue(m) > 0)
218,835✔
3307
                        continue;
11,295✔
3308

3309
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
207,540✔
3310
                        continue;
4,691✔
3311

3312
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
202,849✔
3313
                        continue;
×
3314

3315
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
202,849✔
3316
                        continue;
156✔
3317

3318
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
202,693✔
3319
                        continue;
267✔
3320

3321
                if (manager_dispatch_release_resources_queue(m) > 0)
202,426✔
3322
                        continue;
1,219✔
3323

3324
                if (manager_dispatch_stop_notify_queue(m) > 0)
201,207✔
3325
                        continue;
×
3326

3327
                if (manager_dispatch_dbus_queue(m) > 0)
201,207✔
3328
                        continue;
8,164✔
3329

3330
                /* Sleep for watchdog runtime wait time */
3331
                r = sd_event_run(m->event, watchdog_runtime_wait(/* divisor= */ 2));
193,043✔
3332
                if (r < 0)
193,043✔
3333
                        return log_error_errno(r, "Failed to run event loop: %m");
×
3334
        }
3335

3336
        return m->objective;
3337
}
3338

3339
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
379,140✔
3340
        _cleanup_free_ char *n = NULL;
379,140✔
3341
        sd_id128_t invocation_id;
379,140✔
3342
        Unit *u;
379,140✔
3343
        int r;
379,140✔
3344

3345
        assert(m);
379,140✔
3346
        assert(s);
379,140✔
3347
        assert(_u);
379,140✔
3348

3349
        r = unit_name_from_dbus_path(s, &n);
379,140✔
3350
        if (r < 0)
379,140✔
3351
                return r;
3352

3353
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
3354
         * we use it as invocation ID. */
3355
        r = sd_id128_from_string(n, &invocation_id);
379,103✔
3356
        if (r >= 0) {
379,103✔
3357
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
×
3358
                if (u) {
×
3359
                        *_u = u;
×
3360
                        return 0;
×
3361
                }
3362

3363
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
×
3364
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3365
                                         SD_ID128_FORMAT_VAL(invocation_id));
×
3366
        }
3367

3368
        /* If this didn't work, we check if this is a unit name */
3369
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
379,103✔
3370
                _cleanup_free_ char *nn = NULL;
1✔
3371

3372
                nn = cescape(n);
1✔
3373
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
1✔
3374
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3375
        }
3376

3377
        r = manager_load_unit(m, n, NULL, e, &u);
379,102✔
3378
        if (r < 0)
379,102✔
3379
                return r;
3380

3381
        *_u = u;
379,102✔
3382
        return 0;
379,102✔
3383
}
3384

3385
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1,074✔
3386
        const char *p;
1,074✔
3387
        unsigned id;
1,074✔
3388
        Job *j;
1,074✔
3389
        int r;
1,074✔
3390

3391
        assert(m);
1,074✔
3392
        assert(s);
1,074✔
3393
        assert(_j);
1,074✔
3394

3395
        p = startswith(s, "/org/freedesktop/systemd1/job/");
1,074✔
3396
        if (!p)
1,074✔
3397
                return -EINVAL;
1,074✔
3398

3399
        r = safe_atou(p, &id);
1,073✔
3400
        if (r < 0)
1,073✔
3401
                return r;
3402

3403
        j = manager_get_job(m, id);
1,073✔
3404
        if (!j)
1,073✔
3405
                return -ENOENT;
3406

3407
        *_j = j;
1,049✔
3408

3409
        return 0;
1,049✔
3410
}
3411

3412
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
3,917✔
3413

3414
#if HAVE_AUDIT
3415
        _cleanup_free_ char *p = NULL;
3,917✔
3416
        const char *msg;
3,917✔
3417
        int audit_fd, r;
3,917✔
3418

3419
        assert(m);
3,917✔
3420
        assert(u);
3,917✔
3421

3422
        if (!MANAGER_IS_SYSTEM(m))
3,917✔
3423
                return;
3424

3425
        /* Don't generate audit events if the service was already started and we're just deserializing */
3426
        if (MANAGER_IS_RELOADING(m))
2,449✔
3427
                return;
3428

3429
        audit_fd = get_core_audit_fd();
2,449✔
3430
        if (audit_fd < 0)
2,449✔
3431
                return;
3432

3433
        r = unit_name_to_prefix_and_instance(u->id, &p);
866✔
3434
        if (r < 0) {
866✔
3435
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
×
3436
                return;
×
3437
        }
3438

3439
        msg = strjoina("unit=", p);
4,330✔
3440
        if (sym_audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
866✔
3441
                if (ERRNO_IS_PRIVILEGE(errno)) {
×
3442
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
3443
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
×
3444
                        close_core_audit_fd();
×
3445
                } else
3446
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
866✔
3447
        }
3448
#endif
3449
}
3450

3451
void manager_send_unit_plymouth(Manager *m, Unit *u) {
45,898✔
3452
        _cleanup_free_ char *message = NULL;
45,898✔
3453
        int c, r;
45,898✔
3454

3455
        assert(m);
45,898✔
3456
        assert(u);
45,898✔
3457

3458
        if (!MANAGER_IS_SYSTEM(m))
45,898✔
3459
                return;
3460

3461
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
3462
        if (MANAGER_IS_RELOADING(m))
6,243✔
3463
                return;
3464

3465
        if (detect_container() > 0)
6,243✔
3466
                return;
3467

3468
        if (!UNIT_VTABLE(u)->notify_plymouth)
3,284✔
3469
                return;
3470

3471
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
631✔
3472
        if (c < 0)
631✔
3473
                return (void) log_oom();
×
3474

3475
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
3476
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
631✔
3477
        if (r < 0)
631✔
3478
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
631✔
3479
                               "Failed to communicate with plymouth: %m");
3480
}
3481

3482
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
75,139✔
3483
        assert(m);
75,139✔
3484
        assert(u);
75,139✔
3485

3486
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
3487
         * surrounding service manager. */
3488

3489
        if (MANAGER_IS_RELOADING(m))
75,139✔
3490
                return;
3491

3492
        if (!UNIT_VTABLE(u)->notify_supervisor)
75,139✔
3493
                return;
3494

3495
        if (in_initrd()) /* Only send these once we left the initrd */
4,257✔
3496
                return;
3497

3498
        (void) sd_notifyf(/* unset_environment= */ false,
5,224✔
3499
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
3500
                          u->id);
3501
}
3502

3503
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
575✔
3504
        assert(m);
575✔
3505

3506
        if (MANAGER_IS_USER(m))
575✔
3507
                return USEC_INFINITY;
3508

3509
        if (m->watchdog_overridden[t] != USEC_INFINITY)
185✔
3510
                return m->watchdog_overridden[t];
3511

3512
        return m->watchdog[t];
182✔
3513
}
3514

3515
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
1,244✔
3516

3517
        assert(m);
1,244✔
3518

3519
        if (MANAGER_IS_USER(m))
1,244✔
3520
                return;
3521

3522
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
344✔
3523
                if (t == WATCHDOG_RUNTIME)
335✔
3524
                        (void) watchdog_setup(timeout);
86✔
3525
                else if (t == WATCHDOG_PRETIMEOUT)
249✔
3526
                        (void) watchdog_setup_pretimeout(timeout);
86✔
3527
        }
3528

3529
        m->watchdog[t] = timeout;
344✔
3530
}
3531

3532
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
10✔
3533
        usec_t usec;
10✔
3534

3535
        assert(m);
10✔
3536

3537
        if (MANAGER_IS_USER(m))
10✔
3538
                return;
3539

3540
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
10✔
3541
        if (t == WATCHDOG_RUNTIME)
10✔
3542
                (void) watchdog_setup(usec);
×
3543
        else if (t == WATCHDOG_PRETIMEOUT)
10✔
3544
                (void) watchdog_setup_pretimeout(usec);
×
3545

3546
        m->watchdog_overridden[t] = timeout;
10✔
3547
}
3548

3549
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
311✔
3550
        _cleanup_free_ char *p = NULL;
311✔
3551
        int r;
311✔
3552

3553
        assert(m);
311✔
3554

3555
        if (MANAGER_IS_USER(m))
311✔
3556
                return 0;
3557

3558
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
86✔
3559
                return 0;
3560

3561
        p = strdup(governor);
×
3562
        if (!p)
×
3563
                return -ENOMEM;
3564

3565
        r = watchdog_setup_pretimeout_governor(governor);
×
3566
        if (r < 0)
×
3567
                return r;
3568

3569
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3570
}
3571

3572
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
×
3573
        _cleanup_free_ char *p = NULL;
×
3574
        int r;
×
3575

3576
        assert(m);
×
3577

3578
        if (MANAGER_IS_USER(m))
×
3579
                return 0;
3580

3581
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3582
                return 0;
3583

3584
        p = strdup(governor);
×
3585
        if (!p)
×
3586
                return -ENOMEM;
3587

3588
        r = watchdog_setup_pretimeout_governor(governor);
×
3589
        if (r < 0)
×
3590
                return r;
3591

3592
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3593
}
3594

3595
int manager_reload(Manager *m) {
66✔
3596
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
66✔
3597
        _cleanup_fdset_free_ FDSet *fds = NULL;
×
3598
        _cleanup_fclose_ FILE *f = NULL;
66✔
3599
        int r;
66✔
3600

3601
        assert(m);
66✔
3602

3603
        r = manager_open_serialization(m, &f);
66✔
3604
        if (r < 0)
66✔
3605
                return log_error_errno(r, "Failed to create serialization file: %m");
×
3606

3607
        fds = fdset_new();
66✔
3608
        if (!fds)
66✔
3609
                return log_oom();
×
3610

3611
        /* We are officially in reload mode from here on. */
3612
        reloading = manager_reloading_start(m);
66✔
3613

3614
        r = manager_serialize(m, f, fds, false);
66✔
3615
        if (r < 0)
66✔
3616
                return r;
3617

3618
        r = finish_serialization_file(f);
66✔
3619
        if (r < 0)
66✔
3620
                return log_error_errno(r, "Failed to finish serialization: %m");
×
3621

3622
        /* 💀 This is the point of no return, from here on there is no way back. 💀 */
3623
        reloading = NULL;
66✔
3624

3625
        bus_manager_send_reloading(m, true);
66✔
3626

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

3631
        manager_clear_jobs_and_units(m);
66✔
3632
        lookup_paths_flush_generator(&m->lookup_paths);
66✔
3633
        exec_shared_runtime_vacuum(m);
66✔
3634
        dynamic_user_vacuum(m, false);
66✔
3635
        m->uid_refs = hashmap_free(m->uid_refs);
66✔
3636
        m->gid_refs = hashmap_free(m->gid_refs);
66✔
3637

3638
        (void) manager_run_environment_generators(m);
66✔
3639
        (void) manager_run_generators(m);
66✔
3640

3641
        /* We flushed out generated files, for which we don't watch mtime, so we should flush the old map. */
3642
        manager_free_unit_name_maps(m);
66✔
3643
        m->unit_file_state_outdated = false;
66✔
3644

3645
        /* First, enumerate what we can from kernel and suchlike */
3646
        manager_enumerate_perpetual(m);
66✔
3647
        manager_enumerate(m);
66✔
3648

3649
        /* Second, deserialize our stored data */
3650
        r = manager_deserialize(m, f, fds);
66✔
3651
        if (r < 0)
66✔
3652
                log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
×
3653

3654
        /* We don't need the serialization anymore */
3655
        f = safe_fclose(f);
66✔
3656

3657
        /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3658
        (void) manager_setup_notify(m);
66✔
3659
        (void) manager_setup_user_lookup_fd(m);
66✔
3660
        (void) manager_setup_handoff_timestamp_fd(m);
66✔
3661
        (void) manager_setup_pidref_transport_fd(m);
66✔
3662

3663
        /* Clean up deserialized bus track information. They're never consumed during reload (as opposed to
3664
         * reexec) since we do not disconnect from the bus. */
3665
        m->subscribed_as_strv = strv_free(m->subscribed_as_strv);
66✔
3666
        m->deserialized_bus_id = SD_ID128_NULL;
66✔
3667

3668
        /* Third, fire things up! */
3669
        manager_coldplug(m);
66✔
3670

3671
        /* Clean up runtime objects no longer referenced */
3672
        manager_vacuum(m);
66✔
3673

3674
        /* Consider the reload process complete now. */
3675
        assert(m->n_reloading > 0);
66✔
3676
        m->n_reloading--;
66✔
3677

3678
        manager_ready(m);
66✔
3679

3680
        m->send_reloading_done = true;
66✔
3681
        return 0;
66✔
3682
}
3683

3684
void manager_reset_failed(Manager *m) {
1✔
3685
        Unit *u;
1✔
3686

3687
        assert(m);
1✔
3688

3689
        HASHMAP_FOREACH(u, m->units)
267✔
3690
                unit_reset_failed(u);
266✔
3691

3692
        m->transactions_with_cycle = set_free(m->transactions_with_cycle);
1✔
3693
}
1✔
3694

3695
bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
×
3696
        Unit *u;
×
3697

3698
        assert(m);
×
3699
        assert(name);
×
3700

3701
        /* Returns true if the unit is inactive or going down */
3702
        u = manager_get_unit(m, name);
×
3703
        if (!u)
×
3704
                return true;
3705

3706
        return unit_inactive_or_pending(u);
×
3707
}
3708

3709
static void log_taint_string(Manager *m) {
3,406✔
3710
        assert(m);
3,406✔
3711

3712
        if (MANAGER_IS_USER(m) || m->taint_logged)
3,406✔
3713
                return;
3,406✔
3714

3715
        m->taint_logged = true; /* only check for taint once */
33✔
3716

3717
        _cleanup_free_ char *taint = taint_string();
66✔
3718
        if (isempty(taint))
33✔
3719
                return;
33✔
3720

3721
        log_struct(LOG_NOTICE,
×
3722
                   LOG_MESSAGE("System is tainted: %s", taint),
3723
                   LOG_ITEM("TAINT=%s", taint),
3724
                   LOG_MESSAGE_ID(SD_MESSAGE_TAINTED_STR));
3725
}
3726

3727
static void manager_notify_finished(Manager *m) {
198✔
3728
        usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
198✔
3729

3730
        if (MANAGER_IS_TEST_RUN(m))
198✔
3731
                return;
3732

3733
        if (MANAGER_IS_SYSTEM(m) && m->soft_reboots_count > 0) {
191✔
3734
                /* The soft-reboot case, where we only report data for the last reboot */
3735
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
×
3736
                total_usec = userspace_usec = usec_sub_unsigned(m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic,
×
3737
                                                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START].monotonic);
3738

3739
                log_struct(LOG_INFO,
×
3740
                           LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3741
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3742
                           LOG_MESSAGE("Soft-reboot finished in %s, counter is now at %u.",
3743
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC),
3744
                                       m->soft_reboots_count));
3745
        } else if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
191✔
3746
                char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
×
3747
                        = {};
3748
                char *p = buf;
×
3749
                size_t size = sizeof buf;
×
3750

3751
                /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3752
                 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
3753
                 * negative values. */
3754

3755
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
×
3756
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3757
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
×
3758
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
×
3759

3760
                if (firmware_usec > 0)
×
3761
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
3762
                if (loader_usec > 0)
×
3763
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3764

3765
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
×
3766

3767
                        /* The initrd case on bare-metal */
3768
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3769
                        initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
×
3770

3771
                        log_struct(LOG_INFO,
×
3772
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3773
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3774
                                   LOG_ITEM("INITRD_USEC="USEC_FMT, initrd_usec),
3775
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3776
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3777
                                               buf,
3778
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3779
                                               FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3780
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3781
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3782
                } else {
3783
                        /* The initrd-less case on bare-metal */
3784

3785
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3786
                        initrd_usec = 0;
×
3787

3788
                        log_struct(LOG_INFO,
×
3789
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3790
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3791
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3792
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3793
                                               buf,
3794
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3795
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3796
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3797
                }
3798
        } else {
3799
                /* The container and --user case */
3800
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
191✔
3801
                total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
191✔
3802

3803
                log_struct(LOG_INFO,
191✔
3804
                           LOG_MESSAGE_ID(SD_MESSAGE_USER_STARTUP_FINISHED_STR),
3805
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3806
                           LOG_MESSAGE("Startup finished in %s.",
3807
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3808
        }
3809

3810
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
191✔
3811

3812
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
191✔
3813
                watchdog_report_if_missing();
×
3814

3815
        log_taint_string(m);
191✔
3816
}
3817

3818
static void manager_send_ready_on_basic_target(Manager *m) {
3,215✔
3819
        int r;
3,215✔
3820

3821
        assert(m);
3,215✔
3822

3823
        /* We send READY=1 on reaching basic.target only when running in --user mode. */
3824
        if (!MANAGER_IS_USER(m) || m->ready_sent)
3,215✔
3825
                return;
3826

3827
        r = sd_notify(/* unset_environment= */ false,
230✔
3828
                      "READY=1\n"
3829
                      "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3830
        if (r < 0)
230✔
3831
                log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
×
3832

3833
        m->ready_sent = true;
230✔
3834
        m->status_ready = false;
230✔
3835
}
3836

3837
static void manager_send_ready_on_idle(Manager *m) {
409✔
3838
        int r;
409✔
3839

3840
        assert(m);
409✔
3841

3842
        /* Skip the notification if nothing changed. */
3843
        if (m->ready_sent && m->status_ready)
409✔
3844
                return;
3845

3846
        /* Note that for user managers, we might have already sent READY=1 in manager_send_ready_user_scope().
3847
         * But we still need to flush STATUS=. The second READY=1 will be treated as a noop so it doesn't
3848
         * hurt to send it twice. */
3849
        r = sd_notify(/* unset_environment= */ false,
231✔
3850
                      "READY=1\n"
3851
                      "STATUS=Ready.");
3852
        if (r < 0)
231✔
3853
                log_full_errno(m->ready_sent ? LOG_DEBUG : LOG_WARNING, r,
×
3854
                               "Failed to send readiness notification, ignoring: %m");
3855

3856
        m->ready_sent = m->status_ready = true;
231✔
3857
}
3858

3859
static void manager_check_basic_target(Manager *m) {
17,868✔
3860
        Unit *u;
17,868✔
3861

3862
        assert(m);
17,868✔
3863

3864
        /* Small shortcut */
3865
        if (m->ready_sent && m->taint_logged)
17,868✔
3866
                return;
3867

3868
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
17,868✔
3869
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
17,868✔
3870
                return;
14,653✔
3871

3872
        /* For user managers, send out READY=1 as soon as we reach basic.target */
3873
        manager_send_ready_on_basic_target(m);
3,215✔
3874

3875
        /* Log the taint string as soon as we reach basic.target */
3876
        log_taint_string(m);
3,215✔
3877
}
3878

3879
void manager_check_finished(Manager *m) {
18,078✔
3880
        assert(m);
18,078✔
3881

3882
        if (MANAGER_IS_RELOADING(m))
18,078✔
3883
                return;
3884

3885
        /* Verify that we have entered the event loop already, and not left it again. */
3886
        if (!MANAGER_IS_RUNNING(m))
18,078✔
3887
                return;
3888

3889
        manager_check_basic_target(m);
17,868✔
3890

3891
        if (!hashmap_isempty(m->jobs)) {
17,868✔
3892
                if (m->jobs_in_progress_event_source)
17,459✔
3893
                        /* Ignore any failure, this is only for feedback */
3894
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
3,962✔
3895
                                                        manager_watch_jobs_next_time(m));
3,962✔
3896
                return;
17,459✔
3897
        }
3898

3899
        /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
3900
           kill the hashmap if it is relatively large. */
3901
        if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
409✔
3902
                m->jobs = hashmap_free(m->jobs);
200✔
3903

3904
        manager_send_ready_on_idle(m);
409✔
3905

3906
        /* Notify Type=idle units that we are done now */
3907
        manager_close_idle_pipe(m);
409✔
3908

3909
        if (MANAGER_IS_FINISHED(m))
409✔
3910
                return;
3911

3912
        manager_flip_auto_status(m, false, "boot finished");
198✔
3913

3914
        /* Turn off confirm spawn now */
3915
        m->confirm_spawn = NULL;
198✔
3916

3917
        /* No need to update ask password status when we're going non-interactive */
3918
        manager_close_ask_password(m);
198✔
3919

3920
        /* This is no longer the first boot */
3921
        manager_set_first_boot(m, false);
198✔
3922

3923
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
198✔
3924

3925
        manager_notify_finished(m);
198✔
3926

3927
        manager_invalidate_startup_units(m);
198✔
3928
}
3929

3930
void manager_send_reloading(Manager *m) {
105✔
3931
        assert(m);
105✔
3932

3933
        /* Let whoever invoked us know that we are now reloading */
3934
        (void) notify_reloading_full(/* status= */ NULL);
105✔
3935

3936
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
3937
        m->ready_sent = false;
105✔
3938
}
105✔
3939

3940
static bool generator_path_any(char * const *paths) {
1,112✔
3941

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

3944
        STRV_FOREACH(i, paths) {
4,448✔
3945
                if (access(*i, F_OK) >= 0)
4,448✔
3946
                        return true;
3947
                if (errno != ENOENT)
3,336✔
3948
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
3,336✔
3949
        }
3950

3951
        return false;
3952
}
3953

3954
static int manager_run_environment_generators(Manager *m) {
828✔
3955
        _cleanup_strv_free_ char **paths = NULL;
828✔
3956
        int r;
828✔
3957

3958
        assert(m);
828✔
3959

3960
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
828✔
3961
                return 0;
3962

3963
        paths = env_generator_binary_paths(m->runtime_scope);
801✔
3964
        if (!paths)
801✔
3965
                return log_oom();
×
3966

3967
        if (!generator_path_any(paths))
801✔
3968
                return 0;
3969

3970
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
801✔
3971
        void *args[_STDOUT_CONSUME_MAX] = {
801✔
3972
                [STDOUT_GENERATE] = &tmp,
3973
                [STDOUT_COLLECT]  = &tmp,
3974
                [STDOUT_CONSUME]  = &m->transient_environment,
801✔
3975
        };
3976

3977
        WITH_UMASK(0022)
1,602✔
3978
                r = execute_directories(
801✔
3979
                                "environment-generators",
3980
                                (const char* const*) paths,
3981
                                DEFAULT_TIMEOUT_USEC,
3982
                                gather_environment,
3983
                                args,
3984
                                /* argv[]= */ NULL,
3985
                                m->transient_environment,
3986
                                EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
3987
        return r;
801✔
3988
}
3989

3990
static int build_generator_environment(Manager *m, char ***ret) {
225✔
3991
        _cleanup_strv_free_ char **nl = NULL;
225✔
3992
        Virtualization v;
225✔
3993
        ConfidentialVirtualization cv;
225✔
3994
        int r;
225✔
3995

3996
        assert(m);
225✔
3997
        assert(ret);
225✔
3998

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

4003
        nl = strv_copy(m->transient_environment);
225✔
4004
        if (!nl)
225✔
4005
                return -ENOMEM;
4006

4007
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
225✔
4008
        if (r < 0)
225✔
4009
                return r;
4010

4011
        if (MANAGER_IS_SYSTEM(m)) {
225✔
4012
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
4013
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
4014
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
4015
                 * same results (hopefully). */
4016
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
4017
                if (r < 0)
×
4018
                        return r;
4019

4020
                if (m->soft_reboots_count > 0) {
×
4021
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
4022
                        if (r < 0)
×
4023
                                return r;
4024
                }
4025

4026
                if (m->first_boot >= 0) {
×
4027
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4028
                        if (r < 0)
×
4029
                                return r;
4030
                }
4031
        }
4032

4033
        v = detect_virtualization();
225✔
4034
        if (v < 0)
225✔
4035
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4036
        else if (v > 0) {
225✔
4037
                const char *s;
225✔
4038

4039
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
1,125✔
4040
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4041
                             virtualization_to_string(v));
4042

4043
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
225✔
4044
                if (r < 0)
225✔
4045
                        return r;
4046
        }
4047

4048
        cv = detect_confidential_virtualization();
225✔
4049
        if (cv < 0)
225✔
4050
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4051
        else if (cv > 0) {
225✔
4052
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4053
                if (r < 0)
×
4054
                        return r;
4055
        }
4056

4057
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
225✔
4058
        if (r < 0)
225✔
4059
                return r;
4060

4061
        *ret = TAKE_PTR(nl);
225✔
4062
        return 0;
225✔
4063
}
4064

4065
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
225✔
4066
        _cleanup_strv_free_ char **ge = NULL;
225✔
4067
        int r;
225✔
4068

4069
        assert(m);
225✔
4070

4071
        r = build_generator_environment(m, &ge);
225✔
4072
        if (r < 0)
225✔
4073
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4074

4075
        if (remount_ro) {
225✔
4076
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4077
                 * checks whether it is read-only to detect containerized execution environments. We leave
4078
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4079
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4080
                 */
4081
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4082
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4083
                if (r < 0)
×
4084
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4085
        }
4086

4087
        const char *argv[] = {
225✔
4088
                NULL, /* Leave this empty, execute_directory() will fill something in */
4089
                m->lookup_paths.generator,
225✔
4090
                m->lookup_paths.generator_early,
225✔
4091
                m->lookup_paths.generator_late,
225✔
4092
                NULL,
4093
        };
4094

4095
        BLOCK_WITH_UMASK(0022);
450✔
4096
        return execute_directories(
225✔
4097
                        "generators",
4098
                        (const char* const*) paths,
4099
                        DEFAULT_TIMEOUT_USEC,
4100
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4101
                        (char**) argv,
4102
                        ge,
4103
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4104
}
4105

4106
static int manager_run_generators(Manager *m) {
828✔
4107
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
828✔
4108
        _cleanup_strv_free_ char **paths = NULL;
828✔
4109
        int r;
828✔
4110

4111
        assert(m);
828✔
4112

4113
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
828✔
4114
                return 0;
4115

4116
        paths = generator_binary_paths(m->runtime_scope);
311✔
4117
        if (!paths)
311✔
4118
                return log_oom();
×
4119

4120
        if (!generator_path_any(paths))
311✔
4121
                return 0;
4122

4123
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
311✔
4124
        if (r < 0) {
311✔
4125
                log_error_errno(r, "Failed to create generator directories: %m");
×
4126
                goto finish;
×
4127
        }
4128

4129
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4130
         * we are the user manager, let's just execute the generators directly. We might not have the
4131
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4132
         */
4133
        if (MANAGER_IS_USER(m)) {
311✔
4134
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
225✔
4135
                goto finish;
225✔
4136
        }
4137

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

4143
        r = pidref_safe_fork("(sd-gens)", flags, /* ret= */ NULL);
86✔
4144
        if (r == 0) {
86✔
4145
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4146
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4147
        }
4148
        if (r < 0) {
86✔
4149
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4150
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4151
                        goto finish;
×
4152
                }
4153

4154
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4155
                 * seccomp or without capability.
4156
                 *
4157
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4158
                 *
4159
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4160
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4161
                 * https://github.com/systemd/systemd/issues/28901.
4162
                 */
4163
                log_debug_errno(r,
×
4164
                                "Failed to fork off sandboxing environment for executing generators. "
4165
                                "Falling back to execute generators without sandboxing: %m");
4166
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4167
        }
4168

4169
finish:
86✔
4170
        lookup_paths_trim_generator(&m->lookup_paths);
311✔
4171
        return r;
4172
}
4173

4174
int manager_transient_environment_add(Manager *m, char **plus) {
311✔
4175
        char **a;
311✔
4176

4177
        assert(m);
311✔
4178

4179
        if (strv_isempty(plus))
311✔
4180
                return 0;
311✔
4181

4182
        a = strv_env_merge(m->transient_environment, plus);
86✔
4183
        if (!a)
86✔
4184
                return log_oom();
×
4185

4186
        sanitize_environment(a);
86✔
4187

4188
        return strv_free_and_replace(m->transient_environment, a);
86✔
4189
}
4190

4191
int manager_client_environment_modify(
193✔
4192
                Manager *m,
4193
                char **minus,
4194
                char **plus) {
4195

4196
        char **a = NULL, **b = NULL, **l;
193✔
4197

4198
        assert(m);
193✔
4199

4200
        if (strv_isempty(minus) && strv_isempty(plus))
193✔
4201
                return 0;
4202

4203
        l = m->client_environment;
193✔
4204

4205
        if (!strv_isempty(minus)) {
193✔
4206
                a = strv_env_delete(l, 1, minus);
1✔
4207
                if (!a)
1✔
4208
                        return -ENOMEM;
4209

4210
                l = a;
4211
        }
4212

4213
        if (!strv_isempty(plus)) {
193✔
4214
                b = strv_env_merge(l, plus);
192✔
4215
                if (!b) {
192✔
4216
                        strv_free(a);
×
4217
                        return -ENOMEM;
×
4218
                }
4219

4220
                l = b;
4221
        }
4222

4223
        if (m->client_environment != l)
193✔
4224
                strv_free(m->client_environment);
193✔
4225

4226
        if (a != l)
193✔
4227
                strv_free(a);
192✔
4228
        if (b != l)
193✔
4229
                strv_free(b);
1✔
4230

4231
        m->client_environment = sanitize_environment(l);
193✔
4232
        return 0;
193✔
4233
}
4234

4235
int manager_get_effective_environment(Manager *m, char ***ret) {
23,197✔
4236
        char **l;
23,197✔
4237

4238
        assert(m);
23,197✔
4239
        assert(ret);
23,197✔
4240

4241
        l = strv_env_merge(m->transient_environment, m->client_environment);
23,197✔
4242
        if (!l)
23,197✔
4243
                return -ENOMEM;
4244

4245
        *ret = l;
23,197✔
4246
        return 0;
23,197✔
4247
}
4248

4249
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
311✔
4250
        _cleanup_free_ char *label = NULL;
311✔
4251
        struct rlimit *rlimit[_RLIMIT_MAX];
311✔
4252
        int r;
311✔
4253

4254
        assert(m);
311✔
4255
        assert(defaults);
311✔
4256

4257
        if (streq_ptr(defaults->smack_process_label, "/"))
311✔
4258
                label = NULL;
4259
        else  {
4260
                const char *l = defaults->smack_process_label;
311✔
4261
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4262
                if (!l)
4263
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4264
#endif
4265
                if (l) {
311✔
4266
                        label = strdup(l);
×
4267
                        if (!label)
×
4268
                                return -ENOMEM;
4269
                } else
4270
                        label = NULL;
4271
        }
4272

4273
        r = rlimit_copy_all(rlimit, defaults->rlimit);
311✔
4274
        if (r < 0)
311✔
4275
                return r;
4276

4277
        m->defaults.std_output = defaults->std_output;
311✔
4278
        m->defaults.std_error = defaults->std_error;
311✔
4279

4280
        m->defaults.restart_usec = defaults->restart_usec;
311✔
4281
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
311✔
4282
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
311✔
4283
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
311✔
4284
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
311✔
4285
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
311✔
4286

4287
        m->defaults.restrict_suid_sgid = defaults->restrict_suid_sgid;
311✔
4288

4289
        m->defaults.start_limit = defaults->start_limit;
311✔
4290

4291
        m->defaults.memory_accounting = defaults->memory_accounting;
311✔
4292
        m->defaults.io_accounting = defaults->io_accounting;
311✔
4293
        m->defaults.tasks_accounting = defaults->tasks_accounting;
311✔
4294
        m->defaults.ip_accounting = defaults->ip_accounting;
311✔
4295

4296
        m->defaults.tasks_max = defaults->tasks_max;
311✔
4297
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
311✔
4298

4299
        m->defaults.oom_policy = defaults->oom_policy;
311✔
4300
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
311✔
4301
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
311✔
4302

4303
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
311✔
4304
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
311✔
4305

4306
        m->defaults.memory_zswap_writeback = defaults->memory_zswap_writeback;
311✔
4307

4308
        free_and_replace(m->defaults.smack_process_label, label);
311✔
4309
        rlimit_free_all(m->defaults.rlimit);
311✔
4310
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
311✔
4311

4312
        return 0;
311✔
4313
}
4314

4315
void manager_recheck_dbus(Manager *m) {
98,657✔
4316
        assert(m);
98,657✔
4317

4318
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4319
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4320
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4321
         * of the system instance, while in the user instance we can assume it's already there. */
4322

4323
        if (MANAGER_IS_RELOADING(m))
98,657✔
4324
                return; /* don't check while we are reloading… */
4325

4326
        if (manager_dbus_is_running(m, false)) {
85,750✔
4327
                (void) bus_init_api(m);
10,220✔
4328

4329
                if (MANAGER_IS_SYSTEM(m))
10,220✔
4330
                        (void) bus_init_system(m);
4,239✔
4331
        } else {
4332
                bus_done_api(m);
75,530✔
4333

4334
                if (MANAGER_IS_SYSTEM(m))
75,530✔
4335
                        bus_done_system(m);
10,357✔
4336
        }
4337
}
4338

4339
static bool manager_journal_is_running(Manager *m) {
16,646✔
4340
        Unit *u;
16,646✔
4341

4342
        assert(m);
16,646✔
4343

4344
        if (MANAGER_IS_TEST_RUN(m))
16,646✔
4345
                return false;
4346

4347
        /* If we are the user manager we can safely assume that the journal is up */
4348
        if (!MANAGER_IS_SYSTEM(m))
16,646✔
4349
                return true;
4350

4351
        /* Check that the socket is not only up, but in RUNNING state */
4352
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
15,911✔
4353
        if (!u)
15,911✔
4354
                return false;
4355
        if (SOCKET(u)->state != SOCKET_RUNNING)
15,911✔
4356
                return false;
4357

4358
        /* Similar, check if the daemon itself is fully up, too */
4359
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
12,322✔
4360
        if (!u)
12,322✔
4361
                return false;
4362
        if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)) || SERVICE(u)->state == SERVICE_EXITED)
12,322✔
4363
                return false;
507✔
4364

4365
        return true;
4366
}
4367

4368
void disable_printk_ratelimit(void) {
17✔
4369
        /* Disable kernel's printk ratelimit.
4370
         *
4371
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4372
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4373
         * setting takes precedence. */
4374
        int r;
17✔
4375

4376
        r = sysctl_write("kernel/printk_devkmsg", "on");
17✔
4377
        if (r < 0)
17✔
4378
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4379
}
17✔
4380

4381
void manager_recheck_journal(Manager *m) {
98,657✔
4382

4383
        assert(m);
98,657✔
4384

4385
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4386
        if (getpid_cached() != 1)
98,657✔
4387
                return;
4388

4389
        /* Don't check this while we are reloading, things might still change */
4390
        if (MANAGER_IS_RELOADING(m))
22,613✔
4391
                return;
4392

4393
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4394
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4395
         * might trigger an activation ourselves we can't fulfill. */
4396
        log_set_prohibit_ipc(!manager_journal_is_running(m));
14,096✔
4397
        log_open();
14,096✔
4398
}
4399

4400
static ShowStatus manager_get_show_status(Manager *m) {
12,047✔
4401
        assert(m);
12,047✔
4402

4403
        if (MANAGER_IS_USER(m))
12,047✔
4404
                return _SHOW_STATUS_INVALID;
4405

4406
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
12,046✔
4407
                return m->show_status_overridden;
4408

4409
        return m->show_status;
12,046✔
4410
}
4411

4412
bool manager_get_show_status_on(Manager *m) {
12,045✔
4413
        assert(m);
12,045✔
4414

4415
        return show_status_on(manager_get_show_status(m));
12,045✔
4416
}
4417

4418
static void set_show_status_marker(bool b) {
62✔
4419
        if (b)
62✔
4420
                (void) touch("/run/systemd/show-status");
×
4421
        else
4422
                (void) unlink("/run/systemd/show-status");
62✔
4423
}
62✔
4424

4425
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
311✔
4426
        assert(m);
311✔
4427
        assert(reason);
311✔
4428
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
311✔
4429

4430
        if (MANAGER_IS_USER(m))
311✔
4431
                return;
4432

4433
        if (mode == m->show_status)
86✔
4434
                return;
4435

4436
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
52✔
4437
                bool enabled;
52✔
4438

4439
                enabled = show_status_on(mode);
52✔
4440
                log_debug("%s (%s) showing of status (%s).",
104✔
4441
                          enabled ? "Enabling" : "Disabling",
4442
                          strna(show_status_to_string(mode)),
4443
                          reason);
4444

4445
                set_show_status_marker(enabled);
52✔
4446
        }
4447

4448
        m->show_status = mode;
52✔
4449
}
4450

4451
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
10✔
4452
        assert(m);
10✔
4453
        assert(mode < _SHOW_STATUS_MAX);
10✔
4454

4455
        if (MANAGER_IS_USER(m))
10✔
4456
                return;
4457

4458
        if (mode == m->show_status_overridden)
10✔
4459
                return;
4460

4461
        m->show_status_overridden = mode;
10✔
4462

4463
        if (mode == _SHOW_STATUS_INVALID)
10✔
4464
                mode = m->show_status;
5✔
4465

4466
        log_debug("%s (%s) showing of status (%s).",
15✔
4467
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4468
                  strna(show_status_to_string(mode)),
4469
                  reason);
4470

4471
        set_show_status_marker(show_status_on(mode));
10✔
4472
}
4473

4474
const char* manager_get_confirm_spawn(Manager *m) {
2,563✔
4475
        static int last_errno = 0;
2,563✔
4476
        struct stat st;
2,563✔
4477
        int r;
2,563✔
4478

4479
        assert(m);
2,563✔
4480

4481
        /* Here's the deal: we want to test the validity of the console but don't want
4482
         * PID1 to go through the whole console process which might block. But we also
4483
         * want to warn the user only once if something is wrong with the console so we
4484
         * cannot do the sanity checks after spawning our children. So here we simply do
4485
         * really basic tests to hopefully trap common errors.
4486
         *
4487
         * If the console suddenly disappear at the time our children will really it
4488
         * then they will simply fail to acquire it and a positive answer will be
4489
         * assumed. New children will fall back to /dev/console though.
4490
         *
4491
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4492
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4493
         * reason the configured console is not ready, we fall back to the default
4494
         * console. */
4495

4496
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
2,563✔
4497
                return m->confirm_spawn;
2,563✔
4498

4499
        if (stat(m->confirm_spawn, &st) < 0) {
×
4500
                r = -errno;
×
4501
                goto fail;
×
4502
        }
4503

4504
        if (!S_ISCHR(st.st_mode)) {
×
4505
                r = -ENOTTY;
×
4506
                goto fail;
×
4507
        }
4508

4509
        last_errno = 0;
×
4510
        return m->confirm_spawn;
×
4511

4512
fail:
×
4513
        if (last_errno != r)
×
4514
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4515

4516
        return "/dev/console";
4517
}
4518

4519
void manager_set_first_boot(Manager *m, bool b) {
443✔
4520
        assert(m);
443✔
4521

4522
        if (!MANAGER_IS_SYSTEM(m))
443✔
4523
                return;
4524

4525
        if (m->first_boot != (int) b) {
52✔
4526
                if (b)
52✔
4527
                        (void) touch("/run/systemd/first-boot");
18✔
4528
                else
4529
                        (void) unlink("/run/systemd/first-boot");
34✔
4530
        }
4531

4532
        m->first_boot = b;
52✔
4533
}
4534

4535
void manager_disable_confirm_spawn(void) {
×
4536
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4537
}
×
4538

4539
static bool manager_should_show_status(Manager *m, StatusType type) {
18,464✔
4540
        assert(m);
18,464✔
4541

4542
        if (!MANAGER_IS_SYSTEM(m))
18,464✔
4543
                return false;
4544

4545
        if (m->no_console_output)
8,102✔
4546
                return false;
4547

4548
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
8,030✔
4549
                return false;
4550

4551
        /* If we cannot find out the status properly, just proceed. */
4552
        if (type < STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
8,030✔
4553
                return false;
4554

4555
        if (type >= STATUS_TYPE_NOTICE && manager_get_show_status(m) != SHOW_STATUS_NO)
8,030✔
4556
                return true;
4557

4558
        return manager_get_show_status_on(m);
8,028✔
4559
}
4560

4561
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
18,464✔
4562
        va_list ap;
18,464✔
4563

4564
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4565

4566
        if (m && !manager_should_show_status(m, type))
18,464✔
4567
                return;
18,462✔
4568

4569
        /* XXX We should totally drop the check for ephemeral here
4570
         * and thus effectively make 'Type=idle' pointless. */
4571
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
2✔
4572
                return;
4573

4574
        va_start(ap, format);
2✔
4575
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
4✔
4576
        va_end(ap);
2✔
4577
}
4578

4579
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
23,506✔
4580
        assert(m);
23,506✔
4581
        assert(path);
23,506✔
4582
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
23,506✔
4583

4584
        if (path_equal(path, "/"))
23,506✔
4585
                path = "";
968✔
4586

4587
        return hashmap_get(m->units_needing_mounts_for[t], path);
23,506✔
4588
}
4589

4590
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
203,776✔
4591
        unsigned size;
203,776✔
4592
        int r;
203,776✔
4593

4594
        assert(m);
203,776✔
4595
        assert(u->manager == m);
203,776✔
4596

4597
        size = set_size(m->failed_units);
203,776✔
4598

4599
        if (failed) {
203,776✔
4600
                r = set_ensure_put(&m->failed_units, NULL, u);
290✔
4601
                if (r < 0)
290✔
4602
                        return log_oom();
×
4603
        } else
4604
                (void) set_remove(m->failed_units, u);
203,486✔
4605

4606
        if (set_size(m->failed_units) != size)
203,776✔
4607
                bus_manager_send_change_signal(m);
580✔
4608

4609
        return 0;
4610
}
4611

4612
ManagerState manager_state(Manager *m) {
523,724✔
4613
        Unit *u;
523,724✔
4614

4615
        assert(m);
523,724✔
4616

4617
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4618
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
523,724✔
4619
        if (u && unit_active_or_pending(u))
523,724✔
4620
                return MANAGER_STOPPING;
4621

4622
        /* Did we ever finish booting? If not then we are still starting up */
4623
        if (!MANAGER_IS_FINISHED(m)) {
401,282✔
4624

4625
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
362,279✔
4626
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
362,279✔
4627
                        return MANAGER_INITIALIZING;
291,307✔
4628

4629
                return MANAGER_STARTING;
4630
        }
4631

4632
        if (MANAGER_IS_SYSTEM(m)) {
39,003✔
4633
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4634
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
×
4635
                if (u && unit_active_or_pending(u))
×
4636
                        return MANAGER_MAINTENANCE;
4637

4638
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
×
4639
                if (u && unit_active_or_pending(u))
×
4640
                        return MANAGER_MAINTENANCE;
4641
        }
4642

4643
        /* Are there any failed units or ordering cycles? If so, we are in degraded mode */
4644
        if (!set_isempty(m->failed_units) || !set_isempty(m->transactions_with_cycle))
39,003✔
4645
                return MANAGER_DEGRADED;
3,587✔
4646

4647
        return MANAGER_RUNNING;
4648
}
4649

4650
static void manager_unref_uid_internal(
1,040✔
4651
                Hashmap *uid_refs,
4652
                uid_t uid,
4653
                bool destroy_now,
4654
                int (*_clean_ipc)(uid_t uid)) {
4655

4656
        uint32_t c, n;
1,040✔
4657

4658
        assert(uid_is_valid(uid));
1,040✔
4659
        assert(_clean_ipc);
1,040✔
4660

4661
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4662
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4663
         *
4664
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4665
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4666
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4667
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4668
         * counter drops to 0 again. */
4669

4670
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
1,040✔
4671
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
1,040✔
4672

4673
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
1,040✔
4674
                return;
4675

4676
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
803✔
4677

4678
        n = c & ~DESTROY_IPC_FLAG;
803✔
4679
        assert(n > 0);
803✔
4680
        n--;
803✔
4681

4682
        if (destroy_now && n == 0) {
803✔
4683
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
219✔
4684

4685
                if (c & DESTROY_IPC_FLAG) {
219✔
4686
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
117✔
4687
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4688
                                  uid);
4689
                        (void) _clean_ipc(uid);
78✔
4690
                }
4691
        } else {
4692
                c = n | (c & DESTROY_IPC_FLAG);
584✔
4693
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
584✔
4694
        }
4695
}
4696

4697
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
518✔
4698
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
518✔
4699
}
518✔
4700

4701
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
522✔
4702
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
522✔
4703
}
522✔
4704

4705
static int manager_ref_uid_internal(
1,040✔
4706
                Hashmap **uid_refs,
4707
                uid_t uid,
4708
                bool clean_ipc) {
4709

4710
        uint32_t c, n;
1,040✔
4711
        int r;
1,040✔
4712

4713
        assert(uid_refs);
1,040✔
4714
        assert(uid_is_valid(uid));
1,040✔
4715

4716
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4717
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4718
         * rules. */
4719

4720
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
1,040✔
4721
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
1,040✔
4722

4723
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
1,040✔
4724
                return 0;
4725

4726
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
803✔
4727
        if (r < 0)
803✔
4728
                return r;
4729

4730
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
803✔
4731

4732
        n = c & ~DESTROY_IPC_FLAG;
803✔
4733
        n++;
803✔
4734

4735
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
803✔
4736
                return -EOVERFLOW;
4737

4738
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
803✔
4739

4740
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
803✔
4741
}
4742

4743
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
518✔
4744
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
518✔
4745
}
4746

4747
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
522✔
4748
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
522✔
4749
}
4750

4751
static void manager_vacuum_uid_refs_internal(
1,656✔
4752
                Hashmap *uid_refs,
4753
                int (*_clean_ipc)(uid_t uid)) {
4754

4755
        void *p, *k;
1,656✔
4756

4757
        assert(_clean_ipc);
1,656✔
4758

4759
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
3,604✔
4760
                uint32_t c, n;
292✔
4761
                uid_t uid;
292✔
4762

4763
                uid = PTR_TO_UID(k);
292✔
4764
                c = PTR_TO_UINT32(p);
292✔
4765

4766
                n = c & ~DESTROY_IPC_FLAG;
292✔
4767
                if (n > 0)
292✔
4768
                        continue;
292✔
4769

4770
                if (c & DESTROY_IPC_FLAG) {
×
4771
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4772
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4773
                                  uid);
4774
                        (void) _clean_ipc(uid);
×
4775
                }
4776

4777
                assert_se(hashmap_remove(uid_refs, k) == p);
1,948✔
4778
        }
4779
}
1,656✔
4780

4781
static void manager_vacuum_uid_refs(Manager *m) {
828✔
4782
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
828✔
4783
}
828✔
4784

4785
static void manager_vacuum_gid_refs(Manager *m) {
828✔
4786
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
828✔
4787
}
828✔
4788

4789
static void manager_vacuum(Manager *m) {
828✔
4790
        assert(m);
828✔
4791

4792
        /* Release any dynamic users no longer referenced */
4793
        dynamic_user_vacuum(m, true);
828✔
4794

4795
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4796
        manager_vacuum_uid_refs(m);
828✔
4797
        manager_vacuum_gid_refs(m);
828✔
4798

4799
        /* Release any runtimes no longer referenced */
4800
        exec_shared_runtime_vacuum(m);
828✔
4801
}
828✔
4802

4803
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
300✔
4804
        struct buffer {
300✔
4805
                uid_t uid;
4806
                gid_t gid;
4807
                char unit_name[UNIT_NAME_MAX+1];
4808
        } _packed_ buffer;
4809

4810
        Manager *m = ASSERT_PTR(userdata);
300✔
4811
        ssize_t l;
300✔
4812
        size_t n;
300✔
4813
        Unit *u;
300✔
4814

4815
        assert(source);
300✔
4816

4817
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4818
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4819
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4820
         * reference counter drops to 0. */
4821

4822
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
300✔
4823
        if (l < 0) {
300✔
4824
                if (ERRNO_IS_TRANSIENT(errno))
×
4825
                        return 0;
300✔
4826

4827
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4828
        }
4829

4830
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
300✔
4831
                log_warning("Received too short user lookup message, ignoring.");
×
4832
                return 0;
×
4833
        }
4834

4835
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
300✔
4836
                log_warning("Received too long user lookup message, ignoring.");
×
4837
                return 0;
×
4838
        }
4839

4840
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
300✔
4841
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4842
                return 0;
×
4843
        }
4844

4845
        n = (size_t) l - offsetof(struct buffer, unit_name);
300✔
4846
        if (memchr(buffer.unit_name, 0, n)) {
300✔
4847
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4848
                return 0;
×
4849
        }
4850

4851
        buffer.unit_name[n] = 0;
300✔
4852
        u = manager_get_unit(m, buffer.unit_name);
300✔
4853
        if (!u) {
300✔
4854
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4855
                return 0;
×
4856
        }
4857

4858
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
300✔
4859

4860
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
300✔
4861
        return 0;
4862
}
4863

4864
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2,535✔
4865
        Manager *m = ASSERT_PTR(userdata);
2,535✔
4866
        usec_t ts[2] = {};
2,535✔
4867
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
2,535✔
4868
        struct msghdr msghdr = {
2,535✔
4869
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
2,535✔
4870
                .msg_iovlen = 1,
4871
                .msg_control = &control,
4872
                .msg_controllen = sizeof(control),
4873
        };
4874
        ssize_t n;
2,535✔
4875

4876
        assert(source);
2,535✔
4877

4878
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2,535✔
4879
        if (ERRNO_IS_NEG_TRANSIENT(n))
2,535✔
4880
                return 0; /* Spurious wakeup, try again */
2,535✔
4881
        if (n == -ECHRNG) {
2,535✔
4882
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4883
                return 0;
×
4884
        }
4885
        if (n == -EXFULL) {
2,535✔
4886
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4887
                return 0;
×
4888
        }
4889
        if (n < 0)
2,535✔
4890
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
4891

4892
        cmsg_close_all(&msghdr);
2,535✔
4893

4894
        if (n != sizeof(ts)) {
2,535✔
4895
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
4896
                return 0;
×
4897
        }
4898

4899
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
2,535✔
4900
        if (!ucred || !pid_is_valid(ucred->pid)) {
2,535✔
4901
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
4902
                return 0;
×
4903
        }
4904

4905
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
2,535✔
4906

4907
        _cleanup_free_ Unit **units = NULL;
2,535✔
4908
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
2,535✔
4909
        if (n_units < 0) {
2,535✔
4910
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
4911
                return 0;
×
4912
        }
4913
        if (n_units == 0) {
2,535✔
4914
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
4915
                return 0;
×
4916
        }
4917

4918
        dual_timestamp dt = {
2,535✔
4919
                .realtime = ts[0],
2,535✔
4920
                .monotonic = ts[1],
2,535✔
4921
        };
4922

4923
        FOREACH_ARRAY(u, units, n_units) {
7,605✔
4924
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
5,070✔
4925
                        continue;
97✔
4926

4927
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
4,973✔
4928
        }
4929

4930
        return 0;
4931
}
4932

4933
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
4934
        Manager *m = ASSERT_PTR(userdata);
3✔
4935
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
3✔
4936
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
6✔
4937
        struct ucred *ucred = NULL;
3✔
4938
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
3✔
4939
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
3✔
4940
        struct msghdr msghdr = {
3✔
4941
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
3✔
4942
                .msg_iovlen = 1,
4943
                .msg_control = &control,
4944
                .msg_controllen = sizeof(control),
4945
        };
4946
        struct cmsghdr *cmsg;
3✔
4947
        ssize_t n;
3✔
4948
        int r;
3✔
4949

4950
        assert(source);
3✔
4951

4952
        /* Server expects:
4953
         * - Parent PID in ucreds enabled via SO_PASSCRED
4954
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
4955
         * - Child PIDFD in SCM_RIGHTS in message body
4956
         * - Child PID in message IOV
4957
         *
4958
         * SO_PASSPIDFD may not be supported by the kernel (it is supported since v6.5) so we fall back to
4959
         * using parent PID from ucreds and accept some raciness. */
4960
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
3✔
4961
        if (ERRNO_IS_NEG_TRANSIENT(n))
6✔
4962
                return 0; /* Spurious wakeup, try again */
4963
        if (n == -ECHRNG) {
3✔
4964
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4965
                return 0;
×
4966
        }
4967
        if (n == -EXFULL) {
3✔
4968
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4969
                return 0;
×
4970
        }
4971
        if (n < 0)
3✔
4972
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
4973

4974
        if (n != sizeof(child_pid)) {
3✔
4975
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
4976
                return 0;
×
4977
        }
4978

4979
        CMSG_FOREACH(cmsg, &msghdr) {
24✔
4980
                if (cmsg->cmsg_level != SOL_SOCKET)
9✔
4981
                        continue;
×
4982

4983
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
9✔
4984
                        assert(!ucred);
3✔
4985
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
3✔
4986
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
6✔
4987
                        assert(parent_pidfd < 0);
3✔
4988
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4989
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
3✔
4990
                        assert(child_pidfd < 0);
3✔
4991
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4992
                }
4993
        }
4994

4995
        /* Verify and set parent pidref. */
4996
        if (!ucred || !pid_is_valid(ucred->pid)) {
3✔
4997
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
4998
                return 0;
×
4999
        }
5000

5001
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
5002
        if (parent_pidfd >= 0)
3✔
5003
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
3✔
5004
        else
5005
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
5006
        if (r < 0) {
3✔
5007
                if (r == -ESRCH)
×
5008
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5009
                else
5010
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5011
                return 0;
×
5012
        }
5013

5014
        if (parent_pidref.pid != ucred->pid) {
3✔
5015
                assert(parent_pidref.fd >= 0);
×
5016
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
5017
                            parent_pidref.pid, ucred->pid);
5018
                return 0;
×
5019
        }
5020

5021
        /* Verify and set child pidref. */
5022
        if (!pid_is_valid(child_pid)) {
3✔
5023
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
5024
                return 0;
×
5025
        }
5026

5027
        /* Need to handle kernels without PIDFD support. */
5028
        if (child_pidfd >= 0)
3✔
5029
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
3✔
5030
        else
5031
                r = pidref_set_pid(&child_pidref, child_pid);
×
5032
        if (r < 0) {
3✔
5033
                if (r == -ESRCH)
×
5034
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5035
                else
5036
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5037
                return 0;
×
5038
        }
5039

5040
        if (child_pidref.pid != child_pid) {
3✔
5041
                assert(child_pidref.fd >= 0);
×
5042
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5043
                            child_pidref.pid, child_pid);
5044
                return 0;
×
5045
        }
5046

5047
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
3✔
5048

5049
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5050
         * Then fall back to finding cgroup of the child process. */
5051
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
3✔
5052
        if (!u)
3✔
5053
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5054
        if (!u) {
×
5055
                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);
×
5056
                return 0;
×
5057
        }
5058

5059
        if (!UNIT_VTABLE(u)->notify_pidref) {
3✔
5060
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5061
                return 0;
×
5062
        }
5063

5064
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
3✔
5065

5066
        return 0;
5067
}
5068

5069
void manager_ref_console(Manager *m) {
86✔
5070
        assert(m);
86✔
5071

5072
        m->n_on_console++;
86✔
5073
}
86✔
5074

5075
void manager_unref_console(Manager *m) {
86✔
5076

5077
        assert(m->n_on_console > 0);
86✔
5078
        m->n_on_console--;
86✔
5079

5080
        if (m->n_on_console == 0)
86✔
5081
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
72✔
5082
}
86✔
5083

5084
void manager_override_log_level(Manager *m, int level) {
4✔
5085
        _cleanup_free_ char *s = NULL;
8✔
5086
        assert(m);
4✔
5087

5088
        if (!m->log_level_overridden) {
4✔
5089
                m->original_log_level = log_get_max_level();
1✔
5090
                m->log_level_overridden = true;
1✔
5091
        }
5092

5093
        (void) log_level_to_string_alloc(level, &s);
4✔
5094
        log_info("Setting log level to %s.", strna(s));
4✔
5095

5096
        log_set_max_level(level);
4✔
5097
}
4✔
5098

5099
void manager_restore_original_log_level(Manager *m) {
×
5100
        _cleanup_free_ char *s = NULL;
×
5101
        assert(m);
×
5102

5103
        if (!m->log_level_overridden)
×
5104
                return;
×
5105

5106
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5107
        log_info("Restoring log level to original (%s).", strna(s));
×
5108

5109
        log_set_max_level(m->original_log_level);
×
5110
        m->log_level_overridden = false;
×
5111
}
5112

5113
void manager_override_log_target(Manager *m, LogTarget target) {
4✔
5114
        assert(m);
4✔
5115

5116
        if (!m->log_target_overridden) {
4✔
5117
                m->original_log_target = log_get_target();
1✔
5118
                m->log_target_overridden = true;
1✔
5119
        }
5120

5121
        log_info("Setting log target to %s.", log_target_to_string(target));
4✔
5122
        log_set_target(target);
4✔
5123
}
4✔
5124

5125
void manager_restore_original_log_target(Manager *m) {
×
5126
        assert(m);
×
5127

5128
        if (!m->log_target_overridden)
×
5129
                return;
5130

5131
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5132

5133
        log_set_target(m->original_log_target);
×
5134
        m->log_target_overridden = false;
×
5135
}
5136

5137
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
3,538✔
5138
        if (in_initrd() &&
3,538✔
5139
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
66✔
5140
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5141
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
66✔
5142
        return s;
5143
}
5144

5145
int manager_allocate_idle_pipe(Manager *m) {
1,915✔
5146
        int r;
1,915✔
5147

5148
        assert(m);
1,915✔
5149

5150
        if (m->idle_pipe[0] >= 0) {
1,915✔
5151
                assert(m->idle_pipe[1] >= 0);
827✔
5152
                assert(m->idle_pipe[2] >= 0);
827✔
5153
                assert(m->idle_pipe[3] >= 0);
827✔
5154
                return 0;
5155
        }
5156

5157
        assert(m->idle_pipe[1] < 0);
1,088✔
5158
        assert(m->idle_pipe[2] < 0);
1,088✔
5159
        assert(m->idle_pipe[3] < 0);
1,088✔
5160

5161
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
1,088✔
5162
        if (r < 0)
×
5163
                return r;
5164

5165
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
1,088✔
5166
        if (r < 0) {
×
5167
                safe_close_pair(m->idle_pipe + 0);
×
5168
                return r;
×
5169
        }
5170

5171
        return 1;
5172
}
5173

5174
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,267✔
5175
        assert(defaults);
1,267✔
5176
        assert(scope >= 0);
1,267✔
5177
        assert(scope < _RUNTIME_SCOPE_MAX);
1,267✔
5178

5179
        *defaults = (UnitDefaults) {
2,534✔
5180
                .std_output = EXEC_OUTPUT_JOURNAL,
5181
                .std_error = EXEC_OUTPUT_INHERIT,
5182
                .restart_usec = DEFAULT_RESTART_USEC,
5183
                .timeout_start_usec = manager_default_timeout(scope),
1,267✔
5184
                .timeout_stop_usec = manager_default_timeout(scope),
1,267✔
5185
                .timeout_abort_usec = manager_default_timeout(scope),
1,267✔
5186
                .timeout_abort_set = false,
5187
                .device_timeout_usec = manager_default_timeout(scope),
1,267✔
5188
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5189

5190
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5191
                .io_accounting = false,
5192
                .tasks_accounting = true,
5193
                .ip_accounting = false,
5194

5195
                .tasks_max = DEFAULT_TASKS_MAX,
5196
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5197

5198
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5199
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5200

5201
                .oom_policy = OOM_STOP,
5202
                .oom_score_adjust_set = false,
5203

5204
                .memory_zswap_writeback = true,
5205
        };
5206
}
1,267✔
5207

5208
void unit_defaults_done(UnitDefaults *defaults) {
1,267✔
5209
        assert(defaults);
1,267✔
5210

5211
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,267✔
5212
        rlimit_free_all(defaults->rlimit);
1,267✔
5213
}
1,267✔
5214

5215
LogTarget manager_get_executor_log_target(Manager *m) {
2,561✔
5216
        assert(m);
2,561✔
5217

5218
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5219
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
2,561✔
5220
                return LOG_TARGET_KMSG;
5221

5222
        return log_get_target();
2,132✔
5223
}
5224

5225
void manager_log_caller(Manager *manager, PidRef *caller, const char *method) {
98✔
5226
        _cleanup_free_ char *comm = NULL;
98✔
5227

5228
        assert(manager);
98✔
5229
        assert(method);
98✔
5230

5231
        if (!pidref_is_set(caller)) {
98✔
5232
                log_notice("%s requested from unknown client PID...", method);
×
5233
                return;
×
5234
        }
5235

5236
        (void) pidref_get_comm(caller, &comm);
98✔
5237
        Unit *caller_unit = manager_get_unit_by_pidref(manager, caller);
98✔
5238

5239
        log_notice("%s requested from client PID " PID_FMT "%s%s%s%s%s%s...",
98✔
5240
                   method, caller->pid,
5241
                   comm ? " ('" : "", strempty(comm), comm ? "')" : "",
5242
                   caller_unit ? " (unit " : "", caller_unit ? caller_unit->id : "", caller_unit ? ")" : "");
5243
}
5244

5245
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5246
        [MANAGER_INITIALIZING] = "initializing",
5247
        [MANAGER_STARTING]     = "starting",
5248
        [MANAGER_RUNNING]      = "running",
5249
        [MANAGER_DEGRADED]     = "degraded",
5250
        [MANAGER_MAINTENANCE]  = "maintenance",
5251
        [MANAGER_STOPPING]     = "stopping",
5252
};
5253

5254
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
82✔
5255

5256
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5257
        [MANAGER_OK]          = "ok",
5258
        [MANAGER_EXIT]        = "exit",
5259
        [MANAGER_RELOAD]      = "reload",
5260
        [MANAGER_REEXECUTE]   = "reexecute",
5261
        [MANAGER_REBOOT]      = "reboot",
5262
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5263
        [MANAGER_POWEROFF]    = "poweroff",
5264
        [MANAGER_HALT]        = "halt",
5265
        [MANAGER_KEXEC]       = "kexec",
5266
        [MANAGER_SWITCH_ROOT] = "switch-root",
5267
};
5268

5269
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
211✔
5270

5271
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5272
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5273
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5274
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5275
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5276
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5277
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5278
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5279
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5280
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5281
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5282
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5283
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5284
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5285
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5286
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5287
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5288
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5289
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5290
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5291
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5292
};
5293

5294
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
7,908✔
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