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