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

systemd / systemd / 16533846256

25 Jul 2025 07:44PM UTC coverage: 72.199% (+0.03%) from 72.165%
16533846256

push

github

bluca
bootctl: automatically set --graceful when running in chroot

Installing stuff in a chroot should not fail because efivars are
not available. When running in a container touching efivars is
completely disabled, but there are some cases (recovery) where
it is needed to touch them in a chroot, so don't disable them but
avoid failing the run instead.

1 of 3 new or added lines in 1 file covered. (33.33%)

223 existing lines in 36 files now uncovered.

302658 of 419200 relevant lines covered (72.2%)

732672.88 hits per line

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

79.8
/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-path.h"
16

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

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

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

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

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

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

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

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

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

145
        return usec_add(now(CLOCK_MONOTONIC), timeout);
4,624✔
146
}
147

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

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

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

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

161
        assert(m);
3,215✔
162

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

169
        if (m->jobs_in_progress_event_source)
3,215✔
170
                return;
171

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

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

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

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

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

UNCOV
204
        assert(m);
×
UNCOV
205
        assert(m->n_running_jobs > 0);
×
206

UNCOV
207
        manager_flip_auto_status(m, true, "delay");
×
208

UNCOV
209
        print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
×
210

UNCOV
211
        HASHMAP_FOREACH(j, m->jobs)
×
UNCOV
212
                if (j->state == JOB_RUNNING && counter++ == print_nr)
×
213
                        break;
214

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

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

UNCOV
225
        m->jobs_in_progress_iteration++;
×
226

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

UNCOV
231
        (void) job_get_timeout(j, &timeout);
×
232

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

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

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

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

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

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

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

281
                return -errno;
×
282
        }
283

284
        FOREACH_DIRENT_ALL(de, dir, return -errno) {
135✔
285
                if (!IN_SET(de->d_type, DT_REG, DT_UNKNOWN))
90✔
286
                        continue;
90✔
287

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

292
        return false;
293
}
294

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

299
        (void) flush_fd(fd);
45✔
300

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

306
        return 0;
45✔
307
}
308

309
static void manager_close_ask_password(Manager *m) {
900✔
310
        assert(m);
900✔
311

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

316
static int manager_check_ask_password(Manager *m) {
6,736✔
317
        int r;
6,736✔
318

319
        assert(m);
6,736✔
320

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

326
        if (!m->ask_password_event_source) {
6,736✔
327
                _cleanup_close_ int inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
90✔
328
                if (inotify_fd < 0)
45✔
329
                        return log_error_errno(errno, "Failed to create inotify object: %m");
×
330

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

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

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

352
                (void) sd_event_source_set_description(event_source, "manager-ask-password");
45✔
353

354
                m->ask_password_event_source = TAKE_PTR(event_source);
45✔
355

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

360
        return m->have_ask_password;
6,736✔
361
}
362

363
static int manager_watch_idle_pipe(Manager *m) {
437✔
364
        int r;
437✔
365

366
        assert(m);
437✔
367

368
        if (m->idle_pipe_event_source)
437✔
369
                return 0;
370

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

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

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

380
        return 0;
46✔
381
}
382

383
static void manager_close_idle_pipe(Manager *m) {
3,438✔
384
        assert(m);
3,438✔
385

386
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
3,438✔
387

388
        safe_close_pair(m->idle_pipe);
3,438✔
389
        safe_close_pair(m->idle_pipe + 2);
3,438✔
390
}
3,438✔
391

392
static int manager_setup_time_change(Manager *m) {
250✔
393
        int r;
250✔
394

395
        assert(m);
250✔
396

397
        if (MANAGER_IS_TEST_RUN(m))
250✔
398
                return 0;
399

400
        m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
238✔
401

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

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

411
        log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
238✔
412

413
        return 0;
414
}
415

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

420
        assert(m);
305✔
421

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

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

433
                m->etc_localtime_mtime = k;
238✔
434
                m->etc_localtime_accessible = true;
238✔
435
        }
436

437
        return changed;
305✔
438
}
439

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

444
        assert(m);
278✔
445

446
        if (MANAGER_IS_TEST_RUN(m))
278✔
447
                return 0;
448

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

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

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

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

473
                r = sd_event_add_inotify(m->event, &new_event, localtime_dir,
45✔
474
                                         IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
475
        }
476
        if (r < 0)
266✔
477
                return log_error_errno(r, "Failed to create timezone change event source: %m");
×
478

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

484
        sd_event_source_unref(m->timezone_change_event_source);
266✔
485
        m->timezone_change_event_source = TAKE_PTR(new_event);
266✔
486

487
        return 0;
266✔
488
}
489

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

493
        assert(m);
247✔
494

495
        if (!MANAGER_IS_SYSTEM(m) || MANAGER_IS_TEST_RUN(m))
247✔
496
                return 0;
497

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

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

513
        return 0;
514
}
515

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

524
        assert(m);
247✔
525

526
        assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
247✔
527

528
        /* We make liberal use of realtime signals here. On Linux/glibc we have 30 of them, between
529
         * SIGRTMIN+0 ... SIGRTMIN+30 (aka SIGRTMAX). */
530

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

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

551
                        /* ... space for more special targets ... */
552

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

560
                        /* ... space ... */
561

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

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

574
                        /* ... one free signal here SIGRTMIN+30 ... */
575
                        -1);
576
        assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
247✔
577

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

582
        r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
247✔
583
        if (r < 0)
247✔
584
                return r;
585

586
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
247✔
587

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

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

607
        return manager_enable_special_signals(m);
247✔
608
}
609

610
static char** sanitize_environment(char **l) {
1,227✔
611

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

651
        /* Let's order the environment alphabetically, just to make it pretty */
652
        return strv_sort(l);
1,227✔
653
}
654

655
int manager_default_environment(Manager *m) {
968✔
656
        assert(m);
968✔
657

658
        m->transient_environment = strv_free(m->transient_environment);
968✔
659

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

670
                if (strv_consume(&m->transient_environment, path) < 0)
577✔
671
                        return log_oom();
×
672

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

679
                m->transient_environment = strv_copy(environ);
391✔
680
                if (!m->transient_environment)
391✔
681
                        return log_oom();
×
682

683
                char *path = strjoin("PATH=", default_user_PATH());
391✔
684
                if (!path)
391✔
685
                        return log_oom();
×
686

687
                if (strv_env_replace_consume(&m->transient_environment, path) < 0)
391✔
688
                        return log_oom();
×
689

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

701
        sanitize_environment(m->transient_environment);
968✔
702
        return 0;
968✔
703
}
704

705
static int manager_setup_prefix(Manager *m) {
708✔
706
        struct table_entry {
708✔
707
                uint64_t type;
708
                const char *suffix;
709
        };
710

711
        static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
708✔
712
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_SYSTEM_RUNTIME,       NULL },
713
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
714
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_SYSTEM_STATE_CACHE,   NULL },
715
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_SYSTEM_STATE_LOGS,    NULL },
716
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
717
        };
718

719
        static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
708✔
720
                [EXEC_DIRECTORY_RUNTIME]       = { SD_PATH_USER_RUNTIME,       NULL  },
721
                [EXEC_DIRECTORY_STATE]         = { SD_PATH_USER_STATE_PRIVATE, NULL  },
722
                [EXEC_DIRECTORY_CACHE]         = { SD_PATH_USER_STATE_CACHE,   NULL  },
723
                [EXEC_DIRECTORY_LOGS]          = { SD_PATH_USER_STATE_PRIVATE, "log" },
724
                [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL  },
725
        };
726

727
        assert(m);
708✔
728

729
        const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
708✔
730
        int r;
708✔
731

732
        for (ExecDirectoryType i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
4,248✔
733
                r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
3,540✔
734
                if (r < 0)
3,540✔
735
                        return log_warning_errno(r, "Failed to lookup %s path: %m",
×
736
                                                 exec_directory_type_to_string(i));
737
        }
738

739
        return 0;
740
}
741

742
static void manager_free_unit_name_maps(Manager *m) {
733✔
743
        m->unit_id_map = hashmap_free(m->unit_id_map);
733✔
744
        m->unit_name_map = hashmap_free(m->unit_name_map);
733✔
745
        m->unit_path_cache = set_free(m->unit_path_cache);
733✔
746
        m->unit_cache_timestamp_hash = 0;
733✔
747
}
733✔
748

749
static int manager_setup_run_queue(Manager *m) {
708✔
750
        int r;
708✔
751

752
        assert(m);
708✔
753
        assert(!m->run_queue_event_source);
708✔
754

755
        r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
708✔
756
        if (r < 0)
708✔
757
                return r;
758

759
        r = sd_event_source_set_priority(m->run_queue_event_source, EVENT_PRIORITY_RUN_QUEUE);
708✔
760
        if (r < 0)
708✔
761
                return r;
762

763
        r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
708✔
764
        if (r < 0)
708✔
765
                return r;
766

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

769
        return 0;
708✔
770
}
771

772
static int manager_setup_sigchld_event_source(Manager *m) {
247✔
773
        int r;
247✔
774

775
        assert(m);
247✔
776
        assert(!m->sigchld_event_source);
247✔
777

778
        r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
247✔
779
        if (r < 0)
247✔
780
                return r;
781

782
        r = sd_event_source_set_priority(m->sigchld_event_source, EVENT_PRIORITY_SIGCHLD);
247✔
783
        if (r < 0)
247✔
784
                return r;
785

786
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
247✔
787
        if (r < 0)
247✔
788
                return r;
789

790
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
247✔
791

792
        return 0;
247✔
793
}
794

795
int manager_setup_memory_pressure_event_source(Manager *m) {
510✔
796
        int r;
510✔
797

798
        assert(m);
510✔
799

800
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
510✔
801

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

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

817
        return 0;
510✔
818
}
819

820
static int manager_find_credentials_dirs(Manager *m) {
708✔
821
        const char *e;
708✔
822
        int r;
708✔
823

824
        assert(m);
708✔
825

826
        r = get_credentials_dir(&e);
708✔
827
        if (r < 0) {
708✔
828
                if (r != -ENXIO)
658✔
829
                        log_debug_errno(r, "Failed to determine credentials directory, ignoring: %m");
×
830
        } else {
831
                m->received_credentials_directory = strdup(e);
50✔
832
                if (!m->received_credentials_directory)
50✔
833
                        return -ENOMEM;
708✔
834
        }
835

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

846
        return 0;
847
}
848

849
void manager_set_switching_root(Manager *m, bool switching_root) {
950✔
850
        assert(m);
950✔
851

852
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
950✔
853
}
950✔
854

855
double manager_get_progress(Manager *m) {
17✔
856
        assert(m);
17✔
857

858
        if (MANAGER_IS_FINISHED(m) || m->n_installed_jobs == 0)
33✔
859
                return 1.0;
860

861
        return 1.0 - ((double) hashmap_size(m->jobs) / (double) m->n_installed_jobs);
16✔
862
}
863

864
static int compare_job_priority(const void *a, const void *b) {
351,018✔
865
        const Job *x = a, *y = b;
351,018✔
866

867
        return unit_compare_priority(x->unit, y->unit);
351,018✔
868
}
869

870
usec_t manager_default_timeout(RuntimeScope scope) {
4,608✔
871
        return scope == RUNTIME_SCOPE_SYSTEM ? DEFAULT_TIMEOUT_USEC : DEFAULT_USER_TIMEOUT_USEC;
4,608✔
872
}
873

874
int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags, Manager **ret) {
708✔
875
        _cleanup_(manager_freep) Manager *m = NULL;
708✔
876
        int r;
708✔
877

878
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
708✔
879
        assert(ret);
708✔
880

881
        m = new(Manager, 1);
708✔
882
        if (!m)
708✔
883
                return -ENOMEM;
884

885
        *m = (Manager) {
708✔
886
                .runtime_scope = runtime_scope,
887
                .objective = _MANAGER_OBJECTIVE_INVALID,
888
                .previous_objective = _MANAGER_OBJECTIVE_INVALID,
889

890
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
891

892
                .original_log_level = -1,
893
                .original_log_target = _LOG_TARGET_INVALID,
894

895
                .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
896
                .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
897
                .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
898
                .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
899

900
                .show_status_overridden = _SHOW_STATUS_INVALID,
901

902
                .notify_fd = -EBADF,
903
                .signal_fd = -EBADF,
904
                .user_lookup_fds = EBADF_PAIR,
905
                .handoff_timestamp_fds = EBADF_PAIR,
906
                .pidref_transport_fds = EBADF_PAIR,
907
                .private_listen_fd = -EBADF,
908
                .dev_autofs_fd = -EBADF,
909
                .cgroup_inotify_fd = -EBADF,
910
                .pin_cgroupfs_fd = -EBADF,
911
                .idle_pipe = { -EBADF, -EBADF, -EBADF, -EBADF},
912

913
                 /* start as id #1, so that we can leave #0 around as "null-like" value */
914
                .current_job_id = 1,
915

916
                .have_ask_password = -EINVAL, /* we don't know */
917
                .first_boot = -1,
918
                .test_run_flags = test_run_flags,
919

920
                .dump_ratelimit = (const RateLimit) { .interval = 10 * USEC_PER_MINUTE, .burst = 10 },
921

922
                .executor_fd = -EBADF,
923
        };
924

925
        unit_defaults_init(&m->defaults, runtime_scope);
708✔
926

927
#if ENABLE_EFI
928
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
708✔
929
                boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
23✔
930
                                m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
23✔
931
                                m->timestamps + MANAGER_TIMESTAMP_LOADER);
23✔
932
#endif
933

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

937
        r = manager_default_environment(m);
708✔
938
        if (r < 0)
708✔
939
                return r;
940

941
        r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
708✔
942
        if (r < 0)
708✔
943
                return r;
944

945
        r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
708✔
946
        if (r < 0)
708✔
947
                return r;
948

949
        r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
708✔
950
        if (r < 0)
708✔
951
                return r;
952

953
        r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
708✔
954
        if (r < 0)
708✔
955
                return r;
956

957
        r = manager_setup_prefix(m);
708✔
958
        if (r < 0)
708✔
959
                return r;
960

961
        r = manager_find_credentials_dirs(m);
708✔
962
        if (r < 0)
708✔
963
                return r;
964

965
        r = sd_event_default(&m->event);
708✔
966
        if (r < 0)
708✔
967
                return r;
968

969
        r = manager_setup_run_queue(m);
708✔
970
        if (r < 0)
708✔
971
                return r;
972

973
        if (FLAGS_SET(test_run_flags, MANAGER_TEST_RUN_MINIMAL)) {
708✔
974
                m->cgroup_root = strdup("");
461✔
975
                if (!m->cgroup_root)
461✔
976
                        return -ENOMEM;
977
        } else {
978
                r = manager_setup_signals(m);
247✔
979
                if (r < 0)
247✔
980
                        return r;
981

982
                r = manager_setup_cgroup(m);
247✔
983
                if (r < 0)
247✔
984
                        return r;
985

986
                r = manager_setup_time_change(m);
247✔
987
                if (r < 0)
247✔
988
                        return r;
989

990
                r = manager_read_timezone_stat(m);
247✔
991
                if (r < 0)
247✔
992
                        return r;
993

994
                (void) manager_setup_timezone_change(m);
247✔
995

996
                r = manager_setup_sigchld_event_source(m);
247✔
997
                if (r < 0)
247✔
998
                        return r;
999

1000
                r = manager_setup_memory_pressure_event_source(m);
247✔
1001
                if (r < 0)
247✔
1002
                        return r;
1003

1004
#if HAVE_LIBBPF
1005
                if (MANAGER_IS_SYSTEM(m) && bpf_restrict_fs_supported(/* initialize = */ true)) {
247✔
1006
                        r = bpf_restrict_fs_setup(m);
12✔
1007
                        if (r < 0)
12✔
1008
                                log_warning_errno(r, "Failed to setup LSM BPF, ignoring: %m");
×
1009
                }
1010
#endif
1011
        }
1012

1013
        if (test_run_flags == 0) {
708✔
1014
                if (MANAGER_IS_SYSTEM(m))
235✔
1015
                        r = mkdir_label("/run/systemd/units", 0755);
50✔
1016
                else {
1017
                        _cleanup_free_ char *units_path = NULL;
185✔
1018
                        r = xdg_user_runtime_dir("/systemd/units", &units_path);
185✔
1019
                        if (r < 0)
185✔
1020
                                return r;
×
1021

1022
                        r = mkdir_label(units_path, 0755);
185✔
1023
                }
1024
                if (r < 0 && r != -EEXIST)
235✔
1025
                        return r;
1026
        }
1027

1028
        if (!FLAGS_SET(test_run_flags, MANAGER_TEST_DONT_OPEN_EXECUTOR)) {
708✔
1029
                m->executor_fd = pin_callout_binary(SYSTEMD_EXECUTOR_BINARY_PATH, &m->executor_path);
254✔
1030
                if (m->executor_fd < 0)
254✔
1031
                        return log_debug_errno(m->executor_fd, "Failed to pin executor binary: %m");
×
1032

1033
                log_debug("Using systemd-executor binary from '%s'.", m->executor_path);
254✔
1034
        }
1035

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

1039
        *ret = TAKE_PTR(m);
708✔
1040

1041
        return 0;
708✔
1042
}
1043

1044
static int manager_setup_notify(Manager *m) {
731✔
1045
        int r;
731✔
1046

1047
        if (MANAGER_IS_TEST_RUN(m))
731✔
1048
                return 0;
1049

1050
        if (m->notify_fd < 0) {
260✔
1051
                _cleanup_close_ int fd = -EBADF;
215✔
1052
                union sockaddr_union sa;
215✔
1053
                socklen_t sa_len;
215✔
1054

1055
                /* First free all secondary fields */
1056
                m->notify_socket = mfree(m->notify_socket);
215✔
1057
                m->notify_event_source = sd_event_source_disable_unref(m->notify_event_source);
215✔
1058

1059
                fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
215✔
1060
                if (fd < 0)
215✔
1061
                        return log_error_errno(errno, "Failed to allocate notification socket: %m");
×
1062

1063
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
215✔
1064

1065
                m->notify_socket = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/notify");
215✔
1066
                if (!m->notify_socket)
215✔
1067
                        return log_oom();
×
1068

1069
                r = sockaddr_un_set_path(&sa.un, m->notify_socket);
215✔
1070
                if (r < 0)
215✔
1071
                        return log_error_errno(r, "Notify socket '%s' not valid for AF_UNIX socket address, refusing.",
×
1072
                                               m->notify_socket);
1073
                sa_len = r;
215✔
1074

1075
                (void) sockaddr_un_unlink(&sa.un);
215✔
1076

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

1081
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
215✔
1082
                if (r < 0)
215✔
1083
                        return log_error_errno(r, "Failed to enable SO_PASSCRED for notify socket: %m");
×
1084

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

1090
                m->notify_fd = TAKE_FD(fd);
215✔
1091

1092
                log_debug("Using notification socket %s", m->notify_socket);
215✔
1093
        }
1094

1095
        if (!m->notify_event_source) {
260✔
1096
                r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
260✔
1097
                if (r < 0)
260✔
1098
                        return log_error_errno(r, "Failed to allocate notify event source: %m");
×
1099

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

1106
                (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
260✔
1107
        }
1108

1109
        return 0;
1110
}
1111

1112
static int manager_setup_user_lookup_fd(Manager *m) {
731✔
1113
        int r;
731✔
1114

1115
        assert(m);
731✔
1116

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

1136
        if (m->user_lookup_fds[0] < 0) {
731✔
1137

1138
                /* Free all secondary fields */
1139
                safe_close_pair(m->user_lookup_fds);
686✔
1140
                m->user_lookup_event_source = sd_event_source_disable_unref(m->user_lookup_event_source);
686✔
1141

1142
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
686✔
1143
                        return log_error_errno(errno, "Failed to allocate user lookup socket: %m");
×
1144

1145
                r = setsockopt_int(m->user_lookup_fds[0], SOL_SOCKET, SO_PASSRIGHTS, false);
686✔
1146
                if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
686✔
1147
                        log_warning_errno(r, "Failed to turn off SO_PASSRIGHTS on user lookup socket, ignoring: %m");
×
1148

1149
                (void) fd_increase_rxbuf(m->user_lookup_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
686✔
1150
        }
1151

1152
        if (!m->user_lookup_event_source) {
731✔
1153
                r = sd_event_add_io(m->event, &m->user_lookup_event_source, m->user_lookup_fds[0], EPOLLIN, manager_dispatch_user_lookup_fd, m);
731✔
1154
                if (r < 0)
731✔
1155
                        return log_error_errno(r, "Failed to allocate user lookup event source: %m");
×
1156

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

1163
                (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
731✔
1164
        }
1165

1166
        return 0;
1167
}
1168

1169
static int manager_setup_handoff_timestamp_fd(Manager *m) {
731✔
1170
        int r;
731✔
1171

1172
        assert(m);
731✔
1173

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

1177
        if (m->handoff_timestamp_fds[0] < 0) {
731✔
1178
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
686✔
1179
                safe_close_pair(m->handoff_timestamp_fds);
686✔
1180

1181
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->handoff_timestamp_fds) < 0)
686✔
1182
                        return log_error_errno(errno, "Failed to allocate handoff timestamp socket: %m");
×
1183

1184
                /* Make sure children never have to block */
1185
                (void) fd_increase_rxbuf(m->handoff_timestamp_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
686✔
1186

1187
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSCRED, true);
686✔
1188
                if (r < 0)
686✔
1189
                        return log_error_errno(r, "Failed to enable SO_PASSCRED on handoff timestamp socket: %m");
×
1190

1191
                r = setsockopt_int(m->handoff_timestamp_fds[0], SOL_SOCKET, SO_PASSRIGHTS, false);
686✔
1192
                if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
686✔
1193
                        log_warning_errno(r, "Failed to turn off SO_PASSRIGHTS on handoff timestamp socket, ignoring: %m");
×
1194

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

1201
        if (!m->handoff_timestamp_event_source) {
731✔
1202
                r = sd_event_add_io(m->event, &m->handoff_timestamp_event_source, m->handoff_timestamp_fds[0], EPOLLIN, manager_dispatch_handoff_timestamp_fd, m);
731✔
1203
                if (r < 0)
731✔
1204
                        return log_error_errno(r, "Failed to allocate handoff timestamp event source: %m");
×
1205

1206
                r = sd_event_source_set_priority(m->handoff_timestamp_event_source, EVENT_PRIORITY_HANDOFF_TIMESTAMP);
731✔
1207
                if (r < 0)
731✔
1208
                        return log_error_errno(r, "Failed to set priority of handoff timestamp event source: %m");
×
1209

1210
                (void) sd_event_source_set_description(m->handoff_timestamp_event_source, "handoff-timestamp");
731✔
1211
        }
1212

1213
        return 0;
1214
}
1215

1216
static int manager_setup_pidref_transport_fd(Manager *m) {
731✔
1217
        int r;
731✔
1218

1219
        assert(m);
731✔
1220

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

1224
        if (m->pidref_transport_fds[0] < 0) {
731✔
1225
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
706✔
1226
                safe_close_pair(m->pidref_transport_fds);
706✔
1227

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

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

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

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

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

1250
        if (!m->pidref_event_source) {
731✔
1251
                r = sd_event_add_io(m->event, &m->pidref_event_source, m->pidref_transport_fds[0], EPOLLIN, manager_dispatch_pidref_transport_fd, m);
706✔
1252
                if (r < 0)
706✔
1253
                        return log_error_errno(r, "Failed to allocate pidref event source: %m");
×
1254

1255
                r = sd_event_source_set_priority(m->pidref_event_source, EVENT_PRIORITY_PIDREF);
706✔
1256
                if (r < 0)
706✔
1257
                        return log_error_errno(r, "Failed to set priority of pidref event source: %m");
×
1258

1259
                (void) sd_event_source_set_description(m->pidref_event_source, "pidref");
706✔
1260
        }
1261

1262
        return 0;
1263
}
1264

1265
static unsigned manager_dispatch_cleanup_queue(Manager *m) {
188,553✔
1266
        Unit *u;
188,553✔
1267
        unsigned n = 0;
188,553✔
1268

1269
        assert(m);
188,553✔
1270

1271
        while ((u = m->cleanup_queue)) {
222,935✔
1272
                assert(u->in_cleanup_queue);
34,382✔
1273

1274
                unit_free(u);
34,382✔
1275
                n++;
34,382✔
1276
        }
1277

1278
        return n;
188,553✔
1279
}
1280

1281
static unsigned manager_dispatch_release_resources_queue(Manager *m) {
175,341✔
1282
        unsigned n = 0;
175,341✔
1283
        Unit *u;
175,341✔
1284

1285
        assert(m);
175,341✔
1286

1287
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
176,530✔
1288
                assert(u->in_release_resources_queue);
1,189✔
1289
                u->in_release_resources_queue = false;
1,189✔
1290

1291
                n++;
1,189✔
1292

1293
                unit_release_resources(u);
1,189✔
1294
        }
1295

1296
        return n;
175,341✔
1297
}
1298

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

1307
static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
65,146✔
1308
        Unit *other;
65,146✔
1309

1310
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
65,146✔
1311

1312
        /* Recursively mark referenced units as GOOD as well */
1313
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
438,922✔
1314
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
234,830✔
1315
                        unit_gc_mark_good(other, gc_marker);
1,157✔
1316
}
65,146✔
1317

1318
static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
114,373✔
1319
        Unit *other;
114,373✔
1320
        bool is_bad;
114,373✔
1321

1322
        assert(u);
114,373✔
1323

1324
        if (IN_SET(u->gc_marker - gc_marker,
114,373✔
1325
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1326
                return;
50,384✔
1327

1328
        if (u->in_cleanup_queue)
99,527✔
1329
                goto bad;
×
1330

1331
        if (!unit_may_gc(u))
99,527✔
1332
                goto good;
46,226✔
1333

1334
        u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
53,301✔
1335

1336
        is_bad = true;
53,301✔
1337

1338
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
112,809✔
1339
                unit_gc_sweep(other, gc_marker);
21,547✔
1340

1341
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
21,547✔
1342
                        goto good;
17,763✔
1343

1344
                if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
3,784✔
1345
                        is_bad = false;
3,306✔
1346
        }
1347

1348
        LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
35,834✔
1349
                unit_gc_sweep(ref->source, gc_marker);
296✔
1350

1351
                if (ref->source->gc_marker == gc_marker + GC_OFFSET_GOOD)
296✔
1352
                        goto good;
×
1353

1354
                if (ref->source->gc_marker != gc_marker + GC_OFFSET_BAD)
296✔
1355
                        is_bad = false;
296✔
1356
        }
1357

1358
        if (is_bad)
35,538✔
1359
                goto bad;
34,011✔
1360

1361
        /* We were unable to find anything out about this entry, so
1362
         * let's investigate it later */
1363
        u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
1,527✔
1364
        unit_add_to_gc_queue(u);
1,527✔
1365
        return;
1366

1367
bad:
34,011✔
1368
        /* We definitely know that this one is not useful anymore, so
1369
         * let's mark it for deletion */
1370
        u->gc_marker = gc_marker + GC_OFFSET_BAD;
34,011✔
1371
        unit_add_to_cleanup_queue(u);
34,011✔
1372
        return;
1373

1374
good:
63,989✔
1375
        unit_gc_mark_good(u, gc_marker);
63,989✔
1376
}
1377

1378
static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
202,728✔
1379
        unsigned n = 0, gc_marker;
202,728✔
1380

1381
        assert(m);
202,728✔
1382

1383
        /* log_debug("Running GC..."); */
1384

1385
        m->gc_marker += _GC_OFFSET_MAX;
202,728✔
1386
        if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
202,728✔
1387
                m->gc_marker = 1;
×
1388

1389
        gc_marker = m->gc_marker;
202,728✔
1390

1391
        Unit *u;
202,728✔
1392
        while ((u = m->gc_unit_queue)) {
295,258✔
1393
                assert(u->in_gc_queue);
92,530✔
1394

1395
                unit_gc_sweep(u, gc_marker);
92,530✔
1396

1397
                LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
92,530✔
1398
                u->in_gc_queue = false;
92,530✔
1399

1400
                n++;
92,530✔
1401

1402
                if (IN_SET(u->gc_marker - gc_marker,
92,530✔
1403
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1404
                        if (u->id)
34,381✔
1405
                                log_unit_debug(u, "Collecting.");
34,381✔
1406
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
34,381✔
1407
                        unit_add_to_cleanup_queue(u);
34,381✔
1408
                }
1409
        }
1410

1411
        return n;
202,728✔
1412
}
1413

1414
static unsigned manager_dispatch_gc_job_queue(Manager *m) {
202,733✔
1415
        unsigned n = 0;
202,733✔
1416
        Job *j;
202,733✔
1417

1418
        assert(m);
202,733✔
1419

1420
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
202,739✔
1421
                assert(j->in_gc_queue);
6✔
1422
                j->in_gc_queue = false;
6✔
1423

1424
                n++;
6✔
1425

1426
                if (!job_may_gc(j))
6✔
1427
                        continue;
6✔
1428

1429
                log_unit_debug(j->unit, "Collecting job.");
×
1430
                (void) job_finish_and_invalidate(j, JOB_COLLECTED, false, false);
×
1431
        }
1432

1433
        return n;
202,733✔
1434
}
1435

1436
static int manager_ratelimit_requeue(sd_event_source *s, uint64_t usec, void *userdata) {
×
1437
        Unit *u = userdata;
×
1438

1439
        assert(u);
×
1440
        assert(s == u->auto_start_stop_event_source);
×
1441

1442
        u->auto_start_stop_event_source = sd_event_source_unref(u->auto_start_stop_event_source);
×
1443

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

1449
        return 0;
×
1450
}
1451

1452
static int manager_ratelimit_check_and_queue(Unit *u) {
13✔
1453
        int r;
13✔
1454

1455
        assert(u);
13✔
1456

1457
        if (ratelimit_below(&u->auto_start_stop_ratelimit))
13✔
1458
                return 1;
1459

1460
        /* Already queued, no need to requeue */
1461
        if (u->auto_start_stop_event_source)
×
1462
                return 0;
1463

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

1475
        return 0;
1476
}
1477

1478
static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
175,492✔
1479
        unsigned n = 0;
175,492✔
1480
        Unit *u;
175,492✔
1481
        int r;
175,492✔
1482

1483
        assert(m);
175,492✔
1484

1485
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
175,725✔
1486
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
233✔
1487

1488
                assert(u->in_stop_when_unneeded_queue);
233✔
1489
                u->in_stop_when_unneeded_queue = false;
233✔
1490

1491
                n++;
233✔
1492

1493
                if (!unit_is_unneeded(u))
233✔
1494
                        continue;
223✔
1495

1496
                log_unit_debug(u, "Unit is not needed anymore.");
10✔
1497

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

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

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

1515
        return n;
175,492✔
1516
}
1517

1518
static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
175,624✔
1519
        unsigned n = 0;
175,624✔
1520
        Unit *u;
175,624✔
1521
        int r;
175,624✔
1522

1523
        assert(m);
175,624✔
1524

1525
        while ((u = LIST_POP(start_when_upheld_queue, m->start_when_upheld_queue))) {
175,624✔
1526
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1527
                Unit *culprit = NULL;
×
1528

1529
                assert(u->in_start_when_upheld_queue);
×
1530
                u->in_start_when_upheld_queue = false;
×
1531

1532
                n++;
×
1533

1534
                if (!unit_is_upheld_by_active(u, &culprit))
×
1535
                        continue;
×
1536

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

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

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

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

1556
        return n;
175,624✔
1557
}
1558

1559
static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
175,624✔
1560
        unsigned n = 0;
175,624✔
1561
        Unit *u;
175,624✔
1562
        int r;
175,624✔
1563

1564
        assert(m);
175,624✔
1565

1566
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
175,857✔
1567
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
233✔
1568
                Unit *culprit = NULL;
233✔
1569

1570
                assert(u->in_stop_when_bound_queue);
233✔
1571
                u->in_stop_when_bound_queue = false;
233✔
1572

1573
                n++;
233✔
1574

1575
                if (!unit_is_bound_by_inactive(u, &culprit))
233✔
1576
                        continue;
230✔
1577

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

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

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

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

1597
        return n;
175,624✔
1598
}
1599

1600
static unsigned manager_dispatch_stop_notify_queue(Manager *m) {
174,296✔
1601
        unsigned n = 0;
174,296✔
1602

1603
        assert(m);
174,296✔
1604

1605
        if (m->may_dispatch_stop_notify_queue < 0)
174,296✔
1606
                m->may_dispatch_stop_notify_queue = hashmap_isempty(m->jobs);
5,122✔
1607

1608
        if (!m->may_dispatch_stop_notify_queue)
174,296✔
1609
                return 0;
1610

1611
        m->may_dispatch_stop_notify_queue = false;
9,470✔
1612

1613
        LIST_FOREACH(stop_notify_queue, u, m->stop_notify_queue) {
9,472✔
1614
                assert(u->in_stop_notify_queue);
2✔
1615

1616
                assert(UNIT_VTABLE(u)->stop_notify);
2✔
1617
                if (UNIT_VTABLE(u)->stop_notify(u)) {
2✔
1618
                        assert(!u->in_stop_notify_queue);
×
1619
                        n++;
×
1620
                }
1621
        }
1622

1623
        return n;
1624
}
1625

1626
static void manager_clear_jobs_and_units(Manager *m) {
733✔
1627
        Unit *u;
733✔
1628

1629
        assert(m);
733✔
1630

1631
        while ((u = hashmap_first(m->units)))
46,434✔
1632
                unit_free(u);
45,701✔
1633

1634
        manager_dispatch_cleanup_queue(m);
733✔
1635

1636
        assert(!m->load_queue);
733✔
1637
        assert(prioq_isempty(m->run_queue));
733✔
1638
        assert(!m->dbus_unit_queue);
733✔
1639
        assert(!m->dbus_job_queue);
733✔
1640
        assert(!m->cleanup_queue);
733✔
1641
        assert(!m->gc_unit_queue);
733✔
1642
        assert(!m->gc_job_queue);
733✔
1643
        assert(!m->cgroup_realize_queue);
733✔
1644
        assert(!m->cgroup_empty_queue);
733✔
1645
        assert(!m->cgroup_oom_queue);
733✔
1646
        assert(!m->target_deps_queue);
733✔
1647
        assert(!m->stop_when_unneeded_queue);
733✔
1648
        assert(!m->start_when_upheld_queue);
733✔
1649
        assert(!m->stop_when_bound_queue);
733✔
1650
        assert(!m->release_resources_queue);
733✔
1651

1652
        assert(hashmap_isempty(m->jobs));
733✔
1653
        assert(hashmap_isempty(m->units));
733✔
1654
        assert(hashmap_isempty(m->units_by_invocation_id));
733✔
1655

1656
        m->n_on_console = 0;
733✔
1657
        m->n_running_jobs = 0;
733✔
1658
        m->n_installed_jobs = 0;
733✔
1659
        m->n_failed_jobs = 0;
733✔
1660
}
733✔
1661

1662
Manager* manager_free(Manager *m) {
708✔
1663
        if (!m)
708✔
1664
                return NULL;
1665

1666
        manager_clear_jobs_and_units(m);
708✔
1667

1668
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
8,496✔
1669
                if (unit_vtable[c]->shutdown)
7,788✔
1670
                        unit_vtable[c]->shutdown(m);
2,832✔
1671

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

1675
        lookup_paths_flush_generator(&m->lookup_paths);
708✔
1676

1677
        bus_done(m);
708✔
1678
        manager_varlink_done(m);
708✔
1679

1680
        exec_shared_runtime_vacuum(m);
708✔
1681
        hashmap_free(m->exec_shared_runtime_by_id);
708✔
1682

1683
        dynamic_user_vacuum(m, false);
708✔
1684
        hashmap_free(m->dynamic_users);
708✔
1685

1686
        hashmap_free(m->units);
708✔
1687
        hashmap_free(m->units_by_invocation_id);
708✔
1688
        hashmap_free(m->jobs);
708✔
1689
        hashmap_free(m->watch_pids);
708✔
1690
        hashmap_free(m->watch_pids_more);
708✔
1691
        hashmap_free(m->watch_bus);
708✔
1692

1693
        prioq_free(m->run_queue);
708✔
1694

1695
        set_free(m->startup_units);
708✔
1696
        set_free(m->failed_units);
708✔
1697

1698
        sd_event_source_unref(m->signal_event_source);
708✔
1699
        sd_event_source_unref(m->sigchld_event_source);
708✔
1700
        sd_event_source_unref(m->notify_event_source);
708✔
1701
        sd_event_source_unref(m->time_change_event_source);
708✔
1702
        sd_event_source_unref(m->timezone_change_event_source);
708✔
1703
        sd_event_source_unref(m->jobs_in_progress_event_source);
708✔
1704
        sd_event_source_unref(m->run_queue_event_source);
708✔
1705
        sd_event_source_unref(m->user_lookup_event_source);
708✔
1706
        sd_event_source_unref(m->handoff_timestamp_event_source);
708✔
1707
        sd_event_source_unref(m->pidref_event_source);
708✔
1708
        sd_event_source_unref(m->memory_pressure_event_source);
708✔
1709

1710
        safe_close(m->signal_fd);
708✔
1711
        safe_close(m->notify_fd);
708✔
1712
        safe_close_pair(m->user_lookup_fds);
708✔
1713
        safe_close_pair(m->handoff_timestamp_fds);
708✔
1714
        safe_close_pair(m->pidref_transport_fds);
708✔
1715

1716
        manager_close_ask_password(m);
708✔
1717

1718
        manager_close_idle_pipe(m);
708✔
1719

1720
        sd_event_unref(m->event);
708✔
1721

1722
        free(m->notify_socket);
708✔
1723

1724
        lookup_paths_done(&m->lookup_paths);
708✔
1725
        strv_free(m->transient_environment);
708✔
1726
        strv_free(m->client_environment);
708✔
1727

1728
        hashmap_free(m->cgroup_unit);
708✔
1729
        manager_free_unit_name_maps(m);
708✔
1730

1731
        free(m->switch_root);
708✔
1732
        free(m->switch_root_init);
708✔
1733

1734
        sd_bus_track_unref(m->subscribed);
708✔
1735
        strv_free(m->subscribed_as_strv);
708✔
1736

1737
        unit_defaults_done(&m->defaults);
708✔
1738

1739
        FOREACH_ARRAY(map, m->units_needing_mounts_for, _UNIT_MOUNT_DEPENDENCY_TYPE_MAX) {
2,124✔
1740
                assert(hashmap_isempty(*map));
1,416✔
1741
                hashmap_free(*map);
1,416✔
1742
        }
1743

1744
        hashmap_free(m->uid_refs);
708✔
1745
        hashmap_free(m->gid_refs);
708✔
1746

1747
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
4,248✔
1748
                free(*i);
3,540✔
1749

1750
        free(m->received_credentials_directory);
708✔
1751
        free(m->received_encrypted_credentials_directory);
708✔
1752

1753
        free(m->watchdog_pretimeout_governor);
708✔
1754
        free(m->watchdog_pretimeout_governor_overridden);
708✔
1755

1756
        fw_ctx_free(m->fw_ctx);
708✔
1757

1758
#if BPF_FRAMEWORK
1759
        bpf_restrict_fs_destroy(m->restrict_fs);
708✔
1760
#endif
1761

1762
        safe_close(m->executor_fd);
708✔
1763
        free(m->executor_path);
708✔
1764

1765
        return mfree(m);
708✔
1766
}
1767

1768
static void manager_enumerate_perpetual(Manager *m) {
731✔
1769
        assert(m);
731✔
1770

1771
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
731✔
1772
                return;
1773

1774
        /* Let's ask every type to load all units from disk/kernel that it might know */
1775
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,264✔
1776
                if (!unit_type_supported(c)) {
2,992✔
1777
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
459✔
1778
                        continue;
459✔
1779
                }
1780

1781
                if (unit_vtable[c]->enumerate_perpetual)
2,533✔
1782
                        unit_vtable[c]->enumerate_perpetual(m);
816✔
1783
        }
1784
}
1785

1786
static void manager_enumerate(Manager *m) {
731✔
1787
        assert(m);
731✔
1788

1789
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
731✔
1790
                return;
1791

1792
        /* Let's ask every type to load all units from disk/kernel that it might know */
1793
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
3,264✔
1794
                if (!unit_type_supported(c)) {
2,992✔
1795
                        log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
459✔
1796
                        continue;
459✔
1797
                }
1798

1799
                if (unit_vtable[c]->enumerate)
2,533✔
1800
                        unit_vtable[c]->enumerate(m);
510✔
1801
        }
1802

1803
        manager_dispatch_load_queue(m);
272✔
1804
}
1805

1806
static void manager_coldplug(Manager *m) {
731✔
1807
        Unit *u;
731✔
1808
        char *k;
731✔
1809
        int r;
731✔
1810

1811
        assert(m);
731✔
1812

1813
        log_debug("Invoking unit coldplug() handlers%s", glyph(GLYPH_ELLIPSIS));
1,050✔
1814

1815
        /* Let's place the units back into their deserialized state */
1816
        HASHMAP_FOREACH_KEY(u, k, m->units) {
40,341✔
1817

1818
                /* ignore aliases */
1819
                if (u->id != k)
38,879✔
1820
                        continue;
664✔
1821

1822
                r = unit_coldplug(u);
38,215✔
1823
                if (r < 0)
38,215✔
1824
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
39,610✔
1825
        }
1826
}
731✔
1827

1828
static void manager_catchup(Manager *m) {
731✔
1829
        Unit *u;
731✔
1830
        char *k;
731✔
1831

1832
        assert(m);
731✔
1833

1834
        log_debug("Invoking unit catchup() handlers%s", glyph(GLYPH_ELLIPSIS));
1,050✔
1835

1836
        /* Let's catch up on any state changes that happened while we were reloading/reexecing */
1837
        HASHMAP_FOREACH_KEY(u, k, m->units) {
39,610✔
1838

1839
                /* ignore aliases */
1840
                if (u->id != k)
38,879✔
1841
                        continue;
664✔
1842

1843
                unit_catchup(u);
38,215✔
1844
        }
1845
}
731✔
1846

1847
static void manager_distribute_fds(Manager *m, FDSet *fds) {
706✔
1848
        Unit *u;
706✔
1849

1850
        assert(m);
706✔
1851

1852
        HASHMAP_FOREACH(u, m->units) {
7,911✔
1853

1854
                if (fdset_isempty(fds))
7,432✔
1855
                        break;
1856

1857
                if (!UNIT_VTABLE(u)->distribute_fds)
7,205✔
1858
                        continue;
6,472✔
1859

1860
                UNIT_VTABLE(u)->distribute_fds(u, fds);
733✔
1861
        }
1862
}
706✔
1863

1864
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
66,618✔
1865
        Unit *u;
66,618✔
1866

1867
        assert(m);
66,618✔
1868

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

1873
        if (MANAGER_IS_TEST_RUN(m))
66,618✔
1874
                return false;
1875

1876
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
65,758✔
1877
        if (!u)
65,758✔
1878
                return false;
1879
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
108,302✔
1880
                return false;
1881

1882
        u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
4,824✔
1883
        if (!u)
4,824✔
1884
                return false;
1885
        if (!IN_SET((deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state),
9,648✔
1886
                    SERVICE_RUNNING,
1887
                    SERVICE_MOUNTING,
1888
                    SERVICE_RELOAD,
1889
                    SERVICE_RELOAD_NOTIFY,
1890
                    SERVICE_REFRESH_EXTENSIONS,
1891
                    SERVICE_RELOAD_SIGNAL))
1892
                return false;
257✔
1893

1894
        return true;
1895
}
1896

1897
static void manager_setup_bus(Manager *m) {
706✔
1898
        assert(m);
706✔
1899

1900
        if (MANAGER_IS_TEST_RUN(m))
706✔
1901
                return;
1902

1903
        /* Let's set up our private bus connection now, unconditionally */
1904
        (void) bus_init_private(m);
235✔
1905

1906
        /* If we are in --user mode also connect to the system bus now */
1907
        if (MANAGER_IS_USER(m))
235✔
1908
                (void) bus_init_system(m);
185✔
1909

1910
        /* Let's connect to the bus now, but only if the unit is supposed to be up */
1911
        if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
235✔
1912
                (void) bus_init_api(m);
17✔
1913

1914
                if (MANAGER_IS_SYSTEM(m))
17✔
1915
                        (void) bus_init_system(m);
16✔
1916
        }
1917
}
1918

1919
static void manager_preset_all(Manager *m) {
706✔
1920
        int r;
706✔
1921

1922
        assert(m);
706✔
1923

1924
        if (m->first_boot <= 0)
706✔
1925
                return;
688✔
1926

1927
        if (!MANAGER_IS_SYSTEM(m))
18✔
1928
                return;
1929

1930
        if (MANAGER_IS_TEST_RUN(m))
18✔
1931
                return;
1932

1933
        /* If this is the first boot, and we are in the host system, then preset everything */
1934
        UnitFilePresetMode mode =
18✔
1935
                ENABLE_FIRST_BOOT_FULL_PRESET ? UNIT_FILE_PRESET_FULL : UNIT_FILE_PRESET_ENABLE_ONLY;
1936
        InstallChange *changes = NULL;
18✔
1937
        size_t n_changes = 0;
18✔
1938

1939
        CLEANUP_ARRAY(changes, n_changes, install_changes_free);
×
1940

1941
        log_info("Applying preset policy.");
18✔
1942
        r = unit_file_preset_all(RUNTIME_SCOPE_SYSTEM, /* file_flags = */ 0,
18✔
1943
                                 /* root_dir = */ NULL, mode, &changes, &n_changes);
1944
        install_changes_dump(r, "preset", changes, n_changes, /* quiet = */ false);
18✔
1945
        if (r < 0)
18✔
1946
                log_full_errno(r == -EEXIST ? LOG_NOTICE : LOG_WARNING, r,
18✔
1947
                               "Failed to populate /etc with preset unit settings, ignoring: %m");
1948
        else
1949
                log_info("Populated /etc with preset unit settings.");
18✔
1950
}
1951

1952
static void manager_ready(Manager *m) {
731✔
1953
        assert(m);
731✔
1954

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

1957
        m->objective = MANAGER_OK; /* Tell everyone we are up now */
731✔
1958

1959
        /* It might be safe to log to the journal now and connect to dbus */
1960
        manager_recheck_journal(m);
731✔
1961
        manager_recheck_dbus(m);
731✔
1962

1963
        /* Let's finally catch up with any changes that took place while we were reloading/reexecing */
1964
        manager_catchup(m);
731✔
1965

1966
        /* Create a file which will indicate when the manager started loading units the last time. */
1967
        if (MANAGER_IS_SYSTEM(m))
731✔
1968
                (void) touch_file("/run/systemd/systemd-units-load", false,
527✔
1969
                        m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].realtime ?: now(CLOCK_REALTIME),
527✔
1970
                        UID_INVALID, GID_INVALID, 0444);
1971
}
731✔
1972

1973
Manager* manager_reloading_start(Manager *m) {
151✔
1974
        m->n_reloading++;
151✔
1975
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
151✔
1976
        return m;
151✔
1977
}
1978

1979
void manager_reloading_stopp(Manager **m) {
837✔
1980
        if (*m) {
837✔
1981
                assert((*m)->n_reloading > 0);
126✔
1982
                (*m)->n_reloading--;
126✔
1983
        }
1984
}
837✔
1985

1986
static int manager_make_runtime_dir(Manager *m) {
706✔
1987
        int r;
706✔
1988

1989
        assert(m);
706✔
1990

1991
        _cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
1,412✔
1992
        if (!d)
706✔
1993
                return log_oom();
×
1994

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

1999
        return 0;
2000
}
2001

2002
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
706✔
2003
        int r;
706✔
2004

2005
        assert(m);
706✔
2006

2007
        r = manager_make_runtime_dir(m);
706✔
2008
        if (r < 0)
706✔
2009
                return r;
2010

2011
        /* If we are running in test mode, we still want to run the generators,
2012
         * but we should not touch the real generator directories. */
2013
        r = lookup_paths_init_or_warn(&m->lookup_paths, m->runtime_scope,
706✔
2014
                                      MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
706✔
2015
                                      root);
2016
        if (r < 0)
706✔
2017
                return r;
2018

2019
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
706✔
2020
        r = manager_run_environment_generators(m);
706✔
2021
        if (r >= 0)
706✔
2022
                r = manager_run_generators(m);
706✔
2023
        dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
706✔
2024
        if (r < 0)
706✔
2025
                return r;
2026

2027
        manager_preset_all(m);
706✔
2028

2029
        lookup_paths_log(&m->lookup_paths);
706✔
2030

2031
        {
2032
                /* This block is (optionally) done with the reloading counter bumped */
2033
                _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
706✔
2034

2035
                /* Make sure we don't have a left-over from a previous run */
2036
                if (!serialization)
706✔
2037
                        (void) rm_rf(m->lookup_paths.transient, 0);
686✔
2038

2039
                /* If we will deserialize make sure that during enumeration this is already known, so we increase the
2040
                 * counter here already */
2041
                if (serialization)
20✔
2042
                        reloading = manager_reloading_start(m);
20✔
2043

2044
                /* First, enumerate what we can from all config files */
2045
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
706✔
2046
                manager_enumerate_perpetual(m);
706✔
2047
                manager_enumerate(m);
706✔
2048
                dual_timestamp_now(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
706✔
2049

2050
                /* Second, deserialize if there is something to deserialize */
2051
                if (serialization) {
706✔
2052
                        r = manager_deserialize(m, serialization, fds);
20✔
2053
                        if (r < 0)
20✔
2054
                                return log_error_errno(r, "Deserialization failed: %m");
×
2055
                }
2056

2057
                if (m->previous_objective >= 0) {
706✔
2058
                        if (IN_SET(m->previous_objective, MANAGER_REEXECUTE, MANAGER_SOFT_REBOOT, MANAGER_SWITCH_ROOT))
20✔
2059
                                log_debug("Launching as effect of a '%s' operation.",
20✔
2060
                                          manager_objective_to_string(m->previous_objective));
2061
                        else
2062
                                log_warning("Got unexpected previous objective '%s', ignoring.",
×
2063
                                            manager_objective_to_string(m->previous_objective));
2064
                }
2065

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

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

2076
                /* We might have deserialized the notify fd, but if we didn't then let's create it now */
2077
                r = manager_setup_notify(m);
706✔
2078
                if (r < 0)
706✔
2079
                        /* No sense to continue without notifications, our children would fail anyway. */
2080
                        return r;
2081

2082
                r = manager_setup_user_lookup_fd(m);
706✔
2083
                if (r < 0)
706✔
2084
                        /* This shouldn't fail, except if things are really broken. */
2085
                        return r;
2086

2087
                r = manager_setup_handoff_timestamp_fd(m);
706✔
2088
                if (r < 0)
706✔
2089
                        /* This shouldn't fail, except if things are really broken. */
2090
                        return r;
2091

2092
                r = manager_setup_pidref_transport_fd(m);
706✔
2093
                if (r < 0)
706✔
2094
                        /* This shouldn't fail, except if things are really broken. */
2095
                        return r;
2096

2097
                /* Connect to the bus if we are good for it */
2098
                manager_setup_bus(m);
706✔
2099

2100
                r = manager_varlink_init(m);
706✔
2101
                if (r < 0)
706✔
2102
                        log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
×
2103

2104
                /* Third, fire things up! */
2105
                manager_coldplug(m);
706✔
2106

2107
                /* Clean up runtime objects */
2108
                manager_vacuum(m);
706✔
2109

2110
                if (serialization)
706✔
2111
                        /* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
2112
                         * reload is finished */
2113
                        m->send_reloading_done = true;
20✔
2114
        }
2115

2116
        manager_ready(m);
706✔
2117

2118
        manager_set_switching_root(m, false);
706✔
2119

2120
        return 0;
706✔
2121
}
2122

2123
int manager_add_job_full(
1,351✔
2124
                Manager *m,
2125
                JobType type,
2126
                Unit *unit,
2127
                JobMode mode,
2128
                TransactionAddFlags extra_flags,
2129
                Set *affected_jobs,
2130
                sd_bus_error *error,
2131
                Job **ret) {
2132

2133
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,351✔
2134
        int r;
1,351✔
2135

2136
        assert(m);
1,351✔
2137
        assert(type >= 0 && type < _JOB_TYPE_MAX);
1,351✔
2138
        assert(unit);
1,351✔
2139
        assert(mode >= 0 && mode < _JOB_MODE_MAX);
1,351✔
2140
        assert((extra_flags & ~_TRANSACTION_FLAGS_MASK_PUBLIC) == 0);
1,351✔
2141

2142
        if (mode == JOB_ISOLATE && type != JOB_START)
1,351✔
2143
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
×
2144

2145
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,351✔
2146
                return sd_bus_error_set(error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
25✔
2147

2148
        if (mode == JOB_TRIGGERING && type != JOB_STOP)
1,326✔
2149
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
×
2150

2151
        if (mode == JOB_RESTART_DEPENDENCIES && type != JOB_START)
1,326✔
2152
                return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=restart-dependencies is only valid for start.");
×
2153

2154
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1,326✔
2155

2156
        type = job_type_collapse(type, unit);
1,326✔
2157

2158
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1,326✔
2159
        if (!tr)
1,326✔
2160
                return -ENOMEM;
2161

2162
        r = transaction_add_job_and_dependencies(
3,978✔
2163
                        tr,
2164
                        type,
2165
                        unit,
2166
                        /* by= */ NULL,
2167
                        TRANSACTION_MATTERS |
2168
                        (IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
1,326✔
2169
                        (mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
1,326✔
2170
                        (mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
2,647✔
2171
                        extra_flags,
2172
                        error);
2173
        if (r < 0)
1,326✔
2174
                return r;
2175

2176
        if (mode == JOB_ISOLATE) {
1,318✔
2177
                r = transaction_add_isolate_jobs(tr, m);
202✔
2178
                if (r < 0)
202✔
2179
                        return r;
2180
        }
2181

2182
        if (mode == JOB_TRIGGERING) {
1,318✔
2183
                r = transaction_add_triggering_jobs(tr, unit);
×
2184
                if (r < 0)
×
2185
                        return r;
2186
        }
2187

2188
        r = transaction_activate(tr, m, mode, affected_jobs, error);
1,318✔
2189
        if (r < 0)
1,318✔
2190
                return r;
2191

2192
        log_unit_debug(unit,
1,308✔
2193
                       "Enqueued job %s/%s as %u", unit->id,
2194
                       job_type_to_string(type), (unsigned) tr->anchor_job->id);
2195

2196
        if (ret)
1,308✔
2197
                *ret = tr->anchor_job;
730✔
2198

2199
        tr = transaction_free(tr);
1,308✔
2200
        return 0;
1,308✔
2201
}
2202

2203
int manager_add_job(
834✔
2204
        Manager *m,
2205
        JobType type,
2206
        Unit *unit,
2207
        JobMode mode,
2208
        sd_bus_error *error,
2209
        Job **ret) {
2210

2211
        return manager_add_job_full(m, type, unit, mode, 0, NULL, error, ret);
834✔
2212
}
2213

2214
int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
204✔
2215
        Unit *unit = NULL;  /* just to appease gcc, initialization is not really necessary */
204✔
2216
        int r;
204✔
2217

2218
        assert(m);
204✔
2219
        assert(type < _JOB_TYPE_MAX);
204✔
2220
        assert(name);
204✔
2221
        assert(mode < _JOB_MODE_MAX);
204✔
2222

2223
        r = manager_load_unit(m, name, NULL, NULL, &unit);
204✔
2224
        if (r < 0)
204✔
2225
                return r;
204✔
2226
        assert(unit);
204✔
2227

2228
        return manager_add_job_full(m, type, unit, mode, /* extra_flags = */ 0, affected_jobs, e, ret);
204✔
2229
}
2230

2231
int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
186✔
2232
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
186✔
2233
        int r;
186✔
2234

2235
        assert(m);
186✔
2236
        assert(type < _JOB_TYPE_MAX);
186✔
2237
        assert(name);
186✔
2238
        assert(mode < _JOB_MODE_MAX);
186✔
2239

2240
        r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
186✔
2241
        if (r < 0)
186✔
2242
                return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
×
2243

2244
        return r;
2245
}
2246

2247
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
17,662✔
2248
        int r;
17,662✔
2249
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
17,662✔
2250

2251
        assert(m);
17,662✔
2252
        assert(unit);
17,662✔
2253
        assert(mode < _JOB_MODE_MAX);
17,662✔
2254
        assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
17,662✔
2255

2256
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
17,662✔
2257
        if (!tr)
17,662✔
2258
                return -ENOMEM;
2259

2260
        /* We need an anchor job */
2261
        r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
17,662✔
2262
        if (r < 0)
17,662✔
2263
                return r;
2264

2265
        /* Failure in adding individual dependencies is ignored, so this always succeeds. */
2266
        transaction_add_propagate_reload_jobs(
17,662✔
2267
                        tr,
2268
                        unit,
2269
                        tr->anchor_job,
17,662✔
2270
                        mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0);
2271

2272
        r = transaction_activate(tr, m, mode, NULL, e);
17,662✔
2273
        if (r < 0)
17,662✔
2274
                return r;
2275

2276
        tr = transaction_free(tr);
17,662✔
2277
        return 0;
17,662✔
2278
}
2279

2280
Job *manager_get_job(Manager *m, uint32_t id) {
15,983✔
2281
        assert(m);
15,983✔
2282

2283
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
15,983✔
2284
}
2285

2286
Unit *manager_get_unit(Manager *m, const char *name) {
1,604,432✔
2287
        assert(m);
1,604,432✔
2288
        assert(name);
1,604,432✔
2289

2290
        return hashmap_get(m->units, name);
1,604,432✔
2291
}
2292

2293
static int manager_dispatch_target_deps_queue(Manager *m) {
217,446✔
2294
        Unit *u;
217,446✔
2295
        int r = 0;
217,446✔
2296

2297
        assert(m);
217,446✔
2298

2299
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
275,954✔
2300
                _cleanup_free_ Unit **targets = NULL;
58,508✔
2301
                int n_targets;
58,508✔
2302

2303
                assert(u->in_target_deps_queue);
58,508✔
2304

2305
                u->in_target_deps_queue = false;
58,508✔
2306

2307
                /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2308
                 * dependencies, and we can't have it that hash tables we iterate through are modified while
2309
                 * we are iterating through them. */
2310
                n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
58,508✔
2311
                if (n_targets < 0)
58,508✔
2312
                        return n_targets;
2313

2314
                FOREACH_ARRAY(i, targets, n_targets) {
112,088✔
2315
                        r = unit_add_default_target_dependency(u, *i);
53,580✔
2316
                        if (r < 0)
53,580✔
2317
                                return r;
2318
                }
2319
        }
2320

2321
        return r;
2322
}
2323

2324
unsigned manager_dispatch_load_queue(Manager *m) {
244,756✔
2325
        Unit *u;
244,756✔
2326
        unsigned n = 0;
244,756✔
2327

2328
        assert(m);
244,756✔
2329

2330
        /* Make sure we are not run recursively */
2331
        if (m->dispatching_load_queue)
244,756✔
2332
                return 0;
2333

2334
        m->dispatching_load_queue = true;
217,446✔
2335

2336
        /* Dispatches the load queue. Takes a unit from the queue and
2337
         * tries to load its data until the queue is empty */
2338

2339
        while ((u = m->load_queue)) {
297,664✔
2340
                assert(u->in_load_queue);
80,218✔
2341

2342
                unit_load(u);
80,218✔
2343
                n++;
80,218✔
2344
        }
2345

2346
        m->dispatching_load_queue = false;
217,446✔
2347

2348
        /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2349
         * should be loaded and have aliases resolved */
2350
        (void) manager_dispatch_target_deps_queue(m);
217,446✔
2351

2352
        return n;
217,446✔
2353
}
2354

2355
bool manager_unit_cache_should_retry_load(Unit *u) {
437,957✔
2356
        assert(u);
437,957✔
2357

2358
        /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2359
         * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2360
         * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
2361
        if (u->load_state != UNIT_NOT_FOUND)
437,957✔
2362
                return false;
2363

2364
        /* The cache has been updated since the last time we tried to load the unit. There might be new
2365
         * fragment paths to read. */
2366
        if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
2,466✔
2367
                return true;
2368

2369
        /* The cache needs to be updated because there are modifications on disk. */
2370
        return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
2,466✔
2371
}
2372

2373
int manager_load_unit_prepare(
417,096✔
2374
                Manager *m,
2375
                const char *name,
2376
                const char *path,
2377
                sd_bus_error *e,
2378
                Unit **ret) {
2379

2380
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2381
        _cleanup_free_ char *nbuf = NULL;
417,096✔
2382
        int r;
417,096✔
2383

2384
        assert(m);
417,096✔
2385
        assert(ret);
417,096✔
2386
        assert(name || path);
417,096✔
2387

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

2390
        if (path && !path_is_absolute(path))
417,096✔
2391
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2392

2393
        if (!name) {
417,096✔
2394
                r = path_extract_filename(path, &nbuf);
449✔
2395
                if (r < 0)
449✔
2396
                        return r;
2397
                if (r == O_DIRECTORY)
449✔
2398
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2399

2400
                name = nbuf;
449✔
2401
        }
2402

2403
        UnitType t = unit_name_to_type(name);
417,096✔
2404

2405
        if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
417,096✔
2406
                if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
×
2407
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
×
2408

2409
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
×
2410
        }
2411

2412
        Unit *unit = manager_get_unit(m, name);
417,096✔
2413
        if (unit) {
417,096✔
2414
                /* The time-based cache allows new units to be started without daemon-reload,
2415
                 * but if they are already referenced (because of dependencies or ordering)
2416
                 * then we have to force a load of the fragment. As an optimization, check
2417
                 * first if anything in the usual paths was modified since the last time
2418
                 * the cache was loaded. Also check if the last time an attempt to load the
2419
                 * unit was made was before the most recent cache refresh, so that we know
2420
                 * we need to try again — even if the cache is current, it might have been
2421
                 * updated in a different context before we had a chance to retry loading
2422
                 * this particular unit. */
2423
                if (manager_unit_cache_should_retry_load(unit))
367,477✔
2424
                        unit->load_state = UNIT_STUB;
×
2425
                else {
2426
                        *ret = unit;
367,477✔
2427
                        return 0;  /* The unit was already loaded */
367,477✔
2428
                }
2429
        } else {
2430
                unit = cleanup_unit = unit_new(m, unit_vtable[t]->object_size);
49,619✔
2431
                if (!unit)
49,619✔
2432
                        return -ENOMEM;
2433
        }
2434

2435
        if (path) {
49,619✔
2436
                r = free_and_strdup(&unit->fragment_path, path);
449✔
2437
                if (r < 0)
449✔
2438
                        return r;
2439
        }
2440

2441
        r = unit_add_name(unit, name);
49,619✔
2442
        if (r < 0)
49,619✔
2443
                return r;
2444

2445
        unit_add_to_load_queue(unit);
49,619✔
2446
        unit_add_to_dbus_queue(unit);
49,619✔
2447
        unit_add_to_gc_queue(unit);
49,619✔
2448

2449
        *ret = unit;
49,619✔
2450
        TAKE_PTR(cleanup_unit);
49,619✔
2451

2452
        return 1;  /* The unit was added the load queue */
49,619✔
2453
}
2454

2455
int manager_load_unit(
397,054✔
2456
                Manager *m,
2457
                const char *name,
2458
                const char *path,
2459
                sd_bus_error *e,
2460
                Unit **ret) {
2461
        int r;
397,054✔
2462

2463
        assert(m);
397,054✔
2464
        assert(ret);
397,054✔
2465

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

2468
        r = manager_load_unit_prepare(m, name, path, e, ret);
397,054✔
2469
        if (r <= 0)
397,054✔
2470
                return r;
2471

2472
        /* Unit was newly loaded */
2473
        manager_dispatch_load_queue(m);
29,610✔
2474
        *ret = unit_follow_merge(*ret);
29,610✔
2475
        return 0;
29,610✔
2476
}
2477

2478
int manager_load_startable_unit_or_warn(
705✔
2479
                Manager *m,
2480
                const char *name,
2481
                const char *path,
2482
                Unit **ret) {
2483

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

2486
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
705✔
2487
        Unit *unit;
705✔
2488
        int r;
705✔
2489

2490
        r = manager_load_unit(m, name, path, &error, &unit);
705✔
2491
        if (r < 0)
705✔
2492
                return log_error_errno(r, "Failed to load %s %s: %s",
×
2493
                                       name ? "unit" : "unit file", name ?: path,
2494
                                       bus_error_message(&error, r));
2495

2496
        r = bus_unit_validate_load_state(unit, &error);
705✔
2497
        if (r < 0)
705✔
2498
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2499

2500
        *ret = unit;
696✔
2501
        return 0;
696✔
2502
}
2503

2504
void manager_clear_jobs(Manager *m) {
439✔
2505
        Job *j;
439✔
2506

2507
        assert(m);
439✔
2508

2509
        while ((j = hashmap_first(m->jobs)))
466✔
2510
                /* No need to recurse. We're cancelling all jobs. */
2511
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
27✔
2512
}
439✔
2513

2514
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
2,281✔
2515
        assert(m);
2,281✔
2516

2517
        for (;;) {
×
2518
                Unit *u;
2,281✔
2519

2520
                u = manager_get_unit_by_pidref_watching(m, pid);
2,281✔
2521
                if (!u)
2,281✔
2522
                        break;
2523

2524
                unit_unwatch_pidref(u, pid);
×
2525
        }
2526
}
2,281✔
2527

2528
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
6,271✔
2529
        Manager *m = ASSERT_PTR(userdata);
6,271✔
2530
        Job *j;
6,271✔
2531

2532
        assert(source);
6,271✔
2533

2534
        while ((j = prioq_peek(m->run_queue))) {
60,657✔
2535
                assert(j->installed);
54,386✔
2536
                assert(j->in_run_queue);
54,386✔
2537

2538
                (void) job_run_and_invalidate(j);
54,386✔
2539
        }
2540

2541
        if (m->n_running_jobs > 0)
6,271✔
2542
                manager_watch_jobs_in_progress(m);
3,215✔
2543

2544
        if (m->n_on_console > 0)
6,271✔
2545
                manager_watch_idle_pipe(m);
437✔
2546

2547
        return 1;
6,271✔
2548
}
2549

2550
void manager_trigger_run_queue(Manager *m) {
56,605✔
2551
        int r;
56,605✔
2552

2553
        assert(m);
56,605✔
2554

2555
        r = sd_event_source_set_enabled(
113,036✔
2556
                        m->run_queue_event_source,
2557
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
56,605✔
2558
        if (r < 0)
56,605✔
2559
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2560
}
56,605✔
2561

2562
static unsigned manager_dispatch_dbus_queue(Manager *m) {
174,296✔
2563
        unsigned n = 0, budget;
174,296✔
2564
        Unit *u;
174,296✔
2565
        Job *j;
174,296✔
2566

2567
        assert(m);
174,296✔
2568

2569
        /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2570
         * as we can. There's no point in throttling generation of signals in that case. */
2571
        if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message)
174,296✔
2572
                budget = UINT_MAX; /* infinite budget in this case */
2573
        else {
2574
                /* Anything to do at all? */
2575
                if (!m->dbus_unit_queue && !m->dbus_job_queue)
174,251✔
2576
                        return 0;
2577

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

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

2597
        while (budget != 0 && (u = m->dbus_unit_queue)) {
31,532✔
2598

2599
                assert(u->in_dbus_queue);
23,156✔
2600

2601
                bus_unit_send_change_signal(u);
23,156✔
2602
                n++;
23,156✔
2603

2604
                if (budget != UINT_MAX)
23,156✔
2605
                        budget--;
12,213✔
2606
        }
2607

2608
        while (budget != 0 && (j = m->dbus_job_queue)) {
43,387✔
2609
                assert(j->in_dbus_queue);
35,011✔
2610

2611
                bus_job_send_change_signal(j);
35,011✔
2612
                n++;
35,011✔
2613

2614
                if (budget != UINT_MAX)
35,011✔
2615
                        budget--;
34,621✔
2616
        }
2617

2618
        if (m->send_reloading_done) {
8,376✔
2619
                m->send_reloading_done = false;
45✔
2620
                bus_manager_send_reloading(m, false);
45✔
2621
                n++;
45✔
2622
        }
2623

2624
        if (m->pending_reload_message) {
8,376✔
2625
                bus_send_pending_reload_message(m);
25✔
2626
                n++;
25✔
2627
        }
2628

2629
        return n;
2630
}
2631

2632
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
3,003✔
2633

2634
        /* nothing else must be sent when using BARRIER=1 */
2635
        if (strv_contains(tags, "BARRIER=1")) {
3,003✔
2636
                if (strv_length(tags) != 1)
12✔
2637
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
×
2638
                else if (fdset_size(fds) != 1)
12✔
2639
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
×
2640

2641
                /* Drop the message if BARRIER=1 was found */
2642
                return true;
12✔
2643
        }
2644

2645
        return false;
2646
}
2647

2648
static void manager_invoke_notify_message(
5,847✔
2649
                Manager *m,
2650
                Unit *u,
2651
                PidRef *pidref,
2652
                const struct ucred *ucred,
2653
                char * const *tags,
2654
                FDSet *fds) {
2655

2656
        assert(m);
5,847✔
2657
        assert(u);
5,847✔
2658
        assert(pidref_is_set(pidref));
5,847✔
2659
        assert(ucred);
5,847✔
2660
        assert(pidref->pid == ucred->pid);
5,847✔
2661
        assert(tags);
5,847✔
2662

2663
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
5,847✔
2664
                return;
2665
        u->notifygen = m->notifygen;
2,990✔
2666

2667
        if (UNIT_VTABLE(u)->notify_message)
2,990✔
2668
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
2,990✔
2669

2670
        else if (DEBUG_LOGGING) {
×
2671
                _cleanup_free_ char *joined = strv_join(tags, ", ");
×
2672
                char buf[CELLESCAPE_DEFAULT_LENGTH];
×
2673

2674
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
×
2675
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
2676
        }
2677
}
2678

2679
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
9,990✔
2680
        /* Determine array of every unit that is interested in the specified process */
2681

2682
        assert(m);
9,990✔
2683
        assert(pidref_is_set(pidref));
9,990✔
2684

2685
        Unit *u1, *u2, **array;
9,990✔
2686
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
9,990✔
2687
        u2 = hashmap_get(m->watch_pids, pidref);
9,990✔
2688
        array = hashmap_get(m->watch_pids_more, pidref);
9,990✔
2689

2690
        size_t n = 0;
9,990✔
2691
        if (u1)
9,990✔
2692
                n++;
9,989✔
2693
        if (u2)
9,990✔
2694
                n++;
7,230✔
2695
        if (array)
9,990✔
2696
                for (size_t j = 0; array[j]; j++)
×
2697
                        n++;
×
2698

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

2701
        if (ret_units) {
9,990✔
2702
                _cleanup_free_ Unit **units = NULL;
×
2703

2704
                if (n > 0) {
9,990✔
2705
                        units = new(Unit*, n + 1);
9,989✔
2706
                        if (!units)
9,989✔
2707
                                return -ENOMEM;
×
2708

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

2713
                        size_t i = 0;
9,989✔
2714
                        if (u1)
9,989✔
2715
                                units[i++] = u1;
9,989✔
2716
                        if (u2)
9,989✔
2717
                                units[i++] = u2;
7,230✔
2718
                        if (array)
9,989✔
2719
                                for (size_t j = 0; array[j]; j++)
×
2720
                                        units[i++] = array[j];
×
2721
                        assert(i == n);
9,989✔
2722

2723
                        units[i] = NULL; /* end array in an extra NULL */
9,989✔
2724
                }
2725

2726
                *ret_units = TAKE_PTR(units);
9,990✔
2727
        }
2728

2729
        return (int) n;
9,990✔
2730
}
2731

2732
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,003✔
2733
        Manager *m = ASSERT_PTR(userdata);
3,003✔
2734
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3,003✔
2735
        struct ucred ucred;
3,003✔
2736
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
3,003✔
2737
        int r;
3,003✔
2738

2739
        assert(m->notify_fd == fd);
3,003✔
2740

2741
        if (revents != EPOLLIN) {
3,003✔
2742
                log_warning("Got unexpected poll event for notify fd.");
×
2743
                return 0;
×
2744
        }
2745

2746
        _cleanup_strv_free_ char **tags = NULL;
3,003✔
2747
        r = notify_recv_with_fds_strv(m->notify_fd, &tags, &ucred, &pidref, &fds);
3,003✔
2748
        if (r == -EAGAIN)
3,003✔
2749
                return 0;
2750
        if (r < 0)
3,003✔
2751
                /* If this is any other, real error, then stop processing this socket. This of course means
2752
                 * we won't take notification messages anymore, but that's still better than busy looping:
2753
                 * being woken up over and over again, but being unable to actually read the message from the
2754
                 * socket. */
2755
                return r;
2756

2757
        /* Possibly a barrier fd, let's see. */
2758
        if (manager_process_barrier_fd(tags, fds)) {
3,003✔
2759
                log_debug("Received barrier notification message from PID " PID_FMT ".", pidref.pid);
12✔
2760
                return 0;
12✔
2761
        }
2762

2763
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
2764
        m->notifygen++;
2,991✔
2765

2766
        /* Notify every unit that might be interested, which might be multiple. */
2767
        _cleanup_free_ Unit **array = NULL;
2,991✔
2768

2769
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
2,991✔
2770
        if (n_array < 0) {
2,991✔
2771
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", pidref.pid);
×
2772
                return 0;
×
2773
        }
2774
        if (n_array == 0)
2,991✔
2775
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", pidref.pid);
1✔
2776
        else
2777
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
2778
                 * duplicate units – making sure we only invoke each unit's handler once. */
2779
                FOREACH_ARRAY(u, array, n_array)
8,837✔
2780
                        manager_invoke_notify_message(m, *u, &pidref, &ucred, tags, fds);
5,847✔
2781

2782
        if (!fdset_isempty(fds))
2,991✔
2783
                log_warning("Got extra auxiliary fds with notification message, closing them.");
×
2784

2785
        return 0;
2786
}
2787

2788
static void manager_invoke_sigchld_event(
6,848✔
2789
                Manager *m,
2790
                Unit *u,
2791
                const siginfo_t *si) {
2792

2793
        assert(m);
6,848✔
2794
        assert(u);
6,848✔
2795
        assert(si);
6,848✔
2796

2797
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2798
        if (u->sigchldgen == m->sigchldgen)
6,848✔
2799
                return;
2,105✔
2800
        u->sigchldgen = m->sigchldgen;
4,743✔
2801

2802
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
4,743✔
2803
        unit_unwatch_pidref(u, &PIDREF_MAKE_FROM_PID(si->si_pid));
4,743✔
2804

2805
        if (UNIT_VTABLE(u)->sigchld_event)
4,743✔
2806
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
4,608✔
2807
}
2808

2809
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
8,497✔
2810
        Manager *m = ASSERT_PTR(userdata);
8,497✔
2811
        siginfo_t si = {};
8,497✔
2812
        int r;
8,497✔
2813

2814
        assert(source);
8,497✔
2815

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

2819
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
8,497✔
2820

2821
                if (errno != ECHILD)
80✔
2822
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
×
2823

2824
                goto turn_off;
80✔
2825
        }
2826

2827
        if (si.si_pid <= 0)
8,417✔
2828
                goto turn_off;
3,680✔
2829

2830
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
4,737✔
2831
                _cleanup_free_ char *name = NULL;
9,474✔
2832
                (void) pid_get_comm(si.si_pid, &name);
4,737✔
2833

2834
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
9,341✔
2835
                          si.si_pid, strna(name),
2836
                          sigchld_code_to_string(si.si_code),
2837
                          si.si_status,
2838
                          strna(si.si_code == CLD_EXITED
2839
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2840
                                : signal_to_string(si.si_status)));
2841

2842
                /* Increase the generation counter used for filtering out duplicate unit invocations */
2843
                m->sigchldgen++;
4,737✔
2844

2845
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
2846
                 * pidfd here any more even if we wanted (since the process just exited). */
2847
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
4,737✔
2848

2849
                /* And now figure out the units this belongs to, there might be multiple... */
2850
                _cleanup_free_ Unit **array = NULL;
4,737✔
2851
                int n_array = manager_get_units_for_pidref(m, &pidref, &array);
4,737✔
2852
                if (n_array < 0)
4,737✔
2853
                        log_warning_errno(n_array, "Failed to get units for process " PID_FMT ", ignoring: %m", si.si_pid);
4,737✔
2854
                else if (n_array == 0)
4,737✔
2855
                        log_debug("Got SIGCHLD for process " PID_FMT " we weren't interested in, ignoring.", si.si_pid);
×
2856
                else {
2857
                        /* We check for an OOM condition, in case we got SIGCHLD before the OOM notification.
2858
                         * We only do this for the cgroup the PID belonged to, which is the f */
2859
                        (void) unit_check_oom(array[0]);
4,737✔
2860

2861
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
2862
                        (void) unit_check_oomd_kill(array[0]);
4,737✔
2863

2864
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
2865
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
2866
                         * iteration. */
2867
                        FOREACH_ARRAY(u, array, n_array)
11,585✔
2868
                                manager_invoke_sigchld_event(m, *u, &si);
6,848✔
2869
                }
2870
        }
2871

2872
        /* And now, we actually reap the zombie. */
2873
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
4,737✔
2874
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
×
2875
                return 0;
8,497✔
2876
        }
2877

2878
        return 0;
2879

2880
turn_off:
3,760✔
2881
        /* All children processed for now, turn off event source */
2882

2883
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
3,760✔
2884
        if (r < 0)
3,760✔
2885
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
×
2886

2887
        return 0;
2888
}
2889

2890
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
184✔
2891
        Job *job;
184✔
2892

2893
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
184✔
2894
                return;
×
2895

2896
        const char *s = unit_status_string(job->unit, NULL);
184✔
2897

2898
        log_info("Activating special unit %s...", s);
184✔
2899

2900
        (void) sd_notifyf(/* unset_environment= */ false,
184✔
2901
                          "STATUS=Activating special unit %s...", s);
2902
        m->status_ready = false;
184✔
2903
}
2904

2905
static void manager_handle_ctrl_alt_del(Manager *m) {
×
2906
        assert(m);
×
2907

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

2911
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
×
2912
                manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
×
2913
        else
2914
                emergency_action(
×
2915
                                m,
2916
                                m->cad_burst_action,
2917
                                EMERGENCY_ACTION_WARN,
2918
                                /* reboot_arg= */ NULL,
2919
                                /* exit_status= */ -1,
2920
                                "Ctrl-Alt-Del was pressed more than 7 times within 2s");
2921
}
×
2922

2923
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,688✔
2924
        Manager *m = ASSERT_PTR(userdata);
3,688✔
2925
        ssize_t n;
3,688✔
2926
        struct signalfd_siginfo sfsi;
3,688✔
2927
        int r;
3,688✔
2928

2929
        assert(m->signal_fd == fd);
3,688✔
2930

2931
        if (revents != EPOLLIN) {
3,688✔
2932
                log_warning("Got unexpected events from signal file descriptor.");
×
2933
                return 0;
×
2934
        }
2935

2936
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
3,688✔
2937
        if (n < 0) {
3,688✔
2938
                if (ERRNO_IS_TRANSIENT(errno))
×
2939
                        return 0;
2940

2941
                /* We return an error here, which will kill this handler,
2942
                 * to avoid a busy loop on read error. */
2943
                return log_error_errno(errno, "Reading from signal fd failed: %m");
×
2944
        }
2945
        if (n != sizeof(sfsi)) {
3,688✔
2946
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
×
2947
                return 0;
×
2948
        }
2949

2950
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
3,872✔
2951
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
184✔
2952
                            ? LOG_DEBUG : LOG_INFO,
2953
                            &sfsi);
2954

2955
        switch (sfsi.ssi_signo) {
3,688✔
2956

2957
        case SIGCHLD:
3,504✔
2958
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
3,504✔
2959
                if (r < 0)
3,504✔
2960
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
3,688✔
2961

2962
                break;
2963

2964
        case SIGTERM:
184✔
2965
                if (MANAGER_IS_SYSTEM(m)) {
184✔
2966
                        /* This is for compatibility with the original sysvinit */
2967
                        m->objective = MANAGER_REEXECUTE;
×
2968
                        break;
×
2969
                }
2970

2971
                _fallthrough_;
184✔
2972
        case SIGINT:
2973
                if (MANAGER_IS_SYSTEM(m))
184✔
2974
                        manager_handle_ctrl_alt_del(m);
×
2975
                else
2976
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
184✔
2977
                break;
2978

2979
        case SIGWINCH:
×
2980
                /* This is a nop on non-init */
2981
                if (MANAGER_IS_SYSTEM(m))
×
2982
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
×
2983

2984
                break;
2985

2986
        case SIGPWR:
×
2987
                /* This is a nop on non-init */
2988
                if (MANAGER_IS_SYSTEM(m))
×
2989
                        manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
×
2990

2991
                break;
2992

2993
        case SIGUSR1:
×
2994
                if (manager_dbus_is_running(m, false)) {
×
2995
                        log_info("Trying to reconnect to bus...");
×
2996

2997
                        (void) bus_init_api(m);
×
2998

2999
                        if (MANAGER_IS_SYSTEM(m))
×
3000
                                (void) bus_init_system(m);
×
3001
                } else
3002
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
×
3003

3004
                break;
3005

3006
        case SIGUSR2: {
×
3007
                _cleanup_free_ char *dump = NULL;
×
3008

3009
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
×
3010
                if (r < 0) {
×
3011
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
×
3012
                        break;
3013
                }
3014

3015
                log_dump(LOG_INFO, dump);
×
3016
                break;
3017
        }
3018

3019
        case SIGHUP:
×
3020
                m->objective = MANAGER_RELOAD;
×
3021
                break;
×
3022

3023
        default: {
×
3024

3025
                if (MANAGER_IS_SYSTEM(m)) {
×
3026
                        /* Starting SIGRTMIN+0 */
3027
                        static const struct {
×
3028
                                const char *target;
3029
                                JobMode mode;
3030
                        } target_table[] = {
3031
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
3032
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
3033
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
3034
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
3035
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
3036
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
3037
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
3038
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
3039
                        };
3040

3041
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
3042
                        static const ManagerObjective objective_table[] = {
×
3043
                                [0] = MANAGER_HALT,
3044
                                [1] = MANAGER_POWEROFF,
3045
                                [2] = MANAGER_REBOOT,
3046
                                [3] = MANAGER_KEXEC,
3047
                                [4] = MANAGER_SOFT_REBOOT,
3048
                        };
3049

3050
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
×
3051
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
×
3052
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
×
3053
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
×
3054
                                break;
3055
                        }
3056

3057
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
×
3058
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
×
3059
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
×
3060
                                break;
×
3061
                        }
3062
                }
3063

3064
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3065

3066
                case 18: {
×
3067
                        bool generic = false;
×
3068

3069
                        if (sfsi.ssi_code != SI_QUEUE)
×
3070
                                generic = true;
3071
                        else {
3072
                                /* Override a few select commands by our own PID1-specific logic */
3073

3074
                                switch (sfsi.ssi_int) {
×
3075

3076
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
×
3077
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
×
3078
                                        break;
3079

3080
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3081
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3082
                                        break;
3083

3084
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3085
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3086
                                        break;
3087

3088
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3089
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3090
                                        break;
3091

3092
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3093
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3094
                                        break;
3095

3096
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3097
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3098

3099
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
×
3100
                                        if (r < 0) {
×
3101
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
×
3102
                                                break;
3103
                                        }
3104

3105
                                        log_dump(LOG_INFO, dump_jobs);
×
3106
                                        break;
3107
                                }
3108

3109
                                default:
3110
                                        generic = true;
3111
                                }
3112
                        }
3113

3114
                        if (generic)
×
3115
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3116

3117
                        break;
3118
                }
3119

3120
                case 20:
×
3121
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
×
3122
                        break;
3123

3124
                case 21:
×
3125
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
×
3126
                        break;
3127

3128
                case 22:
×
3129
                        manager_override_log_level(m, LOG_DEBUG);
×
3130
                        break;
3131

3132
                case 23:
×
3133
                        manager_restore_original_log_level(m);
×
3134
                        break;
3135

3136
                case 24:
×
3137
                        if (MANAGER_IS_USER(m)) {
×
3138
                                m->objective = MANAGER_EXIT;
×
3139
                                return 0;
×
3140
                        }
3141

3142
                        /* This is a nop on init */
3143
                        break;
3144

3145
                case 25:
×
3146
                        m->objective = MANAGER_REEXECUTE;
×
3147
                        break;
×
3148

3149
                case 26:
×
3150
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
3151
                        manager_restore_original_log_target(m);
×
3152
                        break;
3153

3154
                case 27:
×
3155
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3156
                        break;
3157

3158
                case 28:
×
3159
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3160
                        break;
3161

3162
                default:
3163
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
×
3164
                }
3165
        }}
3166

3167
        return 0;
3168
}
3169

3170
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
3171
        Manager *m = ASSERT_PTR(userdata);
3✔
3172
        Unit *u;
3✔
3173

3174
        log_struct(LOG_DEBUG,
3✔
3175
                   LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
3176
                   LOG_MESSAGE("Time has been changed"));
3177

3178
        /* Restart the watch */
3179
        (void) manager_setup_time_change(m);
3✔
3180

3181
        HASHMAP_FOREACH(u, m->units)
402✔
3182
                if (UNIT_VTABLE(u)->time_change)
396✔
3183
                        UNIT_VTABLE(u)->time_change(u);
3✔
3184

3185
        return 0;
3✔
3186
}
3187

3188
static int manager_dispatch_timezone_change(
58✔
3189
                sd_event_source *source,
3190
                const struct inotify_event *e,
3191
                void *userdata) {
3192

3193
        Manager *m = ASSERT_PTR(userdata);
58✔
3194
        int changed;
58✔
3195
        Unit *u;
58✔
3196

3197
        log_debug("inotify event for /etc/localtime");
58✔
3198

3199
        changed = manager_read_timezone_stat(m);
58✔
3200
        if (changed <= 0)
58✔
3201
                return changed;
58✔
3202

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

3206
        /* Read the new timezone */
3207
        tzset();
31✔
3208

3209
        log_debug("Timezone has been changed (now: %s).", tzname[daylight]);
31✔
3210

3211
        HASHMAP_FOREACH(u, m->units)
6,112✔
3212
                if (UNIT_VTABLE(u)->timezone_change)
6,050✔
3213
                        UNIT_VTABLE(u)->timezone_change(u);
67✔
3214

3215
        return 0;
31✔
3216
}
3217

3218
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
11✔
3219
        Manager *m = ASSERT_PTR(userdata);
11✔
3220

3221
        assert(m->idle_pipe[2] == fd);
11✔
3222

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

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

3234
        return 0;
11✔
3235
}
3236

UNCOV
3237
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
×
UNCOV
3238
        Manager *m = ASSERT_PTR(userdata);
×
UNCOV
3239
        int r;
×
3240

UNCOV
3241
        assert(source);
×
3242

UNCOV
3243
        manager_print_jobs_in_progress(m);
×
3244

UNCOV
3245
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
×
UNCOV
3246
        if (r < 0)
×
3247
                return r;
3248

UNCOV
3249
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
×
3250
}
3251

3252
int manager_loop(Manager *m) {
260✔
3253
        RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
260✔
3254
        int r;
260✔
3255

3256
        assert(m);
260✔
3257
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
260✔
3258

3259
        manager_check_finished(m);
260✔
3260

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

3266
        while (m->objective == MANAGER_OK) {
202,993✔
3267

3268
                if (!ratelimit_below(&rl)) {
202,733✔
3269
                        /* Yay, something is going seriously wrong, pause a little */
3270
                        log_warning("Looping too fast. Throttling execution a little.");
×
3271
                        sleep(1);
×
3272
                }
3273

3274
                (void) watchdog_ping();
202,733✔
3275

3276
                if (manager_dispatch_load_queue(m) > 0)
202,733✔
3277
                        continue;
×
3278

3279
                if (manager_dispatch_gc_job_queue(m) > 0)
202,733✔
3280
                        continue;
5✔
3281

3282
                if (manager_dispatch_gc_unit_queue(m) > 0)
202,728✔
3283
                        continue;
14,908✔
3284

3285
                if (manager_dispatch_cleanup_queue(m) > 0)
187,820✔
3286
                        continue;
8,552✔
3287

3288
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
179,268✔
3289
                        continue;
3,644✔
3290

3291
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
175,624✔
3292
                        continue;
×
3293

3294
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
175,624✔
3295
                        continue;
132✔
3296

3297
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
175,492✔
3298
                        continue;
151✔
3299

3300
                if (manager_dispatch_release_resources_queue(m) > 0)
175,341✔
3301
                        continue;
1,045✔
3302

3303
                if (manager_dispatch_stop_notify_queue(m) > 0)
174,296✔
3304
                        continue;
×
3305

3306
                if (manager_dispatch_dbus_queue(m) > 0)
174,296✔
3307
                        continue;
8,376✔
3308

3309
                /* Sleep for watchdog runtime wait time */
3310
                r = sd_event_run(m->event, watchdog_runtime_wait(/* divisor= */ 2));
165,920✔
3311
                if (r < 0)
165,920✔
3312
                        return log_error_errno(r, "Failed to run event loop: %m");
×
3313
        }
3314

3315
        return m->objective;
3316
}
3317

3318
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
226,738✔
3319
        _cleanup_free_ char *n = NULL;
226,738✔
3320
        sd_id128_t invocation_id;
226,738✔
3321
        Unit *u;
226,738✔
3322
        int r;
226,738✔
3323

3324
        assert(m);
226,738✔
3325
        assert(s);
226,738✔
3326
        assert(_u);
226,738✔
3327

3328
        r = unit_name_from_dbus_path(s, &n);
226,738✔
3329
        if (r < 0)
226,738✔
3330
                return r;
3331

3332
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
3333
         * we use it as invocation ID. */
3334
        r = sd_id128_from_string(n, &invocation_id);
226,738✔
3335
        if (r >= 0) {
226,738✔
3336
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
×
3337
                if (u) {
×
3338
                        *_u = u;
×
3339
                        return 0;
×
3340
                }
3341

3342
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
×
3343
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3344
                                         SD_ID128_FORMAT_VAL(invocation_id));
×
3345
        }
3346

3347
        /* If this didn't work, we check if this is a unit name */
3348
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
226,738✔
3349
                _cleanup_free_ char *nn = NULL;
1✔
3350

3351
                nn = cescape(n);
1✔
3352
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
1✔
3353
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3354
        }
3355

3356
        r = manager_load_unit(m, n, NULL, e, &u);
226,737✔
3357
        if (r < 0)
226,737✔
3358
                return r;
3359

3360
        *_u = u;
226,737✔
3361
        return 0;
226,737✔
3362
}
3363

3364
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
640✔
3365
        const char *p;
640✔
3366
        unsigned id;
640✔
3367
        Job *j;
640✔
3368
        int r;
640✔
3369

3370
        assert(m);
640✔
3371
        assert(s);
640✔
3372
        assert(_j);
640✔
3373

3374
        p = startswith(s, "/org/freedesktop/systemd1/job/");
640✔
3375
        if (!p)
640✔
3376
                return -EINVAL;
640✔
3377

3378
        r = safe_atou(p, &id);
640✔
3379
        if (r < 0)
640✔
3380
                return r;
3381

3382
        j = manager_get_job(m, id);
640✔
3383
        if (!j)
640✔
3384
                return -ENOENT;
3385

3386
        *_j = j;
640✔
3387

3388
        return 0;
640✔
3389
}
3390

3391
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
3,502✔
3392

3393
#if HAVE_AUDIT
3394
        _cleanup_free_ char *p = NULL;
3,502✔
3395
        const char *msg;
3,502✔
3396
        int audit_fd, r;
3,502✔
3397

3398
        assert(m);
3,502✔
3399
        assert(u);
3,502✔
3400

3401
        if (!MANAGER_IS_SYSTEM(m))
3,502✔
3402
                return;
3403

3404
        /* Don't generate audit events if the service was already started and we're just deserializing */
3405
        if (MANAGER_IS_RELOADING(m))
1,812✔
3406
                return;
3407

3408
        audit_fd = get_core_audit_fd();
1,812✔
3409
        if (audit_fd < 0)
1,812✔
3410
                return;
3411

3412
        r = unit_name_to_prefix_and_instance(u->id, &p);
843✔
3413
        if (r < 0) {
843✔
3414
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
×
3415
                return;
×
3416
        }
3417

3418
        msg = strjoina("unit=", p);
4,215✔
3419
        if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
843✔
3420
                if (ERRNO_IS_PRIVILEGE(errno)) {
×
3421
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
3422
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
×
3423
                        close_core_audit_fd();
×
3424
                } else
3425
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
843✔
3426
        }
3427
#endif
3428
}
3429

3430
void manager_send_unit_plymouth(Manager *m, Unit *u) {
36,499✔
3431
        _cleanup_free_ char *message = NULL;
36,499✔
3432
        int c, r;
36,499✔
3433

3434
        assert(m);
36,499✔
3435
        assert(u);
36,499✔
3436

3437
        if (!MANAGER_IS_SYSTEM(m))
36,499✔
3438
                return;
3439

3440
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
3441
        if (MANAGER_IS_RELOADING(m))
5,357✔
3442
                return;
3443

3444
        if (detect_container() > 0)
5,357✔
3445
                return;
3446

3447
        if (!UNIT_VTABLE(u)->notify_plymouth)
3,160✔
3448
                return;
3449

3450
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
590✔
3451
        if (c < 0)
590✔
3452
                return (void) log_oom();
×
3453

3454
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
3455
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
590✔
3456
        if (r < 0)
590✔
3457
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
590✔
3458
                               "Failed to communicate with plymouth: %m");
3459
}
3460

3461
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
57,857✔
3462
        assert(m);
57,857✔
3463
        assert(u);
57,857✔
3464

3465
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
3466
         * surrounding service manager. */
3467

3468
        if (MANAGER_IS_RELOADING(m))
57,857✔
3469
                return;
3470

3471
        if (!UNIT_VTABLE(u)->notify_supervisor)
57,857✔
3472
                return;
3473

3474
        if (in_initrd()) /* Only send these once we left the initrd */
4,444✔
3475
                return;
3476

3477
        (void) sd_notifyf(/* unset_environment= */ false,
5,664✔
3478
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
3479
                          u->id);
3480
}
3481

3482
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
538✔
3483
        assert(m);
538✔
3484

3485
        if (MANAGER_IS_USER(m))
538✔
3486
                return USEC_INFINITY;
3487

3488
        if (m->watchdog_overridden[t] != USEC_INFINITY)
164✔
3489
                return m->watchdog_overridden[t];
3490

3491
        return m->watchdog[t];
164✔
3492
}
3493

3494
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
1,040✔
3495

3496
        assert(m);
1,040✔
3497

3498
        if (MANAGER_IS_USER(m))
1,040✔
3499
                return;
3500

3501
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
292✔
3502
                if (t == WATCHDOG_RUNTIME)
292✔
3503
                        (void) watchdog_setup(timeout);
73✔
3504
                else if (t == WATCHDOG_PRETIMEOUT)
219✔
3505
                        (void) watchdog_setup_pretimeout(timeout);
73✔
3506
        }
3507

3508
        m->watchdog[t] = timeout;
292✔
3509
}
3510

3511
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
×
3512
        usec_t usec;
×
3513

3514
        assert(m);
×
3515

3516
        if (MANAGER_IS_USER(m))
×
3517
                return;
3518

3519
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
×
3520
        if (t == WATCHDOG_RUNTIME)
×
3521
                (void) watchdog_setup(usec);
×
3522
        else if (t == WATCHDOG_PRETIMEOUT)
×
3523
                (void) watchdog_setup_pretimeout(usec);
×
3524

3525
        m->watchdog_overridden[t] = timeout;
×
3526
}
3527

3528
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
260✔
3529
        _cleanup_free_ char *p = NULL;
260✔
3530
        int r;
260✔
3531

3532
        assert(m);
260✔
3533

3534
        if (MANAGER_IS_USER(m))
260✔
3535
                return 0;
3536

3537
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
73✔
3538
                return 0;
3539

3540
        p = strdup(governor);
×
3541
        if (!p)
×
3542
                return -ENOMEM;
3543

3544
        r = watchdog_setup_pretimeout_governor(governor);
×
3545
        if (r < 0)
×
3546
                return r;
3547

3548
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3549
}
3550

3551
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
×
3552
        _cleanup_free_ char *p = NULL;
×
3553
        int r;
×
3554

3555
        assert(m);
×
3556

3557
        if (MANAGER_IS_USER(m))
×
3558
                return 0;
3559

3560
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3561
                return 0;
3562

3563
        p = strdup(governor);
×
3564
        if (!p)
×
3565
                return -ENOMEM;
3566

3567
        r = watchdog_setup_pretimeout_governor(governor);
×
3568
        if (r < 0)
×
3569
                return r;
3570

3571
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3572
}
3573

3574
int manager_reload(Manager *m) {
25✔
3575
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
25✔
3576
        _cleanup_fdset_free_ FDSet *fds = NULL;
×
3577
        _cleanup_fclose_ FILE *f = NULL;
25✔
3578
        int r;
25✔
3579

3580
        assert(m);
25✔
3581

3582
        r = manager_open_serialization(m, &f);
25✔
3583
        if (r < 0)
25✔
3584
                return log_error_errno(r, "Failed to create serialization file: %m");
×
3585

3586
        fds = fdset_new();
25✔
3587
        if (!fds)
25✔
3588
                return log_oom();
×
3589

3590
        /* We are officially in reload mode from here on. */
3591
        reloading = manager_reloading_start(m);
25✔
3592

3593
        r = manager_serialize(m, f, fds, false);
25✔
3594
        if (r < 0)
25✔
3595
                return r;
3596

3597
        r = finish_serialization_file(f);
25✔
3598
        if (r < 0)
25✔
3599
                return log_error_errno(r, "Failed to finish serialization: %m");
×
3600

3601
        /* 💀 This is the point of no return, from here on there is no way back. 💀 */
3602
        reloading = NULL;
25✔
3603

3604
        bus_manager_send_reloading(m, true);
25✔
3605

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

3610
        manager_clear_jobs_and_units(m);
25✔
3611
        lookup_paths_flush_generator(&m->lookup_paths);
25✔
3612
        exec_shared_runtime_vacuum(m);
25✔
3613
        dynamic_user_vacuum(m, false);
25✔
3614
        m->uid_refs = hashmap_free(m->uid_refs);
25✔
3615
        m->gid_refs = hashmap_free(m->gid_refs);
25✔
3616

3617
        (void) manager_run_environment_generators(m);
25✔
3618
        (void) manager_run_generators(m);
25✔
3619

3620
        /* We flushed out generated files, for which we don't watch mtime, so we should flush the old map. */
3621
        manager_free_unit_name_maps(m);
25✔
3622
        m->unit_file_state_outdated = false;
25✔
3623

3624
        /* First, enumerate what we can from kernel and suchlike */
3625
        manager_enumerate_perpetual(m);
25✔
3626
        manager_enumerate(m);
25✔
3627

3628
        /* Second, deserialize our stored data */
3629
        r = manager_deserialize(m, f, fds);
25✔
3630
        if (r < 0)
25✔
3631
                log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
×
3632

3633
        /* We don't need the serialization anymore */
3634
        f = safe_fclose(f);
25✔
3635

3636
        /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3637
        (void) manager_setup_notify(m);
25✔
3638
        (void) manager_setup_user_lookup_fd(m);
25✔
3639
        (void) manager_setup_handoff_timestamp_fd(m);
25✔
3640
        (void) manager_setup_pidref_transport_fd(m);
25✔
3641

3642
        /* Clean up deserialized bus track information. They're never consumed during reload (as opposed to
3643
         * reexec) since we do not disconnect from the bus. */
3644
        m->subscribed_as_strv = strv_free(m->subscribed_as_strv);
25✔
3645
        m->deserialized_bus_id = SD_ID128_NULL;
25✔
3646

3647
        /* Third, fire things up! */
3648
        manager_coldplug(m);
25✔
3649

3650
        /* Clean up runtime objects no longer referenced */
3651
        manager_vacuum(m);
25✔
3652

3653
        /* Consider the reload process complete now. */
3654
        assert(m->n_reloading > 0);
25✔
3655
        m->n_reloading--;
25✔
3656

3657
        manager_ready(m);
25✔
3658

3659
        m->send_reloading_done = true;
25✔
3660
        return 0;
25✔
3661
}
3662

3663
void manager_reset_failed(Manager *m) {
1✔
3664
        Unit *u;
1✔
3665

3666
        assert(m);
1✔
3667

3668
        HASHMAP_FOREACH(u, m->units)
249✔
3669
                unit_reset_failed(u);
248✔
3670
}
1✔
3671

3672
bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
×
3673
        Unit *u;
×
3674

3675
        assert(m);
×
3676
        assert(name);
×
3677

3678
        /* Returns true if the unit is inactive or going down */
3679
        u = manager_get_unit(m, name);
×
3680
        if (!u)
×
3681
                return true;
3682

3683
        return unit_inactive_or_pending(u);
×
3684
}
3685

3686
static void log_taint_string(Manager *m) {
20,194✔
3687
        assert(m);
20,194✔
3688

3689
        if (MANAGER_IS_USER(m) || m->taint_logged)
20,194✔
3690
                return;
20,194✔
3691

3692
        m->taint_logged = true; /* only check for taint once */
31✔
3693

3694
        _cleanup_free_ char *taint = taint_string();
62✔
3695
        if (isempty(taint))
31✔
3696
                return;
31✔
3697

3698
        log_struct(LOG_NOTICE,
×
3699
                   LOG_MESSAGE("System is tainted: %s", taint),
3700
                   LOG_ITEM("TAINT=%s", taint),
3701
                   LOG_MESSAGE_ID(SD_MESSAGE_TAINTED_STR));
3702
}
3703

3704
static void manager_notify_finished(Manager *m) {
192✔
3705
        usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
192✔
3706

3707
        if (MANAGER_IS_TEST_RUN(m))
192✔
3708
                return;
3709

3710
        if (MANAGER_IS_SYSTEM(m) && m->soft_reboots_count > 0) {
185✔
3711
                /* The soft-reboot case, where we only report data for the last reboot */
3712
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
×
3713
                total_usec = userspace_usec = usec_sub_unsigned(m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic,
×
3714
                                                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START].monotonic);
3715

3716
                log_struct(LOG_INFO,
×
3717
                           LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3718
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3719
                           LOG_MESSAGE("Soft-reboot finished in %s, counter is now at %u.",
3720
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC),
3721
                                       m->soft_reboots_count));
3722
        } else if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
186✔
3723
                char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
1✔
3724
                        = {};
3725
                char *p = buf;
1✔
3726
                size_t size = sizeof buf;
1✔
3727

3728
                /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3729
                 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
3730
                 * negative values. */
3731

3732
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
1✔
3733
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
1✔
3734
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
1✔
3735
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
1✔
3736

3737
                if (firmware_usec > 0)
1✔
3738
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
3739
                if (loader_usec > 0)
1✔
3740
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3741

3742
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
1✔
3743

3744
                        /* The initrd case on bare-metal */
3745
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3746
                        initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
×
3747

3748
                        log_struct(LOG_INFO,
×
3749
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3750
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3751
                                   LOG_ITEM("INITRD_USEC="USEC_FMT, initrd_usec),
3752
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3753
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3754
                                               buf,
3755
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3756
                                               FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3757
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3758
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3759
                } else {
3760
                        /* The initrd-less case on bare-metal */
3761

3762
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
1✔
3763
                        initrd_usec = 0;
1✔
3764

3765
                        log_struct(LOG_INFO,
1✔
3766
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3767
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3768
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3769
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3770
                                               buf,
3771
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3772
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3773
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3774
                }
3775
        } else {
3776
                /* The container and --user case */
3777
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
184✔
3778
                total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
184✔
3779

3780
                log_struct(LOG_INFO,
184✔
3781
                           LOG_MESSAGE_ID(SD_MESSAGE_USER_STARTUP_FINISHED_STR),
3782
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3783
                           LOG_MESSAGE("Startup finished in %s.",
3784
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3785
        }
3786

3787
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
185✔
3788

3789
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
185✔
3790
                watchdog_report_if_missing();
1✔
3791

3792
        log_taint_string(m);
185✔
3793
}
3794

3795
static void manager_send_ready_on_basic_target(Manager *m) {
20,009✔
3796
        int r;
20,009✔
3797

3798
        assert(m);
20,009✔
3799

3800
        /* We send READY=1 on reaching basic.target only when running in --user mode. */
3801
        if (!MANAGER_IS_USER(m) || m->ready_sent)
20,009✔
3802
                return;
3803

3804
        r = sd_notify(/* unset_environment= */ false,
193✔
3805
                      "READY=1\n"
3806
                      "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3807
        if (r < 0)
193✔
3808
                log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
×
3809

3810
        m->ready_sent = true;
193✔
3811
        m->status_ready = false;
193✔
3812
}
3813

3814
static void manager_send_ready_on_idle(Manager *m) {
2,719✔
3815
        int r;
2,719✔
3816

3817
        assert(m);
2,719✔
3818

3819
        /* Skip the notification if nothing changed. */
3820
        if (m->ready_sent && m->status_ready)
2,719✔
3821
                return;
3822

3823
        /* Note that for user managers, we might have already sent READY=1 in manager_send_ready_user_scope().
3824
         * But we still need to flush STATUS=. The second READY=1 will be treated as a noop so it doesn't
3825
         * hurt to send it twice. */
3826
        r = sd_notify(/* unset_environment= */ false,
195✔
3827
                      "READY=1\n"
3828
                      "STATUS=Ready.");
3829
        if (r < 0)
195✔
3830
                log_full_errno(m->ready_sent ? LOG_DEBUG : LOG_WARNING, r,
×
3831
                               "Failed to send readiness notification, ignoring: %m");
3832

3833
        m->ready_sent = m->status_ready = true;
195✔
3834
}
3835

3836
static void manager_check_basic_target(Manager *m) {
32,364✔
3837
        Unit *u;
32,364✔
3838

3839
        assert(m);
32,364✔
3840

3841
        /* Small shortcut */
3842
        if (m->ready_sent && m->taint_logged)
32,364✔
3843
                return;
3844

3845
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
32,291✔
3846
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
32,291✔
3847
                return;
12,282✔
3848

3849
        /* For user managers, send out READY=1 as soon as we reach basic.target */
3850
        manager_send_ready_on_basic_target(m);
20,009✔
3851

3852
        /* Log the taint string as soon as we reach basic.target */
3853
        log_taint_string(m);
20,009✔
3854
}
3855

3856
void manager_check_finished(Manager *m) {
32,563✔
3857
        assert(m);
32,563✔
3858

3859
        if (MANAGER_IS_RELOADING(m))
32,563✔
3860
                return;
3861

3862
        /* Verify that we have entered the event loop already, and not left it again. */
3863
        if (!MANAGER_IS_RUNNING(m))
32,563✔
3864
                return;
3865

3866
        manager_check_basic_target(m);
32,364✔
3867

3868
        if (!hashmap_isempty(m->jobs)) {
32,364✔
3869
                if (m->jobs_in_progress_event_source)
29,645✔
3870
                        /* Ignore any failure, this is only for feedback */
3871
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
3,852✔
3872
                                                        manager_watch_jobs_next_time(m));
3,852✔
3873
                return;
29,645✔
3874
        }
3875

3876
        /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
3877
           kill the hashmap if it is relatively large. */
3878
        if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
2,719✔
3879
                m->jobs = hashmap_free(m->jobs);
561✔
3880

3881
        manager_send_ready_on_idle(m);
2,719✔
3882

3883
        /* Notify Type=idle units that we are done now */
3884
        manager_close_idle_pipe(m);
2,719✔
3885

3886
        if (MANAGER_IS_FINISHED(m))
2,719✔
3887
                return;
3888

3889
        manager_flip_auto_status(m, false, "boot finished");
192✔
3890

3891
        /* Turn off confirm spawn now */
3892
        m->confirm_spawn = NULL;
192✔
3893

3894
        /* No need to update ask password status when we're going non-interactive */
3895
        manager_close_ask_password(m);
192✔
3896

3897
        /* This is no longer the first boot */
3898
        manager_set_first_boot(m, false);
192✔
3899

3900
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
192✔
3901

3902
        manager_notify_finished(m);
192✔
3903

3904
        manager_invalidate_startup_units(m);
192✔
3905
}
3906

3907
void manager_send_reloading(Manager *m) {
61✔
3908
        assert(m);
61✔
3909

3910
        /* Let whoever invoked us know that we are now reloading */
3911
        (void) notify_reloading_full(/* status = */ NULL);
61✔
3912

3913
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
3914
        m->ready_sent = false;
61✔
3915
}
61✔
3916

3917
static bool generator_path_any(char * const *paths) {
968✔
3918

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

3921
        STRV_FOREACH(i, paths) {
3,872✔
3922
                if (access(*i, F_OK) >= 0)
3,872✔
3923
                        return true;
3924
                if (errno != ENOENT)
2,904✔
3925
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
2,904✔
3926
        }
3927

3928
        return false;
3929
}
3930

3931
static int manager_run_environment_generators(Manager *m) {
731✔
3932
        _cleanup_strv_free_ char **paths = NULL;
731✔
3933
        int r;
731✔
3934

3935
        assert(m);
731✔
3936

3937
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
731✔
3938
                return 0;
3939

3940
        paths = env_generator_binary_paths(m->runtime_scope);
708✔
3941
        if (!paths)
708✔
3942
                return log_oom();
×
3943

3944
        if (!generator_path_any(paths))
708✔
3945
                return 0;
3946

3947
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
708✔
3948
        void *args[_STDOUT_CONSUME_MAX] = {
708✔
3949
                [STDOUT_GENERATE] = &tmp,
3950
                [STDOUT_COLLECT]  = &tmp,
3951
                [STDOUT_CONSUME]  = &m->transient_environment,
708✔
3952
        };
3953

3954
        WITH_UMASK(0022)
1,416✔
3955
                r = execute_directories(
708✔
3956
                                (const char* const*) paths,
3957
                                DEFAULT_TIMEOUT_USEC,
3958
                                gather_environment,
3959
                                args,
3960
                                /* argv[]= */ NULL,
3961
                                m->transient_environment,
3962
                                EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
3963
        return r;
708✔
3964
}
3965

3966
static int build_generator_environment(Manager *m, char ***ret) {
187✔
3967
        _cleanup_strv_free_ char **nl = NULL;
187✔
3968
        Virtualization v;
187✔
3969
        ConfidentialVirtualization cv;
187✔
3970
        int r;
187✔
3971

3972
        assert(m);
187✔
3973
        assert(ret);
187✔
3974

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

3979
        nl = strv_copy(m->transient_environment);
187✔
3980
        if (!nl)
187✔
3981
                return -ENOMEM;
3982

3983
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
187✔
3984
        if (r < 0)
187✔
3985
                return r;
3986

3987
        if (MANAGER_IS_SYSTEM(m)) {
187✔
3988
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
3989
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
3990
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
3991
                 * same results (hopefully). */
3992
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
3993
                if (r < 0)
×
3994
                        return r;
3995

3996
                if (m->soft_reboots_count > 0) {
×
3997
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
3998
                        if (r < 0)
×
3999
                                return r;
4000
                }
4001

4002
                if (m->first_boot >= 0) {
×
4003
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4004
                        if (r < 0)
×
4005
                                return r;
4006
                }
4007
        }
4008

4009
        v = detect_virtualization();
187✔
4010
        if (v < 0)
187✔
4011
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4012
        else if (v > 0) {
187✔
4013
                const char *s;
187✔
4014

4015
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
935✔
4016
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4017
                             virtualization_to_string(v));
4018

4019
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
187✔
4020
                if (r < 0)
187✔
4021
                        return r;
4022
        }
4023

4024
        cv = detect_confidential_virtualization();
187✔
4025
        if (cv < 0)
187✔
4026
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4027
        else if (cv > 0) {
187✔
4028
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4029
                if (r < 0)
×
4030
                        return r;
4031
        }
4032

4033
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
187✔
4034
        if (r < 0)
187✔
4035
                return r;
4036

4037
        *ret = TAKE_PTR(nl);
187✔
4038
        return 0;
187✔
4039
}
4040

4041
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
187✔
4042
        _cleanup_strv_free_ char **ge = NULL;
187✔
4043
        int r;
187✔
4044

4045
        assert(m);
187✔
4046

4047
        r = build_generator_environment(m, &ge);
187✔
4048
        if (r < 0)
187✔
4049
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4050

4051
        if (remount_ro) {
187✔
4052
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4053
                 * checks whether it is read-only to detect containerized execution environments. We leave
4054
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4055
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4056
                 */
4057
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4058
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4059
                if (r < 0)
×
4060
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4061
        }
4062

4063
        const char *argv[] = {
187✔
4064
                NULL, /* Leave this empty, execute_directory() will fill something in */
4065
                m->lookup_paths.generator,
187✔
4066
                m->lookup_paths.generator_early,
187✔
4067
                m->lookup_paths.generator_late,
187✔
4068
                NULL,
4069
        };
4070

4071
        BLOCK_WITH_UMASK(0022);
374✔
4072
        return execute_directories(
187✔
4073
                        (const char* const*) paths,
4074
                        DEFAULT_TIMEOUT_USEC,
4075
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4076
                        (char**) argv,
4077
                        ge,
4078
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4079
}
4080

4081
static int manager_run_generators(Manager *m) {
731✔
4082
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
731✔
4083
        _cleanup_strv_free_ char **paths = NULL;
731✔
4084
        int r;
731✔
4085

4086
        assert(m);
731✔
4087

4088
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
731✔
4089
                return 0;
4090

4091
        paths = generator_binary_paths(m->runtime_scope);
260✔
4092
        if (!paths)
260✔
4093
                return log_oom();
×
4094

4095
        if (!generator_path_any(paths))
260✔
4096
                return 0;
4097

4098
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
260✔
4099
        if (r < 0) {
260✔
4100
                log_error_errno(r, "Failed to create generator directories: %m");
×
4101
                goto finish;
×
4102
        }
4103

4104
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4105
         * we are the user manager, let's just execute the generators directly. We might not have the
4106
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4107
         */
4108
        if (MANAGER_IS_USER(m)) {
260✔
4109
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
187✔
4110
                goto finish;
187✔
4111
        }
4112

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

4118
        r = safe_fork("(sd-gens)", flags, NULL);
73✔
4119
        if (r == 0) {
73✔
4120
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4121
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4122
        }
4123
        if (r < 0) {
73✔
4124
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4125
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4126
                        goto finish;
×
4127
                }
4128

4129
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4130
                 * seccomp or without capability.
4131
                 *
4132
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4133
                 *
4134
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4135
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4136
                 * https://github.com/systemd/systemd/issues/28901.
4137
                 */
4138
                log_debug_errno(r,
×
4139
                                "Failed to fork off sandboxing environment for executing generators. "
4140
                                "Falling back to execute generators without sandboxing: %m");
4141
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4142
        }
4143

4144
finish:
73✔
4145
        lookup_paths_trim_generator(&m->lookup_paths);
260✔
4146
        return r;
4147
}
4148

4149
int manager_transient_environment_add(Manager *m, char **plus) {
260✔
4150
        char **a;
260✔
4151

4152
        assert(m);
260✔
4153

4154
        if (strv_isempty(plus))
260✔
4155
                return 0;
260✔
4156

4157
        a = strv_env_merge(m->transient_environment, plus);
73✔
4158
        if (!a)
73✔
4159
                return log_oom();
×
4160

4161
        sanitize_environment(a);
73✔
4162

4163
        return strv_free_and_replace(m->transient_environment, a);
73✔
4164
}
4165

4166
int manager_client_environment_modify(
186✔
4167
                Manager *m,
4168
                char **minus,
4169
                char **plus) {
4170

4171
        char **a = NULL, **b = NULL, **l;
186✔
4172

4173
        assert(m);
186✔
4174

4175
        if (strv_isempty(minus) && strv_isempty(plus))
186✔
4176
                return 0;
4177

4178
        l = m->client_environment;
186✔
4179

4180
        if (!strv_isempty(minus)) {
186✔
4181
                a = strv_env_delete(l, 1, minus);
1✔
4182
                if (!a)
1✔
4183
                        return -ENOMEM;
4184

4185
                l = a;
4186
        }
4187

4188
        if (!strv_isempty(plus)) {
186✔
4189
                b = strv_env_merge(l, plus);
185✔
4190
                if (!b) {
185✔
4191
                        strv_free(a);
×
4192
                        return -ENOMEM;
×
4193
                }
4194

4195
                l = b;
4196
        }
4197

4198
        if (m->client_environment != l)
186✔
4199
                strv_free(m->client_environment);
186✔
4200

4201
        if (a != l)
186✔
4202
                strv_free(a);
185✔
4203
        if (b != l)
186✔
4204
                strv_free(b);
1✔
4205

4206
        m->client_environment = sanitize_environment(l);
186✔
4207
        return 0;
186✔
4208
}
4209

4210
int manager_get_effective_environment(Manager *m, char ***ret) {
19,909✔
4211
        char **l;
19,909✔
4212

4213
        assert(m);
19,909✔
4214
        assert(ret);
19,909✔
4215

4216
        l = strv_env_merge(m->transient_environment, m->client_environment);
19,909✔
4217
        if (!l)
19,909✔
4218
                return -ENOMEM;
4219

4220
        *ret = l;
19,909✔
4221
        return 0;
19,909✔
4222
}
4223

4224
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
260✔
4225
        _cleanup_free_ char *label = NULL;
260✔
4226
        struct rlimit *rlimit[_RLIMIT_MAX];
260✔
4227
        int r;
260✔
4228

4229
        assert(m);
260✔
4230
        assert(defaults);
260✔
4231

4232
        if (streq_ptr(defaults->smack_process_label, "/"))
260✔
4233
                label = NULL;
4234
        else  {
4235
                const char *l = defaults->smack_process_label;
260✔
4236
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4237
                if (!l)
4238
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4239
#endif
4240
                if (l) {
260✔
4241
                        label = strdup(l);
×
4242
                        if (!label)
×
4243
                                return -ENOMEM;
4244
                } else
4245
                        label = NULL;
4246
        }
4247

4248
        r = rlimit_copy_all(rlimit, defaults->rlimit);
260✔
4249
        if (r < 0)
260✔
4250
                return r;
4251

4252
        m->defaults.std_output = defaults->std_output;
260✔
4253
        m->defaults.std_error = defaults->std_error;
260✔
4254

4255
        m->defaults.restart_usec = defaults->restart_usec;
260✔
4256
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
260✔
4257
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
260✔
4258
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
260✔
4259
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
260✔
4260
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
260✔
4261

4262
        m->defaults.restrict_suid_sgid = defaults->restrict_suid_sgid;
260✔
4263

4264
        m->defaults.start_limit = defaults->start_limit;
260✔
4265

4266
        m->defaults.memory_accounting = defaults->memory_accounting;
260✔
4267
        m->defaults.io_accounting = defaults->io_accounting;
260✔
4268
        m->defaults.tasks_accounting = defaults->tasks_accounting;
260✔
4269
        m->defaults.ip_accounting = defaults->ip_accounting;
260✔
4270

4271
        m->defaults.tasks_max = defaults->tasks_max;
260✔
4272
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
260✔
4273

4274
        m->defaults.oom_policy = defaults->oom_policy;
260✔
4275
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
260✔
4276
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
260✔
4277

4278
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
260✔
4279
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
260✔
4280

4281
        free_and_replace(m->defaults.smack_process_label, label);
260✔
4282
        rlimit_free_all(m->defaults.rlimit);
260✔
4283
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
260✔
4284

4285
        return 0;
260✔
4286
}
4287

4288
void manager_recheck_dbus(Manager *m) {
73,053✔
4289
        assert(m);
73,053✔
4290

4291
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4292
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4293
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4294
         * of the system instance, while in the user instance we can assume it's already there. */
4295

4296
        if (MANAGER_IS_RELOADING(m))
73,053✔
4297
                return; /* don't check while we are reloading… */
4298

4299
        if (manager_dbus_is_running(m, false)) {
66,383✔
4300
                (void) bus_init_api(m);
4,550✔
4301

4302
                if (MANAGER_IS_SYSTEM(m))
4,550✔
4303
                        (void) bus_init_system(m);
3,406✔
4304
        } else {
4305
                (void) bus_done_api(m);
61,833✔
4306

4307
                if (MANAGER_IS_SYSTEM(m))
61,833✔
4308
                        (void) bus_done_system(m);
8,574✔
4309
        }
4310
}
4311

4312
static bool manager_journal_is_running(Manager *m) {
13,793✔
4313
        Unit *u;
13,793✔
4314

4315
        assert(m);
13,793✔
4316

4317
        if (MANAGER_IS_TEST_RUN(m))
13,793✔
4318
                return false;
4319

4320
        /* If we are the user manager we can safely assume that the journal is up */
4321
        if (!MANAGER_IS_SYSTEM(m))
13,793✔
4322
                return true;
4323

4324
        /* Check that the socket is not only up, but in RUNNING state */
4325
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
12,958✔
4326
        if (!u)
12,958✔
4327
                return false;
4328
        if (SOCKET(u)->state != SOCKET_RUNNING)
12,958✔
4329
                return false;
4330

4331
        /* Similar, check if the daemon itself is fully up, too */
4332
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
9,923✔
4333
        if (!u)
9,923✔
4334
                return false;
4335
        if (!IN_SET(SERVICE(u)->state, SERVICE_RELOAD, SERVICE_RUNNING))
9,923✔
4336
                return false;
505✔
4337

4338
        return true;
4339
}
4340

4341
void disable_printk_ratelimit(void) {
16✔
4342
        /* Disable kernel's printk ratelimit.
4343
         *
4344
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4345
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4346
         * setting takes precedence. */
4347
        int r;
16✔
4348

4349
        r = sysctl_write("kernel/printk_devkmsg", "on");
16✔
4350
        if (r < 0)
16✔
4351
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4352
}
16✔
4353

4354
void manager_recheck_journal(Manager *m) {
73,053✔
4355

4356
        assert(m);
73,053✔
4357

4358
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4359
        if (getpid_cached() != 1)
73,053✔
4360
                return;
4361

4362
        /* Don't check this while we are reloading, things might still change */
4363
        if (MANAGER_IS_RELOADING(m))
18,051✔
4364
                return;
4365

4366
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4367
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4368
         * might trigger an activation ourselves we can't fulfill. */
4369
        log_set_prohibit_ipc(!manager_journal_is_running(m));
11,526✔
4370
        log_open();
11,526✔
4371
}
4372

4373
static ShowStatus manager_get_show_status(Manager *m) {
6,752✔
4374
        assert(m);
6,752✔
4375

4376
        if (MANAGER_IS_USER(m))
6,752✔
4377
                return _SHOW_STATUS_INVALID;
4378

4379
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
6,751✔
4380
                return m->show_status_overridden;
4381

4382
        return m->show_status;
6,751✔
4383
}
4384

4385
bool manager_get_show_status_on(Manager *m) {
6,752✔
4386
        assert(m);
6,752✔
4387

4388
        return show_status_on(manager_get_show_status(m));
6,752✔
4389
}
4390

4391
static void set_show_status_marker(bool b) {
50✔
4392
        if (b)
50✔
4393
                (void) touch("/run/systemd/show-status");
×
4394
        else
4395
                (void) unlink("/run/systemd/show-status");
50✔
4396
}
50✔
4397

4398
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
260✔
4399
        assert(m);
260✔
4400
        assert(reason);
260✔
4401
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
260✔
4402

4403
        if (MANAGER_IS_USER(m))
260✔
4404
                return;
4405

4406
        if (mode == m->show_status)
73✔
4407
                return;
4408

4409
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
50✔
4410
                bool enabled;
50✔
4411

4412
                enabled = show_status_on(mode);
50✔
4413
                log_debug("%s (%s) showing of status (%s).",
100✔
4414
                          enabled ? "Enabling" : "Disabling",
4415
                          strna(show_status_to_string(mode)),
4416
                          reason);
4417

4418
                set_show_status_marker(enabled);
50✔
4419
        }
4420

4421
        m->show_status = mode;
50✔
4422
}
4423

4424
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
×
4425
        assert(m);
×
4426
        assert(mode < _SHOW_STATUS_MAX);
×
4427

4428
        if (MANAGER_IS_USER(m))
×
4429
                return;
4430

4431
        if (mode == m->show_status_overridden)
×
4432
                return;
4433

4434
        m->show_status_overridden = mode;
×
4435

4436
        if (mode == _SHOW_STATUS_INVALID)
×
4437
                mode = m->show_status;
×
4438

4439
        log_debug("%s (%s) showing of status (%s).",
×
4440
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4441
                  strna(show_status_to_string(mode)),
4442
                  reason);
4443

4444
        set_show_status_marker(show_status_on(mode));
×
4445
}
4446

4447
const char* manager_get_confirm_spawn(Manager *m) {
2,279✔
4448
        static int last_errno = 0;
2,279✔
4449
        struct stat st;
2,279✔
4450
        int r;
2,279✔
4451

4452
        assert(m);
2,279✔
4453

4454
        /* Here's the deal: we want to test the validity of the console but don't want
4455
         * PID1 to go through the whole console process which might block. But we also
4456
         * want to warn the user only once if something is wrong with the console so we
4457
         * cannot do the sanity checks after spawning our children. So here we simply do
4458
         * really basic tests to hopefully trap common errors.
4459
         *
4460
         * If the console suddenly disappear at the time our children will really it
4461
         * then they will simply fail to acquire it and a positive answer will be
4462
         * assumed. New children will fall back to /dev/console though.
4463
         *
4464
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4465
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4466
         * reason the configured console is not ready, we fall back to the default
4467
         * console. */
4468

4469
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
2,279✔
4470
                return m->confirm_spawn;
2,279✔
4471

4472
        if (stat(m->confirm_spawn, &st) < 0) {
×
4473
                r = -errno;
×
4474
                goto fail;
×
4475
        }
4476

4477
        if (!S_ISCHR(st.st_mode)) {
×
4478
                r = -ENOTTY;
×
4479
                goto fail;
×
4480
        }
4481

4482
        last_errno = 0;
×
4483
        return m->confirm_spawn;
×
4484

4485
fail:
×
4486
        if (last_errno != r)
×
4487
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4488

4489
        return "/dev/console";
4490
}
4491

4492
void manager_set_first_boot(Manager *m, bool b) {
427✔
4493
        assert(m);
427✔
4494

4495
        if (!MANAGER_IS_SYSTEM(m))
427✔
4496
                return;
4497

4498
        if (m->first_boot != (int) b) {
51✔
4499
                if (b)
51✔
4500
                        (void) touch("/run/systemd/first-boot");
18✔
4501
                else
4502
                        (void) unlink("/run/systemd/first-boot");
33✔
4503
        }
4504

4505
        m->first_boot = b;
51✔
4506
}
4507

4508
void manager_disable_confirm_spawn(void) {
×
4509
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4510
}
×
4511

4512
static bool manager_should_show_status(Manager *m, StatusType type) {
16,114✔
4513
        assert(m);
16,114✔
4514

4515
        if (!MANAGER_IS_SYSTEM(m))
16,114✔
4516
                return false;
4517

4518
        if (m->no_console_output)
6,820✔
4519
                return false;
4520

4521
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
6,736✔
4522
                return false;
4523

4524
        /* If we cannot find out the status properly, just proceed. */
4525
        if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
6,736✔
4526
                return false;
4527

4528
        if (type == STATUS_TYPE_NOTICE && m->show_status != SHOW_STATUS_NO)
6,736✔
4529
                return true;
4530

4531
        return manager_get_show_status_on(m);
6,735✔
4532
}
4533

4534
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
16,114✔
4535
        va_list ap;
16,114✔
4536

4537
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4538

4539
        if (m && !manager_should_show_status(m, type))
16,114✔
4540
                return;
16,113✔
4541

4542
        /* XXX We should totally drop the check for ephemeral here
4543
         * and thus effectively make 'Type=idle' pointless. */
4544
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
1✔
4545
                return;
4546

4547
        va_start(ap, format);
1✔
4548
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
2✔
4549
        va_end(ap);
1✔
4550
}
4551

4552
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
18,424✔
4553
        assert(m);
18,424✔
4554
        assert(path);
18,424✔
4555
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
18,424✔
4556

4557
        if (path_equal(path, "/"))
18,424✔
4558
                path = "";
830✔
4559

4560
        return hashmap_get(m->units_needing_mounts_for[t], path);
18,424✔
4561
}
4562

4563
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
152,418✔
4564
        unsigned size;
152,418✔
4565
        int r;
152,418✔
4566

4567
        assert(m);
152,418✔
4568
        assert(u->manager == m);
152,418✔
4569

4570
        size = set_size(m->failed_units);
152,418✔
4571

4572
        if (failed) {
152,418✔
4573
                r = set_ensure_put(&m->failed_units, NULL, u);
249✔
4574
                if (r < 0)
249✔
4575
                        return log_oom();
×
4576
        } else
4577
                (void) set_remove(m->failed_units, u);
152,169✔
4578

4579
        if (set_size(m->failed_units) != size)
152,418✔
4580
                bus_manager_send_change_signal(m);
498✔
4581

4582
        return 0;
4583
}
4584

4585
ManagerState manager_state(Manager *m) {
417,510✔
4586
        Unit *u;
417,510✔
4587

4588
        assert(m);
417,510✔
4589

4590
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4591
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
417,510✔
4592
        if (u && unit_active_or_pending(u))
417,510✔
4593
                return MANAGER_STOPPING;
4594

4595
        /* Did we ever finish booting? If not then we are still starting up */
4596
        if (!MANAGER_IS_FINISHED(m)) {
329,280✔
4597

4598
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
295,908✔
4599
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
295,908✔
4600
                        return MANAGER_INITIALIZING;
250,413✔
4601

4602
                return MANAGER_STARTING;
4603
        }
4604

4605
        if (MANAGER_IS_SYSTEM(m)) {
33,372✔
4606
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4607
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
48✔
4608
                if (u && unit_active_or_pending(u))
48✔
4609
                        return MANAGER_MAINTENANCE;
4610

4611
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
48✔
4612
                if (u && unit_active_or_pending(u))
48✔
4613
                        return MANAGER_MAINTENANCE;
4614
        }
4615

4616
        /* Are there any failed units? If so, we are in degraded mode */
4617
        if (!set_isempty(m->failed_units))
33,372✔
4618
                return MANAGER_DEGRADED;
1,210✔
4619

4620
        return MANAGER_RUNNING;
4621
}
4622

4623
static void manager_unref_uid_internal(
635✔
4624
                Hashmap *uid_refs,
4625
                uid_t uid,
4626
                bool destroy_now,
4627
                int (*_clean_ipc)(uid_t uid)) {
4628

4629
        uint32_t c, n;
635✔
4630

4631
        assert(uid_is_valid(uid));
635✔
4632
        assert(_clean_ipc);
635✔
4633

4634
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4635
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4636
         *
4637
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4638
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4639
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4640
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4641
         * counter drops to 0 again. */
4642

4643
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
635✔
4644
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
635✔
4645

4646
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
635✔
4647
                return;
4648

4649
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
553✔
4650

4651
        n = c & ~DESTROY_IPC_FLAG;
553✔
4652
        assert(n > 0);
553✔
4653
        n--;
553✔
4654

4655
        if (destroy_now && n == 0) {
553✔
4656
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
107✔
4657

4658
                if (c & DESTROY_IPC_FLAG) {
107✔
4659
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
3✔
4660
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4661
                                  uid);
4662
                        (void) _clean_ipc(uid);
2✔
4663
                }
4664
        } else {
4665
                c = n | (c & DESTROY_IPC_FLAG);
446✔
4666
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
446✔
4667
        }
4668
}
4669

4670
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
317✔
4671
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
317✔
4672
}
317✔
4673

4674
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
318✔
4675
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
318✔
4676
}
318✔
4677

4678
static int manager_ref_uid_internal(
635✔
4679
                Hashmap **uid_refs,
4680
                uid_t uid,
4681
                bool clean_ipc) {
4682

4683
        uint32_t c, n;
635✔
4684
        int r;
635✔
4685

4686
        assert(uid_refs);
635✔
4687
        assert(uid_is_valid(uid));
635✔
4688

4689
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4690
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4691
         * rules. */
4692

4693
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
635✔
4694
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
635✔
4695

4696
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
635✔
4697
                return 0;
4698

4699
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
553✔
4700
        if (r < 0)
553✔
4701
                return r;
4702

4703
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
553✔
4704

4705
        n = c & ~DESTROY_IPC_FLAG;
553✔
4706
        n++;
553✔
4707

4708
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
553✔
4709
                return -EOVERFLOW;
4710

4711
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
553✔
4712

4713
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
553✔
4714
}
4715

4716
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
317✔
4717
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
317✔
4718
}
4719

4720
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
318✔
4721
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
318✔
4722
}
4723

4724
static void manager_vacuum_uid_refs_internal(
1,462✔
4725
                Hashmap *uid_refs,
4726
                int (*_clean_ipc)(uid_t uid)) {
4727

4728
        void *p, *k;
1,462✔
4729

4730
        assert(_clean_ipc);
1,462✔
4731

4732
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
3,160✔
4733
                uint32_t c, n;
236✔
4734
                uid_t uid;
236✔
4735

4736
                uid = PTR_TO_UID(k);
236✔
4737
                c = PTR_TO_UINT32(p);
236✔
4738

4739
                n = c & ~DESTROY_IPC_FLAG;
236✔
4740
                if (n > 0)
236✔
4741
                        continue;
236✔
4742

4743
                if (c & DESTROY_IPC_FLAG) {
×
4744
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4745
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4746
                                  uid);
4747
                        (void) _clean_ipc(uid);
×
4748
                }
4749

4750
                assert_se(hashmap_remove(uid_refs, k) == p);
1,698✔
4751
        }
4752
}
1,462✔
4753

4754
static void manager_vacuum_uid_refs(Manager *m) {
731✔
4755
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
731✔
4756
}
731✔
4757

4758
static void manager_vacuum_gid_refs(Manager *m) {
731✔
4759
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
731✔
4760
}
731✔
4761

4762
static void manager_vacuum(Manager *m) {
731✔
4763
        assert(m);
731✔
4764

4765
        /* Release any dynamic users no longer referenced */
4766
        dynamic_user_vacuum(m, true);
731✔
4767

4768
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4769
        manager_vacuum_uid_refs(m);
731✔
4770
        manager_vacuum_gid_refs(m);
731✔
4771

4772
        /* Release any runtimes no longer referenced */
4773
        exec_shared_runtime_vacuum(m);
731✔
4774
}
731✔
4775

4776
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
144✔
4777
        struct buffer {
144✔
4778
                uid_t uid;
4779
                gid_t gid;
4780
                char unit_name[UNIT_NAME_MAX+1];
4781
        } _packed_ buffer;
4782

4783
        Manager *m = ASSERT_PTR(userdata);
144✔
4784
        ssize_t l;
144✔
4785
        size_t n;
144✔
4786
        Unit *u;
144✔
4787

4788
        assert(source);
144✔
4789

4790
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4791
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4792
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4793
         * reference counter drops to 0. */
4794

4795
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
144✔
4796
        if (l < 0) {
144✔
4797
                if (ERRNO_IS_TRANSIENT(errno))
×
4798
                        return 0;
144✔
4799

4800
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4801
        }
4802

4803
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
144✔
4804
                log_warning("Received too short user lookup message, ignoring.");
×
4805
                return 0;
×
4806
        }
4807

4808
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
144✔
4809
                log_warning("Received too long user lookup message, ignoring.");
×
4810
                return 0;
×
4811
        }
4812

4813
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
144✔
4814
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4815
                return 0;
×
4816
        }
4817

4818
        n = (size_t) l - offsetof(struct buffer, unit_name);
144✔
4819
        if (memchr(buffer.unit_name, 0, n)) {
144✔
4820
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4821
                return 0;
×
4822
        }
4823

4824
        buffer.unit_name[n] = 0;
144✔
4825
        u = manager_get_unit(m, buffer.unit_name);
144✔
4826
        if (!u) {
144✔
4827
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4828
                return 0;
×
4829
        }
4830

4831
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
144✔
4832

4833
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
144✔
4834
        return 0;
4835
}
4836

4837
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2,262✔
4838
        Manager *m = ASSERT_PTR(userdata);
2,262✔
4839
        usec_t ts[2] = {};
2,262✔
4840
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
2,262✔
4841
        struct msghdr msghdr = {
2,262✔
4842
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
2,262✔
4843
                .msg_iovlen = 1,
4844
                .msg_control = &control,
4845
                .msg_controllen = sizeof(control),
4846
        };
4847
        ssize_t n;
2,262✔
4848

4849
        assert(source);
2,262✔
4850

4851
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2,262✔
4852
        if (ERRNO_IS_NEG_TRANSIENT(n))
2,262✔
4853
                return 0; /* Spurious wakeup, try again */
2,262✔
4854
        if (n == -ECHRNG) {
2,262✔
4855
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4856
                return 0;
×
4857
        }
4858
        if (n == -EXFULL) {
2,262✔
4859
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4860
                return 0;
×
4861
        }
4862
        if (n < 0)
2,262✔
4863
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
4864

4865
        cmsg_close_all(&msghdr);
2,262✔
4866

4867
        if (n != sizeof(ts)) {
2,262✔
4868
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
4869
                return 0;
×
4870
        }
4871

4872
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
2,262✔
4873
        if (!ucred || !pid_is_valid(ucred->pid)) {
2,262✔
4874
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
4875
                return 0;
×
4876
        }
4877

4878
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
2,262✔
4879

4880
        _cleanup_free_ Unit **units = NULL;
2,262✔
4881
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
2,262✔
4882
        if (n_units < 0) {
2,262✔
4883
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
4884
                return 0;
×
4885
        }
4886
        if (n_units == 0) {
2,262✔
4887
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
4888
                return 0;
×
4889
        }
4890

4891
        dual_timestamp dt = {
2,262✔
4892
                .realtime = ts[0],
2,262✔
4893
                .monotonic = ts[1],
2,262✔
4894
        };
4895

4896
        FOREACH_ARRAY(u, units, n_units) {
6,786✔
4897
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
4,524✔
4898
                        continue;
5✔
4899

4900
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
4,519✔
4901
        }
4902

4903
        return 0;
4904
}
4905

4906
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
4907
        Manager *m = ASSERT_PTR(userdata);
3✔
4908
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
3✔
4909
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
6✔
4910
        struct ucred *ucred = NULL;
3✔
4911
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
3✔
4912
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
3✔
4913
        struct msghdr msghdr = {
3✔
4914
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
3✔
4915
                .msg_iovlen = 1,
4916
                .msg_control = &control,
4917
                .msg_controllen = sizeof(control),
4918
        };
4919
        struct cmsghdr *cmsg;
3✔
4920
        ssize_t n;
3✔
4921
        int r;
3✔
4922

4923
        assert(source);
3✔
4924

4925
        /* Server expects:
4926
         * - Parent PID in ucreds enabled via SO_PASSCRED
4927
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
4928
         * - Child PIDFD in SCM_RIGHTS in message body
4929
         * - Child PID in message IOV
4930
         *
4931
         * SO_PASSPIDFD may not be supported by the kernel (it is supported since v6.5) so we fall back to
4932
         * using parent PID from ucreds and accept some raciness. */
4933
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
3✔
4934
        if (ERRNO_IS_NEG_TRANSIENT(n))
6✔
4935
                return 0; /* Spurious wakeup, try again */
4936
        if (n == -ECHRNG) {
3✔
4937
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4938
                return 0;
×
4939
        }
4940
        if (n == -EXFULL) {
3✔
4941
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4942
                return 0;
×
4943
        }
4944
        if (n < 0)
3✔
4945
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
4946

4947
        if (n != sizeof(child_pid)) {
3✔
4948
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
4949
                return 0;
×
4950
        }
4951

4952
        CMSG_FOREACH(cmsg, &msghdr) {
24✔
4953
                if (cmsg->cmsg_level != SOL_SOCKET)
9✔
4954
                        continue;
×
4955

4956
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
9✔
4957
                        assert(!ucred);
3✔
4958
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
3✔
4959
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
6✔
4960
                        assert(parent_pidfd < 0);
3✔
4961
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4962
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
3✔
4963
                        assert(child_pidfd < 0);
3✔
4964
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4965
                }
4966
        }
4967

4968
        /* Verify and set parent pidref. */
4969
        if (!ucred || !pid_is_valid(ucred->pid)) {
3✔
4970
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
4971
                return 0;
×
4972
        }
4973

4974
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
4975
        if (parent_pidfd >= 0)
3✔
4976
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
3✔
4977
        else
4978
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
4979
        if (r < 0) {
3✔
4980
                if (r == -ESRCH)
×
4981
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
4982
                else
4983
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
4984
                return 0;
×
4985
        }
4986

4987
        if (parent_pidref.pid != ucred->pid) {
3✔
4988
                assert(parent_pidref.fd >= 0);
×
4989
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
4990
                            parent_pidref.pid, ucred->pid);
4991
                return 0;
×
4992
        }
4993

4994
        /* Verify and set child pidref. */
4995
        if (!pid_is_valid(child_pid)) {
3✔
4996
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
4997
                return 0;
×
4998
        }
4999

5000
        /* Need to handle kernels without PIDFD support. */
5001
        if (child_pidfd >= 0)
3✔
5002
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
3✔
5003
        else
5004
                r = pidref_set_pid(&child_pidref, child_pid);
×
5005
        if (r < 0) {
3✔
5006
                if (r == -ESRCH)
×
5007
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5008
                else
5009
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5010
                return 0;
×
5011
        }
5012

5013
        if (child_pidref.pid != child_pid) {
3✔
5014
                assert(child_pidref.fd >= 0);
×
5015
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5016
                            child_pidref.pid, child_pid);
5017
                return 0;
×
5018
        }
5019

5020
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
3✔
5021

5022
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5023
         * Then fall back to finding cgroup of the child process. */
5024
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
3✔
5025
        if (!u)
3✔
5026
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5027
        if (!u) {
×
5028
                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);
×
5029
                return 0;
×
5030
        }
5031

5032
        if (!UNIT_VTABLE(u)->notify_pidref) {
3✔
5033
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5034
                return 0;
×
5035
        }
5036

5037
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
3✔
5038

5039
        return 0;
5040
}
5041

5042
void manager_ref_console(Manager *m) {
138✔
5043
        assert(m);
138✔
5044

5045
        m->n_on_console++;
138✔
5046
}
138✔
5047

5048
void manager_unref_console(Manager *m) {
138✔
5049

5050
        assert(m->n_on_console > 0);
138✔
5051
        m->n_on_console--;
138✔
5052

5053
        if (m->n_on_console == 0)
138✔
5054
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
82✔
5055
}
138✔
5056

5057
void manager_override_log_level(Manager *m, int level) {
48✔
5058
        _cleanup_free_ char *s = NULL;
96✔
5059
        assert(m);
48✔
5060

5061
        if (!m->log_level_overridden) {
48✔
5062
                m->original_log_level = log_get_max_level();
17✔
5063
                m->log_level_overridden = true;
17✔
5064
        }
5065

5066
        (void) log_level_to_string_alloc(level, &s);
48✔
5067
        log_info("Setting log level to %s.", strna(s));
48✔
5068

5069
        log_set_max_level(level);
48✔
5070
}
48✔
5071

5072
void manager_restore_original_log_level(Manager *m) {
×
5073
        _cleanup_free_ char *s = NULL;
×
5074
        assert(m);
×
5075

5076
        if (!m->log_level_overridden)
×
5077
                return;
×
5078

5079
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5080
        log_info("Restoring log level to original (%s).", strna(s));
×
5081

5082
        log_set_max_level(m->original_log_level);
×
5083
        m->log_level_overridden = false;
×
5084
}
5085

5086
void manager_override_log_target(Manager *m, LogTarget target) {
16✔
5087
        assert(m);
16✔
5088

5089
        if (!m->log_target_overridden) {
16✔
5090
                m->original_log_target = log_get_target();
11✔
5091
                m->log_target_overridden = true;
11✔
5092
        }
5093

5094
        log_info("Setting log target to %s.", log_target_to_string(target));
16✔
5095
        log_set_target(target);
16✔
5096
}
16✔
5097

5098
void manager_restore_original_log_target(Manager *m) {
×
5099
        assert(m);
×
5100

5101
        if (!m->log_target_overridden)
×
5102
                return;
5103

5104
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5105

5106
        log_set_target(m->original_log_target);
×
5107
        m->log_target_overridden = false;
×
5108
}
5109

5110
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
3,294✔
5111
        if (in_initrd() &&
3,294✔
5112
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
54✔
5113
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5114
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
54✔
5115
        return s;
5116
}
5117

5118
int manager_allocate_idle_pipe(Manager *m) {
18,970✔
5119
        int r;
18,970✔
5120

5121
        assert(m);
18,970✔
5122

5123
        if (m->idle_pipe[0] >= 0) {
18,970✔
5124
                assert(m->idle_pipe[1] >= 0);
15,592✔
5125
                assert(m->idle_pipe[2] >= 0);
15,592✔
5126
                assert(m->idle_pipe[3] >= 0);
15,592✔
5127
                return 0;
5128
        }
5129

5130
        assert(m->idle_pipe[1] < 0);
3,378✔
5131
        assert(m->idle_pipe[2] < 0);
3,378✔
5132
        assert(m->idle_pipe[3] < 0);
3,378✔
5133

5134
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
3,378✔
5135
        if (r < 0)
×
5136
                return r;
5137

5138
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
3,378✔
5139
        if (r < 0) {
×
5140
                safe_close_pair(m->idle_pipe + 0);
×
5141
                return r;
×
5142
        }
5143

5144
        return 1;
5145
}
5146

5147
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,152✔
5148
        assert(defaults);
1,152✔
5149
        assert(scope >= 0);
1,152✔
5150
        assert(scope < _RUNTIME_SCOPE_MAX);
1,152✔
5151

5152
        *defaults = (UnitDefaults) {
2,304✔
5153
                .std_output = EXEC_OUTPUT_JOURNAL,
5154
                .std_error = EXEC_OUTPUT_INHERIT,
5155
                .restart_usec = DEFAULT_RESTART_USEC,
5156
                .timeout_start_usec = manager_default_timeout(scope),
1,152✔
5157
                .timeout_stop_usec = manager_default_timeout(scope),
1,152✔
5158
                .timeout_abort_usec = manager_default_timeout(scope),
1,152✔
5159
                .timeout_abort_set = false,
5160
                .device_timeout_usec = manager_default_timeout(scope),
1,152✔
5161
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5162

5163
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5164
                .io_accounting = false,
5165
                .tasks_accounting = true,
5166
                .ip_accounting = false,
5167

5168
                .tasks_max = DEFAULT_TASKS_MAX,
5169
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5170

5171
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5172
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5173

5174
                .oom_policy = OOM_STOP,
5175
                .oom_score_adjust_set = false,
5176
        };
5177
}
1,152✔
5178

5179
void unit_defaults_done(UnitDefaults *defaults) {
1,152✔
5180
        assert(defaults);
1,152✔
5181

5182
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,152✔
5183
        rlimit_free_all(defaults->rlimit);
1,152✔
5184
}
1,152✔
5185

5186
LogTarget manager_get_executor_log_target(Manager *m) {
2,278✔
5187
        assert(m);
2,278✔
5188

5189
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5190
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
2,278✔
5191
                return LOG_TARGET_KMSG;
5192

5193
        return log_get_target();
1,862✔
5194
}
5195

5196
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5197
        [MANAGER_INITIALIZING] = "initializing",
5198
        [MANAGER_STARTING]     = "starting",
5199
        [MANAGER_RUNNING]      = "running",
5200
        [MANAGER_DEGRADED]     = "degraded",
5201
        [MANAGER_MAINTENANCE]  = "maintenance",
5202
        [MANAGER_STOPPING]     = "stopping",
5203
};
5204

5205
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
75✔
5206

5207
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5208
        [MANAGER_OK]          = "ok",
5209
        [MANAGER_EXIT]        = "exit",
5210
        [MANAGER_RELOAD]      = "reload",
5211
        [MANAGER_REEXECUTE]   = "reexecute",
5212
        [MANAGER_REBOOT]      = "reboot",
5213
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5214
        [MANAGER_POWEROFF]    = "poweroff",
5215
        [MANAGER_HALT]        = "halt",
5216
        [MANAGER_KEXEC]       = "kexec",
5217
        [MANAGER_SWITCH_ROOT] = "switch-root",
5218
};
5219

5220
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
124✔
5221

5222
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5223
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5224
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5225
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5226
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5227
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5228
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5229
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5230
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5231
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5232
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5233
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5234
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5235
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5236
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5237
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5238
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5239
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5240
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5241
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5242
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5243
};
5244

5245
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
4,399✔
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