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