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

systemd / systemd / 20684862027

03 Jan 2026 10:26PM UTC coverage: 72.702% (+0.03%) from 72.677%
20684862027

push

github

web-flow
core/dynamic-user: two trivial modernizations (#40264)

2 of 4 new or added lines in 1 file covered. (50.0%)

215 existing lines in 37 files now uncovered.

310139 of 426587 relevant lines covered (72.7%)

1143601.25 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

136
        if (MANAGER_IS_USER(m))
5,584✔
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))
4,819✔
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;
4,819✔
145

146
        return usec_add(now(CLOCK_MONOTONIC), timeout);
5,584✔
147
}
148

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

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

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

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

162
        assert(m);
3,569✔
163

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

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

173
        next = manager_watch_jobs_next_time(m);
778✔
174
        r = sd_event_add_time(
778✔
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)
778✔
181
                return;
182

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

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

189
        if (enable) {
196✔
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)
196✔
194
                        manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
×
195
        }
196
}
196✔
197

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

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

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

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

212
        HASHMAP_FOREACH(j, m->jobs)
×
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. */
218
        assert(counter == print_nr + 1);
×
219
        assert(j);
×
220

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

226
        m->jobs_in_progress_iteration++;
×
227

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

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(). */
239
        const char *ident = unit_status_string(j->unit, NULL);
×
240

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

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 {
254
                const char *status_text = unit_status_text(j->unit);
×
255

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

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

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

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

282
                return -errno;
×
283
        }
284

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

UNCOV
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,
50✔
297
                                            int fd, uint32_t revents, void *userdata) {
298
        Manager *m = ASSERT_PTR(userdata);
50✔
299

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

302
        m->have_ask_password = have_ask_password();
50✔
303
        if (m->have_ask_password < 0)
50✔
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;
50✔
308
}
309

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

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

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

320
        assert(m);
7,954✔
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))
7,954✔
325
                return 0;
326

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

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

337
                _cleanup_(sd_event_source_disable_unrefp) sd_event_source *event_source = NULL;
48✔
338
                r = sd_event_add_io(
48✔
339
                                m->event,
340
                                &event_source,
341
                                inotify_fd,
342
                                EPOLLIN,
343
                                manager_dispatch_ask_password_fd,
344
                                m);
345
                if (r < 0)
48✔
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);
48✔
349
                if (r < 0)
48✔
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);
48✔
352

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

355
                m->ask_password_event_source = TAKE_PTR(event_source);
48✔
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);
48✔
359
        }
360

361
        return m->have_ask_password;
7,954✔
362
}
363

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

367
        assert(m);
762✔
368

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

372
        if (m->idle_pipe[2] < 0)
41✔
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);
41✔
376
        if (r < 0)
41✔
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");
41✔
380

381
        return 0;
41✔
382
}
383

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

387
        m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
3,701✔
388

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

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

396
        assert(m);
266✔
397

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

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

403
        r = event_add_time_change(m->event, &m->time_change_event_source, manager_dispatch_time_change_fd, m);
254✔
404
        if (r < 0)
254✔
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);
254✔
409
        if (r < 0)
254✔
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.");
254✔
413

414
        return 0;
415
}
416

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

421
        assert(m);
312✔
422

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

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

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

438
        return changed;
312✔
439
}
440

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

445
        assert(m);
287✔
446

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

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

461
        r = sd_event_add_inotify(m->event, &new_event, etc_localtime(),
275✔
462
                                 IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
463
        if (r == -ENOENT) {
275✔
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;
48✔
467

468
                int dir_r = path_extract_directory(etc_localtime(), &localtime_dir);
48✔
469
                if (dir_r < 0)
48✔
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);
48✔
473

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

488
        return 0;
275✔
489
}
490

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

494
        assert(m);
255✔
495

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

514
        return 0;
515
}
516

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

525
        assert(m);
255✔
526

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

730
        assert(m);
739✔
731

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

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

742
        return 0;
743
}
744

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

752
static int manager_setup_run_queue(Manager *m) {
739✔
753
        int r;
739✔
754

755
        assert(m);
739✔
756
        assert(!m->run_queue_event_source);
739✔
757

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

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

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

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

772
        return 0;
739✔
773
}
774

775
static int manager_setup_sigchld_event_source(Manager *m) {
255✔
776
        int r;
255✔
777

778
        assert(m);
255✔
779
        assert(!m->sigchld_event_source);
255✔
780

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

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

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

793
        (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
255✔
794

795
        return 0;
255✔
796
}
797

798
int manager_setup_memory_pressure_event_source(Manager *m) {
529✔
799
        int r;
529✔
800

801
        assert(m);
529✔
802

803
        m->memory_pressure_event_source = sd_event_source_disable_unref(m->memory_pressure_event_source);
529✔
804

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

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

820
        return 0;
529✔
821
}
822

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

827
        assert(m);
739✔
828

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

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

849
        return 0;
850
}
851

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

855
        m->switching_root = MANAGER_IS_SYSTEM(m) && switching_root;
991✔
856
}
991✔
857

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

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

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

867
static int compare_job_priority(const void *a, const void *b) {
401,166✔
868
        const Job *x = a, *y = b;
401,166✔
869

870
        return unit_compare_priority(x->unit, y->unit);
401,166✔
871
}
872

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

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

881
        assert(IN_SET(runtime_scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
739✔
882
        assert(ret);
739✔
883

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

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

893
                .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
894

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

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

903
                .show_status_overridden = _SHOW_STATUS_INVALID,
904

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

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

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

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

925
                .executor_fd = -EBADF,
926
        };
927

928
        unit_defaults_init(&m->defaults, runtime_scope);
739✔
929

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

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

940
        r = manager_default_environment(m);
739✔
941
        if (r < 0)
739✔
942
                return r;
943

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

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

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

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

960
        r = manager_setup_prefix(m);
739✔
961
        if (r < 0)
739✔
962
                return r;
963

964
        r = manager_find_credentials_dirs(m);
739✔
965
        if (r < 0)
739✔
966
                return r;
967

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

972
        r = manager_setup_run_queue(m);
739✔
973
        if (r < 0)
739✔
974
                return r;
975

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

985
                r = manager_setup_cgroup(m);
255✔
986
                if (r < 0)
255✔
987
                        return r;
988

989
                r = manager_setup_time_change(m);
255✔
990
                if (r < 0)
255✔
991
                        return r;
992

993
                r = manager_read_timezone_stat(m);
255✔
994
                if (r < 0)
255✔
995
                        return r;
996

997
                (void) manager_setup_timezone_change(m);
255✔
998

999
                r = manager_setup_sigchld_event_source(m);
255✔
1000
                if (r < 0)
255✔
1001
                        return r;
1002

1003
                r = manager_setup_memory_pressure_event_source(m);
255✔
1004
                if (r < 0)
255✔
1005
                        return r;
1006

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

1016
        if (test_run_flags == 0) {
739✔
1017
                if (MANAGER_IS_SYSTEM(m))
243✔
1018
                        r = mkdir_label("/run/systemd/units", 0755);
53✔
1019
                else {
1020
                        _cleanup_free_ char *units_path = NULL;
190✔
1021
                        r = xdg_user_runtime_dir("/systemd/units", &units_path);
190✔
1022
                        if (r < 0)
190✔
1023
                                return r;
×
1024

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

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

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

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

1042
        *ret = TAKE_PTR(m);
739✔
1043

1044
        return 0;
739✔
1045
}
1046

1047
static int manager_setup_notify(Manager *m) {
768✔
1048
        int r;
768✔
1049

1050
        if (MANAGER_IS_TEST_RUN(m))
768✔
1051
                return 0;
1052

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

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

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

1066
                (void) fd_increase_rxbuf(fd, MANAGER_SOCKET_RCVBUF_SIZE);
223✔
1067

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

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

1078
                (void) sockaddr_un_unlink(&sa.un);
223✔
1079

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

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

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

1093
                m->notify_fd = TAKE_FD(fd);
223✔
1094

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

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

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

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

1112
        return 0;
1113
}
1114

1115
static int manager_setup_user_lookup_fd(Manager *m) {
768✔
1116
        int r;
768✔
1117

1118
        assert(m);
768✔
1119

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

1139
        if (m->user_lookup_fds[0] < 0) {
768✔
1140

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

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

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

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

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

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

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

1169
        return 0;
1170
}
1171

1172
static int manager_setup_handoff_timestamp_fd(Manager *m) {
768✔
1173
        int r;
768✔
1174

1175
        assert(m);
768✔
1176

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

1180
        if (m->handoff_timestamp_fds[0] < 0) {
768✔
1181
                m->handoff_timestamp_event_source = sd_event_source_disable_unref(m->handoff_timestamp_event_source);
717✔
1182
                safe_close_pair(m->handoff_timestamp_fds);
717✔
1183

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

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

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

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

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

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

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

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

1216
        return 0;
1217
}
1218

1219
static int manager_setup_pidref_transport_fd(Manager *m) {
768✔
1220
        int r;
768✔
1221

1222
        assert(m);
768✔
1223

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

1227
        if (m->pidref_transport_fds[0] < 0) {
768✔
1228
                m->pidref_event_source = sd_event_source_disable_unref(m->pidref_event_source);
737✔
1229
                safe_close_pair(m->pidref_transport_fds);
737✔
1230

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

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

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

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

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

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

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

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

1265
        return 0;
1266
}
1267

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

1272
        assert(m);
219,848✔
1273

1274
        while ((u = m->cleanup_queue)) {
258,913✔
1275
                assert(u->in_cleanup_queue);
39,065✔
1276

1277
                unit_free(u);
39,065✔
1278
                n++;
39,065✔
1279
        }
1280

1281
        return n;
219,848✔
1282
}
1283

1284
static unsigned manager_dispatch_release_resources_queue(Manager *m) {
204,663✔
1285
        unsigned n = 0;
204,663✔
1286
        Unit *u;
204,663✔
1287

1288
        assert(m);
204,663✔
1289

1290
        while ((u = LIST_POP(release_resources_queue, m->release_resources_queue))) {
205,975✔
1291
                assert(u->in_release_resources_queue);
1,312✔
1292
                u->in_release_resources_queue = false;
1,312✔
1293

1294
                n++;
1,312✔
1295

1296
                unit_release_resources(u);
1,312✔
1297
        }
1298

1299
        return n;
204,663✔
1300
}
1301

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

1310
static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
76,154✔
1311
        Unit *other;
76,154✔
1312

1313
        u->gc_marker = gc_marker + GC_OFFSET_GOOD;
76,154✔
1314

1315
        /* Recursively mark referenced units as GOOD as well */
1316
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
556,456✔
1317
                if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
313,950✔
1318
                        unit_gc_mark_good(other, gc_marker);
1,023✔
1319
}
76,154✔
1320

1321
static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
130,827✔
1322
        Unit *other;
130,827✔
1323
        bool is_bad;
130,827✔
1324

1325
        assert(u);
130,827✔
1326

1327
        if (IN_SET(u->gc_marker - gc_marker,
130,827✔
1328
                   GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
1329
                return;
55,696✔
1330

1331
        if (u->in_cleanup_queue)
115,218✔
1332
                goto bad;
×
1333

1334
        if (!unit_may_gc(u))
115,218✔
1335
                goto good;
53,135✔
1336

1337
        u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
62,083✔
1338

1339
        is_bad = true;
62,083✔
1340

1341
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
130,043✔
1342
                unit_gc_sweep(other, gc_marker);
25,582✔
1343

1344
                if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
25,582✔
1345
                        goto good;
21,996✔
1346

1347
                if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
3,586✔
1348
                        is_bad = false;
2,933✔
1349
        }
1350

1351
        LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
40,368✔
1352
                unit_gc_sweep(ref->source, gc_marker);
281✔
1353

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

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

1361
        if (is_bad)
40,087✔
1362
                goto bad;
38,692✔
1363

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

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

1377
good:
75,131✔
1378
        unit_gc_mark_good(u, gc_marker);
75,131✔
1379
}
1380

1381
static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
236,805✔
1382
        unsigned n = 0, gc_marker;
236,805✔
1383

1384
        assert(m);
236,805✔
1385

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

1388
        m->gc_marker += _GC_OFFSET_MAX;
236,805✔
1389
        if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
236,805✔
1390
                m->gc_marker = 1;
×
1391

1392
        gc_marker = m->gc_marker;
236,805✔
1393

1394
        Unit *u;
236,805✔
1395
        while ((u = m->gc_unit_queue)) {
341,769✔
1396
                assert(u->in_gc_queue);
104,964✔
1397

1398
                unit_gc_sweep(u, gc_marker);
104,964✔
1399

1400
                LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
104,964✔
1401
                u->in_gc_queue = false;
104,964✔
1402

1403
                n++;
104,964✔
1404

1405
                if (IN_SET(u->gc_marker - gc_marker,
104,964✔
1406
                           GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
1407
                        if (u->id)
39,064✔
1408
                                log_unit_debug(u, "Collecting.");
39,064✔
1409
                        u->gc_marker = gc_marker + GC_OFFSET_BAD;
39,064✔
1410
                        unit_add_to_cleanup_queue(u);
39,064✔
1411
                }
1412
        }
1413

1414
        return n;
236,805✔
1415
}
1416

1417
static unsigned manager_dispatch_gc_job_queue(Manager *m) {
236,815✔
1418
        unsigned n = 0;
236,815✔
1419
        Job *j;
236,815✔
1420

1421
        assert(m);
236,815✔
1422

1423
        while ((j = LIST_POP(gc_queue, m->gc_job_queue))) {
236,825✔
1424
                assert(j->in_gc_queue);
10✔
1425
                j->in_gc_queue = false;
10✔
1426

1427
                n++;
10✔
1428

1429
                if (!job_may_gc(j))
10✔
1430
                        continue;
10✔
1431

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

1436
        return n;
236,815✔
1437
}
1438

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

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

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

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

1452
        return 0;
×
1453
}
1454

1455
static int manager_ratelimit_check_and_queue(Unit *u) {
15✔
1456
        int r;
15✔
1457

1458
        assert(u);
15✔
1459

1460
        if (ratelimit_below(&u->auto_start_stop_ratelimit))
15✔
1461
                return 1;
1462

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

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

1478
        return 0;
1479
}
1480

1481
static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
204,916✔
1482
        unsigned n = 0;
204,916✔
1483
        Unit *u;
204,916✔
1484
        int r;
204,916✔
1485

1486
        assert(m);
204,916✔
1487

1488
        while ((u = LIST_POP(stop_when_unneeded_queue, m->stop_when_unneeded_queue))) {
205,260✔
1489
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
344✔
1490

1491
                assert(u->in_stop_when_unneeded_queue);
344✔
1492
                u->in_stop_when_unneeded_queue = false;
344✔
1493

1494
                n++;
344✔
1495

1496
                if (!unit_is_unneeded(u))
344✔
1497
                        continue;
332✔
1498

1499
                log_unit_debug(u, "Unit is not needed anymore.");
12✔
1500

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

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

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

1518
        return n;
204,916✔
1519
}
1520

1521
static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
205,067✔
1522
        unsigned n = 0;
205,067✔
1523
        Unit *u;
205,067✔
1524
        int r;
205,067✔
1525

1526
        assert(m);
205,067✔
1527

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

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

1535
                n++;
×
1536

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

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

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

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

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

1559
        return n;
205,067✔
1560
}
1561

1562
static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
205,067✔
1563
        unsigned n = 0;
205,067✔
1564
        Unit *u;
205,067✔
1565
        int r;
205,067✔
1566

1567
        assert(m);
205,067✔
1568

1569
        while ((u = LIST_POP(stop_when_bound_queue, m->stop_when_bound_queue))) {
205,328✔
1570
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
261✔
1571
                Unit *culprit = NULL;
261✔
1572

1573
                assert(u->in_stop_when_bound_queue);
261✔
1574
                u->in_stop_when_bound_queue = false;
261✔
1575

1576
                n++;
261✔
1577

1578
                if (!unit_is_bound_by_inactive(u, &culprit))
261✔
1579
                        continue;
258✔
1580

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

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

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

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

1600
        return n;
205,067✔
1601
}
1602

1603
static unsigned manager_dispatch_stop_notify_queue(Manager *m) {
203,514✔
1604
        unsigned n = 0;
203,514✔
1605

1606
        assert(m);
203,514✔
1607

1608
        if (m->may_dispatch_stop_notify_queue < 0)
203,514✔
1609
                m->may_dispatch_stop_notify_queue = hashmap_isempty(m->jobs);
5,851✔
1610

1611
        if (!m->may_dispatch_stop_notify_queue)
203,514✔
1612
                return 0;
1613

1614
        m->may_dispatch_stop_notify_queue = false;
10,449✔
1615

1616
        LIST_FOREACH(stop_notify_queue, u, m->stop_notify_queue) {
10,455✔
1617
                assert(u->in_stop_notify_queue);
6✔
1618

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

1626
        return n;
1627
}
1628

1629
static void manager_clear_jobs_and_units(Manager *m) {
770✔
1630
        Unit *u;
770✔
1631

1632
        assert(m);
770✔
1633

1634
        while ((u = hashmap_first(m->units)))
51,440✔
1635
                unit_free(u);
50,670✔
1636

1637
        manager_dispatch_cleanup_queue(m);
770✔
1638

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

1655
        assert(hashmap_isempty(m->jobs));
770✔
1656
        assert(hashmap_isempty(m->units));
770✔
1657
        assert(hashmap_isempty(m->units_by_invocation_id));
770✔
1658

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

1664
        m->transactions_with_cycle = set_free(m->transactions_with_cycle);
770✔
1665
}
770✔
1666

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

1671
        manager_clear_jobs_and_units(m);
739✔
1672

1673
        for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
8,868✔
1674
                if (unit_vtable[c]->shutdown)
8,129✔
1675
                        unit_vtable[c]->shutdown(m);
2,956✔
1676

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

1680
        lookup_paths_flush_generator(&m->lookup_paths);
739✔
1681

1682
        bus_done(m);
739✔
1683
        manager_varlink_done(m);
739✔
1684

1685
        exec_shared_runtime_vacuum(m);
739✔
1686
        hashmap_free(m->exec_shared_runtime_by_id);
739✔
1687

1688
        dynamic_user_vacuum(m, false);
739✔
1689
        hashmap_free(m->dynamic_users);
739✔
1690

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

1698
        prioq_free(m->run_queue);
739✔
1699

1700
        set_free(m->startup_units);
739✔
1701
        set_free(m->failed_units);
739✔
1702

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

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

1721
        manager_close_ask_password(m);
739✔
1722

1723
        manager_close_idle_pipe(m);
739✔
1724

1725
        sd_event_unref(m->event);
739✔
1726

1727
        free(m->notify_socket);
739✔
1728

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

1733
        hashmap_free(m->cgroup_unit);
739✔
1734
        manager_free_unit_name_maps(m);
739✔
1735

1736
        free(m->switch_root);
739✔
1737
        free(m->switch_root_init);
739✔
1738

1739
        sd_bus_track_unref(m->subscribed);
739✔
1740
        strv_free(m->subscribed_as_strv);
739✔
1741

1742
        unit_defaults_done(&m->defaults);
739✔
1743

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

1749
        hashmap_free(m->uid_refs);
739✔
1750
        hashmap_free(m->gid_refs);
739✔
1751

1752
        FOREACH_ARRAY(i, m->prefix, _EXEC_DIRECTORY_TYPE_MAX)
4,434✔
1753
                free(*i);
3,695✔
1754

1755
        free(m->received_credentials_directory);
739✔
1756
        free(m->received_encrypted_credentials_directory);
739✔
1757

1758
        free(m->watchdog_pretimeout_governor);
739✔
1759
        free(m->watchdog_pretimeout_governor_overridden);
739✔
1760

1761
        sd_netlink_unref(m->nfnl);
739✔
1762

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

1767
        safe_close(m->executor_fd);
739✔
1768
        free(m->executor_path);
739✔
1769

1770
        return mfree(m);
739✔
1771
}
1772

1773
static void manager_enumerate_perpetual(Manager *m) {
768✔
1774
        assert(m);
768✔
1775

1776
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
768✔
1777
                return;
1778

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

1786
                if (unit_vtable[c]->enumerate_perpetual)
2,660✔
1787
                        unit_vtable[c]->enumerate_perpetual(m);
858✔
1788
        }
1789
}
1790

1791
static void manager_enumerate(Manager *m) {
768✔
1792
        assert(m);
768✔
1793

1794
        if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
768✔
1795
                return;
1796

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

1804
                if (unit_vtable[c]->enumerate)
2,660✔
1805
                        unit_vtable[c]->enumerate(m);
534✔
1806
        }
1807

1808
        manager_dispatch_load_queue(m);
286✔
1809
}
1810

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

1816
        assert(m);
768✔
1817

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

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

1823
                /* ignore aliases */
1824
                if (u->id != k)
43,004✔
1825
                        continue;
747✔
1826

1827
                r = unit_coldplug(u);
42,257✔
1828
                if (r < 0)
42,257✔
1829
                        log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
43,772✔
1830
        }
1831
}
768✔
1832

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

1837
        assert(m);
768✔
1838

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

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

1844
                /* ignore aliases */
1845
                if (u->id != k)
43,004✔
1846
                        continue;
747✔
1847

1848
                unit_catchup(u);
42,257✔
1849
        }
1850
}
768✔
1851

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

1855
        assert(m);
737✔
1856

1857
        HASHMAP_FOREACH(u, m->units) {
8,165✔
1858

1859
                if (fdset_isempty(fds))
7,663✔
1860
                        break;
1861

1862
                if (!UNIT_VTABLE(u)->distribute_fds)
7,428✔
1863
                        continue;
6,616✔
1864

1865
                UNIT_VTABLE(u)->distribute_fds(u, fds);
812✔
1866
        }
1867
}
737✔
1868

1869
static bool manager_dbus_is_running(Manager *m, bool deserialized) {
73,579✔
1870
        Unit *u;
73,579✔
1871

1872
        assert(m);
73,579✔
1873

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

1878
        if (MANAGER_IS_TEST_RUN(m))
73,579✔
1879
                return false;
1880

1881
        u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
72,708✔
1882
        if (!u)
72,708✔
1883
                return false;
1884
        if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
121,546✔
1885
                return false;
1886

1887
        u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
7,015✔
1888
        if (!u)
7,015✔
1889
                return false;
1890
        if (!IN_SET((deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state),
14,030✔
1891
                    SERVICE_RUNNING,
1892
                    SERVICE_MOUNTING,
1893
                    SERVICE_RELOAD,
1894
                    SERVICE_RELOAD_NOTIFY,
1895
                    SERVICE_REFRESH_EXTENSIONS,
1896
                    SERVICE_RELOAD_SIGNAL))
1897
                return false;
310✔
1898

1899
        return true;
1900
}
1901

1902
static void manager_setup_bus(Manager *m) {
737✔
1903
        assert(m);
737✔
1904

1905
        if (MANAGER_IS_TEST_RUN(m))
737✔
1906
                return;
1907

1908
        /* Let's set up our private bus connection now, unconditionally */
1909
        (void) bus_init_private(m);
243✔
1910

1911
        /* If we are in --user mode also connect to the system bus now */
1912
        if (MANAGER_IS_USER(m))
243✔
1913
                (void) bus_init_system(m);
190✔
1914

1915
        /* Let's connect to the bus now, but only if the unit is supposed to be up */
1916
        if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
243✔
1917
                (void) bus_init_api(m);
17✔
1918

1919
                if (MANAGER_IS_SYSTEM(m))
17✔
1920
                        (void) bus_init_system(m);
16✔
1921
        }
1922
}
1923

1924
static void manager_preset_all(Manager *m) {
737✔
1925
        int r;
737✔
1926

1927
        assert(m);
737✔
1928

1929
        if (m->first_boot <= 0)
737✔
1930
                return;
718✔
1931

1932
        if (!MANAGER_IS_SYSTEM(m))
19✔
1933
                return;
1934

1935
        if (MANAGER_IS_TEST_RUN(m))
19✔
1936
                return;
1937

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

1944
        CLEANUP_ARRAY(changes, n_changes, install_changes_free);
×
1945

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

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

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

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

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

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

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

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

1984
void manager_reloading_stopp(Manager **m) {
889✔
1985
        if (*m) {
889✔
1986
                assert((*m)->n_reloading > 0);
141✔
1987
                (*m)->n_reloading--;
141✔
1988
        }
1989
}
889✔
1990

1991
static int manager_make_runtime_dir(Manager *m) {
737✔
1992
        int r;
737✔
1993

1994
        assert(m);
737✔
1995

1996
        _cleanup_free_ char *d = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd");
1,474✔
1997
        if (!d)
737✔
1998
                return log_oom();
×
1999

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

2004
        return 0;
2005
}
2006

2007
int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
737✔
2008
        int r;
737✔
2009

2010
        assert(m);
737✔
2011

2012
        r = manager_make_runtime_dir(m);
737✔
2013
        if (r < 0)
737✔
2014
                return r;
2015

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

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

2032
        manager_preset_all(m);
737✔
2033

2034
        lookup_paths_log(&m->lookup_paths);
737✔
2035

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

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

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

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

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

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

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

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

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

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

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

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

2102
                /* Connect to the bus if we are good for it */
2103
                manager_setup_bus(m);
737✔
2104

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

2109
                /* Third, fire things up! */
2110
                manager_coldplug(m);
737✔
2111

2112
                /* Clean up runtime objects */
2113
                manager_vacuum(m);
737✔
2114

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

2121
        manager_ready(m);
737✔
2122

2123
        manager_set_switching_root(m, false);
737✔
2124

2125
        return 0;
737✔
2126
}
2127

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

2138
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
1,816✔
2139
        int r;
1,816✔
2140

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

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

2150
        if (mode == JOB_ISOLATE && !unit->allow_isolate)
1,816✔
2151
                return sd_bus_error_set(reterr_error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
26✔
2152

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

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

2159
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
1,790✔
2160
        if (!tr)
1,790✔
2161
                return -ENOMEM;
2162

2163
        LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
3,580✔
2164

2165
        log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1,790✔
2166

2167
        type = job_type_collapse(type, unit);
1,790✔
2168

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

2183
        if (mode == JOB_ISOLATE) {
1,777✔
2184
                r = transaction_add_isolate_jobs(tr, m);
211✔
2185
                if (r < 0)
211✔
2186
                        return r;
2187
        }
2188

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

2195
        r = transaction_activate(tr, m, mode, affected_jobs, reterr_error);
1,777✔
2196
        if (r < 0)
1,777✔
2197
                return r;
2198

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

2203
        if (ret)
1,762✔
2204
                *ret = tr->anchor_job;
1,056✔
2205

2206
        tr = transaction_free(tr);
1,762✔
2207
        return 0;
1,762✔
2208
}
2209

2210
int manager_add_job(
984✔
2211
        Manager *m,
2212
        JobType type,
2213
        Unit *unit,
2214
        JobMode mode,
2215
        sd_bus_error *reterr_error,
2216
        Job **ret) {
2217

2218
        return manager_add_job_full(m, type, unit, mode, 0, NULL, reterr_error, ret);
984✔
2219
}
2220

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

2225
        assert(m);
206✔
2226
        assert(type < _JOB_TYPE_MAX);
206✔
2227
        assert(name);
206✔
2228
        assert(mode < _JOB_MODE_MAX);
206✔
2229

2230
        r = manager_load_unit(m, name, NULL, NULL, &unit);
206✔
2231
        if (r < 0)
206✔
2232
                return r;
206✔
2233
        assert(unit);
206✔
2234

2235
        return manager_add_job_full(m, type, unit, mode, /* extra_flags= */ 0, affected_jobs, e, ret);
206✔
2236
}
2237

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

2242
        assert(m);
191✔
2243
        assert(type < _JOB_TYPE_MAX);
191✔
2244
        assert(name);
191✔
2245
        assert(mode < _JOB_MODE_MAX);
191✔
2246

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

2251
        return r;
2252
}
2253

2254
int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
19,044✔
2255
        _cleanup_(transaction_abort_and_freep) Transaction *tr = NULL;
19,044✔
2256
        int r;
19,044✔
2257

2258
        assert(m);
19,044✔
2259
        assert(unit);
19,044✔
2260
        assert(mode < _JOB_MODE_MAX);
19,044✔
2261
        assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
19,044✔
2262

2263
        tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY, ++m->last_transaction_id);
19,044✔
2264
        if (!tr)
19,044✔
2265
                return -ENOMEM;
2266

2267
        LOG_CONTEXT_PUSHF("TRANSACTION_ID=%" PRIu64, tr->id);
38,088✔
2268

2269
        /* We need an anchor job */
2270
        r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, TRANSACTION_IGNORE_REQUIREMENTS|TRANSACTION_IGNORE_ORDER, e);
19,044✔
2271
        if (r < 0)
19,044✔
2272
                return r;
2273

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

2281
        r = transaction_activate(tr, m, mode, NULL, e);
19,044✔
2282
        if (r < 0)
19,044✔
2283
                return r;
2284

2285
        tr = transaction_free(tr);
19,044✔
2286
        return 0;
19,044✔
2287
}
2288

2289
Job *manager_get_job(Manager *m, uint32_t id) {
18,039✔
2290
        assert(m);
18,039✔
2291

2292
        return hashmap_get(m->jobs, UINT32_TO_PTR(id));
18,039✔
2293
}
2294

2295
Unit *manager_get_unit(Manager *m, const char *name) {
1,985,421✔
2296
        assert(m);
1,985,421✔
2297
        assert(name);
1,985,421✔
2298

2299
        return hashmap_get(m->units, name);
1,985,421✔
2300
}
2301

2302
static int manager_dispatch_target_deps_queue(Manager *m) {
253,543✔
2303
        Unit *u;
253,543✔
2304
        int r = 0;
253,543✔
2305

2306
        assert(m);
253,543✔
2307

2308
        while ((u = LIST_POP(target_deps_queue, m->target_deps_queue))) {
319,363✔
2309
                _cleanup_free_ Unit **targets = NULL;
65,820✔
2310
                int n_targets;
65,820✔
2311

2312
                assert(u->in_target_deps_queue);
65,820✔
2313

2314
                u->in_target_deps_queue = false;
65,820✔
2315

2316
                /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2317
                 * dependencies, and we can't have it that hash tables we iterate through are modified while
2318
                 * we are iterating through them. */
2319
                n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
65,820✔
2320
                if (n_targets < 0)
65,820✔
2321
                        return n_targets;
2322

2323
                FOREACH_ARRAY(i, targets, n_targets) {
128,593✔
2324
                        r = unit_add_default_target_dependency(u, *i);
62,773✔
2325
                        if (r < 0)
62,773✔
2326
                                return r;
2327
                }
2328
        }
2329

2330
        return r;
2331
}
2332

2333
unsigned manager_dispatch_load_queue(Manager *m) {
284,501✔
2334
        Unit *u;
284,501✔
2335
        unsigned n = 0;
284,501✔
2336

2337
        assert(m);
284,501✔
2338

2339
        /* Make sure we are not run recursively */
2340
        if (m->dispatching_load_queue)
284,501✔
2341
                return 0;
2342

2343
        m->dispatching_load_queue = true;
253,543✔
2344

2345
        /* Dispatches the load queue. Takes a unit from the queue and
2346
         * tries to load its data until the queue is empty */
2347

2348
        while ((u = m->load_queue)) {
343,680✔
2349
                assert(u->in_load_queue);
90,137✔
2350

2351
                unit_load(u);
90,137✔
2352
                n++;
90,137✔
2353
        }
2354

2355
        m->dispatching_load_queue = false;
253,543✔
2356

2357
        /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2358
         * should be loaded and have aliases resolved */
2359
        (void) manager_dispatch_target_deps_queue(m);
253,543✔
2360

2361
        return n;
253,543✔
2362
}
2363

2364
bool manager_unit_cache_should_retry_load(Unit *u) {
638,137✔
2365
        assert(u);
638,137✔
2366

2367
        /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2368
         * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2369
         * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
2370
        if (u->load_state != UNIT_NOT_FOUND)
638,137✔
2371
                return false;
2372

2373
        /* The cache has been updated since the last time we tried to load the unit. There might be new
2374
         * fragment paths to read. */
2375
        if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
2,057✔
2376
                return true;
2377

2378
        /* The cache needs to be updated because there are modifications on disk. */
2379
        return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
2,057✔
2380
}
2381

2382
int manager_load_unit_prepare(
585,427✔
2383
                Manager *m,
2384
                const char *name,
2385
                const char *path,
2386
                sd_bus_error *e,
2387
                Unit **ret) {
2388

2389
        _cleanup_(unit_freep) Unit *cleanup_unit = NULL;
×
2390
        _cleanup_free_ char *nbuf = NULL;
585,427✔
2391
        int r;
585,427✔
2392

2393
        assert(m);
585,427✔
2394
        assert(ret);
585,427✔
2395
        assert(name || path);
585,427✔
2396

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

2399
        if (path && !path_is_absolute(path))
585,427✔
2400
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
×
2401

2402
        if (!name) {
585,427✔
2403
                r = path_extract_filename(path, &nbuf);
469✔
2404
                if (r < 0)
469✔
2405
                        return r;
2406
                if (r == O_DIRECTORY)
469✔
2407
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path '%s' refers to directory, refusing.", path);
×
2408

2409
                name = nbuf;
469✔
2410
        }
2411

2412
        UnitType t = unit_name_to_type(name);
585,427✔
2413

2414
        if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
585,427✔
2415
                if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
×
2416
                        return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
×
2417

2418
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
×
2419
        }
2420

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

2444
        if (path) {
57,062✔
2445
                r = free_and_strdup(&unit->fragment_path, path);
469✔
2446
                if (r < 0)
469✔
2447
                        return r;
2448
        }
2449

2450
        r = unit_add_name(unit, name);
57,062✔
2451
        if (r < 0)
57,062✔
2452
                return r;
2453

2454
        unit_add_to_load_queue(unit);
57,062✔
2455
        unit_add_to_dbus_queue(unit);
57,062✔
2456
        unit_add_to_gc_queue(unit);
57,062✔
2457

2458
        *ret = unit;
57,062✔
2459
        TAKE_PTR(cleanup_unit);
57,062✔
2460

2461
        return 1;  /* The unit was added the load queue */
57,062✔
2462
}
2463

2464
int manager_load_unit(
562,036✔
2465
                Manager *m,
2466
                const char *name,
2467
                const char *path,
2468
                sd_bus_error *e,
2469
                Unit **ret) {
2470
        int r;
562,036✔
2471

2472
        assert(m);
562,036✔
2473
        assert(ret);
562,036✔
2474

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

2477
        r = manager_load_unit_prepare(m, name, path, e, ret);
562,036✔
2478
        if (r <= 0)
562,036✔
2479
                return r;
2480

2481
        /* Unit was newly loaded */
2482
        manager_dispatch_load_queue(m);
34,061✔
2483
        *ret = unit_follow_merge(*ret);
34,061✔
2484
        return 0;
34,061✔
2485
}
2486

2487
int manager_load_startable_unit_or_warn(
734✔
2488
                Manager *m,
2489
                const char *name,
2490
                const char *path,
2491
                Unit **ret) {
2492

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

2495
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
734✔
2496
        Unit *unit;
734✔
2497
        int r;
734✔
2498

2499
        r = manager_load_unit(m, name, path, &error, &unit);
734✔
2500
        if (r < 0)
734✔
2501
                return log_error_errno(r, "Failed to load %s %s: %s",
×
2502
                                       name ? "unit" : "unit file", name ?: path,
2503
                                       bus_error_message(&error, r));
2504

2505
        r = bus_unit_validate_load_state(unit, &error);
734✔
2506
        if (r < 0)
734✔
2507
                return log_error_errno(r, "%s", bus_error_message(&error, r));
9✔
2508

2509
        *ret = unit;
725✔
2510
        return 0;
725✔
2511
}
2512

2513
void manager_clear_jobs(Manager *m) {
459✔
2514
        Job *j;
459✔
2515

2516
        assert(m);
459✔
2517

2518
        while ((j = hashmap_first(m->jobs)))
480✔
2519
                /* No need to recurse. We're cancelling all jobs. */
2520
                job_finish_and_invalidate(j, JOB_CANCELED, false, false);
21✔
2521
}
459✔
2522

2523
void manager_unwatch_pidref(Manager *m, const PidRef *pid) {
2,476✔
2524
        assert(m);
2,476✔
2525

2526
        for (;;) {
×
2527
                Unit *u;
2,476✔
2528

2529
                u = manager_get_unit_by_pidref_watching(m, pid);
2,476✔
2530
                if (!u)
2,476✔
2531
                        break;
2532

2533
                unit_unwatch_pidref(u, pid);
×
2534
        }
2535
}
2,476✔
2536

2537
static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
6,857✔
2538
        Manager *m = ASSERT_PTR(userdata);
6,857✔
2539
        Job *j;
6,857✔
2540

2541
        assert(source);
6,857✔
2542

2543
        while ((j = prioq_peek(m->run_queue))) {
67,044✔
2544
                assert(j->installed);
60,187✔
2545
                assert(j->in_run_queue);
60,187✔
2546

2547
                (void) job_run_and_invalidate(j);
60,187✔
2548
        }
2549

2550
        if (m->n_running_jobs > 0)
6,857✔
2551
                manager_watch_jobs_in_progress(m);
3,569✔
2552

2553
        if (m->n_on_console > 0)
6,857✔
2554
                manager_watch_idle_pipe(m);
762✔
2555

2556
        return 1;
6,857✔
2557
}
2558

2559
void manager_trigger_run_queue(Manager *m) {
62,762✔
2560
        int r;
62,762✔
2561

2562
        assert(m);
62,762✔
2563

2564
        r = sd_event_source_set_enabled(
125,335✔
2565
                        m->run_queue_event_source,
2566
                        prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
62,762✔
2567
        if (r < 0)
62,762✔
2568
                log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
×
2569
}
62,762✔
2570

2571
static unsigned manager_dispatch_dbus_queue(Manager *m) {
203,514✔
2572
        unsigned n = 0, budget;
203,514✔
2573
        Unit *u;
203,514✔
2574
        Job *j;
203,514✔
2575

2576
        assert(m);
203,514✔
2577

2578
        /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2579
         * as we can. There's no point in throttling generation of signals in that case. */
2580
        if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message_dbus || m->pending_reload_message_vl)
203,514✔
2581
                budget = UINT_MAX; /* infinite budget in this case */
2582
        else {
2583
                /* Anything to do at all? */
2584
                if (!m->dbus_unit_queue && !m->dbus_job_queue)
203,463✔
2585
                        return 0;
2586

2587
                /* Do we have overly many messages queued at the moment? If so, let's not enqueue more on top, let's
2588
                 * sit this cycle out, and process things in a later cycle when the queues got a bit emptier. */
2589
                if (manager_bus_n_queued_write(m) > MANAGER_BUS_BUSY_THRESHOLD)
10,868✔
2590
                        return 0;
2591

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

2606
        while (budget != 0 && (u = m->dbus_unit_queue)) {
42,490✔
2607

2608
                assert(u->in_dbus_queue);
31,571✔
2609

2610
                bus_unit_send_change_signal(u);
31,571✔
2611
                n++;
31,571✔
2612

2613
                if (budget != UINT_MAX)
31,571✔
2614
                        budget--;
18,143✔
2615
        }
2616

2617
        while (budget != 0 && (j = m->dbus_job_queue)) {
48,845✔
2618
                assert(j->in_dbus_queue);
37,926✔
2619

2620
                bus_job_send_change_signal(j);
37,926✔
2621
                n++;
37,926✔
2622

2623
                if (budget != UINT_MAX)
37,926✔
2624
                        budget--;
37,524✔
2625
        }
2626

2627
        if (m->send_reloading_done) {
10,919✔
2628
                m->send_reloading_done = false;
51✔
2629
                bus_manager_send_reloading(m, false);
51✔
2630
                n++;
51✔
2631
        }
2632

2633
        if (m->pending_reload_message_dbus) {
10,919✔
2634
                bus_send_pending_reload_message(m);
30✔
2635
                n++;
30✔
2636
        }
2637

2638
        if (m->pending_reload_message_vl) {
10,919✔
2639
                manager_varlink_send_pending_reload_message(m);
1✔
2640
                n++;
1✔
2641
        }
2642

2643
        return n;
2644
}
2645

2646
static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
3,725✔
2647

2648
        /* nothing else must be sent when using BARRIER=1 */
2649
        if (strv_contains(tags, "BARRIER=1")) {
3,725✔
2650
                if (strv_length(tags) != 1)
12✔
2651
                        log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
×
2652
                else if (fdset_size(fds) != 1)
12✔
2653
                        log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
×
2654

2655
                /* Drop the message if BARRIER=1 was found */
2656
                return true;
12✔
2657
        }
2658

2659
        return false;
2660
}
2661

2662
static void manager_invoke_notify_message(
7,289✔
2663
                Manager *m,
2664
                Unit *u,
2665
                PidRef *pidref,
2666
                const struct ucred *ucred,
2667
                char * const *tags,
2668
                FDSet *fds) {
2669

2670
        assert(m);
7,289✔
2671
        assert(u);
7,289✔
2672
        assert(pidref_is_set(pidref));
7,289✔
2673
        assert(ucred);
7,289✔
2674
        assert(pidref->pid == ucred->pid);
7,289✔
2675
        assert(tags);
7,289✔
2676

2677
        if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
7,289✔
2678
                return;
2679
        u->notifygen = m->notifygen;
3,713✔
2680

2681
        if (UNIT_VTABLE(u)->notify_message)
3,713✔
2682
                UNIT_VTABLE(u)->notify_message(u, pidref, ucred, tags, fds);
3,713✔
2683

2684
        else if (DEBUG_LOGGING) {
×
2685
                _cleanup_free_ char *joined = strv_join(tags, ", ");
×
2686
                char buf[CELLESCAPE_DEFAULT_LENGTH];
×
2687

2688
                log_unit_debug(u, "Got notification message from unexpected unit type, ignoring: %s",
×
2689
                               joined ? cellescape(buf, sizeof(buf), joined) : "(null)");
2690
        }
2691
}
2692

2693
static int manager_get_units_for_pidref(Manager *m, const PidRef *pidref, Unit ***ret_units) {
11,990✔
2694
        /* Determine array of every unit that is interested in the specified process */
2695

2696
        assert(m);
11,990✔
2697
        assert(pidref_is_set(pidref));
11,990✔
2698

2699
        Unit *u1, *u2, **array;
11,990✔
2700
        u1 = manager_get_unit_by_pidref_cgroup(m, pidref);
11,990✔
2701
        u2 = hashmap_get(m->watch_pids, pidref);
11,990✔
2702
        array = hashmap_get(m->watch_pids_more, pidref);
11,990✔
2703

2704
        size_t n = 0;
11,990✔
2705
        if (u1)
11,990✔
2706
                n++;
11,990✔
2707
        if (u2)
11,990✔
2708
                n++;
8,309✔
2709
        if (array)
11,990✔
2710
                for (size_t j = 0; array[j]; j++)
×
2711
                        n++;
×
2712

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

2715
        if (ret_units) {
11,990✔
2716
                _cleanup_free_ Unit **units = NULL;
×
2717

2718
                if (n > 0) {
11,990✔
2719
                        units = new(Unit*, n + 1);
11,990✔
2720
                        if (!units)
11,990✔
2721
                                return -ENOMEM;
×
2722

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

2727
                        size_t i = 0;
11,990✔
2728
                        if (u1)
11,990✔
2729
                                units[i++] = u1;
11,990✔
2730
                        if (u2)
11,990✔
2731
                                units[i++] = u2;
8,309✔
2732
                        if (array)
11,990✔
2733
                                for (size_t j = 0; array[j]; j++)
×
2734
                                        units[i++] = array[j];
×
2735
                        assert(i == n);
11,990✔
2736

2737
                        units[i] = NULL; /* end array in an extra NULL */
11,990✔
2738
                }
2739

2740
                *ret_units = TAKE_PTR(units);
11,990✔
2741
        }
2742

2743
        return (int) n;
11,990✔
2744
}
2745

2746
static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3,725✔
2747
        Manager *m = ASSERT_PTR(userdata);
3,725✔
2748
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3,725✔
2749
        struct ucred ucred;
3,725✔
2750
        _cleanup_(fdset_free_asyncp) FDSet *fds = NULL;
3,725✔
2751
        int r;
3,725✔
2752

2753
        assert(m->notify_fd == fd);
3,725✔
2754

2755
        if (revents != EPOLLIN) {
3,725✔
2756
                log_warning("Got unexpected poll event for notify fd.");
×
2757
                return 0;
×
2758
        }
2759

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

2771
        /* Possibly a barrier fd, let's see. */
2772
        if (manager_process_barrier_fd(tags, fds)) {
3,725✔
2773
                log_debug("Received barrier notification message from PID " PID_FMT ".", pidref.pid);
12✔
2774
                return 0;
12✔
2775
        }
2776

2777
        /* Increase the generation counter used for filtering out duplicate unit invocations. */
2778
        m->notifygen++;
3,713✔
2779

2780
        /* Notify every unit that might be interested, which might be multiple. */
2781
        _cleanup_free_ Unit **array = NULL;
3,713✔
2782

2783
        int n_array = manager_get_units_for_pidref(m, &pidref, &array);
3,713✔
2784
        if (n_array < 0) {
3,713✔
2785
                log_warning_errno(n_array, "Failed to determine units for PID " PID_FMT ", ignoring: %m", pidref.pid);
×
2786
                return 0;
×
2787
        }
2788
        if (n_array == 0)
3,713✔
UNCOV
2789
                log_debug("Cannot find unit for notify message of PID "PID_FMT", ignoring.", pidref.pid);
×
2790
        else
2791
                /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle
2792
                 * duplicate units – making sure we only invoke each unit's handler once. */
2793
                FOREACH_ARRAY(u, array, n_array)
11,002✔
2794
                        manager_invoke_notify_message(m, *u, &pidref, &ucred, tags, fds);
7,289✔
2795

2796
        if (!fdset_isempty(fds))
3,713✔
2797
                log_warning("Got extra auxiliary fds with notification message, closing them.");
×
2798

2799
        return 0;
2800
}
2801

2802
static void manager_invoke_sigchld_event(
8,114✔
2803
                Manager *m,
2804
                Unit *u,
2805
                const siginfo_t *si) {
2806

2807
        assert(m);
8,114✔
2808
        assert(u);
8,114✔
2809
        assert(si);
8,114✔
2810

2811
        /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2812
        if (u->sigchldgen == m->sigchldgen)
8,114✔
2813
                return;
2,187✔
2814
        u->sigchldgen = m->sigchldgen;
5,927✔
2815

2816
        log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
5,927✔
2817
        unit_unwatch_pidref(u, &PIDREF_MAKE_FROM_PID(si->si_pid));
5,927✔
2818

2819
        if (UNIT_VTABLE(u)->sigchld_event)
5,927✔
2820
                UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
5,772✔
2821
}
2822

2823
static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
10,350✔
2824
        Manager *m = ASSERT_PTR(userdata);
10,350✔
2825
        siginfo_t si = {};
10,350✔
2826
        int r;
10,350✔
2827

2828
        assert(source);
10,350✔
2829

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

2833
        if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
10,350✔
2834

2835
                if (errno != ECHILD)
89✔
2836
                        log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
×
2837

2838
                goto turn_off;
89✔
2839
        }
2840

2841
        if (si.si_pid <= 0)
10,261✔
2842
                goto turn_off;
4,432✔
2843

2844
        if (SIGINFO_CODE_IS_DEAD(si.si_code)) {
5,829✔
2845
                _cleanup_free_ char *name = NULL;
11,658✔
2846
                (void) pid_get_comm(si.si_pid, &name);
5,829✔
2847

2848
                log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
11,658✔
2849
                          si.si_pid, strna(name),
2850
                          sigchld_code_to_string(si.si_code),
2851
                          si.si_status,
2852
                          strna(si.si_code == CLD_EXITED
2853
                                ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2854
                                : signal_to_string(si.si_status)));
2855

2856
                /* Increase the generation counter used for filtering out duplicate unit invocations */
2857
                m->sigchldgen++;
5,829✔
2858

2859
                /* We look this up by a PidRef that only consists of the PID. After all we couldn't create a
2860
                 * pidfd here any more even if we wanted (since the process just exited). */
2861
                PidRef pidref = PIDREF_MAKE_FROM_PID(si.si_pid);
5,829✔
2862

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

2875
                        /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
2876
                        (void) unit_check_oomd_kill(array[0]);
5,829✔
2877

2878
                        /* Finally, execute them all. Note that the array might contain duplicates, but that's fine,
2879
                         * manager_invoke_sigchld_event() will ensure we only invoke the handlers once for each
2880
                         * iteration. */
2881
                        FOREACH_ARRAY(u, array, n_array)
13,943✔
2882
                                manager_invoke_sigchld_event(m, *u, &si);
8,114✔
2883
                }
2884
        }
2885

2886
        /* And now, we actually reap the zombie. */
2887
        if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
5,829✔
2888
                log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
×
2889
                return 0;
10,350✔
2890
        }
2891

2892
        return 0;
2893

2894
turn_off:
4,521✔
2895
        /* All children processed for now, turn off event source */
2896

2897
        r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
4,521✔
2898
        if (r < 0)
4,521✔
2899
                return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
×
2900

2901
        return 0;
2902
}
2903

2904
static void manager_start_special(Manager *m, const char *name, JobMode mode) {
189✔
2905
        Job *job;
189✔
2906

2907
        if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
189✔
2908
                return;
×
2909

2910
        const char *s = unit_status_string(job->unit, NULL);
189✔
2911

2912
        log_info("Activating special unit %s...", s);
189✔
2913

2914
        (void) sd_notifyf(/* unset_environment= */ false,
189✔
2915
                          "STATUS=Activating special unit %s...", s);
2916
        m->status_ready = false;
189✔
2917
}
2918

2919
static void manager_handle_ctrl_alt_del(Manager *m) {
×
2920
        assert(m);
×
2921

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

2925
        if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
×
2926
                manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
×
2927
        else
2928
                emergency_action(
×
2929
                                m,
2930
                                m->cad_burst_action,
2931
                                EMERGENCY_ACTION_WARN,
2932
                                /* reboot_arg= */ NULL,
2933
                                /* exit_status= */ -1,
2934
                                "Ctrl-Alt-Del was pressed more than 7 times within 2s");
2935
}
×
2936

2937
static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
4,440✔
2938
        Manager *m = ASSERT_PTR(userdata);
4,440✔
2939
        ssize_t n;
4,440✔
2940
        struct signalfd_siginfo sfsi;
4,440✔
2941
        int r;
4,440✔
2942

2943
        assert(m->signal_fd == fd);
4,440✔
2944

2945
        if (revents != EPOLLIN) {
4,440✔
2946
                log_warning("Got unexpected events from signal file descriptor.");
×
2947
                return 0;
×
2948
        }
2949

2950
        n = read(m->signal_fd, &sfsi, sizeof(sfsi));
4,440✔
2951
        if (n < 0) {
4,440✔
2952
                if (ERRNO_IS_TRANSIENT(errno))
×
2953
                        return 0;
2954

2955
                /* We return an error here, which will kill this handler,
2956
                 * to avoid a busy loop on read error. */
2957
                return log_error_errno(errno, "Reading from signal fd failed: %m");
×
2958
        }
2959
        if (n != sizeof(sfsi)) {
4,440✔
2960
                log_warning("Truncated read from signal fd (%zi bytes), ignoring!", n);
×
2961
                return 0;
×
2962
        }
2963

2964
        log_received_signal(sfsi.ssi_signo == SIGCHLD ||
4,629✔
2965
                            (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
189✔
2966
                            ? LOG_DEBUG : LOG_INFO,
2967
                            &sfsi);
2968

2969
        switch (sfsi.ssi_signo) {
4,440✔
2970

2971
        case SIGCHLD:
4,251✔
2972
                r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
4,251✔
2973
                if (r < 0)
4,251✔
2974
                        log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
4,440✔
2975

2976
                break;
2977

2978
        case SIGTERM:
189✔
2979
                if (MANAGER_IS_SYSTEM(m)) {
189✔
2980
                        /* This is for compatibility with the original sysvinit */
2981
                        m->objective = MANAGER_REEXECUTE;
×
2982
                        break;
×
2983
                }
2984

2985
                _fallthrough_;
189✔
2986
        case SIGINT:
2987
                if (MANAGER_IS_SYSTEM(m))
189✔
2988
                        manager_handle_ctrl_alt_del(m);
×
2989
                else
2990
                        manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
189✔
2991
                break;
2992

2993
        case SIGWINCH:
×
2994
                /* This is a nop on non-init */
2995
                if (MANAGER_IS_SYSTEM(m))
×
2996
                        manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
×
2997

2998
                break;
2999

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

3005
                break;
3006

3007
        case SIGUSR1:
×
3008
                if (manager_dbus_is_running(m, false)) {
×
3009
                        log_info("Trying to reconnect to bus...");
×
3010

3011
                        (void) bus_init_api(m);
×
3012

3013
                        if (MANAGER_IS_SYSTEM(m))
×
3014
                                (void) bus_init_system(m);
×
3015
                } else
3016
                        manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
×
3017

3018
                break;
3019

3020
        case SIGUSR2: {
×
3021
                _cleanup_free_ char *dump = NULL;
×
3022

3023
                r = manager_get_dump_string(m, /* patterns= */ NULL, &dump);
×
3024
                if (r < 0) {
×
3025
                        log_warning_errno(r, "Failed to acquire manager dump: %m");
×
3026
                        break;
3027
                }
3028

3029
                log_dump(LOG_INFO, dump);
×
3030
                break;
3031
        }
3032

3033
        case SIGHUP:
×
3034
                m->objective = MANAGER_RELOAD;
×
3035
                break;
×
3036

3037
        default: {
×
3038

3039
                if (MANAGER_IS_SYSTEM(m)) {
×
3040
                        /* Starting SIGRTMIN+0 */
3041
                        static const struct {
×
3042
                                const char *target;
3043
                                JobMode mode;
3044
                        } target_table[] = {
3045
                                [0] = { SPECIAL_DEFAULT_TARGET,     JOB_ISOLATE              },
3046
                                [1] = { SPECIAL_RESCUE_TARGET,      JOB_ISOLATE              },
3047
                                [2] = { SPECIAL_EMERGENCY_TARGET,   JOB_ISOLATE              },
3048
                                [3] = { SPECIAL_HALT_TARGET,        JOB_REPLACE_IRREVERSIBLY },
3049
                                [4] = { SPECIAL_POWEROFF_TARGET,    JOB_REPLACE_IRREVERSIBLY },
3050
                                [5] = { SPECIAL_REBOOT_TARGET,      JOB_REPLACE_IRREVERSIBLY },
3051
                                [6] = { SPECIAL_KEXEC_TARGET,       JOB_REPLACE_IRREVERSIBLY },
3052
                                [7] = { SPECIAL_SOFT_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
3053
                        };
3054

3055
                        /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
3056
                        static const ManagerObjective objective_table[] = {
×
3057
                                [0] = MANAGER_HALT,
3058
                                [1] = MANAGER_POWEROFF,
3059
                                [2] = MANAGER_REBOOT,
3060
                                [3] = MANAGER_KEXEC,
3061
                                [4] = MANAGER_SOFT_REBOOT,
3062
                        };
3063

3064
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
×
3065
                            (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
×
3066
                                int idx = (int) sfsi.ssi_signo - SIGRTMIN;
×
3067
                                manager_start_special(m, target_table[idx].target, target_table[idx].mode);
×
3068
                                break;
3069
                        }
3070

3071
                        if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
×
3072
                            (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
×
3073
                                m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
×
3074
                                break;
×
3075
                        }
3076
                }
3077

3078
                switch (sfsi.ssi_signo - SIGRTMIN) {
×
3079

3080
                case 18: {
×
3081
                        bool generic = false;
×
3082

3083
                        if (sfsi.ssi_code != SI_QUEUE)
×
3084
                                generic = true;
3085
                        else {
3086
                                /* Override a few select commands by our own PID1-specific logic */
3087

3088
                                switch (sfsi.ssi_int) {
×
3089

3090
                                case _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE..._COMMON_SIGNAL_COMMAND_LOG_LEVEL_END:
×
3091
                                        manager_override_log_level(m, sfsi.ssi_int - _COMMON_SIGNAL_COMMAND_LOG_LEVEL_BASE);
×
3092
                                        break;
3093

3094
                                case COMMON_SIGNAL_COMMAND_CONSOLE:
×
3095
                                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3096
                                        break;
3097

3098
                                case COMMON_SIGNAL_COMMAND_JOURNAL:
×
3099
                                        manager_override_log_target(m, LOG_TARGET_JOURNAL);
×
3100
                                        break;
3101

3102
                                case COMMON_SIGNAL_COMMAND_KMSG:
×
3103
                                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3104
                                        break;
3105

3106
                                case COMMON_SIGNAL_COMMAND_NULL:
×
3107
                                        manager_override_log_target(m, LOG_TARGET_NULL);
×
3108
                                        break;
3109

3110
                                case MANAGER_SIGNAL_COMMAND_DUMP_JOBS: {
×
3111
                                        _cleanup_free_ char *dump_jobs = NULL;
×
3112

3113
                                        r = manager_get_dump_jobs_string(m, /* patterns= */ NULL, "  ", &dump_jobs);
×
3114
                                        if (r < 0) {
×
3115
                                                log_warning_errno(r, "Failed to acquire manager jobs dump: %m");
×
3116
                                                break;
3117
                                        }
3118

3119
                                        log_dump(LOG_INFO, dump_jobs);
×
3120
                                        break;
3121
                                }
3122

3123
                                default:
3124
                                        generic = true;
3125
                                }
3126
                        }
3127

3128
                        if (generic)
×
3129
                                return sigrtmin18_handler(source, &sfsi, NULL);
×
3130

3131
                        break;
3132
                }
3133

3134
                case 20:
×
3135
                        manager_override_show_status(m, SHOW_STATUS_YES, "signal");
×
3136
                        break;
3137

3138
                case 21:
×
3139
                        manager_override_show_status(m, SHOW_STATUS_NO, "signal");
×
3140
                        break;
3141

3142
                case 22:
×
3143
                        manager_override_log_level(m, LOG_DEBUG);
×
3144
                        break;
3145

3146
                case 23:
×
3147
                        manager_restore_original_log_level(m);
×
3148
                        break;
3149

3150
                case 24:
×
3151
                        if (MANAGER_IS_USER(m)) {
×
3152
                                m->objective = MANAGER_EXIT;
×
3153
                                return 0;
×
3154
                        }
3155

3156
                        /* This is a nop on init */
3157
                        break;
3158

3159
                case 25:
×
3160
                        m->objective = MANAGER_REEXECUTE;
×
3161
                        break;
×
3162

3163
                case 26:
×
3164
                case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
3165
                        manager_restore_original_log_target(m);
×
3166
                        break;
3167

3168
                case 27:
×
3169
                        manager_override_log_target(m, LOG_TARGET_CONSOLE);
×
3170
                        break;
3171

3172
                case 28:
×
3173
                        manager_override_log_target(m, LOG_TARGET_KMSG);
×
3174
                        break;
3175

3176
                default:
3177
                        log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
×
3178
                }
3179
        }}
3180

3181
        return 0;
3182
}
3183

3184
static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
11✔
3185
        Manager *m = ASSERT_PTR(userdata);
11✔
3186
        Unit *u;
11✔
3187

3188
        log_struct(LOG_DEBUG,
11✔
3189
                   LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE_STR),
3190
                   LOG_MESSAGE("Time has been changed"));
3191

3192
        /* Restart the watch */
3193
        (void) manager_setup_time_change(m);
11✔
3194

3195
        HASHMAP_FOREACH(u, m->units)
1,508✔
3196
                if (UNIT_VTABLE(u)->time_change)
1,486✔
3197
                        UNIT_VTABLE(u)->time_change(u);
11✔
3198

3199
        return 0;
11✔
3200
}
3201

3202
static int manager_dispatch_timezone_change(
57✔
3203
                sd_event_source *source,
3204
                const struct inotify_event *e,
3205
                void *userdata) {
3206

3207
        Manager *m = ASSERT_PTR(userdata);
57✔
3208
        int changed;
57✔
3209
        Unit *u;
57✔
3210

3211
        log_debug("inotify event for /etc/localtime");
57✔
3212

3213
        changed = manager_read_timezone_stat(m);
57✔
3214
        if (changed <= 0)
57✔
3215
                return changed;
57✔
3216

3217
        /* Something changed, restart the watch, to ensure we watch the new /etc/localtime if it changed */
3218
        (void) manager_setup_timezone_change(m);
32✔
3219

3220
        /* Read the new timezone */
3221
        tzset();
32✔
3222

3223
        log_debug("Timezone has been changed (now: %s).", get_tzname(daylight));
32✔
3224

3225
        HASHMAP_FOREACH(u, m->units)
6,712✔
3226
                if (UNIT_VTABLE(u)->timezone_change)
6,648✔
3227
                        UNIT_VTABLE(u)->timezone_change(u);
70✔
3228

3229
        return 0;
32✔
3230
}
3231

3232
static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
9✔
3233
        Manager *m = ASSERT_PTR(userdata);
9✔
3234

3235
        assert(m->idle_pipe[2] == fd);
9✔
3236

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

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

3248
        return 0;
9✔
3249
}
3250

3251
static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
×
3252
        Manager *m = ASSERT_PTR(userdata);
×
3253
        int r;
×
3254

3255
        assert(source);
×
3256

3257
        manager_print_jobs_in_progress(m);
×
3258

3259
        r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
×
3260
        if (r < 0)
×
3261
                return r;
3262

3263
        return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
×
3264
}
3265

3266
int manager_loop(Manager *m) {
274✔
3267
        RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
274✔
3268
        int r;
274✔
3269

3270
        assert(m);
274✔
3271
        assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
274✔
3272

3273
        manager_check_finished(m);
274✔
3274

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

3280
        while (m->objective == MANAGER_OK) {
237,090✔
3281

3282
                if (!ratelimit_below(&rl)) {
236,816✔
3283
                        /* Yay, something is going seriously wrong, pause a little */
3284
                        log_warning("Looping too fast. Throttling execution a little.");
×
3285
                        sleep(1);
×
3286
                }
3287

3288
                (void) watchdog_ping();
236,816✔
3289

3290
                if (manager_dispatch_load_queue(m) > 0)
236,816✔
3291
                        continue;
1✔
3292

3293
                if (manager_dispatch_gc_job_queue(m) > 0)
236,815✔
3294
                        continue;
10✔
3295

3296
                if (manager_dispatch_gc_unit_queue(m) > 0)
236,805✔
3297
                        continue;
17,727✔
3298

3299
                if (manager_dispatch_cleanup_queue(m) > 0)
219,078✔
3300
                        continue;
9,683✔
3301

3302
                if (manager_dispatch_cgroup_realize_queue(m) > 0)
209,395✔
3303
                        continue;
4,328✔
3304

3305
                if (manager_dispatch_start_when_upheld_queue(m) > 0)
205,067✔
3306
                        continue;
×
3307

3308
                if (manager_dispatch_stop_when_bound_queue(m) > 0)
205,067✔
3309
                        continue;
151✔
3310

3311
                if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
204,916✔
3312
                        continue;
253✔
3313

3314
                if (manager_dispatch_release_resources_queue(m) > 0)
204,663✔
3315
                        continue;
1,149✔
3316

3317
                if (manager_dispatch_stop_notify_queue(m) > 0)
203,514✔
3318
                        continue;
×
3319

3320
                if (manager_dispatch_dbus_queue(m) > 0)
203,514✔
3321
                        continue;
10,919✔
3322

3323
                /* Sleep for watchdog runtime wait time */
3324
                r = sd_event_run(m->event, watchdog_runtime_wait(/* divisor= */ 2));
192,595✔
3325
                if (r < 0)
192,595✔
3326
                        return log_error_errno(r, "Failed to run event loop: %m");
×
3327
        }
3328

3329
        return m->objective;
3330
}
3331

3332
int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
362,330✔
3333
        _cleanup_free_ char *n = NULL;
362,330✔
3334
        sd_id128_t invocation_id;
362,330✔
3335
        Unit *u;
362,330✔
3336
        int r;
362,330✔
3337

3338
        assert(m);
362,330✔
3339
        assert(s);
362,330✔
3340
        assert(_u);
362,330✔
3341

3342
        r = unit_name_from_dbus_path(s, &n);
362,330✔
3343
        if (r < 0)
362,330✔
3344
                return r;
3345

3346
        /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128-bit ID then
3347
         * we use it as invocation ID. */
3348
        r = sd_id128_from_string(n, &invocation_id);
362,293✔
3349
        if (r >= 0) {
362,293✔
3350
                u = hashmap_get(m->units_by_invocation_id, &invocation_id);
×
3351
                if (u) {
×
3352
                        *_u = u;
×
3353
                        return 0;
×
3354
                }
3355

3356
                return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
×
3357
                                         "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3358
                                         SD_ID128_FORMAT_VAL(invocation_id));
×
3359
        }
3360

3361
        /* If this didn't work, we check if this is a unit name */
3362
        if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
362,293✔
3363
                _cleanup_free_ char *nn = NULL;
1✔
3364

3365
                nn = cescape(n);
1✔
3366
                return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
1✔
3367
                                         "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3368
        }
3369

3370
        r = manager_load_unit(m, n, NULL, e, &u);
362,292✔
3371
        if (r < 0)
362,292✔
3372
                return r;
3373

3374
        *_u = u;
362,292✔
3375
        return 0;
362,292✔
3376
}
3377

3378
int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
928✔
3379
        const char *p;
928✔
3380
        unsigned id;
928✔
3381
        Job *j;
928✔
3382
        int r;
928✔
3383

3384
        assert(m);
928✔
3385
        assert(s);
928✔
3386
        assert(_j);
928✔
3387

3388
        p = startswith(s, "/org/freedesktop/systemd1/job/");
928✔
3389
        if (!p)
928✔
3390
                return -EINVAL;
928✔
3391

3392
        r = safe_atou(p, &id);
927✔
3393
        if (r < 0)
927✔
3394
                return r;
3395

3396
        j = manager_get_job(m, id);
927✔
3397
        if (!j)
927✔
3398
                return -ENOENT;
3399

3400
        *_j = j;
919✔
3401

3402
        return 0;
919✔
3403
}
3404

3405
void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
3,758✔
3406

3407
#if HAVE_AUDIT
3408
        _cleanup_free_ char *p = NULL;
3,758✔
3409
        const char *msg;
3,758✔
3410
        int audit_fd, r;
3,758✔
3411

3412
        assert(m);
3,758✔
3413
        assert(u);
3,758✔
3414

3415
        if (!MANAGER_IS_SYSTEM(m))
3,758✔
3416
                return;
3417

3418
        /* Don't generate audit events if the service was already started and we're just deserializing */
3419
        if (MANAGER_IS_RELOADING(m))
2,372✔
3420
                return;
3421

3422
        audit_fd = get_core_audit_fd();
2,372✔
3423
        if (audit_fd < 0)
2,372✔
3424
                return;
3425

3426
        r = unit_name_to_prefix_and_instance(u->id, &p);
896✔
3427
        if (r < 0) {
896✔
3428
                log_warning_errno(r, "Failed to extract prefix and instance of unit name, ignoring: %m");
×
3429
                return;
×
3430
        }
3431

3432
        msg = strjoina("unit=", p);
4,480✔
3433
        if (sym_audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
896✔
3434
                if (ERRNO_IS_PRIVILEGE(errno)) {
×
3435
                        /* We aren't allowed to send audit messages?  Then let's not retry again. */
3436
                        log_debug_errno(errno, "Failed to send audit message, closing audit socket: %m");
×
3437
                        close_core_audit_fd();
×
3438
                } else
3439
                        log_warning_errno(errno, "Failed to send audit message, ignoring: %m");
896✔
3440
        }
3441
#endif
3442
}
3443

3444
void manager_send_unit_plymouth(Manager *m, Unit *u) {
39,649✔
3445
        _cleanup_free_ char *message = NULL;
39,649✔
3446
        int c, r;
39,649✔
3447

3448
        assert(m);
39,649✔
3449
        assert(u);
39,649✔
3450

3451
        if (!MANAGER_IS_SYSTEM(m))
39,649✔
3452
                return;
3453

3454
        /* Don't generate plymouth events if the service was already started and we're just deserializing */
3455
        if (MANAGER_IS_RELOADING(m))
6,296✔
3456
                return;
3457

3458
        if (detect_container() > 0)
6,296✔
3459
                return;
3460

3461
        if (!UNIT_VTABLE(u)->notify_plymouth)
3,534✔
3462
                return;
3463

3464
        c = asprintf(&message, "U\x02%c%s%c", (int) (strlen(u->id) + 1), u->id, '\x00');
639✔
3465
        if (c < 0)
639✔
3466
                return (void) log_oom();
×
3467

3468
        /* We set SOCK_NONBLOCK here so that we rather drop the message then wait for plymouth */
3469
        r = plymouth_send_raw(message, c, SOCK_NONBLOCK);
639✔
3470
        if (r < 0)
639✔
3471
                log_full_errno(ERRNO_IS_NO_PLYMOUTH(r) ? LOG_DEBUG : LOG_WARNING, r,
639✔
3472
                               "Failed to communicate with plymouth: %m");
3473
}
3474

3475
void manager_send_unit_supervisor(Manager *m, Unit *u, bool active) {
63,381✔
3476
        assert(m);
63,381✔
3477
        assert(u);
63,381✔
3478

3479
        /* Notify a "supervisor" process about our progress, i.e. a container manager, hypervisor, or
3480
         * surrounding service manager. */
3481

3482
        if (MANAGER_IS_RELOADING(m))
63,381✔
3483
                return;
3484

3485
        if (!UNIT_VTABLE(u)->notify_supervisor)
63,381✔
3486
                return;
3487

3488
        if (in_initrd()) /* Only send these once we left the initrd */
4,255✔
3489
                return;
3490

3491
        (void) sd_notifyf(/* unset_environment= */ false,
5,222✔
3492
                          active ? "X_SYSTEMD_UNIT_ACTIVE=%s" : "X_SYSTEMD_UNIT_INACTIVE=%s",
3493
                          u->id);
3494
}
3495

3496
usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
571✔
3497
        assert(m);
571✔
3498

3499
        if (MANAGER_IS_USER(m))
571✔
3500
                return USEC_INFINITY;
3501

3502
        if (m->watchdog_overridden[t] != USEC_INFINITY)
187✔
3503
                return m->watchdog_overridden[t];
3504

3505
        return m->watchdog[t];
184✔
3506
}
3507

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

3510
        assert(m);
1,096✔
3511

3512
        if (MANAGER_IS_USER(m))
1,096✔
3513
                return;
3514

3515
        if (m->watchdog_overridden[t] == USEC_INFINITY) {
328✔
3516
                if (t == WATCHDOG_RUNTIME)
322✔
3517
                        (void) watchdog_setup(timeout);
82✔
3518
                else if (t == WATCHDOG_PRETIMEOUT)
240✔
3519
                        (void) watchdog_setup_pretimeout(timeout);
82✔
3520
        }
3521

3522
        m->watchdog[t] = timeout;
328✔
3523
}
3524

3525
void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
7✔
3526
        usec_t usec;
7✔
3527

3528
        assert(m);
7✔
3529

3530
        if (MANAGER_IS_USER(m))
7✔
3531
                return;
3532

3533
        usec = timeout == USEC_INFINITY ? m->watchdog[t] : timeout;
7✔
3534
        if (t == WATCHDOG_RUNTIME)
7✔
3535
                (void) watchdog_setup(usec);
×
3536
        else if (t == WATCHDOG_PRETIMEOUT)
7✔
3537
                (void) watchdog_setup_pretimeout(usec);
×
3538

3539
        m->watchdog_overridden[t] = timeout;
7✔
3540
}
3541

3542
int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
274✔
3543
        _cleanup_free_ char *p = NULL;
274✔
3544
        int r;
274✔
3545

3546
        assert(m);
274✔
3547

3548
        if (MANAGER_IS_USER(m))
274✔
3549
                return 0;
3550

3551
        if (streq_ptr(m->watchdog_pretimeout_governor, governor))
82✔
3552
                return 0;
3553

3554
        p = strdup(governor);
×
3555
        if (!p)
×
3556
                return -ENOMEM;
3557

3558
        r = watchdog_setup_pretimeout_governor(governor);
×
3559
        if (r < 0)
×
3560
                return r;
3561

3562
        return free_and_replace(m->watchdog_pretimeout_governor, p);
×
3563
}
3564

3565
int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
×
3566
        _cleanup_free_ char *p = NULL;
×
3567
        int r;
×
3568

3569
        assert(m);
×
3570

3571
        if (MANAGER_IS_USER(m))
×
3572
                return 0;
3573

3574
        if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
×
3575
                return 0;
3576

3577
        p = strdup(governor);
×
3578
        if (!p)
×
3579
                return -ENOMEM;
3580

3581
        r = watchdog_setup_pretimeout_governor(governor);
×
3582
        if (r < 0)
×
3583
                return r;
3584

3585
        return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
×
3586
}
3587

3588
int manager_reload(Manager *m) {
31✔
3589
        _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
31✔
3590
        _cleanup_fdset_free_ FDSet *fds = NULL;
×
3591
        _cleanup_fclose_ FILE *f = NULL;
31✔
3592
        int r;
31✔
3593

3594
        assert(m);
31✔
3595

3596
        r = manager_open_serialization(m, &f);
31✔
3597
        if (r < 0)
31✔
3598
                return log_error_errno(r, "Failed to create serialization file: %m");
×
3599

3600
        fds = fdset_new();
31✔
3601
        if (!fds)
31✔
3602
                return log_oom();
×
3603

3604
        /* We are officially in reload mode from here on. */
3605
        reloading = manager_reloading_start(m);
31✔
3606

3607
        r = manager_serialize(m, f, fds, false);
31✔
3608
        if (r < 0)
31✔
3609
                return r;
3610

3611
        r = finish_serialization_file(f);
31✔
3612
        if (r < 0)
31✔
3613
                return log_error_errno(r, "Failed to finish serialization: %m");
×
3614

3615
        /* 💀 This is the point of no return, from here on there is no way back. 💀 */
3616
        reloading = NULL;
31✔
3617

3618
        bus_manager_send_reloading(m, true);
31✔
3619

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

3624
        manager_clear_jobs_and_units(m);
31✔
3625
        lookup_paths_flush_generator(&m->lookup_paths);
31✔
3626
        exec_shared_runtime_vacuum(m);
31✔
3627
        dynamic_user_vacuum(m, false);
31✔
3628
        m->uid_refs = hashmap_free(m->uid_refs);
31✔
3629
        m->gid_refs = hashmap_free(m->gid_refs);
31✔
3630

3631
        (void) manager_run_environment_generators(m);
31✔
3632
        (void) manager_run_generators(m);
31✔
3633

3634
        /* We flushed out generated files, for which we don't watch mtime, so we should flush the old map. */
3635
        manager_free_unit_name_maps(m);
31✔
3636
        m->unit_file_state_outdated = false;
31✔
3637

3638
        /* First, enumerate what we can from kernel and suchlike */
3639
        manager_enumerate_perpetual(m);
31✔
3640
        manager_enumerate(m);
31✔
3641

3642
        /* Second, deserialize our stored data */
3643
        r = manager_deserialize(m, f, fds);
31✔
3644
        if (r < 0)
31✔
3645
                log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
×
3646

3647
        /* We don't need the serialization anymore */
3648
        f = safe_fclose(f);
31✔
3649

3650
        /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3651
        (void) manager_setup_notify(m);
31✔
3652
        (void) manager_setup_user_lookup_fd(m);
31✔
3653
        (void) manager_setup_handoff_timestamp_fd(m);
31✔
3654
        (void) manager_setup_pidref_transport_fd(m);
31✔
3655

3656
        /* Clean up deserialized bus track information. They're never consumed during reload (as opposed to
3657
         * reexec) since we do not disconnect from the bus. */
3658
        m->subscribed_as_strv = strv_free(m->subscribed_as_strv);
31✔
3659
        m->deserialized_bus_id = SD_ID128_NULL;
31✔
3660

3661
        /* Third, fire things up! */
3662
        manager_coldplug(m);
31✔
3663

3664
        /* Clean up runtime objects no longer referenced */
3665
        manager_vacuum(m);
31✔
3666

3667
        /* Consider the reload process complete now. */
3668
        assert(m->n_reloading > 0);
31✔
3669
        m->n_reloading--;
31✔
3670

3671
        manager_ready(m);
31✔
3672

3673
        m->send_reloading_done = true;
31✔
3674
        return 0;
31✔
3675
}
3676

3677
void manager_reset_failed(Manager *m) {
1✔
3678
        Unit *u;
1✔
3679

3680
        assert(m);
1✔
3681

3682
        HASHMAP_FOREACH(u, m->units)
255✔
3683
                unit_reset_failed(u);
254✔
3684

3685
        m->transactions_with_cycle = set_free(m->transactions_with_cycle);
1✔
3686
}
1✔
3687

3688
bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
×
3689
        Unit *u;
×
3690

3691
        assert(m);
×
3692
        assert(name);
×
3693

3694
        /* Returns true if the unit is inactive or going down */
3695
        u = manager_get_unit(m, name);
×
3696
        if (!u)
×
3697
                return true;
3698

3699
        return unit_inactive_or_pending(u);
×
3700
}
3701

3702
static void log_taint_string(Manager *m) {
21,321✔
3703
        assert(m);
21,321✔
3704

3705
        if (MANAGER_IS_USER(m) || m->taint_logged)
21,321✔
3706
                return;
21,321✔
3707

3708
        m->taint_logged = true; /* only check for taint once */
34✔
3709

3710
        _cleanup_free_ char *taint = taint_string();
68✔
3711
        if (isempty(taint))
34✔
3712
                return;
34✔
3713

3714
        log_struct(LOG_NOTICE,
×
3715
                   LOG_MESSAGE("System is tainted: %s", taint),
3716
                   LOG_ITEM("TAINT=%s", taint),
3717
                   LOG_MESSAGE_ID(SD_MESSAGE_TAINTED_STR));
3718
}
3719

3720
static void manager_notify_finished(Manager *m) {
196✔
3721
        usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
196✔
3722

3723
        if (MANAGER_IS_TEST_RUN(m))
196✔
3724
                return;
3725

3726
        if (MANAGER_IS_SYSTEM(m) && m->soft_reboots_count > 0) {
189✔
3727
                /* The soft-reboot case, where we only report data for the last reboot */
3728
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
×
3729
                total_usec = userspace_usec = usec_sub_unsigned(m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic,
×
3730
                                                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START].monotonic);
3731

3732
                log_struct(LOG_INFO,
×
3733
                           LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3734
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3735
                           LOG_MESSAGE("Soft-reboot finished in %s, counter is now at %u.",
3736
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC),
3737
                                       m->soft_reboots_count));
3738
        } else if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
190✔
3739
                char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
1✔
3740
                        = {};
3741
                char *p = buf;
1✔
3742
                size_t size = sizeof buf;
1✔
3743

3744
                /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3745
                 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
3746
                 * negative values. */
3747

3748
                firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
1✔
3749
                loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
1✔
3750
                userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
1✔
3751
                total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
1✔
3752

3753
                if (firmware_usec > 0)
1✔
3754
                        size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
×
3755
                if (loader_usec > 0)
1✔
3756
                        size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
×
3757

3758
                if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
1✔
3759

3760
                        /* The initrd case on bare-metal */
3761
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
×
3762
                        initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
×
3763

3764
                        log_struct(LOG_INFO,
×
3765
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3766
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3767
                                   LOG_ITEM("INITRD_USEC="USEC_FMT, initrd_usec),
3768
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3769
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3770
                                               buf,
3771
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3772
                                               FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3773
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3774
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3775
                } else {
3776
                        /* The initrd-less case on bare-metal */
3777

3778
                        kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
1✔
3779
                        initrd_usec = 0;
1✔
3780

3781
                        log_struct(LOG_INFO,
1✔
3782
                                   LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED_STR),
3783
                                   LOG_ITEM("KERNEL_USEC="USEC_FMT, kernel_usec),
3784
                                   LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3785
                                   LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3786
                                               buf,
3787
                                               FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3788
                                               FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3789
                                               FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3790
                }
3791
        } else {
3792
                /* The container and --user case */
3793
                firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
188✔
3794
                total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
188✔
3795

3796
                log_struct(LOG_INFO,
188✔
3797
                           LOG_MESSAGE_ID(SD_MESSAGE_USER_STARTUP_FINISHED_STR),
3798
                           LOG_ITEM("USERSPACE_USEC="USEC_FMT, userspace_usec),
3799
                           LOG_MESSAGE("Startup finished in %s.",
3800
                                       FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
3801
        }
3802

3803
        bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
189✔
3804

3805
        if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
189✔
3806
                watchdog_report_if_missing();
1✔
3807

3808
        log_taint_string(m);
189✔
3809
}
3810

3811
static void manager_send_ready_on_basic_target(Manager *m) {
21,132✔
3812
        int r;
21,132✔
3813

3814
        assert(m);
21,132✔
3815

3816
        /* We send READY=1 on reaching basic.target only when running in --user mode. */
3817
        if (!MANAGER_IS_USER(m) || m->ready_sent)
21,132✔
3818
                return;
3819

3820
        r = sd_notify(/* unset_environment= */ false,
197✔
3821
                      "READY=1\n"
3822
                      "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3823
        if (r < 0)
197✔
3824
                log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
×
3825

3826
        m->ready_sent = true;
197✔
3827
        m->status_ready = false;
197✔
3828
}
3829

3830
static void manager_send_ready_on_idle(Manager *m) {
2,953✔
3831
        int r;
2,953✔
3832

3833
        assert(m);
2,953✔
3834

3835
        /* Skip the notification if nothing changed. */
3836
        if (m->ready_sent && m->status_ready)
2,953✔
3837
                return;
3838

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

3849
        m->ready_sent = m->status_ready = true;
199✔
3850
}
3851

3852
static void manager_check_basic_target(Manager *m) {
35,541✔
3853
        Unit *u;
35,541✔
3854

3855
        assert(m);
35,541✔
3856

3857
        /* Small shortcut */
3858
        if (m->ready_sent && m->taint_logged)
35,541✔
3859
                return;
3860

3861
        u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
35,464✔
3862
        if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
35,464✔
3863
                return;
14,332✔
3864

3865
        /* For user managers, send out READY=1 as soon as we reach basic.target */
3866
        manager_send_ready_on_basic_target(m);
21,132✔
3867

3868
        /* Log the taint string as soon as we reach basic.target */
3869
        log_taint_string(m);
21,132✔
3870
}
3871

3872
void manager_check_finished(Manager *m) {
35,750✔
3873
        assert(m);
35,750✔
3874

3875
        if (MANAGER_IS_RELOADING(m))
35,750✔
3876
                return;
3877

3878
        /* Verify that we have entered the event loop already, and not left it again. */
3879
        if (!MANAGER_IS_RUNNING(m))
35,750✔
3880
                return;
3881

3882
        manager_check_basic_target(m);
35,541✔
3883

3884
        if (!hashmap_isempty(m->jobs)) {
35,541✔
3885
                if (m->jobs_in_progress_event_source)
32,588✔
3886
                        /* Ignore any failure, this is only for feedback */
3887
                        (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
4,806✔
3888
                                                        manager_watch_jobs_next_time(m));
4,806✔
3889
                return;
32,588✔
3890
        }
3891

3892
        /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
3893
           kill the hashmap if it is relatively large. */
3894
        if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
2,953✔
3895
                m->jobs = hashmap_free(m->jobs);
518✔
3896

3897
        manager_send_ready_on_idle(m);
2,953✔
3898

3899
        /* Notify Type=idle units that we are done now */
3900
        manager_close_idle_pipe(m);
2,953✔
3901

3902
        if (MANAGER_IS_FINISHED(m))
2,953✔
3903
                return;
3904

3905
        manager_flip_auto_status(m, false, "boot finished");
196✔
3906

3907
        /* Turn off confirm spawn now */
3908
        m->confirm_spawn = NULL;
196✔
3909

3910
        /* No need to update ask password status when we're going non-interactive */
3911
        manager_close_ask_password(m);
196✔
3912

3913
        /* This is no longer the first boot */
3914
        manager_set_first_boot(m, false);
196✔
3915

3916
        dual_timestamp_now(m->timestamps + MANAGER_TIMESTAMP_FINISH);
196✔
3917

3918
        manager_notify_finished(m);
196✔
3919

3920
        manager_invalidate_startup_units(m);
196✔
3921
}
3922

3923
void manager_send_reloading(Manager *m) {
70✔
3924
        assert(m);
70✔
3925

3926
        /* Let whoever invoked us know that we are now reloading */
3927
        (void) notify_reloading_full(/* status= */ NULL);
70✔
3928

3929
        /* And ensure that we'll send READY=1 again as soon as we are ready again */
3930
        m->ready_sent = false;
70✔
3931
}
70✔
3932

3933
static bool generator_path_any(char * const *paths) {
1,016✔
3934

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

3937
        STRV_FOREACH(i, paths) {
4,064✔
3938
                if (access(*i, F_OK) >= 0)
4,064✔
3939
                        return true;
3940
                if (errno != ENOENT)
3,048✔
3941
                        log_warning_errno(errno, "Failed to check if generator dir '%s' exists, assuming not: %m", *i);
3,048✔
3942
        }
3943

3944
        return false;
3945
}
3946

3947
static int manager_run_environment_generators(Manager *m) {
768✔
3948
        _cleanup_strv_free_ char **paths = NULL;
768✔
3949
        int r;
768✔
3950

3951
        assert(m);
768✔
3952

3953
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
768✔
3954
                return 0;
3955

3956
        paths = env_generator_binary_paths(m->runtime_scope);
742✔
3957
        if (!paths)
742✔
3958
                return log_oom();
×
3959

3960
        if (!generator_path_any(paths))
742✔
3961
                return 0;
3962

3963
        char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
742✔
3964
        void *args[_STDOUT_CONSUME_MAX] = {
742✔
3965
                [STDOUT_GENERATE] = &tmp,
3966
                [STDOUT_COLLECT]  = &tmp,
3967
                [STDOUT_CONSUME]  = &m->transient_environment,
742✔
3968
        };
3969

3970
        WITH_UMASK(0022)
1,484✔
3971
                r = execute_directories(
742✔
3972
                                "environment-generators",
3973
                                (const char* const*) paths,
3974
                                DEFAULT_TIMEOUT_USEC,
3975
                                gather_environment,
3976
                                args,
3977
                                /* argv[]= */ NULL,
3978
                                m->transient_environment,
3979
                                EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
3980
        return r;
742✔
3981
}
3982

3983
static int build_generator_environment(Manager *m, char ***ret) {
192✔
3984
        _cleanup_strv_free_ char **nl = NULL;
192✔
3985
        Virtualization v;
192✔
3986
        ConfidentialVirtualization cv;
192✔
3987
        int r;
192✔
3988

3989
        assert(m);
192✔
3990
        assert(ret);
192✔
3991

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

3996
        nl = strv_copy(m->transient_environment);
192✔
3997
        if (!nl)
192✔
3998
                return -ENOMEM;
3999

4000
        r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
192✔
4001
        if (r < 0)
192✔
4002
                return r;
4003

4004
        if (MANAGER_IS_SYSTEM(m)) {
192✔
4005
                /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
4006
                 * codebase. This is hence more than purely informational. It will shortcut detection of the
4007
                 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
4008
                 * same results (hopefully). */
4009
                r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
×
4010
                if (r < 0)
×
4011
                        return r;
4012

4013
                if (m->soft_reboots_count > 0) {
×
4014
                        r = strv_env_assignf(&nl, "SYSTEMD_SOFT_REBOOTS_COUNT", "%u", m->soft_reboots_count);
×
4015
                        if (r < 0)
×
4016
                                return r;
4017
                }
4018

4019
                if (m->first_boot >= 0) {
×
4020
                        r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
×
4021
                        if (r < 0)
×
4022
                                return r;
4023
                }
4024
        }
4025

4026
        v = detect_virtualization();
192✔
4027
        if (v < 0)
192✔
4028
                log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
×
4029
        else if (v > 0) {
192✔
4030
                const char *s;
192✔
4031

4032
                s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
960✔
4033
                             VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
4034
                             virtualization_to_string(v));
4035

4036
                r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
192✔
4037
                if (r < 0)
192✔
4038
                        return r;
4039
        }
4040

4041
        cv = detect_confidential_virtualization();
192✔
4042
        if (cv < 0)
192✔
4043
                log_debug_errno(cv, "Failed to detect confidential virtualization, ignoring: %m");
×
4044
        else if (cv > 0) {
192✔
4045
                r = strv_env_assign(&nl, "SYSTEMD_CONFIDENTIAL_VIRTUALIZATION", confidential_virtualization_to_string(cv));
×
4046
                if (r < 0)
×
4047
                        return r;
4048
        }
4049

4050
        r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
192✔
4051
        if (r < 0)
192✔
4052
                return r;
4053

4054
        *ret = TAKE_PTR(nl);
192✔
4055
        return 0;
192✔
4056
}
4057

4058
static int manager_execute_generators(Manager *m, char * const *paths, bool remount_ro) {
192✔
4059
        _cleanup_strv_free_ char **ge = NULL;
192✔
4060
        int r;
192✔
4061

4062
        assert(m);
192✔
4063

4064
        r = build_generator_environment(m, &ge);
192✔
4065
        if (r < 0)
192✔
4066
                return log_error_errno(r, "Failed to build generator environment: %m");
×
4067

4068
        if (remount_ro) {
192✔
4069
                /* Remount most of the filesystem tree read-only. We leave /sys/ as-is, because our code
4070
                 * checks whether it is read-only to detect containerized execution environments. We leave
4071
                 * /run/ as-is too, because that's where our output goes. We also leave /proc/ and /dev/shm/
4072
                 * because they're API, and /tmp/ that safe_fork() mounted for us.
4073
                 */
4074
                r = bind_remount_recursive("/", MS_RDONLY, MS_RDONLY,
×
4075
                                           STRV_MAKE("/sys", "/run", "/proc", "/dev/shm", "/tmp"));
×
4076
                if (r < 0)
×
4077
                        log_warning_errno(r, "Read-only bind remount failed, ignoring: %m");
×
4078
        }
4079

4080
        const char *argv[] = {
192✔
4081
                NULL, /* Leave this empty, execute_directory() will fill something in */
4082
                m->lookup_paths.generator,
192✔
4083
                m->lookup_paths.generator_early,
192✔
4084
                m->lookup_paths.generator_late,
192✔
4085
                NULL,
4086
        };
4087

4088
        BLOCK_WITH_UMASK(0022);
384✔
4089
        return execute_directories(
192✔
4090
                        "generators",
4091
                        (const char* const*) paths,
4092
                        DEFAULT_TIMEOUT_USEC,
4093
                        /* callbacks= */ NULL, /* callback_args= */ NULL,
4094
                        (char**) argv,
4095
                        ge,
4096
                        EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID | EXEC_DIR_WARN_WORLD_WRITABLE);
4097
}
4098

4099
static int manager_run_generators(Manager *m) {
768✔
4100
        ForkFlags flags = FORK_RESET_SIGNALS | FORK_WAIT | FORK_NEW_MOUNTNS | FORK_MOUNTNS_SLAVE;
768✔
4101
        _cleanup_strv_free_ char **paths = NULL;
768✔
4102
        int r;
768✔
4103

4104
        assert(m);
768✔
4105

4106
        if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
768✔
4107
                return 0;
4108

4109
        paths = generator_binary_paths(m->runtime_scope);
274✔
4110
        if (!paths)
274✔
4111
                return log_oom();
×
4112

4113
        if (!generator_path_any(paths))
274✔
4114
                return 0;
4115

4116
        r = lookup_paths_mkdir_generator(&m->lookup_paths);
274✔
4117
        if (r < 0) {
274✔
4118
                log_error_errno(r, "Failed to create generator directories: %m");
×
4119
                goto finish;
×
4120
        }
4121

4122
        /* If we are the system manager, we fork and invoke the generators in a sanitized mount namespace. If
4123
         * we are the user manager, let's just execute the generators directly. We might not have the
4124
         * necessary privileges, and the system manager has already mounted /tmp/ and everything else for us.
4125
         */
4126
        if (MANAGER_IS_USER(m)) {
274✔
4127
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
192✔
4128
                goto finish;
192✔
4129
        }
4130

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

4136
        r = pidref_safe_fork("(sd-gens)", flags, /* ret= */ NULL);
82✔
4137
        if (r == 0) {
82✔
4138
                r = manager_execute_generators(m, paths, /* remount_ro= */ true);
×
4139
                _exit(r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE);
×
4140
        }
4141
        if (r < 0) {
82✔
4142
                if (!ERRNO_IS_PRIVILEGE(r) && r != -EINVAL) {
×
4143
                        log_error_errno(r, "Failed to fork off sandboxing environment for executing generators: %m");
×
4144
                        goto finish;
×
4145
                }
4146

4147
                /* Failed to fork with new mount namespace? Maybe, running in a container environment with
4148
                 * seccomp or without capability.
4149
                 *
4150
                 * We also allow -EINVAL to allow running without CLONE_NEWNS.
4151
                 *
4152
                 * Also, when running on non-native userland architecture via systemd-nspawn and
4153
                 * qemu-user-static QEMU-emulator, clone() with CLONE_NEWNS fails with EINVAL, see
4154
                 * https://github.com/systemd/systemd/issues/28901.
4155
                 */
4156
                log_debug_errno(r,
×
4157
                                "Failed to fork off sandboxing environment for executing generators. "
4158
                                "Falling back to execute generators without sandboxing: %m");
4159
                r = manager_execute_generators(m, paths, /* remount_ro= */ false);
×
4160
        }
4161

4162
finish:
82✔
4163
        lookup_paths_trim_generator(&m->lookup_paths);
274✔
4164
        return r;
4165
}
4166

4167
int manager_transient_environment_add(Manager *m, char **plus) {
274✔
4168
        char **a;
274✔
4169

4170
        assert(m);
274✔
4171

4172
        if (strv_isempty(plus))
274✔
4173
                return 0;
274✔
4174

4175
        a = strv_env_merge(m->transient_environment, plus);
82✔
4176
        if (!a)
82✔
4177
                return log_oom();
×
4178

4179
        sanitize_environment(a);
82✔
4180

4181
        return strv_free_and_replace(m->transient_environment, a);
82✔
4182
}
4183

4184
int manager_client_environment_modify(
190✔
4185
                Manager *m,
4186
                char **minus,
4187
                char **plus) {
4188

4189
        char **a = NULL, **b = NULL, **l;
190✔
4190

4191
        assert(m);
190✔
4192

4193
        if (strv_isempty(minus) && strv_isempty(plus))
190✔
4194
                return 0;
4195

4196
        l = m->client_environment;
190✔
4197

4198
        if (!strv_isempty(minus)) {
190✔
4199
                a = strv_env_delete(l, 1, minus);
1✔
4200
                if (!a)
1✔
4201
                        return -ENOMEM;
4202

4203
                l = a;
4204
        }
4205

4206
        if (!strv_isempty(plus)) {
190✔
4207
                b = strv_env_merge(l, plus);
189✔
4208
                if (!b) {
189✔
4209
                        strv_free(a);
×
4210
                        return -ENOMEM;
×
4211
                }
4212

4213
                l = b;
4214
        }
4215

4216
        if (m->client_environment != l)
190✔
4217
                strv_free(m->client_environment);
190✔
4218

4219
        if (a != l)
190✔
4220
                strv_free(a);
189✔
4221
        if (b != l)
190✔
4222
                strv_free(b);
1✔
4223

4224
        m->client_environment = sanitize_environment(l);
190✔
4225
        return 0;
190✔
4226
}
4227

4228
int manager_get_effective_environment(Manager *m, char ***ret) {
22,394✔
4229
        char **l;
22,394✔
4230

4231
        assert(m);
22,394✔
4232
        assert(ret);
22,394✔
4233

4234
        l = strv_env_merge(m->transient_environment, m->client_environment);
22,394✔
4235
        if (!l)
22,394✔
4236
                return -ENOMEM;
4237

4238
        *ret = l;
22,394✔
4239
        return 0;
22,394✔
4240
}
4241

4242
int manager_set_unit_defaults(Manager *m, const UnitDefaults *defaults) {
274✔
4243
        _cleanup_free_ char *label = NULL;
274✔
4244
        struct rlimit *rlimit[_RLIMIT_MAX];
274✔
4245
        int r;
274✔
4246

4247
        assert(m);
274✔
4248
        assert(defaults);
274✔
4249

4250
        if (streq_ptr(defaults->smack_process_label, "/"))
274✔
4251
                label = NULL;
4252
        else  {
4253
                const char *l = defaults->smack_process_label;
274✔
4254
#ifdef SMACK_DEFAULT_PROCESS_LABEL
4255
                if (!l)
4256
                        l = SMACK_DEFAULT_PROCESS_LABEL;
4257
#endif
4258
                if (l) {
274✔
4259
                        label = strdup(l);
×
4260
                        if (!label)
×
4261
                                return -ENOMEM;
4262
                } else
4263
                        label = NULL;
4264
        }
4265

4266
        r = rlimit_copy_all(rlimit, defaults->rlimit);
274✔
4267
        if (r < 0)
274✔
4268
                return r;
4269

4270
        m->defaults.std_output = defaults->std_output;
274✔
4271
        m->defaults.std_error = defaults->std_error;
274✔
4272

4273
        m->defaults.restart_usec = defaults->restart_usec;
274✔
4274
        m->defaults.timeout_start_usec = defaults->timeout_start_usec;
274✔
4275
        m->defaults.timeout_stop_usec = defaults->timeout_stop_usec;
274✔
4276
        m->defaults.timeout_abort_usec = defaults->timeout_abort_usec;
274✔
4277
        m->defaults.timeout_abort_set = defaults->timeout_abort_set;
274✔
4278
        m->defaults.device_timeout_usec = defaults->device_timeout_usec;
274✔
4279

4280
        m->defaults.restrict_suid_sgid = defaults->restrict_suid_sgid;
274✔
4281

4282
        m->defaults.start_limit = defaults->start_limit;
274✔
4283

4284
        m->defaults.memory_accounting = defaults->memory_accounting;
274✔
4285
        m->defaults.io_accounting = defaults->io_accounting;
274✔
4286
        m->defaults.tasks_accounting = defaults->tasks_accounting;
274✔
4287
        m->defaults.ip_accounting = defaults->ip_accounting;
274✔
4288

4289
        m->defaults.tasks_max = defaults->tasks_max;
274✔
4290
        m->defaults.timer_accuracy_usec = defaults->timer_accuracy_usec;
274✔
4291

4292
        m->defaults.oom_policy = defaults->oom_policy;
274✔
4293
        m->defaults.oom_score_adjust = defaults->oom_score_adjust;
274✔
4294
        m->defaults.oom_score_adjust_set = defaults->oom_score_adjust_set;
274✔
4295

4296
        m->defaults.memory_pressure_watch = defaults->memory_pressure_watch;
274✔
4297
        m->defaults.memory_pressure_threshold_usec = defaults->memory_pressure_threshold_usec;
274✔
4298

4299
        free_and_replace(m->defaults.smack_process_label, label);
274✔
4300
        rlimit_free_all(m->defaults.rlimit);
274✔
4301
        memcpy(m->defaults.rlimit, rlimit, sizeof(struct rlimit*) * _RLIMIT_MAX);
274✔
4302

4303
        return 0;
274✔
4304
}
4305

4306
void manager_recheck_dbus(Manager *m) {
80,987✔
4307
        assert(m);
80,987✔
4308

4309
        /* Connects to the bus if the dbus service and socket are running. If we are running in user mode
4310
         * this is all it does. In system mode we'll also connect to the system bus (which will most likely
4311
         * just reuse the connection of the API bus). That's because the system bus after all runs as service
4312
         * of the system instance, while in the user instance we can assume it's already there. */
4313

4314
        if (MANAGER_IS_RELOADING(m))
80,987✔
4315
                return; /* don't check while we are reloading… */
4316

4317
        if (manager_dbus_is_running(m, false)) {
73,336✔
4318
                (void) bus_init_api(m);
6,688✔
4319

4320
                if (MANAGER_IS_SYSTEM(m))
6,688✔
4321
                        (void) bus_init_system(m);
4,745✔
4322
        } else {
4323
                bus_done_api(m);
66,648✔
4324

4325
                if (MANAGER_IS_SYSTEM(m))
66,648✔
4326
                        bus_done_system(m);
9,637✔
4327
        }
4328
}
4329

4330
static bool manager_journal_is_running(Manager *m) {
16,366✔
4331
        Unit *u;
16,366✔
4332

4333
        assert(m);
16,366✔
4334

4335
        if (MANAGER_IS_TEST_RUN(m))
16,366✔
4336
                return false;
4337

4338
        /* If we are the user manager we can safely assume that the journal is up */
4339
        if (!MANAGER_IS_SYSTEM(m))
16,366✔
4340
                return true;
4341

4342
        /* Check that the socket is not only up, but in RUNNING state */
4343
        u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
15,680✔
4344
        if (!u)
15,680✔
4345
                return false;
4346
        if (SOCKET(u)->state != SOCKET_RUNNING)
15,680✔
4347
                return false;
4348

4349
        /* Similar, check if the daemon itself is fully up, too */
4350
        u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
12,221✔
4351
        if (!u)
12,221✔
4352
                return false;
4353
        if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)) || SERVICE(u)->state == SERVICE_EXITED)
12,221✔
4354
                return false;
510✔
4355

4356
        return true;
4357
}
4358

4359
void disable_printk_ratelimit(void) {
18✔
4360
        /* Disable kernel's printk ratelimit.
4361
         *
4362
         * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
4363
         * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
4364
         * setting takes precedence. */
4365
        int r;
18✔
4366

4367
        r = sysctl_write("kernel/printk_devkmsg", "on");
18✔
4368
        if (r < 0)
18✔
4369
                log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
×
4370
}
18✔
4371

4372
void manager_recheck_journal(Manager *m) {
80,987✔
4373

4374
        assert(m);
80,987✔
4375

4376
        /* Don't bother with this unless we are in the special situation of being PID 1 */
4377
        if (getpid_cached() != 1)
80,987✔
4378
                return;
4379

4380
        /* Don't check this while we are reloading, things might still change */
4381
        if (MANAGER_IS_RELOADING(m))
21,411✔
4382
                return;
4383

4384
        /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If
4385
         * the journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we
4386
         * might trigger an activation ourselves we can't fulfill. */
4387
        log_set_prohibit_ipc(!manager_journal_is_running(m));
13,905✔
4388
        log_open();
13,905✔
4389
}
4390

4391
static ShowStatus manager_get_show_status(Manager *m) {
12,794✔
4392
        assert(m);
12,794✔
4393

4394
        if (MANAGER_IS_USER(m))
12,794✔
4395
                return _SHOW_STATUS_INVALID;
4396

4397
        if (m->show_status_overridden != _SHOW_STATUS_INVALID)
12,793✔
4398
                return m->show_status_overridden;
4399

4400
        return m->show_status;
12,789✔
4401
}
4402

4403
bool manager_get_show_status_on(Manager *m) {
12,792✔
4404
        assert(m);
12,792✔
4405

4406
        return show_status_on(manager_get_show_status(m));
12,792✔
4407
}
4408

4409
static void set_show_status_marker(bool b) {
63✔
4410
        if (b)
63✔
4411
                (void) touch("/run/systemd/show-status");
×
4412
        else
4413
                (void) unlink("/run/systemd/show-status");
63✔
4414
}
63✔
4415

4416
void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
274✔
4417
        assert(m);
274✔
4418
        assert(reason);
274✔
4419
        assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
274✔
4420

4421
        if (MANAGER_IS_USER(m))
274✔
4422
                return;
4423

4424
        if (mode == m->show_status)
82✔
4425
                return;
4426

4427
        if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
53✔
4428
                bool enabled;
53✔
4429

4430
                enabled = show_status_on(mode);
53✔
4431
                log_debug("%s (%s) showing of status (%s).",
106✔
4432
                          enabled ? "Enabling" : "Disabling",
4433
                          strna(show_status_to_string(mode)),
4434
                          reason);
4435

4436
                set_show_status_marker(enabled);
53✔
4437
        }
4438

4439
        m->show_status = mode;
53✔
4440
}
4441

4442
void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
10✔
4443
        assert(m);
10✔
4444
        assert(mode < _SHOW_STATUS_MAX);
10✔
4445

4446
        if (MANAGER_IS_USER(m))
10✔
4447
                return;
4448

4449
        if (mode == m->show_status_overridden)
10✔
4450
                return;
4451

4452
        m->show_status_overridden = mode;
10✔
4453

4454
        if (mode == _SHOW_STATUS_INVALID)
10✔
4455
                mode = m->show_status;
5✔
4456

4457
        log_debug("%s (%s) showing of status (%s).",
15✔
4458
                  m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
4459
                  strna(show_status_to_string(mode)),
4460
                  reason);
4461

4462
        set_show_status_marker(show_status_on(mode));
10✔
4463
}
4464

4465
const char* manager_get_confirm_spawn(Manager *m) {
2,474✔
4466
        static int last_errno = 0;
2,474✔
4467
        struct stat st;
2,474✔
4468
        int r;
2,474✔
4469

4470
        assert(m);
2,474✔
4471

4472
        /* Here's the deal: we want to test the validity of the console but don't want
4473
         * PID1 to go through the whole console process which might block. But we also
4474
         * want to warn the user only once if something is wrong with the console so we
4475
         * cannot do the sanity checks after spawning our children. So here we simply do
4476
         * really basic tests to hopefully trap common errors.
4477
         *
4478
         * If the console suddenly disappear at the time our children will really it
4479
         * then they will simply fail to acquire it and a positive answer will be
4480
         * assumed. New children will fall back to /dev/console though.
4481
         *
4482
         * Note: TTYs are devices that can come and go any time, and frequently aren't
4483
         * available yet during early boot (consider a USB rs232 dongle...). If for any
4484
         * reason the configured console is not ready, we fall back to the default
4485
         * console. */
4486

4487
        if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
2,474✔
4488
                return m->confirm_spawn;
2,474✔
4489

4490
        if (stat(m->confirm_spawn, &st) < 0) {
×
4491
                r = -errno;
×
4492
                goto fail;
×
4493
        }
4494

4495
        if (!S_ISCHR(st.st_mode)) {
×
4496
                r = -ENOTTY;
×
4497
                goto fail;
×
4498
        }
4499

4500
        last_errno = 0;
×
4501
        return m->confirm_spawn;
×
4502

4503
fail:
×
4504
        if (last_errno != r)
×
4505
                last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
×
4506

4507
        return "/dev/console";
4508
}
4509

4510
void manager_set_first_boot(Manager *m, bool b) {
439✔
4511
        assert(m);
439✔
4512

4513
        if (!MANAGER_IS_SYSTEM(m))
439✔
4514
                return;
4515

4516
        if (m->first_boot != (int) b) {
54✔
4517
                if (b)
54✔
4518
                        (void) touch("/run/systemd/first-boot");
19✔
4519
                else
4520
                        (void) unlink("/run/systemd/first-boot");
35✔
4521
        }
4522

4523
        m->first_boot = b;
54✔
4524
}
4525

4526
void manager_disable_confirm_spawn(void) {
×
4527
        (void) touch("/run/systemd/confirm_spawn_disabled");
×
4528
}
×
4529

4530
static bool manager_should_show_status(Manager *m, StatusType type) {
17,739✔
4531
        assert(m);
17,739✔
4532

4533
        if (!MANAGER_IS_SYSTEM(m))
17,739✔
4534
                return false;
4535

4536
        if (m->no_console_output)
8,019✔
4537
                return false;
4538

4539
        if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
7,954✔
4540
                return false;
4541

4542
        /* If we cannot find out the status properly, just proceed. */
4543
        if (type < STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
7,954✔
4544
                return false;
4545

4546
        if (type >= STATUS_TYPE_NOTICE && manager_get_show_status(m) != SHOW_STATUS_NO)
7,954✔
4547
                return true;
4548

4549
        return manager_get_show_status_on(m);
7,952✔
4550
}
4551

4552
void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
17,739✔
4553
        va_list ap;
17,739✔
4554

4555
        /* If m is NULL, assume we're after shutdown and let the messages through. */
4556

4557
        if (m && !manager_should_show_status(m, type))
17,739✔
4558
                return;
17,737✔
4559

4560
        /* XXX We should totally drop the check for ephemeral here
4561
         * and thus effectively make 'Type=idle' pointless. */
4562
        if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
2✔
4563
                return;
4564

4565
        va_start(ap, format);
2✔
4566
        status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
4✔
4567
        va_end(ap);
2✔
4568
}
4569

4570
Set* manager_get_units_needing_mounts_for(Manager *m, const char *path, UnitMountDependencyType t) {
19,786✔
4571
        assert(m);
19,786✔
4572
        assert(path);
19,786✔
4573
        assert(t >= 0 && t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX);
19,786✔
4574

4575
        if (path_equal(path, "/"))
19,786✔
4576
                path = "";
876✔
4577

4578
        return hashmap_get(m->units_needing_mounts_for[t], path);
19,786✔
4579
}
4580

4581
int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
169,967✔
4582
        unsigned size;
169,967✔
4583
        int r;
169,967✔
4584

4585
        assert(m);
169,967✔
4586
        assert(u->manager == m);
169,967✔
4587

4588
        size = set_size(m->failed_units);
169,967✔
4589

4590
        if (failed) {
169,967✔
4591
                r = set_ensure_put(&m->failed_units, NULL, u);
280✔
4592
                if (r < 0)
280✔
4593
                        return log_oom();
×
4594
        } else
4595
                (void) set_remove(m->failed_units, u);
169,687✔
4596

4597
        if (set_size(m->failed_units) != size)
169,967✔
4598
                bus_manager_send_change_signal(m);
560✔
4599

4600
        return 0;
4601
}
4602

4603
ManagerState manager_state(Manager *m) {
509,371✔
4604
        Unit *u;
509,371✔
4605

4606
        assert(m);
509,371✔
4607

4608
        /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4609
        u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
509,371✔
4610
        if (u && unit_active_or_pending(u))
509,371✔
4611
                return MANAGER_STOPPING;
4612

4613
        /* Did we ever finish booting? If not then we are still starting up */
4614
        if (!MANAGER_IS_FINISHED(m)) {
396,724✔
4615

4616
                u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
360,185✔
4617
                if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
360,185✔
4618
                        return MANAGER_INITIALIZING;
289,604✔
4619

4620
                return MANAGER_STARTING;
4621
        }
4622

4623
        if (MANAGER_IS_SYSTEM(m)) {
36,539✔
4624
                /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4625
                u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
6✔
4626
                if (u && unit_active_or_pending(u))
6✔
4627
                        return MANAGER_MAINTENANCE;
4628

4629
                u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
6✔
4630
                if (u && unit_active_or_pending(u))
6✔
4631
                        return MANAGER_MAINTENANCE;
4632
        }
4633

4634
        /* Are there any failed units or ordering cycles? If so, we are in degraded mode */
4635
        if (!set_isempty(m->failed_units) || !set_isempty(m->transactions_with_cycle))
36,539✔
4636
                return MANAGER_DEGRADED;
2,514✔
4637

4638
        return MANAGER_RUNNING;
4639
}
4640

4641
static void manager_unref_uid_internal(
904✔
4642
                Hashmap *uid_refs,
4643
                uid_t uid,
4644
                bool destroy_now,
4645
                int (*_clean_ipc)(uid_t uid)) {
4646

4647
        uint32_t c, n;
904✔
4648

4649
        assert(uid_is_valid(uid));
904✔
4650
        assert(_clean_ipc);
904✔
4651

4652
        /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the
4653
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity rules.
4654
         *
4655
         * We store a hashmap where the key is the UID/GID and the value is a 32-bit reference counter, whose
4656
         * highest bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last
4657
         * reference to the UID/GID is dropped. The flag is set to on, once at least one reference from a
4658
         * unit where RemoveIPC= is set is added on a UID/GID. It is reset when the UID's/GID's reference
4659
         * counter drops to 0 again. */
4660

4661
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
904✔
4662
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
904✔
4663

4664
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
904✔
4665
                return;
4666

4667
        c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
677✔
4668

4669
        n = c & ~DESTROY_IPC_FLAG;
677✔
4670
        assert(n > 0);
677✔
4671
        n--;
677✔
4672

4673
        if (destroy_now && n == 0) {
677✔
4674
                hashmap_remove(uid_refs, UID_TO_PTR(uid));
131✔
4675

4676
                if (c & DESTROY_IPC_FLAG) {
131✔
4677
                        log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
9✔
4678
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4679
                                  uid);
4680
                        (void) _clean_ipc(uid);
6✔
4681
                }
4682
        } else {
4683
                c = n | (c & DESTROY_IPC_FLAG);
546✔
4684
                assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
546✔
4685
        }
4686
}
4687

4688
void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
450✔
4689
        manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
450✔
4690
}
450✔
4691

4692
void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
454✔
4693
        manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
454✔
4694
}
454✔
4695

4696
static int manager_ref_uid_internal(
904✔
4697
                Hashmap **uid_refs,
4698
                uid_t uid,
4699
                bool clean_ipc) {
4700

4701
        uint32_t c, n;
904✔
4702
        int r;
904✔
4703

4704
        assert(uid_refs);
904✔
4705
        assert(uid_is_valid(uid));
904✔
4706

4707
        /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the
4708
         * assumption that uid_t and gid_t are actually defined the same way, with the same validity
4709
         * rules. */
4710

4711
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
904✔
4712
        assert_cc(UID_INVALID == (uid_t) GID_INVALID);
904✔
4713

4714
        if (uid == 0) /* We don't keep track of root, and will never destroy it */
904✔
4715
                return 0;
4716

4717
        r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
677✔
4718
        if (r < 0)
677✔
4719
                return r;
4720

4721
        c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
677✔
4722

4723
        n = c & ~DESTROY_IPC_FLAG;
677✔
4724
        n++;
677✔
4725

4726
        if (n & DESTROY_IPC_FLAG) /* check for overflow */
677✔
4727
                return -EOVERFLOW;
4728

4729
        c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
677✔
4730

4731
        return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
677✔
4732
}
4733

4734
int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
450✔
4735
        return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
450✔
4736
}
4737

4738
int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
454✔
4739
        return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
454✔
4740
}
4741

4742
static void manager_vacuum_uid_refs_internal(
1,536✔
4743
                Hashmap *uid_refs,
4744
                int (*_clean_ipc)(uid_t uid)) {
4745

4746
        void *p, *k;
1,536✔
4747

4748
        assert(_clean_ipc);
1,536✔
4749

4750
        HASHMAP_FOREACH_KEY(p, k, uid_refs) {
3,338✔
4751
                uint32_t c, n;
266✔
4752
                uid_t uid;
266✔
4753

4754
                uid = PTR_TO_UID(k);
266✔
4755
                c = PTR_TO_UINT32(p);
266✔
4756

4757
                n = c & ~DESTROY_IPC_FLAG;
266✔
4758
                if (n > 0)
266✔
4759
                        continue;
266✔
4760

4761
                if (c & DESTROY_IPC_FLAG) {
×
4762
                        log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
×
4763
                                  _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4764
                                  uid);
4765
                        (void) _clean_ipc(uid);
×
4766
                }
4767

4768
                assert_se(hashmap_remove(uid_refs, k) == p);
1,802✔
4769
        }
4770
}
1,536✔
4771

4772
static void manager_vacuum_uid_refs(Manager *m) {
768✔
4773
        manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
768✔
4774
}
768✔
4775

4776
static void manager_vacuum_gid_refs(Manager *m) {
768✔
4777
        manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
768✔
4778
}
768✔
4779

4780
static void manager_vacuum(Manager *m) {
768✔
4781
        assert(m);
768✔
4782

4783
        /* Release any dynamic users no longer referenced */
4784
        dynamic_user_vacuum(m, true);
768✔
4785

4786
        /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4787
        manager_vacuum_uid_refs(m);
768✔
4788
        manager_vacuum_gid_refs(m);
768✔
4789

4790
        /* Release any runtimes no longer referenced */
4791
        exec_shared_runtime_vacuum(m);
768✔
4792
}
768✔
4793

4794
static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
255✔
4795
        struct buffer {
255✔
4796
                uid_t uid;
4797
                gid_t gid;
4798
                char unit_name[UNIT_NAME_MAX+1];
4799
        } _packed_ buffer;
4800

4801
        Manager *m = ASSERT_PTR(userdata);
255✔
4802
        ssize_t l;
255✔
4803
        size_t n;
255✔
4804
        Unit *u;
255✔
4805

4806
        assert(source);
255✔
4807

4808
        /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the
4809
         * resulting UID/GID in a datagram. We parse the datagram here and pass it off to the unit, so that
4810
         * it can add a reference to the UID/GID so that it can destroy the UID/GID's IPC objects when the
4811
         * reference counter drops to 0. */
4812

4813
        l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
255✔
4814
        if (l < 0) {
255✔
4815
                if (ERRNO_IS_TRANSIENT(errno))
×
4816
                        return 0;
255✔
4817

4818
                return log_error_errno(errno, "Failed to read from user lookup fd: %m");
×
4819
        }
4820

4821
        if ((size_t) l <= offsetof(struct buffer, unit_name)) {
255✔
4822
                log_warning("Received too short user lookup message, ignoring.");
×
4823
                return 0;
×
4824
        }
4825

4826
        if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
255✔
4827
                log_warning("Received too long user lookup message, ignoring.");
×
4828
                return 0;
×
4829
        }
4830

4831
        if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
255✔
4832
                log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
×
4833
                return 0;
×
4834
        }
4835

4836
        n = (size_t) l - offsetof(struct buffer, unit_name);
255✔
4837
        if (memchr(buffer.unit_name, 0, n)) {
255✔
4838
                log_warning("Received lookup message with embedded NUL character, ignoring.");
×
4839
                return 0;
×
4840
        }
4841

4842
        buffer.unit_name[n] = 0;
255✔
4843
        u = manager_get_unit(m, buffer.unit_name);
255✔
4844
        if (!u) {
255✔
4845
                log_debug("Got user lookup message but unit doesn't exist, ignoring.");
×
4846
                return 0;
×
4847
        }
4848

4849
        log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
255✔
4850

4851
        unit_notify_user_lookup(u, buffer.uid, buffer.gid);
255✔
4852
        return 0;
4853
}
4854

4855
static int manager_dispatch_handoff_timestamp_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2,448✔
4856
        Manager *m = ASSERT_PTR(userdata);
2,448✔
4857
        usec_t ts[2] = {};
2,448✔
4858
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
2,448✔
4859
        struct msghdr msghdr = {
2,448✔
4860
                .msg_iov = &IOVEC_MAKE(ts, sizeof(ts)),
2,448✔
4861
                .msg_iovlen = 1,
4862
                .msg_control = &control,
4863
                .msg_controllen = sizeof(control),
4864
        };
4865
        ssize_t n;
2,448✔
4866

4867
        assert(source);
2,448✔
4868

4869
        n = recvmsg_safe(m->handoff_timestamp_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
2,448✔
4870
        if (ERRNO_IS_NEG_TRANSIENT(n))
2,448✔
4871
                return 0; /* Spurious wakeup, try again */
2,448✔
4872
        if (n == -ECHRNG) {
2,448✔
4873
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4874
                return 0;
×
4875
        }
4876
        if (n == -EXFULL) {
2,448✔
4877
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4878
                return 0;
×
4879
        }
4880
        if (n < 0)
2,448✔
4881
                return log_error_errno(n, "Failed to receive handoff timestamp message: %m");
×
4882

4883
        cmsg_close_all(&msghdr);
2,448✔
4884

4885
        if (n != sizeof(ts)) {
2,448✔
4886
                log_warning("Got handoff timestamp message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(ts));
×
4887
                return 0;
×
4888
        }
4889

4890
        struct ucred *ucred = CMSG_FIND_DATA(&msghdr, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
2,448✔
4891
        if (!ucred || !pid_is_valid(ucred->pid)) {
2,448✔
4892
                log_warning("Received handoff timestamp message without valid credentials. Ignoring.");
×
4893
                return 0;
×
4894
        }
4895

4896
        log_debug("Got handoff timestamp event for PID " PID_FMT ".", ucred->pid);
2,448✔
4897

4898
        _cleanup_free_ Unit **units = NULL;
2,448✔
4899
        int n_units = manager_get_units_for_pidref(m, &PIDREF_MAKE_FROM_PID(ucred->pid), &units);
2,448✔
4900
        if (n_units < 0) {
2,448✔
4901
                log_warning_errno(n_units, "Unable to determine units for PID " PID_FMT ", ignoring: %m", ucred->pid);
×
4902
                return 0;
×
4903
        }
4904
        if (n_units == 0) {
2,448✔
4905
                log_debug("Got handoff timestamp for process " PID_FMT " we are not interested in, ignoring.", ucred->pid);
×
4906
                return 0;
×
4907
        }
4908

4909
        dual_timestamp dt = {
2,448✔
4910
                .realtime = ts[0],
2,448✔
4911
                .monotonic = ts[1],
2,448✔
4912
        };
4913

4914
        FOREACH_ARRAY(u, units, n_units) {
7,344✔
4915
                if (!UNIT_VTABLE(*u)->notify_handoff_timestamp)
4,896✔
4916
                        continue;
95✔
4917

4918
                UNIT_VTABLE(*u)->notify_handoff_timestamp(*u, ucred, &dt);
4,801✔
4919
        }
4920

4921
        return 0;
4922
}
4923

4924
static int manager_dispatch_pidref_transport_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3✔
4925
        Manager *m = ASSERT_PTR(userdata);
3✔
4926
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL, parent_pidref = PIDREF_NULL;
3✔
4927
        _cleanup_close_ int child_pidfd = -EBADF, parent_pidfd = -EBADF;
6✔
4928
        struct ucred *ucred = NULL;
3✔
4929
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int)) * 2) control;
3✔
4930
        pid_t child_pid = 0; /* silence false-positive warning by coverity */
3✔
4931
        struct msghdr msghdr = {
3✔
4932
                .msg_iov = &IOVEC_MAKE(&child_pid, sizeof(child_pid)),
3✔
4933
                .msg_iovlen = 1,
4934
                .msg_control = &control,
4935
                .msg_controllen = sizeof(control),
4936
        };
4937
        struct cmsghdr *cmsg;
3✔
4938
        ssize_t n;
3✔
4939
        int r;
3✔
4940

4941
        assert(source);
3✔
4942

4943
        /* Server expects:
4944
         * - Parent PID in ucreds enabled via SO_PASSCRED
4945
         * - Parent PIDFD in SCM_PIDFD message enabled via SO_PASSPIDFD
4946
         * - Child PIDFD in SCM_RIGHTS in message body
4947
         * - Child PID in message IOV
4948
         *
4949
         * SO_PASSPIDFD may not be supported by the kernel (it is supported since v6.5) so we fall back to
4950
         * using parent PID from ucreds and accept some raciness. */
4951
        n = recvmsg_safe(m->pidref_transport_fds[0], &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
3✔
4952
        if (ERRNO_IS_NEG_TRANSIENT(n))
6✔
4953
                return 0; /* Spurious wakeup, try again */
4954
        if (n == -ECHRNG) {
3✔
4955
                log_warning_errno(n, "Got message with truncated control data (unexpected fds sent?), ignoring.");
×
4956
                return 0;
×
4957
        }
4958
        if (n == -EXFULL) {
3✔
4959
                log_warning_errno(n, "Got message with truncated payload data, ignoring.");
×
4960
                return 0;
×
4961
        }
4962
        if (n < 0)
3✔
4963
                return log_error_errno(n, "Failed to receive pidref message: %m");
×
4964

4965
        if (n != sizeof(child_pid)) {
3✔
4966
                log_warning("Got pidref message of unexpected size %zi (expected %zu), ignoring.", n, sizeof(child_pid));
×
4967
                return 0;
×
4968
        }
4969

4970
        CMSG_FOREACH(cmsg, &msghdr) {
24✔
4971
                if (cmsg->cmsg_level != SOL_SOCKET)
9✔
4972
                        continue;
×
4973

4974
                if (cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
9✔
4975
                        assert(!ucred);
3✔
4976
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
3✔
4977
                } else if (cmsg->cmsg_type == SCM_PIDFD) {
6✔
4978
                        assert(parent_pidfd < 0);
3✔
4979
                        parent_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4980
                } else if (cmsg->cmsg_type == SCM_RIGHTS) {
3✔
4981
                        assert(child_pidfd < 0);
3✔
4982
                        child_pidfd = *CMSG_TYPED_DATA(cmsg, int);
3✔
4983
                }
4984
        }
4985

4986
        /* Verify and set parent pidref. */
4987
        if (!ucred || !pid_is_valid(ucred->pid)) {
3✔
4988
                log_warning("Received pidref message without valid credentials. Ignoring.");
×
4989
                return 0;
×
4990
        }
4991

4992
        /* Need to handle kernels without SO_PASSPIDFD where SCM_PIDFD will not be set. */
4993
        if (parent_pidfd >= 0)
3✔
4994
                r = pidref_set_pidfd_consume(&parent_pidref, TAKE_FD(parent_pidfd));
3✔
4995
        else
4996
                r = pidref_set_pid(&parent_pidref, ucred->pid);
×
4997
        if (r < 0) {
3✔
4998
                if (r == -ESRCH)
×
4999
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5000
                else
5001
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5002
                return 0;
×
5003
        }
5004

5005
        if (parent_pidref.pid != ucred->pid) {
3✔
5006
                assert(parent_pidref.fd >= 0);
×
5007
                log_warning("Got SCM_PIDFD for parent process " PID_FMT " but got SCM_CREDENTIALS for parent process " PID_FMT ". Ignoring.",
×
5008
                            parent_pidref.pid, ucred->pid);
5009
                return 0;
×
5010
        }
5011

5012
        /* Verify and set child pidref. */
5013
        if (!pid_is_valid(child_pid)) {
3✔
5014
                log_warning("Received pidref message without valid child PID. Ignoring.");
×
5015
                return 0;
×
5016
        }
5017

5018
        /* Need to handle kernels without PIDFD support. */
5019
        if (child_pidfd >= 0)
3✔
5020
                r = pidref_set_pidfd_consume(&child_pidref, TAKE_FD(child_pidfd));
3✔
5021
        else
5022
                r = pidref_set_pid(&child_pidref, child_pid);
×
5023
        if (r < 0) {
3✔
5024
                if (r == -ESRCH)
×
5025
                        log_debug_errno(r, "PidRef child process died before message is processed. Ignoring.");
×
5026
                else
5027
                        log_warning_errno(r, "Failed to pin pidref child process, ignoring message: %m");
×
5028
                return 0;
×
5029
        }
5030

5031
        if (child_pidref.pid != child_pid) {
3✔
5032
                assert(child_pidref.fd >= 0);
×
5033
                log_warning("Got SCM_RIGHTS for child process " PID_FMT " but PID in IOV message is " PID_FMT ". Ignoring.",
×
5034
                            child_pidref.pid, child_pid);
5035
                return 0;
×
5036
        }
5037

5038
        log_debug("Got pidref event with parent PID " PID_FMT " and child PID " PID_FMT ".", parent_pidref.pid, child_pidref.pid);
3✔
5039

5040
        /* Try finding cgroup of parent process. But if parent process exited and we're not using PIDFD, this could return NULL.
5041
         * Then fall back to finding cgroup of the child process. */
5042
        Unit *u = manager_get_unit_by_pidref_cgroup(m, &parent_pidref);
3✔
5043
        if (!u)
3✔
5044
                u = manager_get_unit_by_pidref_cgroup(m, &child_pidref);
×
5045
        if (!u) {
×
5046
                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);
×
5047
                return 0;
×
5048
        }
5049

5050
        if (!UNIT_VTABLE(u)->notify_pidref) {
3✔
5051
                log_unit_warning(u, "Received pidref event from unexpected unit type '%s'.", unit_type_to_string(u->type));
×
5052
                return 0;
×
5053
        }
5054

5055
        UNIT_VTABLE(u)->notify_pidref(u, &parent_pidref, &child_pidref);
3✔
5056

5057
        return 0;
5058
}
5059

5060
void manager_ref_console(Manager *m) {
82✔
5061
        assert(m);
82✔
5062

5063
        m->n_on_console++;
82✔
5064
}
82✔
5065

5066
void manager_unref_console(Manager *m) {
82✔
5067

5068
        assert(m->n_on_console > 0);
82✔
5069
        m->n_on_console--;
82✔
5070

5071
        if (m->n_on_console == 0)
82✔
5072
                m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
68✔
5073
}
82✔
5074

5075
void manager_override_log_level(Manager *m, int level) {
4✔
5076
        _cleanup_free_ char *s = NULL;
8✔
5077
        assert(m);
4✔
5078

5079
        if (!m->log_level_overridden) {
4✔
5080
                m->original_log_level = log_get_max_level();
1✔
5081
                m->log_level_overridden = true;
1✔
5082
        }
5083

5084
        (void) log_level_to_string_alloc(level, &s);
4✔
5085
        log_info("Setting log level to %s.", strna(s));
4✔
5086

5087
        log_set_max_level(level);
4✔
5088
}
4✔
5089

5090
void manager_restore_original_log_level(Manager *m) {
×
5091
        _cleanup_free_ char *s = NULL;
×
5092
        assert(m);
×
5093

5094
        if (!m->log_level_overridden)
×
5095
                return;
×
5096

5097
        (void) log_level_to_string_alloc(m->original_log_level, &s);
×
5098
        log_info("Restoring log level to original (%s).", strna(s));
×
5099

5100
        log_set_max_level(m->original_log_level);
×
5101
        m->log_level_overridden = false;
×
5102
}
5103

5104
void manager_override_log_target(Manager *m, LogTarget target) {
4✔
5105
        assert(m);
4✔
5106

5107
        if (!m->log_target_overridden) {
4✔
5108
                m->original_log_target = log_get_target();
1✔
5109
                m->log_target_overridden = true;
1✔
5110
        }
5111

5112
        log_info("Setting log target to %s.", log_target_to_string(target));
4✔
5113
        log_set_target(target);
4✔
5114
}
4✔
5115

5116
void manager_restore_original_log_target(Manager *m) {
×
5117
        assert(m);
×
5118

5119
        if (!m->log_target_overridden)
×
5120
                return;
5121

5122
        log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
×
5123

5124
        log_set_target(m->original_log_target);
×
5125
        m->log_target_overridden = false;
×
5126
}
5127

5128
ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
3,434✔
5129
        if (in_initrd() &&
3,434✔
5130
            s >= MANAGER_TIMESTAMP_SECURITY_START &&
66✔
5131
            s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
5132
                return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
66✔
5133
        return s;
5134
}
5135

5136
int manager_allocate_idle_pipe(Manager *m) {
20,806✔
5137
        int r;
20,806✔
5138

5139
        assert(m);
20,806✔
5140

5141
        if (m->idle_pipe[0] >= 0) {
20,806✔
5142
                assert(m->idle_pipe[1] >= 0);
17,168✔
5143
                assert(m->idle_pipe[2] >= 0);
17,168✔
5144
                assert(m->idle_pipe[3] >= 0);
17,168✔
5145
                return 0;
5146
        }
5147

5148
        assert(m->idle_pipe[1] < 0);
3,638✔
5149
        assert(m->idle_pipe[2] < 0);
3,638✔
5150
        assert(m->idle_pipe[3] < 0);
3,638✔
5151

5152
        r = RET_NERRNO(pipe2(m->idle_pipe + 0, O_NONBLOCK|O_CLOEXEC));
3,638✔
5153
        if (r < 0)
×
5154
                return r;
5155

5156
        r = RET_NERRNO(pipe2(m->idle_pipe + 2, O_NONBLOCK|O_CLOEXEC));
3,638✔
5157
        if (r < 0) {
×
5158
                safe_close_pair(m->idle_pipe + 0);
×
5159
                return r;
×
5160
        }
5161

5162
        return 1;
5163
}
5164

5165
void unit_defaults_init(UnitDefaults *defaults, RuntimeScope scope) {
1,202✔
5166
        assert(defaults);
1,202✔
5167
        assert(scope >= 0);
1,202✔
5168
        assert(scope < _RUNTIME_SCOPE_MAX);
1,202✔
5169

5170
        *defaults = (UnitDefaults) {
2,404✔
5171
                .std_output = EXEC_OUTPUT_JOURNAL,
5172
                .std_error = EXEC_OUTPUT_INHERIT,
5173
                .restart_usec = DEFAULT_RESTART_USEC,
5174
                .timeout_start_usec = manager_default_timeout(scope),
1,202✔
5175
                .timeout_stop_usec = manager_default_timeout(scope),
1,202✔
5176
                .timeout_abort_usec = manager_default_timeout(scope),
1,202✔
5177
                .timeout_abort_set = false,
5178
                .device_timeout_usec = manager_default_timeout(scope),
1,202✔
5179
                .start_limit = { DEFAULT_START_LIMIT_INTERVAL, DEFAULT_START_LIMIT_BURST },
5180

5181
                .memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
5182
                .io_accounting = false,
5183
                .tasks_accounting = true,
5184
                .ip_accounting = false,
5185

5186
                .tasks_max = DEFAULT_TASKS_MAX,
5187
                .timer_accuracy_usec = 1 * USEC_PER_MINUTE,
5188

5189
                .memory_pressure_watch = CGROUP_PRESSURE_WATCH_AUTO,
5190
                .memory_pressure_threshold_usec = MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC,
5191

5192
                .oom_policy = OOM_STOP,
5193
                .oom_score_adjust_set = false,
5194
        };
5195
}
1,202✔
5196

5197
void unit_defaults_done(UnitDefaults *defaults) {
1,202✔
5198
        assert(defaults);
1,202✔
5199

5200
        defaults->smack_process_label = mfree(defaults->smack_process_label);
1,202✔
5201
        rlimit_free_all(defaults->rlimit);
1,202✔
5202
}
1,202✔
5203

5204
LogTarget manager_get_executor_log_target(Manager *m) {
2,472✔
5205
        assert(m);
2,472✔
5206

5207
        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
5208
        if (!MANAGER_IS_TEST_RUN(m) && !manager_journal_is_running(m))
2,472✔
5209
                return LOG_TARGET_KMSG;
5210

5211
        return log_get_target();
2,030✔
5212
}
5213

5214
void manager_log_caller(Manager *manager, PidRef *caller, const char *method) {
63✔
5215
        _cleanup_free_ char *comm = NULL;
126✔
5216

5217
        assert(manager);
63✔
5218
        assert(pidref_is_set(caller));
63✔
5219
        assert(method);
63✔
5220

5221
        (void) pidref_get_comm(caller, &comm);
63✔
5222
        Unit *caller_unit = manager_get_unit_by_pidref(manager, caller);
63✔
5223

5224
        log_notice("%s requested from client PID " PID_FMT "%s%s%s%s%s%s...",
63✔
5225
                   method, caller->pid,
5226
                   comm ? " ('" : "", strempty(comm), comm ? "')" : "",
5227
                   caller_unit ? " (unit " : "", caller_unit ? caller_unit->id : "", caller_unit ? ")" : "");
5228
}
63✔
5229

5230
static const char* const manager_state_table[_MANAGER_STATE_MAX] = {
5231
        [MANAGER_INITIALIZING] = "initializing",
5232
        [MANAGER_STARTING]     = "starting",
5233
        [MANAGER_RUNNING]      = "running",
5234
        [MANAGER_DEGRADED]     = "degraded",
5235
        [MANAGER_MAINTENANCE]  = "maintenance",
5236
        [MANAGER_STOPPING]     = "stopping",
5237
};
5238

5239
DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
82✔
5240

5241
static const char* const manager_objective_table[_MANAGER_OBJECTIVE_MAX] = {
5242
        [MANAGER_OK]          = "ok",
5243
        [MANAGER_EXIT]        = "exit",
5244
        [MANAGER_RELOAD]      = "reload",
5245
        [MANAGER_REEXECUTE]   = "reexecute",
5246
        [MANAGER_REBOOT]      = "reboot",
5247
        [MANAGER_SOFT_REBOOT] = "soft-reboot",
5248
        [MANAGER_POWEROFF]    = "poweroff",
5249
        [MANAGER_HALT]        = "halt",
5250
        [MANAGER_KEXEC]       = "kexec",
5251
        [MANAGER_SWITCH_ROOT] = "switch-root",
5252
};
5253

5254
DEFINE_STRING_TABLE_LOOKUP(manager_objective, ManagerObjective);
141✔
5255

5256
static const char* const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
5257
        [MANAGER_TIMESTAMP_FIRMWARE]                 = "firmware",
5258
        [MANAGER_TIMESTAMP_LOADER]                   = "loader",
5259
        [MANAGER_TIMESTAMP_KERNEL]                   = "kernel",
5260
        [MANAGER_TIMESTAMP_INITRD]                   = "initrd",
5261
        [MANAGER_TIMESTAMP_USERSPACE]                = "userspace",
5262
        [MANAGER_TIMESTAMP_FINISH]                   = "finish",
5263
        [MANAGER_TIMESTAMP_SECURITY_START]           = "security-start",
5264
        [MANAGER_TIMESTAMP_SECURITY_FINISH]          = "security-finish",
5265
        [MANAGER_TIMESTAMP_GENERATORS_START]         = "generators-start",
5266
        [MANAGER_TIMESTAMP_GENERATORS_FINISH]        = "generators-finish",
5267
        [MANAGER_TIMESTAMP_UNITS_LOAD_START]         = "units-load-start",
5268
        [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH]        = "units-load-finish",
5269
        [MANAGER_TIMESTAMP_UNITS_LOAD]               = "units-load",
5270
        [MANAGER_TIMESTAMP_INITRD_SECURITY_START]    = "initrd-security-start",
5271
        [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH]   = "initrd-security-finish",
5272
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_START]  = "initrd-generators-start",
5273
        [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
5274
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START]  = "initrd-units-load-start",
5275
        [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
5276
        [MANAGER_TIMESTAMP_SHUTDOWN_START]           = "shutdown-start",
5277
};
5278

5279
DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
4,928✔
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