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

systemd / systemd / 18810271929

25 Oct 2025 04:50PM UTC coverage: 72.26%. Remained the same
18810271929

push

github

YHNdnzj
core/exec-invoke: relax restriction for process name length

Previously, we limit the length of process name by 8.
This relax the restriction then at least process comm or
program_invocation_name contains the untrucated process name.

Closes #38367.

24 of 28 new or added lines in 3 files covered. (85.71%)

486 existing lines in 52 files now uncovered.

304829 of 421852 relevant lines covered (72.26%)

1095984.64 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

162
        assert(m);
2,876✔
163

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

170
        if (m->jobs_in_progress_event_source)
2,876✔
171
                return;
172

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

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

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

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

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

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

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

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

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

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

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

UNCOV
226
        m->jobs_in_progress_iteration++;
×
227

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

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

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

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

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

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

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

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

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

282
                return -errno;
×
283
        }
284

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

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

293
        return false;
294
}
295

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

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

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

307
        return 0;
45✔
308
}
309

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

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

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

320
        assert(m);
6,967✔
321

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

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

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

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

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

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

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

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

361
        return m->have_ask_password;
6,967✔
362
}
363

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

367
        assert(m);
339✔
368

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

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

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

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

381
        return 0;
38✔
382
}
383

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

387
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
2,963✔
388

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

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

396
        assert(m);
260✔
397

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

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

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

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

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

414
        return 0;
415
}
416

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

421
        assert(m);
305✔
422

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

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

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

438
        return changed;
305✔
439
}
440

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

445
        assert(m);
280✔
446

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

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

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

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

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

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

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

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

488
        return 0;
268✔
489
}
490

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

494
        assert(m);
250✔
495

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

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

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

514
        return 0;
515
}
516

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

525
        assert(m);
250✔
526

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

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

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

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

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

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

561
                        /* ... space ... */
562

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

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

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

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

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

587
        (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
250✔
588

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

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

608
        return manager_enable_special_signals(m);
250✔
609
}
610

611
static char** sanitize_environment(char **l) {
1,250✔
612

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

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

657
int manager_default_environment(Manager *m) {
989✔
658
        assert(m);
989✔
659

660
        m->transient_environment = strv_free(m->transient_environment);
989✔
661

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

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

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

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

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

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

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

703
        sanitize_environment(m->transient_environment);
989✔
704
        return 0;
989✔
705
}
706

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

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

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

729
        assert(m);
726✔
730

731
        const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
726✔
732
        int r;
726✔
733

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

741
        return 0;
742
}
743

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

751
static int manager_setup_run_queue(Manager *m) {
726✔
752
        int r;
726✔
753

754
        assert(m);
726✔
755
        assert(!m->run_queue_event_source);
726✔
756

757
        r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
726✔
758
        if (r < 0)
726✔
759
                return r;
760

761
        r = sd_event_source_set_priority(m->run_queue_event_source, EVENT_PRIORITY_RUN_QUEUE);
726✔
762
        if (r < 0)
726✔
763
                return r;
764

765
        r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
726✔
766
        if (r < 0)
726✔
767
                return r;
768

769
        (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
726✔
770

771
        return 0;
726✔
772
}
773

774
static int manager_setup_sigchld_event_source(Manager *m) {
250✔
775
        int r;
250✔
776

777
        assert(m);
250✔
778
        assert(!m->sigchld_event_source);
250✔
779

780
        r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
250✔
781
        if (r < 0)
250✔
782
                return r;
783

784
        r = sd_event_source_set_priority(m->sigchld_event_source, EVENT_PRIORITY_SIGCHLD);
250✔
785
        if (r < 0)
250✔
786
                return r;
787

788
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
250✔
789
        if (r < 0)
250✔
790
                return r;
791

792
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
250✔
793

794
        return 0;
250✔
795
}
796

797
int manager_setup_memory_pressure_event_source(Manager *m) {
513✔
798
        int r;
513✔
799

800
        assert(m);
513✔
801

802
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
513✔
803

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

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

819
        return 0;
513✔
820
}
821

822
static int manager_find_credentials_dirs(Manager *m) {
726✔
823
        const char *e;
726✔
824
        int r;
726✔
825

826
        assert(m);
726✔
827

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

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

848
        return 0;
849
}
850

851
void manager_set_switching_root(Manager *m, bool switching_root) {
973✔
852
        assert(m);
973✔
853

854
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
973✔
855
}
973✔
856

857
double manager_get_progress(Manager *m) {
17✔
858
        assert(m);
17✔
859

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

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

866
static int compare_job_priority(const void *a, const void *b) {
379,941✔
867
        const Job *x = a, *y = b;
379,941✔
868

869
        return unit_compare_priority(x->unit, y->unit);
379,941✔
870
}
871

872
usec_t manager_default_timeout(RuntimeScope scope) {
4,700✔
873
        return scope == RUNTIME_SCOPE_SYSTEM ? DEFAULT_TIMEOUT_USEC : DEFAULT_USER_TIMEOUT_USEC;
4,700✔
874
}
875

876
int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags, Manager **ret) {
726✔
877
        _cleanup_(manager_freep) Manager *m = NULL;
726✔
878
        int r;
726✔
879

880
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
726✔
881
        assert(ret);
726✔
882

883
        m = new(Manager, 1);
726✔
884
        if (!m)
726✔
885
                return -ENOMEM;
886

887
        *m = (Manager) {
726✔
888
                .runtime_scope = runtime_scope,
889
                .objective = _MANAGER_OBJECTIVE_INVALID,
890
                .previous_objective = _MANAGER_OBJECTIVE_INVALID,
891

892
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
893

894
                .original_log_level = -1,
895
                .original_log_target = _LOG_TARGET_INVALID,
896

897
                .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
898
                .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
899
                .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
900
                .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
901

902
                .show_status_overridden = _SHOW_STATUS_INVALID,
903

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

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

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

922
                .dump_ratelimit = (const RateLimit) { .interval = 10 * USEC_PER_MINUTE, .burst = 10 },
923

924
                .executor_fd = -EBADF,
925
        };
926

927
        unit_defaults_init(&m->defaults, runtime_scope);
726✔
928

929
#if ENABLE_EFI
930
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
726✔
931
                boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
24✔
932
                                m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
24✔
933
                                m->timestamps + MANAGER_TIMESTAMP_LOADER);
24✔
934
#endif
935

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

939
        r = manager_default_environment(m);
726✔
940
        if (r < 0)
726✔
941
                return r;
942

943
        r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
726✔
944
        if (r < 0)
726✔
945
                return r;
946

947
        r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
726✔
948
        if (r < 0)
726✔
949
                return r;
950

951
        r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
726✔
952
        if (r < 0)
726✔
953
                return r;
954

955
        r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
726✔
956
        if (r < 0)
726✔
957
                return r;
958

959
        r = manager_setup_prefix(m);
726✔
960
        if (r < 0)
726✔
961
                return r;
962

963
        r = manager_find_credentials_dirs(m);
726✔
964
        if (r < 0)
726✔
965
                return r;
966

967
        r = sd_event_default(&m->event);
726✔
968
        if (r < 0)
726✔
969
                return r;
970

971
        r = manager_setup_run_queue(m);
726✔
972
        if (r < 0)
726✔
973
                return r;
974

975
        if (FLAGS_SET(test_run_flags, MANAGER_TEST_RUN_MINIMAL)) {
726✔
976
                m->cgroup_root = strdup("");
476✔
977
                if (!m->cgroup_root)
476✔
978
                        return -ENOMEM;
979
        } else {
980
                r = manager_setup_signals(m);
250✔
981
                if (r < 0)
250✔
982
                        return r;
983

984
                r = manager_setup_cgroup(m);
250✔
985
                if (r < 0)
250✔
986
                        return r;
987

988
                r = manager_setup_time_change(m);
250✔
989
                if (r < 0)
250✔
990
                        return r;
991

992
                r = manager_read_timezone_stat(m);
250✔
993
                if (r < 0)
250✔
994
                        return r;
995

996
                (void) manager_setup_timezone_change(m);
250✔
997

998
                r = manager_setup_sigchld_event_source(m);
250✔
999
                if (r < 0)
250✔
1000
                        return r;
1001

1002
                r = manager_setup_memory_pressure_event_source(m);
250✔
1003
                if (r < 0)
250✔
1004
                        return r;
1005

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

1015
        if (test_run_flags == 0) {
726✔
1016
                if (MANAGER_IS_SYSTEM(m))
238✔
1017
                        r = mkdir_label("/run/systemd/units", 0755);
51✔
1018
                else {
1019
                        _cleanup_free_ char *units_path = NULL;
187✔
1020
                        r = xdg_user_runtime_dir("/systemd/units", &units_path);
187✔
1021
                        if (r < 0)
187✔
1022
                                return r;
×
1023

1024
                        r = mkdir_label(units_path, 0755);
187✔
1025
                }
1026
                if (r < 0 && r != -EEXIST)
238✔
1027
                        return r;
1028
        }
1029

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

1035
                log_debug("Using systemd-executor binary from '%s'.", m->executor_path);
257✔
1036
        }
1037

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

1041
        *ret = TAKE_PTR(m);
726✔
1042

1043
        return 0;
726✔
1044
}
1045

1046
static int manager_setup_notify(Manager *m) {
749✔
1047
        int r;
749✔
1048

1049
        if (MANAGER_IS_TEST_RUN(m))
749✔
1050
                return 0;
1051

1052
        if (m->notify_fd < 0) {
263✔
1053
                _cleanup_close_ int fd = -EBADF;
218✔
1054
                union sockaddr_union sa;
218✔
1055
                socklen_t sa_len;
218✔
1056

1057
                /* First free all secondary fields */
1058
                m->notify_socket = mfree(m->notify_socket);
218✔
1059
                m->notify_event_source = sd_event_source_disable_unref(m->notify_event_source);
218✔
1060

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

1065
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
218✔
1066

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

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

1077
                (void) sockaddr_un_unlink(&sa.un);
218✔
1078

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

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

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

1092
                m->notify_fd = TAKE_FD(fd);
218✔
1093

1094
                log_debug("Using notification socket %s", m->notify_socket);
218✔
1095
        }
1096

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

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

1108
                (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
263✔
1109
        }
1110

1111
        return 0;
1112
}
1113

1114
static int manager_setup_user_lookup_fd(Manager *m) {
749✔
1115
        int r;
749✔
1116

1117
        assert(m);
749✔
1118

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

1138
        if (m->user_lookup_fds[0] < 0) {
749✔
1139

1140
                /* Free all secondary fields */
1141
                safe_close_pair(m->user_lookup_fds);
704✔
1142
                m->user_lookup_event_source = sd_event_source_disable_unref(m->user_lookup_event_source);
704✔
1143

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

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

1151
                (void) fd_increase_rxbuf(m->user_lookup_fds[0], MANAGER_SOCKET_RCVBUF_SIZE);
704✔
1152
        }
1153

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

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

1165
                (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
749✔
1166
        }
1167

1168
        return 0;
1169
}
1170

1171
static int manager_setup_handoff_timestamp_fd(Manager *m) {
749✔
1172
        int r;
749✔
1173

1174
        assert(m);
749✔
1175

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

1179
        if (m->handoff_timestamp_fds[0] < 0) {
749✔
1180
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
704✔
1181
                safe_close_pair(m->handoff_timestamp_fds);
704✔
1182

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

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

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

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

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

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

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

1212
                (void) sd_event_source_set_description(m->handoff_timestamp_event_source, "handoff-timestamp");
749✔
1213
        }
1214

1215
        return 0;
1216
}
1217

1218
static int manager_setup_pidref_transport_fd(Manager *m) {
749✔
1219
        int r;
749✔
1220

1221
        assert(m);
749✔
1222

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

1226
        if (m->pidref_transport_fds[0] < 0) {
749✔
1227
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
724✔
1228
                safe_close_pair(m->pidref_transport_fds);
724✔
1229

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

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

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

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

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

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

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

1261
                (void) sd_event_source_set_description(m->pidref_event_source, "pidref");
724✔
1262
        }
1263

1264
        return 0;
1265
}
1266

1267
static unsigned manager_dispatch_cleanup_queue(Manager *m) {
187,220✔
1268
        Unit *u;
187,220✔
1269
        unsigned n = 0;
187,220✔
1270

1271
        assert(m);
187,220✔
1272

1273
        while ((u = m->cleanup_queue)) {
222,548✔
1274
                assert(u->in_cleanup_queue);
35,328✔
1275

1276
                unit_free(u);
35,328✔
1277
                n++;
35,328✔
1278
        }
1279

1280
        return n;
187,220✔
1281
}
1282

1283
static unsigned manager_dispatch_release_resources_queue(Manager *m) {
174,130✔
1284
        unsigned n = 0;
174,130✔
1285
        Unit *u;
174,130✔
1286

1287
        assert(m);
174,130✔
1288

1289
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
175,166✔
1290
                assert(u->in_release_resources_queue);
1,036✔
1291
                u->in_release_resources_queue = false;
1,036✔
1292

1293
                n++;
1,036✔
1294

1295
                unit_release_resources(u);
1,036✔
1296
        }
1297

1298
        return n;
174,130✔
1299
}
1300

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

1309
static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
65,968✔
1310
        Unit *other;
65,968✔
1311

1312
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
65,968✔
1313

1314
        /* Recursively mark referenced units as GOOD as well */
1315
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
450,544✔
1316
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
242,064✔
1317
                        unit_gc_mark_good(other, gc_marker);
1,059✔
1318
}
65,968✔
1319

1320
static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
116,050✔
1321
        Unit *other;
116,050✔
1322
        bool is_bad;
116,050✔
1323

1324
        assert(u);
116,050✔
1325

1326
        if (IN_SET(u->gc_marker - gc_marker,
116,050✔
1327
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1328
                return;
51,141✔
1329

1330
        if (u->in_cleanup_queue)
101,295✔
1331
                goto bad;
×
1332

1333
        if (!unit_may_gc(u))
101,295✔
1334
                goto good;
47,008✔
1335

1336
        u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
54,287✔
1337

1338
        is_bad = true;
54,287✔
1339

1340
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
114,571✔
1341
                unit_gc_sweep(other, gc_marker);
21,673✔
1342

1343
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
21,673✔
1344
                        goto good;
17,901✔
1345

1346
                if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
3,772✔
1347
                        is_bad = false;
3,180✔
1348
        }
1349

1350
        LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
36,661✔
1351
                unit_gc_sweep(ref->source, gc_marker);
275✔
1352

1353
                if (ref->source->gc_marker == gc_marker + GC_OFFSET_GOOD)
275✔
1354
                        goto good;
×
1355

1356
                if (ref->source->gc_marker != gc_marker + GC_OFFSET_BAD)
275✔
1357
                        is_bad = false;
275✔
1358
        }
1359

1360
        if (is_bad)
36,386✔
1361
                goto bad;
34,961✔
1362

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

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

1376
good:
64,909✔
1377
        unit_gc_mark_good(u, gc_marker);
64,909✔
1378
}
1379

1380
static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
201,657✔
1381
        unsigned n = 0, gc_marker;
201,657✔
1382

1383
        assert(m);
201,657✔
1384

1385
        /* log_debug("Running GC..."); */
1386

1387
        m->gc_marker += _GC_OFFSET_MAX;
201,657✔
1388
        if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
201,657✔
1389
                m->gc_marker = 1;
×
1390

1391
        gc_marker = m->gc_marker;
201,657✔
1392

1393
        Unit *u;
201,657✔
1394
        while ((u = m->gc_unit_queue)) {
295,759✔
1395
                assert(u->in_gc_queue);
94,102✔
1396

1397
                unit_gc_sweep(u, gc_marker);
94,102✔
1398

1399
                LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
94,102✔
1400
                u->in_gc_queue = false;
94,102✔
1401

1402
                n++;
94,102✔
1403

1404
                if (IN_SET(u->gc_marker - gc_marker,
94,102✔
1405
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1406
                        if (u->id)
35,327✔
1407
                                log_unit_debug(u, "Collecting.");
35,327✔
1408
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
35,327✔
1409
                        unit_add_to_cleanup_queue(u);
35,327✔
1410
                }
1411
        }
1412

1413
        return n;
201,657✔
1414
}
1415

1416
static unsigned manager_dispatch_gc_job_queue(Manager *m) {
201,664✔
1417
        unsigned n = 0;
201,664✔
1418
        Job *j;
201,664✔
1419

1420
        assert(m);
201,664✔
1421

1422
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
201,672✔
1423
                assert(j->in_gc_queue);
8✔
1424
                j->in_gc_queue = false;
8✔
1425

1426
                n++;
8✔
1427

1428
                if (!job_may_gc(j))
8✔
1429
                        continue;
8✔
1430

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

1435
        return n;
201,664✔
1436
}
1437

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

1441
        assert(u);
×
1442
        assert(s == u->auto_start_stop_event_source);
×
1443

1444
        u->auto_start_stop_event_source = sd_event_source_unref(u->auto_start_stop_event_source);
×
1445

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

1451
        return 0;
×
1452
}
1453

1454
static int manager_ratelimit_check_and_queue(Unit *u) {
13✔
1455
        int r;
13✔
1456

1457
        assert(u);
13✔
1458

1459
        if (ratelimit_below(&u->auto_start_stop_ratelimit))
13✔
1460
                return 1;
1461

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

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

1477
        return 0;
1478
}
1479

1480
static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
174,272✔
1481
        unsigned n = 0;
174,272✔
1482
        Unit *u;
174,272✔
1483
        int r;
174,272✔
1484

1485
        assert(m);
174,272✔
1486

1487
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
174,497✔
1488
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
225✔
1489

1490
                assert(u->in_stop_when_unneeded_queue);
225✔
1491
                u->in_stop_when_unneeded_queue = false;
225✔
1492

1493
                n++;
225✔
1494

1495
                if (!unit_is_unneeded(u))
225✔
1496
                        continue;
215✔
1497

1498
                log_unit_debug(u, "Unit is not needed anymore.");
10✔
1499

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

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

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

1517
        return n;
174,272✔
1518
}
1519

1520
static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
174,406✔
1521
        unsigned n = 0;
174,406✔
1522
        Unit *u;
174,406✔
1523
        int r;
174,406✔
1524

1525
        assert(m);
174,406✔
1526

1527
        while ((u = LIST_POP(start_when_upheld_queue, m->start_when_upheld_queue))) {
174,406✔
1528
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
1529
                Unit *culprit = NULL;
×
1530

1531
                assert(u->in_start_when_upheld_queue);
×
1532
                u->in_start_when_upheld_queue = false;
×
1533

1534
                n++;
×
1535

1536
                if (!unit_is_upheld_by_active(u, &culprit))
×
1537
                        continue;
×
1538

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

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

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

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

1558
        return n;
174,406✔
1559
}
1560

1561
static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
174,406✔
1562
        unsigned n = 0;
174,406✔
1563
        Unit *u;
174,406✔
1564
        int r;
174,406✔
1565

1566
        assert(m);
174,406✔
1567

1568
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
174,642✔
1569
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
236✔
1570
                Unit *culprit = NULL;
236✔
1571

1572
                assert(u->in_stop_when_bound_queue);
236✔
1573
                u->in_stop_when_bound_queue = false;
236✔
1574

1575
                n++;
236✔
1576

1577
                if (!unit_is_bound_by_inactive(u, &culprit))
236✔
1578
                        continue;
233✔
1579

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

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

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

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

1599
        return n;
174,406✔
1600
}
1601

1602
static unsigned manager_dispatch_stop_notify_queue(Manager *m) {
173,244✔
1603
        unsigned n = 0;
173,244✔
1604

1605
        assert(m);
173,244✔
1606

1607
        if (m->may_dispatch_stop_notify_queue < 0)
173,244✔
1608
                m->may_dispatch_stop_notify_queue = hashmap_isempty(m->jobs);
4,586✔
1609

1610
        if (!m->may_dispatch_stop_notify_queue)
173,244✔
1611
                return 0;
1612

1613
        m->may_dispatch_stop_notify_queue = false;
9,063✔
1614

1615
        LIST_FOREACH(stop_notify_queue, u, m->stop_notify_queue) {
9,063✔
1616
                assert(u->in_stop_notify_queue);
×
1617

1618
                assert(UNIT_VTABLE(u)->stop_notify);
×
1619
                if (UNIT_VTABLE(u)->stop_notify(u)) {
×
1620
                        assert(!u->in_stop_notify_queue);
×
1621
                        n++;
×
1622
                }
1623
        }
1624

1625
        return n;
1626
}
1627

1628
static void manager_clear_jobs_and_units(Manager *m) {
751✔
1629
        Unit *u;
751✔
1630

1631
        assert(m);
751✔
1632

1633
        while ((u = hashmap_first(m->units)))
48,454✔
1634
                unit_free(u);
47,703✔
1635

1636
        manager_dispatch_cleanup_queue(m);
751✔
1637

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

1654
        assert(hashmap_isempty(m->jobs));
751✔
1655
        assert(hashmap_isempty(m->units));
751✔
1656
        assert(hashmap_isempty(m->units_by_invocation_id));
751✔
1657

1658
        m->n_on_console = 0;
751✔
1659
        m->n_running_jobs = 0;
751✔
1660
        m->n_installed_jobs = 0;
751✔
1661
        m->n_failed_jobs = 0;
751✔
1662
}
751✔
1663

1664
Manager* manager_free(Manager *m) {
726✔
1665
        if (!m)
726✔
1666
                return NULL;
1667

1668
        manager_clear_jobs_and_units(m);
726✔
1669

1670
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
8,712✔
1671
                if (unit_vtable[c]->shutdown)
7,986✔
1672
                        unit_vtable[c]->shutdown(m);
2,904✔
1673

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

1677
        lookup_paths_flush_generator(&m->lookup_paths);
726✔
1678

1679
        bus_done(m);
726✔
1680
        manager_varlink_done(m);
726✔
1681

1682
        exec_shared_runtime_vacuum(m);
726✔
1683
        hashmap_free(m->exec_shared_runtime_by_id);
726✔
1684

1685
        dynamic_user_vacuum(m, false);
726✔
1686
        hashmap_free(m->dynamic_users);
726✔
1687

1688
        hashmap_free(m->units);
726✔
1689
        hashmap_free(m->units_by_invocation_id);
726✔
1690
        hashmap_free(m->jobs);
726✔
1691
        hashmap_free(m->watch_pids);
726✔
1692
        hashmap_free(m->watch_pids_more);
726✔
1693
        hashmap_free(m->watch_bus);
726✔
1694

1695
        prioq_free(m->run_queue);
726✔
1696

1697
        set_free(m->startup_units);
726✔
1698
        set_free(m->failed_units);
726✔
1699

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

1712
        safe_close(m->signal_fd);
726✔
1713
        safe_close(m->notify_fd);
726✔
1714
        safe_close_pair(m->user_lookup_fds);
726✔
1715
        safe_close_pair(m->handoff_timestamp_fds);
726✔
1716
        safe_close_pair(m->pidref_transport_fds);
726✔
1717

1718
        manager_close_ask_password(m);
726✔
1719

1720
        manager_close_idle_pipe(m);
726✔
1721

1722
        sd_event_unref(m->event);
726✔
1723

1724
        free(m->notify_socket);
726✔
1725

1726
        lookup_paths_done(&m->lookup_paths);
726✔
1727
        strv_free(m->transient_environment);
726✔
1728
        strv_free(m->client_environment);
726✔
1729

1730
        hashmap_free(m->cgroup_unit);
726✔
1731
        manager_free_unit_name_maps(m);
726✔
1732

1733
        free(m->switch_root);
726✔
1734
        free(m->switch_root_init);
726✔
1735

1736
        sd_bus_track_unref(m->subscribed);
726✔
1737
        strv_free(m->subscribed_as_strv);
726✔
1738

1739
        unit_defaults_done(&m->defaults);
726✔
1740

1741
        FOREACH_ARRAY(map, m->units_needing_mounts_for, _UNIT_MOUNT_DEPENDENCY_TYPE_MAX) {
2,178✔
1742
                assert(hashmap_isempty(*map));
1,452✔
1743
                hashmap_free(*map);
1,452✔
1744
        }
1745

1746
        hashmap_free(m->uid_refs);
726✔
1747
        hashmap_free(m->gid_refs);
726✔
1748

1749
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
4,356✔
1750
                free(*i);
3,630✔
1751

1752
        free(m->received_credentials_directory);
726✔
1753
        free(m->received_encrypted_credentials_directory);
726✔
1754

1755
        free(m->watchdog_pretimeout_governor);
726✔
1756
        free(m->watchdog_pretimeout_governor_overridden);
726✔
1757

1758
        sd_netlink_unref(m->nfnl);
726✔
1759

1760
#if BPF_FRAMEWORK
1761
        bpf_restrict_fs_destroy(m->restrict_fs);
726✔
1762
#endif
1763

1764
        safe_close(m->executor_fd);
726✔
1765
        free(m->executor_path);
726✔
1766

1767
        return mfree(m);
726✔
1768
}
1769

1770
static void manager_enumerate_perpetual(Manager *m) {
749✔
1771
        assert(m);
749✔
1772

1773
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
749✔
1774
                return;
1775

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

1783
                if (unit_vtable[c]->enumerate_perpetual)
2,566✔
1784
                        unit_vtable[c]->enumerate_perpetual(m);
825✔
1785
        }
1786
}
1787

1788
static void manager_enumerate(Manager *m) {
749✔
1789
        assert(m);
749✔
1790

1791
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
749✔
1792
                return;
1793

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

1801
                if (unit_vtable[c]->enumerate)
2,566✔
1802
                        unit_vtable[c]->enumerate(m);
519✔
1803
        }
1804

1805
        manager_dispatch_load_queue(m);
275✔
1806
}
1807

1808
static void manager_coldplug(Manager *m) {
749✔
1809
        Unit *u;
749✔
1810
        char *k;
749✔
1811
        int r;
749✔
1812

1813
        assert(m);
749✔
1814

1815
        log_debug("Invoking unit coldplug() handlers%s", glyph(GLYPH_ELLIPSIS));
1,082✔
1816

1817
        /* Let's place the units back into their deserialized state */
1818
        HASHMAP_FOREACH_KEY(u, k, m->units) {
41,068✔
1819

1820
                /* ignore aliases */
1821
                if (u->id != k)
39,570✔
1822
                        continue;
674✔
1823

1824
                r = unit_coldplug(u);
38,896✔
1825
                if (r < 0)
38,896✔
1826
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
40,319✔
1827
        }
1828
}
749✔
1829

1830
static void manager_catchup(Manager *m) {
749✔
1831
        Unit *u;
749✔
1832
        char *k;
749✔
1833

1834
        assert(m);
749✔
1835

1836
        log_debug("Invoking unit catchup() handlers%s", glyph(GLYPH_ELLIPSIS));
1,082✔
1837

1838
        /* Let's catch up on any state changes that happened while we were reloading/reexecing */
1839
        HASHMAP_FOREACH_KEY(u, k, m->units) {
40,319✔
1840

1841
                /* ignore aliases */
1842
                if (u->id != k)
39,570✔
1843
                        continue;
674✔
1844

1845
                unit_catchup(u);
38,896✔
1846
        }
1847
}
749✔
1848

1849
static void manager_distribute_fds(Manager *m, FDSet *fds) {
724✔
1850
        Unit *u;
724✔
1851

1852
        assert(m);
724✔
1853

1854
        HASHMAP_FOREACH(u, m->units) {
8,018✔
1855

1856
                if (fdset_isempty(fds))
7,524✔
1857
                        break;
1858

1859
                if (!UNIT_VTABLE(u)->distribute_fds)
7,294✔
1860
                        continue;
6,520✔
1861

1862
                UNIT_VTABLE(u)->distribute_fds(u, fds);
774✔
1863
        }
1864
}
724✔
1865

1866
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
68,232✔
1867
        Unit *u;
68,232✔
1868

1869
        assert(m);
68,232✔
1870

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

1875
        if (MANAGER_IS_TEST_RUN(m))
68,232✔
1876
                return false;
1877

1878
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
67,357✔
1879
        if (!u)
67,357✔
1880
                return false;
1881
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
111,176✔
1882
                return false;
1883

1884
        u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
5,231✔
1885
        if (!u)
5,231✔
1886
                return false;
1887
        if (!IN_SET((deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state),
10,462✔
1888
                    SERVICE_RUNNING,
1889
                    SERVICE_MOUNTING,
1890
                    SERVICE_RELOAD,
1891
                    SERVICE_RELOAD_NOTIFY,
1892
                    SERVICE_REFRESH_EXTENSIONS,
1893
                    SERVICE_RELOAD_SIGNAL))
1894
                return false;
247✔
1895

1896
        return true;
1897
}
1898

1899
static void manager_setup_bus(Manager *m) {
724✔
1900
        assert(m);
724✔
1901

1902
        if (MANAGER_IS_TEST_RUN(m))
724✔
1903
                return;
1904

1905
        /* Let's set up our private bus connection now, unconditionally */
1906
        (void) bus_init_private(m);
238✔
1907

1908
        /* If we are in --user mode also connect to the system bus now */
1909
        if (MANAGER_IS_USER(m))
238✔
1910
                (void) bus_init_system(m);
187✔
1911

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

1916
                if (MANAGER_IS_SYSTEM(m))
17✔
1917
                        (void) bus_init_system(m);
16✔
1918
        }
1919
}
1920

1921
static void manager_preset_all(Manager *m) {
724✔
1922
        int r;
724✔
1923

1924
        assert(m);
724✔
1925

1926
        if (m->first_boot <= 0)
724✔
1927
                return;
707✔
1928

1929
        if (!MANAGER_IS_SYSTEM(m))
17✔
1930
                return;
1931

1932
        if (MANAGER_IS_TEST_RUN(m))
17✔
1933
                return;
1934

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

1941
        CLEANUP_ARRAY(changes, n_changes, install_changes_free);
×
1942

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

1954
static void manager_ready(Manager *m) {
749✔
1955
        assert(m);
749✔
1956

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

1959
        m->objective = MANAGER_OK; /* Tell everyone we are up now */
749✔
1960

1961
        /* It might be safe to log to the journal now and connect to dbus */
1962
        manager_recheck_journal(m);
749✔
1963
        manager_recheck_dbus(m);
749✔
1964

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

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

1975
Manager* manager_reloading_start(Manager *m) {
153✔
1976
        m->n_reloading++;
153✔
1977
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
153✔
1978
        return m;
153✔
1979
}
1980

1981
void manager_reloading_stopp(Manager **m) {
857✔
1982
        if (*m) {
857✔
1983
                assert((*m)->n_reloading > 0);
128✔
1984
                (*m)->n_reloading--;
128✔
1985
        }
1986
}
857✔
1987

1988
static int manager_make_runtime_dir(Manager *m) {
724✔
1989
        int r;
724✔
1990

1991
        assert(m);
724✔
1992

1993
        _cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
1,448✔
1994
        if (!d)
724✔
1995
                return log_oom();
×
1996

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

2001
        return 0;
2002
}
2003

2004
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
724✔
2005
        int r;
724✔
2006

2007
        assert(m);
724✔
2008

2009
        r = manager_make_runtime_dir(m);
724✔
2010
        if (r < 0)
724✔
2011
                return r;
2012

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

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

2029
        manager_preset_all(m);
724✔
2030

2031
        lookup_paths_log(&m->lookup_paths);
724✔
2032

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

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

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

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

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

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

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

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

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

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

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

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

2099
                /* Connect to the bus if we are good for it */
2100
                manager_setup_bus(m);
724✔
2101

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

2106
                /* Third, fire things up! */
2107
                manager_coldplug(m);
724✔
2108

2109
                /* Clean up runtime objects */
2110
                manager_vacuum(m);
724✔
2111

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

2118
        manager_ready(m);
724✔
2119

2120
        manager_set_switching_root(m, false);
724✔
2121

2122
        return 0;
724✔
2123
}
2124

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

2135
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,374✔
2136
        int r;
1,374✔
2137

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

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

2147
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,374✔
2148
                return sd_bus_error_set(error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
24✔
2149

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

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

2156
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1,350✔
2157

2158
        type = job_type_collapse(type, unit);
1,350✔
2159

2160
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1,350✔
2161
        if (!tr)
1,350✔
2162
                return -ENOMEM;
2163

2164
        r = transaction_add_job_and_dependencies(
4,050✔
2165
                        tr,
2166
                        type,
2167
                        unit,
2168
                        /* by= */ NULL,
2169
                        TRANSACTION_MATTERS |
2170
                        (IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS) ? TRANSACTION_IGNORE_REQUIREMENTS : 0) |
1,350✔
2171
                        (mode == JOB_IGNORE_DEPENDENCIES ? TRANSACTION_IGNORE_ORDER : 0) |
1,350✔
2172
                        (mode == JOB_RESTART_DEPENDENCIES ? TRANSACTION_PROPAGATE_START_AS_RESTART : 0) |
2,695✔
2173
                        extra_flags,
2174
                        error);
2175
        if (r < 0)
1,350✔
2176
                return r;
2177

2178
        if (mode == JOB_ISOLATE) {
1,342✔
2179
                r = transaction_add_isolate_jobs(tr, m);
208✔
2180
                if (r < 0)
208✔
2181
                        return r;
2182
        }
2183

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

2190
        r = transaction_activate(tr, m, mode, affected_jobs, error);
1,342✔
2191
        if (r < 0)
1,342✔
2192
                return r;
2193

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

2198
        if (ret)
1,338✔
2199
                *ret = tr->anchor_job;
743✔
2200

2201
        tr = transaction_free(tr);
1,338✔
2202
        return 0;
1,338✔
2203
}
2204

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

2213
        return manager_add_job_full(m, type, unit, mode, 0, NULL, error, ret);
856✔
2214
}
2215

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

2220
        assert(m);
202✔
2221
        assert(type < _JOB_TYPE_MAX);
202✔
2222
        assert(name);
202✔
2223
        assert(mode < _JOB_MODE_MAX);
202✔
2224

2225
        r = manager_load_unit(m, name, NULL, NULL, &unit);
202✔
2226
        if (r < 0)
202✔
2227
                return r;
202✔
2228
        assert(unit);
202✔
2229

2230
        return manager_add_job_full(m, type, unit, mode, /* extra_flags = */ 0, affected_jobs, e, ret);
202✔
2231
}
2232

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

2237
        assert(m);
187✔
2238
        assert(type < _JOB_TYPE_MAX);
187✔
2239
        assert(name);
187✔
2240
        assert(mode < _JOB_MODE_MAX);
187✔
2241

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

2246
        return r;
2247
}
2248

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

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

2258
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
17,339✔
2259
        if (!tr)
17,339✔
2260
                return -ENOMEM;
2261

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

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

2274
        r = transaction_activate(tr, m, mode, NULL, e);
17,339✔
2275
        if (r < 0)
17,339✔
2276
                return r;
2277

2278
        tr = transaction_free(tr);
17,339✔
2279
        return 0;
17,339✔
2280
}
2281

2282
Job *manager_get_job(Manager *m, uint32_t id) {
16,582✔
2283
        assert(m);
16,582✔
2284

2285
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
16,582✔
2286
}
2287

2288
Unit *manager_get_unit(Manager *m, const char *name) {
1,695,429✔
2289
        assert(m);
1,695,429✔
2290
        assert(name);
1,695,429✔
2291

2292
        return hashmap_get(m->units, name);
1,695,429✔
2293
}
2294

2295
static int manager_dispatch_target_deps_queue(Manager *m) {
216,659✔
2296
        Unit *u;
216,659✔
2297
        int r = 0;
216,659✔
2298

2299
        assert(m);
216,659✔
2300

2301
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
277,645✔
2302
                _cleanup_free_ Unit **targets = NULL;
60,986✔
2303
                int n_targets;
60,986✔
2304

2305
                assert(u->in_target_deps_queue);
60,986✔
2306

2307
                u->in_target_deps_queue = false;
60,986✔
2308

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

2316
                FOREACH_ARRAY(i, targets, n_targets) {
118,956✔
2317
                        r = unit_add_default_target_dependency(u, *i);
57,970✔
2318
                        if (r < 0)
57,970✔
2319
                                return r;
2320
                }
2321
        }
2322

2323
        return r;
2324
}
2325

2326
unsigned manager_dispatch_load_queue(Manager *m) {
245,294✔
2327
        Unit *u;
245,294✔
2328
        unsigned n = 0;
245,294✔
2329

2330
        assert(m);
245,294✔
2331

2332
        /* Make sure we are not run recursively */
2333
        if (m->dispatching_load_queue)
245,294✔
2334
                return 0;
2335

2336
        m->dispatching_load_queue = true;
216,659✔
2337

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

2341
        while ((u = m->load_queue)) {
299,828✔
2342
                assert(u->in_load_queue);
83,169✔
2343

2344
                unit_load(u);
83,169✔
2345
                n++;
83,169✔
2346
        }
2347

2348
        m->dispatching_load_queue = false;
216,659✔
2349

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

2354
        return n;
216,659✔
2355
}
2356

2357
bool manager_unit_cache_should_retry_load(Unit *u) {
452,892✔
2358
        assert(u);
452,892✔
2359

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

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

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

2375
int manager_load_unit_prepare(
435,761✔
2376
                Manager *m,
2377
                const char *name,
2378
                const char *path,
2379
                sd_bus_error *e,
2380
                Unit **ret) {
2381

2382
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2383
        _cleanup_free_ char *nbuf = NULL;
435,761✔
2384
        int r;
435,761✔
2385

2386
        assert(m);
435,761✔
2387
        assert(ret);
435,761✔
2388
        assert(name || path);
435,761✔
2389

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

2392
        if (path && !path_is_absolute(path))
435,761✔
2393
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2394

2395
        if (!name) {
435,761✔
2396
                r = path_extract_filename(path, &nbuf);
464✔
2397
                if (r < 0)
464✔
2398
                        return r;
2399
                if (r == O_DIRECTORY)
464✔
2400
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2401

2402
                name = nbuf;
464✔
2403
        }
2404

2405
        UnitType t = unit_name_to_type(name);
435,761✔
2406

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

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

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

2437
        if (path) {
52,444✔
2438
                r = free_and_strdup(&unit->fragment_path, path);
464✔
2439
                if (r < 0)
464✔
2440
                        return r;
2441
        }
2442

2443
        r = unit_add_name(unit, name);
52,444✔
2444
        if (r < 0)
52,444✔
2445
                return r;
2446

2447
        unit_add_to_load_queue(unit);
52,444✔
2448
        unit_add_to_dbus_queue(unit);
52,444✔
2449
        unit_add_to_gc_queue(unit);
52,444✔
2450

2451
        *ret = unit;
52,444✔
2452
        TAKE_PTR(cleanup_unit);
52,444✔
2453

2454
        return 1;  /* The unit was added the load queue */
52,444✔
2455
}
2456

2457
int manager_load_unit(
414,317✔
2458
                Manager *m,
2459
                const char *name,
2460
                const char *path,
2461
                sd_bus_error *e,
2462
                Unit **ret) {
2463
        int r;
414,317✔
2464

2465
        assert(m);
414,317✔
2466
        assert(ret);
414,317✔
2467

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

2470
        r = manager_load_unit_prepare(m, name, path, e, ret);
414,317✔
2471
        if (r <= 0)
414,317✔
2472
                return r;
2473

2474
        /* Unit was newly loaded */
2475
        manager_dispatch_load_queue(m);
31,028✔
2476
        *ret = unit_follow_merge(*ret);
31,028✔
2477
        return 0;
31,028✔
2478
}
2479

2480
int manager_load_startable_unit_or_warn(
723✔
2481
                Manager *m,
2482
                const char *name,
2483
                const char *path,
2484
                Unit **ret) {
2485

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

2488
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
723✔
2489
        Unit *unit;
723✔
2490
        int r;
723✔
2491

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

2498
        r = bus_unit_validate_load_state(unit, &error);
723✔
2499
        if (r < 0)
723✔
2500
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2501

2502
        *ret = unit;
714✔
2503
        return 0;
714✔
2504
}
2505

2506
void manager_clear_jobs(Manager *m) {
454✔
2507
        Job *j;
454✔
2508

2509
        assert(m);
454✔
2510

2511
        while ((j = hashmap_first(m->jobs)))
475✔
2512
                /* No need to recurse. We're cancelling all jobs. */
2513
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
21✔
2514
}
454✔
2515

2516
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
2,119✔
2517
        assert(m);
2,119✔
2518

2519
        for (;;) {
×
2520
                Unit *u;
2,119✔
2521

2522
                u = manager_get_unit_by_pidref_watching(m, pid);
2,119✔
2523
                if (!u)
2,119✔
2524
                        break;
2525

2526
                unit_unwatch_pidref(u, pid);
×
2527
        }
2528
}
2,119✔
2529

2530
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
5,442✔
2531
        Manager *m = ASSERT_PTR(userdata);
5,442✔
2532
        Job *j;
5,442✔
2533

2534
        assert(source);
5,442✔
2535

2536
        while ((j = prioq_peek(m->run_queue))) {
60,845✔
2537
                assert(j->installed);
55,403✔
2538
                assert(j->in_run_queue);
55,403✔
2539

2540
                (void) job_run_and_invalidate(j);
55,403✔
2541
        }
2542

2543
        if (m->n_running_jobs > 0)
5,442✔
2544
                manager_watch_jobs_in_progress(m);
2,876✔
2545

2546
        if (m->n_on_console > 0)
5,442✔
2547
                manager_watch_idle_pipe(m);
339✔
2548

2549
        return 1;
5,442✔
2550
}
2551

2552
void manager_trigger_run_queue(Manager *m) {
57,896✔
2553
        int r;
57,896✔
2554

2555
        assert(m);
57,896✔
2556

2557
        r = sd_event_source_set_enabled(
115,626✔
2558
                        m->run_queue_event_source,
2559
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
57,896✔
2560
        if (r < 0)
57,896✔
2561
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2562
}
57,896✔
2563

2564
static unsigned manager_dispatch_dbus_queue(Manager *m) {
173,244✔
2565
        unsigned n = 0, budget;
173,244✔
2566
        Unit *u;
173,244✔
2567
        Job *j;
173,244✔
2568

2569
        assert(m);
173,244✔
2570

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

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

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

2599
        while (budget != 0 && (u = m->dbus_unit_queue)) {
32,731✔
2600

2601
                assert(u->in_dbus_queue);
24,269✔
2602

2603
                bus_unit_send_change_signal(u);
24,269✔
2604
                n++;
24,269✔
2605

2606
                if (budget != UINT_MAX)
24,269✔
2607
                        budget--;
13,094✔
2608
        }
2609

2610
        while (budget != 0 && (j = m->dbus_job_queue)) {
43,629✔
2611
                assert(j->in_dbus_queue);
35,167✔
2612

2613
                bus_job_send_change_signal(j);
35,167✔
2614
                n++;
35,167✔
2615

2616
                if (budget != UINT_MAX)
35,167✔
2617
                        budget--;
34,777✔
2618
        }
2619

2620
        if (m->send_reloading_done) {
8,462✔
2621
                m->send_reloading_done = false;
45✔
2622
                bus_manager_send_reloading(m, false);
45✔
2623
                n++;
45✔
2624
        }
2625

2626
        if (m->pending_reload_message) {
8,462✔
2627
                bus_send_pending_reload_message(m);
25✔
2628
                n++;
25✔
2629
        }
2630

2631
        return n;
2632
}
2633

2634
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
2,934✔
2635

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

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

2647
        return false;
2648
}
2649

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

2658
        assert(m);
5,706✔
2659
        assert(u);
5,706✔
2660
        assert(pidref_is_set(pidref));
5,706✔
2661
        assert(ucred);
5,706✔
2662
        assert(pidref->pid == ucred->pid);
5,706✔
2663
        assert(tags);
5,706✔
2664

2665
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
5,706✔
2666
                return;
2667
        u->notifygen = m->notifygen;
2,920✔
2668

2669
        if (UNIT_VTABLE(u)->notify_message)
2,920✔
2670
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
2,920✔
2671

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

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

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

2684
        assert(m);
9,505✔
2685
        assert(pidref_is_set(pidref));
9,505✔
2686

2687
        Unit *u1, *u2, **array;
9,505✔
2688
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
9,505✔
2689
        u2 = hashmap_get(m->watch_pids, pidref);
9,505✔
2690
        array = hashmap_get(m->watch_pids_more, pidref);
9,505✔
2691

2692
        size_t n = 0;
9,505✔
2693
        if (u1)
9,505✔
2694
                n++;
9,503✔
2695
        if (u2)
9,505✔
2696
                n++;
6,826✔
2697
        if (array)
9,505✔
UNCOV
2698
                for (size_t j = 0; array[j]; j++)
×
UNCOV
2699
                        n++;
×
2700

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

2703
        if (ret_units) {
9,505✔
2704
                _cleanup_free_ Unit **units = NULL;
×
2705

2706
                if (n > 0) {
9,505✔
2707
                        units = new(Unit*, n + 1);
9,503✔
2708
                        if (!units)
9,503✔
2709
                                return -ENOMEM;
×
2710

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

2715
                        size_t i = 0;
9,503✔
2716
                        if (u1)
9,503✔
2717
                                units[i++] = u1;
9,503✔
2718
                        if (u2)
9,503✔
2719
                                units[i++] = u2;
6,826✔
2720
                        if (array)
9,503✔
UNCOV
2721
                                for (size_t j = 0; array[j]; j++)
×
UNCOV
2722
                                        units[i++] = array[j];
×
2723
                        assert(i == n);
9,503✔
2724

2725
                        units[i] = NULL; /* end array in an extra NULL */
9,503✔
2726
                }
2727

2728
                *ret_units = TAKE_PTR(units);
9,505✔
2729
        }
2730

2731
        return (int) n;
9,505✔
2732
}
2733

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

2741
        assert(m->notify_fd == fd);
2,934✔
2742

2743
        if (revents != EPOLLIN) {
2,934✔
2744
                log_warning("Got unexpected poll event for notify fd.");
×
2745
                return 0;
×
2746
        }
2747

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

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

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

2768
        /* Notify every unit that might be interested, which might be multiple. */
2769
        _cleanup_free_ Unit **array = NULL;
2,922✔
2770

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

2784
        if (!fdset_isempty(fds))
2,922✔
2785
                log_warning("Got extra auxiliary fds with notification message, closing them.");
×
2786

2787
        return 0;
2788
}
2789

2790
static void manager_invoke_sigchld_event(
6,437✔
2791
                Manager *m,
2792
                Unit *u,
2793
                const siginfo_t *si) {
2794

2795
        assert(m);
6,437✔
2796
        assert(u);
6,437✔
2797
        assert(si);
6,437✔
2798

2799
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2800
        if (u->sigchldgen == m->sigchldgen)
6,437✔
2801
                return;
1,942✔
2802
        u->sigchldgen = m->sigchldgen;
4,495✔
2803

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

2807
        if (UNIT_VTABLE(u)->sigchld_event)
4,495✔
2808
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
4,367✔
2809
}
2810

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

2816
        assert(source);
8,009✔
2817

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

2821
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
8,009✔
2822

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

2826
                goto turn_off;
86✔
2827
        }
2828

2829
        if (si.si_pid <= 0)
7,923✔
2830
                goto turn_off;
3,433✔
2831

2832
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
4,490✔
2833
                _cleanup_free_ char *name = NULL;
8,980✔
2834
                (void) pid_get_comm(si.si_pid, &name);
4,490✔
2835

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

2844
                /* Increase the generation counter used for filtering out duplicate unit invocations */
2845
                m->sigchldgen++;
4,490✔
2846

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

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

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

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

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

2880
        return 0;
2881

2882
turn_off:
3,519✔
2883
        /* All children processed for now, turn off event source */
2884

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

2889
        return 0;
2890
}
2891

2892
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
186✔
2893
        Job *job;
186✔
2894

2895
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
186✔
2896
                return;
×
2897

2898
        const char *s = unit_status_string(job->unit, NULL);
186✔
2899

2900
        log_info("Activating special unit %s...", s);
186✔
2901

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

2907
static void manager_handle_ctrl_alt_del(Manager *m) {
×
2908
        assert(m);
×
2909

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

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

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

2931
        assert(m->signal_fd == fd);
3,444✔
2932

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

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

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

2952
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
3,630✔
2953
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
186✔
2954
                            ? LOG_DEBUG : LOG_INFO,
2955
                            &sfsi);
2956

2957
        switch (sfsi.ssi_signo) {
3,444✔
2958

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

2964
                break;
2965

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

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

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

2986
                break;
2987

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

2993
                break;
2994

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

2999
                        (void) bus_init_api(m);
×
3000

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

3006
                break;
3007

3008
        case SIGUSR2: {
×
3009
                _cleanup_free_ char *dump = NULL;
×
3010

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

3017
                log_dump(LOG_INFO, dump);
×
3018
                break;
3019
        }
3020

3021
        case SIGHUP:
×
3022
                m->objective = MANAGER_RELOAD;
×
3023
                break;
×
3024

3025
        default: {
×
3026

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

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

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

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

3066
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3067

3068
                case 18: {
×
3069
                        bool generic = false;
×
3070

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

3076
                                switch (sfsi.ssi_int) {
×
3077

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

3082
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3083
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3084
                                        break;
3085

3086
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3087
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3088
                                        break;
3089

3090
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3091
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3092
                                        break;
3093

3094
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3095
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3096
                                        break;
3097

3098
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3099
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3100

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

3107
                                        log_dump(LOG_INFO, dump_jobs);
×
3108
                                        break;
3109
                                }
3110

3111
                                default:
3112
                                        generic = true;
3113
                                }
3114
                        }
3115

3116
                        if (generic)
×
3117
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3118

3119
                        break;
3120
                }
3121

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

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

3130
                case 22:
×
3131
                        manager_override_log_level(m, LOG_DEBUG);
×
3132
                        break;
3133

3134
                case 23:
×
3135
                        manager_restore_original_log_level(m);
×
3136
                        break;
3137

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

3144
                        /* This is a nop on init */
3145
                        break;
3146

3147
                case 25:
×
3148
                        m->objective = MANAGER_REEXECUTE;
×
3149
                        break;
×
3150

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

3156
                case 27:
×
3157
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3158
                        break;
3159

3160
                case 28:
×
3161
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3162
                        break;
3163

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

3169
        return 0;
3170
}
3171

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

3176
        log_struct(LOG_DEBUG,
10✔
3177
                   LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
3178
                   LOG_MESSAGE("Time has been changed"));
3179

3180
        /* Restart the watch */
3181
        (void) manager_setup_time_change(m);
10✔
3182

3183
        HASHMAP_FOREACH(u, m->units)
1,366✔
3184
                if (UNIT_VTABLE(u)->time_change)
1,346✔
3185
                        UNIT_VTABLE(u)->time_change(u);
10✔
3186

3187
        return 0;
10✔
3188
}
3189

3190
static int manager_dispatch_timezone_change(
55✔
3191
                sd_event_source *source,
3192
                const struct inotify_event *e,
3193
                void *userdata) {
3194

3195
        Manager *m = ASSERT_PTR(userdata);
55✔
3196
        int changed;
55✔
3197
        Unit *u;
55✔
3198

3199
        log_debug("inotify event for /etc/localtime");
55✔
3200

3201
        changed = manager_read_timezone_stat(m);
55✔
3202
        if (changed <= 0)
55✔
3203
                return changed;
55✔
3204

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

3208
        /* Read the new timezone */
3209
        tzset();
30✔
3210

3211
        log_debug("Timezone has been changed (now: %s).", tzname[daylight]);
30✔
3212

3213
        HASHMAP_FOREACH(u, m->units)
6,049✔
3214
                if (UNIT_VTABLE(u)->timezone_change)
5,989✔
3215
                        UNIT_VTABLE(u)->timezone_change(u);
64✔
3216

3217
        return 0;
30✔
3218
}
3219

3220
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
8✔
3221
        Manager *m = ASSERT_PTR(userdata);
8✔
3222

3223
        assert(m->idle_pipe[2] == fd);
8✔
3224

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

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

3236
        return 0;
8✔
3237
}
3238

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

UNCOV
3243
        assert(source);
×
3244

UNCOV
3245
        manager_print_jobs_in_progress(m);
×
3246

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

UNCOV
3251
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
×
3252
}
3253

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

3258
        assert(m);
263✔
3259
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
263✔
3260

3261
        manager_check_finished(m);
263✔
3262

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

3268
        while (m->objective == MANAGER_OK) {
201,927✔
3269

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

3276
                (void) watchdog_ping();
201,664✔
3277

3278
                if (manager_dispatch_load_queue(m) > 0)
201,664✔
3279
                        continue;
×
3280

3281
                if (manager_dispatch_gc_job_queue(m) > 0)
201,664✔
3282
                        continue;
7✔
3283

3284
                if (manager_dispatch_gc_unit_queue(m) > 0)
201,657✔
3285
                        continue;
15,188✔
3286

3287
                if (manager_dispatch_cleanup_queue(m) > 0)
186,469✔
3288
                        continue;
8,599✔
3289

3290
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
177,870✔
3291
                        continue;
3,464✔
3292

3293
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
174,406✔
3294
                        continue;
×
3295

3296
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
174,406✔
3297
                        continue;
134✔
3298

3299
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
174,272✔
3300
                        continue;
142✔
3301

3302
                if (manager_dispatch_release_resources_queue(m) > 0)
174,130✔
3303
                        continue;
886✔
3304

3305
                if (manager_dispatch_stop_notify_queue(m) > 0)
173,244✔
3306
                        continue;
×
3307

3308
                if (manager_dispatch_dbus_queue(m) > 0)
173,244✔
3309
                        continue;
8,462✔
3310

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

3317
        return m->objective;
3318
}
3319

3320
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
233,263✔
3321
        _cleanup_free_ char *n = NULL;
233,263✔
3322
        sd_id128_t invocation_id;
233,263✔
3323
        Unit *u;
233,263✔
3324
        int r;
233,263✔
3325

3326
        assert(m);
233,263✔
3327
        assert(s);
233,263✔
3328
        assert(_u);
233,263✔
3329

3330
        r = unit_name_from_dbus_path(s, &n);
233,263✔
3331
        if (r < 0)
233,263✔
3332
                return r;
3333

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

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

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

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

3358
        r = manager_load_unit(m, n, NULL, e, &u);
233,262✔
3359
        if (r < 0)
233,262✔
3360
                return r;
3361

3362
        *_u = u;
233,262✔
3363
        return 0;
233,262✔
3364
}
3365

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

3372
        assert(m);
595✔
3373
        assert(s);
595✔
3374
        assert(_j);
595✔
3375

3376
        p = startswith(s, "/org/freedesktop/systemd1/job/");
595✔
3377
        if (!p)
595✔
3378
                return -EINVAL;
595✔
3379

3380
        r = safe_atou(p, &id);
595✔
3381
        if (r < 0)
595✔
3382
                return r;
3383

3384
        j = manager_get_job(m, id);
595✔
3385
        if (!j)
595✔
3386
                return -ENOENT;
3387

3388
        *_j = j;
595✔
3389

3390
        return 0;
595✔
3391
}
3392

3393
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
3,166✔
3394

3395
#if HAVE_AUDIT
3396
        _cleanup_free_ char *p = NULL;
3,166✔
3397
        const char *msg;
3,166✔
3398
        int audit_fd, r;
3,166✔
3399

3400
        assert(m);
3,166✔
3401
        assert(u);
3,166✔
3402

3403
        if (!MANAGER_IS_SYSTEM(m))
3,166✔
3404
                return;
3405

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

3410
        audit_fd = get_core_audit_fd();
1,816✔
3411
        if (audit_fd < 0)
1,816✔
3412
                return;
3413

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

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

3432
void manager_send_unit_plymouth(Manager *m, Unit *u) {
37,133✔
3433
        _cleanup_free_ char *message = NULL;
37,133✔
3434
        int c, r;
37,133✔
3435

3436
        assert(m);
37,133✔
3437
        assert(u);
37,133✔
3438

3439
        if (!MANAGER_IS_SYSTEM(m))
37,133✔
3440
                return;
3441

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

3446
        if (detect_container() > 0)
5,419✔
3447
                return;
3448

3449
        if (!UNIT_VTABLE(u)->notify_plymouth)
3,183✔
3450
                return;
3451

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

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

3463
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
58,939✔
3464
        assert(m);
58,939✔
3465
        assert(u);
58,939✔
3466

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

3470
        if (MANAGER_IS_RELOADING(m))
58,939✔
3471
                return;
3472

3473
        if (!UNIT_VTABLE(u)->notify_supervisor)
58,939✔
3474
                return;
3475

3476
        if (in_initrd()) /* Only send these once we left the initrd */
4,148✔
3477
                return;
3478

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

3484
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
544✔
3485
        assert(m);
544✔
3486

3487
        if (MANAGER_IS_USER(m))
544✔
3488
                return USEC_INFINITY;
3489

3490
        if (m->watchdog_overridden[t] != USEC_INFINITY)
166✔
3491
                return m->watchdog_overridden[t];
3492

3493
        return m->watchdog[t];
166✔
3494
}
3495

3496
void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
1,052✔
3497

3498
        assert(m);
1,052✔
3499

3500
        if (MANAGER_IS_USER(m))
1,052✔
3501
                return;
3502

3503
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
296✔
3504
                if (t == WATCHDOG_RUNTIME)
296✔
3505
                        (void) watchdog_setup(timeout);
74✔
3506
                else if (t == WATCHDOG_PRETIMEOUT)
222✔
3507
                        (void) watchdog_setup_pretimeout(timeout);
74✔
3508
        }
3509

3510
        m->watchdog[t] = timeout;
296✔
3511
}
3512

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

3516
        assert(m);
×
3517

3518
        if (MANAGER_IS_USER(m))
×
3519
                return;
3520

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

3527
        m->watchdog_overridden[t] = timeout;
×
3528
}
3529

3530
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
263✔
3531
        _cleanup_free_ char *p = NULL;
263✔
3532
        int r;
263✔
3533

3534
        assert(m);
263✔
3535

3536
        if (MANAGER_IS_USER(m))
263✔
3537
                return 0;
3538

3539
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
74✔
3540
                return 0;
3541

3542
        p = strdup(governor);
×
3543
        if (!p)
×
3544
                return -ENOMEM;
3545

3546
        r = watchdog_setup_pretimeout_governor(governor);
×
3547
        if (r < 0)
×
3548
                return r;
3549

3550
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3551
}
3552

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

3557
        assert(m);
×
3558

3559
        if (MANAGER_IS_USER(m))
×
3560
                return 0;
3561

3562
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3563
                return 0;
3564

3565
        p = strdup(governor);
×
3566
        if (!p)
×
3567
                return -ENOMEM;
3568

3569
        r = watchdog_setup_pretimeout_governor(governor);
×
3570
        if (r < 0)
×
3571
                return r;
3572

3573
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3574
}
3575

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

3582
        assert(m);
25✔
3583

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

3588
        fds = fdset_new();
25✔
3589
        if (!fds)
25✔
3590
                return log_oom();
×
3591

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

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

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

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

3606
        bus_manager_send_reloading(m, true);
25✔
3607

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

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

3619
        (void) manager_run_environment_generators(m);
25✔
3620
        (void) manager_run_generators(m);
25✔
3621

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

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

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

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

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

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

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

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

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

3659
        manager_ready(m);
25✔
3660

3661
        m->send_reloading_done = true;
25✔
3662
        return 0;
25✔
3663
}
3664

3665
void manager_reset_failed(Manager *m) {
1✔
3666
        Unit *u;
1✔
3667

3668
        assert(m);
1✔
3669

3670
        HASHMAP_FOREACH(u, m->units)
251✔
3671
                unit_reset_failed(u);
250✔
3672
}
1✔
3673

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

3677
        assert(m);
×
3678
        assert(name);
×
3679

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

3685
        return unit_inactive_or_pending(u);
×
3686
}
3687

3688
static void log_taint_string(Manager *m) {
18,356✔
3689
        assert(m);
18,356✔
3690

3691
        if (MANAGER_IS_USER(m) || m->taint_logged)
18,356✔
3692
                return;
18,356✔
3693

3694
        m->taint_logged = true; /* only check for taint once */
32✔
3695

3696
        _cleanup_free_ char *taint = taint_string();
64✔
3697
        if (isempty(taint))
32✔
3698
                return;
32✔
3699

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

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

3709
        if (MANAGER_IS_TEST_RUN(m))
192✔
3710
                return;
3711

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

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

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

UNCOV
3734
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
×
UNCOV
3735
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
UNCOV
3736
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
×
UNCOV
3737
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
×
3738

UNCOV
3739
                if (firmware_usec > 0)
×
3740
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
UNCOV
3741
                if (loader_usec > 0)
×
3742
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3743

UNCOV
3744
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
×
3745

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

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

UNCOV
3764
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
UNCOV
3765
                        initrd_usec = 0;
×
3766

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

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

3789
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
185✔
3790

3791
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
185✔
UNCOV
3792
                watchdog_report_if_missing();
×
3793

3794
        log_taint_string(m);
185✔
3795
}
3796

3797
static void manager_send_ready_on_basic_target(Manager *m) {
18,171✔
3798
        int r;
18,171✔
3799

3800
        assert(m);
18,171✔
3801

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

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

3812
        m->ready_sent = true;
194✔
3813
        m->status_ready = false;
194✔
3814
}
3815

3816
static void manager_send_ready_on_idle(Manager *m) {
2,229✔
3817
        int r;
2,229✔
3818

3819
        assert(m);
2,229✔
3820

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

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

3835
        m->ready_sent = m->status_ready = true;
195✔
3836
}
3837

3838
static void manager_check_basic_target(Manager *m) {
31,843✔
3839
        Unit *u;
31,843✔
3840

3841
        assert(m);
31,843✔
3842

3843
        /* Small shortcut */
3844
        if (m->ready_sent && m->taint_logged)
31,843✔
3845
                return;
3846

3847
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
31,843✔
3848
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
31,843✔
3849
                return;
13,672✔
3850

3851
        /* For user managers, send out READY=1 as soon as we reach basic.target */
3852
        manager_send_ready_on_basic_target(m);
18,171✔
3853

3854
        /* Log the taint string as soon as we reach basic.target */
3855
        log_taint_string(m);
18,171✔
3856
}
3857

3858
void manager_check_finished(Manager *m) {
32,045✔
3859
        assert(m);
32,045✔
3860

3861
        if (MANAGER_IS_RELOADING(m))
32,045✔
3862
                return;
3863

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

3868
        manager_check_basic_target(m);
31,843✔
3869

3870
        if (!hashmap_isempty(m->jobs)) {
31,843✔
3871
                if (m->jobs_in_progress_event_source)
29,614✔
3872
                        /* Ignore any failure, this is only for feedback */
3873
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
3,554✔
3874
                                                        manager_watch_jobs_next_time(m));
3,554✔
3875
                return;
29,614✔
3876
        }
3877

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

3883
        manager_send_ready_on_idle(m);
2,229✔
3884

3885
        /* Notify Type=idle units that we are done now */
3886
        manager_close_idle_pipe(m);
2,229✔
3887

3888
        if (MANAGER_IS_FINISHED(m))
2,229✔
3889
                return;
3890

3891
        manager_flip_auto_status(m, false, "boot finished");
192✔
3892

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

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

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

3902
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
192✔
3903

3904
        manager_notify_finished(m);
192✔
3905

3906
        manager_invalidate_startup_units(m);
192✔
3907
}
3908

3909
void manager_send_reloading(Manager *m) {
63✔
3910
        assert(m);
63✔
3911

3912
        /* Let whoever invoked us know that we are now reloading */
3913
        (void) notify_reloading_full(/* status = */ NULL);
63✔
3914

3915
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
3916
        m->ready_sent = false;
63✔
3917
}
63✔
3918

3919
static bool generator_path_any(char * const *paths) {
989✔
3920

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

3923
        STRV_FOREACH(i, paths) {
3,956✔
3924
                if (access(*i, F_OK) >= 0)
3,956✔
3925
                        return true;
3926
                if (errno != ENOENT)
2,967✔
3927
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
2,967✔
3928
        }
3929

3930
        return false;
3931
}
3932

3933
static int manager_run_environment_generators(Manager *m) {
749✔
3934
        _cleanup_strv_free_ char **paths = NULL;
749✔
3935
        int r;
749✔
3936

3937
        assert(m);
749✔
3938

3939
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
749✔
3940
                return 0;
3941

3942
        paths = env_generator_binary_paths(m->runtime_scope);
726✔
3943
        if (!paths)
726✔
3944
                return log_oom();
×
3945

3946
        if (!generator_path_any(paths))
726✔
3947
                return 0;
3948

3949
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
726✔
3950
        void *args[_STDOUT_CONSUME_MAX] = {
726✔
3951
                [STDOUT_GENERATE] = &tmp,
3952
                [STDOUT_COLLECT]  = &tmp,
3953
                [STDOUT_CONSUME]  = &m->transient_environment,
726✔
3954
        };
3955

3956
        WITH_UMASK(0022)
1,452✔
3957
                r = execute_directories(
726✔
3958
                                "environment-generators",
3959
                                (const char* const*) paths,
3960
                                DEFAULT_TIMEOUT_USEC,
3961
                                gather_environment,
3962
                                args,
3963
                                /* argv[]= */ NULL,
3964
                                m->transient_environment,
3965
                                EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
3966
        return r;
726✔
3967
}
3968

3969
static int build_generator_environment(Manager *m, char ***ret) {
189✔
3970
        _cleanup_strv_free_ char **nl = NULL;
189✔
3971
        Virtualization v;
189✔
3972
        ConfidentialVirtualization cv;
189✔
3973
        int r;
189✔
3974

3975
        assert(m);
189✔
3976
        assert(ret);
189✔
3977

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

3982
        nl = strv_copy(m->transient_environment);
189✔
3983
        if (!nl)
189✔
3984
                return -ENOMEM;
3985

3986
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
189✔
3987
        if (r < 0)
189✔
3988
                return r;
3989

3990
        if (MANAGER_IS_SYSTEM(m)) {
189✔
3991
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
3992
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
3993
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
3994
                 * same results (hopefully). */
3995
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
3996
                if (r < 0)
×
3997
                        return r;
3998

3999
                if (m->soft_reboots_count > 0) {
×
4000
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
4001
                        if (r < 0)
×
4002
                                return r;
4003
                }
4004

4005
                if (m->first_boot >= 0) {
×
4006
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4007
                        if (r < 0)
×
4008
                                return r;
4009
                }
4010
        }
4011

4012
        v = detect_virtualization();
189✔
4013
        if (v < 0)
189✔
4014
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4015
        else if (v > 0) {
189✔
4016
                const char *s;
189✔
4017

4018
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
945✔
4019
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4020
                             virtualization_to_string(v));
4021

4022
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
189✔
4023
                if (r < 0)
189✔
4024
                        return r;
4025
        }
4026

4027
        cv = detect_confidential_virtualization();
189✔
4028
        if (cv < 0)
189✔
4029
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4030
        else if (cv > 0) {
189✔
4031
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4032
                if (r < 0)
×
4033
                        return r;
4034
        }
4035

4036
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
189✔
4037
        if (r < 0)
189✔
4038
                return r;
4039

4040
        *ret = TAKE_PTR(nl);
189✔
4041
        return 0;
189✔
4042
}
4043

4044
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
189✔
4045
        _cleanup_strv_free_ char **ge = NULL;
189✔
4046
        int r;
189✔
4047

4048
        assert(m);
189✔
4049

4050
        r = build_generator_environment(m, &ge);
189✔
4051
        if (r < 0)
189✔
4052
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4053

4054
        if (remount_ro) {
189✔
4055
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4056
                 * checks whether it is read-only to detect containerized execution environments. We leave
4057
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4058
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4059
                 */
4060
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4061
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4062
                if (r < 0)
×
4063
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4064
        }
4065

4066
        const char *argv[] = {
189✔
4067
                NULL, /* Leave this empty, execute_directory() will fill something in */
4068
                m->lookup_paths.generator,
189✔
4069
                m->lookup_paths.generator_early,
189✔
4070
                m->lookup_paths.generator_late,
189✔
4071
                NULL,
4072
        };
4073

4074
        BLOCK_WITH_UMASK(0022);
378✔
4075
        return execute_directories(
189✔
4076
                        "generators",
4077
                        (const char* const*) paths,
4078
                        DEFAULT_TIMEOUT_USEC,
4079
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4080
                        (char**) argv,
4081
                        ge,
4082
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4083
}
4084

4085
static int manager_run_generators(Manager *m) {
749✔
4086
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
749✔
4087
        _cleanup_strv_free_ char **paths = NULL;
749✔
4088
        int r;
749✔
4089

4090
        assert(m);
749✔
4091

4092
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
749✔
4093
                return 0;
4094

4095
        paths = generator_binary_paths(m->runtime_scope);
263✔
4096
        if (!paths)
263✔
4097
                return log_oom();
×
4098

4099
        if (!generator_path_any(paths))
263✔
4100
                return 0;
4101

4102
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
263✔
4103
        if (r < 0) {
263✔
4104
                log_error_errno(r, "Failed to create generator directories: %m");
×
4105
                goto finish;
×
4106
        }
4107

4108
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4109
         * we are the user manager, let's just execute the generators directly. We might not have the
4110
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4111
         */
4112
        if (MANAGER_IS_USER(m)) {
263✔
4113
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
189✔
4114
                goto finish;
189✔
4115
        }
4116

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

4122
        r = safe_fork("(sd-gens)", flags, NULL);
74✔
4123
        if (r == 0) {
74✔
4124
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4125
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4126
        }
4127
        if (r < 0) {
74✔
4128
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4129
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4130
                        goto finish;
×
4131
                }
4132

4133
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4134
                 * seccomp or without capability.
4135
                 *
4136
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4137
                 *
4138
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4139
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4140
                 * https://github.com/systemd/systemd/issues/28901.
4141
                 */
4142
                log_debug_errno(r,
×
4143
                                "Failed to fork off sandboxing environment for executing generators. "
4144
                                "Falling back to execute generators without sandboxing: %m");
4145
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4146
        }
4147

4148
finish:
74✔
4149
        lookup_paths_trim_generator(&m->lookup_paths);
263✔
4150
        return r;
4151
}
4152

4153
int manager_transient_environment_add(Manager *m, char **plus) {
263✔
4154
        char **a;
263✔
4155

4156
        assert(m);
263✔
4157

4158
        if (strv_isempty(plus))
263✔
4159
                return 0;
263✔
4160

4161
        a = strv_env_merge(m->transient_environment, plus);
74✔
4162
        if (!a)
74✔
4163
                return log_oom();
×
4164

4165
        sanitize_environment(a);
74✔
4166

4167
        return strv_free_and_replace(m->transient_environment, a);
74✔
4168
}
4169

4170
int manager_client_environment_modify(
187✔
4171
                Manager *m,
4172
                char **minus,
4173
                char **plus) {
4174

4175
        char **a = NULL, **b = NULL, **l;
187✔
4176

4177
        assert(m);
187✔
4178

4179
        if (strv_isempty(minus) && strv_isempty(plus))
187✔
4180
                return 0;
4181

4182
        l = m->client_environment;
187✔
4183

4184
        if (!strv_isempty(minus)) {
187✔
4185
                a = strv_env_delete(l, 1, minus);
1✔
4186
                if (!a)
1✔
4187
                        return -ENOMEM;
4188

4189
                l = a;
4190
        }
4191

4192
        if (!strv_isempty(plus)) {
187✔
4193
                b = strv_env_merge(l, plus);
186✔
4194
                if (!b) {
186✔
4195
                        strv_free(a);
×
4196
                        return -ENOMEM;
×
4197
                }
4198

4199
                l = b;
4200
        }
4201

4202
        if (m->client_environment != l)
187✔
4203
                strv_free(m->client_environment);
187✔
4204

4205
        if (a != l)
187✔
4206
                strv_free(a);
186✔
4207
        if (b != l)
187✔
4208
                strv_free(b);
1✔
4209

4210
        m->client_environment = sanitize_environment(l);
187✔
4211
        return 0;
187✔
4212
}
4213

4214
int manager_get_effective_environment(Manager *m, char ***ret) {
20,423✔
4215
        char **l;
20,423✔
4216

4217
        assert(m);
20,423✔
4218
        assert(ret);
20,423✔
4219

4220
        l = strv_env_merge(m->transient_environment, m->client_environment);
20,423✔
4221
        if (!l)
20,423✔
4222
                return -ENOMEM;
4223

4224
        *ret = l;
20,423✔
4225
        return 0;
20,423✔
4226
}
4227

4228
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
263✔
4229
        _cleanup_free_ char *label = NULL;
263✔
4230
        struct rlimit *rlimit[_RLIMIT_MAX];
263✔
4231
        int r;
263✔
4232

4233
        assert(m);
263✔
4234
        assert(defaults);
263✔
4235

4236
        if (streq_ptr(defaults->smack_process_label, "/"))
263✔
4237
                label = NULL;
4238
        else  {
4239
                const char *l = defaults->smack_process_label;
263✔
4240
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4241
                if (!l)
4242
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4243
#endif
4244
                if (l) {
263✔
4245
                        label = strdup(l);
×
4246
                        if (!label)
×
4247
                                return -ENOMEM;
4248
                } else
4249
                        label = NULL;
4250
        }
4251

4252
        r = rlimit_copy_all(rlimit, defaults->rlimit);
263✔
4253
        if (r < 0)
263✔
4254
                return r;
4255

4256
        m->defaults.std_output = defaults->std_output;
263✔
4257
        m->defaults.std_error = defaults->std_error;
263✔
4258

4259
        m->defaults.restart_usec = defaults->restart_usec;
263✔
4260
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
263✔
4261
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
263✔
4262
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
263✔
4263
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
263✔
4264
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
263✔
4265

4266
        m->defaults.restrict_suid_sgid = defaults->restrict_suid_sgid;
263✔
4267

4268
        m->defaults.start_limit = defaults->start_limit;
263✔
4269

4270
        m->defaults.memory_accounting = defaults->memory_accounting;
263✔
4271
        m->defaults.io_accounting = defaults->io_accounting;
263✔
4272
        m->defaults.tasks_accounting = defaults->tasks_accounting;
263✔
4273
        m->defaults.ip_accounting = defaults->ip_accounting;
263✔
4274

4275
        m->defaults.tasks_max = defaults->tasks_max;
263✔
4276
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
263✔
4277

4278
        m->defaults.oom_policy = defaults->oom_policy;
263✔
4279
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
263✔
4280
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
263✔
4281

4282
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
263✔
4283
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
263✔
4284

4285
        free_and_replace(m->defaults.smack_process_label, label);
263✔
4286
        rlimit_free_all(m->defaults.rlimit);
263✔
4287
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
263✔
4288

4289
        return 0;
263✔
4290
}
4291

4292
void manager_recheck_dbus(Manager *m) {
74,771✔
4293
        assert(m);
74,771✔
4294

4295
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4296
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4297
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4298
         * of the system instance, while in the user instance we can assume it's already there. */
4299

4300
        if (MANAGER_IS_RELOADING(m))
74,771✔
4301
                return; /* don't check while we are reloading… */
4302

4303
        if (manager_dbus_is_running(m, false)) {
67,994✔
4304
                (void) bus_init_api(m);
4,967✔
4305

4306
                if (MANAGER_IS_SYSTEM(m))
4,967✔
4307
                        (void) bus_init_system(m);
3,174✔
4308
        } else {
4309
                (void) bus_done_api(m);
63,027✔
4310

4311
                if (MANAGER_IS_SYSTEM(m))
63,027✔
4312
                        (void) bus_done_system(m);
9,073✔
4313
        }
4314
}
4315

4316
static bool manager_journal_is_running(Manager *m) {
13,883✔
4317
        Unit *u;
13,883✔
4318

4319
        assert(m);
13,883✔
4320

4321
        if (MANAGER_IS_TEST_RUN(m))
13,883✔
4322
                return false;
4323

4324
        /* If we are the user manager we can safely assume that the journal is up */
4325
        if (!MANAGER_IS_SYSTEM(m))
13,883✔
4326
                return true;
4327

4328
        /* Check that the socket is not only up, but in RUNNING state */
4329
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
13,219✔
4330
        if (!u)
13,219✔
4331
                return false;
4332
        if (SOCKET(u)->state != SOCKET_RUNNING)
13,219✔
4333
                return false;
4334

4335
        /* Similar, check if the daemon itself is fully up, too */
4336
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
10,068✔
4337
        if (!u)
10,068✔
4338
                return false;
4339
        if (!IN_SET(SERVICE(u)->state, SERVICE_RELOAD, SERVICE_RUNNING))
10,068✔
4340
                return false;
451✔
4341

4342
        return true;
4343
}
4344

4345
void disable_printk_ratelimit(void) {
17✔
4346
        /* Disable kernel's printk ratelimit.
4347
         *
4348
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4349
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4350
         * setting takes precedence. */
4351
        int r;
17✔
4352

4353
        r = sysctl_write("kernel/printk_devkmsg", "on");
17✔
4354
        if (r < 0)
17✔
4355
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4356
}
17✔
4357

4358
void manager_recheck_journal(Manager *m) {
74,771✔
4359

4360
        assert(m);
74,771✔
4361

4362
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4363
        if (getpid_cached() != 1)
74,771✔
4364
                return;
4365

4366
        /* Don't check this while we are reloading, things might still change */
4367
        if (MANAGER_IS_RELOADING(m))
18,407✔
4368
                return;
4369

4370
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4371
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4372
         * might trigger an activation ourselves we can't fulfill. */
4373
        log_set_prohibit_ipc(!manager_journal_is_running(m));
11,778✔
4374
        log_open();
11,778✔
4375
}
4376

4377
static ShowStatus manager_get_show_status(Manager *m) {
10,642✔
4378
        assert(m);
10,642✔
4379

4380
        if (MANAGER_IS_USER(m))
10,642✔
4381
                return _SHOW_STATUS_INVALID;
4382

4383
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
10,641✔
4384
                return m->show_status_overridden;
4385

4386
        return m->show_status;
10,641✔
4387
}
4388

4389
bool manager_get_show_status_on(Manager *m) {
10,641✔
4390
        assert(m);
10,641✔
4391

4392
        return show_status_on(manager_get_show_status(m));
10,641✔
4393
}
4394

4395
static void set_show_status_marker(bool b) {
51✔
4396
        if (b)
51✔
4397
                (void) touch("/run/systemd/show-status");
×
4398
        else
4399
                (void) unlink("/run/systemd/show-status");
51✔
4400
}
51✔
4401

4402
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
263✔
4403
        assert(m);
263✔
4404
        assert(reason);
263✔
4405
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
263✔
4406

4407
        if (MANAGER_IS_USER(m))
263✔
4408
                return;
4409

4410
        if (mode == m->show_status)
74✔
4411
                return;
4412

4413
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
51✔
4414
                bool enabled;
51✔
4415

4416
                enabled = show_status_on(mode);
51✔
4417
                log_debug("%s (%s) showing of status (%s).",
102✔
4418
                          enabled ? "Enabling" : "Disabling",
4419
                          strna(show_status_to_string(mode)),
4420
                          reason);
4421

4422
                set_show_status_marker(enabled);
51✔
4423
        }
4424

4425
        m->show_status = mode;
51✔
4426
}
4427

4428
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
×
4429
        assert(m);
×
4430
        assert(mode < _SHOW_STATUS_MAX);
×
4431

4432
        if (MANAGER_IS_USER(m))
×
4433
                return;
4434

4435
        if (mode == m->show_status_overridden)
×
4436
                return;
4437

4438
        m->show_status_overridden = mode;
×
4439

4440
        if (mode == _SHOW_STATUS_INVALID)
×
4441
                mode = m->show_status;
×
4442

4443
        log_debug("%s (%s) showing of status (%s).",
×
4444
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4445
                  strna(show_status_to_string(mode)),
4446
                  reason);
4447

4448
        set_show_status_marker(show_status_on(mode));
×
4449
}
4450

4451
const char* manager_get_confirm_spawn(Manager *m) {
2,117✔
4452
        static int last_errno = 0;
2,117✔
4453
        struct stat st;
2,117✔
4454
        int r;
2,117✔
4455

4456
        assert(m);
2,117✔
4457

4458
        /* Here's the deal: we want to test the validity of the console but don't want
4459
         * PID1 to go through the whole console process which might block. But we also
4460
         * want to warn the user only once if something is wrong with the console so we
4461
         * cannot do the sanity checks after spawning our children. So here we simply do
4462
         * really basic tests to hopefully trap common errors.
4463
         *
4464
         * If the console suddenly disappear at the time our children will really it
4465
         * then they will simply fail to acquire it and a positive answer will be
4466
         * assumed. New children will fall back to /dev/console though.
4467
         *
4468
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4469
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4470
         * reason the configured console is not ready, we fall back to the default
4471
         * console. */
4472

4473
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
2,117✔
4474
                return m->confirm_spawn;
2,117✔
4475

4476
        if (stat(m->confirm_spawn, &st) < 0) {
×
4477
                r = -errno;
×
4478
                goto fail;
×
4479
        }
4480

4481
        if (!S_ISCHR(st.st_mode)) {
×
4482
                r = -ENOTTY;
×
4483
                goto fail;
×
4484
        }
4485

4486
        last_errno = 0;
×
4487
        return m->confirm_spawn;
×
4488

4489
fail:
×
4490
        if (last_errno != r)
×
4491
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4492

4493
        return "/dev/console";
4494
}
4495

4496
void manager_set_first_boot(Manager *m, bool b) {
430✔
4497
        assert(m);
430✔
4498

4499
        if (!MANAGER_IS_SYSTEM(m))
430✔
4500
                return;
4501

4502
        if (m->first_boot != (int) b) {
51✔
4503
                if (b)
51✔
4504
                        (void) touch("/run/systemd/first-boot");
17✔
4505
                else
4506
                        (void) unlink("/run/systemd/first-boot");
34✔
4507
        }
4508

4509
        m->first_boot = b;
51✔
4510
}
4511

4512
void manager_disable_confirm_spawn(void) {
×
4513
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4514
}
×
4515

4516
static bool manager_should_show_status(Manager *m, StatusType type) {
16,580✔
4517
        assert(m);
16,580✔
4518

4519
        if (!MANAGER_IS_SYSTEM(m))
16,580✔
4520
                return false;
4521

4522
        if (m->no_console_output)
7,027✔
4523
                return false;
4524

4525
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
6,967✔
4526
                return false;
4527

4528
        /* If we cannot find out the status properly, just proceed. */
4529
        if (type < STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
6,967✔
4530
                return false;
4531

4532
        if (type >= STATUS_TYPE_NOTICE && manager_get_show_status(m) != SHOW_STATUS_NO)
6,967✔
4533
                return true;
4534

4535
        return manager_get_show_status_on(m);
6,966✔
4536
}
4537

4538
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
16,580✔
4539
        va_list ap;
16,580✔
4540

4541
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4542

4543
        if (m && !manager_should_show_status(m, type))
16,580✔
4544
                return;
16,579✔
4545

4546
        /* XXX We should totally drop the check for ephemeral here
4547
         * and thus effectively make 'Type=idle' pointless. */
4548
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
1✔
4549
                return;
4550

4551
        va_start(ap, format);
1✔
4552
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
2✔
4553
        va_end(ap);
1✔
4554
}
4555

4556
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
18,908✔
4557
        assert(m);
18,908✔
4558
        assert(path);
18,908✔
4559
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
18,908✔
4560

4561
        if (path_equal(path, "/"))
18,908✔
4562
                path = "";
852✔
4563

4564
        return hashmap_get(m->units_needing_mounts_for[t], path);
18,908✔
4565
}
4566

4567
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
157,066✔
4568
        unsigned size;
157,066✔
4569
        int r;
157,066✔
4570

4571
        assert(m);
157,066✔
4572
        assert(u->manager == m);
157,066✔
4573

4574
        size = set_size(m->failed_units);
157,066✔
4575

4576
        if (failed) {
157,066✔
4577
                r = set_ensure_put(&m->failed_units, NULL, u);
255✔
4578
                if (r < 0)
255✔
4579
                        return log_oom();
×
4580
        } else
4581
                (void) set_remove(m->failed_units, u);
156,811✔
4582

4583
        if (set_size(m->failed_units) != size)
157,066✔
4584
                bus_manager_send_change_signal(m);
510✔
4585

4586
        return 0;
4587
}
4588

4589
ManagerState manager_state(Manager *m) {
455,063✔
4590
        Unit *u;
455,063✔
4591

4592
        assert(m);
455,063✔
4593

4594
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4595
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
455,063✔
4596
        if (u && unit_active_or_pending(u))
455,063✔
4597
                return MANAGER_STOPPING;
4598

4599
        /* Did we ever finish booting? If not then we are still starting up */
4600
        if (!MANAGER_IS_FINISHED(m)) {
347,036✔
4601

4602
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
313,761✔
4603
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
313,761✔
4604
                        return MANAGER_INITIALIZING;
268,726✔
4605

4606
                return MANAGER_STARTING;
4607
        }
4608

4609
        if (MANAGER_IS_SYSTEM(m)) {
33,275✔
4610
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
UNCOV
4611
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
×
UNCOV
4612
                if (u && unit_active_or_pending(u))
×
4613
                        return MANAGER_MAINTENANCE;
4614

UNCOV
4615
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
×
UNCOV
4616
                if (u && unit_active_or_pending(u))
×
4617
                        return MANAGER_MAINTENANCE;
4618
        }
4619

4620
        /* Are there any failed units? If so, we are in degraded mode */
4621
        if (!set_isempty(m->failed_units))
33,275✔
4622
                return MANAGER_DEGRADED;
2,038✔
4623

4624
        return MANAGER_RUNNING;
4625
}
4626

4627
static void manager_unref_uid_internal(
637✔
4628
                Hashmap *uid_refs,
4629
                uid_t uid,
4630
                bool destroy_now,
4631
                int (*_clean_ipc)(uid_t uid)) {
4632

4633
        uint32_t c, n;
637✔
4634

4635
        assert(uid_is_valid(uid));
637✔
4636
        assert(_clean_ipc);
637✔
4637

4638
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4639
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4640
         *
4641
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4642
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4643
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4644
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4645
         * counter drops to 0 again. */
4646

4647
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
637✔
4648
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
637✔
4649

4650
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
637✔
4651
                return;
4652

4653
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
555✔
4654

4655
        n = c & ~DESTROY_IPC_FLAG;
555✔
4656
        assert(n > 0);
555✔
4657
        n--;
555✔
4658

4659
        if (destroy_now && n == 0) {
555✔
4660
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
109✔
4661

4662
                if (c & DESTROY_IPC_FLAG) {
109✔
4663
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
3✔
4664
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4665
                                  uid);
4666
                        (void) _clean_ipc(uid);
2✔
4667
                }
4668
        } else {
4669
                c = n | (c & DESTROY_IPC_FLAG);
446✔
4670
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
446✔
4671
        }
4672
}
4673

4674
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
318✔
4675
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
318✔
4676
}
318✔
4677

4678
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
319✔
4679
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
319✔
4680
}
319✔
4681

4682
static int manager_ref_uid_internal(
637✔
4683
                Hashmap **uid_refs,
4684
                uid_t uid,
4685
                bool clean_ipc) {
4686

4687
        uint32_t c, n;
637✔
4688
        int r;
637✔
4689

4690
        assert(uid_refs);
637✔
4691
        assert(uid_is_valid(uid));
637✔
4692

4693
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4694
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4695
         * rules. */
4696

4697
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
637✔
4698
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
637✔
4699

4700
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
637✔
4701
                return 0;
4702

4703
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
555✔
4704
        if (r < 0)
555✔
4705
                return r;
4706

4707
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
555✔
4708

4709
        n = c & ~DESTROY_IPC_FLAG;
555✔
4710
        n++;
555✔
4711

4712
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
555✔
4713
                return -EOVERFLOW;
4714

4715
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
555✔
4716

4717
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
555✔
4718
}
4719

4720
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
318✔
4721
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
318✔
4722
}
4723

4724
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
319✔
4725
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
319✔
4726
}
4727

4728
static void manager_vacuum_uid_refs_internal(
1,498✔
4729
                Hashmap *uid_refs,
4730
                int (*_clean_ipc)(uid_t uid)) {
4731

4732
        void *p, *k;
1,498✔
4733

4734
        assert(_clean_ipc);
1,498✔
4735

4736
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
3,232✔
4737
                uint32_t c, n;
236✔
4738
                uid_t uid;
236✔
4739

4740
                uid = PTR_TO_UID(k);
236✔
4741
                c = PTR_TO_UINT32(p);
236✔
4742

4743
                n = c & ~DESTROY_IPC_FLAG;
236✔
4744
                if (n > 0)
236✔
4745
                        continue;
236✔
4746

4747
                if (c & DESTROY_IPC_FLAG) {
×
4748
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4749
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4750
                                  uid);
4751
                        (void) _clean_ipc(uid);
×
4752
                }
4753

4754
                assert_se(hashmap_remove(uid_refs, k) == p);
1,734✔
4755
        }
4756
}
1,498✔
4757

4758
static void manager_vacuum_uid_refs(Manager *m) {
749✔
4759
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
749✔
4760
}
749✔
4761

4762
static void manager_vacuum_gid_refs(Manager *m) {
749✔
4763
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
749✔
4764
}
749✔
4765

4766
static void manager_vacuum(Manager *m) {
749✔
4767
        assert(m);
749✔
4768

4769
        /* Release any dynamic users no longer referenced */
4770
        dynamic_user_vacuum(m, true);
749✔
4771

4772
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4773
        manager_vacuum_uid_refs(m);
749✔
4774
        manager_vacuum_gid_refs(m);
749✔
4775

4776
        /* Release any runtimes no longer referenced */
4777
        exec_shared_runtime_vacuum(m);
749✔
4778
}
749✔
4779

4780
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
144✔
4781
        struct buffer {
144✔
4782
                uid_t uid;
4783
                gid_t gid;
4784
                char unit_name[UNIT_NAME_MAX+1];
4785
        } _packed_ buffer;
4786

4787
        Manager *m = ASSERT_PTR(userdata);
144✔
4788
        ssize_t l;
144✔
4789
        size_t n;
144✔
4790
        Unit *u;
144✔
4791

4792
        assert(source);
144✔
4793

4794
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4795
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4796
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4797
         * reference counter drops to 0. */
4798

4799
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
144✔
4800
        if (l < 0) {
144✔
4801
                if (ERRNO_IS_TRANSIENT(errno))
×
4802
                        return 0;
144✔
4803

4804
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4805
        }
4806

4807
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
144✔
4808
                log_warning("Received too short user lookup message, ignoring.");
×
4809
                return 0;
×
4810
        }
4811

4812
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
144✔
4813
                log_warning("Received too long user lookup message, ignoring.");
×
4814
                return 0;
×
4815
        }
4816

4817
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
144✔
4818
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4819
                return 0;
×
4820
        }
4821

4822
        n = (size_t) l - offsetof(struct buffer, unit_name);
144✔
4823
        if (memchr(buffer.unit_name, 0, n)) {
144✔
4824
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4825
                return 0;
×
4826
        }
4827

4828
        buffer.unit_name[n] = 0;
144✔
4829
        u = manager_get_unit(m, buffer.unit_name);
144✔
4830
        if (!u) {
144✔
4831
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4832
                return 0;
×
4833
        }
4834

4835
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
144✔
4836

4837
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
144✔
4838
        return 0;
4839
}
4840

4841
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2,093✔
4842
        Manager *m = ASSERT_PTR(userdata);
2,093✔
4843
        usec_t ts[2] = {};
2,093✔
4844
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
2,093✔
4845
        struct msghdr msghdr = {
2,093✔
4846
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
2,093✔
4847
                .msg_iovlen = 1,
4848
                .msg_control = &control,
4849
                .msg_controllen = sizeof(control),
4850
        };
4851
        ssize_t n;
2,093✔
4852

4853
        assert(source);
2,093✔
4854

4855
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2,093✔
4856
        if (ERRNO_IS_NEG_TRANSIENT(n))
2,093✔
4857
                return 0; /* Spurious wakeup, try again */
2,093✔
4858
        if (n == -ECHRNG) {
2,093✔
4859
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4860
                return 0;
×
4861
        }
4862
        if (n == -EXFULL) {
2,093✔
4863
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4864
                return 0;
×
4865
        }
4866
        if (n < 0)
2,093✔
4867
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
4868

4869
        cmsg_close_all(&msghdr);
2,093✔
4870

4871
        if (n != sizeof(ts)) {
2,093✔
4872
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
4873
                return 0;
×
4874
        }
4875

4876
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
2,093✔
4877
        if (!ucred || !pid_is_valid(ucred->pid)) {
2,093✔
4878
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
4879
                return 0;
×
4880
        }
4881

4882
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
2,093✔
4883

4884
        _cleanup_free_ Unit **units = NULL;
2,093✔
4885
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
2,093✔
4886
        if (n_units < 0) {
2,093✔
4887
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
4888
                return 0;
×
4889
        }
4890
        if (n_units == 0) {
2,093✔
4891
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
4892
                return 0;
×
4893
        }
4894

4895
        dual_timestamp dt = {
2,093✔
4896
                .realtime = ts[0],
2,093✔
4897
                .monotonic = ts[1],
2,093✔
4898
        };
4899

4900
        FOREACH_ARRAY(u, units, n_units) {
6,279✔
4901
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
4,186✔
4902
                        continue;
5✔
4903

4904
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
4,181✔
4905
        }
4906

4907
        return 0;
4908
}
4909

4910
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
4911
        Manager *m = ASSERT_PTR(userdata);
3✔
4912
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
3✔
4913
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
6✔
4914
        struct ucred *ucred = NULL;
3✔
4915
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
3✔
4916
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
3✔
4917
        struct msghdr msghdr = {
3✔
4918
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
3✔
4919
                .msg_iovlen = 1,
4920
                .msg_control = &control,
4921
                .msg_controllen = sizeof(control),
4922
        };
4923
        struct cmsghdr *cmsg;
3✔
4924
        ssize_t n;
3✔
4925
        int r;
3✔
4926

4927
        assert(source);
3✔
4928

4929
        /* Server expects:
4930
         * - Parent PID in ucreds enabled via SO_PASSCRED
4931
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
4932
         * - Child PIDFD in SCM_RIGHTS in message body
4933
         * - Child PID in message IOV
4934
         *
4935
         * SO_PASSPIDFD may not be supported by the kernel (it is supported since v6.5) so we fall back to
4936
         * using parent PID from ucreds and accept some raciness. */
4937
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
3✔
4938
        if (ERRNO_IS_NEG_TRANSIENT(n))
6✔
4939
                return 0; /* Spurious wakeup, try again */
4940
        if (n == -ECHRNG) {
3✔
4941
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4942
                return 0;
×
4943
        }
4944
        if (n == -EXFULL) {
3✔
4945
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4946
                return 0;
×
4947
        }
4948
        if (n < 0)
3✔
4949
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
4950

4951
        if (n != sizeof(child_pid)) {
3✔
4952
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
4953
                return 0;
×
4954
        }
4955

4956
        CMSG_FOREACH(cmsg, &msghdr) {
24✔
4957
                if (cmsg->cmsg_level != SOL_SOCKET)
9✔
4958
                        continue;
×
4959

4960
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
9✔
4961
                        assert(!ucred);
3✔
4962
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
3✔
4963
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
6✔
4964
                        assert(parent_pidfd < 0);
3✔
4965
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4966
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
3✔
4967
                        assert(child_pidfd < 0);
3✔
4968
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4969
                }
4970
        }
4971

4972
        /* Verify and set parent pidref. */
4973
        if (!ucred || !pid_is_valid(ucred->pid)) {
3✔
4974
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
4975
                return 0;
×
4976
        }
4977

4978
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
4979
        if (parent_pidfd >= 0)
3✔
4980
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
3✔
4981
        else
4982
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
4983
        if (r < 0) {
3✔
4984
                if (r == -ESRCH)
×
4985
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
4986
                else
4987
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
4988
                return 0;
×
4989
        }
4990

4991
        if (parent_pidref.pid != ucred->pid) {
3✔
4992
                assert(parent_pidref.fd >= 0);
×
4993
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
4994
                            parent_pidref.pid, ucred->pid);
4995
                return 0;
×
4996
        }
4997

4998
        /* Verify and set child pidref. */
4999
        if (!pid_is_valid(child_pid)) {
3✔
5000
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
5001
                return 0;
×
5002
        }
5003

5004
        /* Need to handle kernels without PIDFD support. */
5005
        if (child_pidfd >= 0)
3✔
5006
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
3✔
5007
        else
5008
                r = pidref_set_pid(&child_pidref, child_pid);
×
5009
        if (r < 0) {
3✔
5010
                if (r == -ESRCH)
×
5011
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5012
                else
5013
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5014
                return 0;
×
5015
        }
5016

5017
        if (child_pidref.pid != child_pid) {
3✔
5018
                assert(child_pidref.fd >= 0);
×
5019
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5020
                            child_pidref.pid, child_pid);
5021
                return 0;
×
5022
        }
5023

5024
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
3✔
5025

5026
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5027
         * Then fall back to finding cgroup of the child process. */
5028
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
3✔
5029
        if (!u)
3✔
5030
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5031
        if (!u) {
×
5032
                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);
×
5033
                return 0;
×
5034
        }
5035

5036
        if (!UNIT_VTABLE(u)->notify_pidref) {
3✔
5037
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5038
                return 0;
×
5039
        }
5040

5041
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
3✔
5042

5043
        return 0;
5044
}
5045

5046
void manager_ref_console(Manager *m) {
73✔
5047
        assert(m);
73✔
5048

5049
        m->n_on_console++;
73✔
5050
}
73✔
5051

5052
void manager_unref_console(Manager *m) {
73✔
5053

5054
        assert(m->n_on_console > 0);
73✔
5055
        m->n_on_console--;
73✔
5056

5057
        if (m->n_on_console == 0)
73✔
5058
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
59✔
5059
}
73✔
5060

5061
void manager_override_log_level(Manager *m, int level) {
4✔
5062
        _cleanup_free_ char *s = NULL;
8✔
5063
        assert(m);
4✔
5064

5065
        if (!m->log_level_overridden) {
4✔
5066
                m->original_log_level = log_get_max_level();
1✔
5067
                m->log_level_overridden = true;
1✔
5068
        }
5069

5070
        (void) log_level_to_string_alloc(level, &s);
4✔
5071
        log_info("Setting log level to %s.", strna(s));
4✔
5072

5073
        log_set_max_level(level);
4✔
5074
}
4✔
5075

5076
void manager_restore_original_log_level(Manager *m) {
×
5077
        _cleanup_free_ char *s = NULL;
×
5078
        assert(m);
×
5079

5080
        if (!m->log_level_overridden)
×
5081
                return;
×
5082

5083
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5084
        log_info("Restoring log level to original (%s).", strna(s));
×
5085

5086
        log_set_max_level(m->original_log_level);
×
5087
        m->log_level_overridden = false;
×
5088
}
5089

5090
void manager_override_log_target(Manager *m, LogTarget target) {
4✔
5091
        assert(m);
4✔
5092

5093
        if (!m->log_target_overridden) {
4✔
5094
                m->original_log_target = log_get_target();
1✔
5095
                m->log_target_overridden = true;
1✔
5096
        }
5097

5098
        log_info("Setting log target to %s.", log_target_to_string(target));
4✔
5099
        log_set_target(target);
4✔
5100
}
4✔
5101

5102
void manager_restore_original_log_target(Manager *m) {
×
5103
        assert(m);
×
5104

5105
        if (!m->log_target_overridden)
×
5106
                return;
5107

5108
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5109

5110
        log_set_target(m->original_log_target);
×
5111
        m->log_target_overridden = false;
×
5112
}
5113

5114
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
3,372✔
5115
        if (in_initrd() &&
3,372✔
5116
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
66✔
5117
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5118
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
66✔
5119
        return s;
5120
}
5121

5122
int manager_allocate_idle_pipe(Manager *m) {
18,677✔
5123
        int r;
18,677✔
5124

5125
        assert(m);
18,677✔
5126

5127
        if (m->idle_pipe[0] >= 0) {
18,677✔
5128
                assert(m->idle_pipe[1] >= 0);
15,774✔
5129
                assert(m->idle_pipe[2] >= 0);
15,774✔
5130
                assert(m->idle_pipe[3] >= 0);
15,774✔
5131
                return 0;
5132
        }
5133

5134
        assert(m->idle_pipe[1] < 0);
2,903✔
5135
        assert(m->idle_pipe[2] < 0);
2,903✔
5136
        assert(m->idle_pipe[3] < 0);
2,903✔
5137

5138
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
2,903✔
5139
        if (r < 0)
×
5140
                return r;
5141

5142
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
2,903✔
5143
        if (r < 0) {
×
5144
                safe_close_pair(m->idle_pipe + 0);
×
5145
                return r;
×
5146
        }
5147

5148
        return 1;
5149
}
5150

5151
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,175✔
5152
        assert(defaults);
1,175✔
5153
        assert(scope >= 0);
1,175✔
5154
        assert(scope < _RUNTIME_SCOPE_MAX);
1,175✔
5155

5156
        *defaults = (UnitDefaults) {
2,350✔
5157
                .std_output = EXEC_OUTPUT_JOURNAL,
5158
                .std_error = EXEC_OUTPUT_INHERIT,
5159
                .restart_usec = DEFAULT_RESTART_USEC,
5160
                .timeout_start_usec = manager_default_timeout(scope),
1,175✔
5161
                .timeout_stop_usec = manager_default_timeout(scope),
1,175✔
5162
                .timeout_abort_usec = manager_default_timeout(scope),
1,175✔
5163
                .timeout_abort_set = false,
5164
                .device_timeout_usec = manager_default_timeout(scope),
1,175✔
5165
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5166

5167
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5168
                .io_accounting = false,
5169
                .tasks_accounting = true,
5170
                .ip_accounting = false,
5171

5172
                .tasks_max = DEFAULT_TASKS_MAX,
5173
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5174

5175
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5176
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5177

5178
                .oom_policy = OOM_STOP,
5179
                .oom_score_adjust_set = false,
5180
        };
5181
}
1,175✔
5182

5183
void unit_defaults_done(UnitDefaults *defaults) {
1,175✔
5184
        assert(defaults);
1,175✔
5185

5186
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,175✔
5187
        rlimit_free_all(defaults->rlimit);
1,175✔
5188
}
1,175✔
5189

5190
LogTarget manager_get_executor_log_target(Manager *m) {
2,116✔
5191
        assert(m);
2,116✔
5192

5193
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5194
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
2,116✔
5195
                return LOG_TARGET_KMSG;
5196

5197
        return log_get_target();
1,700✔
5198
}
5199

5200
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5201
        [MANAGER_INITIALIZING] = "initializing",
5202
        [MANAGER_STARTING]     = "starting",
5203
        [MANAGER_RUNNING]      = "running",
5204
        [MANAGER_DEGRADED]     = "degraded",
5205
        [MANAGER_MAINTENANCE]  = "maintenance",
5206
        [MANAGER_STOPPING]     = "stopping",
5207
};
5208

5209
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
75✔
5210

5211
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5212
        [MANAGER_OK]          = "ok",
5213
        [MANAGER_EXIT]        = "exit",
5214
        [MANAGER_RELOAD]      = "reload",
5215
        [MANAGER_REEXECUTE]   = "reexecute",
5216
        [MANAGER_REBOOT]      = "reboot",
5217
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5218
        [MANAGER_POWEROFF]    = "poweroff",
5219
        [MANAGER_HALT]        = "halt",
5220
        [MANAGER_KEXEC]       = "kexec",
5221
        [MANAGER_SWITCH_ROOT] = "switch-root",
5222
};
5223

5224
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
128✔
5225

5226
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5227
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5228
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5229
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5230
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5231
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5232
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5233
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5234
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5235
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5236
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5237
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5238
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5239
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5240
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5241
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5242
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5243
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5244
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5245
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5246
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5247
};
5248

5249
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
4,423✔
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