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