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