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