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

systemd / systemd / 14630481637

23 Apr 2025 07:04PM UTC coverage: 72.178% (-0.002%) from 72.18%
14630481637

push

github

DaanDeMeyer
mkosi: Run clangd within the tools tree instead of the build container

Running within the build sandbox has a number of disadvantages:
- We have a separate clangd cache for each distribution/release combo
- It requires to build the full image before clangd can be used
- It breaks every time the image becomes out of date and requires a
  rebuild
- We can't look at system headers as we don't have the knowledge to map
  them from inside the build sandbox to the corresponding path on the host

Instead, let's have mkosi.clangd run clangd within the tools tree. We
already require building systemd for both the host and the target anyway,
and all the dependencies to build systemd are installed in the tools tree
already for that, as well as clangd since it's installed together with the
other clang tooling we install in the tools tree. Unlike the previous approach,
this approach only requires the mkosi tools tree to be built upfront, which has
a much higher chance of not invalidating its cache. We can also trivially map
system header lookups from within the sandbox to the path within mkosi.tools
on the host so that starts working as well.

297054 of 411557 relevant lines covered (72.18%)

686269.58 hits per line

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

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

3
#include <errno.h>
4
#include <math.h>
5
#include <sys/stat.h>
6
#include <sys/types.h>
7
#include <unistd.h>
8

9
#include "sd-messages.h"
10

11
#include "alloc-util.h"
12
#include "async.h"
13
#include "bus-common-errors.h"
14
#include "bus-error.h"
15
#include "bus-kernel.h"
16
#include "bus-util.h"
17
#include "chase.h"
18
#include "constants.h"
19
#include "dbus-service.h"
20
#include "dbus-unit.h"
21
#include "devnum-util.h"
22
#include "env-util.h"
23
#include "escape.h"
24
#include "exec-credential.h"
25
#include "exit-status.h"
26
#include "fd-util.h"
27
#include "fileio.h"
28
#include "format-util.h"
29
#include "io-util.h"
30
#include "load-dropin.h"
31
#include "load-fragment.h"
32
#include "log.h"
33
#include "manager.h"
34
#include "missing_audit.h"
35
#include "mount-util.h"
36
#include "open-file.h"
37
#include "parse-util.h"
38
#include "path-util.h"
39
#include "pidfd-util.h"
40
#include "process-util.h"
41
#include "random-util.h"
42
#include "selinux-util.h"
43
#include "serialize.h"
44
#include "service.h"
45
#include "signal-util.h"
46
#include "special.h"
47
#include "stdio-util.h"
48
#include "string-table.h"
49
#include "string-util.h"
50
#include "strv.h"
51
#include "transaction.h"
52
#include "unit-name.h"
53
#include "unit.h"
54
#include "utf8.h"
55

56
#define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
57

58
static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
59
        [SERVICE_DEAD]                       = UNIT_INACTIVE,
60
        [SERVICE_CONDITION]                  = UNIT_ACTIVATING,
61
        [SERVICE_START_PRE]                  = UNIT_ACTIVATING,
62
        [SERVICE_START]                      = UNIT_ACTIVATING,
63
        [SERVICE_START_POST]                 = UNIT_ACTIVATING,
64
        [SERVICE_RUNNING]                    = UNIT_ACTIVE,
65
        [SERVICE_EXITED]                     = UNIT_ACTIVE,
66
        [SERVICE_RELOAD]                     = UNIT_RELOADING,
67
        [SERVICE_RELOAD_SIGNAL]              = UNIT_RELOADING,
68
        [SERVICE_RELOAD_NOTIFY]              = UNIT_RELOADING,
69
        [SERVICE_MOUNTING]                   = UNIT_REFRESHING,
70
        [SERVICE_STOP]                       = UNIT_DEACTIVATING,
71
        [SERVICE_STOP_WATCHDOG]              = UNIT_DEACTIVATING,
72
        [SERVICE_STOP_SIGTERM]               = UNIT_DEACTIVATING,
73
        [SERVICE_STOP_SIGKILL]               = UNIT_DEACTIVATING,
74
        [SERVICE_STOP_POST]                  = UNIT_DEACTIVATING,
75
        [SERVICE_FINAL_WATCHDOG]             = UNIT_DEACTIVATING,
76
        [SERVICE_FINAL_SIGTERM]              = UNIT_DEACTIVATING,
77
        [SERVICE_FINAL_SIGKILL]              = UNIT_DEACTIVATING,
78
        [SERVICE_FAILED]                     = UNIT_FAILED,
79
        [SERVICE_DEAD_BEFORE_AUTO_RESTART]   = UNIT_INACTIVE,
80
        [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
81
        [SERVICE_DEAD_RESOURCES_PINNED]      = UNIT_INACTIVE,
82
        [SERVICE_AUTO_RESTART]               = UNIT_ACTIVATING,
83
        [SERVICE_AUTO_RESTART_QUEUED]        = UNIT_ACTIVATING,
84
        [SERVICE_CLEANING]                   = UNIT_MAINTENANCE,
85
};
86

87
/* For Type=idle we never want to delay any other jobs, hence we
88
 * consider idle jobs active as soon as we start working on them */
89
static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
90
        [SERVICE_DEAD]                       = UNIT_INACTIVE,
91
        [SERVICE_CONDITION]                  = UNIT_ACTIVE,
92
        [SERVICE_START_PRE]                  = UNIT_ACTIVE,
93
        [SERVICE_START]                      = UNIT_ACTIVE,
94
        [SERVICE_START_POST]                 = UNIT_ACTIVE,
95
        [SERVICE_RUNNING]                    = UNIT_ACTIVE,
96
        [SERVICE_EXITED]                     = UNIT_ACTIVE,
97
        [SERVICE_RELOAD]                     = UNIT_RELOADING,
98
        [SERVICE_RELOAD_SIGNAL]              = UNIT_RELOADING,
99
        [SERVICE_RELOAD_NOTIFY]              = UNIT_RELOADING,
100
        [SERVICE_MOUNTING]                   = UNIT_REFRESHING,
101
        [SERVICE_STOP]                       = UNIT_DEACTIVATING,
102
        [SERVICE_STOP_WATCHDOG]              = UNIT_DEACTIVATING,
103
        [SERVICE_STOP_SIGTERM]               = UNIT_DEACTIVATING,
104
        [SERVICE_STOP_SIGKILL]               = UNIT_DEACTIVATING,
105
        [SERVICE_STOP_POST]                  = UNIT_DEACTIVATING,
106
        [SERVICE_FINAL_WATCHDOG]             = UNIT_DEACTIVATING,
107
        [SERVICE_FINAL_SIGTERM]              = UNIT_DEACTIVATING,
108
        [SERVICE_FINAL_SIGKILL]              = UNIT_DEACTIVATING,
109
        [SERVICE_FAILED]                     = UNIT_FAILED,
110
        [SERVICE_DEAD_BEFORE_AUTO_RESTART]   = UNIT_INACTIVE,
111
        [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
112
        [SERVICE_DEAD_RESOURCES_PINNED]      = UNIT_INACTIVE,
113
        [SERVICE_AUTO_RESTART]               = UNIT_ACTIVATING,
114
        [SERVICE_AUTO_RESTART_QUEUED]        = UNIT_ACTIVATING,
115
        [SERVICE_CLEANING]                   = UNIT_MAINTENANCE,
116
};
117

118
static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
119
static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
120
static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
121
static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
122

123
static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
124
static void service_enter_reload_by_notify(Service *s);
125

126
static bool SERVICE_STATE_WITH_MAIN_PROCESS(ServiceState state) {
7,855✔
127
        return IN_SET(state,
7,855✔
128
                      SERVICE_START, SERVICE_START_POST,
129
                      SERVICE_RUNNING,
130
                      SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
131
                      SERVICE_MOUNTING,
132
                      SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
133
                      SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL);
134
}
135

136
static bool SERVICE_STATE_WITH_CONTROL_PROCESS(ServiceState state) {
7,203✔
137
        return IN_SET(state,
7,203✔
138
                      SERVICE_CONDITION,
139
                      SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
140
                      SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
141
                      SERVICE_MOUNTING,
142
                      SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
143
                      SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
144
                      SERVICE_CLEANING);
145
}
146

147
static void service_init(Unit *u) {
13,648✔
148
        Service *s = SERVICE(u);
13,648✔
149

150
        assert(u);
×
151
        assert(u->load_state == UNIT_STUB);
13,648✔
152

153
        s->timeout_start_usec = u->manager->defaults.timeout_start_usec;
13,648✔
154
        s->timeout_stop_usec = u->manager->defaults.timeout_stop_usec;
13,648✔
155
        s->timeout_abort_usec = u->manager->defaults.timeout_abort_usec;
13,648✔
156
        s->timeout_abort_set = u->manager->defaults.timeout_abort_set;
13,648✔
157
        s->restart_usec = u->manager->defaults.restart_usec;
13,648✔
158
        s->restart_max_delay_usec = USEC_INFINITY;
13,648✔
159
        s->runtime_max_usec = USEC_INFINITY;
13,648✔
160
        s->type = _SERVICE_TYPE_INVALID;
13,648✔
161
        s->socket_fd = -EBADF;
13,648✔
162
        s->stdin_fd = s->stdout_fd = s->stderr_fd = -EBADF;
13,648✔
163
        s->guess_main_pid = true;
13,648✔
164
        s->main_pid = PIDREF_NULL;
13,648✔
165
        s->control_pid = PIDREF_NULL;
13,648✔
166
        s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
13,648✔
167

168
        s->exec_context.keyring_mode = MANAGER_IS_SYSTEM(u->manager) ?
13,648✔
169
                EXEC_KEYRING_PRIVATE : EXEC_KEYRING_INHERIT;
13,648✔
170

171
        s->notify_access_override = _NOTIFY_ACCESS_INVALID;
13,648✔
172

173
        s->watchdog_original_usec = USEC_INFINITY;
13,648✔
174

175
        s->oom_policy = _OOM_POLICY_INVALID;
13,648✔
176
        s->reload_begin_usec = USEC_INFINITY;
13,648✔
177
        s->reload_signal = SIGHUP;
13,648✔
178

179
        s->fd_store_preserve_mode = EXEC_PRESERVE_RESTART;
13,648✔
180
}
13,648✔
181

182
static void service_unwatch_control_pid(Service *s) {
31,367✔
183
        assert(s);
31,367✔
184
        unit_unwatch_pidref_done(UNIT(s), &s->control_pid);
31,367✔
185
}
31,367✔
186

187
static void service_unwatch_main_pid(Service *s) {
21,353✔
188
        assert(s);
21,353✔
189
        unit_unwatch_pidref_done(UNIT(s), &s->main_pid);
21,353✔
190
}
21,353✔
191

192
static void service_unwatch_pid_file(Service *s) {
20,852✔
193
        assert(s);
20,852✔
194

195
        if (!s->pid_file_pathspec)
20,852✔
196
                return;
197

198
        log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
×
199
        path_spec_unwatch(s->pid_file_pathspec);
×
200
        path_spec_done(s->pid_file_pathspec);
×
201
        s->pid_file_pathspec = mfree(s->pid_file_pathspec);
×
202
}
203

204
static int service_set_main_pidref(Service *s, PidRef pidref_consume, const dual_timestamp *start_timestamp) {
2,366✔
205
        _cleanup_(pidref_done) PidRef pidref = pidref_consume;
×
206
        int r;
2,366✔
207

208
        assert(s);
2,366✔
209

210
        /* Takes ownership of the specified pidref on both success and failure. */
211

212
        if (!pidref_is_set(&pidref))
4,732✔
213
                return -ESRCH;
214

215
        if (pidref.pid <= 1)
2,366✔
216
                return -EINVAL;
217

218
        if (pidref_is_self(&pidref))
2,366✔
219
                return -EINVAL;
220

221
        if (s->main_pid_known && pidref_equal(&s->main_pid, &pidref))
2,366✔
222
                return 0;
223

224
        if (!pidref_equal(&s->main_pid, &pidref)) {
2,366✔
225
                service_unwatch_main_pid(s);
2,366✔
226

227
                dual_timestamp pid_start_time;
2,366✔
228

229
                if (!start_timestamp) {
2,366✔
230
                        usec_t t;
657✔
231

232
                        if (pidref_get_start_time(&pidref, &t) >= 0)
657✔
233
                                start_timestamp = dual_timestamp_from_boottime(&pid_start_time, t);
657✔
234
                }
235

236
                exec_status_start(&s->main_exec_status, pidref.pid, start_timestamp);
2,366✔
237
        }
238

239
        s->main_pid = TAKE_PIDREF(pidref);
2,366✔
240
        s->main_pid_known = true;
2,366✔
241

242
        r = pidref_is_my_child(&s->main_pid);
2,366✔
243
        if (r < 0)
2,366✔
244
                log_unit_warning_errno(UNIT(s), r, "Can't determine if process "PID_FMT" is our child, assuming it is not: %m", s->main_pid.pid);
×
245
        else if (r == 0) // FIXME: Supervise through pidfd here
2,366✔
246
                log_unit_warning(UNIT(s), "Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", s->main_pid.pid);
2✔
247
        s->main_pid_alien = r <= 0;
2,366✔
248

249
        return 0;
2,366✔
250
}
251

252
void service_release_socket_fd(Service *s) {
14,810✔
253
        assert(s);
14,810✔
254

255
        if (s->socket_fd < 0 && !UNIT_ISSET(s->accept_socket) && !s->socket_peer)
14,810✔
256
                return;
257

258
        log_unit_debug(UNIT(s), "Closing connection socket.");
2✔
259

260
        /* Undo the effect of service_set_socket_fd(). */
261

262
        s->socket_fd = asynchronous_close(s->socket_fd);
2✔
263

264
        if (UNIT_ISSET(s->accept_socket)) {
2✔
265
                socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
2✔
266
                unit_ref_unset(&s->accept_socket);
2✔
267
        }
268

269
        s->socket_peer = socket_peer_unref(s->socket_peer);
2✔
270
}
271

272
static void service_override_notify_access(Service *s, NotifyAccess notify_access_override) {
×
273
        assert(s);
×
274

275
        s->notify_access_override = notify_access_override;
×
276

277
        log_unit_debug(UNIT(s), "notify_access=%s", notify_access_to_string(s->notify_access));
×
278
        log_unit_debug(UNIT(s), "notify_access_override=%s", notify_access_to_string(s->notify_access_override));
×
279
}
×
280

281
static void service_stop_watchdog(Service *s) {
21,109✔
282
        assert(s);
21,109✔
283

284
        s->watchdog_event_source = sd_event_source_disable_unref(s->watchdog_event_source);
21,109✔
285
        s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
21,109✔
286
}
21,109✔
287

288
static void service_start_watchdog(Service *s) {
2,736✔
289
        usec_t watchdog_usec;
2,736✔
290
        int r;
2,736✔
291

292
        assert(s);
2,736✔
293

294
        watchdog_usec = service_get_watchdog_usec(s);
2,736✔
295
        if (!timestamp_is_set(watchdog_usec)) {
2,736✔
296
                service_stop_watchdog(s);
1,855✔
297
                return;
1,855✔
298
        }
299

300
        if (s->watchdog_event_source) {
881✔
301
                r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
512✔
302
                if (r < 0) {
256✔
303
                        log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
×
304
                        return;
×
305
                }
306

307
                r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
256✔
308
        } else {
309
                r = sd_event_add_time(
625✔
310
                                UNIT(s)->manager->event,
625✔
311
                                &s->watchdog_event_source,
312
                                CLOCK_MONOTONIC,
313
                                usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
314
                                service_dispatch_watchdog, s);
315
                if (r < 0) {
625✔
316
                        log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
×
317
                        return;
×
318
                }
319

320
                (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
625✔
321

322
                /* Let's process everything else which might be a sign
323
                 * of living before we consider a service died. */
324
                r = sd_event_source_set_priority(s->watchdog_event_source, EVENT_PRIORITY_SERVICE_WATCHDOG);
625✔
325
        }
326
        if (r < 0)
881✔
327
                log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
×
328
}
329

330
usec_t service_restart_usec_next(Service *s) {
1,087✔
331
        unsigned n_restarts_next;
1,087✔
332

333
        assert(s);
1,087✔
334

335
        /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
336
         * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
337
         * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
338
        n_restarts_next = s->n_restarts + (s->state == SERVICE_AUTO_RESTART_QUEUED ? 0 : 1);
1,087✔
339

340
        if (n_restarts_next <= 1 ||
1,087✔
341
            s->restart_steps == 0 ||
6✔
342
            s->restart_usec == 0 ||
×
343
            s->restart_max_delay_usec == USEC_INFINITY ||
×
344
            s->restart_usec >= s->restart_max_delay_usec)
345
                return s->restart_usec;
1,087✔
346

347
        if (n_restarts_next > s->restart_steps)
×
348
                return s->restart_max_delay_usec;
349

350
        /* Enforced in service_verify() and above */
351
        assert(s->restart_max_delay_usec > s->restart_usec);
×
352

353
        /* r_i / r_0 = (r_n / r_0) ^ (i / n)
354
         * where,
355
         *   r_0 : initial restart usec (s->restart_usec),
356
         *   r_i : i-th restart usec (value),
357
         *   r_n : maximum restart usec (s->restart_max_delay_usec),
358
         *   i : index of the next step (n_restarts_next - 1)
359
         *   n : num maximum steps (s->restart_steps) */
360
        return (usec_t) (s->restart_usec * powl((long double) s->restart_max_delay_usec / s->restart_usec,
×
361
                                                (long double) (n_restarts_next - 1) / s->restart_steps));
×
362
}
363

364
static void service_extend_event_source_timeout(Service *s, sd_event_source *source, usec_t extended) {
×
365
        usec_t current;
×
366
        int r;
×
367

368
        assert(s);
×
369

370
        /* Extends the specified event source timer to at least the specified time, unless it is already later
371
         * anyway. */
372

373
        if (!source)
×
374
                return;
×
375

376
        r = sd_event_source_get_time(source, &current);
×
377
        if (r < 0) {
×
378
                const char *desc;
×
379
                (void) sd_event_source_get_description(s->timer_event_source, &desc);
×
380
                log_unit_warning_errno(UNIT(s), r, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc));
×
381
                return;
×
382
        }
383

384
        if (current >= extended) /* Current timeout is already longer, ignore this. */
×
385
                return;
386

387
        r = sd_event_source_set_time(source, extended);
×
388
        if (r < 0) {
×
389
                const char *desc;
×
390
                (void) sd_event_source_get_description(s->timer_event_source, &desc);
×
391
                log_unit_warning_errno(UNIT(s), r, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc));
×
392
        }
393
}
394

395
static void service_extend_timeout(Service *s, usec_t extend_timeout_usec) {
×
396
        usec_t extended;
×
397

398
        assert(s);
×
399

400
        if (!timestamp_is_set(extend_timeout_usec))
×
401
                return;
402

403
        extended = usec_add(now(CLOCK_MONOTONIC), extend_timeout_usec);
×
404

405
        service_extend_event_source_timeout(s, s->timer_event_source, extended);
×
406
        service_extend_event_source_timeout(s, s->watchdog_event_source, extended);
×
407
}
408

409
static void service_reset_watchdog(Service *s) {
2,140✔
410
        assert(s);
2,140✔
411

412
        dual_timestamp_now(&s->watchdog_timestamp);
2,140✔
413
        service_start_watchdog(s);
2,140✔
414
}
2,140✔
415

416
static void service_override_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
×
417
        assert(s);
×
418

419
        s->watchdog_override_enable = true;
×
420
        s->watchdog_override_usec = watchdog_override_usec;
×
421
        service_reset_watchdog(s);
×
422

423
        log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
×
424
        log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
×
425
}
×
426

427
static ServiceFDStore* service_fd_store_unlink(ServiceFDStore *fs) {
2,359✔
428
        if (!fs)
2,359✔
429
                return NULL;
430

431
        if (fs->service) {
2,359✔
432
                assert(fs->service->n_fd_store > 0);
2,359✔
433
                LIST_REMOVE(fd_store, fs->service->fd_store, fs);
2,359✔
434
                fs->service->n_fd_store--;
2,359✔
435
        }
436

437
        sd_event_source_disable_unref(fs->event_source);
2,359✔
438

439
        free(fs->fdname);
2,359✔
440
        asynchronous_close(fs->fd);
2,359✔
441
        return mfree(fs);
2,359✔
442
}
443

444
DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore*, service_fd_store_unlink);
2,359✔
445

446
static void service_release_fd_store(Service *s) {
14,801✔
447
        assert(s);
14,801✔
448

449
        if (!s->fd_store)
14,801✔
450
                return;
451

452
        log_unit_debug(UNIT(s), "Releasing all stored fds.");
175✔
453

454
        while (s->fd_store)
1,264✔
455
                service_fd_store_unlink(s->fd_store);
1,089✔
456

457
        assert(s->n_fd_store == 0);
175✔
458
}
459

460
static void service_release_extra_fds(Service *s) {
14,810✔
461
        assert(s);
14,810✔
462

463
        if (!s->extra_fds)
14,810✔
464
                return;
465

466
        log_unit_debug(UNIT(s), "Releasing extra file descriptors.");
1✔
467

468
        FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
3✔
469
                asynchronous_close(i->fd);
2✔
470
                free(i->fdname);
2✔
471
        }
472

473
        s->extra_fds = mfree(s->extra_fds);
1✔
474
        s->n_extra_fds = 0;
1✔
475
}
476

477
static void service_release_stdio_fd(Service *s) {
14,810✔
478
        assert(s);
14,810✔
479

480
        if (s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
14,810✔
481
                return;
482

483
        log_unit_debug(UNIT(s), "Releasing stdin/stdout/stderr file descriptors.");
81✔
484

485
        s->stdin_fd = asynchronous_close(s->stdin_fd);
81✔
486
        s->stdout_fd = asynchronous_close(s->stdout_fd);
81✔
487
        s->stderr_fd = asynchronous_close(s->stderr_fd);
81✔
488
}
489

490
static void service_done(Unit *u) {
13,649✔
491
        Service *s = ASSERT_PTR(SERVICE(u));
13,649✔
492

493
        open_file_free_many(&s->open_files);
13,649✔
494

495
        s->pid_file = mfree(s->pid_file);
13,649✔
496
        s->status_text = mfree(s->status_text);
13,649✔
497
        s->status_bus_error = mfree(s->status_bus_error);
13,649✔
498
        s->status_varlink_error = mfree(s->status_varlink_error);
13,649✔
499

500
        s->exec_runtime = exec_runtime_free(s->exec_runtime);
13,649✔
501

502
        exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
13,649✔
503
        s->control_command = NULL;
13,649✔
504
        s->main_command = NULL;
13,649✔
505

506
        exit_status_set_free(&s->restart_prevent_status);
13,649✔
507
        exit_status_set_free(&s->restart_force_status);
13,649✔
508
        exit_status_set_free(&s->success_status);
13,649✔
509

510
        /* This will leak a process, but at least no memory or any of our resources */
511
        service_unwatch_main_pid(s);
13,649✔
512
        service_unwatch_control_pid(s);
13,649✔
513
        service_unwatch_pid_file(s);
13,649✔
514

515
        if (s->bus_name)  {
13,649✔
516
                unit_unwatch_bus_name(u, s->bus_name);
966✔
517
                s->bus_name = mfree(s->bus_name);
966✔
518
        }
519

520
        s->usb_function_descriptors = mfree(s->usb_function_descriptors);
13,649✔
521
        s->usb_function_strings = mfree(s->usb_function_strings);
13,649✔
522

523
        service_stop_watchdog(s);
13,649✔
524

525
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
13,649✔
526
        s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
13,649✔
527

528
        s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
13,649✔
529

530
        service_release_socket_fd(s);
13,649✔
531
        service_release_stdio_fd(s);
13,649✔
532
        service_release_fd_store(s);
13,649✔
533
        service_release_extra_fds(s);
13,649✔
534

535
        s->mount_request = sd_bus_message_unref(s->mount_request);
13,649✔
536
}
13,649✔
537

538
static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
1,261✔
539
        ServiceFDStore *fs = ASSERT_PTR(userdata);
1,261✔
540

541
        assert(e);
1,261✔
542

543
        /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
544
        log_unit_debug(UNIT(fs->service),
2,522✔
545
                       "Received %s on stored fd %d (%s), closing.",
546
                       revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
547
                       fs->fd, strna(fs->fdname));
548
        service_fd_store_unlink(fs);
1,261✔
549
        return 0;
1,261✔
550
}
551

552
static int service_add_fd_store(Service *s, int fd_in, const char *name, bool do_poll) {
2,359✔
553
        _cleanup_(service_fd_store_unlinkp) ServiceFDStore *fs = NULL;
2,359✔
554
        _cleanup_(asynchronous_closep) int fd = ASSERT_FD(fd_in);
4,718✔
555
        struct stat st;
2,359✔
556
        int r;
2,359✔
557

558
        /* fd is always consumed even if the function fails. */
559

560
        assert(s);
2,359✔
561

562
        if (fstat(fd, &st) < 0)
2,359✔
563
                return -errno;
×
564

565
        log_unit_debug(UNIT(s), "Trying to stash fd for dev=" DEVNUM_FORMAT_STR "/inode=%" PRIu64,
2,359✔
566
                       DEVNUM_FORMAT_VAL(st.st_dev), (uint64_t) st.st_ino);
567

568
        if (s->n_fd_store >= s->n_fd_store_max)
2,359✔
569
                /* Our store is full.  Use this errno rather than E[NM]FILE to distinguish from the case
570
                 * where systemd itself hits the file limit. */
571
                return log_unit_debug_errno(UNIT(s), SYNTHETIC_ERRNO(EXFULL), "Hit fd store limit.");
×
572

573
        LIST_FOREACH(fd_store, i, s->fd_store) {
16,076✔
574
                r = same_fd(i->fd, fd);
13,717✔
575
                if (r < 0)
13,717✔
576
                        return r;
577
                if (r > 0) {
13,717✔
578
                        log_unit_debug(UNIT(s), "Suppressing duplicate fd %i in fd store.", fd);
×
579
                        return 0; /* fd already included */
×
580
                }
581
        }
582

583
        fs = new(ServiceFDStore, 1);
2,359✔
584
        if (!fs)
2,359✔
585
                return -ENOMEM;
586

587
        *fs = (ServiceFDStore) {
4,718✔
588
                .fd = TAKE_FD(fd),
2,359✔
589
                .do_poll = do_poll,
590
                .fdname = strdup(name ?: "stored"),
2,359✔
591
        };
592

593
        if (!fs->fdname)
2,359✔
594
                return -ENOMEM;
595

596
        if (do_poll) {
2,359✔
597
                r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fs->fd, 0, on_fd_store_io, fs);
2,359✔
598
                if (r < 0 && r != -EPERM) /* EPERM indicates fds that aren't pollable, which is OK */
2,359✔
599
                        return r;
600
                if (r >= 0)
2,359✔
601
                        (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
2,347✔
602
        }
603

604
        log_unit_debug(UNIT(s), "Added fd %i (%s) to fd store.", fs->fd, fs->fdname);
2,359✔
605

606
        fs->service = s;
2,359✔
607
        LIST_PREPEND(fd_store, s->fd_store, TAKE_PTR(fs));
2,359✔
608
        s->n_fd_store++;
2,359✔
609

610
        return 1; /* fd newly stored */
2,359✔
611
}
612

613
static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name, bool do_poll) {
1,484✔
614
        int r;
1,484✔
615

616
        assert(s);
1,484✔
617

618
        for (;;) {
2,968✔
619
                int fd;
2,968✔
620

621
                fd = fdset_steal_first(fds);
2,968✔
622
                if (fd < 0)
2,968✔
623
                        break;
624

625
                r = service_add_fd_store(s, fd, name, do_poll);
1,484✔
626
                if (r == -EXFULL)
1,484✔
627
                        return log_unit_warning_errno(UNIT(s), r,
×
628
                                                      "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
629
                                                      s->n_fd_store_max);
630
                if (r < 0)
1,484✔
631
                        return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
×
632
        }
633

634
        return 0;
635
}
636

637
static void service_remove_fd_store(Service *s, const char *name) {
145✔
638
        assert(s);
145✔
639
        assert(name);
145✔
640

641
        LIST_FOREACH(fd_store, fs, s->fd_store) {
268✔
642
                if (!streq(fs->fdname, name))
123✔
643
                        continue;
114✔
644

645
                log_unit_debug(UNIT(s), "Got explicit request to remove fd %i (%s), closing.", fs->fd, name);
9✔
646
                service_fd_store_unlink(fs);
9✔
647
        }
648
}
145✔
649

650
static usec_t service_running_timeout(Service *s) {
1,570✔
651
        usec_t delta = 0;
1,570✔
652

653
        assert(s);
1,570✔
654

655
        if (s->runtime_rand_extra_usec != 0) {
1,570✔
656
                delta = random_u64_range(s->runtime_rand_extra_usec);
×
657
                log_unit_debug(UNIT(s), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta, USEC_PER_SEC));
×
658
        }
659

660
        return usec_add(usec_add(UNIT(s)->active_enter_timestamp.monotonic,
1,572✔
661
                                 s->runtime_max_usec),
662
                        delta);
663
}
664

665
static int service_arm_timer(Service *s, bool relative, usec_t usec) {
5,221✔
666
        assert(s);
5,221✔
667

668
        return unit_arm_timer(UNIT(s), &s->timer_event_source, relative, usec, service_dispatch_timer);
5,221✔
669
}
670

671
static int service_verify(Service *s) {
12,924✔
672
        assert(s);
12,924✔
673
        assert(UNIT(s)->load_state == UNIT_LOADED);
12,924✔
674

675
        for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++)
103,392✔
676
                LIST_FOREACH(command, command, s->exec_command[c]) {
106,725✔
677
                        if (!path_is_absolute(command->path) && !filename_is_valid(command->path))
16,257✔
678
                                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
×
679
                                                            "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
680
                                                            command->path,
681
                                                            service_exec_command_to_string(c));
682
                        if (strv_isempty(command->argv))
32,514✔
683
                                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
×
684
                                                            "Service has an empty argv in %s=. Refusing.",
685
                                                            service_exec_command_to_string(c));
686
                }
687

688
        if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP] &&
12,924✔
689
            UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
393✔
690
                /* FailureAction= only makes sense if one of the start or stop commands is specified.
691
                 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
692
                 * either a command or SuccessAction= are required. */
693

694
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
×
695

696
        if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START])
12,924✔
697
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
×
698

699
        if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START] && UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
12,924✔
700
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= and no SuccessAction= settings and does not have RemainAfterExit=yes set. Refusing.");
×
701

702
        if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next)
12,924✔
703
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
×
704

705
        if (s->type == SERVICE_ONESHOT && IN_SET(s->restart, SERVICE_RESTART_ALWAYS, SERVICE_RESTART_ON_SUCCESS))
12,924✔
706
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has Restart= set to either always or on-success, which isn't allowed for Type=oneshot services. Refusing.");
×
707

708
        if (s->type == SERVICE_ONESHOT && s->exit_type == SERVICE_EXIT_CGROUP)
12,924✔
709
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
×
710

711
        if (s->type == SERVICE_DBUS && !s->bus_name)
12,924✔
712
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
1✔
713

714
        if (s->type == SERVICE_FORKING && exec_needs_pid_namespace(&s->exec_context))
12,923✔
715
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service of Type=forking does not support PrivatePIDs=yes. Refusing.");
1✔
716

717
        if (s->usb_function_descriptors && !s->usb_function_strings)
12,922✔
718
                log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
×
719

720
        if (!s->usb_function_descriptors && s->usb_function_strings)
12,922✔
721
                log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
×
722

723
        if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
12,922✔
724
                log_unit_warning(UNIT(s), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
×
725

726
        if (s->runtime_max_usec == USEC_INFINITY && s->runtime_rand_extra_usec != 0)
12,922✔
727
                log_unit_warning(UNIT(s), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
×
728

729
        if (s->type == SERVICE_SIMPLE && s->exec_command[SERVICE_EXEC_START_POST] && exec_context_has_credentials(&s->exec_context))
12,922✔
730
                log_unit_warning(UNIT(s), "Service uses a combination of Type=simple, ExecStartPost=, and credentials. This could lead to race conditions. Continuing.");
×
731

732
        if (s->restart_max_delay_usec == USEC_INFINITY && s->restart_steps > 0)
12,922✔
733
                log_unit_warning(UNIT(s), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
×
734

735
        if (s->restart_max_delay_usec != USEC_INFINITY && s->restart_steps == 0)
12,922✔
736
                log_unit_warning(UNIT(s), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
×
737

738
        if (s->restart_max_delay_usec < s->restart_usec) {
12,922✔
739
                log_unit_warning(UNIT(s), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
×
740
                s->restart_usec = s->restart_max_delay_usec;
×
741
        }
742

743
        return 0;
744
}
745

746
static int service_add_default_dependencies(Service *s) {
12,924✔
747
        int r;
12,924✔
748

749
        assert(s);
12,924✔
750

751
        if (!UNIT(s)->default_dependencies)
12,924✔
752
                return 0;
753

754
        /* Add a number of automatic dependencies useful for the
755
         * majority of services. */
756

757
        if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
3,142✔
758
                /* First, pull in the really early boot stuff, and
759
                 * require it, so that we fail if we can't acquire
760
                 * it. */
761

762
                r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
2,160✔
763
                if (r < 0)
2,160✔
764
                        return r;
765
        } else {
766

767
                /* In the --user instance there's no sysinit.target,
768
                 * in that case require basic.target instead. */
769

770
                r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
982✔
771
                if (r < 0)
982✔
772
                        return r;
773
        }
774

775
        /* Second, if the rest of the base system is in the same
776
         * transaction, order us after it, but do not pull it in or
777
         * even require it. */
778
        r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
3,142✔
779
        if (r < 0)
3,142✔
780
                return r;
781

782
        /* Third, add us in for normal shutdown. */
783
        return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
3,142✔
784
}
785

786
static void service_fix_stdio(Service *s) {
12,924✔
787
        assert(s);
12,924✔
788

789
        /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
790
         * default value that is subject to automatic overriding triggered by other settings and an explicit
791
         * choice the user can make. We don't distinguish between these cases currently. */
792

793
        if (s->exec_context.std_input == EXEC_INPUT_NULL &&
12,924✔
794
            s->exec_context.stdin_data_size > 0)
12,402✔
795
                s->exec_context.std_input = EXEC_INPUT_DATA;
×
796

797
        if (IN_SET(s->exec_context.std_input,
12,924✔
798
                    EXEC_INPUT_TTY,
799
                    EXEC_INPUT_TTY_FORCE,
800
                    EXEC_INPUT_TTY_FAIL,
801
                    EXEC_INPUT_SOCKET,
802
                    EXEC_INPUT_NAMED_FD))
803
                return;
804

805
        /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
806
         * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
807
         * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
808
         * duplicated for both input and output at the same time (since they then would cause a feedback
809
         * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting.  */
810

811
        if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
12,402✔
812
            s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
813
                s->exec_context.std_error = UNIT(s)->manager->defaults.std_error;
12,018✔
814

815
        if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
12,402✔
816
                s->exec_context.std_output = UNIT(s)->manager->defaults.std_output;
12,194✔
817
}
818

819
static int service_setup_bus_name(Service *s) {
12,924✔
820
        int r;
12,924✔
821

822
        assert(s);
12,924✔
823

824
        /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
825
        if (!s->bus_name)
12,924✔
826
                return 0;
827

828
        if (s->type == SERVICE_DBUS) {
966✔
829
                r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
225✔
830
                if (r < 0)
225✔
831
                        return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
×
832

833
                /* We always want to be ordered against dbus.socket if both are in the transaction. */
834
                r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
225✔
835
                if (r < 0)
225✔
836
                        return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
×
837
        }
838

839
        r = unit_watch_bus_name(UNIT(s), s->bus_name);
966✔
840
        if (r == -EEXIST)
966✔
841
                return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
×
842
        if (r < 0)
966✔
843
                return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
×
844

845
        return 0;
846
}
847

848
static int service_add_extras(Service *s) {
12,924✔
849
        int r;
12,924✔
850

851
        assert(s);
12,924✔
852

853
        if (s->type == _SERVICE_TYPE_INVALID) {
12,924✔
854
                /* Figure out a type automatically */
855
                if (s->bus_name)
2,427✔
856
                        s->type = SERVICE_DBUS;
223✔
857
                else if (exec_context_has_credentials(&s->exec_context))
2,204✔
858
                        s->type = SERVICE_EXEC;
26✔
859
                else if (s->exec_command[SERVICE_EXEC_START])
2,178✔
860
                        s->type = SERVICE_SIMPLE;
1,785✔
861
                else
862
                        s->type = SERVICE_ONESHOT;
393✔
863
        }
864

865
        /* Oneshot services have disabled start timeout by default */
866
        if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
12,924✔
867
                s->timeout_start_usec = USEC_INFINITY;
6,457✔
868

869
        service_fix_stdio(s);
12,924✔
870

871
        r = unit_patch_contexts(UNIT(s));
12,924✔
872
        if (r < 0)
12,924✔
873
                return r;
874

875
        r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
12,924✔
876
        if (r < 0)
12,924✔
877
                return r;
878

879
        r = unit_set_default_slice(UNIT(s));
12,924✔
880
        if (r < 0)
12,924✔
881
                return r;
882

883
        /* If the service needs the notify socket, let's enable it automatically. */
884
        if (s->notify_access == NOTIFY_NONE &&
12,924✔
885
            (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) || s->watchdog_usec > 0 || s->n_fd_store_max > 0))
12,698✔
886
                s->notify_access = NOTIFY_MAIN;
1,989✔
887

888
        /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
889
         * delegation is on, in that case it we assume the payload knows better what to do and can process
890
         * things in a more focused way. */
891
        if (s->oom_policy < 0)
12,924✔
892
                s->oom_policy = s->cgroup_context.delegate ? OOM_CONTINUE : UNIT(s)->manager->defaults.oom_policy;
12,924✔
893

894
        /* Let the kernel do the killing if that's requested. */
895
        s->cgroup_context.memory_oom_group = s->oom_policy == OOM_KILL;
12,924✔
896

897
        r = service_add_default_dependencies(s);
12,924✔
898
        if (r < 0)
12,924✔
899
                return r;
900

901
        r = service_setup_bus_name(s);
12,924✔
902
        if (r < 0)
12,924✔
903
                return r;
×
904

905
        return 0;
906
}
907

908
static int service_load(Unit *u) {
13,750✔
909
        Service *s = ASSERT_PTR(SERVICE(u));
13,750✔
910
        int r;
13,750✔
911

912
        r = unit_load_fragment_and_dropin(u, true);
13,750✔
913
        if (r < 0)
13,750✔
914
                return r;
915

916
        if (u->load_state != UNIT_LOADED)
12,945✔
917
                return 0;
918

919
        /* This is a new unit? Then let's add in some extras */
920
        r = service_add_extras(s);
12,924✔
921
        if (r < 0)
12,924✔
922
                return r;
923

924
        return service_verify(s);
12,924✔
925
}
926

927
static int service_dump_fd(int fd, const char *fdname, const char *header, FILE *f, const char *prefix) {
150✔
928
        _cleanup_free_ char *path = NULL;
150✔
929
        struct stat st;
150✔
930
        int flags;
150✔
931

932
        assert(fd >= 0);
150✔
933
        assert(fdname);
150✔
934
        assert(header);
150✔
935
        assert(f);
150✔
936
        assert(prefix);
150✔
937

938
        if (fstat(fd, &st) < 0)
150✔
939
                return log_debug_errno(errno, "Failed to stat service fd: %m");
×
940

941
        flags = fcntl(fd, F_GETFL);
150✔
942
        if (flags < 0)
150✔
943
                return log_debug_errno(errno, "Failed to get service fd flags: %m");
×
944

945
        (void) fd_get_path(fd, &path);
150✔
946

947
        fprintf(f,
150✔
948
                "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR "; inode=%" PRIu64 "; rdev=" DEVNUM_FORMAT_STR "; path=%s; access=%s)\n",
949
                prefix,
950
                header,
951
                fdname,
952
                strna(inode_type_to_string(st.st_mode)),
953
                DEVNUM_FORMAT_VAL(st.st_dev),
954
                (uint64_t) st.st_ino,
150✔
955
                DEVNUM_FORMAT_VAL(st.st_rdev),
956
                strna(path),
957
                strna(accmode_to_string(flags)));
958

959
        return 0;
960
}
961

962
static void service_dump(Unit *u, FILE *f, const char *prefix) {
91✔
963
        Service *s = ASSERT_PTR(SERVICE(u));
91✔
964
        const char *prefix2;
91✔
965

966
        prefix = strempty(prefix);
91✔
967
        prefix2 = strjoina(prefix, "\t");
455✔
968

969
        fprintf(f,
182✔
970
                "%sService State: %s\n"
971
                "%sResult: %s\n"
972
                "%sReload Result: %s\n"
973
                "%sClean Result: %s\n"
974
                "%sLiveMount Result: %s\n"
975
                "%sPermissionsStartOnly: %s\n"
976
                "%sRootDirectoryStartOnly: %s\n"
977
                "%sRemainAfterExit: %s\n"
978
                "%sGuessMainPID: %s\n"
979
                "%sType: %s\n"
980
                "%sRestart: %s\n"
981
                "%sNotifyAccess: %s\n"
982
                "%sNotifyState: %s\n"
983
                "%sOOMPolicy: %s\n"
984
                "%sReloadSignal: %s\n",
985
                prefix, service_state_to_string(s->state),
986
                prefix, service_result_to_string(s->result),
987
                prefix, service_result_to_string(s->reload_result),
988
                prefix, service_result_to_string(s->live_mount_result),
989
                prefix, service_result_to_string(s->clean_result),
990
                prefix, yes_no(s->permissions_start_only),
91✔
991
                prefix, yes_no(s->root_directory_start_only),
91✔
992
                prefix, yes_no(s->remain_after_exit),
91✔
993
                prefix, yes_no(s->guess_main_pid),
91✔
994
                prefix, service_type_to_string(s->type),
995
                prefix, service_restart_to_string(s->restart),
996
                prefix, notify_access_to_string(service_get_notify_access(s)),
997
                prefix, notify_state_to_string(s->notify_state),
998
                prefix, oom_policy_to_string(s->oom_policy),
999
                prefix, signal_to_string(s->reload_signal));
1000

1001
        if (pidref_is_set(&s->control_pid))
91✔
1002
                fprintf(f,
×
1003
                        "%sControl PID: "PID_FMT"\n",
1004
                        prefix, s->control_pid.pid);
1005

1006
        if (pidref_is_set(&s->main_pid))
1007
                fprintf(f,
10✔
1008
                        "%sMain PID: "PID_FMT"\n"
1009
                        "%sMain PID Known: %s\n"
1010
                        "%sMain PID Alien: %s\n",
1011
                        prefix, s->main_pid.pid,
1012
                        prefix, yes_no(s->main_pid_known),
10✔
1013
                        prefix, yes_no(s->main_pid_alien));
10✔
1014

1015
        if (s->pid_file)
91✔
1016
                fprintf(f,
×
1017
                        "%sPIDFile: %s\n",
1018
                        prefix, s->pid_file);
1019

1020
        if (s->bus_name)
91✔
1021
                fprintf(f,
×
1022
                        "%sBusName: %s\n"
1023
                        "%sBus Name Good: %s\n",
1024
                        prefix, s->bus_name,
1025
                        prefix, yes_no(s->bus_name_good));
×
1026

1027
        if (UNIT_ISSET(s->accept_socket))
91✔
1028
                fprintf(f,
×
1029
                        "%sAccept Socket: %s\n",
1030
                        prefix, UNIT_DEREF(s->accept_socket)->id);
1031

1032
        fprintf(f,
182✔
1033
                "%sRestartSec: %s\n"
1034
                "%sRestartSteps: %u\n"
1035
                "%sRestartMaxDelaySec: %s\n"
1036
                "%sTimeoutStartSec: %s\n"
1037
                "%sTimeoutStopSec: %s\n"
1038
                "%sTimeoutStartFailureMode: %s\n"
1039
                "%sTimeoutStopFailureMode: %s\n",
1040
                prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC),
91✔
1041
                prefix, s->restart_steps,
1042
                prefix, FORMAT_TIMESPAN(s->restart_max_delay_usec, USEC_PER_SEC),
91✔
1043
                prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC),
91✔
1044
                prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC),
91✔
1045
                prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode),
1046
                prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode));
1047

1048
        if (s->timeout_abort_set)
91✔
1049
                fprintf(f,
×
1050
                        "%sTimeoutAbortSec: %s\n",
1051
                        prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC));
×
1052

1053
        fprintf(f,
91✔
1054
                "%sRuntimeMaxSec: %s\n"
1055
                "%sRuntimeRandomizedExtraSec: %s\n"
1056
                "%sWatchdogSec: %s\n",
1057
                prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC),
91✔
1058
                prefix, FORMAT_TIMESPAN(s->runtime_rand_extra_usec, USEC_PER_SEC),
91✔
1059
                prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC));
91✔
1060

1061
        kill_context_dump(&s->kill_context, f, prefix);
91✔
1062
        exec_context_dump(&s->exec_context, f, prefix);
91✔
1063

1064
        for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
728✔
1065
                if (!s->exec_command[c])
637✔
1066
                        continue;
546✔
1067

1068
                fprintf(f, "%s%s %s:\n",
91✔
1069
                        prefix, glyph(GLYPH_ARROW_RIGHT), service_exec_command_to_string(c));
1070

1071
                exec_command_dump_list(s->exec_command[c], f, prefix2);
91✔
1072
        }
1073

1074
        if (s->status_text)
91✔
1075
                fprintf(f, "%sStatus Text: %s\n",
10✔
1076
                        prefix, s->status_text);
1077

1078
        if (s->status_errno > 0)
91✔
1079
                fprintf(f, "%sStatus Errno: %s\n",
×
1080
                        prefix, STRERROR(s->status_errno));
×
1081

1082
        if (s->status_bus_error)
91✔
1083
                fprintf(f, "%sStatus Bus Error: %s\n",
×
1084
                        prefix, s->status_bus_error);
1085

1086
        if (s->status_varlink_error)
91✔
1087
                fprintf(f, "%sStatus Varlink Error: %s\n",
×
1088
                        prefix, s->status_varlink_error);
1089

1090
        if (s->n_fd_store_max > 0) {
91✔
1091
                fprintf(f,
10✔
1092
                        "%sFile Descriptor Store Max: %u\n"
1093
                        "%sFile Descriptor Store Pin: %s\n"
1094
                        "%sFile Descriptor Store Current: %zu\n",
1095
                        prefix, s->n_fd_store_max,
1096
                        prefix, exec_preserve_mode_to_string(s->fd_store_preserve_mode),
1097
                        prefix, s->n_fd_store);
1098

1099
                LIST_FOREACH(fd_store, i, s->fd_store)
160✔
1100
                        (void) service_dump_fd(i->fd,
300✔
1101
                                               i->fdname,
150✔
1102
                                               i == s->fd_store ? "File Descriptor Store Entry:" : "                            ",
150✔
1103
                                               f,
1104
                                               prefix);
1105
        }
1106

1107
        FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds)
91✔
1108
                (void) service_dump_fd(i->fd,
×
1109
                                       i->fdname,
×
1110
                                       i == s->extra_fds ? "Extra File Descriptor Entry:" : "                            ",
×
1111
                                       f,
1112
                                       prefix);
1113

1114
        if (s->open_files)
91✔
1115
                LIST_FOREACH(open_files, of, s->open_files) {
×
1116
                        _cleanup_free_ char *ofs = NULL;
×
1117
                        int r;
×
1118

1119
                        r = open_file_to_string(of, &ofs);
×
1120
                        if (r < 0) {
×
1121
                                log_debug_errno(r,
×
1122
                                                "Failed to convert OpenFile= setting to string, ignoring: %m");
1123
                                continue;
×
1124
                        }
1125

1126
                        fprintf(f, "%sOpen File: %s\n", prefix, ofs);
×
1127
                }
1128

1129
        cgroup_context_dump(UNIT(s), f, prefix);
91✔
1130
}
91✔
1131

1132
static int service_is_suitable_main_pid(Service *s, PidRef *pid, int prio) {
2✔
1133
        Unit *owner;
2✔
1134
        int r;
2✔
1135

1136
        assert(s);
2✔
1137
        assert(pidref_is_set(pid));
2✔
1138

1139
        /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
1140
         * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
1141
         * good */
1142

1143
        if (pidref_is_self(pid) || pid->pid == 1)
2✔
1144
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the manager, refusing.", pid->pid);
×
1145

1146
        if (pidref_equal(pid, &s->control_pid))
2✔
1147
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the control process, refusing.", pid->pid);
×
1148

1149
        r = pidref_is_alive(pid);
2✔
1150
        if (r < 0)
2✔
1151
                return log_unit_full_errno(UNIT(s), prio, r, "Failed to check if main PID "PID_FMT" exists or is a zombie: %m", pid->pid);
×
1152
        if (r == 0)
2✔
1153
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(ESRCH), "New main PID "PID_FMT" does not exist or is a zombie.", pid->pid);
×
1154

1155
        owner = manager_get_unit_by_pidref(UNIT(s)->manager, pid);
2✔
1156
        if (owner == UNIT(s)) {
2✔
1157
                log_unit_debug(UNIT(s), "New main PID "PID_FMT" belongs to service, we are happy.", pid->pid);
2✔
1158
                return 1; /* Yay, it's definitely a good PID */
2✔
1159
        }
1160

1161
        return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
1162
}
1163

1164
static int service_load_pid_file(Service *s, bool may_warn) {
1,542✔
1165
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
1166
        _cleanup_fclose_ FILE *f = NULL;
1,542✔
1167
        _cleanup_free_ char *k = NULL;
1,542✔
1168
        bool questionable_pid_file = false;
1,542✔
1169
        int r, prio = may_warn ? LOG_INFO : LOG_DEBUG;
1,542✔
1170

1171
        assert(s);
1,542✔
1172

1173
        if (!s->pid_file)
1,542✔
1174
                return -ENOENT;
1175

1176
        r = chase_and_fopen_unlocked(s->pid_file, NULL, CHASE_SAFE, "re", NULL, &f);
×
1177
        if (r == -ENOLINK) {
×
1178
                log_unit_debug_errno(UNIT(s), r,
×
1179
                                     "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s->pid_file);
1180

1181
                questionable_pid_file = true;
×
1182

1183
                r = chase_and_fopen_unlocked(s->pid_file, NULL, 0, "re", NULL, &f);
×
1184
        }
1185
        if (r < 0)
×
1186
                return log_unit_full_errno(UNIT(s), prio, r,
×
1187
                                           "Can't open PID file '%s' (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
1188

1189
        /* Let's read the PID file now that we chased it down. */
1190
        r = read_line(f, LINE_MAX, &k);
×
1191
        if (r < 0)
×
1192
                return log_unit_error_errno(UNIT(s), r, "Failed to read PID file '%s': %m", s->pid_file);
×
1193

1194
        r = pidref_set_pidstr(&pidref, k);
×
1195
        if (r < 0)
×
1196
                return log_unit_full_errno(UNIT(s), prio, r, "Failed to create reference to PID %s from file '%s': %m", k, s->pid_file);
×
1197

1198
        if (s->main_pid_known && pidref_equal(&pidref, &s->main_pid))
×
1199
                return 0;
1200

1201
        r = service_is_suitable_main_pid(s, &pidref, prio);
×
1202
        if (r < 0)
×
1203
                return r;
1204
        if (r == 0) {
×
1205
                struct stat st;
×
1206

1207
                if (questionable_pid_file)
×
1208
                        return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
×
1209
                                                    "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s->pid_file);
1210

1211
                /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1212

1213
                if (fstat(fileno(f), &st) < 0)
×
1214
                        return log_unit_error_errno(UNIT(s), errno, "Failed to fstat() PID file '%s': %m", s->pid_file);
×
1215

1216
                if (st.st_uid != 0)
×
1217
                        return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
×
1218
                                                    "New main PID "PID_FMT" from PID file does not belong to service, and PID file is not owned by root. Refusing.", pidref.pid);
1219

1220
                log_unit_debug(UNIT(s), "New main PID "PID_FMT" does not belong to service, accepting anyway since PID file is owned by root.", pidref.pid);
×
1221
        }
1222

1223
        if (s->main_pid_known) {
×
1224
                log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid.pid, pidref.pid);
×
1225

1226
                service_unwatch_main_pid(s);
×
1227
                s->main_pid_known = false;
×
1228
        } else
1229
                log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pidref.pid);
×
1230

1231
        r = service_set_main_pidref(s, TAKE_PIDREF(pidref), /* start_timestamp = */ NULL);
×
1232
        if (r < 0)
×
1233
                return r;
1234

1235
        r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
×
1236
        if (r < 0) /* FIXME: we need to do something here */
×
1237
                return log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", s->main_pid.pid);
×
1238

1239
        return 1;
1240
}
1241

1242
static void service_search_main_pid(Service *s) {
3✔
1243
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
3✔
1244
        int r;
3✔
1245

1246
        assert(s);
3✔
1247

1248
        /* If we know it anyway, don't ever fall back to unreliable heuristics */
1249
        if (s->main_pid_known)
3✔
1250
                return;
1251

1252
        if (!s->guess_main_pid)
×
1253
                return;
1254

1255
        assert(!pidref_is_set(&s->main_pid));
×
1256

1257
        if (unit_search_main_pid(UNIT(s), &pid) < 0)
×
1258
                return;
1259

1260
        log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid.pid);
×
1261
        if (service_set_main_pidref(s, TAKE_PIDREF(pid), /* start_timestamp = */ NULL) < 0)
×
1262
                return;
1263

1264
        r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
×
1265
        if (r < 0)
×
1266
                /* FIXME: we need to do something here */
1267
                log_unit_warning_errno(UNIT(s), r, "Failed to watch main PID "PID_FMT": %m", s->main_pid.pid);
×
1268
}
1269

1270
static void service_set_state(Service *s, ServiceState state) {
7,203✔
1271
        Unit *u = UNIT(ASSERT_PTR(s));
7,203✔
1272
        ServiceState old_state;
7,203✔
1273
        const UnitActiveState *table;
7,203✔
1274

1275
        if (s->state != state)
7,203✔
1276
                bus_unit_send_pending_change_signal(u, false);
7,095✔
1277

1278
        table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
7,203✔
1279

1280
        old_state = s->state;
7,203✔
1281
        s->state = state;
7,203✔
1282

1283
        service_unwatch_pid_file(s);
7,203✔
1284

1285
        if (!IN_SET(state,
7,203✔
1286
                    SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1287
                    SERVICE_RUNNING,
1288
                    SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
1289
                    SERVICE_MOUNTING,
1290
                    SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1291
                    SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
1292
                    SERVICE_AUTO_RESTART,
1293
                    SERVICE_CLEANING))
1294
                s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
3,386✔
1295

1296
        if (!SERVICE_STATE_WITH_MAIN_PROCESS(state)) {
7,203✔
1297
                service_unwatch_main_pid(s);
3,416✔
1298
                s->main_command = NULL;
3,416✔
1299
        }
1300

1301
        if (!SERVICE_STATE_WITH_CONTROL_PROCESS(state)) {
7,203✔
1302
                service_unwatch_control_pid(s);
4,961✔
1303
                s->control_command = NULL;
4,961✔
1304
                s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
4,961✔
1305
        }
1306

1307
        if (IN_SET(state,
7,203✔
1308
                   SERVICE_DEAD, SERVICE_FAILED,
1309
                   SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
1310
                   SERVICE_DEAD_RESOURCES_PINNED))
1311
                unit_unwatch_all_pids(u);
1,557✔
1312

1313
        if (state != SERVICE_START)
7,203✔
1314
                s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5,731✔
1315

1316
        if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_MOUNTING))
5,731✔
1317
                service_stop_watchdog(s);
5,605✔
1318

1319
        if (state != SERVICE_MOUNTING) /* Just in case */
7,203✔
1320
                s->mount_request = sd_bus_message_unref(s->mount_request);
7,203✔
1321

1322
        if (state == SERVICE_EXITED && !MANAGER_IS_RELOADING(u->manager)) {
7,203✔
1323
                /* For the inactive states unit_notify() will trim the cgroup. But for exit we have to
1324
                 * do that ourselves... */
1325
                unit_prune_cgroup(u);
764✔
1326

1327
                /* If none of ExecReload= and ExecStop*= is used, we can safely destroy runtime data
1328
                 * as soon as the service enters SERVICE_EXITED. This saves us from keeping the credential mount
1329
                 * for the whole duration of the oneshot service while no processes are actually running,
1330
                 * among other things. */
1331

1332
                bool start_only = true;
764✔
1333
                for (ServiceExecCommand c = SERVICE_EXEC_RELOAD; c < _SERVICE_EXEC_COMMAND_MAX; c++)
2,664✔
1334
                        if (s->exec_command[c]) {
2,096✔
1335
                                start_only = false;
1336
                                break;
1337
                        }
1338

1339
                if (start_only)
764✔
1340
                        unit_destroy_runtime_data(u, &s->exec_context, /* destroy_runtime_dir = */ false);
568✔
1341
        }
1342

1343
        if (old_state != state)
7,203✔
1344
                log_unit_debug(u, "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
7,095✔
1345

1346
        unit_notify(u, table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
7,203✔
1347
}
7,203✔
1348

1349
static usec_t service_coldplug_timeout(Service *s) {
1,760✔
1350
        assert(s);
1,760✔
1351

1352
        switch (s->deserialized_state) {
1,760✔
1353

1354
        case SERVICE_CONDITION:
1355
        case SERVICE_START_PRE:
1356
        case SERVICE_START:
1357
        case SERVICE_START_POST:
1358
        case SERVICE_RELOAD:
1359
        case SERVICE_RELOAD_SIGNAL:
1360
        case SERVICE_RELOAD_NOTIFY:
1361
        case SERVICE_MOUNTING:
1362
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
56✔
1363

1364
        case SERVICE_RUNNING:
596✔
1365
                return service_running_timeout(s);
596✔
1366

1367
        case SERVICE_STOP:
1368
        case SERVICE_STOP_SIGTERM:
1369
        case SERVICE_STOP_SIGKILL:
1370
        case SERVICE_STOP_POST:
1371
        case SERVICE_FINAL_SIGTERM:
1372
        case SERVICE_FINAL_SIGKILL:
1373
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
×
1374

1375
        case SERVICE_STOP_WATCHDOG:
×
1376
        case SERVICE_FINAL_WATCHDOG:
1377
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, service_timeout_abort_usec(s));
×
1378

1379
        case SERVICE_AUTO_RESTART:
×
1380
                return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic, service_restart_usec_next(s));
×
1381

1382
        case SERVICE_CLEANING:
1383
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->exec_context.timeout_clean_usec);
×
1384

1385
        default:
1386
                return USEC_INFINITY;
1387
        }
1388
}
1389

1390
static int service_coldplug(Unit *u) {
8,479✔
1391
        Service *s = SERVICE(u);
8,479✔
1392
        int r;
8,479✔
1393

1394
        assert(s);
×
1395
        assert(s->state == SERVICE_DEAD);
8,479✔
1396

1397
        if (s->deserialized_state == s->state)
8,479✔
1398
                return 0;
1399

1400
        r = service_arm_timer(s, /* relative= */ false, service_coldplug_timeout(s));
1,760✔
1401
        if (r < 0)
1,760✔
1402
                return r;
1403

1404
        if (pidref_is_set(&s->main_pid) &&
3,064✔
1405
            pidref_is_unwaited(&s->main_pid) > 0 &&
652✔
1406
            SERVICE_STATE_WITH_MAIN_PROCESS(s->deserialized_state)) {
652✔
1407
                r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
652✔
1408
                if (r < 0)
652✔
1409
                        return r;
1410
        }
1411

1412
        if (pidref_is_set(&s->control_pid) &&
×
1413
            pidref_is_unwaited(&s->control_pid) > 0 &&
×
1414
            SERVICE_STATE_WITH_CONTROL_PROCESS(s->deserialized_state)) {
×
1415
                r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
×
1416
                if (r < 0)
×
1417
                        return r;
1418
        }
1419

1420
        if (!IN_SET(s->deserialized_state,
1,760✔
1421
                    SERVICE_DEAD, SERVICE_FAILED,
1422
                    SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
1423
                    SERVICE_CLEANING,
1424
                    SERVICE_DEAD_RESOURCES_PINNED))
1425
                (void) unit_setup_exec_runtime(u);
1,722✔
1426

1427
        if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_MOUNTING))
1,760✔
1428
                service_start_watchdog(s);
596✔
1429

1430
        if (UNIT_ISSET(s->accept_socket)) {
1,760✔
1431
                Socket *socket = SOCKET(UNIT_DEREF(s->accept_socket));
×
1432

1433
                if (socket->max_connections_per_source > 0) {
×
1434
                        SocketPeer *peer;
×
1435

1436
                        /* Make a best-effort attempt at bumping the connection count */
1437
                        if (socket_acquire_peer(socket, s->socket_fd, &peer) > 0) {
×
1438
                                socket_peer_unref(s->socket_peer);
×
1439
                                s->socket_peer = peer;
×
1440
                        }
1441
                }
1442
        }
1443

1444
        service_set_state(s, s->deserialized_state);
1,760✔
1445
        return 0;
1,760✔
1446
}
1447

1448
static int service_collect_fds(
1,711✔
1449
                Service *s,
1450
                int **fds,
1451
                char ***fd_names,
1452
                size_t *n_socket_fds,
1453
                size_t *n_storage_fds,
1454
                size_t *n_extra_fds) {
1455

1456
        _cleanup_strv_free_ char **rfd_names = NULL;
×
1457
        _cleanup_free_ int *rfds = NULL;
1,711✔
1458
        size_t rn_socket_fds = 0;
1,711✔
1459
        int r;
1,711✔
1460

1461
        assert(s);
1,711✔
1462
        assert(fds);
1,711✔
1463
        assert(fd_names);
1,711✔
1464
        assert(n_socket_fds);
1,711✔
1465
        assert(n_storage_fds);
1,711✔
1466
        assert(n_extra_fds);
1,711✔
1467

1468
        if (s->socket_fd >= 0) {
1,711✔
1469
                Socket *sock = ASSERT_PTR(SOCKET(UNIT_DEREF(s->accept_socket)));
2✔
1470

1471
                /* Pass the per-connection socket */
1472

1473
                rfds = newdup(int, &s->socket_fd, 1);
2✔
1474
                if (!rfds)
2✔
1475
                        return -ENOMEM;
1476

1477
                rfd_names = strv_new(socket_fdname(sock));
2✔
1478
                if (!rfd_names)
2✔
1479
                        return -ENOMEM;
1480

1481
                rn_socket_fds = 1;
2✔
1482
        } else {
1483
                /* Pass all our configured sockets for singleton services */
1484

1485
                Unit *u;
1,709✔
1486
                UNIT_FOREACH_DEPENDENCY(u, UNIT(s), UNIT_ATOM_TRIGGERED_BY) {
4,270✔
1487
                        _cleanup_free_ int *cfds = NULL;
475✔
1488
                        int cn_fds;
475✔
1489
                        Socket *sock;
475✔
1490

1491
                        sock = SOCKET(u);
475✔
1492
                        if (!sock)
475✔
1493
                                continue;
16✔
1494

1495
                        cn_fds = socket_collect_fds(sock, &cfds);
459✔
1496
                        if (cn_fds < 0)
459✔
1497
                                return cn_fds;
1498
                        if (cn_fds == 0)
459✔
1499
                                continue;
19✔
1500

1501
                        if (!rfds) {
440✔
1502
                                rfds = TAKE_PTR(cfds);
361✔
1503
                                rn_socket_fds = cn_fds;
361✔
1504
                        } else if (!GREEDY_REALLOC_APPEND(rfds, rn_socket_fds, cfds, cn_fds))
79✔
1505
                                return -ENOMEM;
1506

1507
                        r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
440✔
1508
                        if (r < 0)
440✔
1509
                                return r;
1510
                }
1511
        }
1512

1513
        if (s->n_fd_store + s->n_extra_fds > 0) {
1,711✔
1514
                int *t = reallocarray(rfds, rn_socket_fds + s->n_fd_store + s->n_extra_fds, sizeof(int));
5✔
1515
                if (!t)
5✔
1516
                        return -ENOMEM;
1517
                rfds = t;
5✔
1518

1519
                char **nl = reallocarray(rfd_names, rn_socket_fds + s->n_fd_store + s->n_extra_fds + 1, sizeof(char *));
5✔
1520
                if (!nl)
5✔
1521
                        return -ENOMEM;
1522
                rfd_names = nl;
5✔
1523

1524
                size_t n_fds = rn_socket_fds;
5✔
1525

1526
                LIST_FOREACH(fd_store, fs, s->fd_store) {
22✔
1527
                        rfds[n_fds] = fs->fd;
17✔
1528
                        rfd_names[n_fds] = strdup(fs->fdname);
17✔
1529
                        if (!rfd_names[n_fds])
17✔
1530
                                return -ENOMEM;
1531

1532
                        n_fds++;
17✔
1533
                }
1534

1535
                FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
7✔
1536
                        rfds[n_fds] = i->fd;
2✔
1537
                        rfd_names[n_fds] = strdup(i->fdname);
2✔
1538
                        if (!rfd_names[n_fds])
2✔
1539
                                return -ENOMEM;
1540

1541
                        n_fds++;
2✔
1542
                }
1543

1544
                rfd_names[n_fds] = NULL;
5✔
1545
        }
1546

1547
        *fds = TAKE_PTR(rfds);
1,711✔
1548
        *fd_names = TAKE_PTR(rfd_names);
1,711✔
1549
        *n_socket_fds = rn_socket_fds;
1,711✔
1550
        *n_storage_fds = s->n_fd_store;
1,711✔
1551
        *n_extra_fds = s->n_extra_fds;
1,711✔
1552

1553
        return 0;
1,711✔
1554
}
1555

1556
static int service_allocate_exec_fd_event_source(
16✔
1557
                Service *s,
1558
                int fd,
1559
                sd_event_source **ret_event_source) {
1560

1561
        _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
16✔
1562
        int r;
16✔
1563

1564
        assert(s);
16✔
1565
        assert(fd >= 0);
16✔
1566
        assert(ret_event_source);
16✔
1567

1568
        r = sd_event_add_io(UNIT(s)->manager->event, &source, fd, 0, service_dispatch_exec_io, s);
16✔
1569
        if (r < 0)
16✔
1570
                return log_unit_error_errno(UNIT(s), r, "Failed to allocate exec_fd event source: %m");
×
1571

1572
        /* This is a bit higher priority than SIGCHLD, to make sure we don't confuse the case "failed to
1573
         * start" from the case "succeeded to start, but failed immediately after". */
1574

1575
        r = sd_event_source_set_priority(source, EVENT_PRIORITY_EXEC_FD);
16✔
1576
        if (r < 0)
16✔
1577
                return log_unit_error_errno(UNIT(s), r, "Failed to adjust priority of exec_fd event source: %m");
×
1578

1579
        (void) sd_event_source_set_description(source, "service exec_fd");
16✔
1580

1581
        r = sd_event_source_set_io_fd_own(source, true);
16✔
1582
        if (r < 0)
16✔
1583
                return log_unit_error_errno(UNIT(s), r, "Failed to pass ownership of fd to event source: %m");
×
1584

1585
        *ret_event_source = TAKE_PTR(source);
16✔
1586
        return 0;
16✔
1587
}
1588

1589
static int service_allocate_exec_fd(
16✔
1590
                Service *s,
1591
                sd_event_source **ret_event_source,
1592
                int *ret_exec_fd) {
1593

1594
        _cleanup_close_pair_ int p[] = EBADF_PAIR;
16✔
1595
        int r;
16✔
1596

1597
        assert(s);
16✔
1598
        assert(ret_event_source);
16✔
1599
        assert(ret_exec_fd);
16✔
1600

1601
        if (pipe2(p, O_CLOEXEC|O_NONBLOCK) < 0)
16✔
1602
                return log_unit_error_errno(UNIT(s), errno, "Failed to allocate exec_fd pipe: %m");
×
1603

1604
        r = service_allocate_exec_fd_event_source(s, p[0], ret_event_source);
16✔
1605
        if (r < 0)
16✔
1606
                return r;
1607

1608
        TAKE_FD(p[0]);
16✔
1609
        *ret_exec_fd = TAKE_FD(p[1]);
16✔
1610

1611
        return 0;
16✔
1612
}
1613

1614
static bool service_exec_needs_notify_socket(Service *s, ExecFlags flags) {
1,854✔
1615
        assert(s);
1,854✔
1616

1617
        /* Notifications are accepted depending on the process and
1618
         * the access setting of the service:
1619
         *     process: \ access:  NONE  MAIN  EXEC   ALL
1620
         *     main                  no   yes   yes   yes
1621
         *     control               no    no   yes   yes
1622
         *     other (forked)        no    no    no   yes */
1623

1624
        if (flags & EXEC_IS_CONTROL)
1,854✔
1625
                /* A control process */
1626
                return IN_SET(service_get_notify_access(s), NOTIFY_EXEC, NOTIFY_ALL);
143✔
1627

1628
        /* We only spawn main processes and control processes, so any
1629
         * process that is not a control process is a main process */
1630
        return service_get_notify_access(s) != NOTIFY_NONE;
1,711✔
1631
}
1632

1633
static Service *service_get_triggering_service(Service *s) {
1,736✔
1634
        Unit *candidate = NULL, *other;
1,736✔
1635

1636
        assert(s);
1,736✔
1637

1638
        /* Return the service which triggered service 's', this means dependency
1639
         * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
1640
         *
1641
         * N.B. if there are multiple services which could trigger 's' via OnFailure=
1642
         * or OnSuccess= then we return NULL. This is since we don't know from which
1643
         * one to propagate the exit status. */
1644

1645
        UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_SUCCESS_OF|UNIT_ATOM_ON_FAILURE_OF) {
17,748✔
1646
                if (candidate)
9✔
1647
                        goto have_other;
×
1648
                candidate = other;
9✔
1649
        }
1650

1651
        return SERVICE(candidate);
3,472✔
1652

1653
 have_other:
×
1654
        log_unit_warning(UNIT(s), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
×
1655
                         candidate->id, other->id);
1656
        return NULL;
×
1657
}
1658

1659
static ExecFlags service_exec_flags(ServiceExecCommand command_id, ExecFlags cred_flag) {
1,854✔
1660
        /* All service main/control processes honor sandboxing and namespacing options (except those
1661
        explicitly excluded in service_spawn()) */
1662
        ExecFlags flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT;
1,854✔
1663

1664
        assert(command_id >= 0);
1,854✔
1665
        assert(command_id < _SERVICE_EXEC_COMMAND_MAX);
1,854✔
1666
        assert((cred_flag & ~(EXEC_SETUP_CREDENTIALS_FRESH|EXEC_SETUP_CREDENTIALS)) == 0);
1,854✔
1667
        assert((cred_flag != 0) == (command_id == SERVICE_EXEC_START));
1,854✔
1668

1669
        /* Control processes spawned before main process also get tty access */
1670
        if (IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
1,854✔
1671
                flags |= EXEC_APPLY_TTY_STDIN;
1,736✔
1672

1673
        /* All start phases get access to credentials. ExecStartPre= gets a new credential store upon
1674
         * every invocation, so that updating credential files through it works. When the first main process
1675
         * starts, passed creds become stable. Also see 'cred_flag'. */
1676
        if (command_id == SERVICE_EXEC_START_PRE)
1,854✔
1677
                flags |= EXEC_SETUP_CREDENTIALS_FRESH;
25✔
1678
        if (command_id == SERVICE_EXEC_START_POST)
1,854✔
1679
                flags |= EXEC_SETUP_CREDENTIALS;
×
1680

1681
        if (IN_SET(command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
1,854✔
1682
                flags |= EXEC_SETENV_MONITOR_RESULT;
1,736✔
1683

1684
        if (command_id == SERVICE_EXEC_START)
1,854✔
1685
                return flags|cred_flag|EXEC_PASS_FDS|EXEC_SET_WATCHDOG;
1,711✔
1686

1687
        flags |= EXEC_IS_CONTROL;
143✔
1688

1689
        /* Put control processes spawned later than main process under .control sub-cgroup if appropriate */
1690
        if (!IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE))
143✔
1691
                flags |= EXEC_CONTROL_CGROUP;
118✔
1692

1693
        if (IN_SET(command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
143✔
1694
                flags |= EXEC_SETENV_RESULT;
114✔
1695

1696
        return flags;
1697
}
1698

1699
static int service_spawn_internal(
1,854✔
1700
                const char *caller,
1701
                Service *s,
1702
                ExecCommand *c,
1703
                ExecFlags flags,
1704
                usec_t timeout,
1705
                PidRef *ret_pid) {
1706

1707
        _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(flags);
×
1708
        _cleanup_(sd_event_source_unrefp) sd_event_source *exec_fd_source = NULL;
1,854✔
1709
        _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL;
1,854✔
1710
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
1,854✔
1711
        size_t n_env = 0;
1,854✔
1712
        int r;
1,854✔
1713

1714
        assert(caller);
1,854✔
1715
        assert(s);
1,854✔
1716
        assert(c);
1,854✔
1717
        assert(ret_pid);
1,854✔
1718

1719
        log_unit_debug(UNIT(s), "Will spawn child (%s): %s", caller, c->path);
1,854✔
1720

1721
        r = unit_prepare_exec(UNIT(s)); /* This realizes the cgroup, among other things */
1,854✔
1722
        if (r < 0)
1,854✔
1723
                return r;
1724

1725
        assert(!s->exec_fd_event_source);
1,854✔
1726

1727
        if (FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL)) {
1,854✔
1728
                /* If this is a control process, mask the permissions/chroot application if this is requested. */
1729
                if (s->permissions_start_only)
143✔
1730
                        exec_params.flags &= ~EXEC_APPLY_SANDBOXING;
×
1731
                if (s->root_directory_start_only)
143✔
1732
                        exec_params.flags &= ~EXEC_APPLY_CHROOT;
×
1733
        }
1734

1735
        if (FLAGS_SET(exec_params.flags, EXEC_PASS_FDS) ||
1,854✔
1736
            s->exec_context.std_input == EXEC_INPUT_SOCKET ||
143✔
1737
            s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
143✔
1738
            s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
143✔
1739

1740
                r = service_collect_fds(s,
1,711✔
1741
                                        &exec_params.fds,
1742
                                        &exec_params.fd_names,
1743
                                        &exec_params.n_socket_fds,
1744
                                        &exec_params.n_storage_fds,
1745
                                        &exec_params.n_extra_fds);
1746
                if (r < 0)
1,711✔
1747
                        return r;
1748

1749
                exec_params.open_files = s->open_files;
1,711✔
1750

1751
                exec_params.flags |= EXEC_PASS_FDS;
1,711✔
1752

1753
                log_unit_debug(UNIT(s), "Passing %zu fds to service", exec_params.n_socket_fds + exec_params.n_storage_fds + exec_params.n_extra_fds);
1,711✔
1754
        }
1755

1756
        if (!FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL) && s->type == SERVICE_EXEC) {
1,854✔
1757
                r = service_allocate_exec_fd(s, &exec_fd_source, &exec_params.exec_fd);
16✔
1758
                if (r < 0)
16✔
1759
                        return r;
1760
        }
1761

1762
        r = service_arm_timer(s, /* relative= */ true, timeout);
1,854✔
1763
        if (r < 0)
1,854✔
1764
                return r;
1765

1766
        our_env = new0(char*, 15);
1,854✔
1767
        if (!our_env)
1,854✔
1768
                return -ENOMEM;
1769

1770
        if (service_exec_needs_notify_socket(s, exec_params.flags)) {
1,854✔
1771
                exec_params.notify_socket = UNIT(s)->manager->notify_socket;
332✔
1772

1773
                if (s->n_fd_store_max > 0)
332✔
1774
                        if (asprintf(our_env + n_env++, "FDSTORE=%u", s->n_fd_store_max) < 0)
130✔
1775
                                return -ENOMEM;
1776
        }
1777

1778
        if (pidref_is_set(&s->main_pid)) {
1779
                if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid.pid) < 0)
4✔
1780
                        return -ENOMEM;
1781

1782
                if (pidref_acquire_pidfd_id(&s->main_pid) >= 0)
4✔
1783
                        if (asprintf(our_env + n_env++, "MAINPIDFDID=%" PRIu64, s->main_pid.fd_id) < 0)
4✔
1784
                                return -ENOMEM;
1785
        }
1786

1787
        if (MANAGER_IS_USER(UNIT(s)->manager)) {
1,854✔
1788
                if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid_cached()) < 0)
616✔
1789
                        return -ENOMEM;
×
1790

1791
                uint64_t pidfdid;
616✔
1792
                if (pidfd_get_inode_id_self_cached(&pidfdid) >= 0)
616✔
1793
                        if (asprintf(our_env + n_env++, "MANAGERPIDFDID=%" PRIu64, pidfdid) < 0)
616✔
1794
                                return -ENOMEM;
1795
        }
1796

1797
        if (s->pid_file)
1,854✔
1798
                if (asprintf(our_env + n_env++, "PIDFILE=%s", s->pid_file) < 0)
×
1799
                        return -ENOMEM;
1800

1801
        if (s->socket_fd >= 0) {
1,854✔
1802
                union sockaddr_union sa;
2✔
1803
                socklen_t salen = sizeof(sa);
2✔
1804

1805
                /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1806
                 * useful. Note that we do this only when we are still connected at this point in time, which we might
1807
                 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1808
                 * in ENOTCONN), and just use whate we can use. */
1809

1810
                if (getpeername(s->socket_fd, &sa.sa, &salen) >= 0 &&
2✔
1811
                    IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK, AF_UNIX)) {
2✔
1812
                        _cleanup_free_ char *addr = NULL;
2✔
1813
                        char *t;
2✔
1814

1815
                        r = sockaddr_pretty(&sa.sa, salen, /* translate_ipv6= */ true, /* include_port= */ false, &addr);
2✔
1816
                        if (r < 0)
2✔
1817
                                return r;
1818

1819
                        if (sa.sa.sa_family != AF_UNIX || IN_SET(addr[0], '/', '@')) {
2✔
1820
                                t = strjoin("REMOTE_ADDR=", addr);
×
1821
                                if (!t)
×
1822
                                        return -ENOMEM;
1823
                                our_env[n_env++] = t;
×
1824
                        }
1825

1826
                        if (IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
2✔
1827
                                unsigned port;
×
1828

1829
                                r = sockaddr_port(&sa.sa, &port);
×
1830
                                if (r < 0)
×
1831
                                        return r;
×
1832

1833
                                if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
×
1834
                                        return -ENOMEM;
1835
                                our_env[n_env++] = t;
×
1836
                        }
1837
                }
1838
        }
1839

1840
        Service *env_source = NULL;
1,854✔
1841
        const char *monitor_prefix;
1,854✔
1842
        if (FLAGS_SET(exec_params.flags, EXEC_SETENV_RESULT)) {
1,854✔
1843
                env_source = s;
1844
                monitor_prefix = "";
1845
        } else if (FLAGS_SET(exec_params.flags, EXEC_SETENV_MONITOR_RESULT)) {
1,740✔
1846
                env_source = service_get_triggering_service(s);
1,736✔
1847
                monitor_prefix = "MONITOR_";
1848
        }
1849

1850
        if (env_source) {
1,850✔
1851
                if (asprintf(our_env + n_env++, "%sSERVICE_RESULT=%s", monitor_prefix, service_result_to_string(env_source->result)) < 0)
123✔
1852
                        return -ENOMEM;
1853

1854
                if (env_source->main_exec_status.pid > 0 &&
123✔
1855
                    dual_timestamp_is_set(&env_source->main_exec_status.exit_timestamp)) {
109✔
1856
                        if (asprintf(our_env + n_env++, "%sEXIT_CODE=%s", monitor_prefix, sigchld_code_to_string(env_source->main_exec_status.code)) < 0)
109✔
1857
                                return -ENOMEM;
1858

1859
                        if (env_source->main_exec_status.code == CLD_EXITED)
109✔
1860
                                r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%i", monitor_prefix, env_source->main_exec_status.status);
108✔
1861
                        else
1862
                                r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%s", monitor_prefix, signal_to_string(env_source->main_exec_status.status));
1✔
1863
                        if (r < 0)
109✔
1864
                                return -ENOMEM;
1865
                }
1866

1867
                if (env_source != s) {
123✔
1868
                        if (!sd_id128_is_null(UNIT(env_source)->invocation_id))
9✔
1869
                                if (asprintf(our_env + n_env++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR,
9✔
1870
                                             monitor_prefix, SD_ID128_FORMAT_VAL(UNIT(env_source)->invocation_id)) < 0)
9✔
1871
                                        return -ENOMEM;
1872

1873
                        if (asprintf(our_env + n_env++, "%sUNIT=%s", monitor_prefix, UNIT(env_source)->id) < 0)
9✔
1874
                                return -ENOMEM;
1875
                }
1876
        }
1877

1878
        if (UNIT(s)->debug_invocation) {
1,854✔
1879
                char *t = strdup("DEBUG_INVOCATION=1");
×
1880
                if (!t)
×
1881
                        return -ENOMEM;
1882
                our_env[n_env++] = t;
×
1883
        }
1884

1885
        if (UNIT(s)->activation_details) {
1,854✔
1886
                r = activation_details_append_env(UNIT(s)->activation_details, &our_env);
16✔
1887
                if (r < 0)
16✔
1888
                        return r;
1889
                /* The number of env vars added here can vary, rather than keeping the allocation block in
1890
                 * sync manually, these functions simply use the strv methods to append to it, so we need
1891
                 * to update n_env when we are done in case of future usage. */
1892
                n_env += r;
1,854✔
1893
        }
1894

1895
        r = unit_set_exec_params(UNIT(s), &exec_params);
1,854✔
1896
        if (r < 0)
1,854✔
1897
                return r;
1898

1899
        final_env = strv_env_merge(exec_params.environment, our_env);
1,854✔
1900
        if (!final_env)
1,854✔
1901
                return -ENOMEM;
1902

1903
        /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
1904
        SET_FLAG(exec_params.flags, EXEC_NSS_DYNAMIC_BYPASS,
1,854✔
1905
                 MANAGER_IS_SYSTEM(UNIT(s)->manager) && unit_has_name(UNIT(s), SPECIAL_DBUS_SERVICE));
1906

1907
        strv_free_and_replace(exec_params.environment, final_env);
1,854✔
1908
        exec_params.watchdog_usec = service_get_watchdog_usec(s);
1,854✔
1909
        exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
1,854✔
1910
        if (s->type == SERVICE_IDLE)
1,854✔
1911
                exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
28✔
1912
        exec_params.stdin_fd = s->stdin_fd;
1,854✔
1913
        exec_params.stdout_fd = s->stdout_fd;
1,854✔
1914
        exec_params.stderr_fd = s->stderr_fd;
1,854✔
1915

1916
        r = exec_spawn(UNIT(s),
3,708✔
1917
                       c,
1918
                       &s->exec_context,
1,854✔
1919
                       &exec_params,
1920
                       s->exec_runtime,
1921
                       &s->cgroup_context,
1,854✔
1922
                       &pidref);
1923
        if (r < 0)
1,854✔
1924
                return r;
1925

1926
        s->exec_fd_event_source = TAKE_PTR(exec_fd_source);
1,854✔
1927
        s->exec_fd_hot = false;
1,854✔
1928

1929
        r = unit_watch_pidref(UNIT(s), &pidref, /* exclusive= */ true);
1,854✔
1930
        if (r < 0)
1,854✔
1931
                return r;
1932

1933
        *ret_pid = TAKE_PIDREF(pidref);
1,854✔
1934
        return 0;
1,854✔
1935
}
1936

1937
static int main_pid_good(Service *s) {
39,979✔
1938
        assert(s);
39,979✔
1939

1940
        /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
1941

1942
        /* If we know the pid file, then let's just check if it is still valid */
1943
        if (s->main_pid_known) {
39,979✔
1944

1945
                /* If it's an alien child let's check if it is still alive ... */
1946
                if (s->main_pid_alien && pidref_is_set(&s->main_pid))
5,605✔
1947
                        return pidref_is_alive(&s->main_pid);
2✔
1948

1949
                /* .. otherwise assume we'll get a SIGCHLD for it, which we really should wait for to collect
1950
                 * exit status and code */
1951
                return pidref_is_set(&s->main_pid);
5,603✔
1952
        }
1953

1954
        /* We don't know the pid */
1955
        return -EAGAIN;
1956
}
1957

1958
static int control_pid_good(Service *s) {
38,410✔
1959
        assert(s);
38,410✔
1960

1961
        /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1962
         * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1963
         * means: we can't figure it out. */
1964

1965
        return pidref_is_set(&s->control_pid);
38,410✔
1966
}
1967

1968
static int cgroup_good(Service *s) {
211✔
1969
        int r;
211✔
1970

1971
        assert(s);
211✔
1972

1973
        /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1974
         * figure it out */
1975

1976
        if (!s->cgroup_runtime || !s->cgroup_runtime->cgroup_path)
211✔
1977
                return 0;
1978

1979
        r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_runtime->cgroup_path);
211✔
1980
        if (r < 0)
211✔
1981
                return r;
1982

1983
        return r == 0;
211✔
1984
}
1985

1986
static bool service_shall_restart(Service *s, const char **reason) {
413✔
1987
        assert(s);
413✔
1988
        assert(reason);
413✔
1989

1990
        /* Don't restart after manual stops */
1991
        if (s->forbid_restart) {
413✔
1992
                *reason = "manual stop";
13✔
1993
                return false;
13✔
1994
        }
1995

1996
        /* Never restart if this is configured as special exception */
1997
        if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status)) {
400✔
1998
                *reason = "prevented by exit status";
×
1999
                return false;
×
2000
        }
2001

2002
        /* Restart if the exit code/status are configured as restart triggers */
2003
        if (exit_status_set_test(&s->restart_force_status,  s->main_exec_status.code, s->main_exec_status.status)) {
400✔
2004
                /* Don't allow Type=oneshot services to restart on success. Note that Restart=always/on-success
2005
                 * is already rejected in service_verify. */
2006
                if (s->type == SERVICE_ONESHOT && s->result == SERVICE_SUCCESS) {
×
2007
                        *reason = "service type and exit status";
×
2008
                        return false;
×
2009
                }
2010

2011
                *reason = "forced by exit status";
×
2012
                return true;
×
2013
        }
2014

2015
        *reason = "restart setting";
400✔
2016
        switch (s->restart) {
400✔
2017

2018
        case SERVICE_RESTART_NO:
2019
                return false;
2020

2021
        case SERVICE_RESTART_ALWAYS:
3✔
2022
                return s->result != SERVICE_SKIP_CONDITION;
3✔
2023

2024
        case SERVICE_RESTART_ON_SUCCESS:
×
2025
                return s->result == SERVICE_SUCCESS;
×
2026

2027
        case SERVICE_RESTART_ON_FAILURE:
1✔
2028
                return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_SKIP_CONDITION);
1✔
2029

2030
        case SERVICE_RESTART_ON_ABNORMAL:
×
2031
                return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE, SERVICE_SKIP_CONDITION);
×
2032

2033
        case SERVICE_RESTART_ON_WATCHDOG:
×
2034
                return s->result == SERVICE_FAILURE_WATCHDOG;
×
2035

2036
        case SERVICE_RESTART_ON_ABORT:
2✔
2037
                return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
2✔
2038

2039
        default:
×
2040
                assert_not_reached();
×
2041
        }
2042
}
2043

2044
static bool service_will_restart(Unit *u) {
1,161✔
2045
        Service *s = SERVICE(u);
1,161✔
2046

2047
        assert(s);
×
2048

2049
        if (IN_SET(s->state, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED))
1,161✔
2050
                return true;
2051

2052
        return unit_will_restart_default(u);
1,161✔
2053
}
2054

2055
static ServiceState service_determine_dead_state(Service *s) {
1,294✔
2056
        assert(s);
1,294✔
2057

2058
        return s->fd_store && s->fd_store_preserve_mode == EXEC_PRESERVE_YES ? SERVICE_DEAD_RESOURCES_PINNED : SERVICE_DEAD;
1,294✔
2059
}
2060

2061
static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1,509✔
2062
        ServiceState end_state, restart_state;
1,509✔
2063
        int r;
1,509✔
2064

2065
        assert(s);
1,509✔
2066

2067
        /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
2068
         * undo what has already been enqueued. */
2069
        if (unit_stop_pending(UNIT(s)))
1,509✔
2070
                allow_restart = false;
1,095✔
2071

2072
        if (s->result == SERVICE_SUCCESS)
1,509✔
2073
                s->result = f;
1,294✔
2074

2075
        if (s->result == SERVICE_SUCCESS) {
1,509✔
2076
                unit_log_success(UNIT(s));
1,294✔
2077
                end_state = service_determine_dead_state(s);
1,294✔
2078
                restart_state = SERVICE_DEAD_BEFORE_AUTO_RESTART;
1,294✔
2079
        } else if (s->result == SERVICE_SKIP_CONDITION) {
215✔
2080
                unit_log_skip(UNIT(s), service_result_to_string(s->result));
×
2081
                end_state = service_determine_dead_state(s);
×
2082
                restart_state = _SERVICE_STATE_INVALID; /* Never restart if skipped due to condition failure */
×
2083
        } else {
2084
                unit_log_failure(UNIT(s), service_result_to_string(s->result));
215✔
2085
                end_state = SERVICE_FAILED;
215✔
2086
                restart_state = SERVICE_FAILED_BEFORE_AUTO_RESTART;
215✔
2087
        }
2088
        unit_warn_leftover_processes(UNIT(s), /* start = */ false);
1,509✔
2089

2090
        if (!allow_restart)
1,509✔
2091
                log_unit_debug(UNIT(s), "Service restart not allowed.");
1,096✔
2092
        else {
2093
                const char *reason;
413✔
2094

2095
                allow_restart = service_shall_restart(s, &reason);
413✔
2096
                log_unit_debug(UNIT(s), "Service will %srestart (%s)",
821✔
2097
                                        allow_restart ? "" : "not ",
2098
                                        reason);
2099
        }
2100

2101
        if (allow_restart) {
1,509✔
2102
                usec_t restart_usec_next;
5✔
2103

2104
                assert(restart_state >= 0 && restart_state < _SERVICE_STATE_MAX);
5✔
2105

2106
                /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
2107
                 * state (i.e. a state indicating deactivation), and then one that maps to the
2108
                 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
2109
                 * external software can watch the state changes and see all service failures, even if they
2110
                 * are only transitionary and followed by an automatic restart. We have fine-grained
2111
                 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
2112
                 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
2113
                if (s->restart_mode != SERVICE_RESTART_MODE_DIRECT)
5✔
2114
                        service_set_state(s, restart_state);
5✔
2115

2116
                restart_usec_next = service_restart_usec_next(s);
5✔
2117

2118
                r = service_arm_timer(s, /* relative= */ true, restart_usec_next);
5✔
2119
                if (r < 0) {
5✔
2120
                        log_unit_warning_errno(UNIT(s), r, "Failed to install restart timer: %m");
×
2121
                        return service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
×
2122
                }
2123

2124
                /* If the relevant option is set, and the unit doesn't already have logging level set to
2125
                 * debug, enable it now. Make sure to overwrite the state in /run/systemd/units/ too, to
2126
                 * ensure journald doesn't prune the messages. The previous state is saved and restored
2127
                 * once the auto-restart flow ends. */
2128
                if (s->restart_mode == SERVICE_RESTART_MODE_DEBUG) {
5✔
2129
                        r = unit_set_debug_invocation(UNIT(s), true);
×
2130
                        if (r < 0)
×
2131
                                log_unit_warning_errno(UNIT(s), r, "Failed to enable debug invocation, ignoring: %m");
×
2132
                        if (r > 0)
×
2133
                                log_unit_notice(UNIT(s), "Service dead, subsequent restarts will be executed with debug level logging.");
×
2134
                }
2135

2136
                log_unit_debug(UNIT(s), "Next restart interval calculated as: %s", FORMAT_TIMESPAN(restart_usec_next, 0));
5✔
2137

2138
                service_set_state(s, SERVICE_AUTO_RESTART);
5✔
2139
        } else {
2140
                /* If we shan't restart, the restart counter would be flushed out. But rather than doing that
2141
                 * immediately here, this is delegated to service_start(), i.e. next start, so that the user
2142
                 * can still introspect the counter. */
2143
                service_set_state(s, end_state);
1,504✔
2144

2145
                (void) unit_set_debug_invocation(UNIT(s), false);
1,504✔
2146
        }
2147

2148
        /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
2149
        s->forbid_restart = false;
1,509✔
2150

2151
        /* Reset NotifyAccess override */
2152
        s->notify_access_override = _NOTIFY_ACCESS_INVALID;
1,509✔
2153

2154
        /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
2155
        s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
1,509✔
2156

2157
        /* Also, remove the runtime directory */
2158
        unit_destroy_runtime_data(UNIT(s), &s->exec_context, /* destroy_runtime_dir = */ true);
1,509✔
2159

2160
        /* Also get rid of the fd store, if that's configured. */
2161
        if (s->fd_store_preserve_mode == EXEC_PRESERVE_NO)
1,509✔
2162
                service_release_fd_store(s);
×
2163

2164
        /* Get rid of the IPC bits of the user */
2165
        unit_unref_uid_gid(UNIT(s), true);
1,509✔
2166

2167
        /* Try to delete the pid file. At this point it will be
2168
         * out-of-date, and some software might be confused by it, so
2169
         * let's remove it. */
2170
        if (s->pid_file)
1,509✔
2171
                (void) unlink(s->pid_file);
×
2172

2173
        /* Reset TTY ownership if necessary */
2174
        exec_context_revert_tty(&s->exec_context, UNIT(s)->invocation_id);
1,509✔
2175
}
2176

2177
static void service_enter_stop_post(Service *s, ServiceResult f) {
1,508✔
2178
        int r;
1,508✔
2179
        assert(s);
1,508✔
2180

2181
        if (s->result == SERVICE_SUCCESS)
1,508✔
2182
                s->result = f;
1,294✔
2183

2184
        service_unwatch_control_pid(s);
1,508✔
2185

2186
        s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1,508✔
2187
        if (s->control_command) {
1,508✔
2188
                s->control_command_id = SERVICE_EXEC_STOP_POST;
14✔
2189
                pidref_done(&s->control_pid);
14✔
2190

2191
                r = service_spawn(s,
14✔
2192
                                  s->control_command,
2193
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2194
                                  s->timeout_stop_usec,
2195
                                  &s->control_pid);
2196
                if (r < 0) {
14✔
2197
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-post' task: %m");
×
2198
                        service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
2199
                        return;
×
2200
                }
2201

2202
                service_set_state(s, SERVICE_STOP_POST);
14✔
2203
        } else
2204
                service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1,494✔
2205
}
2206

2207
static int state_to_kill_operation(Service *s, ServiceState state) {
5,443✔
2208
        switch (state) {
5,443✔
2209

2210
        case SERVICE_STOP_WATCHDOG:
2211
        case SERVICE_FINAL_WATCHDOG:
2212
                return KILL_WATCHDOG;
2213

2214
        case SERVICE_STOP_SIGTERM:
1,508✔
2215
                if (unit_has_job_type(UNIT(s), JOB_RESTART))
1,508✔
2216
                        return KILL_RESTART;
2✔
2217
                _fallthrough_;
2218

2219
        case SERVICE_FINAL_SIGTERM:
2220
                return KILL_TERMINATE;
2221

2222
        case SERVICE_STOP_SIGKILL:
2,427✔
2223
        case SERVICE_FINAL_SIGKILL:
2224
                return KILL_KILL;
2,427✔
2225

2226
        default:
×
2227
                return _KILL_OPERATION_INVALID;
×
2228
        }
2229
}
2230

2231
static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
5,443✔
2232
        int kill_operation, r;
5,443✔
2233

2234
        assert(s);
5,443✔
2235

2236
        if (s->result == SERVICE_SUCCESS)
5,443✔
2237
                s->result = f;
4,958✔
2238

2239
        kill_operation = state_to_kill_operation(s, state);
5,443✔
2240
        r = unit_kill_context(UNIT(s), kill_operation);
5,443✔
2241
        if (r < 0) {
5,443✔
2242
                log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
×
2243
                goto fail;
×
2244
        }
2245

2246
        if (r > 0) {
5,443✔
2247
                r = service_arm_timer(s, /* relative= */ true,
603✔
2248
                                      kill_operation == KILL_WATCHDOG ? service_timeout_abort_usec(s) : s->timeout_stop_usec);
×
2249
                if (r < 0) {
603✔
2250
                        log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2251
                        goto fail;
×
2252
                }
2253

2254
                service_set_state(s, state);
603✔
2255
        } else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
4,840✔
2256
                service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
920✔
2257
        else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
3,920✔
2258
                service_enter_stop_post(s, SERVICE_SUCCESS);
920✔
2259
        else if (IN_SET(state, SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM) && s->kill_context.send_sigkill)
3,000✔
2260
                service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1,507✔
2261
        else
2262
                service_enter_dead(s, SERVICE_SUCCESS, /* allow_restart= */ true);
1,493✔
2263

2264
        return;
2265

2266
fail:
×
2267
        if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
×
2268
                service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
×
2269
        else
2270
                service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
×
2271
}
2272

2273
static void service_enter_stop_by_notify(Service *s) {
×
2274
        int r;
×
2275

2276
        assert(s);
×
2277

2278
        r = service_arm_timer(s, /* relative= */ true, s->timeout_stop_usec);
×
2279
        if (r < 0) {
×
2280
                log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2281
                service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
2282
                return;
×
2283
        }
2284

2285
        /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2286
        service_set_state(s, SERVICE_STOP_SIGTERM);
×
2287
}
2288

2289
static void service_enter_stop(Service *s, ServiceResult f) {
1,467✔
2290
        int r;
1,467✔
2291

2292
        assert(s);
1,467✔
2293

2294
        if (s->result == SERVICE_SUCCESS)
1,467✔
2295
                s->result = f;
1,463✔
2296

2297
        service_unwatch_control_pid(s);
1,467✔
2298

2299
        s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1,467✔
2300
        if (s->control_command) {
1,467✔
2301
                s->control_command_id = SERVICE_EXEC_STOP;
100✔
2302
                pidref_done(&s->control_pid);
100✔
2303

2304
                r = service_spawn(s,
100✔
2305
                                  s->control_command,
2306
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2307
                                  s->timeout_stop_usec,
2308
                                  &s->control_pid);
2309
                if (r < 0) {
100✔
2310
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop' task: %m");
×
2311
                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
2312
                        return;
×
2313
                }
2314

2315
                service_set_state(s, SERVICE_STOP);
100✔
2316
        } else
2317
                service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1,367✔
2318
}
2319

2320
static bool service_good(Service *s) {
2,112✔
2321
        int main_pid_ok;
2,112✔
2322

2323
        assert(s);
2,112✔
2324

2325
        if (s->type == SERVICE_DBUS && !s->bus_name_good)
2,112✔
2326
                return false;
2327

2328
        main_pid_ok = main_pid_good(s);
2,110✔
2329
        if (main_pid_ok > 0) /* It's alive */
2,110✔
2330
                return true;
2331
        if (main_pid_ok == 0 && s->exit_type == SERVICE_EXIT_MAIN) /* It's dead */
1,133✔
2332
                return false;
2333

2334
        /* OK, we don't know anything about the main PID, maybe
2335
         * because there is none. Let's check the control group
2336
         * instead. */
2337

2338
        return cgroup_good(s) != 0;
211✔
2339
}
2340

2341
static void service_enter_running(Service *s, ServiceResult f) {
2,134✔
2342
        int r;
2,134✔
2343

2344
        assert(s);
2,134✔
2345

2346
        if (s->result == SERVICE_SUCCESS)
2,134✔
2347
                s->result = f;
2,112✔
2348

2349
        service_unwatch_control_pid(s);
2,134✔
2350

2351
        if (s->result != SERVICE_SUCCESS)
2,134✔
2352
                service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
22✔
2353
        else if (service_good(s)) {
2,112✔
2354

2355
                /* If there are any queued up sd_notify() notifications, process them now */
2356
                if (s->notify_state == NOTIFY_RELOADING)
977✔
2357
                        service_enter_reload_by_notify(s);
3✔
2358
                else if (s->notify_state == NOTIFY_STOPPING)
974✔
2359
                        service_enter_stop_by_notify(s);
×
2360
                else {
2361
                        service_set_state(s, SERVICE_RUNNING);
974✔
2362

2363
                        r = service_arm_timer(s, /* relative= */ false, service_running_timeout(s));
974✔
2364
                        if (r < 0) {
974✔
2365
                                log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2366
                                service_enter_running(s, SERVICE_FAILURE_RESOURCES);
×
2367
                                return;
×
2368
                        }
2369
                }
2370

2371
        } else if (s->remain_after_exit)
1,135✔
2372
                service_set_state(s, SERVICE_EXITED);
764✔
2373
        else
2374
                service_enter_stop(s, SERVICE_SUCCESS);
371✔
2375
}
2376

2377
static void service_enter_start_post(Service *s) {
1,884✔
2378
        int r;
1,884✔
2379

2380
        assert(s);
1,884✔
2381

2382
        service_unwatch_control_pid(s);
1,884✔
2383
        service_reset_watchdog(s);
1,884✔
2384

2385
        s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1,884✔
2386
        if (s->control_command) {
1,884✔
2387
                s->control_command_id = SERVICE_EXEC_START_POST;
×
2388
                pidref_done(&s->control_pid);
×
2389

2390
                r = service_spawn(s,
×
2391
                                  s->control_command,
2392
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2393
                                  s->timeout_start_usec,
2394
                                  &s->control_pid);
2395
                if (r < 0) {
×
2396
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-post' task: %m");
×
2397
                        service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
×
2398
                        return;
×
2399
                }
2400

2401
                service_set_state(s, SERVICE_START_POST);
×
2402
        } else
2403
                service_enter_running(s, SERVICE_SUCCESS);
1,884✔
2404
}
2405

2406
static void service_kill_control_process(Service *s) {
3✔
2407
        int r;
3✔
2408

2409
        assert(s);
3✔
2410

2411
        if (!pidref_is_set(&s->control_pid))
3✔
2412
                return;
2413

2414
        r = pidref_kill_and_sigcont(&s->control_pid, SIGKILL);
×
2415
        if (r < 0) {
×
2416
                _cleanup_free_ char *comm = NULL;
×
2417

2418
                (void) pidref_get_comm(&s->control_pid, &comm);
×
2419

2420
                log_unit_debug_errno(UNIT(s), r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m",
×
2421
                                     s->control_pid.pid, strna(comm));
2422
        }
2423
}
2424

2425
static int service_adverse_to_leftover_processes(Service *s) {
1,945✔
2426
        assert(s);
1,945✔
2427

2428
        /* KillMode=mixed and control group are used to indicate that all process should be killed off.
2429
         * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2430
         * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2431
         * time is quite variable (so Timeout settings aren't of use).
2432
         *
2433
         * Here we take these two factors and refuse to start a service if there are existing processes
2434
         * within a control group. Databases, while generally having some protection against multiple
2435
         * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
2436
         * aren't as rigoriously written to protect against multiple use. */
2437

2438
        if (unit_warn_leftover_processes(UNIT(s), /* start = */ true) > 0 &&
1,945✔
2439
            IN_SET(s->kill_context.kill_mode, KILL_MIXED, KILL_CONTROL_GROUP) &&
×
2440
            !s->kill_context.send_sigkill)
×
2441
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EBUSY),
×
2442
                                            "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2443

2444
        return 0;
2445
}
2446

2447
static void service_enter_start(Service *s) {
1,920✔
2448
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
1,920✔
2449
        ExecCommand *c;
1,920✔
2450
        usec_t timeout;
1,920✔
2451
        int r;
1,920✔
2452

2453
        assert(s);
1,920✔
2454

2455
        service_unwatch_control_pid(s);
1,920✔
2456
        service_unwatch_main_pid(s);
1,920✔
2457

2458
        r = service_adverse_to_leftover_processes(s);
1,920✔
2459
        if (r < 0)
1,920✔
2460
                goto fail;
×
2461

2462
        if (s->type == SERVICE_FORKING) {
1,920✔
2463
                s->control_command_id = SERVICE_EXEC_START;
2✔
2464
                c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2✔
2465

2466
                s->main_command = NULL;
2✔
2467
        } else {
2468
                s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1,918✔
2469
                s->control_command = NULL;
1,918✔
2470

2471
                c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1,918✔
2472
        }
2473

2474
        if (!c) {
1,920✔
2475
                if (s->type != SERVICE_ONESHOT) {
211✔
2476
                        /* There's no command line configured for the main command? Hmm, that is strange.
2477
                         * This can only happen if the configuration changes at runtime. In this case,
2478
                         * let's enter a failure state. */
2479
                        r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENXIO), "There's no 'start' task anymore we could start.");
×
2480
                        goto fail;
×
2481
                }
2482

2483
                /* We force a fake state transition here. Otherwise, the unit would go directly from
2484
                 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
2485
                 * in between. This way we can later trigger actions that depend on the state
2486
                 * transition, including SuccessAction=. */
2487
                service_set_state(s, SERVICE_START);
211✔
2488

2489
                service_enter_start_post(s);
211✔
2490
                return;
2491
        }
2492

2493
        if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
1,709✔
2494
                /* For simple + idle this is the main process. We don't apply any timeout here, but
2495
                 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2496
                timeout = USEC_INFINITY;
2497
        else
2498
                timeout = s->timeout_start_usec;
1,205✔
2499

2500
        r = service_spawn(s,
1,709✔
2501
                          c,
2502
                          service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS_FRESH),
2503
                          timeout,
2504
                          &pidref);
2505
        if (r < 0) {
1,709✔
2506
                log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start' task: %m");
×
2507
                goto fail;
×
2508
        }
2509

2510
        assert(pidref.pid == c->exec_status.pid);
1,709✔
2511

2512
        switch (s->type) {
1,709✔
2513

2514
        case SERVICE_SIMPLE:
504✔
2515
        case SERVICE_IDLE:
2516
                /* For simple services we immediately start the START_POST binaries. */
2517
                (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), &c->exec_status.start_timestamp);
504✔
2518
                return service_enter_start_post(s);
504✔
2519

2520
        case SERVICE_FORKING:
2✔
2521
                /* For forking services we wait until the start process exited. */
2522
                pidref_done(&s->control_pid);
2✔
2523
                s->control_pid = TAKE_PIDREF(pidref);
2✔
2524
                return service_set_state(s, SERVICE_START);
2✔
2525

2526
        case SERVICE_ONESHOT: /* For oneshot services we wait until the start process exited, too, but it is our main process. */
1,203✔
2527
        case SERVICE_EXEC:
2528
        case SERVICE_DBUS:
2529
        case SERVICE_NOTIFY:
2530
        case SERVICE_NOTIFY_RELOAD:
2531
                /* For D-Bus services we know the main pid right away, but wait for the bus name to appear
2532
                 * on the bus. 'notify' and 'exec' services wait for readiness notification and EOF
2533
                 * on exec_fd, respectively. */
2534
                (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), &c->exec_status.start_timestamp);
1,203✔
2535
                return service_set_state(s, SERVICE_START);
1,203✔
2536

2537
        default:
×
2538
                assert_not_reached();
×
2539
        }
2540

2541
fail:
×
2542
        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
2543
}
2544

2545
static void service_enter_start_pre(Service *s) {
1,920✔
2546
        int r;
1,920✔
2547

2548
        assert(s);
1,920✔
2549

2550
        service_unwatch_control_pid(s);
1,920✔
2551

2552
        s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1,920✔
2553
        if (s->control_command) {
1,920✔
2554

2555
                r = service_adverse_to_leftover_processes(s);
25✔
2556
                if (r < 0)
25✔
2557
                        goto fail;
×
2558

2559
                s->control_command_id = SERVICE_EXEC_START_PRE;
25✔
2560

2561
                r = service_spawn(s,
25✔
2562
                                  s->control_command,
2563
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2564
                                  s->timeout_start_usec,
2565
                                  &s->control_pid);
2566
                if (r < 0) {
25✔
2567
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-pre' task: %m");
×
2568
                        goto fail;
×
2569
                }
2570

2571
                service_set_state(s, SERVICE_START_PRE);
25✔
2572
        } else
2573
                service_enter_start(s);
1,895✔
2574

2575
        return;
2576

2577
fail:
×
2578
        service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
×
2579
}
2580

2581
static void service_enter_condition(Service *s) {
1,920✔
2582
        int r;
1,920✔
2583

2584
        assert(s);
1,920✔
2585

2586
        service_unwatch_control_pid(s);
1,920✔
2587

2588
        s->control_command = s->exec_command[SERVICE_EXEC_CONDITION];
1,920✔
2589
        if (s->control_command) {
1,920✔
2590

2591
                r = service_adverse_to_leftover_processes(s);
×
2592
                if (r < 0)
×
2593
                        goto fail;
×
2594

2595
                s->control_command_id = SERVICE_EXEC_CONDITION;
×
2596
                pidref_done(&s->control_pid);
×
2597

2598
                r = service_spawn(s,
×
2599
                                  s->control_command,
2600
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2601
                                  s->timeout_start_usec,
2602
                                  &s->control_pid);
2603
                if (r < 0) {
×
2604
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'exec-condition' task: %m");
×
2605
                        goto fail;
×
2606
                }
2607

2608
                service_set_state(s, SERVICE_CONDITION);
×
2609
        } else
2610
                service_enter_start_pre(s);
1,920✔
2611

2612
        return;
2613

2614
fail:
×
2615
        service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
×
2616
}
2617

2618
static void service_enter_restart(Service *s, bool shortcut) {
5✔
2619
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
5✔
2620
        int r;
5✔
2621

2622
        /* shortcut: a manual start request is received, restart immediately */
2623

2624
        assert(s);
5✔
2625
        assert(s->state == SERVICE_AUTO_RESTART);
5✔
2626

2627
        if (!shortcut && unit_has_job_type(UNIT(s), JOB_STOP)) {
5✔
2628
                /* Don't restart things if we are going down anyway */
2629
                log_unit_info(UNIT(s), "Stop job pending for unit, skipping automatic restart.");
×
2630
                return;
×
2631
        }
2632

2633
        /* Any units that are bound to this service must also be restarted, unless RestartMode=direct.
2634
         * We use JOB_START for ourselves but then set JOB_RESTART_DEPENDENCIES which will enqueue JOB_RESTART
2635
         * for those dependency jobs in the former case, plain JOB_REPLACE when RestartMode=direct.
2636
         *
2637
         * Also, when RestartMode=direct is used, the service being restarted don't enter the inactive/failed state,
2638
         * i.e. unit_process_job -> job_finish_and_invalidate is never called, and the previous job might still
2639
         * be running (especially for Type=oneshot services).
2640
         * We need to refuse late merge and re-enqueue the anchor job. */
2641
        r = manager_add_job_full(UNIT(s)->manager,
15✔
2642
                                 JOB_START, UNIT(s),
5✔
2643
                                 s->restart_mode == SERVICE_RESTART_MODE_DIRECT ? JOB_REPLACE : JOB_RESTART_DEPENDENCIES,
5✔
2644
                                 TRANSACTION_REENQUEUE_ANCHOR,
2645
                                 /* affected_jobs = */ NULL,
2646
                                 &error, /* ret = */ NULL);
2647
        if (r < 0) {
5✔
2648
                log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, r));
×
2649
                return service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
×
2650
        }
2651

2652
        /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't
2653
         * fully stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset
2654
         * the counter explicitly however via the usual "systemctl reset-failure" logic. */
2655
        s->n_restarts++;
5✔
2656

2657
        log_unit_struct(UNIT(s), LOG_INFO,
5✔
2658
                        LOG_MESSAGE_ID(SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR),
2659
                        LOG_UNIT_INVOCATION_ID(UNIT(s)),
2660
                        LOG_UNIT_MESSAGE(UNIT(s),
2661
                                         "Scheduled restart job%s, restart counter is at %u.",
2662
                                         shortcut ? " immediately on client request" : "", s->n_restarts),
2663
                        LOG_ITEM("N_RESTARTS=%u", s->n_restarts));
2664

2665
        service_set_state(s, SERVICE_AUTO_RESTART_QUEUED);
5✔
2666

2667
        /* Notify clients about changed restart counter */
2668
        unit_add_to_dbus_queue(UNIT(s));
5✔
2669
}
2670

2671
static void service_enter_reload_by_notify(Service *s) {
25✔
2672
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
25✔
2673
        int r;
25✔
2674

2675
        assert(s);
25✔
2676

2677
        r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
25✔
2678
        if (r < 0) {
25✔
2679
                log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2680
                s->reload_result = SERVICE_FAILURE_RESOURCES;
×
2681
                service_enter_running(s, SERVICE_SUCCESS);
×
2682
                return;
×
2683
        }
2684

2685
        service_set_state(s, SERVICE_RELOAD_NOTIFY);
25✔
2686

2687
        /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2688
        r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
25✔
2689
        if (r < 0)
25✔
2690
                log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error, r));
×
2691
}
2692

2693
static void service_enter_reload(Service *s) {
3✔
2694
        bool killed = false;
3✔
2695
        int r;
3✔
2696

2697
        assert(s);
3✔
2698

2699
        service_unwatch_control_pid(s);
3✔
2700
        s->reload_result = SERVICE_SUCCESS;
3✔
2701

2702
        usec_t ts = now(CLOCK_MONOTONIC);
3✔
2703

2704
        if (s->type == SERVICE_NOTIFY_RELOAD && pidref_is_set(&s->main_pid)) {
3✔
2705
                r = pidref_kill_and_sigcont(&s->main_pid, s->reload_signal);
×
2706
                if (r < 0) {
×
2707
                        log_unit_warning_errno(UNIT(s), r, "Failed to send reload signal: %m");
×
2708
                        goto fail;
×
2709
                }
2710

2711
                killed = true;
2712
        }
2713

2714
        s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
3✔
2715
        if (s->control_command) {
3✔
2716
                s->control_command_id = SERVICE_EXEC_RELOAD;
3✔
2717
                pidref_done(&s->control_pid);
3✔
2718

2719
                r = service_spawn(s,
3✔
2720
                                  s->control_command,
2721
                                  service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2722
                                  s->timeout_start_usec,
2723
                                  &s->control_pid);
2724
                if (r < 0) {
3✔
2725
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'reload' task: %m");
×
2726
                        goto fail;
×
2727
                }
2728

2729
                service_set_state(s, SERVICE_RELOAD);
3✔
2730
        } else if (killed) {
×
2731
                r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
×
2732
                if (r < 0) {
×
2733
                        log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2734
                        goto fail;
×
2735
                }
2736

2737
                service_set_state(s, SERVICE_RELOAD_SIGNAL);
×
2738
        } else {
2739
                service_enter_running(s, SERVICE_SUCCESS);
×
2740
                return;
×
2741
        }
2742

2743
        /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2744
         * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2745
         * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2746
         * that was already in progress before. */
2747
        s->reload_begin_usec = ts;
3✔
2748
        return;
3✔
2749

2750
fail:
×
2751
        s->reload_result = SERVICE_FAILURE_RESOURCES;
×
2752
        service_enter_running(s, SERVICE_SUCCESS);
×
2753
}
2754

2755
static void service_run_next_control(Service *s) {
1✔
2756
        usec_t timeout;
1✔
2757
        int r;
1✔
2758

2759
        assert(s);
1✔
2760
        assert(s->control_command);
1✔
2761
        assert(s->control_command->command_next);
1✔
2762

2763
        assert(s->control_command_id != SERVICE_EXEC_START);
1✔
2764

2765
        s->control_command = s->control_command->command_next;
1✔
2766
        service_unwatch_control_pid(s);
1✔
2767

2768
        if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1✔
2769
                timeout = s->timeout_start_usec;
1✔
2770
        else
2771
                timeout = s->timeout_stop_usec;
×
2772

2773
        pidref_done(&s->control_pid);
1✔
2774

2775
        r = service_spawn(s,
1✔
2776
                          s->control_command,
2777
                          service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
2778
                          timeout,
2779
                          &s->control_pid);
2780
        if (r < 0) {
1✔
2781
                log_unit_warning_errno(UNIT(s), r, "Failed to spawn next control task: %m");
×
2782

2783
                if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START_POST, SERVICE_STOP))
×
2784
                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
2785
                else if (s->state == SERVICE_STOP_POST)
×
2786
                        service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
×
2787
                else if (s->state == SERVICE_RELOAD) {
×
2788
                        s->reload_result = SERVICE_FAILURE_RESOURCES;
×
2789
                        service_enter_running(s, SERVICE_SUCCESS);
×
2790
                } else
2791
                        service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
×
2792
        }
2793
}
1✔
2794

2795
static void service_run_next_main(Service *s) {
2✔
2796
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
2✔
2797
        int r;
2✔
2798

2799
        assert(s);
2✔
2800
        assert(s->main_command);
2✔
2801
        assert(s->main_command->command_next);
2✔
2802
        assert(s->type == SERVICE_ONESHOT);
2✔
2803

2804
        s->main_command = s->main_command->command_next;
2✔
2805
        service_unwatch_main_pid(s);
2✔
2806

2807
        r = service_spawn(s,
2✔
2808
                          s->main_command,
2809
                          service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS),
2810
                          s->timeout_start_usec,
2811
                          &pidref);
2812
        if (r < 0) {
2✔
2813
                log_unit_warning_errno(UNIT(s), r, "Failed to spawn next main task: %m");
×
2814
                service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
×
2815
                return;
×
2816
        }
2817

2818
        (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), &s->main_command->exec_status.start_timestamp);
2✔
2819
}
2820

2821
static int service_start(Unit *u) {
1,922✔
2822
        Service *s = ASSERT_PTR(SERVICE(u));
1,922✔
2823
        int r;
1,922✔
2824

2825
        /* We cannot fulfill this request right now, try again later
2826
         * please! */
2827
        if (IN_SET(s->state,
1,922✔
2828
                   SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2829
                   SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
2830
                return -EAGAIN;
2831

2832
        /* Already on it! */
2833
        if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
1,920✔
2834
                return 0;
2835

2836
        if (s->state == SERVICE_AUTO_RESTART) {
1,920✔
2837
                /* As mentioned in unit_start(), we allow manual starts to act as "hurry up" signals
2838
                 * for auto restart. We need to re-enqueue the job though, as the job type has changed
2839
                 * (JOB_RESTART_DEPENDENCIES). */
2840

2841
                service_enter_restart(s, /* shortcut = */ true);
×
2842
                return -EAGAIN;
×
2843
        }
2844

2845
        /* SERVICE_*_BEFORE_AUTO_RESTART are not to be expected here, as those are intermediate states
2846
         * that should never be seen outside of service_enter_dead(). */
2847
        assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED, SERVICE_AUTO_RESTART_QUEUED));
1,920✔
2848

2849
        r = unit_acquire_invocation_id(u);
1,920✔
2850
        if (r < 0)
1,920✔
2851
                return r;
2852

2853
        s->result = SERVICE_SUCCESS;
1,920✔
2854
        s->reload_result = SERVICE_SUCCESS;
1,920✔
2855
        s->main_pid_known = false;
1,920✔
2856
        s->main_pid_alien = false;
1,920✔
2857
        s->forbid_restart = false;
1,920✔
2858

2859
        /* This is not an automatic restart? Flush the restart counter then. */
2860
        if (s->state != SERVICE_AUTO_RESTART_QUEUED)
1,920✔
2861
                s->n_restarts = 0;
1,916✔
2862

2863
        s->status_text = mfree(s->status_text);
1,920✔
2864
        s->status_errno = 0;
1,920✔
2865
        s->status_bus_error = mfree(s->status_bus_error);
1,920✔
2866
        s->status_varlink_error = mfree(s->status_varlink_error);
1,920✔
2867

2868
        s->notify_access_override = _NOTIFY_ACCESS_INVALID;
1,920✔
2869
        s->notify_state = NOTIFY_UNKNOWN;
1,920✔
2870

2871
        s->watchdog_original_usec = s->watchdog_usec;
1,920✔
2872
        s->watchdog_override_enable = false;
1,920✔
2873
        s->watchdog_override_usec = USEC_INFINITY;
1,920✔
2874

2875
        exec_command_reset_status_list_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
1,920✔
2876
        exec_status_reset(&s->main_exec_status);
1,920✔
2877

2878
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1,920✔
2879
        if (crt)
1,920✔
2880
                crt->reset_accounting = true;
60✔
2881

2882
        service_enter_condition(s);
1,920✔
2883
        return 1;
1,920✔
2884
}
2885

2886
static void service_live_mount_finish(Service *s, ServiceResult f, const char *error) {
×
2887
        assert(s);
×
2888
        assert(error);
×
2889

2890
        s->live_mount_result = f;
×
2891

2892
        if (!s->mount_request)
×
2893
                return;
2894

2895
        if (f == SERVICE_SUCCESS) {
×
2896
                (void) sd_bus_reply_method_return(s->mount_request, NULL);
×
2897
                log_unit_debug(UNIT(s),
×
2898
                               "'%s' method succeeded",
2899
                               strna(sd_bus_message_get_member(s->mount_request)));
2900
        } else {
2901
                (void) sd_bus_reply_method_errorf(s->mount_request, error,
×
2902
                                                  "method '%s' for unit '%s' failed",
2903
                                                  strna(sd_bus_message_get_member(s->mount_request)),
2904
                                                  UNIT(s)->id);
×
2905
                log_unit_debug(UNIT(s),
×
2906
                               "'%s' method failed: %s",
2907
                               strna(sd_bus_message_get_member(s->mount_request)),
2908
                               error);
2909
        }
2910

2911
        s->mount_request = sd_bus_message_unref(s->mount_request);
×
2912
}
2913

2914
static int service_stop(Unit *u) {
1,106✔
2915
        Service *s = ASSERT_PTR(SERVICE(u));
1,106✔
2916

2917
        /* Don't create restart jobs from manual stops. */
2918
        s->forbid_restart = true;
1,106✔
2919

2920
        switch (s->state) {
1,106✔
2921

2922
        case SERVICE_STOP:
2923
        case SERVICE_STOP_SIGTERM:
2924
        case SERVICE_STOP_SIGKILL:
2925
        case SERVICE_STOP_POST:
2926
        case SERVICE_FINAL_WATCHDOG:
2927
        case SERVICE_FINAL_SIGTERM:
2928
        case SERVICE_FINAL_SIGKILL:
2929
                /* Already on it */
2930
                return 0;
2931

2932
        case SERVICE_AUTO_RESTART:
×
2933
        case SERVICE_AUTO_RESTART_QUEUED:
2934
                /* Give up on the auto restart */
2935
                service_set_state(s, service_determine_dead_state(s));
×
2936
                return 0;
×
2937

2938
        case SERVICE_MOUNTING:
×
2939
                service_kill_control_process(s);
×
2940
                service_live_mount_finish(s, SERVICE_FAILURE_PROTOCOL, BUS_ERROR_UNIT_INACTIVE);
×
2941
                _fallthrough_;
17✔
2942
        case SERVICE_CONDITION:
17✔
2943
        case SERVICE_START_PRE:
2944
        case SERVICE_START:
2945
        case SERVICE_START_POST:
2946
        case SERVICE_RELOAD:
2947
        case SERVICE_RELOAD_SIGNAL:
2948
        case SERVICE_RELOAD_NOTIFY:
2949
        case SERVICE_STOP_WATCHDOG:
2950
                /* If there's already something running we go directly into kill mode. */
2951
                service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
17✔
2952
                return 0;
17✔
2953

2954
        case SERVICE_CLEANING:
×
2955
                /* If we are currently cleaning, then abort it, brutally. */
2956
                service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
×
2957
                return 0;
×
2958

2959
        case SERVICE_RUNNING:
1,089✔
2960
        case SERVICE_EXITED:
2961
                service_enter_stop(s, SERVICE_SUCCESS);
1,089✔
2962
                return 1;
1,089✔
2963

2964
        case SERVICE_DEAD_BEFORE_AUTO_RESTART:
×
2965
        case SERVICE_FAILED_BEFORE_AUTO_RESTART:
2966
        case SERVICE_DEAD:
2967
        case SERVICE_FAILED:
2968
        case SERVICE_DEAD_RESOURCES_PINNED:
2969
        default:
2970
                /* Unknown state, or unit_stop() should already have handled these */
2971
                assert_not_reached();
×
2972
        }
2973
}
2974

2975
static int service_reload(Unit *u) {
3✔
2976
        Service *s = ASSERT_PTR(SERVICE(u));
3✔
2977

2978
        assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
3✔
2979

2980
        service_enter_reload(s);
3✔
2981
        return 1;
3✔
2982
}
2983

2984
static bool service_can_reload(Unit *u) {
1,086✔
2985
        Service *s = ASSERT_PTR(SERVICE(u));
1,086✔
2986

2987
        return s->exec_command[SERVICE_EXEC_RELOAD] ||
1,086✔
2988
                s->type == SERVICE_NOTIFY_RELOAD;
1,050✔
2989
}
2990

2991
static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, const ExecCommand *current) {
791✔
2992
        Service *s = SERVICE(u);
791✔
2993
        unsigned idx = 0;
791✔
2994

2995
        assert(s);
×
2996
        assert(id >= 0);
791✔
2997
        assert(id < _SERVICE_EXEC_COMMAND_MAX);
791✔
2998

2999
        const ExecCommand *first = s->exec_command[id];
791✔
3000

3001
        /* Figure out where we are in the list by walking back to the beginning */
3002
        for (const ExecCommand *c = current; c != first; c = c->command_prev)
791✔
3003
                idx++;
×
3004

3005
        return idx;
791✔
3006
}
3007

3008
static int service_serialize_exec_command(Unit *u, FILE *f, const ExecCommand *command) {
14,386✔
3009
        Service *s = ASSERT_PTR(SERVICE(u));
14,386✔
3010
        _cleanup_free_ char *args = NULL, *p = NULL;
14,386✔
3011
        const char *type, *key;
14,386✔
3012
        ServiceExecCommand id;
14,386✔
3013
        size_t length = 0;
14,386✔
3014
        unsigned idx;
14,386✔
3015

3016
        assert(f);
14,386✔
3017

3018
        if (!command)
14,386✔
3019
                return 0;
3020

3021
        if (command == s->control_command) {
791✔
3022
                type = "control";
×
3023
                id = s->control_command_id;
×
3024
        } else {
3025
                type = "main";
3026
                id = SERVICE_EXEC_START;
3027
        }
3028

3029
        idx = service_exec_command_index(u, id, command);
791✔
3030

3031
        STRV_FOREACH(arg, command->argv) {
2,267✔
3032
                _cleanup_free_ char *e = NULL;
1,476✔
3033
                size_t n;
1,476✔
3034

3035
                e = cescape(*arg);
1,476✔
3036
                if (!e)
1,476✔
3037
                        return log_oom();
×
3038

3039
                n = strlen(e);
1,476✔
3040
                if (!GREEDY_REALLOC(args, length + 2 + n + 2))
1,476✔
3041
                        return log_oom();
×
3042

3043
                if (length > 0)
1,476✔
3044
                        args[length++] = ' ';
685✔
3045

3046
                args[length++] = '"';
1,476✔
3047
                memcpy(args + length, e, n);
1,476✔
3048
                length += n;
1,476✔
3049
                args[length++] = '"';
1,476✔
3050
        }
3051

3052
        if (!GREEDY_REALLOC(args, length + 1))
791✔
3053
                return log_oom();
×
3054

3055
        args[length++] = 0;
791✔
3056

3057
        p = cescape(command->path);
791✔
3058
        if (!p)
791✔
3059
                return log_oom();
×
3060

3061
        key = strjoina(type, "-command");
3,955✔
3062

3063
        /* We use '+1234' instead of '1234' to mark the last command in a sequence.
3064
         * This is used in service_deserialize_exec_command(). */
3065
        (void) serialize_item_format(
791✔
3066
                        f, key,
3067
                        "%s %s%u %s %s",
3068
                        service_exec_command_to_string(id),
3069
                        command->command_next ? "" : "+",
791✔
3070
                        idx,
3071
                        p, args);
3072

3073
        return 0;
3074
}
3075

3076
static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
7,193✔
3077
        Service *s = ASSERT_PTR(SERVICE(u));
7,193✔
3078
        int r;
7,193✔
3079

3080
        assert(f);
7,193✔
3081
        assert(fds);
7,193✔
3082

3083
        (void) serialize_item(f, "state", service_state_to_string(s->state));
7,193✔
3084
        (void) serialize_item(f, "result", service_result_to_string(s->result));
7,193✔
3085
        (void) serialize_item(f, "reload-result", service_result_to_string(s->reload_result));
7,193✔
3086
        (void) serialize_item(f, "live-mount-result", service_result_to_string(s->live_mount_result));
7,193✔
3087

3088
        (void) serialize_pidref(f, fds, "control-pid", &s->control_pid);
7,193✔
3089
        if (s->main_pid_known)
7,193✔
3090
                (void) serialize_pidref(f, fds, "main-pid", &s->main_pid);
2,310✔
3091

3092
        (void) serialize_bool(f, "main-pid-known", s->main_pid_known);
7,193✔
3093
        (void) serialize_bool(f, "bus-name-good", s->bus_name_good);
7,193✔
3094

3095
        (void) serialize_item_format(f, "n-restarts", "%u", s->n_restarts);
7,193✔
3096
        (void) serialize_bool(f, "forbid-restart", s->forbid_restart);
7,193✔
3097

3098
        service_serialize_exec_command(u, f, s->control_command);
7,193✔
3099
        service_serialize_exec_command(u, f, s->main_command);
7,193✔
3100

3101
        r = serialize_fd(f, fds, "stdin-fd", s->stdin_fd);
7,193✔
3102
        if (r < 0)
7,193✔
3103
                return r;
3104
        r = serialize_fd(f, fds, "stdout-fd", s->stdout_fd);
7,193✔
3105
        if (r < 0)
7,193✔
3106
                return r;
3107
        r = serialize_fd(f, fds, "stderr-fd", s->stderr_fd);
7,193✔
3108
        if (r < 0)
7,193✔
3109
                return r;
3110

3111
        if (s->exec_fd_event_source) {
7,193✔
3112
                r = serialize_fd(f, fds, "exec-fd", sd_event_source_get_io_fd(s->exec_fd_event_source));
×
3113
                if (r < 0)
×
3114
                        return r;
3115

3116
                (void) serialize_bool(f, "exec-fd-hot", s->exec_fd_hot);
×
3117
        }
3118

3119
        if (UNIT_ISSET(s->accept_socket)) {
7,193✔
3120
                r = serialize_item(f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
×
3121
                if (r < 0)
×
3122
                        return r;
3123
        }
3124

3125
        r = serialize_fd(f, fds, "socket-fd", s->socket_fd);
7,193✔
3126
        if (r < 0)
7,193✔
3127
                return r;
3128

3129
        LIST_FOREACH(fd_store, fs, s->fd_store) {
8,259✔
3130
                _cleanup_free_ char *c = NULL;
1,066✔
3131
                int copy;
1,066✔
3132

3133
                copy = fdset_put_dup(fds, fs->fd);
1,066✔
3134
                if (copy < 0)
1,066✔
3135
                        return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
×
3136

3137
                c = cescape(fs->fdname);
1,066✔
3138
                if (!c)
1,066✔
3139
                        return log_oom();
×
3140

3141
                (void) serialize_item_format(f, "fd-store-fd", "%i \"%s\" %s", copy, c, one_zero(fs->do_poll));
1,066✔
3142
        }
3143

3144
        FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
7,195✔
3145
                _cleanup_free_ char *c = NULL;
2✔
3146
                int copy;
2✔
3147

3148
                copy = fdset_put_dup(fds, i->fd);
2✔
3149
                if (copy < 0)
2✔
3150
                        return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
×
3151

3152
                c = cescape(i->fdname);
2✔
3153
                if (!c)
2✔
3154
                        return log_oom();
×
3155

3156
                (void) serialize_item_format(f, "extra-fd", "%i \"%s\"", copy, c);
2✔
3157
        }
3158

3159
        if (s->main_exec_status.pid > 0) {
7,193✔
3160
                (void) serialize_item_format(f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2,310✔
3161
                (void) serialize_dual_timestamp(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2,310✔
3162
                (void) serialize_dual_timestamp(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2,310✔
3163
                (void) serialize_dual_timestamp(f, "main-exec-status-handoff", &s->main_exec_status.handoff_timestamp);
2,310✔
3164

3165
                if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2,310✔
3166
                        (void) serialize_item_format(f, "main-exec-status-code", "%i", s->main_exec_status.code);
1,519✔
3167
                        (void) serialize_item_format(f, "main-exec-status-status", "%i", s->main_exec_status.status);
1,519✔
3168
                }
3169
        }
3170

3171
        if (s->notify_access_override >= 0)
7,193✔
3172
                (void) serialize_item(f, "notify-access-override", notify_access_to_string(s->notify_access_override));
×
3173

3174
        r = serialize_item_escaped(f, "status-text", s->status_text);
7,193✔
3175
        if (r < 0)
7,193✔
3176
                return r;
3177

3178
        (void) serialize_item_format(f, "status-errno", "%d", s->status_errno);
7,193✔
3179
        (void) serialize_item(f, "status-bus-error", s->status_bus_error);
7,193✔
3180
        (void) serialize_item(f, "status-varlink-error", s->status_varlink_error);
7,193✔
3181

3182
        (void) serialize_dual_timestamp(f, "watchdog-timestamp", &s->watchdog_timestamp);
7,193✔
3183

3184
        (void) serialize_usec(f, "watchdog-original-usec", s->watchdog_original_usec);
7,193✔
3185
        if (s->watchdog_override_enable)
7,193✔
3186
                (void) serialize_usec(f, "watchdog-override-usec", s->watchdog_override_usec);
×
3187

3188
        (void) serialize_usec(f, "reload-begin-usec", s->reload_begin_usec);
7,193✔
3189

3190
        return 0;
7,193✔
3191
}
3192

3193
int service_deserialize_exec_command(
662✔
3194
                Unit *u,
3195
                const char *key,
3196
                const char *value) {
3197

3198
        Service *s = ASSERT_PTR(SERVICE(u));
662✔
3199
        ExecCommand *command = NULL;
662✔
3200
        ServiceExecCommand id = _SERVICE_EXEC_COMMAND_INVALID;
662✔
3201
        _cleanup_free_ char *path = NULL;
662✔
3202
        _cleanup_strv_free_ char **argv = NULL;
×
3203
        unsigned idx = 0, i;
662✔
3204
        bool control, found = false, last = false;
662✔
3205
        int r;
662✔
3206

3207
        enum ExecCommandState {
662✔
3208
                STATE_EXEC_COMMAND_TYPE,
3209
                STATE_EXEC_COMMAND_INDEX,
3210
                STATE_EXEC_COMMAND_PATH,
3211
                STATE_EXEC_COMMAND_ARGS,
3212
                _STATE_EXEC_COMMAND_MAX,
3213
                _STATE_EXEC_COMMAND_INVALID = -EINVAL,
3214
        } state;
3215

3216
        assert(key);
662✔
3217
        assert(value);
662✔
3218

3219
        control = streq(key, "control-command");
662✔
3220

3221
        state = STATE_EXEC_COMMAND_TYPE;
662✔
3222

3223
        for (;;) {
7,100✔
3224
                _cleanup_free_ char *arg = NULL;
3,222✔
3225

3226
                r = extract_first_word(&value, &arg, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
3,881✔
3227
                if (r < 0)
3,881✔
3228
                        return r;
3229
                if (r == 0)
3,880✔
3230
                        break;
3231

3232
                switch (state) {
3,221✔
3233
                case STATE_EXEC_COMMAND_TYPE:
662✔
3234
                        id = service_exec_command_from_string(arg);
662✔
3235
                        if (id < 0)
662✔
3236
                                return id;
3237

3238
                        state = STATE_EXEC_COMMAND_INDEX;
3239
                        break;
3240
                case STATE_EXEC_COMMAND_INDEX:
661✔
3241
                        /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3242
                         * mark the last command in a sequence. We warn if the deserialized command doesn't
3243
                         * match what we have loaded from the unit, but we don't need to warn if that is the
3244
                         * last command. */
3245

3246
                        r = safe_atou(arg, &idx);
661✔
3247
                        if (r < 0)
661✔
3248
                                return r;
3249
                        last = arg[0] == '+';
660✔
3250

3251
                        state = STATE_EXEC_COMMAND_PATH;
660✔
3252
                        break;
660✔
3253
                case STATE_EXEC_COMMAND_PATH:
659✔
3254
                        path = TAKE_PTR(arg);
659✔
3255
                        state = STATE_EXEC_COMMAND_ARGS;
659✔
3256
                        break;
659✔
3257
                case STATE_EXEC_COMMAND_ARGS:
1,239✔
3258
                        r = strv_extend(&argv, arg);
1,239✔
3259
                        if (r < 0)
1,239✔
3260
                                return r;
3261
                        break;
3262
                default:
×
3263
                        assert_not_reached();
×
3264
                }
3265
        }
3266

3267
        if (state != STATE_EXEC_COMMAND_ARGS)
659✔
3268
                return -EINVAL;
3269
        if (strv_isempty(argv))
1,319✔
3270
                return -EINVAL; /* At least argv[0] must be always present. */
3271

3272
        /* Let's check whether exec command on given offset matches data that we just deserialized */
3273
        for (command = s->exec_command[id], i = 0; command; command = command->command_next, i++) {
657✔
3274
                if (i != idx)
652✔
3275
                        continue;
×
3276

3277
                found = strv_equal(argv, command->argv) && streq(command->path, path);
652✔
3278
                break;
3279
        }
3280

3281
        if (!found) {
3282
                /* Command at the index we serialized is different, let's look for command that exactly
3283
                 * matches but is on different index. If there is no such command we will not resume execution. */
3284
                for (command = s->exec_command[id]; command; command = command->command_next)
5✔
3285
                        if (strv_equal(command->argv, argv) && streq(command->path, path))
×
3286
                                break;
3287
        }
3288

3289
        if (command && control) {
657✔
3290
                s->control_command = command;
×
3291
                s->control_command_id = id;
×
3292
        } else if (command)
657✔
3293
                s->main_command = command;
652✔
3294
        else if (last)
5✔
3295
                log_unit_debug(u, "Current command vanished from the unit file.");
×
3296
        else
3297
                log_unit_warning(u, "Current command vanished from the unit file, execution of the command list won't be resumed.");
5✔
3298

3299
        return 0;
3300
}
3301

3302
static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
64,795✔
3303
        Service *s = ASSERT_PTR(SERVICE(u));
64,795✔
3304
        int r;
64,795✔
3305

3306
        assert(key);
64,795✔
3307
        assert(value);
64,795✔
3308
        assert(fds);
64,795✔
3309

3310
        if (streq(key, "state")) {
64,795✔
3311
                ServiceState state;
5,595✔
3312

3313
                state = service_state_from_string(value);
5,595✔
3314
                if (state < 0)
5,595✔
3315
                        log_unit_debug_errno(u, state, "Failed to parse state value: %s", value);
×
3316
                else
3317
                        s->deserialized_state = state;
5,595✔
3318
        } else if (streq(key, "result")) {
59,200✔
3319
                ServiceResult f;
5,595✔
3320

3321
                f = service_result_from_string(value);
5,595✔
3322
                if (f < 0)
5,595✔
3323
                        log_unit_debug_errno(u, f, "Failed to parse result value: %s", value);
×
3324
                else if (f != SERVICE_SUCCESS)
5,595✔
3325
                        s->result = f;
35✔
3326

3327
        } else if (streq(key, "reload-result")) {
53,605✔
3328
                ServiceResult f;
5,595✔
3329

3330
                f = service_result_from_string(value);
5,595✔
3331
                if (f < 0)
5,595✔
3332
                        log_unit_debug_errno(u, f, "Failed to parse reload result value: %s", value);
×
3333
                else if (f != SERVICE_SUCCESS)
5,595✔
3334
                        s->reload_result = f;
×
3335

3336
        } else if (streq(key, "live-mount-result")) {
48,010✔
3337
                ServiceResult f;
5,595✔
3338

3339
                f = service_result_from_string(value);
5,595✔
3340
                if (f < 0)
5,595✔
3341
                        log_unit_debug_errno(u, f, "Failed to parse live mount result value: %s", value);
×
3342
                else if (f != SERVICE_SUCCESS)
5,595✔
3343
                        s->live_mount_result = f;
×
3344

3345
        } else if (streq(key, "control-pid")) {
42,415✔
3346

3347
                if (!pidref_is_set(&s->control_pid))
64,795✔
3348
                        (void) deserialize_pidref(fds, value, &s->control_pid);
×
3349

3350
        } else if (streq(key, "main-pid")) {
42,415✔
3351
                PidRef pidref;
1,304✔
3352

3353
                if (!pidref_is_set(&s->main_pid) && deserialize_pidref(fds, value, &pidref) >= 0)
1,956✔
3354
                        (void) service_set_main_pidref(s, pidref, /* start_timestamp = */ NULL);
652✔
3355

3356
        } else if (streq(key, "main-pid-known")) {
41,111✔
3357
                r = parse_boolean(value);
5,595✔
3358
                if (r < 0)
5,595✔
3359
                        log_unit_debug_errno(u, r, "Failed to parse main-pid-known value: %s", value);
×
3360
                else
3361
                        s->main_pid_known = r;
5,595✔
3362
        } else if (streq(key, "bus-name-good")) {
35,516✔
3363
                r = parse_boolean(value);
5,595✔
3364
                if (r < 0)
5,595✔
3365
                        log_unit_debug_errno(u, r, "Failed to parse bus-name-good value: %s", value);
×
3366
                else
3367
                        s->bus_name_good = r;
5,595✔
3368
        } else if (streq(key, "accept-socket")) {
29,921✔
3369
                Unit *socket;
×
3370

3371
                if (unit_name_to_type(value) != UNIT_SOCKET) {
×
3372
                        log_unit_debug(u, "Deserialized accept-socket is not a socket unit, ignoring: %s", value);
×
3373
                        return 0;
×
3374
                }
3375

3376
                r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
×
3377
                if (r < 0)
×
3378
                        log_unit_debug_errno(u, r, "Failed to load accept-socket unit '%s': %m", value);
×
3379
                else {
3380
                        unit_ref_set(&s->accept_socket, u, socket);
×
3381
                        ASSERT_PTR(SOCKET(socket))->n_connections++;
×
3382
                }
3383

3384
        } else if (streq(key, "socket-fd")) {
29,921✔
3385
                asynchronous_close(s->socket_fd);
×
3386
                s->socket_fd = deserialize_fd(fds, value);
×
3387

3388
        } else if (streq(key, "fd-store-fd")) {
29,921✔
3389
                _cleanup_free_ char *fdv = NULL, *fdn = NULL, *fdp = NULL;
875✔
3390
                _cleanup_close_ int fd = -EBADF;
875✔
3391
                int do_poll;
875✔
3392

3393
                r = extract_many_words(&value, " ", EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE, &fdv, &fdn, &fdp);
875✔
3394
                if (r < 2 || r > 3) {
875✔
3395
                        log_unit_debug(u, "Failed to deserialize fd-store-fd, ignoring: %s", value);
×
3396
                        return 0;
×
3397
                }
3398

3399
                fd = deserialize_fd(fds, fdv);
875✔
3400
                if (fd < 0)
875✔
3401
                        return 0;
3402

3403
                do_poll = r == 3 ? parse_boolean(fdp) : true;
875✔
3404
                if (do_poll < 0) {
875✔
3405
                        log_unit_debug_errno(u, do_poll,
×
3406
                                             "Failed to deserialize fd-store-fd do_poll, ignoring: %s", fdp);
3407
                        return 0;
×
3408
                }
3409

3410
                r = service_add_fd_store(s, TAKE_FD(fd), fdn, do_poll);
875✔
3411
                if (r < 0) {
875✔
3412
                        log_unit_debug_errno(u, r,
×
3413
                                             "Failed to store deserialized fd '%s', ignoring: %m", fdn);
3414
                        return 0;
×
3415
                }
3416
        } else if (streq(key, "extra-fd")) {
29,046✔
3417
                _cleanup_free_ char *fdv = NULL, *fdn = NULL;
×
3418
                _cleanup_close_ int fd = -EBADF;
×
3419

3420
                r = extract_many_words(&value, " ", EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE, &fdv, &fdn);
×
3421
                if (r != 2) {
×
3422
                        log_unit_debug(u, "Failed to deserialize extra-fd, ignoring: %s", value);
×
3423
                        return 0;
×
3424
                }
3425

3426
                fd = deserialize_fd(fds, fdv);
×
3427
                if (fd < 0)
×
3428
                        return 0;
3429

3430
                if (!GREEDY_REALLOC(s->extra_fds, s->n_extra_fds + 1)) {
×
3431
                        log_oom_debug();
×
3432
                        return 0;
3433
                }
3434

3435
                s->extra_fds[s->n_extra_fds++] = (ServiceExtraFD) {
×
3436
                        .fd = TAKE_FD(fd),
×
3437
                        .fdname = TAKE_PTR(fdn),
×
3438
                };
3439
        } else if (streq(key, "main-exec-status-pid")) {
29,046✔
3440
                pid_t pid;
1,805✔
3441

3442
                if (parse_pid(value, &pid) < 0)
1,805✔
3443
                        log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
×
3444
                else
3445
                        s->main_exec_status.pid = pid;
1,805✔
3446
        } else if (streq(key, "main-exec-status-code")) {
27,241✔
3447
                int i;
1,153✔
3448

3449
                if (safe_atoi(value, &i) < 0)
1,153✔
3450
                        log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
×
3451
                else
3452
                        s->main_exec_status.code = i;
1,153✔
3453
        } else if (streq(key, "main-exec-status-status")) {
26,088✔
3454
                int i;
1,153✔
3455

3456
                if (safe_atoi(value, &i) < 0)
1,153✔
3457
                        log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
×
3458
                else
3459
                        s->main_exec_status.status = i;
1,153✔
3460
        } else if (streq(key, "main-exec-status-start"))
24,935✔
3461
                (void) deserialize_dual_timestamp(value, &s->main_exec_status.start_timestamp);
1,805✔
3462
        else if (streq(key, "main-exec-status-exit"))
23,130✔
3463
                (void) deserialize_dual_timestamp(value, &s->main_exec_status.exit_timestamp);
1,153✔
3464
        else if (streq(key, "main-exec-status-handoff"))
21,977✔
3465
                (void) deserialize_dual_timestamp(value, &s->main_exec_status.handoff_timestamp);
1,795✔
3466
        else if (STR_IN_SET(key, "main-command", "control-command")) {
20,182✔
3467
                r = service_deserialize_exec_command(u, key, value);
652✔
3468
                if (r < 0)
652✔
3469
                        log_unit_debug_errno(u, r, "Failed to parse serialized command \"%s\": %m", value);
×
3470
        } else if (streq(key, "notify-access-override")) {
19,530✔
3471
                NotifyAccess notify_access;
×
3472

3473
                notify_access = notify_access_from_string(value);
×
3474
                if (notify_access < 0)
×
3475
                        log_unit_debug(u, "Failed to parse notify-access-override value: %s", value);
×
3476
                else
3477
                        s->notify_access_override = notify_access;
×
3478
        } else if (streq(key, "n-restarts")) {
19,530✔
3479
                r = safe_atou(value, &s->n_restarts);
5,595✔
3480
                if (r < 0)
5,595✔
3481
                        log_unit_debug_errno(u, r, "Failed to parse serialized restart counter '%s': %m", value);
×
3482

3483
        } else if (streq(key, "forbid-restart")) {
13,935✔
3484
                r = parse_boolean(value);
5,595✔
3485
                if (r < 0)
5,595✔
3486
                        log_unit_debug_errno(u, r, "Failed to parse forbid-restart value: %s", value);
×
3487
                else
3488
                        s->forbid_restart = r;
5,595✔
3489
        } else if (streq(key, "stdin-fd")) {
8,340✔
3490

3491
                asynchronous_close(s->stdin_fd);
1✔
3492
                s->stdin_fd = deserialize_fd(fds, value);
1✔
3493
                if (s->stdin_fd >= 0)
1✔
3494
                        s->exec_context.stdio_as_fds = true;
1✔
3495

3496
        } else if (streq(key, "stdout-fd")) {
8,339✔
3497

3498
                asynchronous_close(s->stdout_fd);
1✔
3499
                s->stdout_fd = deserialize_fd(fds, value);
1✔
3500
                if (s->stdout_fd >= 0)
1✔
3501
                        s->exec_context.stdio_as_fds = true;
1✔
3502

3503
        } else if (streq(key, "stderr-fd")) {
8,338✔
3504

3505
                asynchronous_close(s->stderr_fd);
1✔
3506
                s->stderr_fd = deserialize_fd(fds, value);
1✔
3507
                if (s->stderr_fd >= 0)
1✔
3508
                        s->exec_context.stdio_as_fds = true;
1✔
3509

3510
        } else if (streq(key, "exec-fd")) {
8,337✔
3511
                _cleanup_close_ int fd = -EBADF;
20,182✔
3512

3513
                fd = deserialize_fd(fds, value);
×
3514
                if (fd >= 0) {
×
3515
                        s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
×
3516

3517
                        if (service_allocate_exec_fd_event_source(s, fd, &s->exec_fd_event_source) >= 0)
×
3518
                                TAKE_FD(fd);
×
3519
                }
3520

3521
        } else if (streq(key, "status-text")) {
8,337✔
3522
                char *t;
496✔
3523
                ssize_t l;
496✔
3524

3525
                l = cunescape(value, 0, &t);
496✔
3526
                if (l < 0)
496✔
3527
                        log_unit_debug_errno(u, l, "Failed to unescape status text '%s': %m", value);
×
3528
                else
3529
                        free_and_replace(s->status_text, t);
496✔
3530

3531
        } else if (streq(key, "status-errno")) {
7,841✔
3532
                int i;
5,595✔
3533

3534
                if (safe_atoi(value, &i) < 0)
5,595✔
3535
                        log_unit_debug(u, "Failed to parse status-errno value: %s", value);
×
3536
                else
3537
                        s->status_errno = i;
5,595✔
3538

3539
        } else if (streq(key, "status-bus-error")) {
2,246✔
3540
                if (free_and_strdup(&s->status_bus_error, value) < 0)
×
3541
                        log_oom_debug();
×
3542

3543
        } else if (streq(key, "status-varlink-error")) {
2,246✔
3544
                if (free_and_strdup(&s->status_varlink_error, value) < 0)
×
3545
                        log_oom_debug();
×
3546

3547
        } else if (streq(key, "watchdog-timestamp"))
2,246✔
3548
                (void) deserialize_dual_timestamp(value, &s->watchdog_timestamp);
390✔
3549
        else if (streq(key, "watchdog-original-usec"))
1,856✔
3550
                (void) deserialize_usec(value, &s->watchdog_original_usec);
1,856✔
3551
        else if (streq(key, "watchdog-override-usec")) {
×
3552
                if (deserialize_usec(value, &s->watchdog_override_usec) >= 0)
×
3553
                        s->watchdog_override_enable = true;
×
3554

3555
        } else if (streq(key, "reload-begin-usec"))
×
3556
                (void) deserialize_usec(value, &s->reload_begin_usec);
×
3557
        else
3558
                log_unit_debug(u, "Unknown serialization key: %s", key);
×
3559

3560
        return 0;
3561
}
3562

3563
static UnitActiveState service_active_state(Unit *u) {
917,296✔
3564
        Service *s = ASSERT_PTR(SERVICE(u));
917,296✔
3565
        const UnitActiveState *table;
917,296✔
3566

3567
        table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
917,296✔
3568

3569
        return table[s->state];
917,296✔
3570
}
3571

3572
static const char *service_sub_state_to_string(Unit *u) {
8,457✔
3573
        assert(u);
8,457✔
3574

3575
        return service_state_to_string(SERVICE(u)->state);
8,457✔
3576
}
3577

3578
static bool service_may_gc(Unit *u) {
37,789✔
3579
        Service *s = ASSERT_PTR(SERVICE(u));
37,789✔
3580

3581
        /* Never clean up services that still have a process around, even if the service is formally dead. Note that
3582
         * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
3583
         * have moved outside of the cgroup. */
3584

3585
        if (main_pid_good(s) > 0 ||
75,578✔
3586
            control_pid_good(s) > 0)
37,789✔
3587
                return false;
3588

3589
        /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3590
         * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
3591
        if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
37,789✔
3592
                return false;
×
3593

3594
        return true;
3595
}
3596

3597
static int service_retry_pid_file(Service *s) {
×
3598
        int r;
×
3599

3600
        assert(s);
×
3601
        assert(s->pid_file);
×
3602
        assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
×
3603

3604
        r = service_load_pid_file(s, false);
×
3605
        if (r < 0)
×
3606
                return r;
3607

3608
        service_unwatch_pid_file(s);
×
3609

3610
        service_enter_running(s, SERVICE_SUCCESS);
×
3611
        return 0;
×
3612
}
3613

3614
static int service_watch_pid_file(Service *s) {
×
3615
        int r;
×
3616

3617
        assert(s);
×
3618

3619
        log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
×
3620

3621
        r = path_spec_watch(s->pid_file_pathspec, service_dispatch_inotify_io);
×
3622
        if (r < 0) {
×
3623
                log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
×
3624
                service_unwatch_pid_file(s);
×
3625
                return r;
×
3626
        }
3627

3628
        /* the pidfile might have appeared just before we set the watch */
3629
        log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
×
3630
        service_retry_pid_file(s);
×
3631

3632
        return 0;
×
3633
}
3634

3635
static int service_demand_pid_file(Service *s) {
×
3636
        _cleanup_free_ PathSpec *ps = NULL;
×
3637

3638
        assert(s);
×
3639
        assert(s->pid_file);
×
3640
        assert(!s->pid_file_pathspec);
×
3641

3642
        ps = new(PathSpec, 1);
×
3643
        if (!ps)
×
3644
                return -ENOMEM;
3645

3646
        *ps = (PathSpec) {
×
3647
                .unit = UNIT(s),
×
3648
                .path = strdup(s->pid_file),
×
3649
                /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3650
                 * open all the time. */
3651
                .type = PATH_MODIFIED,
3652
                .inotify_fd = -EBADF,
3653
        };
3654

3655
        if (!ps->path)
×
3656
                return -ENOMEM;
3657

3658
        path_simplify(ps->path);
×
3659

3660
        s->pid_file_pathspec = TAKE_PTR(ps);
×
3661

3662
        return service_watch_pid_file(s);
×
3663
}
3664

3665
static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
×
3666
        PathSpec *p = ASSERT_PTR(userdata);
×
3667
        Service *s = ASSERT_PTR(SERVICE(p->unit));
×
3668

3669
        assert(fd >= 0);
×
3670
        assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
×
3671
        assert(s->pid_file_pathspec);
×
3672
        assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
×
3673

3674
        log_unit_debug(UNIT(s), "inotify event");
×
3675

3676
        if (path_spec_fd_event(p, events) < 0)
×
3677
                goto fail;
×
3678

3679
        if (service_retry_pid_file(s) == 0)
×
3680
                return 0;
3681

3682
        if (service_watch_pid_file(s) < 0)
×
3683
                goto fail;
×
3684

3685
        return 0;
3686

3687
fail:
×
3688
        service_unwatch_pid_file(s);
×
3689
        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
×
3690
        return 0;
×
3691
}
3692

3693
static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
16✔
3694
        Service *s = ASSERT_PTR(SERVICE(userdata));
16✔
3695

3696
        log_unit_debug(UNIT(s), "got exec-fd event");
16✔
3697

3698
        /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3699
         * successfully for it. We implement this through a pipe() towards the child, which the kernel
3700
         * automatically closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on
3701
         * the pipe in the parent. We need to be careful however, as there are other reasons that we might
3702
         * cause the child's side of the pipe to be closed (for example, a simple exit()). To deal with that
3703
         * we'll ignore EOFs on the pipe unless the child signalled us first that it is about to call the
3704
         * execve(). It does so by sending us a simple non-zero byte via the pipe. We also provide the child
3705
         * with a way to inform us in case execve() failed: if it sends a zero byte we'll ignore POLLHUP on
3706
         * the fd again. */
3707

3708
        for (;;) {
48✔
3709
                uint8_t x;
32✔
3710
                ssize_t n;
32✔
3711

3712
                n = read(fd, &x, sizeof(x));
32✔
3713
                if (n < 0) {
32✔
3714
                        if (errno == EAGAIN) /* O_NONBLOCK in effect → everything queued has now been processed. */
×
3715
                                return 0;
16✔
3716

3717
                        return log_unit_error_errno(UNIT(s), errno, "Failed to read from exec_fd: %m");
×
3718
                }
3719
                if (n == 0) { /* EOF → the event we are waiting for in case of Type=exec */
32✔
3720
                        s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
16✔
3721

3722
                        if (s->exec_fd_hot) { /* Did the child tell us to expect EOF now? */
16✔
3723
                                log_unit_debug(UNIT(s), "Got EOF on exec-fd");
16✔
3724

3725
                                s->exec_fd_hot = false;
16✔
3726

3727
                                /* Nice! This is what we have been waiting for. Transition to next state. */
3728
                                if (s->type == SERVICE_EXEC && s->state == SERVICE_START)
16✔
3729
                                        service_enter_start_post(s);
16✔
3730
                        } else
3731
                                log_unit_debug(UNIT(s), "Got EOF on exec-fd while it was disabled, ignoring.");
×
3732

3733
                        return 0;
16✔
3734
                }
3735

3736
                /* A byte was read → this turns on/off the exec fd logic */
3737
                assert(n == sizeof(x));
16✔
3738

3739
                s->exec_fd_hot = x;
16✔
3740
        }
3741
}
3742

3743
static void service_notify_cgroup_empty_event(Unit *u) {
887✔
3744
        Service *s = ASSERT_PTR(SERVICE(u));
887✔
3745

3746
        log_unit_debug(u, "Control group is empty.");
887✔
3747

3748
        switch (s->state) {
887✔
3749

3750
                /* Waiting for SIGCHLD is usually more interesting, because it includes return
3751
                 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3752
                 * don't know pid which to expect the SIGCHLD for. */
3753

3754
        case SERVICE_START:
90✔
3755
                if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
90✔
3756
                    main_pid_good(s) == 0 &&
×
3757
                    control_pid_good(s) == 0) {
×
3758
                        /* No chance of getting a ready notification anymore */
3759
                        service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
×
3760
                        break;
×
3761
                }
3762

3763
                if (s->exit_type == SERVICE_EXIT_CGROUP && main_pid_good(s) <= 0) {
90✔
3764
                        service_enter_stop_post(s, SERVICE_SUCCESS);
×
3765
                        break;
×
3766
                }
3767

3768
                _fallthrough_;
90✔
3769
        case SERVICE_START_POST:
3770
                if (s->pid_file_pathspec &&
90✔
3771
                    main_pid_good(s) == 0 &&
×
3772
                    control_pid_good(s) == 0) {
×
3773

3774
                        /* Give up hoping for the daemon to write its PID file */
3775
                        log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
×
3776

3777
                        service_unwatch_pid_file(s);
×
3778
                        if (s->state == SERVICE_START)
×
3779
                                service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
×
3780
                        else
3781
                                service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
×
3782
                }
3783
                break;
3784

3785
        case SERVICE_RUNNING:
56✔
3786
                /* service_enter_running() will figure out what to do */
3787
                service_enter_running(s, SERVICE_SUCCESS);
56✔
3788
                break;
56✔
3789

3790
        case SERVICE_STOP_WATCHDOG:
37✔
3791
        case SERVICE_STOP_SIGTERM:
3792
        case SERVICE_STOP_SIGKILL:
3793

3794
                if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
37✔
3795
                        service_enter_stop_post(s, SERVICE_SUCCESS);
×
3796

3797
                break;
3798

3799
        case SERVICE_STOP_POST:
29✔
3800
        case SERVICE_FINAL_WATCHDOG:
3801
        case SERVICE_FINAL_SIGTERM:
3802
        case SERVICE_FINAL_SIGKILL:
3803
                if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
29✔
3804
                        service_enter_dead(s, SERVICE_SUCCESS, true);
15✔
3805

3806
                break;
3807

3808
        /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3809
         * up the cgroup earlier and should do it now. */
3810
        case SERVICE_AUTO_RESTART:
5✔
3811
        case SERVICE_AUTO_RESTART_QUEUED:
3812
                unit_prune_cgroup(u);
5✔
3813
                break;
5✔
3814

3815
        default:
887✔
3816
                ;
887✔
3817
        }
3818
}
887✔
3819

3820
static void service_notify_cgroup_oom_event(Unit *u, bool managed_oom) {
1✔
3821
        Service *s = ASSERT_PTR(SERVICE(u));
1✔
3822

3823
        if (managed_oom)
1✔
3824
                log_unit_debug(u, "Process(es) of control group were killed by systemd-oomd.");
1✔
3825
        else
3826
                log_unit_debug(u, "Process of control group was killed by the OOM killer.");
×
3827

3828
        if (s->oom_policy == OOM_CONTINUE)
1✔
3829
                return;
3830

3831
        switch (s->state) {
1✔
3832

3833
        case SERVICE_CONDITION:
×
3834
        case SERVICE_START_PRE:
3835
        case SERVICE_START:
3836
        case SERVICE_START_POST:
3837
        case SERVICE_STOP:
3838
                if (s->oom_policy == OOM_STOP)
×
3839
                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_OOM_KILL);
×
3840
                else if (s->oom_policy == OOM_KILL)
×
3841
                        service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
×
3842

3843
                break;
3844

3845
        case SERVICE_EXITED:
1✔
3846
        case SERVICE_RUNNING:
3847
                if (s->oom_policy == OOM_STOP)
1✔
3848
                        service_enter_stop(s, SERVICE_FAILURE_OOM_KILL);
1✔
3849
                else if (s->oom_policy == OOM_KILL)
×
3850
                        service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
×
3851

3852
                break;
3853

3854
        case SERVICE_STOP_WATCHDOG:
×
3855
        case SERVICE_STOP_SIGTERM:
3856
                service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
×
3857
                break;
×
3858

3859
        case SERVICE_STOP_SIGKILL:
×
3860
        case SERVICE_FINAL_SIGKILL:
3861
                if (s->result == SERVICE_SUCCESS)
×
3862
                        s->result = SERVICE_FAILURE_OOM_KILL;
×
3863
                break;
3864

3865
        case SERVICE_STOP_POST:
×
3866
        case SERVICE_FINAL_SIGTERM:
3867
                service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_OOM_KILL);
×
3868
                break;
×
3869

3870
        default:
1✔
3871
                ;
1✔
3872
        }
3873
}
3874

3875
static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1,724✔
3876
        Service *s = ASSERT_PTR(SERVICE(u));
1,724✔
3877
        bool notify_dbus = true;
1,724✔
3878
        ServiceResult f;
1,724✔
3879
        ExitClean clean_mode;
1,724✔
3880
        int r;
1,724✔
3881

3882
        assert(pid >= 0);
1,724✔
3883

3884
        /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3885
         * considered daemons as they are typically not long running. */
3886
        if (s->type == SERVICE_ONESHOT || (s->control_pid.pid == pid && s->control_command_id != SERVICE_EXEC_START))
1,724✔
3887
                clean_mode = EXIT_CLEAN_COMMAND;
3888
        else
3889
                clean_mode = EXIT_CLEAN_DAEMON;
735✔
3890

3891
        if (is_clean_exit(code, status, clean_mode, &s->success_status))
1,724✔
3892
                f = SERVICE_SUCCESS;
3893
        else if (code == CLD_EXITED)
242✔
3894
                f = SERVICE_FAILURE_EXIT_CODE;
3895
        else if (code == CLD_KILLED)
3896
                f = SERVICE_FAILURE_SIGNAL;
3897
        else if (code == CLD_DUMPED)
3898
                f = SERVICE_FAILURE_CORE_DUMP;
3899
        else
3900
                assert_not_reached();
×
3901

3902
        if (s->main_pid.pid == pid) {
1,724✔
3903
                /* Clean up the exec_fd event source. We want to do this here, not later in
3904
                 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3905
                 * The source owns its end of the pipe, so this will close that too. */
3906
                s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
1,541✔
3907

3908
                /* Forking services may occasionally move to a new PID.
3909
                 * As long as they update the PID file before exiting the old
3910
                 * PID, they're fine. */
3911
                if (service_load_pid_file(s, false) > 0)
1,541✔
3912
                        return;
3913

3914
                pidref_done(&s->main_pid);
1,541✔
3915
                exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
1,541✔
3916

3917
                if (s->main_command) {
1,541✔
3918
                        /* If this is not a forking service than the
3919
                         * main process got started and hence we copy
3920
                         * the exit status so that it is recorded both
3921
                         * as main and as control process exit
3922
                         * status */
3923

3924
                        s->main_command->exec_status = s->main_exec_status;
1,539✔
3925

3926
                        if (s->main_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
1,539✔
3927
                                f = SERVICE_SUCCESS;
66✔
3928
                } else if (s->exec_command[SERVICE_EXEC_START]) {
2✔
3929

3930
                        /* If this is a forked process, then we should
3931
                         * ignore the return value if this was
3932
                         * configured for the starter process */
3933

3934
                        if (s->exec_command[SERVICE_EXEC_START]->flags & EXEC_COMMAND_IGNORE_FAILURE)
2✔
3935
                                f = SERVICE_SUCCESS;
×
3936
                }
3937

3938
                unit_log_process_exit(
1,541✔
3939
                                u,
3940
                                "Main process",
3941
                                service_exec_command_to_string(SERVICE_EXEC_START),
3942
                                f == SERVICE_SUCCESS,
3943
                                code, status);
3944

3945
                if (s->result == SERVICE_SUCCESS)
1,541✔
3946
                        s->result = f;
1,538✔
3947

3948
                if (s->main_command &&
1,541✔
3949
                    s->main_command->command_next &&
1,539✔
3950
                    s->type == SERVICE_ONESHOT &&
2✔
3951
                    f == SERVICE_SUCCESS) {
3952

3953
                        /* There is another command to execute, so let's do that. */
3954

3955
                        log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2✔
3956
                        service_run_next_main(s);
2✔
3957

3958
                } else {
3959
                        s->main_command = NULL;
1,539✔
3960

3961
                        /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3962
                         * already empty */
3963
                        if (s->exit_type == SERVICE_EXIT_MAIN || cgroup_good(s) <= 0) {
1,539✔
3964
                                /* The service exited, so the service is officially gone. */
3965
                                switch (s->state) {
1,539✔
3966

3967
                                case SERVICE_START_POST:
4✔
3968
                                case SERVICE_RELOAD:
3969
                                case SERVICE_RELOAD_SIGNAL:
3970
                                case SERVICE_RELOAD_NOTIFY:
3971
                                case SERVICE_MOUNTING:
3972
                                        /* If neither main nor control processes are running then the current
3973
                                         * state can never exit cleanly, hence immediately terminate the
3974
                                         * service. */
3975
                                        if (control_pid_good(s) <= 0)
4✔
3976
                                                service_enter_stop(s, f);
4✔
3977

3978
                                        /* Otherwise need to wait until the operation is done. */
3979
                                        break;
3980

3981
                                case SERVICE_STOP:
3982
                                        /* Need to wait until the operation is done. */
3983
                                        break;
3984

3985
                                case SERVICE_START:
828✔
3986
                                        if (s->type == SERVICE_ONESHOT) {
828✔
3987
                                                /* This was our main goal, so let's go on */
3988
                                                if (f == SERVICE_SUCCESS)
826✔
3989
                                                        service_enter_start_post(s);
825✔
3990
                                                else
3991
                                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
1✔
3992
                                                break;
3993
                                        } else if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD)) {
2✔
3994
                                                /* Only enter running through a notification, so that the
3995
                                                 * SERVICE_START state signifies that no ready notification
3996
                                                 * has been received */
3997
                                                if (f != SERVICE_SUCCESS)
1✔
3998
                                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
×
3999
                                                else if (!s->remain_after_exit || service_get_notify_access(s) == NOTIFY_MAIN)
1✔
4000
                                                        /* The service has never been and will never be active */
4001
                                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
1✔
4002
                                                break;
4003
                                        }
4004

4005
                                        _fallthrough_;
120✔
4006
                                case SERVICE_RUNNING:
4007
                                        service_enter_running(s, f);
120✔
4008
                                        break;
120✔
4009

4010
                                case SERVICE_STOP_WATCHDOG:
588✔
4011
                                case SERVICE_STOP_SIGTERM:
4012
                                case SERVICE_STOP_SIGKILL:
4013

4014
                                        if (control_pid_good(s) <= 0)
588✔
4015
                                                service_enter_stop_post(s, f);
588✔
4016

4017
                                        /* If there is still a control process, wait for that first */
4018
                                        break;
4019

4020
                                case SERVICE_STOP_POST:
×
4021

4022
                                        if (control_pid_good(s) <= 0)
×
4023
                                                service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
×
4024

4025
                                        break;
4026

4027
                                case SERVICE_FINAL_WATCHDOG:
×
4028
                                case SERVICE_FINAL_SIGTERM:
4029
                                case SERVICE_FINAL_SIGKILL:
4030

4031
                                        if (control_pid_good(s) <= 0)
×
4032
                                                service_enter_dead(s, f, true);
×
4033
                                        break;
4034

4035
                                default:
×
4036
                                        assert_not_reached();
×
4037
                                }
4038
                        } else if (s->exit_type == SERVICE_EXIT_CGROUP && s->state == SERVICE_START &&
×
4039
                                   !IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD, SERVICE_DBUS))
×
4040
                                /* If a main process exits very quickly, this function might be executed
4041
                                 * before service_dispatch_exec_io(). Since this function disabled IO events
4042
                                 * to monitor the main process above, we need to update the state here too.
4043
                                 * Let's consider the process is successfully launched and exited, but
4044
                                 * only when we're not expecting a readiness notification or dbus name. */
4045
                                service_enter_start_post(s);
×
4046
                }
4047

4048
        } else if (s->control_pid.pid == pid) {
183✔
4049
                const char *kind;
145✔
4050
                bool success;
145✔
4051

4052
                pidref_done(&s->control_pid);
145✔
4053

4054
                if (s->control_command) {
145✔
4055
                        exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
145✔
4056

4057
                        if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
145✔
4058
                                f = SERVICE_SUCCESS;
1✔
4059
                }
4060

4061
                /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
4062
                if (s->state == SERVICE_CONDITION) {
145✔
4063
                        if (f == SERVICE_FAILURE_EXIT_CODE && status < 255) {
×
4064
                                UNIT(s)->condition_result = false;
×
4065
                                f = SERVICE_SKIP_CONDITION;
×
4066
                                success = true;
×
4067
                        } else if (f == SERVICE_SUCCESS) {
×
4068
                                UNIT(s)->condition_result = true;
×
4069
                                success = true;
×
4070
                        } else
4071
                                success = false;
4072

4073
                        kind = "Condition check process";
4074
                } else {
4075
                        kind = "Control process";
145✔
4076
                        success = f == SERVICE_SUCCESS;
145✔
4077
                }
4078

4079
                unit_log_process_exit(
145✔
4080
                                u,
4081
                                kind,
4082
                                service_exec_command_to_string(s->control_command_id),
4083
                                success,
4084
                                code, status);
4085

4086
                if (!IN_SET(s->state, SERVICE_RELOAD, SERVICE_MOUNTING) && s->result == SERVICE_SUCCESS)
145✔
4087
                        s->result = f;
135✔
4088

4089
                if (s->control_command &&
145✔
4090
                    s->control_command->command_next &&
145✔
4091
                    f == SERVICE_SUCCESS) {
4092

4093
                        /* There is another command to execute, so let's do that. */
4094

4095
                        log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
1✔
4096
                        service_run_next_control(s);
1✔
4097

4098
                } else {
4099
                        /* No further commands for this step, so let's figure out what to do next */
4100

4101
                        s->control_command = NULL;
144✔
4102
                        s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
144✔
4103

4104
                        log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
144✔
4105

4106
                        switch (s->state) {
144✔
4107

4108
                        case SERVICE_CONDITION:
×
4109
                                if (f == SERVICE_SUCCESS)
×
4110
                                        service_enter_start_pre(s);
×
4111
                                else
4112
                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
×
4113
                                break;
4114

4115
                        case SERVICE_START_PRE:
25✔
4116
                                if (f == SERVICE_SUCCESS)
25✔
4117
                                        service_enter_start(s);
25✔
4118
                                else
4119
                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
×
4120
                                break;
4121

4122
                        case SERVICE_START:
2✔
4123
                                if (s->type != SERVICE_FORKING)
2✔
4124
                                        /* Maybe spurious event due to a reload that changed the type? */
4125
                                        break;
4126

4127
                                if (f != SERVICE_SUCCESS) {
2✔
4128
                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
×
4129
                                        break;
×
4130
                                }
4131

4132
                                if (s->pid_file) {
2✔
4133
                                        bool has_start_post;
×
4134

4135
                                        /* Let's try to load the pid file here if we can.
4136
                                         * The PID file might actually be created by a START_POST
4137
                                         * script. In that case don't worry if the loading fails. */
4138

4139
                                        has_start_post = s->exec_command[SERVICE_EXEC_START_POST];
×
4140
                                        r = service_load_pid_file(s, !has_start_post);
×
4141
                                        if (!has_start_post && r < 0) {
×
4142
                                                r = service_demand_pid_file(s);
×
4143
                                                if (r < 0 || cgroup_good(s) == 0)
×
4144
                                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
×
4145
                                                break;
4146
                                        }
4147
                                } else
4148
                                        service_search_main_pid(s);
2✔
4149

4150
                                service_enter_start_post(s);
2✔
4151
                                break;
2✔
4152

4153
                        case SERVICE_START_POST:
×
4154
                                if (f != SERVICE_SUCCESS) {
×
4155
                                        service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
×
4156
                                        break;
×
4157
                                }
4158

4159
                                if (s->pid_file) {
×
4160
                                        r = service_load_pid_file(s, true);
×
4161
                                        if (r < 0) {
×
4162
                                                r = service_demand_pid_file(s);
×
4163
                                                if (r < 0 || cgroup_good(s) == 0)
×
4164
                                                        service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
×
4165
                                                break;
4166
                                        }
4167
                                } else
4168
                                        service_search_main_pid(s);
×
4169

4170
                                service_enter_running(s, SERVICE_SUCCESS);
×
4171
                                break;
×
4172

4173
                        case SERVICE_RELOAD:
3✔
4174
                        case SERVICE_RELOAD_SIGNAL:
4175
                        case SERVICE_RELOAD_NOTIFY:
4176
                                if (f == SERVICE_SUCCESS)
3✔
4177
                                        if (service_load_pid_file(s, true) < 0)
1✔
4178
                                                service_search_main_pid(s);
1✔
4179

4180
                                s->reload_result = f;
3✔
4181

4182
                                /* If the last notification we received from the service process indicates
4183
                                 * we are still reloading, then don't leave reloading state just yet, just
4184
                                 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4185
                                 * too. */
4186
                                if (s->notify_state == NOTIFY_RELOADING)
3✔
4187
                                        service_set_state(s, SERVICE_RELOAD_NOTIFY);
×
4188
                                else
4189
                                        service_enter_running(s, SERVICE_SUCCESS);
3✔
4190
                                break;
4191

4192
                        case SERVICE_MOUNTING:
×
4193
                                service_live_mount_finish(s, f, SD_BUS_ERROR_FAILED);
×
4194

4195
                                service_enter_running(s, SERVICE_SUCCESS);
×
4196
                                break;
×
4197

4198
                        case SERVICE_STOP:
100✔
4199
                                service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
100✔
4200
                                break;
100✔
4201

4202
                        case SERVICE_STOP_WATCHDOG:
×
4203
                        case SERVICE_STOP_SIGTERM:
4204
                        case SERVICE_STOP_SIGKILL:
4205
                                if (main_pid_good(s) <= 0)
×
4206
                                        service_enter_stop_post(s, f);
×
4207

4208
                                /* If there is still a service process around, wait until
4209
                                 * that one quit, too */
4210
                                break;
4211

4212
                        case SERVICE_STOP_POST:
14✔
4213
                                if (main_pid_good(s) <= 0)
14✔
4214
                                        service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
14✔
4215
                                break;
4216

4217
                        case SERVICE_FINAL_WATCHDOG:
×
4218
                        case SERVICE_FINAL_SIGTERM:
4219
                        case SERVICE_FINAL_SIGKILL:
4220
                                if (main_pid_good(s) <= 0)
×
4221
                                        service_enter_dead(s, f, true);
×
4222
                                break;
4223

4224
                        case SERVICE_CLEANING:
×
4225

4226
                                if (s->clean_result == SERVICE_SUCCESS)
×
4227
                                        s->clean_result = f;
×
4228

4229
                                service_enter_dead(s, SERVICE_SUCCESS, false);
×
4230
                                break;
×
4231

4232
                        default:
×
4233
                                assert_not_reached();
×
4234
                        }
4235
                }
4236
        } else /* Neither control nor main PID? If so, don't notify about anything */
4237
                notify_dbus = false;
4238

4239
        /* Notify clients about changed exit status */
4240
        if (notify_dbus)
1,686✔
4241
                unit_add_to_dbus_queue(u);
1,686✔
4242
}
4243

4244
static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
10✔
4245
        Service *s = ASSERT_PTR(SERVICE(userdata));
10✔
4246

4247
        assert(source == s->timer_event_source);
10✔
4248

4249
        switch (s->state) {
10✔
4250

4251
        case SERVICE_CONDITION:
×
4252
        case SERVICE_START_PRE:
4253
        case SERVICE_START:
4254
        case SERVICE_START_POST:
4255
                switch (s->timeout_start_failure_mode) {
×
4256

4257
                case SERVICE_TIMEOUT_TERMINATE:
4258
                        log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", service_state_to_string(s->state));
×
4259
                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
×
4260
                        break;
×
4261

4262
                case SERVICE_TIMEOUT_ABORT:
4263
                        log_unit_warning(UNIT(s), "%s operation timed out. Aborting.", service_state_to_string(s->state));
×
4264
                        service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
×
4265
                        break;
×
4266

4267
                case SERVICE_TIMEOUT_KILL:
×
4268
                        if (s->kill_context.send_sigkill) {
×
4269
                                log_unit_warning(UNIT(s), "%s operation timed out. Killing.", service_state_to_string(s->state));
×
4270
                                service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4271
                        } else {
4272
                                log_unit_warning(UNIT(s), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s->state));
×
4273
                                service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
×
4274
                        }
4275
                        break;
4276

4277
                default:
×
4278
                        assert_not_reached();
×
4279
                }
4280
                break;
4281

4282
        case SERVICE_RUNNING:
4283
                log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2✔
4284
                service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2✔
4285
                break;
2✔
4286

4287
        case SERVICE_RELOAD:
4288
        case SERVICE_RELOAD_SIGNAL:
4289
        case SERVICE_RELOAD_NOTIFY:
4290
                log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
3✔
4291
                service_kill_control_process(s);
3✔
4292
                s->reload_result = SERVICE_FAILURE_TIMEOUT;
3✔
4293
                service_enter_running(s, SERVICE_SUCCESS);
3✔
4294
                break;
3✔
4295

4296
        case SERVICE_MOUNTING:
4297
                log_unit_warning(UNIT(s), "Mount operation timed out. Killing mount process.");
×
4298
                service_kill_control_process(s);
×
4299
                service_live_mount_finish(s, SERVICE_FAILURE_TIMEOUT, SD_BUS_ERROR_TIMEOUT);
×
4300
                service_enter_running(s, SERVICE_SUCCESS);
×
4301
                break;
×
4302

4303
        case SERVICE_STOP:
×
4304
                switch (s->timeout_stop_failure_mode) {
×
4305

4306
                case SERVICE_TIMEOUT_TERMINATE:
4307
                        log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
×
4308
                        service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
×
4309
                        break;
×
4310

4311
                case SERVICE_TIMEOUT_ABORT:
4312
                        log_unit_warning(UNIT(s), "Stopping timed out. Aborting.");
×
4313
                        service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
×
4314
                        break;
×
4315

4316
                case SERVICE_TIMEOUT_KILL:
×
4317
                        if (s->kill_context.send_sigkill) {
×
4318
                                log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
×
4319
                                service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4320
                        } else {
4321
                                log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
×
4322
                                service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
×
4323
                        }
4324
                        break;
4325

4326
                default:
×
4327
                        assert_not_reached();
×
4328
                }
4329
                break;
4330

4331
        case SERVICE_STOP_WATCHDOG:
×
4332
                if (s->kill_context.send_sigkill) {
×
4333
                        log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Killing.");
×
4334
                        service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4335
                } else {
4336
                        log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
×
4337
                        service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
×
4338
                }
4339
                break;
4340

4341
        case SERVICE_STOP_SIGTERM:
×
4342
                if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
×
4343
                        log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Aborting.");
×
4344
                        service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
×
4345
                } else if (s->kill_context.send_sigkill) {
×
4346
                        log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
×
4347
                        service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4348
                } else {
4349
                        log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
×
4350
                        service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
×
4351
                }
4352

4353
                break;
4354

4355
        case SERVICE_STOP_SIGKILL:
4356
                /* Uh, we sent a SIGKILL and it is still not gone?
4357
                 * Must be something we cannot kill, so let's just be
4358
                 * weirded out and continue */
4359

4360
                log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
×
4361
                service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
×
4362
                break;
×
4363

4364
        case SERVICE_STOP_POST:
×
4365
                switch (s->timeout_stop_failure_mode) {
×
4366

4367
                case SERVICE_TIMEOUT_TERMINATE:
4368
                        log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
×
4369
                        service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
×
4370
                        break;
×
4371

4372
                case SERVICE_TIMEOUT_ABORT:
4373
                        log_unit_warning(UNIT(s), "State 'stop-post' timed out. Aborting.");
×
4374
                        service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
×
4375
                        break;
×
4376

4377
                case SERVICE_TIMEOUT_KILL:
×
4378
                        if (s->kill_context.send_sigkill) {
×
4379
                                log_unit_warning(UNIT(s), "State 'stop-post' timed out. Killing.");
×
4380
                                service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4381
                        } else {
4382
                                log_unit_warning(UNIT(s), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
×
4383
                                service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
×
4384
                        }
4385
                        break;
4386

4387
                default:
×
4388
                        assert_not_reached();
×
4389
                }
4390
                break;
4391

4392
        case SERVICE_FINAL_WATCHDOG:
×
4393
                if (s->kill_context.send_sigkill) {
×
4394
                        log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Killing.");
×
4395
                        service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4396
                } else {
4397
                        log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
×
4398
                        service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
×
4399
                }
4400
                break;
4401

4402
        case SERVICE_FINAL_SIGTERM:
×
4403
                if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
×
4404
                        log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Aborting.");
×
4405
                        service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
×
4406
                } else if (s->kill_context.send_sigkill) {
×
4407
                        log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Killing.");
×
4408
                        service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
×
4409
                } else {
4410
                        log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
×
4411
                        service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
×
4412
                }
4413

4414
                break;
4415

4416
        case SERVICE_FINAL_SIGKILL:
4417
                log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
×
4418
                service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
×
4419
                break;
×
4420

4421
        case SERVICE_AUTO_RESTART:
5✔
4422
                if (s->restart_usec > 0)
5✔
4423
                        log_unit_debug(UNIT(s),
2✔
4424
                                       "Service restart interval %s expired, scheduling restart.",
4425
                                       FORMAT_TIMESPAN(service_restart_usec_next(s), USEC_PER_SEC));
4426
                else
4427
                        log_unit_debug(UNIT(s),
3✔
4428
                                       "Service has no hold-off time (RestartSec=0), scheduling restart.");
4429

4430
                service_enter_restart(s, /* shortcut = */ false);
5✔
4431
                break;
5✔
4432

4433
        case SERVICE_CLEANING:
4434
                log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
×
4435

4436
                if (s->clean_result == SERVICE_SUCCESS)
×
4437
                        s->clean_result = SERVICE_FAILURE_TIMEOUT;
×
4438

4439
                service_enter_signal(s, SERVICE_FINAL_SIGKILL, 0);
×
4440
                break;
×
4441

4442
        default:
×
4443
                assert_not_reached();
×
4444
        }
4445

4446
        return 0;
10✔
4447
}
4448

4449
static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
×
4450
        Service *s = ASSERT_PTR(SERVICE(userdata));
×
4451
        usec_t watchdog_usec;
×
4452

4453
        assert(source == s->watchdog_event_source);
×
4454

4455
        watchdog_usec = service_get_watchdog_usec(s);
×
4456

4457
        if (UNIT(s)->manager->service_watchdogs) {
×
4458
                log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
×
4459
                               FORMAT_TIMESPAN(watchdog_usec, 1));
4460

4461
                service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
×
4462
        } else
4463
                log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
×
4464
                                 FORMAT_TIMESPAN(watchdog_usec, 1));
4465

4466
        return 0;
×
4467
}
4468

4469
static void service_force_watchdog(Service *s) {
×
4470
        assert(s);
×
4471

4472
        if (!UNIT(s)->manager->service_watchdogs)
×
4473
                return;
4474

4475
        log_unit_error(UNIT(s), "Watchdog request (last status: %s)!",
×
4476
                       s->status_text ?: "<unset>");
4477

4478
        service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
×
4479
}
4480

4481
static bool service_notify_message_authorized(Service *s, PidRef *pid) {
3,463✔
4482
        assert(s);
3,463✔
4483
        assert(pidref_is_set(pid));
3,463✔
4484

4485
        switch (service_get_notify_access(s)) {
3,463✔
4486

4487
        case NOTIFY_NONE:
4488
                /* Warn level only if no notifications are expected */
4489
                log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception is disabled", pid->pid);
×
4490
                return false;
×
4491

4492
        case NOTIFY_ALL:
4493
                return true;
4494

4495
        case NOTIFY_MAIN:
3,214✔
4496
                if (pidref_equal(pid, &s->main_pid))
3,214✔
4497
                        return true;
4498

4499
                if (pidref_is_set(&s->main_pid))
×
4500
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid->pid, s->main_pid.pid);
×
4501
                else
4502
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid->pid);
×
4503

4504
                return false;
4505

4506
        case NOTIFY_EXEC:
2✔
4507
                if (pidref_equal(pid, &s->main_pid) || pidref_equal(pid, &s->control_pid))
2✔
4508
                        return true;
2✔
4509

4510
                if (pidref_is_set(&s->main_pid) && pidref_is_set(&s->control_pid))
×
4511
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT" and control PID "PID_FMT,
×
4512
                                       pid->pid, s->main_pid.pid, s->control_pid.pid);
4513
                else if (pidref_is_set(&s->main_pid))
4514
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid->pid, s->main_pid.pid);
×
4515
                else if (pidref_is_set(&s->control_pid))
×
4516
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for control PID "PID_FMT, pid->pid, s->control_pid.pid);
×
4517
                else
4518
                        log_unit_debug(UNIT(s), "Got notification message from PID "PID_FMT", but reception only permitted for main PID and control PID which are currently not known", pid->pid);
×
4519

4520
                return false;
4521

4522
        default:
×
4523
                assert_not_reached();
×
4524
        }
4525
}
4526

4527
static int service_notify_message_parse_new_pid(
3,463✔
4528
                Unit *u,
4529
                char * const *tags,
4530
                FDSet *fds,
4531
                PidRef *ret) {
4532

4533
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3,463✔
4534
        const char *e;
3,463✔
4535
        int r;
3,463✔
4536

4537
        assert(u);
3,463✔
4538
        assert(ret);
3,463✔
4539

4540
        /* MAINPIDFD=1 always takes precedence */
4541
        if (strv_contains(tags, "MAINPIDFD=1")) {
3,463✔
4542
                unsigned n_fds = fdset_size(fds);
×
4543
                if (n_fds != 1)
×
4544
                        return log_unit_warning_errno(u, SYNTHETIC_ERRNO(EINVAL),
×
4545
                                                      "Got MAINPIDFD=1 with %s fd, ignoring.", n_fds == 0 ? "no" : "more than one");
4546

4547
                r = pidref_set_pidfd_consume(&pidref, ASSERT_FD(fdset_steal_first(fds)));
×
4548
                if (r < 0)
×
4549
                        return log_unit_warning_errno(u, r, "Failed to create reference to received new main pidfd: %m");
×
4550

4551
                goto finish;
×
4552
        }
4553

4554
        e = strv_find_startswith(tags, "MAINPID=");
3,463✔
4555
        if (!e) {
3,463✔
4556
                *ret = PIDREF_NULL;
3,461✔
4557
                return 0;
3,461✔
4558
        }
4559

4560
        r = pidref_set_pidstr(&pidref, e);
2✔
4561
        if (r < 0)
2✔
4562
                return log_unit_warning_errno(u, r, "Failed to parse MAINPID=%s field in notification message, ignoring: %m", e);
×
4563

4564
        e = strv_find_startswith(tags, "MAINPIDFDID=");
2✔
4565
        if (!e)
2✔
4566
                goto finish;
2✔
4567

4568
        uint64_t pidfd_id;
×
4569

4570
        r = safe_atou64(e, &pidfd_id);
×
4571
        if (r < 0)
×
4572
                return log_unit_warning_errno(u, r, "Failed to parse MAINPIDFDID= in notification message, refusing: %s", e);
×
4573

4574
        r = pidref_acquire_pidfd_id(&pidref);
×
4575
        if (r < 0) {
×
4576
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
×
4577
                        log_unit_warning_errno(u, r,
×
4578
                                               "Failed to acquire pidfd id of process " PID_FMT ", not validating MAINPIDFDID=%" PRIu64 ": %m",
4579
                                               pidref.pid, pidfd_id);
4580
                goto finish;
×
4581
        }
4582

4583
        if (pidref.fd_id != pidfd_id)
×
4584
                return log_unit_warning_errno(u, SYNTHETIC_ERRNO(ESRCH),
×
4585
                                              "PIDFD ID of process " PID_FMT " (%" PRIu64 ") mismatches with received MAINPIDFDID=%" PRIu64 ", not changing main PID.",
4586
                                              pidref.pid, pidref.fd_id, pidfd_id);
4587

4588
finish:
×
4589
        *ret = TAKE_PIDREF(pidref);
2✔
4590
        return 1;
2✔
4591
}
4592

4593
static void service_notify_message(
3,463✔
4594
                Unit *u,
4595
                PidRef *pidref,
4596
                const struct ucred *ucred,
4597
                char * const *tags,
4598
                FDSet *fds) {
4599

4600
        Service *s = ASSERT_PTR(SERVICE(u));
3,463✔
4601
        int r;
3,463✔
4602

4603
        assert(pidref_is_set(pidref));
3,463✔
4604
        assert(ucred);
3,463✔
4605

4606
        if (!service_notify_message_authorized(s, pidref))
3,463✔
4607
                return;
×
4608

4609
        if (DEBUG_LOGGING) {
3,463✔
4610
                _cleanup_free_ char *cc = strv_join(tags, ", ");
6,922✔
4611
                log_unit_debug(u, "Got notification message from PID "PID_FMT": %s", pidref->pid, empty_to_na(cc));
6,922✔
4612
        }
4613

4614
        usec_t monotonic_usec = USEC_INFINITY;
3,463✔
4615
        bool notify_dbus = false;
3,463✔
4616
        const char *e;
3,463✔
4617

4618
        /* Interpret MAINPID= (+ MAINPIDFDID=) / MAINPIDFD=1 */
4619
        _cleanup_(pidref_done) PidRef new_main_pid = PIDREF_NULL;
3,463✔
4620

4621
        r = service_notify_message_parse_new_pid(u, tags, fds, &new_main_pid);
3,463✔
4622
        if (r > 0 &&
3,463✔
4623
            IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING,
2✔
4624
                             SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
4625
                             SERVICE_STOP, SERVICE_STOP_SIGTERM) &&
2✔
4626
            (!s->main_pid_known || !pidref_equal(&new_main_pid, &s->main_pid))) {
2✔
4627

4628
                r = service_is_suitable_main_pid(s, &new_main_pid, LOG_WARNING);
2✔
4629
                if (r == 0) {
2✔
4630
                        /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
4631

4632
                        if (ucred->uid == 0) {
×
4633
                                log_unit_debug(u, "New main PID "PID_FMT" does not belong to service, but we'll accept it as the request to change it came from a privileged process.", new_main_pid.pid);
×
4634
                                r = 1;
×
4635
                        } else
4636
                                log_unit_warning(u, "New main PID "PID_FMT" does not belong to service, refusing.", new_main_pid.pid);
×
4637
                }
4638
                if (r > 0) {
2✔
4639
                        (void) service_set_main_pidref(s, TAKE_PIDREF(new_main_pid), /* start_timestamp = */ NULL);
2✔
4640

4641
                        r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
2✔
4642
                        if (r < 0)
2✔
4643
                                log_unit_warning_errno(UNIT(s), r, "Failed to watch new main PID "PID_FMT" for service: %m", s->main_pid.pid);
×
4644

4645
                        notify_dbus = true;
4646
                }
4647
        }
4648

4649
        /* Parse MONOTONIC_USEC= */
4650
        e = strv_find_startswith(tags, "MONOTONIC_USEC=");
3,463✔
4651
        if (e) {
3,463✔
4652
                r = safe_atou64(e, &monotonic_usec);
18✔
4653
                if (r < 0)
18✔
4654
                        log_unit_warning_errno(u, r, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e);
×
4655
        }
4656

4657
        /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4658
        if (strv_contains(tags, "STOPPING=1")) {
3,463✔
4659
                s->notify_state = NOTIFY_STOPPING;
127✔
4660

4661
                if (IN_SET(s->state, SERVICE_RUNNING, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY))
127✔
4662
                        service_enter_stop_by_notify(s);
×
4663

4664
                notify_dbus = true;
4665

4666
        } else if (strv_contains(tags, "READY=1")) {
3,336✔
4667

4668
                s->notify_state = NOTIFY_READY;
413✔
4669

4670
                /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4671
                 * immediately finished reloading. */
4672
                if (strv_contains(tags, "RELOADING=1")) {
413✔
4673
                        if (s->state == SERVICE_RELOAD_SIGNAL &&
×
4674
                            monotonic_usec != USEC_INFINITY &&
×
4675
                            monotonic_usec >= s->reload_begin_usec)
×
4676
                                /* Valid Type=notify-reload protocol? Then we're all good. */
4677
                                service_enter_running(s, SERVICE_SUCCESS);
×
4678

4679
                        else if (s->state == SERVICE_RUNNING) {
×
4680
                                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
4681

4682
                                /* Propagate a reload explicitly for plain RELOADING=1 (semantically equivalent to
4683
                                 * service_enter_reload_by_notify() call in below) */
4684
                                r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
×
4685
                                if (r < 0)
×
4686
                                        log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s",
×
4687
                                                         bus_error_message(&error, r));
4688
                        }
4689
                }
4690

4691
                /* Type=notify(-reload) services inform us about completed initialization with READY=1 */
4692
                if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
413✔
4693
                    s->state == SERVICE_START)
351✔
4694
                        service_enter_start_post(s);
301✔
4695

4696
                /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4697
                if (s->state == SERVICE_RELOAD_NOTIFY)
413✔
4698
                        service_enter_running(s, SERVICE_SUCCESS);
18✔
4699

4700
                notify_dbus = true;
4701

4702
        } else if (strv_contains(tags, "RELOADING=1")) {
2,923✔
4703

4704
                s->notify_state = NOTIFY_RELOADING;
22✔
4705

4706
                /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4707
                 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4708
                 * reload is done. Note that we insist on a timestamp being sent along here, so that
4709
                 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4710
                if (s->state == SERVICE_RELOAD_SIGNAL &&
22✔
4711
                    monotonic_usec != USEC_INFINITY &&
×
4712
                    monotonic_usec >= s->reload_begin_usec)
×
4713
                        /* Note, we don't call service_enter_reload_by_notify() here, because we
4714
                         * don't need reload propagation nor do we want to restart the timeout. */
4715
                        service_set_state(s, SERVICE_RELOAD_NOTIFY);
×
4716

4717
                if (s->state == SERVICE_RUNNING)
22✔
4718
                        service_enter_reload_by_notify(s);
22✔
4719

4720
                notify_dbus = true;
4721
        }
4722

4723
        /* Interpret STATUS= */
4724
        e = strv_find_startswith(tags, "STATUS=");
3,463✔
4725
        if (e) {
3,463✔
4726
                _cleanup_free_ char *t = NULL;
912✔
4727

4728
                if (!isempty(e)) {
912✔
4729
                        /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4730
                         * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4731
                        if (strlen(e) > STATUS_TEXT_MAX)
912✔
4732
                                log_unit_warning(u, "Status message overly long (%zu > %u), ignoring.", strlen(e), STATUS_TEXT_MAX);
×
4733
                        else if (!utf8_is_valid(e))
912✔
4734
                                log_unit_warning(u, "Status message in notification message is not UTF-8 clean, ignoring.");
×
4735
                        else {
4736
                                t = strdup(e);
912✔
4737
                                if (!t)
912✔
4738
                                        log_oom_warning();
×
4739
                        }
4740
                }
4741

4742
                if (!streq_ptr(s->status_text, t)) {
912✔
4743
                        free_and_replace(s->status_text, t);
495✔
4744
                        notify_dbus = true;
495✔
4745
                }
4746
        }
4747

4748
        /* Interpret NOTIFYACCESS= */
4749
        e = strv_find_startswith(tags, "NOTIFYACCESS=");
3,463✔
4750
        if (e) {
3,463✔
4751
                NotifyAccess notify_access;
×
4752

4753
                notify_access = notify_access_from_string(e);
×
4754
                if (notify_access < 0)
×
4755
                        log_unit_warning_errno(u, notify_access,
×
4756
                                               "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e);
4757

4758
                /* We don't need to check whether the new access mode is more strict than what is
4759
                 * already in use, since only the privileged process is allowed to change it
4760
                 * in the first place. */
4761
                if (service_get_notify_access(s) != notify_access) {
×
4762
                        service_override_notify_access(s, notify_access);
×
4763
                        notify_dbus = true;
4764
                }
4765
        }
4766

4767
        /* Interpret ERRNO= */
4768
        e = strv_find_startswith(tags, "ERRNO=");
3,463✔
4769
        if (e) {
3,463✔
4770
                int status_errno;
2✔
4771

4772
                status_errno = parse_errno(e);
2✔
4773
                if (status_errno < 0)
2✔
4774
                        log_unit_warning_errno(u, status_errno,
×
4775
                                               "Failed to parse ERRNO= field value '%s' in notification message: %m", e);
4776
                else if (s->status_errno != status_errno) {
2✔
4777
                        s->status_errno = status_errno;
1✔
4778
                        notify_dbus = true;
1✔
4779
                }
4780
        }
4781

4782
        static const struct {
4783
                const char *tag;
4784
                size_t status_offset;
4785
        } status_errors[] = {
4786
                { "BUSERROR=",     offsetof(Service, status_bus_error)     },
4787
                { "VARLINKERROR=", offsetof(Service, status_varlink_error) },
4788
        };
4789

4790
        FOREACH_ELEMENT(i, status_errors) {
10,389✔
4791
                e = strv_find_startswith(tags, i->tag);
6,926✔
4792
                if (!e)
6,926✔
4793
                        continue;
6,926✔
4794

4795
                char **status_error = (char**) ((uint8_t*) s + i->status_offset);
×
4796

4797
                e = empty_to_null(e);
×
4798

4799
                if (e && !string_is_safe_ascii(e)) {
×
4800
                        _cleanup_free_ char *escaped = cescape(e);
×
4801
                        log_unit_warning(u, "Got invalid %s string, ignoring: %s", i->tag, strna(escaped));
×
4802
                } else if (free_and_strdup_warn(status_error, e) > 0)
×
4803
                        notify_dbus = true;
×
4804
        }
4805

4806
        /* Interpret EXTEND_TIMEOUT= */
4807
        e = strv_find_startswith(tags, "EXTEND_TIMEOUT_USEC=");
3,463✔
4808
        if (e) {
3,463✔
4809
                usec_t extend_timeout_usec;
×
4810

4811
                if (safe_atou64(e, &extend_timeout_usec) < 0)
×
4812
                        log_unit_warning(u, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e);
×
4813
                else
4814
                        service_extend_timeout(s, extend_timeout_usec);
×
4815
        }
4816

4817
        /* Interpret WATCHDOG= */
4818
        e = strv_find_startswith(tags, "WATCHDOG=");
3,463✔
4819
        if (e) {
3,463✔
4820
                if (streq(e, "1"))
256✔
4821
                        service_reset_watchdog(s);
256✔
4822
                else if (streq(e, "trigger"))
×
4823
                        service_force_watchdog(s);
×
4824
                else
4825
                        log_unit_warning(u, "Passed WATCHDOG= field is invalid, ignoring.");
×
4826
        }
4827

4828
        e = strv_find_startswith(tags, "WATCHDOG_USEC=");
3,463✔
4829
        if (e) {
3,463✔
4830
                usec_t watchdog_override_usec;
×
4831
                if (safe_atou64(e, &watchdog_override_usec) < 0)
×
4832
                        log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
×
4833
                else
4834
                        service_override_watchdog_timeout(s, watchdog_override_usec);
×
4835
        }
4836

4837
        /* Interpret RESTART_RESET=1 */
4838
        if (strv_contains(tags, "RESTART_RESET=1") && IN_SET(s->state, SERVICE_RUNNING, SERVICE_STOP)) {
3,463✔
4839
                log_unit_struct(u, LOG_NOTICE,
×
4840
                                LOG_UNIT_MESSAGE(u, "Got RESTART_RESET=1, resetting restart counter from %u.", s->n_restarts),
4841
                                LOG_ITEM("N_RESTARTS=0"),
4842
                                LOG_UNIT_INVOCATION_ID(u));
4843

4844
                s->n_restarts = 0;
×
4845
                notify_dbus = true;
×
4846
        }
4847

4848
        /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4849
         * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4850
         * fds, but optional when pushing in new fds, for compatibility reasons. */
4851
        if (strv_contains(tags, "FDSTOREREMOVE=1")) {
3,463✔
4852
                const char *name;
145✔
4853

4854
                name = strv_find_startswith(tags, "FDNAME=");
145✔
4855
                if (!name || !fdname_is_valid(name))
145✔
4856
                        log_unit_warning(u, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
×
4857
                else
4858
                        service_remove_fd_store(s, name);
145✔
4859

4860
        } else if (strv_contains(tags, "FDSTORE=1")) {
3,318✔
4861
                const char *name;
1,484✔
4862

4863
                name = strv_find_startswith(tags, "FDNAME=");
1,484✔
4864
                if (name && !fdname_is_valid(name)) {
1,484✔
4865
                        log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
×
4866
                        name = NULL;
×
4867
                }
4868

4869
                (void) service_add_fd_store_set(s, fds, name, !strv_contains(tags, "FDPOLL=0"));
1,484✔
4870
        }
4871

4872
        /* Notify clients about changed status or main pid */
4873
        if (notify_dbus)
3,463✔
4874
                unit_add_to_dbus_queue(u);
606✔
4875
}
4876

4877
static void service_handoff_timestamp(
3,667✔
4878
                Unit *u,
4879
                const struct ucred *ucred,
4880
                const dual_timestamp *ts) {
4881

4882
        Service *s = ASSERT_PTR(SERVICE(u));
3,667✔
4883

4884
        assert(ucred);
3,667✔
4885
        assert(ts);
3,667✔
4886

4887
        if (s->main_pid.pid == ucred->pid) {
3,667✔
4888
                if (s->main_command)
3,377✔
4889
                        exec_status_handoff(&s->main_command->exec_status, ucred, ts);
3,377✔
4890

4891
                exec_status_handoff(&s->main_exec_status, ucred, ts);
3,377✔
4892
        } else if (s->control_pid.pid == ucred->pid && s->control_command)
290✔
4893
                exec_status_handoff(&s->control_command->exec_status, ucred, ts);
290✔
4894
        else
4895
                return;
4896

4897
        unit_add_to_dbus_queue(u);
3,667✔
4898
}
4899

4900
static void service_notify_pidref(Unit *u, PidRef *parent_pidref, PidRef *child_pidref) {
3✔
4901
        Service *s = ASSERT_PTR(SERVICE(u));
3✔
4902
        int r;
3✔
4903

4904
        assert(pidref_is_set(parent_pidref));
3✔
4905
        assert(pidref_is_set(child_pidref));
3✔
4906

4907
        if (pidref_equal(&s->main_pid, parent_pidref)) {
3✔
4908
                r = service_set_main_pidref(s, TAKE_PIDREF(*child_pidref), /* start_timestamp = */ NULL);
3✔
4909
                if (r < 0)
3✔
4910
                        return (void) log_unit_warning_errno(u, r, "Failed to set new main pid: %m");
×
4911

4912
                /* Since the child process is PID 1 in a new PID namespace, it must be exclusive to this unit. */
4913
                r = unit_watch_pidref(u, &s->main_pid, /* exclusive= */ true);
3✔
4914
                if (r < 0)
3✔
4915
                        log_unit_warning_errno(u, r, "Failed to watch new main PID " PID_FMT ": %m", s->main_pid.pid);
×
4916
        } else if (pidref_equal(&s->control_pid, parent_pidref)) {
×
4917
                service_unwatch_control_pid(s);
×
4918
                s->control_pid = TAKE_PIDREF(*child_pidref);
×
4919

4920
                r = unit_watch_pidref(u, &s->control_pid, /* exclusive= */ true);
×
4921
                if (r < 0)
×
4922
                        log_unit_warning_errno(u, r, "Failed to watch new control PID " PID_FMT ": %m", s->control_pid.pid);
×
4923
        } else
4924
                return (void) log_unit_debug(u, "Parent process " PID_FMT " does not match main or control processes, ignoring.", parent_pidref->pid);
×
4925

4926
        unit_add_to_dbus_queue(u);
3✔
4927
}
4928

4929
static int service_get_timeout(Unit *u, usec_t *timeout) {
403✔
4930
        Service *s = ASSERT_PTR(SERVICE(u));
403✔
4931
        uint64_t t;
403✔
4932
        int r;
403✔
4933

4934
        assert(timeout);
403✔
4935

4936
        if (!s->timer_event_source)
403✔
4937
                return 0;
403✔
4938

4939
        r = sd_event_source_get_time(s->timer_event_source, &t);
×
4940
        if (r < 0)
×
4941
                return r;
4942
        if (t == USEC_INFINITY)
×
4943
                return 0;
4944

4945
        *timeout = t;
×
4946
        return 1;
×
4947
}
4948

4949
static usec_t service_get_timeout_start_usec(Unit *u) {
752✔
4950
        Service *s = ASSERT_PTR(SERVICE(u));
752✔
4951
        return s->timeout_start_usec;
752✔
4952
}
4953

4954
static bool pick_up_pid_from_bus_name(Service *s) {
261✔
4955
        assert(s);
261✔
4956

4957
        /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4958

4959
        return !pidref_is_set(&s->main_pid) &&
261✔
4960
                IN_SET(s->state,
×
4961
                       SERVICE_START,
4962
                       SERVICE_START_POST,
4963
                       SERVICE_RUNNING,
4964
                       SERVICE_RELOAD,
4965
                       SERVICE_RELOAD_SIGNAL,
4966
                       SERVICE_RELOAD_NOTIFY,
4967
                       SERVICE_MOUNTING);
4968
}
4969

4970
static int bus_name_pid_lookup_callback(sd_bus_message *reply, void *userdata, sd_bus_error *ret_error) {
×
4971
        Service *s = ASSERT_PTR(SERVICE(userdata));
×
4972
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
4973
        const sd_bus_error *e;
×
4974
        uint32_t pid;
×
4975
        int r;
×
4976

4977
        assert(reply);
×
4978

4979
        s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
×
4980

4981
        if (!s->bus_name || !pick_up_pid_from_bus_name(s))
×
4982
                return 1;
4983

4984
        e = sd_bus_message_get_error(reply);
×
4985
        if (e) {
×
4986
                r = sd_bus_error_get_errno(e);
×
4987
                log_unit_warning_errno(UNIT(s), r, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e, r));
×
4988
                return 1;
×
4989
        }
4990

4991
        r = sd_bus_message_read(reply, "u", &pid);
×
4992
        if (r < 0) {
×
4993
                bus_log_parse_error(r);
×
4994
                return 1;
×
4995
        }
4996

4997
        r = pidref_set_pid(&pidref, pid);
×
4998
        if (r < 0) {
×
4999
                log_unit_debug_errno(UNIT(s), r, "GetConnectionUnixProcessID() returned invalid PID: %m");
×
5000
                return 1;
×
5001
        }
5002

5003
        log_unit_debug(UNIT(s), "D-Bus name %s is now owned by process " PID_FMT, s->bus_name, pidref.pid);
×
5004

5005
        (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), /* start_timestamp = */ NULL);
×
5006
        (void) unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
×
5007
        return 1;
5008
}
5009

5010
static void service_bus_name_owner_change(Unit *u, const char *new_owner) {
858✔
5011
        Service *s = ASSERT_PTR(SERVICE(u));
858✔
5012
        int r;
858✔
5013

5014
        if (new_owner)
858✔
5015
                log_unit_debug(u, "D-Bus name %s now owned by %s", s->bus_name, new_owner);
335✔
5016
        else
5017
                log_unit_debug(u, "D-Bus name %s now not owned by anyone.", s->bus_name);
523✔
5018

5019
        s->bus_name_good = new_owner;
858✔
5020

5021
        if (s->type == SERVICE_DBUS) {
858✔
5022
                /* service_enter_running() will figure out what to do */
5023
                if (s->state == SERVICE_RUNNING)
206✔
5024
                        service_enter_running(s, SERVICE_SUCCESS);
50✔
5025
                else if (s->state == SERVICE_START && new_owner)
156✔
5026
                        service_enter_start_post(s);
25✔
5027

5028
        } else if (new_owner && pick_up_pid_from_bus_name(s)) {
652✔
5029

5030
                /* Try to acquire PID from bus service */
5031

5032
                s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
×
5033

5034
                r = sd_bus_call_method_async(
×
5035
                                u->manager->api_bus,
×
5036
                                &s->bus_name_pid_lookup_slot,
5037
                                "org.freedesktop.DBus",
5038
                                "/org/freedesktop/DBus",
5039
                                "org.freedesktop.DBus",
5040
                                "GetConnectionUnixProcessID",
5041
                                bus_name_pid_lookup_callback,
5042
                                s,
5043
                                "s",
5044
                                s->bus_name);
5045
                if (r < 0)
×
5046
                        log_unit_debug_errno(u, r, "Failed to request owner PID of service name, ignoring: %m");
×
5047
        }
5048
}
858✔
5049

5050
int service_set_socket_fd(
2✔
5051
                Service *s,
5052
                int fd,
5053
                Socket *sock,
5054
                SocketPeer *peer, /* reference to object is donated to us on success */
5055
                bool selinux_context_net) {
5056

5057
        _cleanup_free_ char *peer_text = NULL;
2✔
5058
        int r;
2✔
5059

5060
        assert(s);
2✔
5061
        assert(fd >= 0);
2✔
5062
        assert(sock);
2✔
5063

5064
        /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
5065
         * to be configured. We take ownership of the passed fd on success. */
5066

5067
        if (UNIT(s)->load_state != UNIT_LOADED)
2✔
5068
                return -EINVAL;
5069

5070
        if (s->socket_fd >= 0)
2✔
5071
                return -EBUSY;
5072

5073
        assert(!s->socket_peer);
2✔
5074

5075
        if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
2✔
5076
                return -EAGAIN;
5077

5078
        if (getpeername_pretty(fd, true, &peer_text) >= 0) {
2✔
5079

5080
                if (UNIT(s)->description) {
2✔
5081
                        _cleanup_free_ char *a = NULL;
2✔
5082

5083
                        a = strjoin(UNIT(s)->description, " (", peer_text, ")");
2✔
5084
                        if (!a)
2✔
5085
                                return -ENOMEM;
×
5086

5087
                        r = unit_set_description(UNIT(s), a);
2✔
5088
                }  else
5089
                        r = unit_set_description(UNIT(s), peer_text);
×
5090
                if (r < 0)
2✔
5091
                        return r;
5092
        }
5093

5094
        r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_TRIGGERED_BY, UNIT(sock), false, UNIT_DEPENDENCY_IMPLICIT);
2✔
5095
        if (r < 0)
2✔
5096
                return log_unit_debug_errno(UNIT(s), r,
×
5097
                                            "Failed to add After=/TriggeredBy= dependencies on socket unit: %m");
5098

5099
        s->socket_fd = fd;
2✔
5100
        s->socket_peer = peer;
2✔
5101
        s->socket_fd_selinux_context_net = selinux_context_net;
2✔
5102

5103
        unit_ref_set(&s->accept_socket, UNIT(s), UNIT(sock));
2✔
5104
        return 0;
5105
}
5106

5107
static void service_reset_failed(Unit *u) {
111✔
5108
        Service *s = ASSERT_PTR(SERVICE(u));
111✔
5109

5110
        if (s->state == SERVICE_FAILED)
111✔
5111
                service_set_state(s, service_determine_dead_state(s));
×
5112

5113
        s->result = SERVICE_SUCCESS;
111✔
5114
        s->reload_result = SERVICE_SUCCESS;
111✔
5115
        s->live_mount_result = SERVICE_SUCCESS;
111✔
5116
        s->clean_result = SERVICE_SUCCESS;
111✔
5117
        s->n_restarts = 0;
111✔
5118
}
111✔
5119

5120
static PidRef* service_main_pid(Unit *u, bool *ret_is_alien) {
9,141✔
5121
        Service *s = ASSERT_PTR(SERVICE(u));
9,141✔
5122

5123
        if (ret_is_alien)
9,141✔
5124
                *ret_is_alien = s->main_pid_alien;
5,443✔
5125

5126
        return &s->main_pid;
9,141✔
5127
}
5128

5129
static PidRef* service_control_pid(Unit *u) {
9,141✔
5130
        return &ASSERT_PTR(SERVICE(u))->control_pid;
18,282✔
5131
}
5132

5133
static bool service_needs_console(Unit *u) {
5,656✔
5134
        Service *s = ASSERT_PTR(SERVICE(u));
5,656✔
5135

5136
        /* We provide our own implementation of this here, instead of relying of the generic implementation
5137
         * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
5138

5139
        if (!exec_context_may_touch_console(&s->exec_context))
5,656✔
5140
                return false;
5141

5142
        return IN_SET(s->state,
328✔
5143
                      SERVICE_CONDITION,
5144
                      SERVICE_START_PRE,
5145
                      SERVICE_START,
5146
                      SERVICE_START_POST,
5147
                      SERVICE_RUNNING,
5148
                      SERVICE_RELOAD,
5149
                      SERVICE_RELOAD_SIGNAL,
5150
                      SERVICE_RELOAD_NOTIFY,
5151
                      SERVICE_MOUNTING,
5152
                      SERVICE_STOP,
5153
                      SERVICE_STOP_WATCHDOG,
5154
                      SERVICE_STOP_SIGTERM,
5155
                      SERVICE_STOP_SIGKILL,
5156
                      SERVICE_STOP_POST,
5157
                      SERVICE_FINAL_WATCHDOG,
5158
                      SERVICE_FINAL_SIGTERM,
5159
                      SERVICE_FINAL_SIGKILL);
5160
}
5161

5162
static int service_exit_status(Unit *u) {
1,506✔
5163
        Service *s = ASSERT_PTR(SERVICE(u));
1,506✔
5164

5165
        if (s->main_exec_status.pid <= 0 ||
1,506✔
5166
            !dual_timestamp_is_set(&s->main_exec_status.exit_timestamp))
1,305✔
5167
                return -ENODATA;
5168

5169
        if (s->main_exec_status.code != CLD_EXITED)
1,305✔
5170
                return -EBADE;
5171

5172
        return s->main_exec_status.status;
1,233✔
5173
}
5174

5175
static const char* service_status_text(Unit *u) {
403✔
5176
        Service *s = ASSERT_PTR(SERVICE(u));
403✔
5177

5178
        return s->status_text;
403✔
5179
}
5180

5181
static int service_clean(Unit *u, ExecCleanMask mask) {
×
5182
        Service *s = ASSERT_PTR(SERVICE(u));
×
5183
        _cleanup_strv_free_ char **l = NULL;
×
5184
        bool may_clean_fdstore = false;
×
5185
        int r;
×
5186

5187
        assert(mask != 0);
×
5188

5189
        if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
×
5190
                return -EBUSY;
5191

5192
        /* Determine if there's anything we could potentially clean */
5193
        r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
×
5194
        if (r < 0)
×
5195
                return r;
5196

5197
        if (mask & EXEC_CLEAN_FDSTORE)
×
5198
                may_clean_fdstore = s->n_fd_store > 0 || s->n_fd_store_max > 0;
×
5199

5200
        if (strv_isempty(l) && !may_clean_fdstore)
×
5201
                return -EUNATCH; /* Nothing to potentially clean */
5202

5203
        /* Let's clean the stuff we can clean quickly */
5204
        if (may_clean_fdstore)
×
5205
                service_release_fd_store(s);
×
5206

5207
        /* If we are done, leave quickly */
5208
        if (strv_isempty(l)) {
×
5209
                if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
×
5210
                        service_set_state(s, SERVICE_DEAD);
×
5211
                return 0;
×
5212
        }
5213

5214
        /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
5215
        service_unwatch_control_pid(s);
×
5216
        s->clean_result = SERVICE_SUCCESS;
×
5217
        s->control_command = NULL;
×
5218
        s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
×
5219

5220
        r = service_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
×
5221
        if (r < 0) {
×
5222
                log_unit_warning_errno(u, r, "Failed to install timer: %m");
×
5223
                goto fail;
×
5224
        }
5225

5226
        r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
×
5227
        if (r < 0) {
×
5228
                log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
×
5229
                goto fail;
×
5230
        }
5231

5232
        service_set_state(s, SERVICE_CLEANING);
×
5233
        return 0;
5234

5235
fail:
×
5236
        s->clean_result = SERVICE_FAILURE_RESOURCES;
×
5237
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
×
5238
        return r;
×
5239
}
5240

5241
static int service_can_clean(Unit *u, ExecCleanMask *ret) {
1,063✔
5242
        Service *s = ASSERT_PTR(SERVICE(u));
1,063✔
5243
        ExecCleanMask mask = 0;
1,063✔
5244
        int r;
1,063✔
5245

5246
        assert(ret);
1,063✔
5247

5248
        r = exec_context_get_clean_mask(&s->exec_context, &mask);
1,063✔
5249
        if (r < 0)
1,063✔
5250
                return r;
1,063✔
5251

5252
        if (s->n_fd_store_max > 0)
1,063✔
5253
                mask |= EXEC_CLEAN_FDSTORE;
18✔
5254

5255
        *ret = mask;
1,063✔
5256
        return 0;
1,063✔
5257
}
5258

5259
static int service_live_mount(
×
5260
                Unit *u,
5261
                const char *src,
5262
                const char *dst,
5263
                sd_bus_message *message,
5264
                MountInNamespaceFlags flags,
5265
                const MountOptions *options,
5266
                sd_bus_error *error) {
5267

5268
        Service *s = ASSERT_PTR(SERVICE(u));
×
5269
        _cleanup_(pidref_done) PidRef worker = PIDREF_NULL;
×
5270
        int r;
×
5271

5272
        assert(u);
×
5273
        assert(u->manager);
×
5274
        assert(src);
×
5275
        assert(dst);
×
5276
        assert(message);
×
5277
        assert(!s->mount_request);
×
5278

5279
        if (s->state != SERVICE_RUNNING || !pidref_is_set(&s->main_pid)) {
×
5280
                log_unit_warning(u, "Service is not running, cannot live mount.");
×
5281
                return sd_bus_error_setf(
×
5282
                                error,
5283
                                BUS_ERROR_UNIT_INACTIVE,
5284
                                "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: service not running",
5285
                                src,
5286
                                dst,
5287
                                u->id);
5288
        }
5289

5290
        if (mount_point_is_credentials(u->manager->prefix[EXEC_DIRECTORY_RUNTIME], dst)) {
×
5291
                log_unit_warning(u, "Refusing to live mount over credential mount '%s'.", dst);
×
5292
                return sd_bus_error_setf(
×
5293
                                error,
5294
                                SD_BUS_ERROR_INVALID_ARGS,
5295
                                "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: cannot mount over credential mount",
5296
                                src,
5297
                                dst,
5298
                                u->id);
5299
        }
5300

5301
        if (path_startswith_strv(dst, s->exec_context.inaccessible_paths)) {
×
5302
                log_unit_warning(u, "%s is not accessible to this unit, cannot live mount.", dst);
×
5303
                return sd_bus_error_setf(
×
5304
                                error,
5305
                                SD_BUS_ERROR_INVALID_ARGS,
5306
                                "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: destination is not accessible to this unit",
5307
                                src,
5308
                                dst,
5309
                                u->id);
5310
        }
5311

5312
        service_unwatch_control_pid(s);
×
5313
        s->live_mount_result = SERVICE_SUCCESS;
×
5314
        s->control_command = NULL;
×
5315
        s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
×
5316

5317
        r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
×
5318
        if (r < 0) {
×
5319
                log_unit_error_errno(u, r, "Failed to install timer: %m");
×
5320
                sd_bus_error_set_errnof(error, r,
×
5321
                                        "Live mounting '%s' on '%s' for unit '%s': failed to install timer: %m",
5322
                                        src, dst, u->id);
5323
                goto fail;
×
5324
        }
5325

5326
        const char *propagate_directory = strjoina("/run/systemd/propagate/", u->id);
×
5327

5328
        /* Given we are running from PID1, avoid doing potentially heavy I/O operations like opening images
5329
         * directly, and instead fork a worker process. We record the D-Bus message, so that we can reply
5330
         * after the operation has finished. This way callers can wait on the message and know that the new
5331
         * resource is available (or the operation failed) once they receive the response. */
5332
        r = unit_fork_helper_process(u, "(sd-mount-in-ns)", /* into_cgroup= */ false, &worker);
×
5333
        if (r < 0) {
4✔
5334
                log_unit_error_errno(u, r,
×
5335
                                     "Failed to fork process to mount '%s' on '%s' in unit's namespace: %m",
5336
                                     src, dst);
5337
                sd_bus_error_set_errnof(error, r,
×
5338
                                        "Live mounting '%s' on '%s' for unit '%s': failed to fork off helper process into namespace: %m",
5339
                                        src, dst, u->id);
5340
                goto fail;
×
5341
        }
5342
        if (r == 0) {
4✔
5343
                if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
4✔
5344
                        r = mount_image_in_namespace(
4✔
5345
                                        &s->main_pid,
2✔
5346
                                        propagate_directory,
5347
                                        "/run/systemd/incoming/",
5348
                                        src, dst,
5349
                                        flags,
5350
                                        options,
5351
                                        s->exec_context.mount_image_policy ?: &image_policy_service);
2✔
5352
                else
5353
                        r = bind_mount_in_namespace(
2✔
5354
                                        &s->main_pid,
2✔
5355
                                        propagate_directory,
5356
                                        "/run/systemd/incoming/",
5357
                                        src, dst,
5358
                                        flags);
5359
                if (r < 0)
4✔
5360
                        log_unit_error_errno(u, r,
×
5361
                                             "Failed to mount '%s' on '%s' in unit's namespace: %m",
5362
                                             src, dst);
5363
                else
5364
                        log_unit_debug(u, "Mounted '%s' on '%s' in unit's namespace", src, dst);
4✔
5365

5366
                _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
4✔
5367
        }
5368

5369
        r = unit_watch_pidref(u, &worker, /* exclusive= */ true);
×
5370
        if (r < 0) {
×
5371
                log_unit_warning_errno(u, r, "Failed to watch live mount helper process: %m");
×
5372
                sd_bus_error_set_errnof(error, r,
×
5373
                                        "Live mounting '%s' on '%s' for unit '%s': failed to watch live mount helper process: %m",
5374
                                        src, dst, u->id);
5375
                goto fail;
×
5376
        }
5377

5378
        s->mount_request = sd_bus_message_ref(message);
×
5379
        s->control_pid = TAKE_PIDREF(worker);
×
5380
        service_set_state(s, SERVICE_MOUNTING);
×
5381
        return 0;
5382

5383
fail:
×
5384
        s->live_mount_result = SERVICE_FAILURE_RESOURCES;
×
5385
        service_enter_running(s, SERVICE_SUCCESS);
×
5386
        return r;
5387
}
5388

5389
static int service_can_live_mount(Unit *u, sd_bus_error *error) {
1,063✔
5390
        Service *s = ASSERT_PTR(SERVICE(u));
1,063✔
5391

5392
        /* Ensure that the unit runs in a private mount namespace */
5393
        if (!exec_needs_mount_namespace(&s->exec_context, /* params= */ NULL, s->exec_runtime))
1,063✔
5394
                return sd_bus_error_setf(
716✔
5395
                                error,
5396
                                SD_BUS_ERROR_INVALID_ARGS,
5397
                                "Unit '%s' not running in private mount namespace, cannot live mount.",
5398
                                u->id);
5399

5400
        return 0;
5401
}
5402

5403
static const char* service_finished_job(Unit *u, JobType t, JobResult result) {
3,016✔
5404
        Service *s = ASSERT_PTR(SERVICE(u));
3,016✔
5405

5406
        if (t == JOB_START &&
3,016✔
5407
            result == JOB_DONE &&
1,878✔
5408
            s->type == SERVICE_ONESHOT)
1,878✔
5409
                return "Finished %s.";
1,030✔
5410

5411
        /* Fall back to generic */
5412
        return NULL;
5413
}
5414

5415
static int service_can_start(Unit *u) {
1,927✔
5416
        Service *s = ASSERT_PTR(SERVICE(u));
1,927✔
5417
        int r;
1,927✔
5418

5419
        /* Make sure we don't enter a busy loop of some kind. */
5420
        r = unit_test_start_limit(u);
1,927✔
5421
        if (r < 0) {
1,927✔
5422
                service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
1✔
5423
                return r;
1✔
5424
        }
5425

5426
        return 1;
5427
}
5428

5429
static void service_release_resources(Unit *u) {
1,161✔
5430
        Service *s = ASSERT_PTR(SERVICE(u));
1,161✔
5431

5432
        /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
5433
         * anymore for it, and it hence is a good idea to release resources */
5434

5435
        /* Don't release resources if this is a transitionary failed/dead state
5436
         * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
5437
         * failure state. */
5438
        if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
1,161✔
5439
                return;
5440

5441
        log_unit_debug(u, "Releasing resources...");
1,161✔
5442

5443
        service_release_socket_fd(s);
1,161✔
5444
        service_release_stdio_fd(s);
1,161✔
5445
        service_release_extra_fds(s);
1,161✔
5446

5447
        if (s->fd_store_preserve_mode != EXEC_PRESERVE_YES)
1,161✔
5448
                service_release_fd_store(s);
1,152✔
5449

5450
        if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
1,161✔
5451
                service_set_state(s, SERVICE_DEAD);
×
5452
}
5453

5454
int service_determine_exec_selinux_label(Service *s, char **ret) {
2,228✔
5455
        int r;
2,228✔
5456

5457
        assert(s);
2,228✔
5458
        assert(ret);
2,228✔
5459

5460
        if (!mac_selinux_use())
2,228✔
5461
                return -ENODATA;
2,228✔
5462

5463
        /* Returns the SELinux label used for execution of the main service binary */
5464

5465
        if (s->exec_context.selinux_context)
×
5466
                /* Prefer the explicitly configured label if there is one */
5467
                return strdup_to(ret, s->exec_context.selinux_context);
×
5468

5469
        if (s->exec_context.root_image ||
×
5470
            s->exec_context.n_extension_images > 0 ||
×
5471
            !strv_isempty(s->exec_context.extension_directories)) /* We cannot chase paths through images */
×
5472
                return log_unit_debug_errno(UNIT(s), SYNTHETIC_ERRNO(ENODATA), "Service with RootImage=, ExtensionImages= or ExtensionDirectories= set, cannot determine socket SELinux label before activation, ignoring.");
×
5473

5474
        ExecCommand *c = s->exec_command[SERVICE_EXEC_START];
×
5475
        if (!c)
×
5476
                return -ENODATA;
5477

5478
        _cleanup_free_ char *path = NULL;
×
5479
        r = chase(c->path, s->exec_context.root_directory, CHASE_PREFIX_ROOT, &path, NULL);
×
5480
        if (r < 0) {
×
5481
                log_unit_debug_errno(UNIT(s), r, "Failed to resolve service binary '%s', ignoring.", c->path);
×
5482
                return -ENODATA;
×
5483
        }
5484

5485
        r = mac_selinux_get_create_label_from_exe(path, ret);
×
5486
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
5487
                log_unit_debug_errno(UNIT(s), r, "Reading SELinux label off binary '%s' is not supported, ignoring.", path);
×
5488
                return -ENODATA;
×
5489
        }
5490
        if (ERRNO_IS_NEG_PRIVILEGE(r)) {
×
5491
                log_unit_debug_errno(UNIT(s), r, "Can't read SELinux label off binary '%s', due to privileges, ignoring.", path);
×
5492
                return -ENODATA;
×
5493
        }
5494
        if (r < 0)
×
5495
                return log_unit_debug_errno(UNIT(s), r, "Failed to read SELinux label off binary '%s': %m", path);
×
5496

5497
        return 0;
5498
}
5499

5500
static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
5501
        [SERVICE_RESTART_NO]          = "no",
5502
        [SERVICE_RESTART_ON_SUCCESS]  = "on-success",
5503
        [SERVICE_RESTART_ON_FAILURE]  = "on-failure",
5504
        [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
5505
        [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
5506
        [SERVICE_RESTART_ON_ABORT]    = "on-abort",
5507
        [SERVICE_RESTART_ALWAYS]      = "always",
5508
};
5509

5510
DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
2,439✔
5511

5512
static const char* const service_restart_mode_table[_SERVICE_RESTART_MODE_MAX] = {
5513
        [SERVICE_RESTART_MODE_NORMAL] = "normal",
5514
        [SERVICE_RESTART_MODE_DIRECT] = "direct",
5515
        [SERVICE_RESTART_MODE_DEBUG]  = "debug",
5516
};
5517

5518
DEFINE_STRING_TABLE_LOOKUP(service_restart_mode, ServiceRestartMode);
1,132✔
5519

5520
static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
5521
        [SERVICE_SIMPLE]        = "simple",
5522
        [SERVICE_FORKING]       = "forking",
5523
        [SERVICE_ONESHOT]       = "oneshot",
5524
        [SERVICE_DBUS]          = "dbus",
5525
        [SERVICE_NOTIFY]        = "notify",
5526
        [SERVICE_NOTIFY_RELOAD] = "notify-reload",
5527
        [SERVICE_IDLE]          = "idle",
5528
        [SERVICE_EXEC]          = "exec",
5529
};
5530

5531
DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
11,748✔
5532

5533
static const char* const service_exit_type_table[_SERVICE_EXIT_TYPE_MAX] = {
5534
        [SERVICE_EXIT_MAIN]   = "main",
5535
        [SERVICE_EXIT_CGROUP] = "cgroup",
5536
};
5537

5538
DEFINE_STRING_TABLE_LOOKUP(service_exit_type, ServiceExitType);
1,080✔
5539

5540
static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
5541
        [SERVICE_EXEC_CONDITION]  = "ExecCondition",
5542
        [SERVICE_EXEC_START_PRE]  = "ExecStartPre",
5543
        [SERVICE_EXEC_START]      = "ExecStart",
5544
        [SERVICE_EXEC_START_POST] = "ExecStartPost",
5545
        [SERVICE_EXEC_RELOAD]     = "ExecReload",
5546
        [SERVICE_EXEC_STOP]       = "ExecStop",
5547
        [SERVICE_EXEC_STOP_POST]  = "ExecStopPost",
5548
};
5549

5550
DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
5,168✔
5551

5552
static const char* const service_exec_ex_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
5553
        [SERVICE_EXEC_CONDITION]  = "ExecConditionEx",
5554
        [SERVICE_EXEC_START_PRE]  = "ExecStartPreEx",
5555
        [SERVICE_EXEC_START]      = "ExecStartEx",
5556
        [SERVICE_EXEC_START_POST] = "ExecStartPostEx",
5557
        [SERVICE_EXEC_RELOAD]     = "ExecReloadEx",
5558
        [SERVICE_EXEC_STOP]       = "ExecStopEx",
5559
        [SERVICE_EXEC_STOP_POST]  = "ExecStopPostEx",
5560
};
5561

5562
DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command, ServiceExecCommand);
1,596✔
5563

5564
static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
5565
        [NOTIFY_UNKNOWN]   = "unknown",
5566
        [NOTIFY_READY]     = "ready",
5567
        [NOTIFY_RELOADING] = "reloading",
5568
        [NOTIFY_STOPPING]  = "stopping",
5569
};
5570

5571
DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
145✔
5572

5573
static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
5574
        [SERVICE_SUCCESS]                 = "success",
5575
        [SERVICE_FAILURE_RESOURCES]       = "resources",
5576
        [SERVICE_FAILURE_PROTOCOL]        = "protocol",
5577
        [SERVICE_FAILURE_TIMEOUT]         = "timeout",
5578
        [SERVICE_FAILURE_EXIT_CODE]       = "exit-code",
5579
        [SERVICE_FAILURE_SIGNAL]          = "signal",
5580
        [SERVICE_FAILURE_CORE_DUMP]       = "core-dump",
5581
        [SERVICE_FAILURE_WATCHDOG]        = "watchdog",
5582
        [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
5583
        [SERVICE_FAILURE_OOM_KILL]        = "oom-kill",
5584
        [SERVICE_SKIP_CONDITION]          = "exec-condition",
5585
};
5586

5587
DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
68,037✔
5588

5589
static const char* const service_timeout_failure_mode_table[_SERVICE_TIMEOUT_FAILURE_MODE_MAX] = {
5590
        [SERVICE_TIMEOUT_TERMINATE] = "terminate",
5591
        [SERVICE_TIMEOUT_ABORT]     = "abort",
5592
        [SERVICE_TIMEOUT_KILL]      = "kill",
5593
};
5594

5595
DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode, ServiceTimeoutFailureMode);
2,342✔
5596

5597
const UnitVTable service_vtable = {
5598
        .object_size = sizeof(Service),
5599
        .exec_context_offset = offsetof(Service, exec_context),
5600
        .cgroup_context_offset = offsetof(Service, cgroup_context),
5601
        .kill_context_offset = offsetof(Service, kill_context),
5602
        .exec_runtime_offset = offsetof(Service, exec_runtime),
5603
        .cgroup_runtime_offset = offsetof(Service, cgroup_runtime),
5604

5605
        .sections =
5606
                "Unit\0"
5607
                "Service\0"
5608
                "Install\0",
5609
        .private_section = "Service",
5610

5611
        .can_transient = true,
5612
        .can_delegate = true,
5613
        .can_fail = true,
5614
        .can_set_managed_oom = true,
5615

5616
        .init = service_init,
5617
        .done = service_done,
5618
        .load = service_load,
5619
        .release_resources = service_release_resources,
5620

5621
        .coldplug = service_coldplug,
5622

5623
        .dump = service_dump,
5624

5625
        .start = service_start,
5626
        .stop = service_stop,
5627
        .reload = service_reload,
5628

5629
        .can_reload = service_can_reload,
5630

5631
        .clean = service_clean,
5632
        .can_clean = service_can_clean,
5633

5634
        .live_mount = service_live_mount,
5635
        .can_live_mount = service_can_live_mount,
5636

5637
        .freezer_action = unit_cgroup_freezer_action,
5638

5639
        .serialize = service_serialize,
5640
        .deserialize_item = service_deserialize_item,
5641

5642
        .active_state = service_active_state,
5643
        .sub_state_to_string = service_sub_state_to_string,
5644

5645
        .will_restart = service_will_restart,
5646

5647
        .may_gc = service_may_gc,
5648

5649
        .sigchld_event = service_sigchld_event,
5650

5651
        .reset_failed = service_reset_failed,
5652

5653
        .notify_cgroup_empty = service_notify_cgroup_empty_event,
5654
        .notify_cgroup_oom = service_notify_cgroup_oom_event,
5655
        .notify_message = service_notify_message,
5656
        .notify_handoff_timestamp = service_handoff_timestamp,
5657
        .notify_pidref = service_notify_pidref,
5658

5659
        .main_pid = service_main_pid,
5660
        .control_pid = service_control_pid,
5661

5662
        .bus_name_owner_change = service_bus_name_owner_change,
5663

5664
        .bus_set_property = bus_service_set_property,
5665
        .bus_commit_properties = bus_service_commit_properties,
5666

5667
        .get_timeout = service_get_timeout,
5668
        .get_timeout_start_usec = service_get_timeout_start_usec,
5669
        .needs_console = service_needs_console,
5670
        .exit_status = service_exit_status,
5671
        .status_text = service_status_text,
5672

5673
        .status_message_formats = {
5674
                .finished_start_job = {
5675
                        [JOB_FAILED]     = "Failed to start %s.",
5676
                },
5677
                .finished_stop_job = {
5678
                        [JOB_DONE]       = "Stopped %s.",
5679
                        [JOB_FAILED]     = "Stopped (with error) %s.",
5680
                },
5681
                .finished_job = service_finished_job,
5682
        },
5683

5684
        .can_start = service_can_start,
5685

5686
        .notify_plymouth = true,
5687

5688
        .audit_start_message_type = AUDIT_SERVICE_START,
5689
        .audit_stop_message_type = AUDIT_SERVICE_STOP,
5690
};
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