]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/service.c
man/systemd-sysext: list ephemeral/ephemeral-import in the list of options
[thirdparty/systemd.git] / src / core / service.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
be1adc27 3#include <math.h>
ca78ad1d 4#include <sys/stat.h>
2c4104f0 5#include <unistd.h>
5cb5a6ff 6
836e4e7e 7#include "sd-bus.h"
7a0019d3
LP
8#include "sd-messages.h"
9
b5efdb8a 10#include "alloc-util.h"
574634bc 11#include "async.h"
5162829e 12#include "bus-common-errors.h"
4f5dd394 13#include "bus-error.h"
4f5dd394 14#include "bus-util.h"
f461a28d 15#include "chase.h"
4139c1b2 16#include "dbus-service.h"
6fcbec6f 17#include "dbus-unit.h"
f2eb0c50 18#include "devnum-util.h"
4d1a6904 19#include "env-util.h"
836e4e7e 20#include "errno-util.h"
4f5dd394 21#include "escape.h"
dfdeb0b1 22#include "execute.h"
757e469d 23#include "exec-credential.h"
4f5dd394 24#include "exit-status.h"
836e4e7e 25#include "extract-word.h"
3ffd4af2 26#include "fd-util.h"
836e4e7e 27#include "fdset.h"
a5c32cff 28#include "fileio.h"
f97b34a6 29#include "format-util.h"
836e4e7e
DDM
30#include "glyph-util.h"
31#include "image-policy.h"
4f5dd394
LP
32#include "log.h"
33#include "manager.h"
d52b8493 34#include "missing_audit.h"
5162829e 35#include "mount-util.h"
dfdeb0b1 36#include "namespace.h"
cd48e23f 37#include "open-file.h"
6bedfcbb 38#include "parse-util.h"
4f5dd394 39#include "path-util.h"
836e4e7e 40#include "path.h"
7933e971 41#include "pidfd-util.h"
0b452006 42#include "process-util.h"
5918a933 43#include "random-util.h"
8017ed7e 44#include "selinux-util.h"
d68c645b 45#include "serialize.h"
3ffd4af2 46#include "service.h"
24882e06 47#include "signal-util.h"
836e4e7e 48#include "socket.h"
4f5dd394 49#include "special.h"
836e4e7e 50#include "stat-util.h"
8b43440b 51#include "string-table.h"
07630cea 52#include "string-util.h"
4f5dd394 53#include "strv.h"
569269d0 54#include "transaction.h"
4f5dd394 55#include "unit.h"
1cf40697 56#include "unit-name.h"
4f5dd394 57#include "utf8.h"
034c6ed7 58
edbf8984
ZJS
59#define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
60
acbb0225 61static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
17f6b640
YW
62 [SERVICE_DEAD] = UNIT_INACTIVE,
63 [SERVICE_CONDITION] = UNIT_ACTIVATING,
64 [SERVICE_START_PRE] = UNIT_ACTIVATING,
65 [SERVICE_START] = UNIT_ACTIVATING,
66 [SERVICE_START_POST] = UNIT_ACTIVATING,
67 [SERVICE_RUNNING] = UNIT_ACTIVE,
68 [SERVICE_EXITED] = UNIT_ACTIVE,
69 [SERVICE_RELOAD] = UNIT_RELOADING,
70 [SERVICE_RELOAD_SIGNAL] = UNIT_RELOADING,
71 [SERVICE_RELOAD_NOTIFY] = UNIT_RELOADING,
dfdeb0b1 72 [SERVICE_REFRESH_EXTENSIONS] = UNIT_REFRESHING,
a53e92a1 73 [SERVICE_MOUNTING] = UNIT_REFRESHING,
17f6b640
YW
74 [SERVICE_STOP] = UNIT_DEACTIVATING,
75 [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
76 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
77 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
78 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
79 [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
80 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
81 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
82 [SERVICE_FAILED] = UNIT_FAILED,
83 [SERVICE_DEAD_BEFORE_AUTO_RESTART] = UNIT_INACTIVE,
a1d31573 84 [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
17f6b640
YW
85 [SERVICE_DEAD_RESOURCES_PINNED] = UNIT_INACTIVE,
86 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
87 [SERVICE_AUTO_RESTART_QUEUED] = UNIT_ACTIVATING,
88 [SERVICE_CLEANING] = UNIT_MAINTENANCE,
034c6ed7 89};
5cb5a6ff 90
e056b01d
LP
91/* For Type=idle we never want to delay any other jobs, hence we
92 * consider idle jobs active as soon as we start working on them */
93static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
17f6b640
YW
94 [SERVICE_DEAD] = UNIT_INACTIVE,
95 [SERVICE_CONDITION] = UNIT_ACTIVE,
96 [SERVICE_START_PRE] = UNIT_ACTIVE,
97 [SERVICE_START] = UNIT_ACTIVE,
98 [SERVICE_START_POST] = UNIT_ACTIVE,
99 [SERVICE_RUNNING] = UNIT_ACTIVE,
100 [SERVICE_EXITED] = UNIT_ACTIVE,
101 [SERVICE_RELOAD] = UNIT_RELOADING,
102 [SERVICE_RELOAD_SIGNAL] = UNIT_RELOADING,
103 [SERVICE_RELOAD_NOTIFY] = UNIT_RELOADING,
dfdeb0b1 104 [SERVICE_REFRESH_EXTENSIONS] = UNIT_REFRESHING,
a53e92a1 105 [SERVICE_MOUNTING] = UNIT_REFRESHING,
17f6b640
YW
106 [SERVICE_STOP] = UNIT_DEACTIVATING,
107 [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
108 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
109 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
110 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
111 [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
112 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
113 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
114 [SERVICE_FAILED] = UNIT_FAILED,
115 [SERVICE_DEAD_BEFORE_AUTO_RESTART] = UNIT_INACTIVE,
a1d31573 116 [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
17f6b640
YW
117 [SERVICE_DEAD_RESOURCES_PINNED] = UNIT_INACTIVE,
118 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
119 [SERVICE_AUTO_RESTART_QUEUED] = UNIT_ACTIVATING,
120 [SERVICE_CLEANING] = UNIT_MAINTENANCE,
e056b01d
LP
121};
122
5686391b 123static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
718db961
LP
124static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
125static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
5686391b 126static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
718db961 127
842129f5 128static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
308d72dc 129static void service_enter_reload_by_notify(Service *s);
842129f5 130
94114711
YW
131static bool SERVICE_STATE_WITH_MAIN_PROCESS(ServiceState state) {
132 return IN_SET(state,
133 SERVICE_START, SERVICE_START_POST,
134 SERVICE_RUNNING,
dfdeb0b1 135 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS,
5162829e 136 SERVICE_MOUNTING,
94114711
YW
137 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
138 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL);
139}
140
141static bool SERVICE_STATE_WITH_CONTROL_PROCESS(ServiceState state) {
142 return IN_SET(state,
143 SERVICE_CONDITION,
144 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
dfdeb0b1 145 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS,
a53e92a1 146 SERVICE_MOUNTING,
94114711
YW
147 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
148 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
a53e92a1 149 SERVICE_CLEANING);
94114711
YW
150}
151
a16e1123
LP
152static void service_init(Unit *u) {
153 Service *s = SERVICE(u);
154
155 assert(u);
ac155bb8 156 assert(u->load_state == UNIT_STUB);
a16e1123 157
c9e120e0
LP
158 s->timeout_start_usec = u->manager->defaults.timeout_start_usec;
159 s->timeout_stop_usec = u->manager->defaults.timeout_stop_usec;
160 s->timeout_abort_usec = u->manager->defaults.timeout_abort_usec;
161 s->timeout_abort_set = u->manager->defaults.timeout_abort_set;
162 s->restart_usec = u->manager->defaults.restart_usec;
e9f17fa8 163 s->restart_max_delay_usec = USEC_INFINITY;
36c16a7c 164 s->runtime_max_usec = USEC_INFINITY;
0b86feac 165 s->type = _SERVICE_TYPE_INVALID;
254d1313
ZJS
166 s->socket_fd = -EBADF;
167 s->stdin_fd = s->stdout_fd = s->stderr_fd = -EBADF;
3185a36b 168 s->guess_main_pid = true;
c79ab77c
LP
169 s->main_pid = PIDREF_NULL;
170 s->control_pid = PIDREF_NULL;
a16e1123 171 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
00f5ad93
LP
172
173 s->exec_context.keyring_mode = MANAGER_IS_SYSTEM(u->manager) ?
174 EXEC_KEYRING_PRIVATE : EXEC_KEYRING_INHERIT;
aa8c4bbf 175
19dff691
MY
176 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
177
aa8c4bbf 178 s->watchdog_original_usec = USEC_INFINITY;
afcfaa69
LP
179
180 s->oom_policy = _OOM_POLICY_INVALID;
3bd28bf7
LP
181 s->reload_begin_usec = USEC_INFINITY;
182 s->reload_signal = SIGHUP;
b9c1883a
LP
183
184 s->fd_store_preserve_mode = EXEC_PRESERVE_RESTART;
a16e1123
LP
185}
186
5e94833f
LP
187static void service_unwatch_control_pid(Service *s) {
188 assert(s);
ea1e0bf1 189 unit_unwatch_pidref_done(UNIT(s), &s->control_pid);
5e94833f
LP
190}
191
192static void service_unwatch_main_pid(Service *s) {
193 assert(s);
ea1e0bf1 194 unit_unwatch_pidref_done(UNIT(s), &s->main_pid);
5e94833f
LP
195}
196
3e52541e 197static void service_unwatch_pid_file(Service *s) {
e9fa1bf7
MY
198 assert(s);
199
3e52541e
MS
200 if (!s->pid_file_pathspec)
201 return;
202
f2341e0a 203 log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
718db961 204 path_spec_unwatch(s->pid_file_pathspec);
3e52541e 205 path_spec_done(s->pid_file_pathspec);
a1e58e8e 206 s->pid_file_pathspec = mfree(s->pid_file_pathspec);
3e52541e
MS
207}
208
7e0e6b50 209static int service_set_main_pidref(Service *s, PidRef pidref_consume, const dual_timestamp *start_timestamp) {
c603f523 210 _cleanup_(pidref_done) PidRef pidref = pidref_consume;
6774be42
LP
211 int r;
212
5925dd3c
LP
213 assert(s);
214
c603f523 215 /* Takes ownership of the specified pidref on both success and failure. */
b1f6901d 216
c603f523 217 if (!pidref_is_set(&pidref))
b1f6901d
LP
218 return -ESRCH;
219
c603f523 220 if (pidref.pid <= 1)
5925dd3c
LP
221 return -EINVAL;
222
c603f523 223 if (pidref_is_self(&pidref))
5925dd3c
LP
224 return -EINVAL;
225
c603f523 226 if (s->main_pid_known && pidref_equal(&s->main_pid, &pidref))
7400b9d2
LP
227 return 0;
228
c603f523 229 if (!pidref_equal(&s->main_pid, &pidref)) {
7400b9d2 230 service_unwatch_main_pid(s);
f781292d
MY
231
232 dual_timestamp pid_start_time;
233
234 if (!start_timestamp) {
235 usec_t t;
236
237 if (pidref_get_start_time(&pidref, &t) >= 0)
238 start_timestamp = dual_timestamp_from_boottime(&pid_start_time, t);
239 }
240
7e0e6b50 241 exec_status_start(&s->main_exec_status, pidref.pid, start_timestamp);
7400b9d2 242 }
41efeaec 243
c603f523 244 s->main_pid = TAKE_PIDREF(pidref);
6dfa5494
LP
245 s->main_pid_known = true;
246
6774be42
LP
247 r = pidref_is_my_child(&s->main_pid);
248 if (r < 0)
249 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);
120be68b 250 else if (r == 0) // FIXME: Supervise through pidfd here
b1f6901d 251 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);
6774be42 252 s->main_pid_alien = r <= 0;
120be68b 253
5925dd3c
LP
254 return 0;
255}
256
81a1d6d6 257void service_release_socket_fd(Service *s) {
4f2d528d
LP
258 assert(s);
259
c25fac9a
LP
260 if (s->socket_fd < 0 && !UNIT_ISSET(s->accept_socket) && !s->socket_peer)
261 return;
262
263 log_unit_debug(UNIT(s), "Closing connection socket.");
264
5cc3985e 265 /* Undo the effect of service_set_socket_fd(). */
4f2d528d 266
5cc3985e 267 s->socket_fd = asynchronous_close(s->socket_fd);
6cf6bbc2 268
5cc3985e
LP
269 if (UNIT_ISSET(s->accept_socket)) {
270 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
271 unit_ref_unset(&s->accept_socket);
272 }
3fabebf4
LP
273
274 s->socket_peer = socket_peer_unref(s->socket_peer);
6cf6bbc2
LP
275}
276
19dff691
MY
277static void service_override_notify_access(Service *s, NotifyAccess notify_access_override) {
278 assert(s);
279
280 s->notify_access_override = notify_access_override;
281
282 log_unit_debug(UNIT(s), "notify_access=%s", notify_access_to_string(s->notify_access));
283 log_unit_debug(UNIT(s), "notify_access_override=%s", notify_access_to_string(s->notify_access_override));
284}
285
a6927d7f
MO
286static void service_stop_watchdog(Service *s) {
287 assert(s);
288
5dcadb4c 289 s->watchdog_event_source = sd_event_source_disable_unref(s->watchdog_event_source);
842129f5 290 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
a6927d7f
MO
291}
292
842129f5 293static void service_start_watchdog(Service *s) {
2787d83c 294 usec_t watchdog_usec;
9fb1cdb4 295 int r;
bb242b7b
MO
296
297 assert(s);
298
2787d83c 299 watchdog_usec = service_get_watchdog_usec(s);
0da36375 300 if (!timestamp_is_set(watchdog_usec)) {
9fb1cdb4 301 service_stop_watchdog(s);
bb242b7b 302 return;
9fb1cdb4 303 }
bb242b7b 304
718db961 305 if (s->watchdog_event_source) {
2787d83c 306 r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
718db961 307 if (r < 0) {
f2341e0a 308 log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
718db961
LP
309 return;
310 }
311
842129f5 312 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
c4ef3317 313 } else {
6a0f1f6d
LP
314 r = sd_event_add_time(
315 UNIT(s)->manager->event,
316 &s->watchdog_event_source,
317 CLOCK_MONOTONIC,
2787d83c 318 usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
6a0f1f6d 319 service_dispatch_watchdog, s);
c4ef3317 320 if (r < 0) {
f2341e0a 321 log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
c4ef3317
LP
322 return;
323 }
324
7dfbe2e3
TG
325 (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
326
c4ef3317
LP
327 /* Let's process everything else which might be a sign
328 * of living before we consider a service died. */
d42b61d2 329 r = sd_event_source_set_priority(s->watchdog_event_source, EVENT_PRIORITY_SERVICE_WATCHDOG);
c4ef3317 330 }
bb242b7b 331 if (r < 0)
f2341e0a 332 log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
bb242b7b
MO
333}
334
5171356e
MY
335usec_t service_restart_usec_next(Service *s) {
336 unsigned n_restarts_next;
be1adc27
MY
337
338 assert(s);
339
0c59d2e4 340 /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
ba5e342c
MY
341 * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
342 * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
343 n_restarts_next = s->n_restarts + (s->state == SERVICE_AUTO_RESTART_QUEUED ? 0 : 1);
be1adc27 344
5171356e 345 if (n_restarts_next <= 1 ||
be1adc27 346 s->restart_steps == 0 ||
ea792cac 347 s->restart_usec == 0 ||
e9f17fa8
MY
348 s->restart_max_delay_usec == USEC_INFINITY ||
349 s->restart_usec >= s->restart_max_delay_usec)
fe3d33c1
MY
350 return s->restart_usec;
351
352 if (n_restarts_next > s->restart_steps)
353 return s->restart_max_delay_usec;
354
355 /* Enforced in service_verify() and above */
356 assert(s->restart_max_delay_usec > s->restart_usec);
357
358 /* r_i / r_0 = (r_n / r_0) ^ (i / n)
359 * where,
360 * r_0 : initial restart usec (s->restart_usec),
361 * r_i : i-th restart usec (value),
362 * r_n : maximum restart usec (s->restart_max_delay_usec),
363 * i : index of the next step (n_restarts_next - 1)
364 * n : num maximum steps (s->restart_steps) */
365 return (usec_t) (s->restart_usec * powl((long double) s->restart_max_delay_usec / s->restart_usec,
366 (long double) (n_restarts_next - 1) / s->restart_steps));
be1adc27
MY
367}
368
ec35a7f6
LP
369static void service_extend_event_source_timeout(Service *s, sd_event_source *source, usec_t extended) {
370 usec_t current;
371 int r;
372
a327431b
DB
373 assert(s);
374
ec35a7f6
LP
375 /* Extends the specified event source timer to at least the specified time, unless it is already later
376 * anyway. */
a327431b 377
ec35a7f6
LP
378 if (!source)
379 return;
a327431b 380
ec35a7f6
LP
381 r = sd_event_source_get_time(source, &current);
382 if (r < 0) {
383 const char *desc;
384 (void) sd_event_source_get_description(s->timer_event_source, &desc);
385 log_unit_warning_errno(UNIT(s), r, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc));
386 return;
387 }
a327431b 388
ec35a7f6
LP
389 if (current >= extended) /* Current timeout is already longer, ignore this. */
390 return;
a327431b 391
ec35a7f6
LP
392 r = sd_event_source_set_time(source, extended);
393 if (r < 0) {
394 const char *desc;
395 (void) sd_event_source_get_description(s->timer_event_source, &desc);
365c2885 396 log_unit_warning_errno(UNIT(s), r, "Failed to set timeout time for event source '%s', ignoring %m", strna(desc));
a327431b
DB
397 }
398}
399
ec35a7f6
LP
400static void service_extend_timeout(Service *s, usec_t extend_timeout_usec) {
401 usec_t extended;
402
403 assert(s);
404
0da36375 405 if (!timestamp_is_set(extend_timeout_usec))
ec35a7f6
LP
406 return;
407
408 extended = usec_add(now(CLOCK_MONOTONIC), extend_timeout_usec);
409
410 service_extend_event_source_timeout(s, s->timer_event_source, extended);
411 service_extend_event_source_timeout(s, s->watchdog_event_source, extended);
412}
413
a6927d7f
MO
414static void service_reset_watchdog(Service *s) {
415 assert(s);
416
fa5a0251 417 dual_timestamp_now(&s->watchdog_timestamp);
842129f5 418 service_start_watchdog(s);
a6927d7f
MO
419}
420
95d0d8ed 421static void service_override_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
2787d83c
M
422 assert(s);
423
424 s->watchdog_override_enable = true;
425 s->watchdog_override_usec = watchdog_override_usec;
426 service_reset_watchdog(s);
427
428 log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
429 log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
430}
431
a02287ea 432static ServiceFDStore* service_fd_store_unlink(ServiceFDStore *fs) {
a354329f 433 if (!fs)
a02287ea 434 return NULL;
a354329f
LP
435
436 if (fs->service) {
437 assert(fs->service->n_fd_store > 0);
438 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
439 fs->service->n_fd_store--;
440 }
441
1d3fe304 442 sd_event_source_disable_unref(fs->event_source);
a354329f 443
8dd4c05b 444 free(fs->fdname);
99620f45 445 asynchronous_close(fs->fd);
a02287ea 446 return mfree(fs);
a354329f
LP
447}
448
a02287ea
YW
449DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore*, service_fd_store_unlink);
450
f0bfbfac
ZJS
451static void service_release_fd_store(Service *s) {
452 assert(s);
453
c25fac9a
LP
454 if (!s->fd_store)
455 return;
456
32af4dd8 457 log_unit_debug(UNIT(s), "Releasing all stored fds.");
c25fac9a 458
f0bfbfac
ZJS
459 while (s->fd_store)
460 service_fd_store_unlink(s->fd_store);
461
462 assert(s->n_fd_store == 0);
463}
464
3543456f
RW
465static void service_release_extra_fds(Service *s) {
466 assert(s);
467
32af4dd8
MY
468 if (!s->extra_fds)
469 return;
470
471 log_unit_debug(UNIT(s), "Releasing extra file descriptors.");
472
473 FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
474 asynchronous_close(i->fd);
475 free(i->fdname);
476 }
477
478 s->extra_fds = mfree(s->extra_fds);
479 s->n_extra_fds = 0;
3543456f
RW
480}
481
c25fac9a 482static void service_release_stdio_fd(Service *s) {
a354329f
LP
483 assert(s);
484
5bcf0881 485 if (s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
a354329f
LP
486 return;
487
c25fac9a 488 log_unit_debug(UNIT(s), "Releasing stdin/stdout/stderr file descriptors.");
a354329f 489
99620f45
LP
490 s->stdin_fd = asynchronous_close(s->stdin_fd);
491 s->stdout_fd = asynchronous_close(s->stdout_fd);
492 s->stderr_fd = asynchronous_close(s->stderr_fd);
a354329f 493}
81006ebb 494
87f0e418 495static void service_done(Unit *u) {
e9fa1bf7 496 Service *s = ASSERT_PTR(SERVICE(u));
44d8db9e 497
cd48e23f
RP
498 open_file_free_many(&s->open_files);
499
a1e58e8e
LP
500 s->pid_file = mfree(s->pid_file);
501 s->status_text = mfree(s->status_text);
9c025022
MY
502 s->status_bus_error = mfree(s->status_bus_error);
503 s->status_varlink_error = mfree(s->status_varlink_error);
efe6e7d3 504
28135da3 505 s->exec_runtime = exec_runtime_free(s->exec_runtime);
9cc54544 506
e537352b 507 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
44d8db9e 508 s->control_command = NULL;
867b3b7d 509 s->main_command = NULL;
44d8db9e 510
37520c1b
LP
511 exit_status_set_free(&s->restart_prevent_status);
512 exit_status_set_free(&s->restart_force_status);
513 exit_status_set_free(&s->success_status);
96342de6 514
c79ab77c 515 /* This will leak a process, but at least no memory or any of our resources */
5e94833f
LP
516 service_unwatch_main_pid(s);
517 service_unwatch_control_pid(s);
3e52541e 518 service_unwatch_pid_file(s);
44d8db9e 519
05e343b7 520 if (s->bus_name) {
ac155bb8 521 unit_unwatch_bus_name(u, s->bus_name);
a1e58e8e 522 s->bus_name = mfree(s->bus_name);
05e343b7
LP
523 }
524
064c5938
ZJS
525 s->usb_function_descriptors = mfree(s->usb_function_descriptors);
526 s->usb_function_strings = mfree(s->usb_function_strings);
527
bb242b7b
MO
528 service_stop_watchdog(s);
529
5dcadb4c
ZJS
530 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
531 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
a354329f 532
e39eb045
LP
533 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
534
81a1d6d6 535 service_release_socket_fd(s);
c25fac9a 536 service_release_stdio_fd(s);
81a1d6d6 537 service_release_fd_store(s);
3543456f 538 service_release_extra_fds(s);
5162829e
LB
539
540 s->mount_request = sd_bus_message_unref(s->mount_request);
718db961
LP
541}
542
2339fc93 543static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
99534007 544 ServiceFDStore *fs = ASSERT_PTR(userdata);
2339fc93
LP
545
546 assert(e);
2339fc93
LP
547
548 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
16f70d63
ZJS
549 log_unit_debug(UNIT(fs->service),
550 "Received %s on stored fd %d (%s), closing.",
551 revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
552 fs->fd, strna(fs->fdname));
2339fc93
LP
553 service_fd_store_unlink(fs);
554 return 0;
555}
556
a02287ea
YW
557static int service_add_fd_store(Service *s, int fd_in, const char *name, bool do_poll) {
558 _cleanup_(service_fd_store_unlinkp) ServiceFDStore *fs = NULL;
559 _cleanup_(asynchronous_closep) int fd = ASSERT_FD(fd_in);
e8783d76 560 struct stat st;
2339fc93
LP
561 int r;
562
a02287ea 563 /* fd is always consumed even if the function fails. */
9021ff17 564
2339fc93 565 assert(s);
2339fc93 566
e8783d76
LP
567 if (fstat(fd, &st) < 0)
568 return -errno;
569
0578371f
MY
570 log_unit_debug(UNIT(s), "Trying to stash fd for dev=" DEVNUM_FORMAT_STR "/inode=%" PRIu64,
571 DEVNUM_FORMAT_VAL(st.st_dev), (uint64_t) st.st_ino);
e8783d76 572
2339fc93 573 if (s->n_fd_store >= s->n_fd_store_max)
e8783d76
LP
574 /* Our store is full. Use this errno rather than E[NM]FILE to distinguish from the case
575 * where systemd itself hits the file limit. */
576 return log_unit_debug_errno(UNIT(s), SYNTHETIC_ERRNO(EXFULL), "Hit fd store limit.");
2339fc93 577
03677889
YW
578 LIST_FOREACH(fd_store, i, s->fd_store) {
579 r = same_fd(i->fd, fd);
2339fc93
LP
580 if (r < 0)
581 return r;
582 if (r > 0) {
a02287ea 583 log_unit_debug(UNIT(s), "Suppressing duplicate fd %i in fd store.", fd);
9021ff17 584 return 0; /* fd already included */
2339fc93
LP
585 }
586 }
587
b0cea477 588 fs = new(ServiceFDStore, 1);
2339fc93
LP
589 if (!fs)
590 return -ENOMEM;
591
b0cea477 592 *fs = (ServiceFDStore) {
a02287ea 593 .fd = TAKE_FD(fd),
b0cea477
LP
594 .do_poll = do_poll,
595 .fdname = strdup(name ?: "stored"),
596 };
597
a02287ea 598 if (!fs->fdname)
8dd4c05b 599 return -ENOMEM;
2339fc93 600
cb5a46b8 601 if (do_poll) {
a02287ea
YW
602 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fs->fd, 0, on_fd_store_io, fs);
603 if (r < 0 && r != -EPERM) /* EPERM indicates fds that aren't pollable, which is OK */
cb5a46b8 604 return r;
0578371f 605 if (r >= 0)
cb5a46b8
KL
606 (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
607 }
7dfbe2e3 608
0578371f
MY
609 log_unit_debug(UNIT(s), "Added fd %i (%s) to fd store.", fs->fd, fs->fdname);
610
a02287ea 611 fs->service = s;
0578371f 612 LIST_PREPEND(fd_store, s->fd_store, TAKE_PTR(fs));
2339fc93
LP
613 s->n_fd_store++;
614
9021ff17 615 return 1; /* fd newly stored */
2339fc93
LP
616}
617
cb5a46b8 618static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name, bool do_poll) {
2339fc93
LP
619 int r;
620
621 assert(s);
622
a02287ea
YW
623 for (;;) {
624 int fd;
2339fc93
LP
625
626 fd = fdset_steal_first(fds);
627 if (fd < 0)
628 break;
629
cb5a46b8 630 r = service_add_fd_store(s, fd, name, do_poll);
b0924635
ZJS
631 if (r == -EXFULL)
632 return log_unit_warning_errno(UNIT(s), r,
633 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
634 s->n_fd_store_max);
2339fc93 635 if (r < 0)
b0924635 636 return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
2339fc93
LP
637 }
638
2339fc93
LP
639 return 0;
640}
641
e78ee06d 642static void service_remove_fd_store(Service *s, const char *name) {
e78ee06d
LP
643 assert(s);
644 assert(name);
645
80a226b2 646 LIST_FOREACH(fd_store, fs, s->fd_store) {
e78ee06d
LP
647 if (!streq(fs->fdname, name))
648 continue;
649
650 log_unit_debug(UNIT(s), "Got explicit request to remove fd %i (%s), closing.", fs->fd, name);
651 service_fd_store_unlink(fs);
652 }
653}
654
ecea250d 655static usec_t service_running_timeout(Service *s) {
5918a933
AB
656 usec_t delta = 0;
657
658 assert(s);
659
660 if (s->runtime_rand_extra_usec != 0) {
661 delta = random_u64_range(s->runtime_rand_extra_usec);
662 log_unit_debug(UNIT(s), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta, USEC_PER_SEC));
663 }
664
665 return usec_add(usec_add(UNIT(s)->active_enter_timestamp.monotonic,
666 s->runtime_max_usec),
667 delta);
668}
669
e5d6dcce 670static int service_arm_timer(Service *s, bool relative, usec_t usec) {
718db961
LP
671 assert(s);
672
e9276800 673 return unit_arm_timer(UNIT(s), &s->timer_event_source, relative, usec, service_dispatch_timer);
44d8db9e
LP
674}
675
243b1432
LP
676static int service_verify(Service *s) {
677 assert(s);
e0cfed4c 678 assert(UNIT(s)->load_state == UNIT_LOADED);
243b1432 679
d85ff944
YW
680 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP] &&
681 UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
3f00d379
ZJS
682 /* FailureAction= only makes sense if one of the start or stop commands is specified.
683 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
684 * either a command or SuccessAction= are required. */
d85ff944 685 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
243b1432 686
d85ff944
YW
687 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START])
688 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
96fb8242 689
d85ff944
YW
690 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START] && UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
691 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.");
96fb8242 692
d85ff944
YW
693 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next)
694 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.");
6cf6bbc2 695
d67c51e3 696 if (s->type == SERVICE_ONESHOT && IN_SET(s->restart, SERVICE_RESTART_ALWAYS, SERVICE_RESTART_ON_SUCCESS))
d85ff944 697 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.");
37520c1b 698
596e4470
HC
699 if (s->type == SERVICE_ONESHOT && s->exit_type == SERVICE_EXIT_CGROUP)
700 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
701
d85ff944
YW
702 if (s->type == SERVICE_DBUS && !s->bus_name)
703 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.");
4d0e5dbd 704
2d8191f4 705 if (s->type == SERVICE_FORKING && exec_needs_pid_namespace(&s->exec_context, /* params= */ NULL))
406f1775
DDM
706 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service of Type=forking does not support PrivatePIDs=yes. Refusing.");
707
6b7e5923
PS
708 if (s->usb_function_descriptors && !s->usb_function_strings)
709 log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
710
711 if (!s->usb_function_descriptors && s->usb_function_strings)
712 log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
713
36c16a7c 714 if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
226a08f2 715 log_unit_warning(UNIT(s), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
36c16a7c 716
5918a933
AB
717 if (s->runtime_max_usec == USEC_INFINITY && s->runtime_rand_extra_usec != 0)
718 log_unit_warning(UNIT(s), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
719
757e469d
MY
720 if (s->type == SERVICE_SIMPLE && s->exec_command[SERVICE_EXEC_START_POST] && exec_context_has_credentials(&s->exec_context))
721 log_unit_warning(UNIT(s), "Service uses a combination of Type=simple, ExecStartPost=, and credentials. This could lead to race conditions. Continuing.");
722
e9f17fa8
MY
723 if (s->restart_max_delay_usec == USEC_INFINITY && s->restart_steps > 0)
724 log_unit_warning(UNIT(s), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
be1adc27 725
e9f17fa8
MY
726 if (s->restart_max_delay_usec != USEC_INFINITY && s->restart_steps == 0)
727 log_unit_warning(UNIT(s), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
be1adc27 728
e9f17fa8
MY
729 if (s->restart_max_delay_usec < s->restart_usec) {
730 log_unit_warning(UNIT(s), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
731 s->restart_usec = s->restart_max_delay_usec;
be1adc27
MY
732 }
733
243b1432
LP
734 return 0;
735}
736
a40eb732
LP
737static int service_add_default_dependencies(Service *s) {
738 int r;
739
740 assert(s);
741
45f06b34
LP
742 if (!UNIT(s)->default_dependencies)
743 return 0;
744
a40eb732
LP
745 /* Add a number of automatic dependencies useful for the
746 * majority of services. */
747
463d0d15 748 if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
3835b9aa
LB
749 /* First, pull in the really early boot stuff, and
750 * require it, so that we fail if we can't acquire
751 * it. */
752
753 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
cb4c247d
LP
754 if (r < 0)
755 return r;
756 } else {
757
758 /* In the --user instance there's no sysinit.target,
759 * in that case require basic.target instead. */
760
35d8c19a 761 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
cb4c247d
LP
762 if (r < 0)
763 return r;
764 }
765
766 /* Second, if the rest of the base system is in the same
767 * transaction, order us after it, but do not pull it in or
768 * even require it. */
35d8c19a 769 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
fccd44ec
KS
770 if (r < 0)
771 return r;
a40eb732 772
cb4c247d 773 /* Third, add us in for normal shutdown. */
3835b9aa 774 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
a40eb732
LP
775}
776
3b7f79dc 777static void service_fix_stdio(Service *s) {
4dfc092a
LP
778 assert(s);
779
3b7f79dc
LP
780 /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
781 * default value that is subject to automatic overriding triggered by other settings and an explicit
162392b7 782 * choice the user can make. We don't distinguish between these cases currently. */
3b7f79dc
LP
783
784 if (s->exec_context.std_input == EXEC_INPUT_NULL &&
785 s->exec_context.stdin_data_size > 0)
786 s->exec_context.std_input = EXEC_INPUT_DATA;
787
788 if (IN_SET(s->exec_context.std_input,
789 EXEC_INPUT_TTY,
790 EXEC_INPUT_TTY_FORCE,
791 EXEC_INPUT_TTY_FAIL,
792 EXEC_INPUT_SOCKET,
793 EXEC_INPUT_NAMED_FD))
794 return;
795
796 /* We assume these listed inputs refer to bidirectional streams, and hence duplicating them from
797 * stdin to stdout/stderr makes sense and hence leaving EXEC_OUTPUT_INHERIT in place makes sense,
798 * too. Outputs such as regular files or sealed data memfds otoh don't really make sense to be
799 * duplicated for both input and output at the same time (since they then would cause a feedback
800 * loop), hence override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting. */
4dfc092a
LP
801
802 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
3b7f79dc 803 s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
c9e120e0 804 s->exec_context.std_error = UNIT(s)->manager->defaults.std_error;
4dfc092a 805
3b7f79dc 806 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
c9e120e0 807 s->exec_context.std_output = UNIT(s)->manager->defaults.std_output;
4dfc092a
LP
808}
809
45f06b34
LP
810static int service_setup_bus_name(Service *s) {
811 int r;
812
813 assert(s);
814
0f97b7c3 815 /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
1e8b312e 816 if (!s->bus_name)
45f06b34
LP
817 return 0;
818
1e8b312e
LP
819 if (s->type == SERVICE_DBUS) {
820 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
821 if (r < 0)
2b2ca7ff 822 return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on %s: %m", SPECIAL_DBUS_SOCKET);
45f06b34 823
1e8b312e
LP
824 /* We always want to be ordered against dbus.socket if both are in the transaction. */
825 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
826 if (r < 0)
2b2ca7ff 827 return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on %s: %m", SPECIAL_DBUS_SOCKET);
1e8b312e 828 }
45f06b34
LP
829
830 r = unit_watch_bus_name(UNIT(s), s->bus_name);
831 if (r == -EEXIST)
832 return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
833 if (r < 0)
834 return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
835
836 return 0;
837}
838
8545f7ce
LP
839static int service_add_extras(Service *s) {
840 int r;
841
842 assert(s);
843
844 if (s->type == _SERVICE_TYPE_INVALID) {
845 /* Figure out a type automatically */
846 if (s->bus_name)
847 s->type = SERVICE_DBUS;
757e469d
MY
848 else if (exec_context_has_credentials(&s->exec_context))
849 s->type = SERVICE_EXEC;
8545f7ce
LP
850 else if (s->exec_command[SERVICE_EXEC_START])
851 s->type = SERVICE_SIMPLE;
852 else
853 s->type = SERVICE_ONESHOT;
854 }
855
856 /* Oneshot services have disabled start timeout by default */
857 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
36c16a7c 858 s->timeout_start_usec = USEC_INFINITY;
8545f7ce 859
3b7f79dc 860 service_fix_stdio(s);
8545f7ce
LP
861
862 r = unit_patch_contexts(UNIT(s));
863 if (r < 0)
864 return r;
865
866 r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
867 if (r < 0)
868 return r;
869
d79200e2 870 r = unit_set_default_slice(UNIT(s));
8545f7ce
LP
871 if (r < 0)
872 return r;
873
4330dc03
AJ
874 /* If the service needs the notify socket, let's enable it automatically. */
875 if (s->notify_access == NOTIFY_NONE &&
3bd28bf7 876 (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) || s->watchdog_usec > 0 || s->n_fd_store_max > 0))
8545f7ce
LP
877 s->notify_access = NOTIFY_MAIN;
878
afcfaa69
LP
879 /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
880 * delegation is on, in that case it we assume the payload knows better what to do and can process
5238e957 881 * things in a more focused way. */
afcfaa69 882 if (s->oom_policy < 0)
c9e120e0 883 s->oom_policy = s->cgroup_context.delegate ? OOM_CONTINUE : UNIT(s)->manager->defaults.oom_policy;
afcfaa69
LP
884
885 /* Let the kernel do the killing if that's requested. */
886 s->cgroup_context.memory_oom_group = s->oom_policy == OOM_KILL;
887
45f06b34
LP
888 r = service_add_default_dependencies(s);
889 if (r < 0)
890 return r;
8545f7ce 891
45f06b34
LP
892 r = service_setup_bus_name(s);
893 if (r < 0)
894 return r;
8545f7ce
LP
895
896 return 0;
897}
898
e537352b 899static int service_load(Unit *u) {
e9fa1bf7 900 Service *s = ASSERT_PTR(SERVICE(u));
8bb2d17d 901 int r;
e537352b 902
e0cfed4c 903 r = unit_load_fragment_and_dropin(u, true);
c2756a68 904 if (r < 0)
5cb5a6ff
LP
905 return r;
906
e0cfed4c
ZJS
907 if (u->load_state != UNIT_LOADED)
908 return 0;
034c6ed7 909
23a177ef 910 /* This is a new unit? Then let's add in some extras */
e0cfed4c
ZJS
911 r = service_add_extras(s);
912 if (r < 0)
913 return r;
8e274523 914
243b1432 915 return service_verify(s);
034c6ed7
LP
916}
917
3543456f
RW
918static int service_dump_fd(int fd, const char *fdname, const char *header, FILE *f, const char *prefix) {
919 _cleanup_free_ char *path = NULL;
920 struct stat st;
921 int flags;
922
32af4dd8
MY
923 assert(fd >= 0);
924 assert(fdname);
925 assert(header);
926 assert(f);
927 assert(prefix);
928
3543456f 929 if (fstat(fd, &st) < 0)
32af4dd8 930 return log_debug_errno(errno, "Failed to stat service fd: %m");
3543456f
RW
931
932 flags = fcntl(fd, F_GETFL);
933 if (flags < 0)
32af4dd8 934 return log_debug_errno(errno, "Failed to get service fd flags: %m");
3543456f
RW
935
936 (void) fd_get_path(fd, &path);
937
938 fprintf(f,
939 "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR "; inode=%" PRIu64 "; rdev=" DEVNUM_FORMAT_STR "; path=%s; access=%s)\n",
940 prefix,
941 header,
942 fdname,
943 strna(inode_type_to_string(st.st_mode)),
944 DEVNUM_FORMAT_VAL(st.st_dev),
945 (uint64_t) st.st_ino,
946 DEVNUM_FORMAT_VAL(st.st_rdev),
947 strna(path),
948 strna(accmode_to_string(flags)));
949
950 return 0;
951}
952
87f0e418 953static void service_dump(Unit *u, FILE *f, const char *prefix) {
e9fa1bf7 954 Service *s = ASSERT_PTR(SERVICE(u));
47be870b 955 const char *prefix2;
5cb5a6ff 956
4c940960 957 prefix = strempty(prefix);
63c372cb 958 prefix2 = strjoina(prefix, "\t");
44d8db9e 959
5cb5a6ff 960 fprintf(f,
81a2b7ce 961 "%sService State: %s\n"
f42806df
LP
962 "%sResult: %s\n"
963 "%sReload Result: %s\n"
4c2f5842 964 "%sClean Result: %s\n"
dc851222 965 "%sLiveMount Result: %s\n"
81a2b7ce 966 "%sPermissionsStartOnly: %s\n"
8e274523 967 "%sRootDirectoryStartOnly: %s\n"
02ee865a 968 "%sRemainAfterExit: %s\n"
3185a36b 969 "%sGuessMainPID: %s\n"
c952c6ec 970 "%sType: %s\n"
2cf3143a 971 "%sRestart: %s\n"
308d72dc 972 "%sNotifyAccess: %s\n"
afcfaa69 973 "%sNotifyState: %s\n"
3bd28bf7
LP
974 "%sOOMPolicy: %s\n"
975 "%sReloadSignal: %s\n",
81a2b7ce 976 prefix, service_state_to_string(s->state),
f42806df
LP
977 prefix, service_result_to_string(s->result),
978 prefix, service_result_to_string(s->reload_result),
5162829e 979 prefix, service_result_to_string(s->live_mount_result),
a53e92a1 980 prefix, service_result_to_string(s->clean_result),
81a2b7ce 981 prefix, yes_no(s->permissions_start_only),
8e274523 982 prefix, yes_no(s->root_directory_start_only),
02ee865a 983 prefix, yes_no(s->remain_after_exit),
3185a36b 984 prefix, yes_no(s->guess_main_pid),
c952c6ec 985 prefix, service_type_to_string(s->type),
2cf3143a 986 prefix, service_restart_to_string(s->restart),
19dff691 987 prefix, notify_access_to_string(service_get_notify_access(s)),
afcfaa69 988 prefix, notify_state_to_string(s->notify_state),
3bd28bf7
LP
989 prefix, oom_policy_to_string(s->oom_policy),
990 prefix, signal_to_string(s->reload_signal));
5cb5a6ff 991
c79ab77c 992 if (pidref_is_set(&s->control_pid))
70123e68 993 fprintf(f,
ccd06097 994 "%sControl PID: "PID_FMT"\n",
c79ab77c 995 prefix, s->control_pid.pid);
70123e68 996
c79ab77c 997 if (pidref_is_set(&s->main_pid))
70123e68 998 fprintf(f,
ccd06097 999 "%sMain PID: "PID_FMT"\n"
6dfa5494
LP
1000 "%sMain PID Known: %s\n"
1001 "%sMain PID Alien: %s\n",
c79ab77c 1002 prefix, s->main_pid.pid,
6dfa5494
LP
1003 prefix, yes_no(s->main_pid_known),
1004 prefix, yes_no(s->main_pid_alien));
70123e68 1005
034c6ed7
LP
1006 if (s->pid_file)
1007 fprintf(f,
1008 "%sPIDFile: %s\n",
1009 prefix, s->pid_file);
1010
05e343b7
LP
1011 if (s->bus_name)
1012 fprintf(f,
1013 "%sBusName: %s\n"
1014 "%sBus Name Good: %s\n",
1015 prefix, s->bus_name,
1016 prefix, yes_no(s->bus_name_good));
1017
9dfb64f8
ZJS
1018 if (UNIT_ISSET(s->accept_socket))
1019 fprintf(f,
1020 "%sAccept Socket: %s\n",
1021 prefix, UNIT_DEREF(s->accept_socket)->id);
1022
c9d41699
YW
1023 fprintf(f,
1024 "%sRestartSec: %s\n"
be1adc27 1025 "%sRestartSteps: %u\n"
e9f17fa8 1026 "%sRestartMaxDelaySec: %s\n"
c9d41699 1027 "%sTimeoutStartSec: %s\n"
bf760801
JK
1028 "%sTimeoutStopSec: %s\n"
1029 "%sTimeoutStartFailureMode: %s\n"
1030 "%sTimeoutStopFailureMode: %s\n",
5291f26d 1031 prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC),
be1adc27 1032 prefix, s->restart_steps,
e9f17fa8 1033 prefix, FORMAT_TIMESPAN(s->restart_max_delay_usec, USEC_PER_SEC),
5291f26d
ZJS
1034 prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC),
1035 prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC),
bf760801
JK
1036 prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode),
1037 prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode));
dcab85be
YW
1038
1039 if (s->timeout_abort_set)
1040 fprintf(f,
1041 "%sTimeoutAbortSec: %s\n",
5291f26d 1042 prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC));
dcab85be
YW
1043
1044 fprintf(f,
1045 "%sRuntimeMaxSec: %s\n"
5918a933 1046 "%sRuntimeRandomizedExtraSec: %s\n"
dcab85be 1047 "%sWatchdogSec: %s\n",
5291f26d 1048 prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC),
5918a933 1049 prefix, FORMAT_TIMESPAN(s->runtime_rand_extra_usec, USEC_PER_SEC),
5291f26d 1050 prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC));
c9d41699 1051
4819ff03 1052 kill_context_dump(&s->kill_context, f, prefix);
5cb5a6ff
LP
1053 exec_context_dump(&s->exec_context, f, prefix);
1054
68e58ca9 1055 for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
44d8db9e
LP
1056 if (!s->exec_command[c])
1057 continue;
1058
3a7bb5c9 1059 fprintf(f, "%s%s %s:\n",
1ae9b0cf 1060 prefix, glyph(GLYPH_ARROW_RIGHT), service_exec_command_to_string(c));
44d8db9e
LP
1061
1062 exec_command_dump_list(s->exec_command[c], f, prefix2);
5cb5a6ff 1063 }
44d8db9e 1064
8c47c732
LP
1065 if (s->status_text)
1066 fprintf(f, "%sStatus Text: %s\n",
1067 prefix, s->status_text);
a354329f 1068
a74b2840
MY
1069 if (s->status_errno > 0)
1070 fprintf(f, "%sStatus Errno: %s\n",
1071 prefix, STRERROR(s->status_errno));
1072
9c025022
MY
1073 if (s->status_bus_error)
1074 fprintf(f, "%sStatus Bus Error: %s\n",
1075 prefix, s->status_bus_error);
1076
1077 if (s->status_varlink_error)
1078 fprintf(f, "%sStatus Varlink Error: %s\n",
1079 prefix, s->status_varlink_error);
1080
32af4dd8 1081 if (s->n_fd_store_max > 0) {
a354329f
LP
1082 fprintf(f,
1083 "%sFile Descriptor Store Max: %u\n"
b9c1883a 1084 "%sFile Descriptor Store Pin: %s\n"
da6053d0 1085 "%sFile Descriptor Store Current: %zu\n",
a354329f 1086 prefix, s->n_fd_store_max,
b9c1883a 1087 prefix, exec_preserve_mode_to_string(s->fd_store_preserve_mode),
a354329f 1088 prefix, s->n_fd_store);
18f573aa 1089
32af4dd8
MY
1090 LIST_FOREACH(fd_store, i, s->fd_store)
1091 (void) service_dump_fd(i->fd,
1092 i->fdname,
1093 i == s->fd_store ? "File Descriptor Store Entry:" : " ",
1094 f,
1095 prefix);
1096 }
1097
1098 FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds)
1099 (void) service_dump_fd(i->fd,
1100 i->fdname,
1101 i == s->extra_fds ? "Extra File Descriptor Entry:" : " ",
1102 f,
1103 prefix);
f2eb0c50 1104
cd48e23f
RP
1105 if (s->open_files)
1106 LIST_FOREACH(open_files, of, s->open_files) {
1107 _cleanup_free_ char *ofs = NULL;
1108 int r;
1109
1110 r = open_file_to_string(of, &ofs);
1111 if (r < 0) {
1112 log_debug_errno(r,
1113 "Failed to convert OpenFile= setting to string, ignoring: %m");
1114 continue;
1115 }
1116
1117 fprintf(f, "%sOpen File: %s\n", prefix, ofs);
1118 }
1119
bc0623df 1120 cgroup_context_dump(UNIT(s), f, prefix);
5cb5a6ff
LP
1121}
1122
495e75ed 1123static int service_is_suitable_main_pid(Service *s, PidRef *pid, int prio) {
db256aab 1124 Unit *owner;
becdfcb9 1125 int r;
db256aab
LP
1126
1127 assert(s);
495e75ed 1128 assert(pidref_is_set(pid));
db256aab
LP
1129
1130 /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
1131 * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
1132 * good */
1133
a7a87769 1134 if (pidref_is_self(pid) || pid->pid == 1)
495e75ed 1135 return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the manager, refusing.", pid->pid);
db256aab 1136
495e75ed
LP
1137 if (pidref_equal(pid, &s->control_pid))
1138 return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the control process, refusing.", pid->pid);
db256aab 1139
becdfcb9 1140 r = pidref_is_alive(pid);
bca08053
MY
1141 if (r < 0)
1142 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);
becdfcb9 1143 if (r == 0)
495e75ed 1144 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);
db256aab 1145
495e75ed 1146 owner = manager_get_unit_by_pidref(UNIT(s)->manager, pid);
db256aab 1147 if (owner == UNIT(s)) {
495e75ed 1148 log_unit_debug(UNIT(s), "New main PID "PID_FMT" belongs to service, we are happy.", pid->pid);
db256aab
LP
1149 return 1; /* Yay, it's definitely a good PID */
1150 }
1151
1152 return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
1153}
1154
c5419d42 1155static int service_load_pid_file(Service *s, bool may_warn) {
b1f6901d 1156 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
7e6ef434 1157 _cleanup_fclose_ FILE *f = NULL;
7fd1b19b 1158 _cleanup_free_ char *k = NULL;
7e6ef434
MY
1159 bool questionable_pid_file = false;
1160 int r, prio = may_warn ? LOG_INFO : LOG_DEBUG;
034c6ed7
LP
1161
1162 assert(s);
1163
034c6ed7 1164 if (!s->pid_file)
13230d5d 1165 return -ENOENT;
034c6ed7 1166
7e6ef434 1167 r = chase_and_fopen_unlocked(s->pid_file, NULL, CHASE_SAFE, "re", NULL, &f);
a5648b80 1168 if (r == -ENOLINK) {
8ed6f81b
YW
1169 log_unit_debug_errno(UNIT(s), r,
1170 "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s->pid_file);
73969ab6
LP
1171
1172 questionable_pid_file = true;
1173
7e6ef434 1174 r = chase_and_fopen_unlocked(s->pid_file, NULL, 0, "re", NULL, &f);
73969ab6 1175 }
a5648b80 1176 if (r < 0)
f86a388d 1177 return log_unit_full_errno(UNIT(s), prio, r,
7e6ef434 1178 "Can't open PID file '%s' (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
db256aab 1179
7e6ef434
MY
1180 /* Let's read the PID file now that we chased it down. */
1181 r = read_line(f, LINE_MAX, &k);
db256aab 1182 if (r < 0)
7e6ef434 1183 return log_unit_error_errno(UNIT(s), r, "Failed to read PID file '%s': %m", s->pid_file);
034c6ed7 1184
495e75ed 1185 r = pidref_set_pidstr(&pidref, k);
db256aab 1186 if (r < 0)
7e6ef434 1187 return log_unit_full_errno(UNIT(s), prio, r, "Failed to create reference to PID %s from file '%s': %m", k, s->pid_file);
db256aab 1188
495e75ed 1189 if (s->main_pid_known && pidref_equal(&pidref, &s->main_pid))
db256aab
LP
1190 return 0;
1191
495e75ed 1192 r = service_is_suitable_main_pid(s, &pidref, prio);
db256aab 1193 if (r < 0)
5925dd3c 1194 return r;
db256aab
LP
1195 if (r == 0) {
1196 struct stat st;
406eaf93 1197
d85ff944
YW
1198 if (questionable_pid_file)
1199 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
1200 "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s->pid_file);
73969ab6 1201
db256aab
LP
1202 /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
1203
7e6ef434
MY
1204 if (fstat(fileno(f), &st) < 0)
1205 return log_unit_error_errno(UNIT(s), errno, "Failed to fstat() PID file '%s': %m", s->pid_file);
db256aab 1206
d85ff944
YW
1207 if (st.st_uid != 0)
1208 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
7e6ef434 1209 "New main PID "PID_FMT" from PID file does not belong to service, and PID file is not owned by root. Refusing.", pidref.pid);
db256aab 1210
7e6ef434 1211 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);
e10c9985
YS
1212 }
1213
db01f8b3 1214 if (s->main_pid_known) {
b1f6901d 1215 log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid.pid, pidref.pid);
8bb2d17d 1216
db01f8b3
MS
1217 service_unwatch_main_pid(s);
1218 s->main_pid_known = false;
3a111838 1219 } else
b1f6901d 1220 log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pidref.pid);
db01f8b3 1221
7e0e6b50 1222 r = service_set_main_pidref(s, TAKE_PIDREF(pidref), /* start_timestamp = */ NULL);
117dcc57 1223 if (r < 0)
16f6025e
LP
1224 return r;
1225
495e75ed 1226 r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
e8b509d3 1227 if (r < 0) /* FIXME: we need to do something here */
b1f6901d 1228 return log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", s->main_pid.pid);
034c6ed7 1229
db256aab 1230 return 1;
034c6ed7
LP
1231}
1232
783e05d6 1233static void service_search_main_pid(Service *s) {
495e75ed 1234 _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
4fbf50b3
LP
1235 int r;
1236
1237 assert(s);
1238
c79ab77c 1239 /* If we know it anyway, don't ever fall back to unreliable heuristics */
4fbf50b3 1240 if (s->main_pid_known)
783e05d6 1241 return;
4fbf50b3 1242
3185a36b 1243 if (!s->guess_main_pid)
783e05d6 1244 return;
3185a36b 1245
c79ab77c 1246 assert(!pidref_is_set(&s->main_pid));
4fbf50b3 1247
783e05d6
ZJS
1248 if (unit_search_main_pid(UNIT(s), &pid) < 0)
1249 return;
4fbf50b3 1250
495e75ed 1251 log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid.pid);
7e0e6b50 1252 if (service_set_main_pidref(s, TAKE_PIDREF(pid), /* start_timestamp = */ NULL) < 0)
783e05d6 1253 return;
4fbf50b3 1254
495e75ed 1255 r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
783e05d6 1256 if (r < 0)
4fbf50b3 1257 /* FIXME: we need to do something here */
f5b0e4f9 1258 log_unit_warning_errno(UNIT(s), r, "Failed to watch main PID "PID_FMT": %m", s->main_pid.pid);
4fbf50b3
LP
1259}
1260
034c6ed7 1261static void service_set_state(Service *s, ServiceState state) {
c26948c6 1262 Unit *u = UNIT(ASSERT_PTR(s));
034c6ed7 1263 ServiceState old_state;
e056b01d 1264 const UnitActiveState *table;
842129f5 1265
6fcbec6f 1266 if (s->state != state)
c26948c6 1267 bus_unit_send_pending_change_signal(u, false);
6fcbec6f 1268
e056b01d
LP
1269 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1270
034c6ed7 1271 old_state = s->state;
5cb5a6ff 1272 s->state = state;
034c6ed7 1273
3a111838
MS
1274 service_unwatch_pid_file(s);
1275
842129f5 1276 if (!IN_SET(state,
31cd5f63 1277 SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
36c16a7c 1278 SERVICE_RUNNING,
dfdeb0b1 1279 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS,
a53e92a1 1280 SERVICE_MOUNTING,
c87700a1 1281 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
bf760801 1282 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
4c2f5842
LP
1283 SERVICE_AUTO_RESTART,
1284 SERVICE_CLEANING))
5dcadb4c 1285 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
034c6ed7 1286
94114711 1287 if (!SERVICE_STATE_WITH_MAIN_PROCESS(state)) {
5e94833f 1288 service_unwatch_main_pid(s);
867b3b7d
LP
1289 s->main_command = NULL;
1290 }
034c6ed7 1291
94114711 1292 if (!SERVICE_STATE_WITH_CONTROL_PROCESS(state)) {
5e94833f 1293 service_unwatch_control_pid(s);
034c6ed7 1294 s->control_command = NULL;
a16e1123 1295 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
e537352b 1296 }
034c6ed7 1297
a1d31573
LP
1298 if (IN_SET(state,
1299 SERVICE_DEAD, SERVICE_FAILED,
09d04ad3 1300 SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
55e4df21 1301 SERVICE_DEAD_RESOURCES_PINNED))
c26948c6 1302 unit_unwatch_all_pids(u);
a911bb9a 1303
5686391b 1304 if (state != SERVICE_START)
5dcadb4c 1305 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b 1306
dfdeb0b1 1307 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS, SERVICE_MOUNTING))
a6927d7f
MO
1308 service_stop_watchdog(s);
1309
a53e92a1
MY
1310 if (state != SERVICE_MOUNTING) /* Just in case */
1311 s->mount_request = sd_bus_message_unref(s->mount_request);
1312
c26948c6
MY
1313 if (state == SERVICE_EXITED && !MANAGER_IS_RELOADING(u->manager)) {
1314 /* For the inactive states unit_notify() will trim the cgroup. But for exit we have to
1315 * do that ourselves... */
1316 unit_prune_cgroup(u);
1317
1318 /* If none of ExecReload= and ExecStop*= is used, we can safely destroy runtime data
1319 * as soon as the service enters SERVICE_EXITED. This saves us from keeping the credential mount
1320 * for the whole duration of the oneshot service while no processes are actually running,
1321 * among other things. */
1322
1323 bool start_only = true;
1324 for (ServiceExecCommand c = SERVICE_EXEC_RELOAD; c < _SERVICE_EXEC_COMMAND_MAX; c++)
1325 if (s->exec_command[c]) {
1326 start_only = false;
1327 break;
1328 }
1329
1330 if (start_only)
703b1b7f 1331 unit_destroy_runtime_data(u, &s->exec_context, /* destroy_runtime_dir = */ false);
c26948c6 1332 }
f6023656 1333
e537352b 1334 if (old_state != state)
c26948c6 1335 log_unit_debug(u, "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
acbb0225 1336
c26948c6 1337 unit_notify(u, table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
034c6ed7
LP
1338}
1339
36c16a7c
LP
1340static usec_t service_coldplug_timeout(Service *s) {
1341 assert(s);
1342
1343 switch (s->deserialized_state) {
1344
31cd5f63 1345 case SERVICE_CONDITION:
36c16a7c
LP
1346 case SERVICE_START_PRE:
1347 case SERVICE_START:
1348 case SERVICE_START_POST:
1349 case SERVICE_RELOAD:
3bd28bf7
LP
1350 case SERVICE_RELOAD_SIGNAL:
1351 case SERVICE_RELOAD_NOTIFY:
dfdeb0b1 1352 case SERVICE_REFRESH_EXTENSIONS:
a53e92a1 1353 case SERVICE_MOUNTING:
36c16a7c
LP
1354 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
1355
1356 case SERVICE_RUNNING:
5918a933 1357 return service_running_timeout(s);
36c16a7c
LP
1358
1359 case SERVICE_STOP:
36c16a7c
LP
1360 case SERVICE_STOP_SIGTERM:
1361 case SERVICE_STOP_SIGKILL:
1362 case SERVICE_STOP_POST:
1363 case SERVICE_FINAL_SIGTERM:
1364 case SERVICE_FINAL_SIGKILL:
1365 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
1366
dc653bf4 1367 case SERVICE_STOP_WATCHDOG:
bf760801 1368 case SERVICE_FINAL_WATCHDOG:
dc653bf4
JK
1369 return usec_add(UNIT(s)->state_change_timestamp.monotonic, service_timeout_abort_usec(s));
1370
36c16a7c 1371 case SERVICE_AUTO_RESTART:
5171356e 1372 return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic, service_restart_usec_next(s));
36c16a7c 1373
4c2f5842 1374 case SERVICE_CLEANING:
12213aed 1375 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->exec_context.timeout_clean_usec);
4c2f5842 1376
36c16a7c
LP
1377 default:
1378 return USEC_INFINITY;
1379 }
1380}
1381
be847e82 1382static int service_coldplug(Unit *u) {
a16e1123
LP
1383 Service *s = SERVICE(u);
1384 int r;
1385
1386 assert(s);
1387 assert(s->state == SERVICE_DEAD);
1388
930d2838
LP
1389 if (s->deserialized_state == s->state)
1390 return 0;
6c12b52e 1391
e5d6dcce 1392 r = service_arm_timer(s, /* relative= */ false, service_coldplug_timeout(s));
36c16a7c
LP
1393 if (r < 0)
1394 return r;
a911bb9a 1395
c79ab77c 1396 if (pidref_is_set(&s->main_pid) &&
4d9f092b 1397 pidref_is_unwaited(&s->main_pid) > 0 &&
94114711 1398 SERVICE_STATE_WITH_MAIN_PROCESS(s->deserialized_state)) {
495e75ed 1399 r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
930d2838
LP
1400 if (r < 0)
1401 return r;
1402 }
bb242b7b 1403
c79ab77c 1404 if (pidref_is_set(&s->control_pid) &&
4d9f092b 1405 pidref_is_unwaited(&s->control_pid) > 0 &&
94114711 1406 SERVICE_STATE_WITH_CONTROL_PROCESS(s->deserialized_state)) {
495e75ed 1407 r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
930d2838
LP
1408 if (r < 0)
1409 return r;
a16e1123 1410 }
92c1622e 1411
a1d31573
LP
1412 if (!IN_SET(s->deserialized_state,
1413 SERVICE_DEAD, SERVICE_FAILED,
09d04ad3 1414 SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
b9c1883a 1415 SERVICE_CLEANING,
55e4df21 1416 SERVICE_DEAD_RESOURCES_PINNED))
e8a565cb 1417 (void) unit_setup_exec_runtime(u);
29206d46 1418
dfdeb0b1 1419 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS, SERVICE_MOUNTING))
50be4f4a
LP
1420 service_start_watchdog(s);
1421
3ebcd323 1422 if (UNIT_ISSET(s->accept_socket)) {
9f5d8c3d 1423 Socket *socket = SOCKET(UNIT_DEREF(s->accept_socket));
3ebcd323
ZJS
1424
1425 if (socket->max_connections_per_source > 0) {
1426 SocketPeer *peer;
1427
1428 /* Make a best-effort attempt at bumping the connection count */
1429 if (socket_acquire_peer(socket, s->socket_fd, &peer) > 0) {
3fabebf4
LP
1430 socket_peer_unref(s->socket_peer);
1431 s->socket_peer = peer;
3ebcd323
ZJS
1432 }
1433 }
1434 }
1435
930d2838 1436 service_set_state(s, s->deserialized_state);
a16e1123
LP
1437 return 0;
1438}
1439
25b583d7
LP
1440static int service_collect_fds(
1441 Service *s,
1442 int **fds,
1443 char ***fd_names,
1444 size_t *n_socket_fds,
3543456f
RW
1445 size_t *n_storage_fds,
1446 size_t *n_extra_fds) {
4c47affc 1447
8dd4c05b 1448 _cleanup_strv_free_ char **rfd_names = NULL;
a354329f 1449 _cleanup_free_ int *rfds = NULL;
32af4dd8 1450 size_t rn_socket_fds = 0;
4c47affc 1451 int r;
44d8db9e
LP
1452
1453 assert(s);
1454 assert(fds);
8dd4c05b 1455 assert(fd_names);
9b141911 1456 assert(n_socket_fds);
25b583d7 1457 assert(n_storage_fds);
3543456f 1458 assert(n_extra_fds);
44d8db9e 1459
8dd4c05b 1460 if (s->socket_fd >= 0) {
daa78907 1461 Socket *sock = ASSERT_PTR(SOCKET(UNIT_DEREF(s->accept_socket)));
6cf6bbc2 1462
8dd4c05b 1463 /* Pass the per-connection socket */
57020a3a 1464
aa7c4dd6 1465 rfds = newdup(int, &s->socket_fd, 1);
8dd4c05b
LP
1466 if (!rfds)
1467 return -ENOMEM;
57020a3a 1468
daa78907 1469 rfd_names = strv_new(socket_fdname(sock));
8dd4c05b
LP
1470 if (!rfd_names)
1471 return -ENOMEM;
44d8db9e 1472
4c47affc 1473 rn_socket_fds = 1;
8dd4c05b 1474 } else {
8dd4c05b 1475 /* Pass all our configured sockets for singleton services */
44d8db9e 1476
0ec3d45b 1477 Unit *u;
15ed3c3a 1478 UNIT_FOREACH_DEPENDENCY(u, UNIT(s), UNIT_ATOM_TRIGGERED_BY) {
8dd4c05b 1479 _cleanup_free_ int *cfds = NULL;
8dd4c05b 1480 int cn_fds;
8d83e0c2 1481 Socket *sock;
44d8db9e 1482
8dd4c05b 1483 sock = SOCKET(u);
469ff6b4
MY
1484 if (!sock)
1485 continue;
a354329f 1486
8dd4c05b
LP
1487 cn_fds = socket_collect_fds(sock, &cfds);
1488 if (cn_fds < 0)
1489 return cn_fds;
0ec3d45b 1490 if (cn_fds == 0)
8dd4c05b 1491 continue;
79c7626d 1492
8dd4c05b 1493 if (!rfds) {
1cc6c93a 1494 rfds = TAKE_PTR(cfds);
4c47affc 1495 rn_socket_fds = cn_fds;
8d83e0c2
MY
1496 } else if (!GREEDY_REALLOC_APPEND(rfds, rn_socket_fds, cfds, cn_fds))
1497 return -ENOMEM;
8dd4c05b
LP
1498
1499 r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1500 if (r < 0)
1501 return r;
44d8db9e
LP
1502 }
1503 }
1504
32af4dd8
MY
1505 if (s->n_fd_store + s->n_extra_fds > 0) {
1506 int *t = reallocarray(rfds, rn_socket_fds + s->n_fd_store + s->n_extra_fds, sizeof(int));
a354329f
LP
1507 if (!t)
1508 return -ENOMEM;
a354329f 1509 rfds = t;
8dd4c05b 1510
32af4dd8 1511 char **nl = reallocarray(rfd_names, rn_socket_fds + s->n_fd_store + s->n_extra_fds + 1, sizeof(char *));
8dd4c05b
LP
1512 if (!nl)
1513 return -ENOMEM;
8dd4c05b 1514 rfd_names = nl;
32af4dd8
MY
1515
1516 size_t n_fds = rn_socket_fds;
8dd4c05b
LP
1517
1518 LIST_FOREACH(fd_store, fs, s->fd_store) {
4c47affc 1519 rfds[n_fds] = fs->fd;
32af4dd8 1520 rfd_names[n_fds] = strdup(fs->fdname);
4c47affc 1521 if (!rfd_names[n_fds])
8dd4c05b
LP
1522 return -ENOMEM;
1523
4c47affc 1524 n_fds++;
8dd4c05b
LP
1525 }
1526
32af4dd8
MY
1527 FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
1528 rfds[n_fds] = i->fd;
1529 rfd_names[n_fds] = strdup(i->fdname);
3543456f
RW
1530 if (!rfd_names[n_fds])
1531 return -ENOMEM;
1532
1533 n_fds++;
1534 }
1535
1536 rfd_names[n_fds] = NULL;
1537 }
1538
1cc6c93a
YW
1539 *fds = TAKE_PTR(rfds);
1540 *fd_names = TAKE_PTR(rfd_names);
9b141911 1541 *n_socket_fds = rn_socket_fds;
32af4dd8
MY
1542 *n_storage_fds = s->n_fd_store;
1543 *n_extra_fds = s->n_extra_fds;
3e33402a 1544
4c47affc 1545 return 0;
44d8db9e
LP
1546}
1547
5686391b
LP
1548static int service_allocate_exec_fd_event_source(
1549 Service *s,
1550 int fd,
1551 sd_event_source **ret_event_source) {
1552
1553 _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
1554 int r;
1555
1556 assert(s);
1557 assert(fd >= 0);
1558 assert(ret_event_source);
1559
1560 r = sd_event_add_io(UNIT(s)->manager->event, &source, fd, 0, service_dispatch_exec_io, s);
1561 if (r < 0)
1562 return log_unit_error_errno(UNIT(s), r, "Failed to allocate exec_fd event source: %m");
1563
f3a269a9
LP
1564 /* This is a bit higher priority than SIGCHLD, to make sure we don't confuse the case "failed to
1565 * start" from the case "succeeded to start, but failed immediately after". */
5686391b 1566
d42b61d2 1567 r = sd_event_source_set_priority(source, EVENT_PRIORITY_EXEC_FD);
5686391b
LP
1568 if (r < 0)
1569 return log_unit_error_errno(UNIT(s), r, "Failed to adjust priority of exec_fd event source: %m");
1570
bc989831 1571 (void) sd_event_source_set_description(source, "service exec_fd");
5686391b
LP
1572
1573 r = sd_event_source_set_io_fd_own(source, true);
1574 if (r < 0)
1575 return log_unit_error_errno(UNIT(s), r, "Failed to pass ownership of fd to event source: %m");
1576
1577 *ret_event_source = TAKE_PTR(source);
1578 return 0;
1579}
1580
1581static int service_allocate_exec_fd(
1582 Service *s,
1583 sd_event_source **ret_event_source,
e78695d4 1584 int *ret_exec_fd) {
5686391b 1585
71136404 1586 _cleanup_close_pair_ int p[] = EBADF_PAIR;
5686391b
LP
1587 int r;
1588
1589 assert(s);
1590 assert(ret_event_source);
1591 assert(ret_exec_fd);
1592
1593 if (pipe2(p, O_CLOEXEC|O_NONBLOCK) < 0)
1594 return log_unit_error_errno(UNIT(s), errno, "Failed to allocate exec_fd pipe: %m");
1595
1596 r = service_allocate_exec_fd_event_source(s, p[0], ret_event_source);
1597 if (r < 0)
1598 return r;
1599
e78695d4 1600 TAKE_FD(p[0]);
5686391b
LP
1601 *ret_exec_fd = TAKE_FD(p[1]);
1602
1603 return 0;
1604}
1605
6375bd20
JW
1606static bool service_exec_needs_notify_socket(Service *s, ExecFlags flags) {
1607 assert(s);
1608
1609 /* Notifications are accepted depending on the process and
1610 * the access setting of the service:
1611 * process: \ access: NONE MAIN EXEC ALL
1612 * main no yes yes yes
1613 * control no no yes yes
1614 * other (forked) no no no yes */
1615
1616 if (flags & EXEC_IS_CONTROL)
1617 /* A control process */
19dff691 1618 return IN_SET(service_get_notify_access(s), NOTIFY_EXEC, NOTIFY_ALL);
6375bd20
JW
1619
1620 /* We only spawn main processes and control processes, so any
1621 * process that is not a control process is a main process */
19dff691 1622 return service_get_notify_access(s) != NOTIFY_NONE;
6375bd20
JW
1623}
1624
95c81c55
LB
1625static Service *service_get_triggering_service(Service *s) {
1626 Unit *candidate = NULL, *other;
cdebedb4 1627
95c81c55 1628 assert(s);
cdebedb4 1629
95c81c55
LB
1630 /* Return the service which triggered service 's', this means dependency
1631 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
cdebedb4 1632 *
95c81c55
LB
1633 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1634 * or OnSuccess= then we return NULL. This is since we don't know from which
1635 * one to propagate the exit status. */
1636
e76d83d1 1637 UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_SUCCESS_OF|UNIT_ATOM_ON_FAILURE_OF) {
7a5049c7
ZJS
1638 if (candidate)
1639 goto have_other;
95c81c55 1640 candidate = other;
cdebedb4
PM
1641 }
1642
95c81c55 1643 return SERVICE(candidate);
7a5049c7
ZJS
1644
1645 have_other:
1646 log_unit_warning(UNIT(s), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1647 candidate->id, other->id);
1648 return NULL;
cdebedb4
PM
1649}
1650
cfbf7538 1651static ExecFlags service_exec_flags(ServiceExecCommand command_id, ExecFlags cred_flag) {
81006ebb
MY
1652 /* All service main/control processes honor sandboxing and namespacing options (except those
1653 explicitly excluded in service_spawn()) */
1654 ExecFlags flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT;
1655
1656 assert(command_id >= 0);
1657 assert(command_id < _SERVICE_EXEC_COMMAND_MAX);
cfbf7538
MY
1658 assert((cred_flag & ~(EXEC_SETUP_CREDENTIALS_FRESH|EXEC_SETUP_CREDENTIALS)) == 0);
1659 assert((cred_flag != 0) == (command_id == SERVICE_EXEC_START));
81006ebb
MY
1660
1661 /* Control processes spawned before main process also get tty access */
fe760177 1662 if (IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
81006ebb
MY
1663 flags |= EXEC_APPLY_TTY_STDIN;
1664
cfbf7538
MY
1665 /* All start phases get access to credentials. ExecStartPre= gets a new credential store upon
1666 * every invocation, so that updating credential files through it works. When the first main process
1667 * starts, passed creds become stable. Also see 'cred_flag'. */
1668 if (command_id == SERVICE_EXEC_START_PRE)
1669 flags |= EXEC_SETUP_CREDENTIALS_FRESH;
1670 if (command_id == SERVICE_EXEC_START_POST)
1221ba0f 1671 flags |= EXEC_SETUP_CREDENTIALS;
81006ebb
MY
1672
1673 if (IN_SET(command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
1674 flags |= EXEC_SETENV_MONITOR_RESULT;
1675
1676 if (command_id == SERVICE_EXEC_START)
cfbf7538 1677 return flags|cred_flag|EXEC_PASS_FDS|EXEC_SET_WATCHDOG;
81006ebb
MY
1678
1679 flags |= EXEC_IS_CONTROL;
1680
1681 /* Put control processes spawned later than main process under .control sub-cgroup if appropriate */
1682 if (!IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE))
1683 flags |= EXEC_CONTROL_CGROUP;
1684
1685 if (IN_SET(command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
1686 flags |= EXEC_SETENV_RESULT;
1687
1688 return flags;
1689}
1690
edbf8984
ZJS
1691static int service_spawn_internal(
1692 const char *caller,
81a2b7ce
LP
1693 Service *s,
1694 ExecCommand *c,
cfbf7538 1695 ExecFlags flags,
21b2ce39 1696 usec_t timeout,
c79ab77c 1697 PidRef *ret_pid) {
81a2b7ce 1698
cfbf7538 1699 _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(flags);
5686391b 1700 _cleanup_(sd_event_source_unrefp) sd_event_source *exec_fd_source = NULL;
c3f8a065 1701 _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL;
c79ab77c 1702 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
c3f8a065 1703 size_t n_env = 0;
8dd4c05b
LP
1704 int r;
1705
edbf8984 1706 assert(caller);
034c6ed7
LP
1707 assert(s);
1708 assert(c);
e78695d4 1709 assert(ret_pid);
034c6ed7 1710
edbf8984
ZJS
1711 log_unit_debug(UNIT(s), "Will spawn child (%s): %s", caller, c->path);
1712
78f93209 1713 r = unit_prepare_exec(UNIT(s)); /* This realizes the cgroup, among other things */
3c7416b6
LP
1714 if (r < 0)
1715 return r;
1716
bc989831
ZJS
1717 assert(!s->exec_fd_event_source);
1718
81006ebb 1719 if (FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL)) {
9c1a61ad
LP
1720 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1721 if (s->permissions_start_only)
1703fa41 1722 exec_params.flags &= ~EXEC_APPLY_SANDBOXING;
9c1a61ad
LP
1723 if (s->root_directory_start_only)
1724 exec_params.flags &= ~EXEC_APPLY_CHROOT;
1725 }
1726
81006ebb 1727 if (FLAGS_SET(exec_params.flags, EXEC_PASS_FDS) ||
6cf6bbc2
LP
1728 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1729 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1730 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1731
c3f8a065
LP
1732 r = service_collect_fds(s,
1733 &exec_params.fds,
1734 &exec_params.fd_names,
1735 &exec_params.n_socket_fds,
3543456f
RW
1736 &exec_params.n_storage_fds,
1737 &exec_params.n_extra_fds);
8dd4c05b 1738 if (r < 0)
36c16a7c 1739 return r;
6cf6bbc2 1740
cd48e23f
RP
1741 exec_params.open_files = s->open_files;
1742
07ff03d6
MY
1743 exec_params.flags |= EXEC_PASS_FDS;
1744
3543456f 1745 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);
4f2d528d 1746 }
44d8db9e 1747
12001b1b 1748 if (!FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL) && s->type == SERVICE_EXEC) {
c3f8a065 1749 r = service_allocate_exec_fd(s, &exec_fd_source, &exec_params.exec_fd);
5686391b
LP
1750 if (r < 0)
1751 return r;
1752 }
1753
e5d6dcce 1754 r = service_arm_timer(s, /* relative= */ true, timeout);
36c16a7c
LP
1755 if (r < 0)
1756 return r;
034c6ed7 1757
bfb1f9e2 1758 our_env = new0(char*, 16);
36c16a7c
LP
1759 if (!our_env)
1760 return -ENOMEM;
c952c6ec 1761
81006ebb 1762 if (service_exec_needs_notify_socket(s, exec_params.flags)) {
3bdc25a4 1763 exec_params.notify_socket = UNIT(s)->manager->notify_socket;
75b29fda
LP
1764
1765 if (s->n_fd_store_max > 0)
1766 if (asprintf(our_env + n_env++, "FDSTORE=%u", s->n_fd_store_max) < 0)
1767 return -ENOMEM;
3bdc25a4
LP
1768 }
1769
7933e971 1770 if (pidref_is_set(&s->main_pid)) {
c79ab77c 1771 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid.pid) < 0)
36c16a7c 1772 return -ENOMEM;
2105e76a 1773
7933e971
LP
1774 if (pidref_acquire_pidfd_id(&s->main_pid) >= 0)
1775 if (asprintf(our_env + n_env++, "MAINPIDFDID=%" PRIu64, s->main_pid.fd_id) < 0)
1776 return -ENOMEM;
1777 }
1778
1779 if (MANAGER_IS_USER(UNIT(s)->manager)) {
df0ff127 1780 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid_cached()) < 0)
36c16a7c 1781 return -ENOMEM;
97ae63e2 1782
7933e971
LP
1783 uint64_t pidfdid;
1784 if (pidfd_get_inode_id_self_cached(&pidfdid) >= 0)
1785 if (asprintf(our_env + n_env++, "MANAGERPIDFDID=%" PRIu64, pidfdid) < 0)
1786 return -ENOMEM;
1787 }
1788
dcf3c3c3
LP
1789 if (s->pid_file)
1790 if (asprintf(our_env + n_env++, "PIDFILE=%s", s->pid_file) < 0)
1791 return -ENOMEM;
1792
8dd4c05b 1793 if (s->socket_fd >= 0) {
3b1c5241
SL
1794 union sockaddr_union sa;
1795 socklen_t salen = sizeof(sa);
1796
f56e7bfe
LP
1797 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1798 * useful. Note that we do this only when we are still connected at this point in time, which we might
1799 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1800 * in ENOTCONN), and just use whate we can use. */
f2dbd059 1801
f56e7bfe 1802 if (getpeername(s->socket_fd, &sa.sa, &salen) >= 0 &&
608bfe76 1803 IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK, AF_UNIX)) {
3b1c5241
SL
1804 _cleanup_free_ char *addr = NULL;
1805 char *t;
3b1c5241 1806
608bfe76 1807 r = sockaddr_pretty(&sa.sa, salen, /* translate_ipv6= */ true, /* include_port= */ false, &addr);
3b1c5241 1808 if (r < 0)
36c16a7c 1809 return r;
3b1c5241 1810
608bfe76
KS
1811 if (sa.sa.sa_family != AF_UNIX || IN_SET(addr[0], '/', '@')) {
1812 t = strjoin("REMOTE_ADDR=", addr);
1813 if (!t)
1814 return -ENOMEM;
1815 our_env[n_env++] = t;
1816 }
3b1c5241 1817
608bfe76
KS
1818 if (IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
1819 unsigned port;
3b1c5241 1820
608bfe76
KS
1821 r = sockaddr_port(&sa.sa, &port);
1822 if (r < 0)
1823 return r;
1824
1825 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1826 return -ENOMEM;
1827 our_env[n_env++] = t;
1828 }
3b1c5241 1829 }
bfb1f9e2
LP
1830
1831 uint64_t cookie;
1832 if (socket_get_cookie(s->socket_fd, &cookie) >= 0) {
1833 char *t;
1834 if (asprintf(&t, "SO_COOKIE=%" PRIu64, cookie) < 0)
1835 return -ENOMEM;
1836 our_env[n_env++] = t;
1837 }
3b1c5241
SL
1838 }
1839
95c81c55
LB
1840 Service *env_source = NULL;
1841 const char *monitor_prefix;
81006ebb 1842 if (FLAGS_SET(exec_params.flags, EXEC_SETENV_RESULT)) {
95c81c55
LB
1843 env_source = s;
1844 monitor_prefix = "";
81006ebb 1845 } else if (FLAGS_SET(exec_params.flags, EXEC_SETENV_MONITOR_RESULT)) {
95c81c55
LB
1846 env_source = service_get_triggering_service(s);
1847 monitor_prefix = "MONITOR_";
1848 }
1849
1850 if (env_source) {
1851 if (asprintf(our_env + n_env++, "%sSERVICE_RESULT=%s", monitor_prefix, service_result_to_string(env_source->result)) < 0)
136dc4c4
LP
1852 return -ENOMEM;
1853
95c81c55
LB
1854 if (env_source->main_exec_status.pid > 0 &&
1855 dual_timestamp_is_set(&env_source->main_exec_status.exit_timestamp)) {
1856 if (asprintf(our_env + n_env++, "%sEXIT_CODE=%s", monitor_prefix, sigchld_code_to_string(env_source->main_exec_status.code)) < 0)
136dc4c4
LP
1857 return -ENOMEM;
1858
95c81c55
LB
1859 if (env_source->main_exec_status.code == CLD_EXITED)
1860 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%i", monitor_prefix, env_source->main_exec_status.status);
136dc4c4 1861 else
95c81c55 1862 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%s", monitor_prefix, signal_to_string(env_source->main_exec_status.status));
136dc4c4
LP
1863 if (r < 0)
1864 return -ENOMEM;
1865 }
cdebedb4 1866
95c81c55 1867 if (env_source != s) {
81006ebb
MY
1868 if (!sd_id128_is_null(UNIT(env_source)->invocation_id))
1869 if (asprintf(our_env + n_env++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR,
1870 monitor_prefix, SD_ID128_FORMAT_VAL(UNIT(env_source)->invocation_id)) < 0)
95c81c55 1871 return -ENOMEM;
95c81c55
LB
1872
1873 if (asprintf(our_env + n_env++, "%sUNIT=%s", monitor_prefix, UNIT(env_source)->id) < 0)
1874 return -ENOMEM;
cdebedb4 1875 }
136dc4c4
LP
1876 }
1877
fbb159b7 1878 if (UNIT(s)->debug_invocation) {
7d8bbfbe
LB
1879 char *t = strdup("DEBUG_INVOCATION=1");
1880 if (!t)
1881 return -ENOMEM;
1882 our_env[n_env++] = t;
1883 }
1884
48b92b37
LB
1885 if (UNIT(s)->activation_details) {
1886 r = activation_details_append_env(UNIT(s)->activation_details, &our_env);
1887 if (r < 0)
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;
1893 }
1894
1ad6e8b3
LP
1895 r = unit_set_exec_params(UNIT(s), &exec_params);
1896 if (r < 0)
1897 return r;
3536f49e 1898
4ab3d29f 1899 final_env = strv_env_merge(exec_params.environment, our_env);
36c16a7c
LP
1900 if (!final_env)
1901 return -ENOMEM;
c952c6ec 1902
ac647978 1903 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
de90700f 1904 SET_FLAG(exec_params.flags, EXEC_NSS_DYNAMIC_BYPASS,
ac647978 1905 MANAGER_IS_SYSTEM(UNIT(s)->manager) && unit_has_name(UNIT(s), SPECIAL_DBUS_SERVICE));
4ad49000 1906
b9c04eaf 1907 strv_free_and_replace(exec_params.environment, final_env);
34b3f625 1908 exec_params.watchdog_usec = service_get_watchdog_usec(s);
a34ceba6 1909 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
9fa95f85
DM
1910 if (s->type == SERVICE_IDLE)
1911 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
a34ceba6
LP
1912 exec_params.stdin_fd = s->stdin_fd;
1913 exec_params.stdout_fd = s->stdout_fd;
1914 exec_params.stderr_fd = s->stderr_fd;
9fa95f85 1915
f2341e0a
LP
1916 r = exec_spawn(UNIT(s),
1917 c,
9e2f7c11 1918 &s->exec_context,
9fa95f85 1919 &exec_params,
613b411c 1920 s->exec_runtime,
6bb00842 1921 &s->cgroup_context,
556d2bc4 1922 &pidref);
9e2f7c11 1923 if (r < 0)
36c16a7c 1924 return r;
034c6ed7 1925
5686391b
LP
1926 s->exec_fd_event_source = TAKE_PTR(exec_fd_source);
1927 s->exec_fd_hot = false;
1928
495e75ed 1929 r = unit_watch_pidref(UNIT(s), &pidref, /* exclusive= */ true);
c79ab77c
LP
1930 if (r < 0)
1931 return r;
034c6ed7 1932
c79ab77c 1933 *ret_pid = TAKE_PIDREF(pidref);
5cb5a6ff 1934 return 0;
034c6ed7
LP
1935}
1936
80876c20
LP
1937static int main_pid_good(Service *s) {
1938 assert(s);
1939
51894d70 1940 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
80876c20 1941
c79ab77c 1942 /* If we know the pid file, then let's just check if it is still valid */
6dfa5494
LP
1943 if (s->main_pid_known) {
1944
c79ab77c
LP
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))
becdfcb9 1947 return pidref_is_alive(&s->main_pid);
6dfa5494 1948
c79ab77c
LP
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);
6dfa5494 1952 }
80876c20
LP
1953
1954 /* We don't know the pid */
1955 return -EAGAIN;
1956}
1957
019be286 1958static int control_pid_good(Service *s) {
80876c20
LP
1959 assert(s);
1960
07697d7e
LP
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
c79ab77c 1965 return pidref_is_set(&s->control_pid);
80876c20
LP
1966}
1967
cb0e818f
HC
1968static int cgroup_good(Service *s) {
1969 int r;
1970
abaf5edd
ZJS
1971 assert(s);
1972
cb0e818f
HC
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
9cc54544 1976 if (!s->cgroup_runtime || !s->cgroup_runtime->cgroup_path)
abaf5edd
ZJS
1977 return 0;
1978
c3f90077 1979 r = cg_is_empty(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_runtime->cgroup_path);
117dcc57 1980 if (r < 0)
80876c20
LP
1981 return r;
1982
b13ddbbc 1983 return r == 0;
80876c20
LP
1984}
1985
ebc57b89 1986static bool service_shall_restart(Service *s, const char **reason) {
a509f0e6 1987 assert(s);
189a08e8 1988 assert(reason);
a509f0e6
LP
1989
1990 /* Don't restart after manual stops */
ebc57b89
ZJS
1991 if (s->forbid_restart) {
1992 *reason = "manual stop";
a509f0e6 1993 return false;
ebc57b89 1994 }
a509f0e6
LP
1995
1996 /* Never restart if this is configured as special exception */
ebc57b89
ZJS
1997 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status)) {
1998 *reason = "prevented by exit status";
a509f0e6 1999 return false;
ebc57b89 2000 }
a509f0e6
LP
2001
2002 /* Restart if the exit code/status are configured as restart triggers */
ebc57b89 2003 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status)) {
189a08e8
MY
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
ebc57b89 2011 *reason = "forced by exit status";
a509f0e6 2012 return true;
ebc57b89 2013 }
a509f0e6 2014
ebc57b89 2015 *reason = "restart setting";
a509f0e6
LP
2016 switch (s->restart) {
2017
2018 case SERVICE_RESTART_NO:
2019 return false;
2020
2021 case SERVICE_RESTART_ALWAYS:
abb99360 2022 return s->result != SERVICE_SKIP_CONDITION;
a509f0e6
LP
2023
2024 case SERVICE_RESTART_ON_SUCCESS:
2025 return s->result == SERVICE_SUCCESS;
2026
2027 case SERVICE_RESTART_ON_FAILURE:
bb924478 2028 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_SKIP_CONDITION);
a509f0e6
LP
2029
2030 case SERVICE_RESTART_ON_ABNORMAL:
bb924478 2031 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE, SERVICE_SKIP_CONDITION);
a509f0e6
LP
2032
2033 case SERVICE_RESTART_ON_WATCHDOG:
2034 return s->result == SERVICE_FAILURE_WATCHDOG;
2035
2036 case SERVICE_RESTART_ON_ABORT:
2037 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
2038
2039 default:
04499a70 2040 assert_not_reached();
a509f0e6
LP
2041 }
2042}
2043
deb4e708
MK
2044static bool service_will_restart(Unit *u) {
2045 Service *s = SERVICE(u);
2046
53f47dfc
YW
2047 assert(s);
2048
09d04ad3 2049 if (IN_SET(s->state, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED))
53f47dfc 2050 return true;
2ad2e41a 2051
52a12341 2052 return unit_will_restart_default(u);
53f47dfc
YW
2053}
2054
b9c1883a
LP
2055static ServiceState service_determine_dead_state(Service *s) {
2056 assert(s);
2057
2058 return s->fd_store && s->fd_store_preserve_mode == EXEC_PRESERVE_YES ? SERVICE_DEAD_RESOURCES_PINNED : SERVICE_DEAD;
2059}
2060
f42806df 2061static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
a1d31573 2062 ServiceState end_state, restart_state;
034c6ed7 2063 int r;
0f52f8e5 2064
034c6ed7
LP
2065 assert(s);
2066
0f52f8e5
LP
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)))
2070 allow_restart = false;
2071
a0fef983 2072 if (s->result == SERVICE_SUCCESS)
f42806df 2073 s->result = f;
034c6ed7 2074
31cd5f63
AZ
2075 if (s->result == SERVICE_SUCCESS) {
2076 unit_log_success(UNIT(s));
b9c1883a 2077 end_state = service_determine_dead_state(s);
a1d31573 2078 restart_state = SERVICE_DEAD_BEFORE_AUTO_RESTART;
31cd5f63
AZ
2079 } else if (s->result == SERVICE_SKIP_CONDITION) {
2080 unit_log_skip(UNIT(s), service_result_to_string(s->result));
b9c1883a 2081 end_state = service_determine_dead_state(s);
8959e17d 2082 restart_state = _SERVICE_STATE_INVALID; /* Never restart if skipped due to condition failure */
31cd5f63
AZ
2083 } else {
2084 unit_log_failure(UNIT(s), service_result_to_string(s->result));
2085 end_state = SERVICE_FAILED;
a1d31573 2086 restart_state = SERVICE_FAILED_BEFORE_AUTO_RESTART;
31cd5f63 2087 }
95e631da 2088 unit_warn_leftover_processes(UNIT(s), /* start = */ false);
ed77d407 2089
ebc57b89
ZJS
2090 if (!allow_restart)
2091 log_unit_debug(UNIT(s), "Service restart not allowed.");
2092 else {
2093 const char *reason;
ebc57b89 2094
49b34f75 2095 allow_restart = service_shall_restart(s, &reason);
ebc57b89 2096 log_unit_debug(UNIT(s), "Service will %srestart (%s)",
49b34f75 2097 allow_restart ? "" : "not ",
ebc57b89 2098 reason);
ebc57b89 2099 }
deb4e708 2100
49b34f75 2101 if (allow_restart) {
fe3d33c1
MY
2102 usec_t restart_usec_next;
2103
8959e17d
MY
2104 assert(restart_state >= 0 && restart_state < _SERVICE_STATE_MAX);
2105
a1d31573 2106 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
c309b9e9 2107 * state (i.e. a state indicating deactivation), and then one that maps to the
a1d31573
LP
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. */
e568fea9
RP
2113 if (s->restart_mode != SERVICE_RESTART_MODE_DIRECT)
2114 service_set_state(s, restart_state);
a1d31573 2115
fe3d33c1
MY
2116 restart_usec_next = service_restart_usec_next(s);
2117
2118 r = service_arm_timer(s, /* relative= */ true, restart_usec_next);
10691b9e
LP
2119 if (r < 0) {
2120 log_unit_warning_errno(UNIT(s), r, "Failed to install restart timer: %m");
d9b8d86b 2121 return service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
10691b9e 2122 }
034c6ed7 2123
7d8bbfbe
LB
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. */
7f2a7ccf
MY
2128 if (s->restart_mode == SERVICE_RESTART_MODE_DEBUG) {
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));
7d8bbfbe 2137
034c6ed7 2138 service_set_state(s, SERVICE_AUTO_RESTART);
7d8bbfbe 2139 } else {
ce31dbf4
MY
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. */
a1d31573
LP
2143 service_set_state(s, end_state);
2144
7f2a7ccf 2145 (void) unit_set_debug_invocation(UNIT(s), false);
7d8bbfbe
LB
2146 }
2147
f2341e0a 2148 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
47342320
LP
2149 s->forbid_restart = false;
2150
19dff691
MY
2151 /* Reset NotifyAccess override */
2152 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
2153
9c0c6701 2154 /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
28135da3 2155 s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
c17ec25e 2156
95939aed 2157 /* Also, remove the runtime directory */
703b1b7f 2158 unit_destroy_runtime_data(UNIT(s), &s->exec_context, /* destroy_runtime_dir = */ true);
e66cf1a3 2159
b9c1883a
LP
2160 /* Also get rid of the fd store, if that's configured. */
2161 if (s->fd_store_preserve_mode == EXEC_PRESERVE_NO)
2162 service_release_fd_store(s);
2163
00d9ef85
LP
2164 /* Get rid of the IPC bits of the user */
2165 unit_unref_uid_gid(UNIT(s), true);
2166
9285c9ff
LN
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)
fabab190 2171 (void) unlink(s->pid_file);
9285c9ff 2172
6f765baf 2173 /* Reset TTY ownership if necessary */
bbdad5c0 2174 exec_context_revert_tty(&s->exec_context, UNIT(s)->invocation_id);
034c6ed7
LP
2175}
2176
f42806df 2177static void service_enter_stop_post(Service *s, ServiceResult f) {
034c6ed7
LP
2178 int r;
2179 assert(s);
2180
a0fef983 2181 if (s->result == SERVICE_SUCCESS)
f42806df 2182 s->result = f;
034c6ed7 2183
5e94833f
LP
2184 service_unwatch_control_pid(s);
2185
117dcc57
ZJS
2186 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
2187 if (s->control_command) {
867b3b7d 2188 s->control_command_id = SERVICE_EXEC_STOP_POST;
c79ab77c 2189 pidref_done(&s->control_pid);
867b3b7d 2190
ecedd90f
LP
2191 r = service_spawn(s,
2192 s->control_command,
cfbf7538 2193 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2194 s->timeout_stop_usec,
ecedd90f 2195 &s->control_pid);
10691b9e
LP
2196 if (r < 0) {
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 }
034c6ed7 2201
80876c20
LP
2202 service_set_state(s, SERVICE_STOP_POST);
2203 } else
ac84d1fb 2204 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2205}
2206
a232ebcc 2207static int state_to_kill_operation(Service *s, ServiceState state) {
4940c0b0
LP
2208 switch (state) {
2209
c87700a1 2210 case SERVICE_STOP_WATCHDOG:
bf760801 2211 case SERVICE_FINAL_WATCHDOG:
c87700a1 2212 return KILL_WATCHDOG;
4940c0b0
LP
2213
2214 case SERVICE_STOP_SIGTERM:
a232ebcc
ZJS
2215 if (unit_has_job_type(UNIT(s), JOB_RESTART))
2216 return KILL_RESTART;
2217 _fallthrough_;
2218
4940c0b0
LP
2219 case SERVICE_FINAL_SIGTERM:
2220 return KILL_TERMINATE;
2221
2222 case SERVICE_STOP_SIGKILL:
2223 case SERVICE_FINAL_SIGKILL:
2224 return KILL_KILL;
2225
2226 default:
2227 return _KILL_OPERATION_INVALID;
2228 }
2229}
2230
f42806df 2231static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
bf760801 2232 int kill_operation, r;
034c6ed7
LP
2233
2234 assert(s);
2235
a0fef983 2236 if (s->result == SERVICE_SUCCESS)
f42806df 2237 s->result = f;
034c6ed7 2238
bf760801 2239 kill_operation = state_to_kill_operation(s, state);
b826e317 2240 r = unit_kill_context(UNIT(s), kill_operation);
10691b9e
LP
2241 if (r < 0) {
2242 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
cd2086fe 2243 goto fail;
10691b9e 2244 }
034c6ed7 2245
cd2086fe 2246 if (r > 0) {
e5d6dcce
LP
2247 r = service_arm_timer(s, /* relative= */ true,
2248 kill_operation == KILL_WATCHDOG ? service_timeout_abort_usec(s) : s->timeout_stop_usec);
10691b9e
LP
2249 if (r < 0) {
2250 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
36c16a7c 2251 goto fail;
10691b9e 2252 }
d6ea93e3 2253
80876c20 2254 service_set_state(s, state);
c87700a1 2255 } else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2256 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
c87700a1 2257 else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2258 service_enter_stop_post(s, SERVICE_SUCCESS);
bf760801 2259 else if (IN_SET(state, SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2260 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
80876c20 2261 else
10691b9e 2262 service_enter_dead(s, SERVICE_SUCCESS, /* allow_restart= */ true);
034c6ed7
LP
2263
2264 return;
2265
2266fail:
c87700a1 2267 if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2268 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
034c6ed7 2269 else
10691b9e 2270 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
034c6ed7
LP
2271}
2272
308d72dc 2273static void service_enter_stop_by_notify(Service *s) {
3dde96d8
LP
2274 int r;
2275
308d72dc
LP
2276 assert(s);
2277
3dde96d8
LP
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 }
308d72dc 2284
6041a7ee
MS
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);
308d72dc
LP
2287}
2288
f42806df 2289static void service_enter_stop(Service *s, ServiceResult f) {
034c6ed7 2290 int r;
5925dd3c 2291
034c6ed7
LP
2292 assert(s);
2293
a0fef983 2294 if (s->result == SERVICE_SUCCESS)
f42806df 2295 s->result = f;
034c6ed7 2296
5e94833f
LP
2297 service_unwatch_control_pid(s);
2298
117dcc57
ZJS
2299 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2300 if (s->control_command) {
867b3b7d 2301 s->control_command_id = SERVICE_EXEC_STOP;
c79ab77c 2302 pidref_done(&s->control_pid);
867b3b7d 2303
ecedd90f
LP
2304 r = service_spawn(s,
2305 s->control_command,
cfbf7538 2306 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2307 s->timeout_stop_usec,
ecedd90f 2308 &s->control_pid);
10691b9e
LP
2309 if (r < 0) {
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 }
034c6ed7 2314
80876c20
LP
2315 service_set_state(s, SERVICE_STOP);
2316 } else
f42806df 2317 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2318}
2319
957c3cf9
LP
2320static bool service_good(Service *s) {
2321 int main_pid_ok;
e9fa1bf7 2322
957c3cf9
LP
2323 assert(s);
2324
2325 if (s->type == SERVICE_DBUS && !s->bus_name_good)
2326 return false;
2327
2328 main_pid_ok = main_pid_good(s);
2329 if (main_pid_ok > 0) /* It's alive */
2330 return true;
ef430065 2331 if (main_pid_ok == 0 && s->exit_type == SERVICE_EXIT_MAIN) /* It's dead */
957c3cf9
LP
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;
2339}
2340
f42806df 2341static void service_enter_running(Service *s, ServiceResult f) {
3dde96d8
LP
2342 int r;
2343
80876c20
LP
2344 assert(s);
2345
a0fef983 2346 if (s->result == SERVICE_SUCCESS)
f42806df 2347 s->result = f;
80876c20 2348
089b64d5
LP
2349 service_unwatch_control_pid(s);
2350
ec5b1452
LP
2351 if (s->result != SERVICE_SUCCESS)
2352 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2353 else if (service_good(s)) {
308d72dc 2354
ec5b1452 2355 /* If there are any queued up sd_notify() notifications, process them now */
308d72dc
LP
2356 if (s->notify_state == NOTIFY_RELOADING)
2357 service_enter_reload_by_notify(s);
2358 else if (s->notify_state == NOTIFY_STOPPING)
2359 service_enter_stop_by_notify(s);
36c16a7c 2360 else {
308d72dc 2361 service_set_state(s, SERVICE_RUNNING);
3dde96d8
LP
2362
2363 r = service_arm_timer(s, /* relative= */ false, service_running_timeout(s));
2364 if (r < 0) {
2365 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2366 service_enter_running(s, SERVICE_FAILURE_RESOURCES);
2367 return;
2368 }
36c16a7c 2369 }
308d72dc 2370
ec5b1452 2371 } else if (s->remain_after_exit)
80876c20
LP
2372 service_set_state(s, SERVICE_EXITED);
2373 else
f42806df 2374 service_enter_stop(s, SERVICE_SUCCESS);
80876c20
LP
2375}
2376
034c6ed7
LP
2377static void service_enter_start_post(Service *s) {
2378 int r;
e9fa1bf7 2379
034c6ed7
LP
2380 assert(s);
2381
5e94833f 2382 service_unwatch_control_pid(s);
842129f5 2383 service_reset_watchdog(s);
bb242b7b 2384
117dcc57
ZJS
2385 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2386 if (s->control_command) {
867b3b7d 2387 s->control_command_id = SERVICE_EXEC_START_POST;
c79ab77c 2388 pidref_done(&s->control_pid);
867b3b7d 2389
ecedd90f
LP
2390 r = service_spawn(s,
2391 s->control_command,
cfbf7538 2392 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2393 s->timeout_start_usec,
ecedd90f 2394 &s->control_pid);
10691b9e
LP
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 }
034c6ed7 2400
80876c20
LP
2401 service_set_state(s, SERVICE_START_POST);
2402 } else
f42806df 2403 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2404}
2405
e9a4f676 2406static void service_kill_control_process(Service *s) {
a6951a50 2407 int r;
4ad49000 2408
a6951a50
LP
2409 assert(s);
2410
c79ab77c 2411 if (!pidref_is_set(&s->control_pid))
e9a4f676 2412 return;
4ad49000 2413
c79ab77c 2414 r = pidref_kill_and_sigcont(&s->control_pid, SIGKILL);
e9a4f676
LP
2415 if (r < 0) {
2416 _cleanup_free_ char *comm = NULL;
a6951a50 2417
d7d74854 2418 (void) pidref_get_comm(&s->control_pid, &comm);
a6951a50 2419
e9a4f676 2420 log_unit_debug_errno(UNIT(s), r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m",
c79ab77c 2421 s->control_pid.pid, strna(comm));
a6951a50 2422 }
4ad49000
LP
2423}
2424
c53d2d54
DB
2425static int service_adverse_to_leftover_processes(Service *s) {
2426 assert(s);
2427
2428 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
4c425434
LP
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).
c53d2d54
DB
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
4c425434 2435 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
38747451 2436 * aren't as rigoriously written to protect against multiple use. */
4c425434 2437
95e631da 2438 if (unit_warn_leftover_processes(UNIT(s), /* start = */ true) > 0 &&
c53d2d54 2439 IN_SET(s->kill_context.kill_mode, KILL_MIXED, KILL_CONTROL_GROUP) &&
569554d9 2440 !s->kill_context.send_sigkill)
95e631da
MY
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");
569554d9 2443
c53d2d54
DB
2444 return 0;
2445}
2446
034c6ed7 2447static void service_enter_start(Service *s) {
c79ab77c 2448 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
4ad49000 2449 ExecCommand *c;
36c16a7c 2450 usec_t timeout;
034c6ed7
LP
2451 int r;
2452
2453 assert(s);
2454
41efeaec
LP
2455 service_unwatch_control_pid(s);
2456 service_unwatch_main_pid(s);
80876c20 2457
c53d2d54
DB
2458 r = service_adverse_to_leftover_processes(s);
2459 if (r < 0)
2460 goto fail;
a4634b21 2461
867b3b7d
LP
2462 if (s->type == SERVICE_FORKING) {
2463 s->control_command_id = SERVICE_EXEC_START;
2464 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2465
2466 s->main_command = NULL;
2467 } else {
2468 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2469 s->control_command = NULL;
2470
2471 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2472 }
34e9ba66 2473
96fb8242 2474 if (!c) {
47fffb35 2475 if (s->type != SERVICE_ONESHOT) {
cbc056c8
ZJS
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. */
d85ff944 2479 r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENXIO), "There's no 'start' task anymore we could start.");
47fffb35
LP
2480 goto fail;
2481 }
2482
ef5ae8e7
ZJS
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
5238e957 2485 * in between. This way we can later trigger actions that depend on the state
ef5ae8e7
ZJS
2486 * transition, including SuccessAction=. */
2487 service_set_state(s, SERVICE_START);
2488
96fb8242
LP
2489 service_enter_start_post(s);
2490 return;
2491 }
2492
36c16a7c
LP
2493 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
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;
2499
ecedd90f
LP
2500 r = service_spawn(s,
2501 c,
cfbf7538 2502 service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS_FRESH),
36c16a7c 2503 timeout,
c79ab77c 2504 &pidref);
10691b9e
LP
2505 if (r < 0) {
2506 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start' task: %m");
034c6ed7 2507 goto fail;
10691b9e 2508 }
034c6ed7 2509
026335e9 2510 assert(pidref.pid == c->exec_status.pid);
034c6ed7 2511
026335e9 2512 switch (s->type) {
034c6ed7 2513
026335e9
MY
2514 case SERVICE_SIMPLE:
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);
2518 return service_enter_start_post(s);
034c6ed7 2519
026335e9
MY
2520 case SERVICE_FORKING:
2521 /* For forking services we wait until the start process exited. */
c79ab77c
LP
2522 pidref_done(&s->control_pid);
2523 s->control_pid = TAKE_PIDREF(pidref);
026335e9
MY
2524 return service_set_state(s, SERVICE_START);
2525
2526 case SERVICE_ONESHOT: /* For oneshot services we wait until the start process exited, too, but it is our main process. */
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. */
7e0e6b50 2534 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), &c->exec_status.start_timestamp);
026335e9 2535 return service_set_state(s, SERVICE_START);
034c6ed7 2536
026335e9 2537 default:
ae1cb17c 2538 assert_not_reached();
026335e9
MY
2539 }
2540
034c6ed7 2541fail:
c3fda31d 2542 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2543}
2544
2545static void service_enter_start_pre(Service *s) {
2546 int r;
2547
2548 assert(s);
2549
5e94833f
LP
2550 service_unwatch_control_pid(s);
2551
117dcc57
ZJS
2552 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2553 if (s->control_command) {
8f53a7b8 2554
c53d2d54
DB
2555 r = service_adverse_to_leftover_processes(s);
2556 if (r < 0)
2557 goto fail;
a4634b21 2558
867b3b7d
LP
2559 s->control_command_id = SERVICE_EXEC_START_PRE;
2560
ecedd90f
LP
2561 r = service_spawn(s,
2562 s->control_command,
cfbf7538 2563 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2564 s->timeout_start_usec,
ecedd90f 2565 &s->control_pid);
10691b9e
LP
2566 if (r < 0) {
2567 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-pre' task: %m");
034c6ed7 2568 goto fail;
10691b9e 2569 }
034c6ed7 2570
80876c20
LP
2571 service_set_state(s, SERVICE_START_PRE);
2572 } else
034c6ed7
LP
2573 service_enter_start(s);
2574
2575 return;
2576
2577fail:
10691b9e 2578 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
034c6ed7
LP
2579}
2580
31cd5f63
AZ
2581static void service_enter_condition(Service *s) {
2582 int r;
2583
2584 assert(s);
2585
2586 service_unwatch_control_pid(s);
2587
2588 s->control_command = s->exec_command[SERVICE_EXEC_CONDITION];
2589 if (s->control_command) {
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;
c79ab77c 2596 pidref_done(&s->control_pid);
31cd5f63
AZ
2597
2598 r = service_spawn(s,
2599 s->control_command,
cfbf7538 2600 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
31cd5f63 2601 s->timeout_start_usec,
31cd5f63 2602 &s->control_pid);
10691b9e
LP
2603 if (r < 0) {
2604 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'exec-condition' task: %m");
31cd5f63 2605 goto fail;
10691b9e 2606 }
31cd5f63
AZ
2607
2608 service_set_state(s, SERVICE_CONDITION);
2609 } else
2610 service_enter_start_pre(s);
2611
2612 return;
2613
2614fail:
10691b9e 2615 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
31cd5f63
AZ
2616}
2617
1391f149 2618static void service_enter_restart(Service *s, bool shortcut) {
4afd3348 2619 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7 2620 int r;
398ef8ba 2621
1391f149
MY
2622 /* shortcut: a manual start request is received, restart immediately */
2623
034c6ed7 2624 assert(s);
1391f149 2625 assert(s->state == SERVICE_AUTO_RESTART);
034c6ed7 2626
1391f149 2627 if (!shortcut && unit_has_job_type(UNIT(s), JOB_STOP)) {
a8bb2e65 2628 /* Don't restart things if we are going down anyway */
c9728806 2629 log_unit_info(UNIT(s), "Stop job pending for unit, skipping automatic restart.");
feae8adb 2630 return;
2edfa366
LP
2631 }
2632
7a139370
MY
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.
569269d0 2636 *
7a139370 2637 * Also, when RestartMode=direct is used, the service being restarted don't enter the inactive/failed state,
569269d0
MY
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,
2642 JOB_START, UNIT(s),
7a139370 2643 s->restart_mode == SERVICE_RESTART_MODE_DIRECT ? JOB_REPLACE : JOB_RESTART_DEPENDENCIES,
569269d0
MY
2644 TRANSACTION_REENQUEUE_ANCHOR,
2645 /* affected_jobs = */ NULL,
2646 &error, /* ret = */ NULL);
10691b9e
LP
2647 if (r < 0) {
2648 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, r));
d993ad6c 2649 return service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
10691b9e 2650 }
034c6ed7 2651
0c59d2e4
LP
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. */
b3a9d980 2655 s->n_restarts++;
7a0019d3 2656
c2503e35 2657 log_unit_struct(UNIT(s), LOG_INFO,
3cf6a3a3 2658 LOG_MESSAGE_ID(SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR),
c2503e35 2659 LOG_UNIT_INVOCATION_ID(UNIT(s)),
92663a5e 2660 LOG_UNIT_MESSAGE(UNIT(s),
1391f149
MY
2661 "Scheduled restart job%s, restart counter is at %u.",
2662 shortcut ? " immediately on client request" : "", s->n_restarts),
3cf6a3a3 2663 LOG_ITEM("N_RESTARTS=%u", s->n_restarts));
7a0019d3 2664
09d04ad3
LP
2665 service_set_state(s, SERVICE_AUTO_RESTART_QUEUED);
2666
7a0019d3
LP
2667 /* Notify clients about changed restart counter */
2668 unit_add_to_dbus_queue(UNIT(s));
034c6ed7
LP
2669}
2670
308d72dc 2671static void service_enter_reload_by_notify(Service *s) {
15d167f8
JW
2672 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2673 int r;
2674
308d72dc
LP
2675 assert(s);
2676
3dde96d8
LP
2677 r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
2678 if (r < 0) {
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
3bd28bf7 2685 service_set_state(s, SERVICE_RELOAD_NOTIFY);
15d167f8
JW
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);
2689 if (r < 0)
3dde96d8 2690 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error, r));
308d72dc
LP
2691}
2692
dfdeb0b1 2693static void service_enter_reload_signal_exec(Service *s) {
3bd28bf7 2694 bool killed = false;
034c6ed7
LP
2695 int r;
2696
2697 assert(s);
2698
5e94833f 2699 service_unwatch_control_pid(s);
95c906ae 2700 s->reload_result = SERVICE_SUCCESS;
5e94833f 2701
3bd28bf7
LP
2702 usec_t ts = now(CLOCK_MONOTONIC);
2703
c79ab77c
LP
2704 if (s->type == SERVICE_NOTIFY_RELOAD && pidref_is_set(&s->main_pid)) {
2705 r = pidref_kill_and_sigcont(&s->main_pid, s->reload_signal);
3bd28bf7
LP
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
117dcc57
ZJS
2714 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2715 if (s->control_command) {
867b3b7d 2716 s->control_command_id = SERVICE_EXEC_RELOAD;
c79ab77c 2717 pidref_done(&s->control_pid);
867b3b7d 2718
ecedd90f
LP
2719 r = service_spawn(s,
2720 s->control_command,
cfbf7538 2721 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2722 s->timeout_start_usec,
ecedd90f 2723 &s->control_pid);
3bd28bf7 2724 if (r < 0) {
10691b9e 2725 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'reload' task: %m");
034c6ed7 2726 goto fail;
3bd28bf7 2727 }
034c6ed7 2728
80876c20 2729 service_set_state(s, SERVICE_RELOAD);
3bd28bf7 2730 } else if (killed) {
3dde96d8
LP
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
3bd28bf7
LP
2737 service_set_state(s, SERVICE_RELOAD_SIGNAL);
2738 } else {
f42806df 2739 service_enter_running(s, SERVICE_SUCCESS);
3bd28bf7
LP
2740 return;
2741 }
034c6ed7 2742
3bd28bf7
LP
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;
034c6ed7
LP
2748 return;
2749
2750fail:
f42806df
LP
2751 s->reload_result = SERVICE_FAILURE_RESOURCES;
2752 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2753}
2754
dfdeb0b1 2755static bool service_should_reload_extensions(Service *s) {
2756 int r;
2757
2758 assert(s);
2759
2760 if (!pidref_is_set(&s->main_pid)) {
2761 log_unit_debug(UNIT(s), "Not reloading extensions for service without main PID.");
2762 return false;
2763 }
2764
2765 r = exec_context_has_vpicked_extensions(&s->exec_context);
2766 if (r < 0)
2767 log_unit_warning_errno(UNIT(s), r, "Failed to determine if service should reload extensions, assuming false: %m");
2768 if (r == 0)
2769 log_unit_debug(UNIT(s), "Service has no extensions to reload.");
2770 if (r <= 0)
2771 return false;
2772
2773 // TODO: Add support for user services, which can use ExtensionDirectories= + notify-reload.
2774 // For now, skip for user services.
2775 if (!MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
2776 log_once(LOG_WARNING, "Not reloading extensions for user services.");
2777 return false;
2778 }
2779
2780 return true;
2781}
2782
2783static void service_enter_refresh_extensions(Service *s) {
2784 _cleanup_(pidref_done) PidRef worker = PIDREF_NULL;
2785 int r;
2786
2787 assert(s);
2788
2789 /* If we don't have extensions to reload, immediately go to the signal step */
2790 if (!service_should_reload_extensions(s))
2791 return (void) service_enter_reload_signal_exec(s);
2792
2793 service_unwatch_control_pid(s);
2794 s->reload_result = SERVICE_SUCCESS;
2795 s->control_command = NULL;
2796 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2797
2798 /* Given we are running from PID1, avoid doing potentially heavy I/O operations like opening images
2799 * directly, and instead fork a worker process. */
2800 r = unit_fork_helper_process(UNIT(s), "(sd-refresh-extensions)", /* into_cgroup= */ false, &worker);
2801 if (r < 0) {
2802 log_unit_error_errno(UNIT(s), r, "Failed to fork process to refresh extensions in unit's namespace: %m");
2803 goto fail;
2804 }
2805 if (r == 0) {
2806 PidRef *unit_pid = &s->main_pid;
2807 assert(pidref_is_set(unit_pid));
2808
2809 _cleanup_free_ char *propagate_dir = path_join("/run/systemd/propagate/", UNIT(s)->id);
2810 if (!propagate_dir) {
2811 log_unit_error_errno(UNIT(s), -ENOMEM, "Failed to allocate memory for propagate directory: %m");
2812 _exit(EXIT_FAILURE);
2813 }
2814
2815 NamespaceParameters p = {
2816 .private_namespace_dir = "/run/systemd",
2817 .incoming_dir = "/run/systemd/incoming",
2818 .propagate_dir = propagate_dir,
2819 .runtime_scope = UNIT(s)->manager->runtime_scope,
2820 .extension_images = s->exec_context.extension_images,
2821 .n_extension_images = s->exec_context.n_extension_images,
2822 .extension_directories = s->exec_context.extension_directories,
2823 .extension_image_policy = s->exec_context.extension_image_policy,
2824 };
2825
2826 /* Only reload confext, and not sysext as they also typically contain the executable(s) used
2827 * by the service and a simply reload cannot meaningfully handle that. */
2828 r = refresh_extensions_in_namespace(
2829 unit_pid,
2830 "SYSTEMD_CONFEXT_HIERARCHIES",
2831 &p);
2832 if (r < 0)
2833 log_unit_error_errno(UNIT(s), r, "Failed to refresh extensions in unit's namespace: %m");
2834 else
2835 log_unit_debug(UNIT(s), "Refreshed extensions in unit's namespace");
2836
2837 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
2838 }
2839
2840 r = unit_watch_pidref(UNIT(s), &worker, /* exclusive= */ true);
2841 if (r < 0) {
2842 log_unit_warning_errno(UNIT(s), r, "Failed to watch extensions refresh helper process: %m");
2843 goto fail;
2844 }
2845
2846 s->control_pid = TAKE_PIDREF(worker);
2847 service_set_state(s, SERVICE_REFRESH_EXTENSIONS);
2848 return;
2849
2850fail:
2851 s->reload_result = SERVICE_FAILURE_RESOURCES;
2852 service_enter_running(s, SERVICE_SUCCESS);
2853}
2854
2855static void service_enter_reload_mounting(Service *s) {
2856 int r;
2857
2858 assert(s);
2859
2860 usec_t ts = now(CLOCK_MONOTONIC);
2861
2862 r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
2863 if (r < 0) {
2864 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2865 s->reload_result = SERVICE_FAILURE_RESOURCES;
2866 service_enter_running(s, SERVICE_SUCCESS);
2867 return;
2868 }
2869
2870 s->reload_begin_usec = ts;
2871
2872 service_enter_refresh_extensions(s);
2873}
2874
f42806df 2875static void service_run_next_control(Service *s) {
36c16a7c 2876 usec_t timeout;
034c6ed7
LP
2877 int r;
2878
2879 assert(s);
2880 assert(s->control_command);
2881 assert(s->control_command->command_next);
2882
34e9ba66 2883 assert(s->control_command_id != SERVICE_EXEC_START);
034c6ed7 2884
34e9ba66 2885 s->control_command = s->control_command->command_next;
5e94833f
LP
2886 service_unwatch_control_pid(s);
2887
31cd5f63 2888 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
36c16a7c
LP
2889 timeout = s->timeout_start_usec;
2890 else
2891 timeout = s->timeout_stop_usec;
2892
c79ab77c
LP
2893 pidref_done(&s->control_pid);
2894
ecedd90f
LP
2895 r = service_spawn(s,
2896 s->control_command,
cfbf7538 2897 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
36c16a7c 2898 timeout,
ecedd90f 2899 &s->control_pid);
10691b9e
LP
2900 if (r < 0) {
2901 log_unit_warning_errno(UNIT(s), r, "Failed to spawn next control task: %m");
2902
2903 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START_POST, SERVICE_STOP))
2904 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2905 else if (s->state == SERVICE_STOP_POST)
2906 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
2907 else if (s->state == SERVICE_RELOAD) {
2908 s->reload_result = SERVICE_FAILURE_RESOURCES;
2909 service_enter_running(s, SERVICE_SUCCESS);
2910 } else
2911 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2912 }
5cb5a6ff
LP
2913}
2914
f42806df 2915static void service_run_next_main(Service *s) {
c79ab77c 2916 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
34e9ba66
LP
2917 int r;
2918
2919 assert(s);
867b3b7d
LP
2920 assert(s->main_command);
2921 assert(s->main_command->command_next);
2922 assert(s->type == SERVICE_ONESHOT);
34e9ba66 2923
867b3b7d 2924 s->main_command = s->main_command->command_next;
34e9ba66
LP
2925 service_unwatch_main_pid(s);
2926
ecedd90f
LP
2927 r = service_spawn(s,
2928 s->main_command,
cfbf7538 2929 service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS),
21b2ce39 2930 s->timeout_start_usec,
c79ab77c 2931 &pidref);
10691b9e
LP
2932 if (r < 0) {
2933 log_unit_warning_errno(UNIT(s), r, "Failed to spawn next main task: %m");
2934 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2935 return;
2936 }
34e9ba66 2937
7e0e6b50 2938 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), &s->main_command->exec_status.start_timestamp);
34e9ba66
LP
2939}
2940
87f0e418 2941static int service_start(Unit *u) {
1391f149 2942 Service *s = ASSERT_PTR(SERVICE(u));
07299350 2943 int r;
5cb5a6ff 2944
034c6ed7
LP
2945 /* We cannot fulfill this request right now, try again later
2946 * please! */
a00973af 2947 if (IN_SET(s->state,
c87700a1 2948 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
bf760801 2949 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
5cb5a6ff
LP
2950 return -EAGAIN;
2951
034c6ed7 2952 /* Already on it! */
31cd5f63 2953 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
034c6ed7
LP
2954 return 0;
2955
1391f149
MY
2956 if (s->state == SERVICE_AUTO_RESTART) {
2957 /* As mentioned in unit_start(), we allow manual starts to act as "hurry up" signals
2958 * for auto restart. We need to re-enqueue the job though, as the job type has changed
2959 * (JOB_RESTART_DEPENDENCIES). */
2960
2961 service_enter_restart(s, /* shortcut = */ true);
a8bb2e65 2962 return -EAGAIN;
1391f149 2963 }
2e9d6c12 2964
1391f149
MY
2965 /* SERVICE_*_BEFORE_AUTO_RESTART are not to be expected here, as those are intermediate states
2966 * that should never be seen outside of service_enter_dead(). */
09d04ad3 2967 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED, SERVICE_AUTO_RESTART_QUEUED));
5cb5a6ff 2968
4b58153d
LP
2969 r = unit_acquire_invocation_id(u);
2970 if (r < 0)
2971 return r;
2972
f42806df
LP
2973 s->result = SERVICE_SUCCESS;
2974 s->reload_result = SERVICE_SUCCESS;
034c6ed7 2975 s->main_pid_known = false;
6dfa5494 2976 s->main_pid_alien = false;
47342320 2977 s->forbid_restart = false;
3c7416b6 2978
ce31dbf4
MY
2979 /* This is not an automatic restart? Flush the restart counter then. */
2980 if (s->state != SERVICE_AUTO_RESTART_QUEUED)
2981 s->n_restarts = 0;
2982
a1e58e8e 2983 s->status_text = mfree(s->status_text);
8cfdb077 2984 s->status_errno = 0;
9c025022
MY
2985 s->status_bus_error = mfree(s->status_bus_error);
2986 s->status_varlink_error = mfree(s->status_varlink_error);
8cfdb077 2987
19dff691 2988 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
308d72dc
LP
2989 s->notify_state = NOTIFY_UNKNOWN;
2990
aa8c4bbf 2991 s->watchdog_original_usec = s->watchdog_usec;
2787d83c 2992 s->watchdog_override_enable = false;
aa8c4bbf 2993 s->watchdog_override_usec = USEC_INFINITY;
2787d83c 2994
6a1d4d9f
LP
2995 exec_command_reset_status_list_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
2996 exec_status_reset(&s->main_exec_status);
2997
9cc54544
LP
2998 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2999 if (crt)
3000 crt->reset_accounting = true;
6a1d4d9f 3001
31cd5f63 3002 service_enter_condition(s);
82a2b6bb 3003 return 1;
5cb5a6ff
LP
3004}
3005
a6eeca9a 3006static void service_live_mount_finish(Service *s, ServiceResult f, const char *error) {
5162829e
LB
3007 assert(s);
3008 assert(error);
3009
a6eeca9a
MY
3010 s->live_mount_result = f;
3011
5162829e
LB
3012 if (!s->mount_request)
3013 return;
3014
a6eeca9a 3015 if (f == SERVICE_SUCCESS) {
5162829e
LB
3016 (void) sd_bus_reply_method_return(s->mount_request, NULL);
3017 log_unit_debug(UNIT(s),
3018 "'%s' method succeeded",
3019 strna(sd_bus_message_get_member(s->mount_request)));
3020 } else {
3021 (void) sd_bus_reply_method_errorf(s->mount_request, error,
3022 "method '%s' for unit '%s' failed",
3023 strna(sd_bus_message_get_member(s->mount_request)),
3024 UNIT(s)->id);
3025 log_unit_debug(UNIT(s),
3026 "'%s' method failed: %s",
3027 strna(sd_bus_message_get_member(s->mount_request)),
3028 error);
3029 }
3030
3031 s->mount_request = sd_bus_message_unref(s->mount_request);
3032}
3033
87f0e418 3034static int service_stop(Unit *u) {
e9fa1bf7 3035 Service *s = ASSERT_PTR(SERVICE(u));
5cb5a6ff 3036
a509f0e6 3037 /* Don't create restart jobs from manual stops. */
47342320 3038 s->forbid_restart = true;
034c6ed7 3039
a1d31573
LP
3040 switch (s->state) {
3041
3042 case SERVICE_STOP:
3043 case SERVICE_STOP_SIGTERM:
3044 case SERVICE_STOP_SIGKILL:
3045 case SERVICE_STOP_POST:
3046 case SERVICE_FINAL_WATCHDOG:
3047 case SERVICE_FINAL_SIGTERM:
3048 case SERVICE_FINAL_SIGKILL:
3049 /* Already on it */
e537352b
LP
3050 return 0;
3051
a1d31573 3052 case SERVICE_AUTO_RESTART:
09d04ad3
LP
3053 case SERVICE_AUTO_RESTART_QUEUED:
3054 /* Give up on the auto restart */
b9c1883a 3055 service_set_state(s, service_determine_dead_state(s));
034c6ed7 3056 return 0;
034c6ed7 3057
5162829e 3058 case SERVICE_MOUNTING:
a6eeca9a 3059 service_live_mount_finish(s, SERVICE_FAILURE_PROTOCOL, BUS_ERROR_UNIT_INACTIVE);
5162829e 3060 _fallthrough_;
dfdeb0b1 3061 case SERVICE_REFRESH_EXTENSIONS:
3062 service_kill_control_process(s);
3063 _fallthrough_;
a1d31573
LP
3064 case SERVICE_CONDITION:
3065 case SERVICE_START_PRE:
3066 case SERVICE_START:
3067 case SERVICE_START_POST:
3068 case SERVICE_RELOAD:
3069 case SERVICE_RELOAD_SIGNAL:
3070 case SERVICE_RELOAD_NOTIFY:
3071 case SERVICE_STOP_WATCHDOG:
3072 /* If there's already something running we go directly into kill mode. */
f42806df 3073 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
3f6c78dc 3074 return 0;
5cb5a6ff 3075
a1d31573
LP
3076 case SERVICE_CLEANING:
3077 /* If we are currently cleaning, then abort it, brutally. */
4c2f5842
LP
3078 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
3079 return 0;
a1d31573
LP
3080
3081 case SERVICE_RUNNING:
3082 case SERVICE_EXITED:
3083 service_enter_stop(s, SERVICE_SUCCESS);
3084 return 1;
3085
3086 case SERVICE_DEAD_BEFORE_AUTO_RESTART:
3087 case SERVICE_FAILED_BEFORE_AUTO_RESTART:
3088 case SERVICE_DEAD:
3089 case SERVICE_FAILED:
b9c1883a 3090 case SERVICE_DEAD_RESOURCES_PINNED:
a1d31573
LP
3091 default:
3092 /* Unknown state, or unit_stop() should already have handled these */
3093 assert_not_reached();
4c2f5842 3094 }
5cb5a6ff
LP
3095}
3096
87f0e418 3097static int service_reload(Unit *u) {
e9fa1bf7 3098 Service *s = ASSERT_PTR(SERVICE(u));
034c6ed7 3099
3742095b 3100 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
034c6ed7 3101
dfdeb0b1 3102 service_enter_reload_mounting(s);
3103
2d018ae2 3104 return 1;
5cb5a6ff
LP
3105}
3106
d1e8e8b5 3107static bool service_can_reload(Unit *u) {
e9fa1bf7 3108 Service *s = ASSERT_PTR(SERVICE(u));
034c6ed7 3109
3bd28bf7
LP
3110 return s->exec_command[SERVICE_EXEC_RELOAD] ||
3111 s->type == SERVICE_NOTIFY_RELOAD;
034c6ed7
LP
3112}
3113
502096b5 3114static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, const ExecCommand *current) {
e266c068
MS
3115 Service *s = SERVICE(u);
3116 unsigned idx = 0;
e266c068
MS
3117
3118 assert(s);
5b99bd5f
LP
3119 assert(id >= 0);
3120 assert(id < _SERVICE_EXEC_COMMAND_MAX);
e266c068 3121
502096b5 3122 const ExecCommand *first = s->exec_command[id];
e266c068
MS
3123
3124 /* Figure out where we are in the list by walking back to the beginning */
502096b5 3125 for (const ExecCommand *c = current; c != first; c = c->command_prev)
e266c068
MS
3126 idx++;
3127
3128 return idx;
3129}
3130
502096b5 3131static int service_serialize_exec_command(Unit *u, FILE *f, const ExecCommand *command) {
e9fa1bf7 3132 Service *s = ASSERT_PTR(SERVICE(u));
d68c645b 3133 _cleanup_free_ char *args = NULL, *p = NULL;
d68c645b 3134 const char *type, *key;
e266c068 3135 ServiceExecCommand id;
319a4f4b 3136 size_t length = 0;
e266c068 3137 unsigned idx;
e266c068 3138
e266c068
MS
3139 assert(f);
3140
3141 if (!command)
3142 return 0;
3143
3144 if (command == s->control_command) {
3145 type = "control";
3146 id = s->control_command_id;
3147 } else {
3148 type = "main";
3149 id = SERVICE_EXEC_START;
3150 }
3151
3152 idx = service_exec_command_index(u, id, command);
3153
3154 STRV_FOREACH(arg, command->argv) {
e266c068 3155 _cleanup_free_ char *e = NULL;
d68c645b 3156 size_t n;
e266c068 3157
d68c645b 3158 e = cescape(*arg);
e266c068 3159 if (!e)
d68c645b 3160 return log_oom();
e266c068
MS
3161
3162 n = strlen(e);
319a4f4b 3163 if (!GREEDY_REALLOC(args, length + 2 + n + 2))
d68c645b 3164 return log_oom();
e266c068
MS
3165
3166 if (length > 0)
3167 args[length++] = ' ';
3168
334c0979 3169 args[length++] = '"';
e266c068
MS
3170 memcpy(args + length, e, n);
3171 length += n;
334c0979 3172 args[length++] = '"';
e266c068
MS
3173 }
3174
319a4f4b 3175 if (!GREEDY_REALLOC(args, length + 1))
d68c645b
LP
3176 return log_oom();
3177
e266c068
MS
3178 args[length++] = 0;
3179
d68c645b 3180 p = cescape(command->path);
e266c068 3181 if (!p)
5b99bd5f 3182 return log_oom();
e266c068 3183
d68c645b 3184 key = strjoina(type, "-command");
a99bd455
ZJS
3185
3186 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
3187 * This is used in service_deserialize_exec_command(). */
3188 (void) serialize_item_format(
3189 f, key,
3190 "%s %s%u %s %s",
3191 service_exec_command_to_string(id),
3192 command->command_next ? "" : "+",
3193 idx,
3194 p, args);
5b99bd5f
LP
3195
3196 return 0;
e266c068
MS
3197}
3198
a16e1123 3199static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
e9fa1bf7 3200 Service *s = ASSERT_PTR(SERVICE(u));
a34ceba6 3201 int r;
a16e1123 3202
a16e1123
LP
3203 assert(f);
3204 assert(fds);
3205
d68c645b
LP
3206 (void) serialize_item(f, "state", service_state_to_string(s->state));
3207 (void) serialize_item(f, "result", service_result_to_string(s->result));
3208 (void) serialize_item(f, "reload-result", service_result_to_string(s->reload_result));
78270121 3209 (void) serialize_item(f, "live-mount-result", service_result_to_string(s->live_mount_result));
a16e1123 3210
2a7451dc
LP
3211 (void) serialize_pidref(f, fds, "control-pid", &s->control_pid);
3212 if (s->main_pid_known)
3213 (void) serialize_pidref(f, fds, "main-pid", &s->main_pid);
a16e1123 3214
d68c645b
LP
3215 (void) serialize_bool(f, "main-pid-known", s->main_pid_known);
3216 (void) serialize_bool(f, "bus-name-good", s->bus_name_good);
a16e1123 3217
d68c645b 3218 (void) serialize_item_format(f, "n-restarts", "%u", s->n_restarts);
301dc073 3219 (void) serialize_bool(f, "forbid-restart", s->forbid_restart);
3a2776bc 3220
e266c068
MS
3221 service_serialize_exec_command(u, f, s->control_command);
3222 service_serialize_exec_command(u, f, s->main_command);
a16e1123 3223
d68c645b 3224 r = serialize_fd(f, fds, "stdin-fd", s->stdin_fd);
a34ceba6
LP
3225 if (r < 0)
3226 return r;
d68c645b 3227 r = serialize_fd(f, fds, "stdout-fd", s->stdout_fd);
a34ceba6
LP
3228 if (r < 0)
3229 return r;
d68c645b 3230 r = serialize_fd(f, fds, "stderr-fd", s->stderr_fd);
a34ceba6
LP
3231 if (r < 0)
3232 return r;
e44da745 3233
5686391b 3234 if (s->exec_fd_event_source) {
d68c645b 3235 r = serialize_fd(f, fds, "exec-fd", sd_event_source_get_io_fd(s->exec_fd_event_source));
5686391b
LP
3236 if (r < 0)
3237 return r;
d68c645b
LP
3238
3239 (void) serialize_bool(f, "exec-fd-hot", s->exec_fd_hot);
5686391b
LP
3240 }
3241
9dfb64f8 3242 if (UNIT_ISSET(s->accept_socket)) {
d68c645b 3243 r = serialize_item(f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
9dfb64f8
ZJS
3244 if (r < 0)
3245 return r;
3246 }
3247
d68c645b 3248 r = serialize_fd(f, fds, "socket-fd", s->socket_fd);
a34ceba6
LP
3249 if (r < 0)
3250 return r;
e44da745 3251
2339fc93 3252 LIST_FOREACH(fd_store, fs, s->fd_store) {
8dd4c05b 3253 _cleanup_free_ char *c = NULL;
2339fc93
LP
3254 int copy;
3255
3256 copy = fdset_put_dup(fds, fs->fd);
3257 if (copy < 0)
d68c645b 3258 return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
2339fc93 3259
8dd4c05b 3260 c = cescape(fs->fdname);
d68c645b
LP
3261 if (!c)
3262 return log_oom();
8dd4c05b 3263
9b85bf02 3264 (void) serialize_item_format(f, "fd-store-fd", "%i \"%s\" %s", copy, c, one_zero(fs->do_poll));
2339fc93
LP
3265 }
3266
8e66f42b
MY
3267 FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
3268 _cleanup_free_ char *c = NULL;
3269 int copy;
3270
3271 copy = fdset_put_dup(fds, i->fd);
3272 if (copy < 0)
3273 return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
3274
3275 c = cescape(i->fdname);
3276 if (!c)
3277 return log_oom();
3278
3279 (void) serialize_item_format(f, "extra-fd", "%i \"%s\"", copy, c);
3280 }
3281
ecdbca40 3282 if (s->main_exec_status.pid > 0) {
d68c645b
LP
3283 (void) serialize_item_format(f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
3284 (void) serialize_dual_timestamp(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
3285 (void) serialize_dual_timestamp(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
3c1d1ca1 3286 (void) serialize_dual_timestamp(f, "main-exec-status-handoff", &s->main_exec_status.handoff_timestamp);
ecdbca40 3287
799fd0fd 3288 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
d68c645b
LP
3289 (void) serialize_item_format(f, "main-exec-status-code", "%i", s->main_exec_status.code);
3290 (void) serialize_item_format(f, "main-exec-status-status", "%i", s->main_exec_status.status);
ecdbca40
LP
3291 }
3292 }
f06db334 3293
19dff691
MY
3294 if (s->notify_access_override >= 0)
3295 (void) serialize_item(f, "notify-access-override", notify_access_to_string(s->notify_access_override));
3296
301dc073
MY
3297 r = serialize_item_escaped(f, "status-text", s->status_text);
3298 if (r < 0)
3299 return r;
3300
a74b2840 3301 (void) serialize_item_format(f, "status-errno", "%d", s->status_errno);
9c025022
MY
3302 (void) serialize_item(f, "status-bus-error", s->status_bus_error);
3303 (void) serialize_item(f, "status-varlink-error", s->status_varlink_error);
a74b2840 3304
d68c645b 3305 (void) serialize_dual_timestamp(f, "watchdog-timestamp", &s->watchdog_timestamp);
6aca9a58 3306
301dc073 3307 (void) serialize_usec(f, "watchdog-original-usec", s->watchdog_original_usec);
2787d83c 3308 if (s->watchdog_override_enable)
301dc073 3309 (void) serialize_usec(f, "watchdog-override-usec", s->watchdog_override_usec);
aa8c4bbf 3310
301dc073 3311 (void) serialize_usec(f, "reload-begin-usec", s->reload_begin_usec);
3bd28bf7 3312
a16e1123
LP
3313 return 0;
3314}
3315
35243b77 3316int service_deserialize_exec_command(
5b99bd5f
LP
3317 Unit *u,
3318 const char *key,
3319 const char *value) {
3320
e9fa1bf7 3321 Service *s = ASSERT_PTR(SERVICE(u));
e266c068 3322 ExecCommand *command = NULL;
e9fa1bf7 3323 ServiceExecCommand id = _SERVICE_EXEC_COMMAND_INVALID;
6eeec374 3324 _cleanup_free_ char *path = NULL;
e266c068 3325 _cleanup_strv_free_ char **argv = NULL;
e9fa1bf7
MY
3326 unsigned idx = 0, i;
3327 bool control, found = false, last = false;
3328 int r;
e266c068 3329
e1fa0e1a 3330 enum {
e266c068
MS
3331 STATE_EXEC_COMMAND_TYPE,
3332 STATE_EXEC_COMMAND_INDEX,
3333 STATE_EXEC_COMMAND_PATH,
3334 STATE_EXEC_COMMAND_ARGS,
3335 _STATE_EXEC_COMMAND_MAX,
2d93c20e 3336 _STATE_EXEC_COMMAND_INVALID = -EINVAL,
e266c068
MS
3337 } state;
3338
e266c068
MS
3339 assert(key);
3340 assert(value);
3341
3342 control = streq(key, "control-command");
3343
3344 state = STATE_EXEC_COMMAND_TYPE;
3345
3346 for (;;) {
3347 _cleanup_free_ char *arg = NULL;
3348
334c0979 3349 r = extract_first_word(&value, &arg, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
efa3f34e
LP
3350 if (r < 0)
3351 return r;
e266c068
MS
3352 if (r == 0)
3353 break;
e266c068
MS
3354
3355 switch (state) {
e1fa0e1a 3356
e266c068
MS
3357 case STATE_EXEC_COMMAND_TYPE:
3358 id = service_exec_command_from_string(arg);
3359 if (id < 0)
7211c853 3360 return id;
e266c068
MS
3361
3362 state = STATE_EXEC_COMMAND_INDEX;
3363 break;
e1fa0e1a 3364
e266c068 3365 case STATE_EXEC_COMMAND_INDEX:
e1fa0e1a
MY
3366 /* ExecCommand index 1234 is serialized as either '1234' or '+1234'. The second form
3367 * is used to mark the last command in a sequence. We warn if the deserialized command
3368 * doesn't match what we have loaded from the unit, but we don't need to warn if
3369 * that is the last command. */
a99bd455 3370
e266c068
MS
3371 r = safe_atou(arg, &idx);
3372 if (r < 0)
7211c853 3373 return r;
a99bd455 3374 last = arg[0] == '+';
e266c068
MS
3375
3376 state = STATE_EXEC_COMMAND_PATH;
3377 break;
e1fa0e1a 3378
e266c068 3379 case STATE_EXEC_COMMAND_PATH:
ae2a15bc 3380 path = TAKE_PTR(arg);
e266c068 3381 state = STATE_EXEC_COMMAND_ARGS;
e266c068 3382 break;
e1fa0e1a 3383
e266c068
MS
3384 case STATE_EXEC_COMMAND_ARGS:
3385 r = strv_extend(&argv, arg);
3386 if (r < 0)
010cd1dc 3387 return r;
e266c068 3388 break;
e1fa0e1a 3389
e266c068 3390 default:
04499a70 3391 assert_not_reached();
e266c068
MS
3392 }
3393 }
3394
3395 if (state != STATE_EXEC_COMMAND_ARGS)
3396 return -EINVAL;
90204792
ZJS
3397 if (strv_isempty(argv))
3398 return -EINVAL; /* At least argv[0] must be always present. */
e266c068
MS
3399
3400 /* Let's check whether exec command on given offset matches data that we just deserialized */
3401 for (command = s->exec_command[id], i = 0; command; command = command->command_next, i++) {
3402 if (i != idx)
3403 continue;
3404
3405 found = strv_equal(argv, command->argv) && streq(command->path, path);
3406 break;
3407 }
3408
3409 if (!found) {
3410 /* Command at the index we serialized is different, let's look for command that exactly
3411 * matches but is on different index. If there is no such command we will not resume execution. */
3412 for (command = s->exec_command[id]; command; command = command->command_next)
3413 if (strv_equal(command->argv, argv) && streq(command->path, path))
3414 break;
3415 }
3416
e9da62b1 3417 if (command && control) {
e266c068 3418 s->control_command = command;
e9da62b1
LP
3419 s->control_command_id = id;
3420 } else if (command)
e266c068 3421 s->main_command = command;
a99bd455
ZJS
3422 else if (last)
3423 log_unit_debug(u, "Current command vanished from the unit file.");
e266c068
MS
3424 else
3425 log_unit_warning(u, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3426
3427 return 0;
3428}
3429
a16e1123 3430static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
e9fa1bf7 3431 Service *s = ASSERT_PTR(SERVICE(u));
2339fc93 3432 int r;
a16e1123 3433
a16e1123
LP
3434 assert(key);
3435 assert(value);
3436 assert(fds);
3437
3438 if (streq(key, "state")) {
3439 ServiceState state;
3440
117dcc57
ZJS
3441 state = service_state_from_string(value);
3442 if (state < 0)
78270121 3443 log_unit_debug_errno(u, state, "Failed to parse state value: %s", value);
a16e1123
LP
3444 else
3445 s->deserialized_state = state;
f42806df
LP
3446 } else if (streq(key, "result")) {
3447 ServiceResult f;
3448
3449 f = service_result_from_string(value);
3450 if (f < 0)
78270121 3451 log_unit_debug_errno(u, f, "Failed to parse result value: %s", value);
f42806df
LP
3452 else if (f != SERVICE_SUCCESS)
3453 s->result = f;
3454
3455 } else if (streq(key, "reload-result")) {
3456 ServiceResult f;
3457
3458 f = service_result_from_string(value);
3459 if (f < 0)
78270121 3460 log_unit_debug_errno(u, f, "Failed to parse reload result value: %s", value);
f42806df
LP
3461 else if (f != SERVICE_SUCCESS)
3462 s->reload_result = f;
a16e1123 3463
78270121
MY
3464 } else if (streq(key, "live-mount-result")) {
3465 ServiceResult f;
3466
3467 f = service_result_from_string(value);
3468 if (f < 0)
3469 log_unit_debug_errno(u, f, "Failed to parse live mount result value: %s", value);
3470 else if (f != SERVICE_SUCCESS)
3471 s->live_mount_result = f;
3472
a16e1123 3473 } else if (streq(key, "control-pid")) {
2a7451dc 3474
aaa872a7
DDM
3475 if (!pidref_is_set(&s->control_pid))
3476 (void) deserialize_pidref(fds, value, &s->control_pid);
2a7451dc 3477
a16e1123 3478 } else if (streq(key, "main-pid")) {
c603f523 3479 PidRef pidref;
2a7451dc 3480
70727771 3481 if (!pidref_is_set(&s->main_pid) && deserialize_pidref(fds, value, &pidref) >= 0)
7e0e6b50 3482 (void) service_set_main_pidref(s, pidref, /* start_timestamp = */ NULL);
a16e1123 3483
a16e1123 3484 } else if (streq(key, "main-pid-known")) {
156d23ab
MY
3485 r = parse_boolean(value);
3486 if (r < 0)
3487 log_unit_debug_errno(u, r, "Failed to parse main-pid-known value: %s", value);
a16e1123 3488 else
156d23ab 3489 s->main_pid_known = r;
de1d4f9b 3490 } else if (streq(key, "bus-name-good")) {
156d23ab
MY
3491 r = parse_boolean(value);
3492 if (r < 0)
3493 log_unit_debug_errno(u, r, "Failed to parse bus-name-good value: %s", value);
de1d4f9b 3494 else
156d23ab 3495 s->bus_name_good = r;
9dfb64f8
ZJS
3496 } else if (streq(key, "accept-socket")) {
3497 Unit *socket;
3498
9f5d8c3d
MY
3499 if (unit_name_to_type(value) != UNIT_SOCKET) {
3500 log_unit_debug(u, "Deserialized accept-socket is not a socket unit, ignoring: %s", value);
45b10174
FS
3501 return 0;
3502 }
3503
9dfb64f8
ZJS
3504 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
3505 if (r < 0)
5e1ee764 3506 log_unit_debug_errno(u, r, "Failed to load accept-socket unit '%s': %m", value);
9dfb64f8 3507 else {
7f7d01ed 3508 unit_ref_set(&s->accept_socket, u, socket);
9f5d8c3d 3509 ASSERT_PTR(SOCKET(socket))->n_connections++;
9dfb64f8
ZJS
3510 }
3511
a16e1123 3512 } else if (streq(key, "socket-fd")) {
dff9808a
LP
3513 asynchronous_close(s->socket_fd);
3514 s->socket_fd = deserialize_fd(fds, value);
a16e1123 3515
2339fc93 3516 } else if (streq(key, "fd-store-fd")) {
30520492 3517 _cleanup_free_ char *fdv = NULL, *fdn = NULL, *fdp = NULL;
dff9808a
LP
3518 _cleanup_close_ int fd = -EBADF;
3519 int do_poll;
2339fc93 3520
9b85bf02
MY
3521 r = extract_many_words(&value, " ", EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE, &fdv, &fdn, &fdp);
3522 if (r < 2 || r > 3) {
3523 log_unit_debug(u, "Failed to deserialize fd-store-fd, ignoring: %s", value);
30520492
KL
3524 return 0;
3525 }
8dd4c05b 3526
dff9808a
LP
3527 fd = deserialize_fd(fds, fdv);
3528 if (fd < 0)
3529 return 0;
3530
9b85bf02
MY
3531 do_poll = r == 3 ? parse_boolean(fdp) : true;
3532 if (do_poll < 0) {
3533 log_unit_debug_errno(u, do_poll,
3534 "Failed to deserialize fd-store-fd do_poll, ignoring: %s", fdp);
30520492 3535 return 0;
2339fc93
LP
3536 }
3537
d9919881 3538 r = service_add_fd_store(s, TAKE_FD(fd), fdn, do_poll);
a02287ea 3539 if (r < 0) {
9b85bf02
MY
3540 log_unit_debug_errno(u, r,
3541 "Failed to store deserialized fd '%s', ignoring: %m", fdn);
a02287ea
YW
3542 return 0;
3543 }
8e66f42b
MY
3544 } else if (streq(key, "extra-fd")) {
3545 _cleanup_free_ char *fdv = NULL, *fdn = NULL;
3546 _cleanup_close_ int fd = -EBADF;
3547
3548 r = extract_many_words(&value, " ", EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE, &fdv, &fdn);
3549 if (r != 2) {
3550 log_unit_debug(u, "Failed to deserialize extra-fd, ignoring: %s", value);
3551 return 0;
3552 }
3553
3554 fd = deserialize_fd(fds, fdv);
3555 if (fd < 0)
3556 return 0;
3557
3558 if (!GREEDY_REALLOC(s->extra_fds, s->n_extra_fds + 1)) {
3559 log_oom_debug();
3560 return 0;
3561 }
3562
3563 s->extra_fds[s->n_extra_fds++] = (ServiceExtraFD) {
3564 .fd = TAKE_FD(fd),
3565 .fdname = TAKE_PTR(fdn),
3566 };
ecdbca40
LP
3567 } else if (streq(key, "main-exec-status-pid")) {
3568 pid_t pid;
3569
e364ad06 3570 if (parse_pid(value, &pid) < 0)
f2341e0a 3571 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
ecdbca40
LP
3572 else
3573 s->main_exec_status.pid = pid;
3574 } else if (streq(key, "main-exec-status-code")) {
3575 int i;
3576
e364ad06 3577 if (safe_atoi(value, &i) < 0)
f2341e0a 3578 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
ecdbca40
LP
3579 else
3580 s->main_exec_status.code = i;
3581 } else if (streq(key, "main-exec-status-status")) {
3582 int i;
3583
e364ad06 3584 if (safe_atoi(value, &i) < 0)
f2341e0a 3585 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
ecdbca40
LP
3586 else
3587 s->main_exec_status.status = i;
799fd0fd 3588 } else if (streq(key, "main-exec-status-start"))
42fdb142 3589 (void) deserialize_dual_timestamp(value, &s->main_exec_status.start_timestamp);
799fd0fd 3590 else if (streq(key, "main-exec-status-exit"))
42fdb142 3591 (void) deserialize_dual_timestamp(value, &s->main_exec_status.exit_timestamp);
3c1d1ca1 3592 else if (streq(key, "main-exec-status-handoff"))
42fdb142 3593 (void) deserialize_dual_timestamp(value, &s->main_exec_status.handoff_timestamp);
301dc073
MY
3594 else if (STR_IN_SET(key, "main-command", "control-command")) {
3595 r = service_deserialize_exec_command(u, key, value);
3596 if (r < 0)
3597 log_unit_debug_errno(u, r, "Failed to parse serialized command \"%s\": %m", value);
3598 } else if (streq(key, "notify-access-override")) {
19dff691
MY
3599 NotifyAccess notify_access;
3600
3601 notify_access = notify_access_from_string(value);
3602 if (notify_access < 0)
3603 log_unit_debug(u, "Failed to parse notify-access-override value: %s", value);
3604 else
3605 s->notify_access_override = notify_access;
301dc073
MY
3606 } else if (streq(key, "n-restarts")) {
3607 r = safe_atou(value, &s->n_restarts);
3608 if (r < 0)
3609 log_unit_debug_errno(u, r, "Failed to parse serialized restart counter '%s': %m", value);
6aca9a58 3610
301dc073
MY
3611 } else if (streq(key, "forbid-restart")) {
3612 r = parse_boolean(value);
3613 if (r < 0)
3614 log_unit_debug_errno(u, r, "Failed to parse forbid-restart value: %s", value);
6aca9a58 3615 else
301dc073 3616 s->forbid_restart = r;
a34ceba6 3617 } else if (streq(key, "stdin-fd")) {
a34ceba6 3618
dff9808a
LP
3619 asynchronous_close(s->stdin_fd);
3620 s->stdin_fd = deserialize_fd(fds, value);
3621 if (s->stdin_fd >= 0)
1e22b5cd 3622 s->exec_context.stdio_as_fds = true;
dff9808a 3623
a34ceba6 3624 } else if (streq(key, "stdout-fd")) {
a34ceba6 3625
dff9808a
LP
3626 asynchronous_close(s->stdout_fd);
3627 s->stdout_fd = deserialize_fd(fds, value);
3628 if (s->stdout_fd >= 0)
1e22b5cd 3629 s->exec_context.stdio_as_fds = true;
dff9808a 3630
a34ceba6 3631 } else if (streq(key, "stderr-fd")) {
a34ceba6 3632
dff9808a
LP
3633 asynchronous_close(s->stderr_fd);
3634 s->stderr_fd = deserialize_fd(fds, value);
3635 if (s->stderr_fd >= 0)
1e22b5cd 3636 s->exec_context.stdio_as_fds = true;
dff9808a 3637
5686391b 3638 } else if (streq(key, "exec-fd")) {
dff9808a 3639 _cleanup_close_ int fd = -EBADF;
5686391b 3640
dff9808a
LP
3641 fd = deserialize_fd(fds, value);
3642 if (fd >= 0) {
5dcadb4c 3643 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b 3644
dff9808a
LP
3645 if (service_allocate_exec_fd_event_source(s, fd, &s->exec_fd_event_source) >= 0)
3646 TAKE_FD(fd);
5686391b 3647 }
dff9808a 3648
301dc073
MY
3649 } else if (streq(key, "status-text")) {
3650 char *t;
3651 ssize_t l;
aa8c4bbf 3652
301dc073
MY
3653 l = cunescape(value, 0, &t);
3654 if (l < 0)
3655 log_unit_debug_errno(u, l, "Failed to unescape status text '%s': %m", value);
3656 else
3657 free_and_replace(s->status_text, t);
7a0019d3 3658
a74b2840
MY
3659 } else if (streq(key, "status-errno")) {
3660 int i;
3661
3662 if (safe_atoi(value, &i) < 0)
3663 log_unit_debug(u, "Failed to parse status-errno value: %s", value);
3664 else
3665 s->status_errno = i;
3666
9c025022
MY
3667 } else if (streq(key, "status-bus-error")) {
3668 if (free_and_strdup(&s->status_bus_error, value) < 0)
3669 log_oom_debug();
3670
3671 } else if (streq(key, "status-varlink-error")) {
3672 if (free_and_strdup(&s->status_varlink_error, value) < 0)
3673 log_oom_debug();
3674
301dc073 3675 } else if (streq(key, "watchdog-timestamp"))
42fdb142 3676 (void) deserialize_dual_timestamp(value, &s->watchdog_timestamp);
301dc073 3677 else if (streq(key, "watchdog-original-usec"))
42fdb142 3678 (void) deserialize_usec(value, &s->watchdog_original_usec);
301dc073
MY
3679 else if (streq(key, "watchdog-override-usec")) {
3680 if (deserialize_usec(value, &s->watchdog_override_usec) >= 0)
3681 s->watchdog_override_enable = true;
7a0019d3 3682
301dc073 3683 } else if (streq(key, "reload-begin-usec"))
42fdb142 3684 (void) deserialize_usec(value, &s->reload_begin_usec);
301dc073 3685 else
f2341e0a 3686 log_unit_debug(u, "Unknown serialization key: %s", key);
a16e1123
LP
3687
3688 return 0;
3689}
3690
d1e8e8b5 3691static UnitActiveState service_active_state(Unit *u) {
e9fa1bf7 3692 Service *s = ASSERT_PTR(SERVICE(u));
e056b01d
LP
3693 const UnitActiveState *table;
3694
e9fa1bf7 3695 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
e056b01d 3696
e9fa1bf7 3697 return table[s->state];
034c6ed7
LP
3698}
3699
10a94420
LP
3700static const char *service_sub_state_to_string(Unit *u) {
3701 assert(u);
3702
3703 return service_state_to_string(SERVICE(u)->state);
3704}
3705
f2f725e5 3706static bool service_may_gc(Unit *u) {
e9fa1bf7 3707 Service *s = ASSERT_PTR(SERVICE(u));
701cc384 3708
e98b2fbb 3709 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
f2f725e5 3710 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
e98b2fbb
LP
3711 * have moved outside of the cgroup. */
3712
3713 if (main_pid_good(s) > 0 ||
6d55002a 3714 control_pid_good(s) > 0)
f2f725e5 3715 return false;
6d55002a 3716
a1d31573
LP
3717 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3718 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
b9c1883a 3719 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
a1d31573
LP
3720 return false;
3721
f2f725e5 3722 return true;
6d55002a
LP
3723}
3724
3a111838
MS
3725static int service_retry_pid_file(Service *s) {
3726 int r;
3727
e9fa1bf7 3728 assert(s);
3a111838 3729 assert(s->pid_file);
3742095b 3730 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838
MS
3731
3732 r = service_load_pid_file(s, false);
3733 if (r < 0)
3734 return r;
3735
3736 service_unwatch_pid_file(s);
3737
f42806df 3738 service_enter_running(s, SERVICE_SUCCESS);
3a111838
MS
3739 return 0;
3740}
3741
3742static int service_watch_pid_file(Service *s) {
3743 int r;
3744
e9fa1bf7
MY
3745 assert(s);
3746
f2341e0a 3747 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
8bb2d17d 3748
5686391b 3749 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_inotify_io);
10691b9e
LP
3750 if (r < 0) {
3751 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
3752 service_unwatch_pid_file(s);
3753 return r;
3754 }
3a111838
MS
3755
3756 /* the pidfile might have appeared just before we set the watch */
f2341e0a 3757 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
3a111838
MS
3758 service_retry_pid_file(s);
3759
3760 return 0;
3a111838
MS
3761}
3762
3763static int service_demand_pid_file(Service *s) {
51339a9a 3764 _cleanup_free_ PathSpec *ps = NULL;
3a111838 3765
e9fa1bf7 3766 assert(s);
3a111838
MS
3767 assert(s->pid_file);
3768 assert(!s->pid_file_pathspec);
3769
51339a9a 3770 ps = new(PathSpec, 1);
3a111838
MS
3771 if (!ps)
3772 return -ENOMEM;
3773
51339a9a
LP
3774 *ps = (PathSpec) {
3775 .unit = UNIT(s),
3776 .path = strdup(s->pid_file),
3777 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3778 * open all the time. */
3779 .type = PATH_MODIFIED,
3780 .inotify_fd = -EBADF,
3781 };
3782
3783 if (!ps->path)
3a111838 3784 return -ENOMEM;
3a111838 3785
4ff361cc 3786 path_simplify(ps->path);
3a111838 3787
51339a9a 3788 s->pid_file_pathspec = TAKE_PTR(ps);
3a111838
MS
3789
3790 return service_watch_pid_file(s);
3791}
3792
5686391b 3793static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
99534007 3794 PathSpec *p = ASSERT_PTR(userdata);
e9fa1bf7 3795 Service *s = ASSERT_PTR(SERVICE(p->unit));
3a111838 3796
3a111838 3797 assert(fd >= 0);
3742095b 3798 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838 3799 assert(s->pid_file_pathspec);
57020a3a 3800 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3a111838 3801
f2341e0a 3802 log_unit_debug(UNIT(s), "inotify event");
3a111838 3803
e14c2802 3804 if (path_spec_fd_event(p, events) < 0)
3a111838
MS
3805 goto fail;
3806
3807 if (service_retry_pid_file(s) == 0)
718db961 3808 return 0;
3a111838
MS
3809
3810 if (service_watch_pid_file(s) < 0)
3811 goto fail;
3812
718db961
LP
3813 return 0;
3814
3a111838
MS
3815fail:
3816 service_unwatch_pid_file(s);
f42806df 3817 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
718db961 3818 return 0;
3a111838
MS
3819}
3820
5686391b 3821static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
e9fa1bf7 3822 Service *s = ASSERT_PTR(SERVICE(userdata));
5686391b
LP
3823
3824 log_unit_debug(UNIT(s), "got exec-fd event");
3825
3826 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
12001b1b
LP
3827 * successfully for it. We implement this through a pipe() towards the child, which the kernel
3828 * automatically closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on
3829 * the pipe in the parent. We need to be careful however, as there are other reasons that we might
3830 * cause the child's side of the pipe to be closed (for example, a simple exit()). To deal with that
3831 * we'll ignore EOFs on the pipe unless the child signalled us first that it is about to call the
3832 * execve(). It does so by sending us a simple non-zero byte via the pipe. We also provide the child
3833 * with a way to inform us in case execve() failed: if it sends a zero byte we'll ignore POLLHUP on
3834 * the fd again. */
5686391b
LP
3835
3836 for (;;) {
12001b1b 3837 uint8_t x;
5686391b
LP
3838 ssize_t n;
3839
12001b1b
LP
3840 n = read(fd, &x, sizeof(x));
3841 if (n < 0) {
3842 if (errno == EAGAIN) /* O_NONBLOCK in effect → everything queued has now been processed. */
3843 return 0;
3844
3845 return log_unit_error_errno(UNIT(s), errno, "Failed to read from exec_fd: %m");
3846 }
3847 if (n == 0) { /* EOF → the event we are waiting for in case of Type=exec */
5dcadb4c 3848 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b
LP
3849
3850 if (s->exec_fd_hot) { /* Did the child tell us to expect EOF now? */
3851 log_unit_debug(UNIT(s), "Got EOF on exec-fd");
3852
3853 s->exec_fd_hot = false;
3854
3855 /* Nice! This is what we have been waiting for. Transition to next state. */
3856 if (s->type == SERVICE_EXEC && s->state == SERVICE_START)
3857 service_enter_start_post(s);
3858 } else
3859 log_unit_debug(UNIT(s), "Got EOF on exec-fd while it was disabled, ignoring.");
3860
3861 return 0;
3862 }
5686391b 3863
12001b1b
LP
3864 /* A byte was read → this turns on/off the exec fd logic */
3865 assert(n == sizeof(x));
93cb78ae 3866
12001b1b 3867 s->exec_fd_hot = x;
93cb78ae 3868 }
5686391b
LP
3869}
3870
a911bb9a 3871static void service_notify_cgroup_empty_event(Unit *u) {
e9fa1bf7 3872 Service *s = ASSERT_PTR(SERVICE(u));
a911bb9a 3873
a5b5aece 3874 log_unit_debug(u, "Control group is empty.");
a911bb9a
LP
3875
3876 switch (s->state) {
3877
a1d31573
LP
3878 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3879 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3880 * don't know pid which to expect the SIGCHLD for. */
a911bb9a
LP
3881
3882 case SERVICE_START:
3bd28bf7 3883 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
3c751b1b
LP
3884 main_pid_good(s) == 0 &&
3885 control_pid_good(s) == 0) {
3d474ef7 3886 /* No chance of getting a ready notification anymore */
c3fda31d 3887 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
71e529fc
JW
3888 break;
3889 }
3890
f52e9ed6
MY
3891 if (s->exit_type == SERVICE_EXIT_CGROUP && main_pid_good(s) <= 0) {
3892 service_enter_stop_post(s, SERVICE_SUCCESS);
3893 break;
3894 }
596e4470 3895
4831981d 3896 _fallthrough_;
71e529fc 3897 case SERVICE_START_POST:
3c751b1b
LP
3898 if (s->pid_file_pathspec &&
3899 main_pid_good(s) == 0 &&
3900 control_pid_good(s) == 0) {
3901
3d474ef7 3902 /* Give up hoping for the daemon to write its PID file */
f2341e0a 3903 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
8bb2d17d 3904
a911bb9a
LP
3905 service_unwatch_pid_file(s);
3906 if (s->state == SERVICE_START)
c3fda31d 3907 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a 3908 else
c35755fb 3909 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a
LP
3910 }
3911 break;
3912
3913 case SERVICE_RUNNING:
3914 /* service_enter_running() will figure out what to do */
3915 service_enter_running(s, SERVICE_SUCCESS);
3916 break;
3917
c87700a1 3918 case SERVICE_STOP_WATCHDOG:
a911bb9a
LP
3919 case SERVICE_STOP_SIGTERM:
3920 case SERVICE_STOP_SIGKILL:
3921
b13ddbbc 3922 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3923 service_enter_stop_post(s, SERVICE_SUCCESS);
3924
3925 break;
3926
3927 case SERVICE_STOP_POST:
bf760801 3928 case SERVICE_FINAL_WATCHDOG:
a911bb9a
LP
3929 case SERVICE_FINAL_SIGTERM:
3930 case SERVICE_FINAL_SIGKILL:
b13ddbbc 3931 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3932 service_enter_dead(s, SERVICE_SUCCESS, true);
3933
3934 break;
3935
e08dabfe
AZ
3936 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3937 * up the cgroup earlier and should do it now. */
a1d31573 3938 case SERVICE_AUTO_RESTART:
09d04ad3 3939 case SERVICE_AUTO_RESTART_QUEUED:
e08dabfe
AZ
3940 unit_prune_cgroup(u);
3941 break;
3942
a911bb9a
LP
3943 default:
3944 ;
3945 }
3946}
3947
38c41427 3948static void service_notify_cgroup_oom_event(Unit *u, bool managed_oom) {
e9fa1bf7 3949 Service *s = ASSERT_PTR(SERVICE(u));
afcfaa69 3950
38c41427
NK
3951 if (managed_oom)
3952 log_unit_debug(u, "Process(es) of control group were killed by systemd-oomd.");
3953 else
3954 log_unit_debug(u, "Process of control group was killed by the OOM killer.");
afcfaa69
LP
3955
3956 if (s->oom_policy == OOM_CONTINUE)
3957 return;
3958
3959 switch (s->state) {
3960
31cd5f63 3961 case SERVICE_CONDITION:
afcfaa69
LP
3962 case SERVICE_START_PRE:
3963 case SERVICE_START:
3964 case SERVICE_START_POST:
3965 case SERVICE_STOP:
3966 if (s->oom_policy == OOM_STOP)
3967 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_OOM_KILL);
3968 else if (s->oom_policy == OOM_KILL)
3969 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3970
3971 break;
3972
3973 case SERVICE_EXITED:
3974 case SERVICE_RUNNING:
3975 if (s->oom_policy == OOM_STOP)
3976 service_enter_stop(s, SERVICE_FAILURE_OOM_KILL);
3977 else if (s->oom_policy == OOM_KILL)
3978 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3979
3980 break;
3981
3982 case SERVICE_STOP_WATCHDOG:
3983 case SERVICE_STOP_SIGTERM:
3984 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3985 break;
3986
3987 case SERVICE_STOP_SIGKILL:
3988 case SERVICE_FINAL_SIGKILL:
3989 if (s->result == SERVICE_SUCCESS)
3990 s->result = SERVICE_FAILURE_OOM_KILL;
3991 break;
3992
3993 case SERVICE_STOP_POST:
3994 case SERVICE_FINAL_SIGTERM:
3995 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3996 break;
3997
3998 default:
3999 ;
4000 }
4001}
4002
87f0e418 4003static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
e9fa1bf7 4004 Service *s = ASSERT_PTR(SERVICE(u));
5cdabc8d 4005 bool notify_dbus = true;
f42806df 4006 ServiceResult f;
e5123725 4007 ExitClean clean_mode;
c917a807 4008 int r;
5cb5a6ff 4009
034c6ed7
LP
4010 assert(pid >= 0);
4011
e5123725
AZ
4012 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
4013 * considered daemons as they are typically not long running. */
c79ab77c 4014 if (s->type == SERVICE_ONESHOT || (s->control_pid.pid == pid && s->control_command_id != SERVICE_EXEC_START))
e5123725
AZ
4015 clean_mode = EXIT_CLEAN_COMMAND;
4016 else
4017 clean_mode = EXIT_CLEAN_DAEMON;
4018
4019 if (is_clean_exit(code, status, clean_mode, &s->success_status))
f42806df
LP
4020 f = SERVICE_SUCCESS;
4021 else if (code == CLD_EXITED)
4022 f = SERVICE_FAILURE_EXIT_CODE;
4023 else if (code == CLD_KILLED)
4024 f = SERVICE_FAILURE_SIGNAL;
4025 else if (code == CLD_DUMPED)
4026 f = SERVICE_FAILURE_CORE_DUMP;
d06dacd0 4027 else
04499a70 4028 assert_not_reached();
034c6ed7 4029
c79ab77c 4030 if (s->main_pid.pid == pid) {
13bb1ffb
ZJS
4031 /* Clean up the exec_fd event source. We want to do this here, not later in
4032 * service_set_state(), because service_enter_stop_post() calls service_spawn().
4033 * The source owns its end of the pipe, so this will close that too. */
4034 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
4035
db01f8b3
MS
4036 /* Forking services may occasionally move to a new PID.
4037 * As long as they update the PID file before exiting the old
4038 * PID, they're fine. */
db256aab 4039 if (service_load_pid_file(s, false) > 0)
db01f8b3 4040 return;
034c6ed7 4041
c79ab77c 4042 pidref_done(&s->main_pid);
6ea832a2 4043 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
034c6ed7 4044
867b3b7d 4045 if (s->main_command) {
fbeefb45
LP
4046 /* If this is not a forking service than the
4047 * main process got started and hence we copy
4048 * the exit status so that it is recorded both
4049 * as main and as control process exit
4050 * status */
4051
867b3b7d 4052 s->main_command->exec_status = s->main_exec_status;
b708e7ce 4053
3ed0cd26 4054 if (s->main_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 4055 f = SERVICE_SUCCESS;
fbeefb45
LP
4056 } else if (s->exec_command[SERVICE_EXEC_START]) {
4057
4058 /* If this is a forked process, then we should
4059 * ignore the return value if this was
4060 * configured for the starter process */
4061
3ed0cd26 4062 if (s->exec_command[SERVICE_EXEC_START]->flags & EXEC_COMMAND_IGNORE_FAILURE)
fbeefb45 4063 f = SERVICE_SUCCESS;
034c6ed7
LP
4064 }
4065
91bbd9b7 4066 unit_log_process_exit(
5cc2cd1c 4067 u,
abaf5edd 4068 "Main process",
91bbd9b7 4069 service_exec_command_to_string(SERVICE_EXEC_START),
5cc2cd1c 4070 f == SERVICE_SUCCESS,
91bbd9b7 4071 code, status);
f42806df 4072
a0fef983 4073 if (s->result == SERVICE_SUCCESS)
f42806df 4074 s->result = f;
034c6ed7 4075
867b3b7d
LP
4076 if (s->main_command &&
4077 s->main_command->command_next &&
b58aeb70 4078 s->type == SERVICE_ONESHOT &&
f42806df 4079 f == SERVICE_SUCCESS) {
034c6ed7 4080
e78695d4 4081 /* There is another command to execute, so let's do that. */
034c6ed7 4082
f2341e0a 4083 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
f42806df 4084 service_run_next_main(s);
034c6ed7 4085
34e9ba66 4086 } else {
867b3b7d 4087 s->main_command = NULL;
34e9ba66 4088
3bd28bf7
LP
4089 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
4090 * already empty */
596e4470
HC
4091 if (s->exit_type == SERVICE_EXIT_MAIN || cgroup_good(s) <= 0) {
4092 /* The service exited, so the service is officially gone. */
4093 switch (s->state) {
4094
4095 case SERVICE_START_POST:
4096 case SERVICE_RELOAD:
3bd28bf7
LP
4097 case SERVICE_RELOAD_SIGNAL:
4098 case SERVICE_RELOAD_NOTIFY:
dfdeb0b1 4099 case SERVICE_REFRESH_EXTENSIONS:
5162829e 4100 case SERVICE_MOUNTING:
3bd28bf7
LP
4101 /* If neither main nor control processes are running then the current
4102 * state can never exit cleanly, hence immediately terminate the
4103 * service. */
596e4470
HC
4104 if (control_pid_good(s) <= 0)
4105 service_enter_stop(s, f);
4106
4107 /* Otherwise need to wait until the operation is done. */
4108 break;
bbe19f68 4109
596e4470
HC
4110 case SERVICE_STOP:
4111 /* Need to wait until the operation is done. */
4112 break;
bbe19f68 4113
596e4470
HC
4114 case SERVICE_START:
4115 if (s->type == SERVICE_ONESHOT) {
4116 /* This was our main goal, so let's go on */
4117 if (f == SERVICE_SUCCESS)
4118 service_enter_start_post(s);
4119 else
4120 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
4121 break;
3bd28bf7 4122 } else if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD)) {
596e4470
HC
4123 /* Only enter running through a notification, so that the
4124 * SERVICE_START state signifies that no ready notification
4125 * has been received */
4126 if (f != SERVICE_SUCCESS)
4127 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
19dff691 4128 else if (!s->remain_after_exit || service_get_notify_access(s) == NOTIFY_MAIN)
596e4470
HC
4129 /* The service has never been and will never be active */
4130 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
4131 break;
4132 }
7d55e835 4133
596e4470
HC
4134 _fallthrough_;
4135 case SERVICE_RUNNING:
4136 service_enter_running(s, f);
3d474ef7 4137 break;
034c6ed7 4138
596e4470
HC
4139 case SERVICE_STOP_WATCHDOG:
4140 case SERVICE_STOP_SIGTERM:
4141 case SERVICE_STOP_SIGKILL:
5cb5a6ff 4142
596e4470
HC
4143 if (control_pid_good(s) <= 0)
4144 service_enter_stop_post(s, f);
5cb5a6ff 4145
596e4470
HC
4146 /* If there is still a control process, wait for that first */
4147 break;
34e9ba66 4148
596e4470 4149 case SERVICE_STOP_POST:
c1566ef0 4150
596e4470
HC
4151 if (control_pid_good(s) <= 0)
4152 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
c1566ef0 4153
596e4470 4154 break;
c1566ef0 4155
596e4470
HC
4156 case SERVICE_FINAL_WATCHDOG:
4157 case SERVICE_FINAL_SIGTERM:
4158 case SERVICE_FINAL_SIGKILL:
bf108e55 4159
596e4470
HC
4160 if (control_pid_good(s) <= 0)
4161 service_enter_dead(s, f, true);
4162 break;
bf108e55 4163
596e4470
HC
4164 default:
4165 assert_not_reached();
4166 }
1651ce09
MY
4167 } else if (s->exit_type == SERVICE_EXIT_CGROUP && s->state == SERVICE_START &&
4168 !IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD, SERVICE_DBUS))
ef430065
FT
4169 /* If a main process exits very quickly, this function might be executed
4170 * before service_dispatch_exec_io(). Since this function disabled IO events
4171 * to monitor the main process above, we need to update the state here too.
1651ce09
MY
4172 * Let's consider the process is successfully launched and exited, but
4173 * only when we're not expecting a readiness notification or dbus name. */
ef430065 4174 service_enter_start_post(s);
034c6ed7 4175 }
5cb5a6ff 4176
c79ab77c 4177 } else if (s->control_pid.pid == pid) {
58441bc1
ZJS
4178 const char *kind;
4179 bool success;
4180
c79ab77c 4181 pidref_done(&s->control_pid);
34e9ba66 4182
b708e7ce 4183 if (s->control_command) {
8bb2d17d 4184 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 4185
3ed0cd26 4186 if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 4187 f = SERVICE_SUCCESS;
b708e7ce
LP
4188 }
4189
42e6f549
AZ
4190 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
4191 if (s->state == SERVICE_CONDITION) {
4192 if (f == SERVICE_FAILURE_EXIT_CODE && status < 255) {
4193 UNIT(s)->condition_result = false;
4194 f = SERVICE_SKIP_CONDITION;
58441bc1
ZJS
4195 success = true;
4196 } else if (f == SERVICE_SUCCESS) {
42e6f549 4197 UNIT(s)->condition_result = true;
58441bc1
ZJS
4198 success = true;
4199 } else
4200 success = false;
4201
4202 kind = "Condition check process";
4203 } else {
4204 kind = "Control process";
4205 success = f == SERVICE_SUCCESS;
42e6f549
AZ
4206 }
4207
91bbd9b7 4208 unit_log_process_exit(
5cc2cd1c 4209 u,
58441bc1 4210 kind,
91bbd9b7 4211 service_exec_command_to_string(s->control_command_id),
58441bc1 4212 success,
91bbd9b7 4213 code, status);
f42806df 4214
5162829e 4215 if (!IN_SET(s->state, SERVICE_RELOAD, SERVICE_MOUNTING) && s->result == SERVICE_SUCCESS)
f42806df 4216 s->result = f;
034c6ed7 4217
34e9ba66
LP
4218 if (s->control_command &&
4219 s->control_command->command_next &&
f42806df 4220 f == SERVICE_SUCCESS) {
034c6ed7 4221
81006ebb 4222 /* There is another command to execute, so let's do that. */
034c6ed7 4223
f2341e0a 4224 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
f42806df 4225 service_run_next_control(s);
034c6ed7 4226
80876c20 4227 } else {
3bd28bf7 4228 /* No further commands for this step, so let's figure out what to do next */
034c6ed7 4229
a16e1123
LP
4230 s->control_command = NULL;
4231 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
4232
f2341e0a 4233 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
bd982a8b 4234
034c6ed7
LP
4235 switch (s->state) {
4236
31cd5f63
AZ
4237 case SERVICE_CONDITION:
4238 if (f == SERVICE_SUCCESS)
4239 service_enter_start_pre(s);
4240 else
4241 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
4242 break;
4243
034c6ed7 4244 case SERVICE_START_PRE:
f42806df 4245 if (f == SERVICE_SUCCESS)
034c6ed7
LP
4246 service_enter_start(s);
4247 else
c3fda31d 4248 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
4249 break;
4250
4251 case SERVICE_START:
bfba3256
LP
4252 if (s->type != SERVICE_FORKING)
4253 /* Maybe spurious event due to a reload that changed the type? */
4254 break;
034c6ed7 4255
f42806df 4256 if (f != SERVICE_SUCCESS) {
c3fda31d 4257 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3a111838
MS
4258 break;
4259 }
034c6ed7 4260
3a111838 4261 if (s->pid_file) {
f42806df 4262 bool has_start_post;
f42806df 4263
3a111838
MS
4264 /* Let's try to load the pid file here if we can.
4265 * The PID file might actually be created by a START_POST
4266 * script. In that case don't worry if the loading fails. */
f42806df 4267
5d904a6a 4268 has_start_post = s->exec_command[SERVICE_EXEC_START_POST];
f42806df 4269 r = service_load_pid_file(s, !has_start_post);
3a111838
MS
4270 if (!has_start_post && r < 0) {
4271 r = service_demand_pid_file(s);
b13ddbbc 4272 if (r < 0 || cgroup_good(s) == 0)
c3fda31d 4273 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3a111838
MS
4274 break;
4275 }
034c6ed7 4276 } else
783e05d6 4277 service_search_main_pid(s);
034c6ed7 4278
3a111838 4279 service_enter_start_post(s);
034c6ed7
LP
4280 break;
4281
4282 case SERVICE_START_POST:
f42806df 4283 if (f != SERVICE_SUCCESS) {
ce359e98 4284 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2096e009 4285 break;
034c6ed7
LP
4286 }
4287
2096e009 4288 if (s->pid_file) {
f42806df 4289 r = service_load_pid_file(s, true);
2096e009
MS
4290 if (r < 0) {
4291 r = service_demand_pid_file(s);
b13ddbbc 4292 if (r < 0 || cgroup_good(s) == 0)
c35755fb 4293 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2096e009
MS
4294 break;
4295 }
4296 } else
783e05d6 4297 service_search_main_pid(s);
2096e009 4298
f42806df 4299 service_enter_running(s, SERVICE_SUCCESS);
3185a36b 4300 break;
034c6ed7
LP
4301
4302 case SERVICE_RELOAD:
3bd28bf7
LP
4303 case SERVICE_RELOAD_SIGNAL:
4304 case SERVICE_RELOAD_NOTIFY:
7236ce6e
ZJS
4305 if (f == SERVICE_SUCCESS)
4306 if (service_load_pid_file(s, true) < 0)
4307 service_search_main_pid(s);
3185a36b 4308
f42806df 4309 s->reload_result = f;
3bd28bf7 4310
d09df6b9 4311 /* If the last notification we received from the service process indicates
3bd28bf7
LP
4312 * we are still reloading, then don't leave reloading state just yet, just
4313 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4314 * too. */
4315 if (s->notify_state == NOTIFY_RELOADING)
4316 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4317 else
4318 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
4319 break;
4320
dfdeb0b1 4321 case SERVICE_REFRESH_EXTENSIONS:
4322 /* Remounting extensions asynchronously done, proceed to signal */
4323 service_enter_reload_signal_exec(s);
4324 break;
4325
a53e92a1 4326 case SERVICE_MOUNTING:
a6eeca9a 4327 service_live_mount_finish(s, f, SD_BUS_ERROR_FAILED);
a53e92a1
MY
4328
4329 service_enter_running(s, SERVICE_SUCCESS);
4330 break;
4331
034c6ed7 4332 case SERVICE_STOP:
f42806df 4333 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
4334 break;
4335
c87700a1 4336 case SERVICE_STOP_WATCHDOG:
034c6ed7
LP
4337 case SERVICE_STOP_SIGTERM:
4338 case SERVICE_STOP_SIGKILL:
4339 if (main_pid_good(s) <= 0)
f42806df 4340 service_enter_stop_post(s, f);
034c6ed7 4341
846a07b5 4342 /* If there is still a service process around, wait until
034c6ed7
LP
4343 * that one quit, too */
4344 break;
4345
4346 case SERVICE_STOP_POST:
c1566ef0
AZ
4347 if (main_pid_good(s) <= 0)
4348 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
4349 break;
4350
bf760801 4351 case SERVICE_FINAL_WATCHDOG:
034c6ed7
LP
4352 case SERVICE_FINAL_SIGTERM:
4353 case SERVICE_FINAL_SIGKILL:
bf108e55
LP
4354 if (main_pid_good(s) <= 0)
4355 service_enter_dead(s, f, true);
034c6ed7
LP
4356 break;
4357
4c2f5842
LP
4358 case SERVICE_CLEANING:
4359
4360 if (s->clean_result == SERVICE_SUCCESS)
4361 s->clean_result = f;
4362
4363 service_enter_dead(s, SERVICE_SUCCESS, false);
4364 break;
4365
034c6ed7 4366 default:
04499a70 4367 assert_not_reached();
034c6ed7
LP
4368 }
4369 }
5cdabc8d
LP
4370 } else /* Neither control nor main PID? If so, don't notify about anything */
4371 notify_dbus = false;
c4e2ceae
LP
4372
4373 /* Notify clients about changed exit status */
5cdabc8d
LP
4374 if (notify_dbus)
4375 unit_add_to_dbus_queue(u);
034c6ed7
LP
4376}
4377
718db961 4378static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
e9fa1bf7 4379 Service *s = ASSERT_PTR(SERVICE(userdata));
034c6ed7 4380
718db961 4381 assert(source == s->timer_event_source);
034c6ed7
LP
4382
4383 switch (s->state) {
4384
31cd5f63 4385 case SERVICE_CONDITION:
034c6ed7
LP
4386 case SERVICE_START_PRE:
4387 case SERVICE_START:
4388 case SERVICE_START_POST:
bf760801
JK
4389 switch (s->timeout_start_failure_mode) {
4390
4391 case SERVICE_TIMEOUT_TERMINATE:
4392 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", service_state_to_string(s->state));
4393 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4394 break;
4395
4396 case SERVICE_TIMEOUT_ABORT:
4397 log_unit_warning(UNIT(s), "%s operation timed out. Aborting.", service_state_to_string(s->state));
4398 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4399 break;
4400
4401 case SERVICE_TIMEOUT_KILL:
4402 if (s->kill_context.send_sigkill) {
4403 log_unit_warning(UNIT(s), "%s operation timed out. Killing.", service_state_to_string(s->state));
4404 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4405 } else {
4406 log_unit_warning(UNIT(s), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s->state));
4407 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4408 }
4409 break;
4410
4411 default:
04499a70 4412 assert_not_reached();
bf760801 4413 }
034c6ed7
LP
4414 break;
4415
36c16a7c
LP
4416 case SERVICE_RUNNING:
4417 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
4418 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
4419 break;
4420
e2f3b44c 4421 case SERVICE_RELOAD:
3bd28bf7
LP
4422 case SERVICE_RELOAD_SIGNAL:
4423 case SERVICE_RELOAD_NOTIFY:
dfdeb0b1 4424 case SERVICE_REFRESH_EXTENSIONS:
089b64d5 4425 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
e9a4f676 4426 service_kill_control_process(s);
f42806df
LP
4427 s->reload_result = SERVICE_FAILURE_TIMEOUT;
4428 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c
LP
4429 break;
4430
5162829e
LB
4431 case SERVICE_MOUNTING:
4432 log_unit_warning(UNIT(s), "Mount operation timed out. Killing mount process.");
4433 service_kill_control_process(s);
a6eeca9a 4434 service_live_mount_finish(s, SERVICE_FAILURE_TIMEOUT, SD_BUS_ERROR_TIMEOUT);
5162829e
LB
4435 service_enter_running(s, SERVICE_SUCCESS);
4436 break;
4437
034c6ed7 4438 case SERVICE_STOP:
bf760801
JK
4439 switch (s->timeout_stop_failure_mode) {
4440
4441 case SERVICE_TIMEOUT_TERMINATE:
4442 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
4443 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4444 break;
4445
4446 case SERVICE_TIMEOUT_ABORT:
4447 log_unit_warning(UNIT(s), "Stopping timed out. Aborting.");
4448 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4449 break;
4450
4451 case SERVICE_TIMEOUT_KILL:
4452 if (s->kill_context.send_sigkill) {
4453 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
4454 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4455 } else {
4456 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
4457 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4458 }
4459 break;
4460
4461 default:
04499a70 4462 assert_not_reached();
bf760801 4463 }
034c6ed7
LP
4464 break;
4465
c87700a1 4466 case SERVICE_STOP_WATCHDOG:
bf760801
JK
4467 if (s->kill_context.send_sigkill) {
4468 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Killing.");
4469 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4470 } else {
4471 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4472 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4473 }
db2cb23b
UTL
4474 break;
4475
034c6ed7 4476 case SERVICE_STOP_SIGTERM:
bf760801
JK
4477 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4478 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Aborting.");
4479 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4480 } else if (s->kill_context.send_sigkill) {
f2341e0a 4481 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
f42806df 4482 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4483 } else {
f2341e0a 4484 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
f42806df 4485 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
ba035df2
LP
4486 }
4487
034c6ed7
LP
4488 break;
4489
4490 case SERVICE_STOP_SIGKILL:
35b8ca3a 4491 /* Uh, we sent a SIGKILL and it is still not gone?
034c6ed7
LP
4492 * Must be something we cannot kill, so let's just be
4493 * weirded out and continue */
4494
f2341e0a 4495 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
f42806df 4496 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
4497 break;
4498
4499 case SERVICE_STOP_POST:
bf760801
JK
4500 switch (s->timeout_stop_failure_mode) {
4501
4502 case SERVICE_TIMEOUT_TERMINATE:
4503 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
4504 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4505 break;
4506
4507 case SERVICE_TIMEOUT_ABORT:
4508 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Aborting.");
4509 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4510 break;
4511
4512 case SERVICE_TIMEOUT_KILL:
4513 if (s->kill_context.send_sigkill) {
4514 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Killing.");
4515 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4516 } else {
4517 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4518 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4519 }
4520 break;
4521
4522 default:
04499a70 4523 assert_not_reached();
bf760801 4524 }
034c6ed7
LP
4525 break;
4526
bf760801 4527 case SERVICE_FINAL_WATCHDOG:
4819ff03 4528 if (s->kill_context.send_sigkill) {
bf760801 4529 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Killing.");
f42806df 4530 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4531 } else {
bf760801
JK
4532 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4533 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4534 }
4535 break;
4536
4537 case SERVICE_FINAL_SIGTERM:
4538 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4539 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Aborting.");
4540 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4541 } else if (s->kill_context.send_sigkill) {
4542 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Killing.");
4543 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4544 } else {
4545 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
f42806df 4546 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
ba035df2
LP
4547 }
4548
034c6ed7
LP
4549 break;
4550
4551 case SERVICE_FINAL_SIGKILL:
f2341e0a 4552 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
f42806df 4553 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
034c6ed7
LP
4554 break;
4555
4556 case SERVICE_AUTO_RESTART:
5291f26d 4557 if (s->restart_usec > 0)
868f7d36 4558 log_unit_debug(UNIT(s),
be1adc27 4559 "Service restart interval %s expired, scheduling restart.",
5171356e 4560 FORMAT_TIMESPAN(service_restart_usec_next(s), USEC_PER_SEC));
5291f26d 4561 else
868f7d36
ZJS
4562 log_unit_debug(UNIT(s),
4563 "Service has no hold-off time (RestartSec=0), scheduling restart.");
5ce6e7f5 4564
1391f149 4565 service_enter_restart(s, /* shortcut = */ false);
034c6ed7
LP
4566 break;
4567
4c2f5842
LP
4568 case SERVICE_CLEANING:
4569 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
4570
4571 if (s->clean_result == SERVICE_SUCCESS)
4572 s->clean_result = SERVICE_FAILURE_TIMEOUT;
4573
4574 service_enter_signal(s, SERVICE_FINAL_SIGKILL, 0);
4575 break;
4576
034c6ed7 4577 default:
04499a70 4578 assert_not_reached();
034c6ed7 4579 }
718db961
LP
4580
4581 return 0;
4582}
4583
4584static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
e9fa1bf7 4585 Service *s = ASSERT_PTR(SERVICE(userdata));
2787d83c 4586 usec_t watchdog_usec;
718db961 4587
718db961
LP
4588 assert(source == s->watchdog_event_source);
4589
2787d83c
M
4590 watchdog_usec = service_get_watchdog_usec(s);
4591
2a12e32e
JK
4592 if (UNIT(s)->manager->service_watchdogs) {
4593 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
5291f26d 4594 FORMAT_TIMESPAN(watchdog_usec, 1));
8bb2d17d 4595
c87700a1 4596 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
2a12e32e
JK
4597 } else
4598 log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
5291f26d 4599 FORMAT_TIMESPAN(watchdog_usec, 1));
842129f5 4600
718db961 4601 return 0;
5cb5a6ff
LP
4602}
4603
3a45fdfc 4604static void service_force_watchdog(Service *s) {
e9fa1bf7
MY
4605 assert(s);
4606
3a45fdfc
MY
4607 if (!UNIT(s)->manager->service_watchdogs)
4608 return;
4609
4610 log_unit_error(UNIT(s), "Watchdog request (last status: %s)!",
4611 s->status_text ?: "<unset>");
4612
4613 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
4614}
4615
19eccb76 4616static bool service_notify_message_authorized(Service *s, PidRef *pid) {
e3285237 4617 assert(s);
19eccb76 4618 assert(pidref_is_set(pid));
8c47c732 4619
d3d0e361 4620 switch (service_get_notify_access(s)) {
19dff691 4621
d3d0e361 4622 case NOTIFY_NONE:
5734d5d0 4623 /* Warn level only if no notifications are expected */
19eccb76 4624 log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception is disabled", pid->pid);
e3285237 4625 return false;
e3285237 4626
d3d0e361
MY
4627 case NOTIFY_ALL:
4628 return true;
4629
4630 case NOTIFY_MAIN:
19eccb76 4631 if (pidref_equal(pid, &s->main_pid))
d3d0e361
MY
4632 return true;
4633
c79ab77c 4634 if (pidref_is_set(&s->main_pid))
19eccb76 4635 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);
336c6e46 4636 else
19eccb76 4637 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);
e3285237
LP
4638
4639 return false;
e3285237 4640
d3d0e361 4641 case NOTIFY_EXEC:
19eccb76 4642 if (pidref_equal(pid, &s->main_pid) || pidref_equal(pid, &s->control_pid))
d3d0e361
MY
4643 return true;
4644
c79ab77c 4645 if (pidref_is_set(&s->main_pid) && pidref_is_set(&s->control_pid))
5734d5d0 4646 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,
19eccb76 4647 pid->pid, s->main_pid.pid, s->control_pid.pid);
c79ab77c 4648 else if (pidref_is_set(&s->main_pid))
19eccb76 4649 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);
c79ab77c 4650 else if (pidref_is_set(&s->control_pid))
19eccb76 4651 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);
6375bd20 4652 else
19eccb76 4653 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);
e3285237
LP
4654
4655 return false;
9711848f 4656
d3d0e361
MY
4657 default:
4658 assert_not_reached();
4659 }
e3285237
LP
4660}
4661
695323d9
MY
4662static int service_notify_message_parse_new_pid(
4663 Unit *u,
4664 char * const *tags,
4665 FDSet *fds,
4666 PidRef *ret) {
4667
4668 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
4669 const char *e;
4670 int r;
4671
4672 assert(u);
4673 assert(ret);
4674
4675 /* MAINPIDFD=1 always takes precedence */
4676 if (strv_contains(tags, "MAINPIDFD=1")) {
4677 unsigned n_fds = fdset_size(fds);
4678 if (n_fds != 1)
4679 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(EINVAL),
4680 "Got MAINPIDFD=1 with %s fd, ignoring.", n_fds == 0 ? "no" : "more than one");
4681
4682 r = pidref_set_pidfd_consume(&pidref, ASSERT_FD(fdset_steal_first(fds)));
4683 if (r < 0)
4684 return log_unit_warning_errno(u, r, "Failed to create reference to received new main pidfd: %m");
4685
4686 goto finish;
4687 }
4688
4689 e = strv_find_startswith(tags, "MAINPID=");
4690 if (!e) {
4691 *ret = PIDREF_NULL;
4692 return 0;
4693 }
4694
4695 r = pidref_set_pidstr(&pidref, e);
4696 if (r < 0)
4697 return log_unit_warning_errno(u, r, "Failed to parse MAINPID=%s field in notification message, ignoring: %m", e);
4698
4699 e = strv_find_startswith(tags, "MAINPIDFDID=");
4700 if (!e)
4701 goto finish;
4702
4703 uint64_t pidfd_id;
4704
4705 r = safe_atou64(e, &pidfd_id);
4706 if (r < 0)
4707 return log_unit_warning_errno(u, r, "Failed to parse MAINPIDFDID= in notification message, refusing: %s", e);
4708
4709 r = pidref_acquire_pidfd_id(&pidref);
4710 if (r < 0) {
4711 if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
4712 log_unit_warning_errno(u, r,
4713 "Failed to acquire pidfd id of process " PID_FMT ", not validating MAINPIDFDID=%" PRIu64 ": %m",
4714 pidref.pid, pidfd_id);
4715 goto finish;
4716 }
4717
4718 if (pidref.fd_id != pidfd_id)
4719 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(ESRCH),
4720 "PIDFD ID of process " PID_FMT " (%" PRIu64 ") mismatches with received MAINPIDFDID=%" PRIu64 ", not changing main PID.",
4721 pidref.pid, pidref.fd_id, pidfd_id);
4722
4723finish:
4724 *ret = TAKE_PIDREF(pidref);
4725 return 1;
4726}
4727
db256aab
LP
4728static void service_notify_message(
4729 Unit *u,
19eccb76 4730 PidRef *pidref,
db256aab 4731 const struct ucred *ucred,
fcee2755 4732 char * const *tags,
db256aab
LP
4733 FDSet *fds) {
4734
b7a22068 4735 Service *s = ASSERT_PTR(SERVICE(u));
db256aab 4736 int r;
e3285237 4737
19eccb76 4738 assert(pidref_is_set(pidref));
db256aab 4739 assert(ucred);
e3285237 4740
19eccb76 4741 if (!service_notify_message_authorized(s, pidref))
e3285237
LP
4742 return;
4743
f1d34068 4744 if (DEBUG_LOGGING) {
b7a22068 4745 _cleanup_free_ char *cc = strv_join(tags, ", ");
19eccb76 4746 log_unit_debug(u, "Got notification message from PID "PID_FMT": %s", pidref->pid, empty_to_na(cc));
9711848f 4747 }
c952c6ec 4748
b7a22068
MY
4749 usec_t monotonic_usec = USEC_INFINITY;
4750 bool notify_dbus = false;
4751 const char *e;
4752
695323d9
MY
4753 /* Interpret MAINPID= (+ MAINPIDFDID=) / MAINPIDFD=1 */
4754 _cleanup_(pidref_done) PidRef new_main_pid = PIDREF_NULL;
31197c68 4755
695323d9
MY
4756 r = service_notify_message_parse_new_pid(u, tags, fds, &new_main_pid);
4757 if (r > 0 &&
4758 IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING,
dfdeb0b1 4759 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS,
695323d9
MY
4760 SERVICE_STOP, SERVICE_STOP_SIGTERM) &&
4761 (!s->main_pid_known || !pidref_equal(&new_main_pid, &s->main_pid))) {
db256aab 4762
695323d9
MY
4763 r = service_is_suitable_main_pid(s, &new_main_pid, LOG_WARNING);
4764 if (r == 0) {
4765 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
db256aab 4766
695323d9
MY
4767 if (ucred->uid == 0) {
4768 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);
4769 r = 1;
4770 } else
4771 log_unit_warning(u, "New main PID "PID_FMT" does not belong to service, refusing.", new_main_pid.pid);
4772 }
4773 if (r > 0) {
4774 (void) service_set_main_pidref(s, TAKE_PIDREF(new_main_pid), /* start_timestamp = */ NULL);
cdc2af3e 4775
695323d9
MY
4776 r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
4777 if (r < 0)
4778 log_unit_warning_errno(UNIT(s), r, "Failed to watch new main PID "PID_FMT" for service: %m", s->main_pid.pid);
cdc2af3e 4779
695323d9 4780 notify_dbus = true;
8c47c732
LP
4781 }
4782 }
4783
3bd28bf7
LP
4784 /* Parse MONOTONIC_USEC= */
4785 e = strv_find_startswith(tags, "MONOTONIC_USEC=");
4786 if (e) {
4787 r = safe_atou64(e, &monotonic_usec);
4788 if (r < 0)
4789 log_unit_warning_errno(u, r, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e);
4790 }
308d72dc 4791
3bd28bf7
LP
4792 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4793 if (strv_contains(tags, "STOPPING=1")) {
4794 s->notify_state = NOTIFY_STOPPING;
308d72dc 4795
dfdeb0b1 4796 if (IN_SET(s->state, SERVICE_RUNNING, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_REFRESH_EXTENSIONS))
3bd28bf7 4797 service_enter_stop_by_notify(s);
308d72dc 4798
3bd28bf7 4799 notify_dbus = true;
308d72dc 4800
3bd28bf7 4801 } else if (strv_contains(tags, "READY=1")) {
308d72dc 4802
3bd28bf7 4803 s->notify_state = NOTIFY_READY;
308d72dc 4804
c337a130
MY
4805 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4806 * immediately finished reloading. */
4807 if (strv_contains(tags, "RELOADING=1")) {
4808 if (s->state == SERVICE_RELOAD_SIGNAL &&
4809 monotonic_usec != USEC_INFINITY &&
4810 monotonic_usec >= s->reload_begin_usec)
4811 /* Valid Type=notify-reload protocol? Then we're all good. */
4812 service_enter_running(s, SERVICE_SUCCESS);
4813
4814 else if (s->state == SERVICE_RUNNING) {
4815 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4816
4817 /* Propagate a reload explicitly for plain RELOADING=1 (semantically equivalent to
dfdeb0b1 4818 * service_enter_reload_mounting() call in below) */
c337a130
MY
4819 r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
4820 if (r < 0)
4821 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s",
4822 bus_error_message(&error, r));
4823 }
4824 }
4825
4826 /* Type=notify(-reload) services inform us about completed initialization with READY=1 */
3bd28bf7
LP
4827 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
4828 s->state == SERVICE_START)
4829 service_enter_start_post(s);
308d72dc 4830
3bd28bf7
LP
4831 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4832 if (s->state == SERVICE_RELOAD_NOTIFY)
4833 service_enter_running(s, SERVICE_SUCCESS);
308d72dc 4834
3bd28bf7
LP
4835 notify_dbus = true;
4836
4837 } else if (strv_contains(tags, "RELOADING=1")) {
4838
4839 s->notify_state = NOTIFY_RELOADING;
4840
4841 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4842 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4843 * reload is done. Note that we insist on a timestamp being sent along here, so that
4844 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4845 if (s->state == SERVICE_RELOAD_SIGNAL &&
4846 monotonic_usec != USEC_INFINITY &&
4847 monotonic_usec >= s->reload_begin_usec)
4848 /* Note, we don't call service_enter_reload_by_notify() here, because we
2257be13 4849 * don't need reload propagation nor do we want to restart the timeout. */
3bd28bf7
LP
4850 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4851
4852 if (s->state == SERVICE_RUNNING)
4853 service_enter_reload_by_notify(s);
4854
4855 notify_dbus = true;
8c47c732
LP
4856 }
4857
4858 /* Interpret STATUS= */
28849dba 4859 e = strv_find_startswith(tags, "STATUS=");
7f110ff9 4860 if (e) {
28849dba 4861 _cleanup_free_ char *t = NULL;
8c47c732 4862
28849dba 4863 if (!isempty(e)) {
3eac1bca
LP
4864 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4865 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4866 if (strlen(e) > STATUS_TEXT_MAX)
4867 log_unit_warning(u, "Status message overly long (%zu > %u), ignoring.", strlen(e), STATUS_TEXT_MAX);
4868 else if (!utf8_is_valid(e))
4869 log_unit_warning(u, "Status message in notification message is not UTF-8 clean, ignoring.");
28849dba 4870 else {
28849dba
LP
4871 t = strdup(e);
4872 if (!t)
9c025022 4873 log_oom_warning();
3a2776bc 4874 }
28849dba 4875 }
8c47c732 4876
30b5275a 4877 if (!streq_ptr(s->status_text, t)) {
3b319885 4878 free_and_replace(s->status_text, t);
30b5275a 4879 notify_dbus = true;
28849dba 4880 }
8c47c732 4881 }
842129f5 4882
19dff691
MY
4883 /* Interpret NOTIFYACCESS= */
4884 e = strv_find_startswith(tags, "NOTIFYACCESS=");
4885 if (e) {
4886 NotifyAccess notify_access;
4887
4888 notify_access = notify_access_from_string(e);
4889 if (notify_access < 0)
4890 log_unit_warning_errno(u, notify_access,
4891 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e);
4892
4893 /* We don't need to check whether the new access mode is more strict than what is
4894 * already in use, since only the privileged process is allowed to change it
4895 * in the first place. */
4896 if (service_get_notify_access(s) != notify_access) {
4897 service_override_notify_access(s, notify_access);
4898 notify_dbus = true;
4899 }
4900 }
4901
4774e357 4902 /* Interpret ERRNO= */
28849dba 4903 e = strv_find_startswith(tags, "ERRNO=");
4774e357
MAA
4904 if (e) {
4905 int status_errno;
4906
2fa40742
LP
4907 status_errno = parse_errno(e);
4908 if (status_errno < 0)
4909 log_unit_warning_errno(u, status_errno,
5e1ee764 4910 "Failed to parse ERRNO= field value '%s' in notification message: %m", e);
2fa40742
LP
4911 else if (s->status_errno != status_errno) {
4912 s->status_errno = status_errno;
4913 notify_dbus = true;
4774e357
MAA
4914 }
4915 }
4916
9c025022
MY
4917 static const struct {
4918 const char *tag;
4919 size_t status_offset;
4920 } status_errors[] = {
4921 { "BUSERROR=", offsetof(Service, status_bus_error) },
4922 { "VARLINKERROR=", offsetof(Service, status_varlink_error) },
4923 };
4924
4925 FOREACH_ELEMENT(i, status_errors) {
4926 e = strv_find_startswith(tags, i->tag);
4927 if (!e)
4928 continue;
4929
4930 char **status_error = (char**) ((uint8_t*) s + i->status_offset);
4931
4932 e = empty_to_null(e);
4933
4934 if (e && !string_is_safe_ascii(e)) {
4935 _cleanup_free_ char *escaped = cescape(e);
4936 log_unit_warning(u, "Got invalid %s string, ignoring: %s", i->tag, strna(escaped));
4937 } else if (free_and_strdup_warn(status_error, e) > 0)
4938 notify_dbus = true;
4939 }
4940
a327431b
DB
4941 /* Interpret EXTEND_TIMEOUT= */
4942 e = strv_find_startswith(tags, "EXTEND_TIMEOUT_USEC=");
4943 if (e) {
4944 usec_t extend_timeout_usec;
9c025022 4945
a327431b
DB
4946 if (safe_atou64(e, &extend_timeout_usec) < 0)
4947 log_unit_warning(u, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e);
4948 else
4949 service_extend_timeout(s, extend_timeout_usec);
4950 }
4951
6f285378 4952 /* Interpret WATCHDOG= */
99b43caf
JK
4953 e = strv_find_startswith(tags, "WATCHDOG=");
4954 if (e) {
4955 if (streq(e, "1"))
4956 service_reset_watchdog(s);
4957 else if (streq(e, "trigger"))
4958 service_force_watchdog(s);
4959 else
4960 log_unit_warning(u, "Passed WATCHDOG= field is invalid, ignoring.");
4961 }
c4e2ceae 4962
c45d11cb
LP
4963 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
4964 if (e) {
4965 usec_t watchdog_override_usec;
4966 if (safe_atou64(e, &watchdog_override_usec) < 0)
4967 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
4968 else
95d0d8ed 4969 service_override_watchdog_timeout(s, watchdog_override_usec);
c45d11cb
LP
4970 }
4971
406aeb5d
MY
4972 /* Interpret RESTART_RESET=1 */
4973 if (strv_contains(tags, "RESTART_RESET=1") && IN_SET(s->state, SERVICE_RUNNING, SERVICE_STOP)) {
4974 log_unit_struct(u, LOG_NOTICE,
4975 LOG_UNIT_MESSAGE(u, "Got RESTART_RESET=1, resetting restart counter from %u.", s->n_restarts),
3cf6a3a3 4976 LOG_ITEM("N_RESTARTS=0"),
406aeb5d
MY
4977 LOG_UNIT_INVOCATION_ID(u));
4978
4979 s->n_restarts = 0;
4980 notify_dbus = true;
4981 }
4982
e78ee06d
LP
4983 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4984 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4985 * fds, but optional when pushing in new fds, for compatibility reasons. */
d29cc4d6 4986 if (strv_contains(tags, "FDSTOREREMOVE=1")) {
e78ee06d
LP
4987 const char *name;
4988
4989 name = strv_find_startswith(tags, "FDNAME=");
4990 if (!name || !fdname_is_valid(name))
4991 log_unit_warning(u, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4992 else
4993 service_remove_fd_store(s, name);
4994
d29cc4d6 4995 } else if (strv_contains(tags, "FDSTORE=1")) {
8dd4c05b
LP
4996 const char *name;
4997
4998 name = strv_find_startswith(tags, "FDNAME=");
4999 if (name && !fdname_is_valid(name)) {
5000 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
5001 name = NULL;
5002 }
5003
cb5a46b8 5004 (void) service_add_fd_store_set(s, fds, name, !strv_contains(tags, "FDPOLL=0"));
8dd4c05b 5005 }
a354329f 5006
c4e2ceae 5007 /* Notify clients about changed status or main pid */
30b5275a
LP
5008 if (notify_dbus)
5009 unit_add_to_dbus_queue(u);
8c47c732
LP
5010}
5011
3c1d1ca1
LP
5012static void service_handoff_timestamp(
5013 Unit *u,
5014 const struct ucred *ucred,
5015 const dual_timestamp *ts) {
5016
5017 Service *s = ASSERT_PTR(SERVICE(u));
5018
5019 assert(ucred);
5020 assert(ts);
5021
5022 if (s->main_pid.pid == ucred->pid) {
5023 if (s->main_command)
5024 exec_status_handoff(&s->main_command->exec_status, ucred, ts);
5025
5026 exec_status_handoff(&s->main_exec_status, ucred, ts);
5027 } else if (s->control_pid.pid == ucred->pid && s->control_command)
5028 exec_status_handoff(&s->control_command->exec_status, ucred, ts);
5029 else
5030 return;
5031
5032 unit_add_to_dbus_queue(u);
5033}
5034
406f1775
DDM
5035static void service_notify_pidref(Unit *u, PidRef *parent_pidref, PidRef *child_pidref) {
5036 Service *s = ASSERT_PTR(SERVICE(u));
5037 int r;
5038
5039 assert(pidref_is_set(parent_pidref));
5040 assert(pidref_is_set(child_pidref));
5041
5042 if (pidref_equal(&s->main_pid, parent_pidref)) {
5043 r = service_set_main_pidref(s, TAKE_PIDREF(*child_pidref), /* start_timestamp = */ NULL);
5044 if (r < 0)
5045 return (void) log_unit_warning_errno(u, r, "Failed to set new main pid: %m");
5046
5047 /* Since the child process is PID 1 in a new PID namespace, it must be exclusive to this unit. */
5048 r = unit_watch_pidref(u, &s->main_pid, /* exclusive= */ true);
5049 if (r < 0)
5050 log_unit_warning_errno(u, r, "Failed to watch new main PID " PID_FMT ": %m", s->main_pid.pid);
5051 } else if (pidref_equal(&s->control_pid, parent_pidref)) {
5052 service_unwatch_control_pid(s);
5053 s->control_pid = TAKE_PIDREF(*child_pidref);
5054
5055 r = unit_watch_pidref(u, &s->control_pid, /* exclusive= */ true);
5056 if (r < 0)
5057 log_unit_warning_errno(u, r, "Failed to watch new control PID " PID_FMT ": %m", s->control_pid.pid);
5058 } else
5059 return (void) log_unit_debug(u, "Parent process " PID_FMT " does not match main or control processes, ignoring.", parent_pidref->pid);
5060
5061 unit_add_to_dbus_queue(u);
5062}
5063
7a7821c8 5064static int service_get_timeout(Unit *u, usec_t *timeout) {
e9fa1bf7 5065 Service *s = ASSERT_PTR(SERVICE(u));
7a7821c8 5066 uint64_t t;
68db7a3b
ZJS
5067 int r;
5068
e9fa1bf7
MY
5069 assert(timeout);
5070
68db7a3b
ZJS
5071 if (!s->timer_event_source)
5072 return 0;
5073
7a7821c8 5074 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
5075 if (r < 0)
5076 return r;
7a7821c8
LP
5077 if (t == USEC_INFINITY)
5078 return 0;
68db7a3b 5079
7a7821c8 5080 *timeout = t;
68db7a3b
ZJS
5081 return 1;
5082}
5083
f5a9d2ee 5084static usec_t service_get_timeout_start_usec(Unit *u) {
e9fa1bf7 5085 Service *s = ASSERT_PTR(SERVICE(u));
f5a9d2ee 5086 return s->timeout_start_usec;
5087}
5088
e39eb045
LP
5089static bool pick_up_pid_from_bus_name(Service *s) {
5090 assert(s);
5091
5092 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
5093
c79ab77c 5094 return !pidref_is_set(&s->main_pid) &&
e39eb045
LP
5095 IN_SET(s->state,
5096 SERVICE_START,
5097 SERVICE_START_POST,
5098 SERVICE_RUNNING,
3bd28bf7
LP
5099 SERVICE_RELOAD,
5100 SERVICE_RELOAD_SIGNAL,
5162829e 5101 SERVICE_RELOAD_NOTIFY,
dfdeb0b1 5102 SERVICE_REFRESH_EXTENSIONS,
5162829e 5103 SERVICE_MOUNTING);
e39eb045
LP
5104}
5105
5106static int bus_name_pid_lookup_callback(sd_bus_message *reply, void *userdata, sd_bus_error *ret_error) {
e9fa1bf7 5107 Service *s = ASSERT_PTR(SERVICE(userdata));
495e75ed 5108 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
e39eb045 5109 const sd_bus_error *e;
e39eb045 5110 uint32_t pid;
e39eb045
LP
5111 int r;
5112
5113 assert(reply);
e39eb045 5114
e39eb045
LP
5115 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
5116
5117 if (!s->bus_name || !pick_up_pid_from_bus_name(s))
5118 return 1;
5119
5120 e = sd_bus_message_get_error(reply);
5121 if (e) {
5122 r = sd_bus_error_get_errno(e);
1e8f0bee 5123 log_unit_warning_errno(UNIT(s), r, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e, r));
e39eb045
LP
5124 return 1;
5125 }
5126
5127 r = sd_bus_message_read(reply, "u", &pid);
5128 if (r < 0) {
5129 bus_log_parse_error(r);
5130 return 1;
5131 }
5132
495e75ed
LP
5133 r = pidref_set_pid(&pidref, pid);
5134 if (r < 0) {
1e8f0bee 5135 log_unit_debug_errno(UNIT(s), r, "GetConnectionUnixProcessID() returned invalid PID: %m");
e39eb045
LP
5136 return 1;
5137 }
5138
e9fa1bf7 5139 log_unit_debug(UNIT(s), "D-Bus name %s is now owned by process " PID_FMT, s->bus_name, pidref.pid);
e39eb045 5140
7e0e6b50 5141 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref), /* start_timestamp = */ NULL);
495e75ed 5142 (void) unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
e39eb045
LP
5143 return 1;
5144}
5145
fc67a943 5146static void service_bus_name_owner_change(Unit *u, const char *new_owner) {
e9fa1bf7 5147 Service *s = ASSERT_PTR(SERVICE(u));
718db961 5148 int r;
05e343b7 5149
fc67a943
LP
5150 if (new_owner)
5151 log_unit_debug(u, "D-Bus name %s now owned by %s", s->bus_name, new_owner);
05e343b7 5152 else
fc67a943 5153 log_unit_debug(u, "D-Bus name %s now not owned by anyone.", s->bus_name);
05e343b7 5154
d7a0f1f4 5155 s->bus_name_good = new_owner;
05e343b7
LP
5156
5157 if (s->type == SERVICE_DBUS) {
029df9ed 5158 /* service_enter_running() will figure out what to do */
05e343b7 5159 if (s->state == SERVICE_RUNNING)
f42806df 5160 service_enter_running(s, SERVICE_SUCCESS);
05e343b7
LP
5161 else if (s->state == SERVICE_START && new_owner)
5162 service_enter_start_post(s);
5163
e39eb045 5164 } else if (new_owner && pick_up_pid_from_bus_name(s)) {
05e343b7 5165
718db961 5166 /* Try to acquire PID from bus service */
05e343b7 5167
e39eb045
LP
5168 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
5169
5170 r = sd_bus_call_method_async(
5171 u->manager->api_bus,
5172 &s->bus_name_pid_lookup_slot,
5173 "org.freedesktop.DBus",
5174 "/org/freedesktop/DBus",
5175 "org.freedesktop.DBus",
5176 "GetConnectionUnixProcessID",
5177 bus_name_pid_lookup_callback,
5178 s,
5179 "s",
5180 s->bus_name);
5181 if (r < 0)
1e8f0bee 5182 log_unit_debug_errno(u, r, "Failed to request owner PID of service name, ignoring: %m");
7400b9d2 5183 }
05e343b7
LP
5184}
5185
3fabebf4
LP
5186int service_set_socket_fd(
5187 Service *s,
5188 int fd,
5189 Socket *sock,
82bdb3ed 5190 SocketPeer *peer, /* reference to object is donated to us on success */
3fabebf4
LP
5191 bool selinux_context_net) {
5192
5193 _cleanup_free_ char *peer_text = NULL;
79a98c60 5194 int r;
57020a3a 5195
4f2d528d
LP
5196 assert(s);
5197 assert(fd >= 0);
23908d84 5198 assert(sock);
4f2d528d 5199
7f2fbbff
LP
5200 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
5201 * to be configured. We take ownership of the passed fd on success. */
4f2d528d 5202
1124fe6f 5203 if (UNIT(s)->load_state != UNIT_LOADED)
4f2d528d
LP
5204 return -EINVAL;
5205
5206 if (s->socket_fd >= 0)
5207 return -EBUSY;
5208
3fabebf4
LP
5209 assert(!s->socket_peer);
5210
b9c1883a 5211 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4f2d528d
LP
5212 return -EAGAIN;
5213
3fabebf4 5214 if (getpeername_pretty(fd, true, &peer_text) >= 0) {
79a98c60
LP
5215
5216 if (UNIT(s)->description) {
c2b2df60 5217 _cleanup_free_ char *a = NULL;
79a98c60 5218
3fabebf4 5219 a = strjoin(UNIT(s)->description, " (", peer_text, ")");
79a98c60
LP
5220 if (!a)
5221 return -ENOMEM;
5222
5223 r = unit_set_description(UNIT(s), a);
5224 } else
3fabebf4 5225 r = unit_set_description(UNIT(s), peer_text);
79a98c60
LP
5226 if (r < 0)
5227 return r;
5228 }
5229
23908d84 5230 r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_TRIGGERED_BY, UNIT(sock), false, UNIT_DEPENDENCY_IMPLICIT);
7f2fbbff 5231 if (r < 0)
23908d84
MY
5232 return log_unit_debug_errno(UNIT(s), r,
5233 "Failed to add After=/TriggeredBy= dependencies on socket unit: %m");
7f2fbbff 5234
4f2d528d 5235 s->socket_fd = fd;
d6a911e9 5236 s->socket_peer = peer;
16115b0a 5237 s->socket_fd_selinux_context_net = selinux_context_net;
6cf6bbc2 5238
7f7d01ed 5239 unit_ref_set(&s->accept_socket, UNIT(s), UNIT(sock));
7f2fbbff 5240 return 0;
4f2d528d
LP
5241}
5242
fdf20a31 5243static void service_reset_failed(Unit *u) {
e9fa1bf7 5244 Service *s = ASSERT_PTR(SERVICE(u));
5632e374 5245
fdf20a31 5246 if (s->state == SERVICE_FAILED)
b9c1883a 5247 service_set_state(s, service_determine_dead_state(s));
5632e374 5248
f42806df
LP
5249 s->result = SERVICE_SUCCESS;
5250 s->reload_result = SERVICE_SUCCESS;
5162829e 5251 s->live_mount_result = SERVICE_SUCCESS;
a53e92a1 5252 s->clean_result = SERVICE_SUCCESS;
7a0019d3 5253 s->n_restarts = 0;
5632e374
LP
5254}
5255
3e22239d
YW
5256static PidRef* service_main_pid(Unit *u, bool *ret_is_alien) {
5257 Service *s = ASSERT_PTR(SERVICE(u));
5258
5259 if (ret_is_alien)
5260 *ret_is_alien = s->main_pid_alien;
5261
5262 return &s->main_pid;
291d565a
LP
5263}
5264
37eb258e
LP
5265static PidRef* service_control_pid(Unit *u) {
5266 return &ASSERT_PTR(SERVICE(u))->control_pid;
291d565a
LP
5267}
5268
bb2c7685 5269static bool service_needs_console(Unit *u) {
e9fa1bf7 5270 Service *s = ASSERT_PTR(SERVICE(u));
bb2c7685
LP
5271
5272 /* We provide our own implementation of this here, instead of relying of the generic implementation
5273 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
5274
5275 if (!exec_context_may_touch_console(&s->exec_context))
5276 return false;
5277
5278 return IN_SET(s->state,
31cd5f63 5279 SERVICE_CONDITION,
bb2c7685
LP
5280 SERVICE_START_PRE,
5281 SERVICE_START,
5282 SERVICE_START_POST,
5283 SERVICE_RUNNING,
5284 SERVICE_RELOAD,
3bd28bf7
LP
5285 SERVICE_RELOAD_SIGNAL,
5286 SERVICE_RELOAD_NOTIFY,
dfdeb0b1 5287 SERVICE_REFRESH_EXTENSIONS,
5162829e 5288 SERVICE_MOUNTING,
bb2c7685 5289 SERVICE_STOP,
c87700a1 5290 SERVICE_STOP_WATCHDOG,
bb2c7685
LP
5291 SERVICE_STOP_SIGTERM,
5292 SERVICE_STOP_SIGKILL,
5293 SERVICE_STOP_POST,
bf760801 5294 SERVICE_FINAL_WATCHDOG,
bb2c7685
LP
5295 SERVICE_FINAL_SIGTERM,
5296 SERVICE_FINAL_SIGKILL);
5297}
5298
7af67e9a 5299static int service_exit_status(Unit *u) {
e9fa1bf7 5300 Service *s = ASSERT_PTR(SERVICE(u));
7af67e9a
LP
5301
5302 if (s->main_exec_status.pid <= 0 ||
5303 !dual_timestamp_is_set(&s->main_exec_status.exit_timestamp))
5304 return -ENODATA;
5305
5306 if (s->main_exec_status.code != CLD_EXITED)
5307 return -EBADE;
5308
5309 return s->main_exec_status.status;
5310}
5311
5e1669ff 5312static const char* service_status_text(Unit *u) {
e9fa1bf7 5313 Service *s = ASSERT_PTR(SERVICE(u));
5e1669ff
ZJS
5314
5315 return s->status_text;
5316}
5317
4c2f5842 5318static int service_clean(Unit *u, ExecCleanMask mask) {
e9fa1bf7 5319 Service *s = ASSERT_PTR(SERVICE(u));
4c2f5842 5320 _cleanup_strv_free_ char **l = NULL;
4fb8f1e8 5321 bool may_clean_fdstore = false;
4c2f5842
LP
5322 int r;
5323
4c2f5842
LP
5324 assert(mask != 0);
5325
4fb8f1e8 5326 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4c2f5842
LP
5327 return -EBUSY;
5328
4fb8f1e8 5329 /* Determine if there's anything we could potentially clean */
4c2f5842
LP
5330 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
5331 if (r < 0)
5332 return r;
5333
4fb8f1e8
LP
5334 if (mask & EXEC_CLEAN_FDSTORE)
5335 may_clean_fdstore = s->n_fd_store > 0 || s->n_fd_store_max > 0;
5336
5337 if (strv_isempty(l) && !may_clean_fdstore)
5338 return -EUNATCH; /* Nothing to potentially clean */
5339
5340 /* Let's clean the stuff we can clean quickly */
5341 if (may_clean_fdstore)
5342 service_release_fd_store(s);
5343
5344 /* If we are done, leave quickly */
5345 if (strv_isempty(l)) {
5346 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
5347 service_set_state(s, SERVICE_DEAD);
5348 return 0;
5349 }
4c2f5842 5350
4fb8f1e8 5351 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4c2f5842
LP
5352 service_unwatch_control_pid(s);
5353 s->clean_result = SERVICE_SUCCESS;
5354 s->control_command = NULL;
5355 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
5356
e5d6dcce 5357 r = service_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
10691b9e
LP
5358 if (r < 0) {
5359 log_unit_warning_errno(u, r, "Failed to install timer: %m");
4c2f5842 5360 goto fail;
10691b9e 5361 }
4c2f5842 5362
4775b55d 5363 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
10691b9e
LP
5364 if (r < 0) {
5365 log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
c79ab77c 5366 goto fail;
10691b9e 5367 }
4c2f5842 5368
c79ab77c 5369 service_set_state(s, SERVICE_CLEANING);
4c2f5842
LP
5370 return 0;
5371
5372fail:
4c2f5842 5373 s->clean_result = SERVICE_FAILURE_RESOURCES;
5dcadb4c 5374 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
4c2f5842
LP
5375 return r;
5376}
5377
5378static int service_can_clean(Unit *u, ExecCleanMask *ret) {
e9fa1bf7 5379 Service *s = ASSERT_PTR(SERVICE(u));
4fb8f1e8
LP
5380 ExecCleanMask mask = 0;
5381 int r;
4c2f5842 5382
4fb8f1e8
LP
5383 assert(ret);
5384
5385 r = exec_context_get_clean_mask(&s->exec_context, &mask);
5386 if (r < 0)
5387 return r;
4c2f5842 5388
4fb8f1e8
LP
5389 if (s->n_fd_store_max > 0)
5390 mask |= EXEC_CLEAN_FDSTORE;
5391
5392 *ret = mask;
5393 return 0;
4c2f5842
LP
5394}
5395
f19afb21
MY
5396static int service_live_mount(
5397 Unit *u,
5162829e
LB
5398 const char *src,
5399 const char *dst,
5400 sd_bus_message *message,
5401 MountInNamespaceFlags flags,
5402 const MountOptions *options,
5403 sd_bus_error *error) {
5404
5162829e 5405 Service *s = ASSERT_PTR(SERVICE(u));
f19afb21 5406 _cleanup_(pidref_done) PidRef worker = PIDREF_NULL;
5162829e
LB
5407 int r;
5408
5409 assert(u);
5410 assert(u->manager);
5411 assert(src);
5412 assert(dst);
5413 assert(message);
5414 assert(!s->mount_request);
5415
5416 if (s->state != SERVICE_RUNNING || !pidref_is_set(&s->main_pid)) {
f19afb21 5417 log_unit_warning(u, "Service is not running, cannot live mount.");
5162829e
LB
5418 return sd_bus_error_setf(
5419 error,
5420 BUS_ERROR_UNIT_INACTIVE,
5421 "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: service not running",
5422 src,
5423 dst,
5424 u->id);
5425 }
5426
5427 if (mount_point_is_credentials(u->manager->prefix[EXEC_DIRECTORY_RUNTIME], dst)) {
f19afb21 5428 log_unit_warning(u, "Refusing to live mount over credential mount '%s'.", dst);
5162829e
LB
5429 return sd_bus_error_setf(
5430 error,
5431 SD_BUS_ERROR_INVALID_ARGS,
5432 "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: cannot mount over credential mount",
5433 src,
5434 dst,
5435 u->id);
5436 }
5437
5438 if (path_startswith_strv(dst, s->exec_context.inaccessible_paths)) {
f19afb21 5439 log_unit_warning(u, "%s is not accessible to this unit, cannot live mount.", dst);
5162829e
LB
5440 return sd_bus_error_setf(
5441 error,
5442 SD_BUS_ERROR_INVALID_ARGS,
5443 "Live mounting '%s' on '%s' for unit '%s' cannot be scheduled: destination is not accessible to this unit",
5444 src,
5445 dst,
5446 u->id);
5447 }
5448
5449 service_unwatch_control_pid(s);
5450 s->live_mount_result = SERVICE_SUCCESS;
5451 s->control_command = NULL;
5452 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
5453
5454 r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
5455 if (r < 0) {
f19afb21
MY
5456 log_unit_error_errno(u, r, "Failed to install timer: %m");
5457 sd_bus_error_set_errnof(error, r,
5458 "Live mounting '%s' on '%s' for unit '%s': failed to install timer: %m",
5459 src, dst, u->id);
5162829e
LB
5460 goto fail;
5461 }
5462
f19afb21 5463 const char *propagate_directory = strjoina("/run/systemd/propagate/", u->id);
5162829e
LB
5464
5465 /* Given we are running from PID1, avoid doing potentially heavy I/O operations like opening images
5466 * directly, and instead fork a worker process. We record the D-Bus message, so that we can reply
5467 * after the operation has finished. This way callers can wait on the message and know that the new
5468 * resource is available (or the operation failed) once they receive the response. */
5469 r = unit_fork_helper_process(u, "(sd-mount-in-ns)", /* into_cgroup= */ false, &worker);
5470 if (r < 0) {
f19afb21
MY
5471 log_unit_error_errno(u, r,
5472 "Failed to fork process to mount '%s' on '%s' in unit's namespace: %m",
5473 src, dst);
5474 sd_bus_error_set_errnof(error, r,
5475 "Live mounting '%s' on '%s' for unit '%s': failed to fork off helper process into namespace: %m",
5476 src, dst, u->id);
5162829e
LB
5477 goto fail;
5478 }
5479 if (r == 0) {
5480 if (flags & MOUNT_IN_NAMESPACE_IS_IMAGE)
5481 r = mount_image_in_namespace(
5482 &s->main_pid,
5483 propagate_directory,
5484 "/run/systemd/incoming/",
5485 src, dst,
5486 flags,
5487 options,
5488 s->exec_context.mount_image_policy ?: &image_policy_service);
5489 else
5490 r = bind_mount_in_namespace(
5491 &s->main_pid,
5492 propagate_directory,
5493 "/run/systemd/incoming/",
5494 src, dst,
5495 flags);
5496 if (r < 0)
f19afb21
MY
5497 log_unit_error_errno(u, r,
5498 "Failed to mount '%s' on '%s' in unit's namespace: %m",
5499 src, dst);
5162829e
LB
5500 else
5501 log_unit_debug(u, "Mounted '%s' on '%s' in unit's namespace", src, dst);
f19afb21 5502
5162829e
LB
5503 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
5504 }
5505
5506 r = unit_watch_pidref(u, &worker, /* exclusive= */ true);
5507 if (r < 0) {
f19afb21
MY
5508 log_unit_warning_errno(u, r, "Failed to watch live mount helper process: %m");
5509 sd_bus_error_set_errnof(error, r,
5510 "Live mounting '%s' on '%s' for unit '%s': failed to watch live mount helper process: %m",
5511 src, dst, u->id);
5162829e
LB
5512 goto fail;
5513 }
5514
5515 s->mount_request = sd_bus_message_ref(message);
5516 s->control_pid = TAKE_PIDREF(worker);
5517 service_set_state(s, SERVICE_MOUNTING);
5518 return 0;
5519
5520fail:
5521 s->live_mount_result = SERVICE_FAILURE_RESOURCES;
20366875 5522 service_enter_running(s, SERVICE_SUCCESS);
5162829e
LB
5523 return r;
5524}
5525
f19afb21
MY
5526static int service_can_live_mount(Unit *u, sd_bus_error *error) {
5527 Service *s = ASSERT_PTR(SERVICE(u));
5162829e
LB
5528
5529 /* Ensure that the unit runs in a private mount namespace */
f19afb21 5530 if (!exec_needs_mount_namespace(&s->exec_context, /* params= */ NULL, s->exec_runtime))
5162829e
LB
5531 return sd_bus_error_setf(
5532 error,
5533 SD_BUS_ERROR_INVALID_ARGS,
d24d546d 5534 "Unit '%s' not running in private mount namespace, cannot live mount.",
5162829e 5535 u->id);
5162829e
LB
5536
5537 return 0;
5538}
5539
e9fa1bf7
MY
5540static const char* service_finished_job(Unit *u, JobType t, JobResult result) {
5541 Service *s = ASSERT_PTR(SERVICE(u));
5542
04d232d8
ZJS
5543 if (t == JOB_START &&
5544 result == JOB_DONE &&
e9fa1bf7 5545 s->type == SERVICE_ONESHOT)
04d232d8 5546 return "Finished %s.";
eda0cbf0
ZJS
5547
5548 /* Fall back to generic */
5549 return NULL;
5550}
5551
705578c3 5552static int service_can_start(Unit *u) {
e9fa1bf7 5553 Service *s = ASSERT_PTR(SERVICE(u));
9727f242
DDM
5554 int r;
5555
9727f242
DDM
5556 /* Make sure we don't enter a busy loop of some kind. */
5557 r = unit_test_start_limit(u);
5558 if (r < 0) {
5559 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
5560 return r;
5561 }
5562
705578c3 5563 return 1;
9727f242
DDM
5564}
5565
c25fac9a 5566static void service_release_resources(Unit *u) {
e9fa1bf7 5567 Service *s = ASSERT_PTR(SERVICE(u));
c25fac9a
LP
5568
5569 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
5570 * anymore for it, and it hence is a good idea to release resources */
5571
5572 /* Don't release resources if this is a transitionary failed/dead state
5573 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
5574 * failure state. */
b9c1883a 5575 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
c25fac9a
LP
5576 return;
5577
5578 log_unit_debug(u, "Releasing resources...");
5579
81a1d6d6 5580 service_release_socket_fd(s);
c25fac9a 5581 service_release_stdio_fd(s);
3543456f 5582 service_release_extra_fds(s);
b9c1883a
LP
5583
5584 if (s->fd_store_preserve_mode != EXEC_PRESERVE_YES)
5585 service_release_fd_store(s);
5586
5587 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
5588 service_set_state(s, SERVICE_DEAD);
c25fac9a
LP
5589}
5590
8017ed7e
LP
5591int service_determine_exec_selinux_label(Service *s, char **ret) {
5592 int r;
5593
5594 assert(s);
5595 assert(ret);
5596
5597 if (!mac_selinux_use())
5598 return -ENODATA;
5599
5600 /* Returns the SELinux label used for execution of the main service binary */
5601
045d9424
ZJS
5602 if (s->exec_context.selinux_context)
5603 /* Prefer the explicitly configured label if there is one */
5604 return strdup_to(ret, s->exec_context.selinux_context);
8017ed7e
LP
5605
5606 if (s->exec_context.root_image ||
5607 s->exec_context.n_extension_images > 0 ||
5608 !strv_isempty(s->exec_context.extension_directories)) /* We cannot chase paths through images */
5609 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.");
5610
5611 ExecCommand *c = s->exec_command[SERVICE_EXEC_START];
5612 if (!c)
5613 return -ENODATA;
5614
5615 _cleanup_free_ char *path = NULL;
5616 r = chase(c->path, s->exec_context.root_directory, CHASE_PREFIX_ROOT, &path, NULL);
5617 if (r < 0) {
5618 log_unit_debug_errno(UNIT(s), r, "Failed to resolve service binary '%s', ignoring.", c->path);
5619 return -ENODATA;
5620 }
5621
5622 r = mac_selinux_get_create_label_from_exe(path, ret);
5623 if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
5624 log_unit_debug_errno(UNIT(s), r, "Reading SELinux label off binary '%s' is not supported, ignoring.", path);
5625 return -ENODATA;
5626 }
5627 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
5628 log_unit_debug_errno(UNIT(s), r, "Can't read SELinux label off binary '%s', due to privileges, ignoring.", path);
5629 return -ENODATA;
5630 }
5631 if (r < 0)
5632 return log_unit_debug_errno(UNIT(s), r, "Failed to read SELinux label off binary '%s': %m", path);
5633
5634 return 0;
5635}
5636
94f04347 5637static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
48d83e33
ZJS
5638 [SERVICE_RESTART_NO] = "no",
5639 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
5640 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
6cfe2fde 5641 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
dc99a976 5642 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
48d83e33
ZJS
5643 [SERVICE_RESTART_ON_ABORT] = "on-abort",
5644 [SERVICE_RESTART_ALWAYS] = "always",
94f04347
LP
5645};
5646
5647DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
5648
e568fea9
RP
5649static const char* const service_restart_mode_table[_SERVICE_RESTART_MODE_MAX] = {
5650 [SERVICE_RESTART_MODE_NORMAL] = "normal",
17f6b640 5651 [SERVICE_RESTART_MODE_DIRECT] = "direct",
7d8bbfbe 5652 [SERVICE_RESTART_MODE_DEBUG] = "debug",
e568fea9
RP
5653};
5654
5655DEFINE_STRING_TABLE_LOOKUP(service_restart_mode, ServiceRestartMode);
5656
94f04347 5657static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3bd28bf7
LP
5658 [SERVICE_SIMPLE] = "simple",
5659 [SERVICE_FORKING] = "forking",
5660 [SERVICE_ONESHOT] = "oneshot",
5661 [SERVICE_DBUS] = "dbus",
5662 [SERVICE_NOTIFY] = "notify",
5663 [SERVICE_NOTIFY_RELOAD] = "notify-reload",
5664 [SERVICE_IDLE] = "idle",
5665 [SERVICE_EXEC] = "exec",
94f04347
LP
5666};
5667
5668DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
5669
596e4470 5670static const char* const service_exit_type_table[_SERVICE_EXIT_TYPE_MAX] = {
fb138166 5671 [SERVICE_EXIT_MAIN] = "main",
596e4470
HC
5672 [SERVICE_EXIT_CGROUP] = "cgroup",
5673};
5674
5675DEFINE_STRING_TABLE_LOOKUP(service_exit_type, ServiceExitType);
5676
e537352b 5677static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5678 [SERVICE_EXEC_CONDITION] = "ExecCondition",
5679 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
5680 [SERVICE_EXEC_START] = "ExecStart",
94f04347 5681 [SERVICE_EXEC_START_POST] = "ExecStartPost",
48d83e33
ZJS
5682 [SERVICE_EXEC_RELOAD] = "ExecReload",
5683 [SERVICE_EXEC_STOP] = "ExecStop",
5684 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
94f04347
LP
5685};
5686
5687DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
5688
b3d59367 5689static const char* const service_exec_ex_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5690 [SERVICE_EXEC_CONDITION] = "ExecConditionEx",
5691 [SERVICE_EXEC_START_PRE] = "ExecStartPreEx",
5692 [SERVICE_EXEC_START] = "ExecStartEx",
b3d59367 5693 [SERVICE_EXEC_START_POST] = "ExecStartPostEx",
48d83e33
ZJS
5694 [SERVICE_EXEC_RELOAD] = "ExecReloadEx",
5695 [SERVICE_EXEC_STOP] = "ExecStopEx",
5696 [SERVICE_EXEC_STOP_POST] = "ExecStopPostEx",
b3d59367
AZ
5697};
5698
5699DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command, ServiceExecCommand);
5700
308d72dc 5701static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
48d83e33
ZJS
5702 [NOTIFY_UNKNOWN] = "unknown",
5703 [NOTIFY_READY] = "ready",
308d72dc 5704 [NOTIFY_RELOADING] = "reloading",
48d83e33 5705 [NOTIFY_STOPPING] = "stopping",
308d72dc
LP
5706};
5707
5708DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
5709
f42806df 5710static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
48d83e33
ZJS
5711 [SERVICE_SUCCESS] = "success",
5712 [SERVICE_FAILURE_RESOURCES] = "resources",
5713 [SERVICE_FAILURE_PROTOCOL] = "protocol",
5714 [SERVICE_FAILURE_TIMEOUT] = "timeout",
5715 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
5716 [SERVICE_FAILURE_SIGNAL] = "signal",
5717 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
5718 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
07299350 5719 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
48d83e33
ZJS
5720 [SERVICE_FAILURE_OOM_KILL] = "oom-kill",
5721 [SERVICE_SKIP_CONDITION] = "exec-condition",
f42806df
LP
5722};
5723
5724DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
5725
bf760801
JK
5726static const char* const service_timeout_failure_mode_table[_SERVICE_TIMEOUT_FAILURE_MODE_MAX] = {
5727 [SERVICE_TIMEOUT_TERMINATE] = "terminate",
48d83e33
ZJS
5728 [SERVICE_TIMEOUT_ABORT] = "abort",
5729 [SERVICE_TIMEOUT_KILL] = "kill",
bf760801
JK
5730};
5731
5732DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode, ServiceTimeoutFailureMode);
5733
87f0e418 5734const UnitVTable service_vtable = {
7d17cfbc 5735 .object_size = sizeof(Service),
718db961
LP
5736 .exec_context_offset = offsetof(Service, exec_context),
5737 .cgroup_context_offset = offsetof(Service, cgroup_context),
5738 .kill_context_offset = offsetof(Service, kill_context),
613b411c 5739 .exec_runtime_offset = offsetof(Service, exec_runtime),
9cc54544 5740 .cgroup_runtime_offset = offsetof(Service, cgroup_runtime),
3ef63c31 5741
f975e971
LP
5742 .sections =
5743 "Unit\0"
5744 "Service\0"
5745 "Install\0",
4ad49000 5746 .private_section = "Service",
71645aca 5747
1d9cc876
LP
5748 .can_transient = true,
5749 .can_delegate = true,
c80a9a33 5750 .can_fail = true,
4d824a4e 5751 .can_set_managed_oom = true,
1d9cc876 5752
034c6ed7
LP
5753 .init = service_init,
5754 .done = service_done,
a16e1123 5755 .load = service_load,
a354329f 5756 .release_resources = service_release_resources,
a16e1123
LP
5757
5758 .coldplug = service_coldplug,
034c6ed7 5759
5cb5a6ff
LP
5760 .dump = service_dump,
5761
5762 .start = service_start,
5763 .stop = service_stop,
5764 .reload = service_reload,
5765
034c6ed7
LP
5766 .can_reload = service_can_reload,
5767
4c2f5842
LP
5768 .clean = service_clean,
5769 .can_clean = service_can_clean,
8a0867d6 5770
5162829e
LB
5771 .live_mount = service_live_mount,
5772 .can_live_mount = service_can_live_mount,
5773
16b6af6a 5774 .freezer_action = unit_cgroup_freezer_action,
d9e45bc3 5775
a16e1123
LP
5776 .serialize = service_serialize,
5777 .deserialize_item = service_deserialize_item,
5778
5cb5a6ff 5779 .active_state = service_active_state,
10a94420 5780 .sub_state_to_string = service_sub_state_to_string,
5cb5a6ff 5781
deb4e708
MK
5782 .will_restart = service_will_restart,
5783
f2f725e5 5784 .may_gc = service_may_gc,
701cc384 5785
034c6ed7 5786 .sigchld_event = service_sigchld_event,
2c4104f0 5787
fdf20a31 5788 .reset_failed = service_reset_failed,
5632e374 5789
4ad49000 5790 .notify_cgroup_empty = service_notify_cgroup_empty_event,
afcfaa69 5791 .notify_cgroup_oom = service_notify_cgroup_oom_event,
8c47c732 5792 .notify_message = service_notify_message,
3c1d1ca1 5793 .notify_handoff_timestamp = service_handoff_timestamp,
406f1775 5794 .notify_pidref = service_notify_pidref,
8e274523 5795
291d565a
LP
5796 .main_pid = service_main_pid,
5797 .control_pid = service_control_pid,
5798
05e343b7 5799 .bus_name_owner_change = service_bus_name_owner_change,
05e343b7 5800
74c964d3
LP
5801 .bus_set_property = bus_service_set_property,
5802 .bus_commit_properties = bus_service_commit_properties,
4139c1b2 5803
68db7a3b 5804 .get_timeout = service_get_timeout,
f5a9d2ee 5805 .get_timeout_start_usec = service_get_timeout_start_usec,
bb2c7685 5806 .needs_console = service_needs_console,
7af67e9a 5807 .exit_status = service_exit_status,
5e1669ff 5808 .status_text = service_status_text,
718db961 5809
c6918296 5810 .status_message_formats = {
c6918296 5811 .finished_start_job = {
c6918296 5812 [JOB_FAILED] = "Failed to start %s.",
c6918296
MS
5813 },
5814 .finished_stop_job = {
5815 [JOB_DONE] = "Stopped %s.",
5816 [JOB_FAILED] = "Stopped (with error) %s.",
c6918296 5817 },
eda0cbf0 5818 .finished_job = service_finished_job,
c6918296 5819 },
9727f242 5820
705578c3 5821 .can_start = service_can_start,
d52b8493 5822
b2bfd121
LP
5823 .notify_plymouth = true,
5824
d52b8493
LP
5825 .audit_start_message_type = AUDIT_SERVICE_START,
5826 .audit_stop_message_type = AUDIT_SERVICE_STOP,
5cb5a6ff 5827};