]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/service.c
core: Fix file descriptor leak
[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"
93cb78ae 27#include "io-util.h"
4f5dd394
LP
28#include "load-dropin.h"
29#include "load-fragment.h"
30#include "log.h"
31#include "manager.h"
d52b8493 32#include "missing_audit.h"
cd48e23f 33#include "open-file.h"
6bedfcbb 34#include "parse-util.h"
4f5dd394 35#include "path-util.h"
0b452006 36#include "process-util.h"
5918a933 37#include "random-util.h"
8017ed7e 38#include "selinux-util.h"
d68c645b 39#include "serialize.h"
3ffd4af2 40#include "service.h"
24882e06 41#include "signal-util.h"
4f5dd394 42#include "special.h"
e266c068 43#include "stdio-util.h"
8b43440b 44#include "string-table.h"
07630cea 45#include "string-util.h"
4f5dd394
LP
46#include "strv.h"
47#include "unit-name.h"
4f5dd394
LP
48#include "unit.h"
49#include "utf8.h"
034c6ed7 50
edbf8984
ZJS
51#define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
52
acbb0225 53static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
17f6b640
YW
54 [SERVICE_DEAD] = UNIT_INACTIVE,
55 [SERVICE_CONDITION] = UNIT_ACTIVATING,
56 [SERVICE_START_PRE] = UNIT_ACTIVATING,
57 [SERVICE_START] = UNIT_ACTIVATING,
58 [SERVICE_START_POST] = UNIT_ACTIVATING,
59 [SERVICE_RUNNING] = UNIT_ACTIVE,
60 [SERVICE_EXITED] = UNIT_ACTIVE,
61 [SERVICE_RELOAD] = UNIT_RELOADING,
62 [SERVICE_RELOAD_SIGNAL] = UNIT_RELOADING,
63 [SERVICE_RELOAD_NOTIFY] = UNIT_RELOADING,
64 [SERVICE_STOP] = UNIT_DEACTIVATING,
65 [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
66 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
67 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
68 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
69 [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
70 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
71 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
72 [SERVICE_FAILED] = UNIT_FAILED,
73 [SERVICE_DEAD_BEFORE_AUTO_RESTART] = UNIT_INACTIVE,
a1d31573 74 [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
17f6b640
YW
75 [SERVICE_DEAD_RESOURCES_PINNED] = UNIT_INACTIVE,
76 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
77 [SERVICE_AUTO_RESTART_QUEUED] = UNIT_ACTIVATING,
78 [SERVICE_CLEANING] = UNIT_MAINTENANCE,
034c6ed7 79};
5cb5a6ff 80
e056b01d
LP
81/* For Type=idle we never want to delay any other jobs, hence we
82 * consider idle jobs active as soon as we start working on them */
83static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
17f6b640
YW
84 [SERVICE_DEAD] = UNIT_INACTIVE,
85 [SERVICE_CONDITION] = UNIT_ACTIVE,
86 [SERVICE_START_PRE] = UNIT_ACTIVE,
87 [SERVICE_START] = UNIT_ACTIVE,
88 [SERVICE_START_POST] = UNIT_ACTIVE,
89 [SERVICE_RUNNING] = UNIT_ACTIVE,
90 [SERVICE_EXITED] = UNIT_ACTIVE,
91 [SERVICE_RELOAD] = UNIT_RELOADING,
92 [SERVICE_RELOAD_SIGNAL] = UNIT_RELOADING,
93 [SERVICE_RELOAD_NOTIFY] = UNIT_RELOADING,
94 [SERVICE_STOP] = UNIT_DEACTIVATING,
95 [SERVICE_STOP_WATCHDOG] = UNIT_DEACTIVATING,
96 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
97 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
98 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
99 [SERVICE_FINAL_WATCHDOG] = UNIT_DEACTIVATING,
100 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
101 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
102 [SERVICE_FAILED] = UNIT_FAILED,
103 [SERVICE_DEAD_BEFORE_AUTO_RESTART] = UNIT_INACTIVE,
a1d31573 104 [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
17f6b640
YW
105 [SERVICE_DEAD_RESOURCES_PINNED] = UNIT_INACTIVE,
106 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING,
107 [SERVICE_AUTO_RESTART_QUEUED] = UNIT_ACTIVATING,
108 [SERVICE_CLEANING] = UNIT_MAINTENANCE,
e056b01d
LP
109};
110
5686391b 111static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
718db961
LP
112static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
113static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
5686391b 114static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
718db961 115
842129f5 116static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
308d72dc 117static void service_enter_reload_by_notify(Service *s);
842129f5 118
94114711
YW
119static bool SERVICE_STATE_WITH_MAIN_PROCESS(ServiceState state) {
120 return IN_SET(state,
121 SERVICE_START, SERVICE_START_POST,
122 SERVICE_RUNNING,
123 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
124 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
125 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL);
126}
127
128static bool SERVICE_STATE_WITH_CONTROL_PROCESS(ServiceState state) {
129 return IN_SET(state,
130 SERVICE_CONDITION,
131 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
132 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
133 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
134 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
135 SERVICE_CLEANING);
136}
137
a16e1123
LP
138static void service_init(Unit *u) {
139 Service *s = SERVICE(u);
140
141 assert(u);
ac155bb8 142 assert(u->load_state == UNIT_STUB);
a16e1123 143
c9e120e0
LP
144 s->timeout_start_usec = u->manager->defaults.timeout_start_usec;
145 s->timeout_stop_usec = u->manager->defaults.timeout_stop_usec;
146 s->timeout_abort_usec = u->manager->defaults.timeout_abort_usec;
147 s->timeout_abort_set = u->manager->defaults.timeout_abort_set;
148 s->restart_usec = u->manager->defaults.restart_usec;
e9f17fa8 149 s->restart_max_delay_usec = USEC_INFINITY;
36c16a7c 150 s->runtime_max_usec = USEC_INFINITY;
0b86feac 151 s->type = _SERVICE_TYPE_INVALID;
254d1313
ZJS
152 s->socket_fd = -EBADF;
153 s->stdin_fd = s->stdout_fd = s->stderr_fd = -EBADF;
3185a36b 154 s->guess_main_pid = true;
c79ab77c
LP
155 s->main_pid = PIDREF_NULL;
156 s->control_pid = PIDREF_NULL;
a16e1123 157 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
00f5ad93
LP
158
159 s->exec_context.keyring_mode = MANAGER_IS_SYSTEM(u->manager) ?
160 EXEC_KEYRING_PRIVATE : EXEC_KEYRING_INHERIT;
aa8c4bbf 161
19dff691
MY
162 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
163
aa8c4bbf 164 s->watchdog_original_usec = USEC_INFINITY;
afcfaa69
LP
165
166 s->oom_policy = _OOM_POLICY_INVALID;
3bd28bf7
LP
167 s->reload_begin_usec = USEC_INFINITY;
168 s->reload_signal = SIGHUP;
b9c1883a
LP
169
170 s->fd_store_preserve_mode = EXEC_PRESERVE_RESTART;
a16e1123
LP
171}
172
5e94833f
LP
173static void service_unwatch_control_pid(Service *s) {
174 assert(s);
ea1e0bf1 175 unit_unwatch_pidref_done(UNIT(s), &s->control_pid);
5e94833f
LP
176}
177
178static void service_unwatch_main_pid(Service *s) {
179 assert(s);
ea1e0bf1 180 unit_unwatch_pidref_done(UNIT(s), &s->main_pid);
5e94833f
LP
181}
182
3e52541e 183static void service_unwatch_pid_file(Service *s) {
e9fa1bf7
MY
184 assert(s);
185
3e52541e
MS
186 if (!s->pid_file_pathspec)
187 return;
188
f2341e0a 189 log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
718db961 190 path_spec_unwatch(s->pid_file_pathspec);
3e52541e 191 path_spec_done(s->pid_file_pathspec);
a1e58e8e 192 s->pid_file_pathspec = mfree(s->pid_file_pathspec);
3e52541e
MS
193}
194
c603f523
MY
195static int service_set_main_pidref(Service *s, PidRef pidref_consume) {
196 _cleanup_(pidref_done) PidRef pidref = pidref_consume;
6774be42
LP
197 int r;
198
5925dd3c
LP
199 assert(s);
200
c603f523 201 /* Takes ownership of the specified pidref on both success and failure. */
b1f6901d 202
c603f523 203 if (!pidref_is_set(&pidref))
b1f6901d
LP
204 return -ESRCH;
205
c603f523 206 if (pidref.pid <= 1)
5925dd3c
LP
207 return -EINVAL;
208
c603f523 209 if (pidref_is_self(&pidref))
5925dd3c
LP
210 return -EINVAL;
211
c603f523 212 if (s->main_pid_known && pidref_equal(&s->main_pid, &pidref))
7400b9d2
LP
213 return 0;
214
c603f523 215 if (!pidref_equal(&s->main_pid, &pidref)) {
7400b9d2 216 service_unwatch_main_pid(s);
c603f523 217 exec_status_start(&s->main_exec_status, pidref.pid);
7400b9d2 218 }
41efeaec 219
c603f523 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);
120be68b 226 else if (r == 0) // FIXME: Supervise through pidfd here
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);
6774be42 228 s->main_pid_alien = r <= 0;
120be68b 229
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
5bcf0881 444 if (s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_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
3a7bb5c9
LP
1026 fprintf(f, "%s%s %s:\n",
1027 prefix, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), 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
c603f523 1169 r = service_set_main_pidref(s, TAKE_PIDREF(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 1198 log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid.pid);
c603f523 1199 if (service_set_main_pidref(s, TAKE_PIDREF(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 1408 _cleanup_free_ int *cfds = NULL;
8dd4c05b 1409 int cn_fds;
8d83e0c2 1410 Socket *sock;
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;
8d83e0c2
MY
1426 } else if (!GREEDY_REALLOC_APPEND(rfds, rn_socket_fds, cfds, cn_fds))
1427 return -ENOMEM;
8dd4c05b
LP
1428
1429 r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1430 if (r < 0)
1431 return r;
44d8db9e
LP
1432 }
1433 }
1434
a354329f 1435 if (s->n_fd_store > 0) {
25b583d7 1436 size_t n_fds;
8dd4c05b 1437 char **nl;
a354329f
LP
1438 int *t;
1439
62d74c78 1440 t = reallocarray(rfds, rn_socket_fds + s->n_fd_store, sizeof(int));
a354329f
LP
1441 if (!t)
1442 return -ENOMEM;
1443
1444 rfds = t;
8dd4c05b 1445
62d74c78 1446 nl = reallocarray(rfd_names, rn_socket_fds + s->n_fd_store + 1, sizeof(char *));
8dd4c05b
LP
1447 if (!nl)
1448 return -ENOMEM;
1449
1450 rfd_names = nl;
4c47affc 1451 n_fds = rn_socket_fds;
8dd4c05b
LP
1452
1453 LIST_FOREACH(fd_store, fs, s->fd_store) {
4c47affc
FB
1454 rfds[n_fds] = fs->fd;
1455 rfd_names[n_fds] = strdup(strempty(fs->fdname));
1456 if (!rfd_names[n_fds])
8dd4c05b
LP
1457 return -ENOMEM;
1458
4c47affc
FB
1459 rn_storage_fds++;
1460 n_fds++;
8dd4c05b
LP
1461 }
1462
4c47affc 1463 rfd_names[n_fds] = NULL;
a354329f
LP
1464 }
1465
1cc6c93a
YW
1466 *fds = TAKE_PTR(rfds);
1467 *fd_names = TAKE_PTR(rfd_names);
9b141911 1468 *n_socket_fds = rn_socket_fds;
4c47affc 1469 *n_storage_fds = rn_storage_fds;
3e33402a 1470
4c47affc 1471 return 0;
44d8db9e
LP
1472}
1473
5686391b
LP
1474static int service_allocate_exec_fd_event_source(
1475 Service *s,
1476 int fd,
1477 sd_event_source **ret_event_source) {
1478
1479 _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
1480 int r;
1481
1482 assert(s);
1483 assert(fd >= 0);
1484 assert(ret_event_source);
1485
1486 r = sd_event_add_io(UNIT(s)->manager->event, &source, fd, 0, service_dispatch_exec_io, s);
1487 if (r < 0)
1488 return log_unit_error_errno(UNIT(s), r, "Failed to allocate exec_fd event source: %m");
1489
f3a269a9
LP
1490 /* This is a bit higher priority than SIGCHLD, to make sure we don't confuse the case "failed to
1491 * start" from the case "succeeded to start, but failed immediately after". */
5686391b 1492
d42b61d2 1493 r = sd_event_source_set_priority(source, EVENT_PRIORITY_EXEC_FD);
5686391b
LP
1494 if (r < 0)
1495 return log_unit_error_errno(UNIT(s), r, "Failed to adjust priority of exec_fd event source: %m");
1496
bc989831 1497 (void) sd_event_source_set_description(source, "service exec_fd");
5686391b
LP
1498
1499 r = sd_event_source_set_io_fd_own(source, true);
1500 if (r < 0)
1501 return log_unit_error_errno(UNIT(s), r, "Failed to pass ownership of fd to event source: %m");
1502
1503 *ret_event_source = TAKE_PTR(source);
1504 return 0;
1505}
1506
1507static int service_allocate_exec_fd(
1508 Service *s,
1509 sd_event_source **ret_event_source,
e78695d4 1510 int *ret_exec_fd) {
5686391b 1511
71136404 1512 _cleanup_close_pair_ int p[] = EBADF_PAIR;
5686391b
LP
1513 int r;
1514
1515 assert(s);
1516 assert(ret_event_source);
1517 assert(ret_exec_fd);
1518
1519 if (pipe2(p, O_CLOEXEC|O_NONBLOCK) < 0)
1520 return log_unit_error_errno(UNIT(s), errno, "Failed to allocate exec_fd pipe: %m");
1521
1522 r = service_allocate_exec_fd_event_source(s, p[0], ret_event_source);
1523 if (r < 0)
1524 return r;
1525
e78695d4 1526 TAKE_FD(p[0]);
5686391b
LP
1527 *ret_exec_fd = TAKE_FD(p[1]);
1528
1529 return 0;
1530}
1531
6375bd20
JW
1532static bool service_exec_needs_notify_socket(Service *s, ExecFlags flags) {
1533 assert(s);
1534
1535 /* Notifications are accepted depending on the process and
1536 * the access setting of the service:
1537 * process: \ access: NONE MAIN EXEC ALL
1538 * main no yes yes yes
1539 * control no no yes yes
1540 * other (forked) no no no yes */
1541
1542 if (flags & EXEC_IS_CONTROL)
1543 /* A control process */
19dff691 1544 return IN_SET(service_get_notify_access(s), NOTIFY_EXEC, NOTIFY_ALL);
6375bd20
JW
1545
1546 /* We only spawn main processes and control processes, so any
1547 * process that is not a control process is a main process */
19dff691 1548 return service_get_notify_access(s) != NOTIFY_NONE;
6375bd20
JW
1549}
1550
95c81c55
LB
1551static Service *service_get_triggering_service(Service *s) {
1552 Unit *candidate = NULL, *other;
cdebedb4 1553
95c81c55 1554 assert(s);
cdebedb4 1555
95c81c55
LB
1556 /* Return the service which triggered service 's', this means dependency
1557 * types which include the UNIT_ATOM_ON_{FAILURE,SUCCESS}_OF atoms.
cdebedb4 1558 *
95c81c55
LB
1559 * N.B. if there are multiple services which could trigger 's' via OnFailure=
1560 * or OnSuccess= then we return NULL. This is since we don't know from which
1561 * one to propagate the exit status. */
1562
1563 UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_FAILURE_OF) {
7a5049c7
ZJS
1564 if (candidate)
1565 goto have_other;
95c81c55
LB
1566 candidate = other;
1567 }
1568
1569 UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_ON_SUCCESS_OF) {
7a5049c7
ZJS
1570 if (candidate)
1571 goto have_other;
95c81c55 1572 candidate = other;
cdebedb4
PM
1573 }
1574
95c81c55 1575 return SERVICE(candidate);
7a5049c7
ZJS
1576
1577 have_other:
1578 log_unit_warning(UNIT(s), "multiple trigger source candidates for exit status propagation (%s, %s), skipping.",
1579 candidate->id, other->id);
1580 return NULL;
cdebedb4
PM
1581}
1582
cfbf7538 1583static ExecFlags service_exec_flags(ServiceExecCommand command_id, ExecFlags cred_flag) {
81006ebb
MY
1584 /* All service main/control processes honor sandboxing and namespacing options (except those
1585 explicitly excluded in service_spawn()) */
1586 ExecFlags flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT;
1587
1588 assert(command_id >= 0);
1589 assert(command_id < _SERVICE_EXEC_COMMAND_MAX);
cfbf7538
MY
1590 assert((cred_flag & ~(EXEC_SETUP_CREDENTIALS_FRESH|EXEC_SETUP_CREDENTIALS)) == 0);
1591 assert((cred_flag != 0) == (command_id == SERVICE_EXEC_START));
81006ebb
MY
1592
1593 /* Control processes spawned before main process also get tty access */
fe760177 1594 if (IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
81006ebb
MY
1595 flags |= EXEC_APPLY_TTY_STDIN;
1596
cfbf7538
MY
1597 /* All start phases get access to credentials. ExecStartPre= gets a new credential store upon
1598 * every invocation, so that updating credential files through it works. When the first main process
1599 * starts, passed creds become stable. Also see 'cred_flag'. */
1600 if (command_id == SERVICE_EXEC_START_PRE)
1601 flags |= EXEC_SETUP_CREDENTIALS_FRESH;
1602 if (command_id == SERVICE_EXEC_START_POST)
1221ba0f 1603 flags |= EXEC_SETUP_CREDENTIALS;
81006ebb
MY
1604
1605 if (IN_SET(command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START))
1606 flags |= EXEC_SETENV_MONITOR_RESULT;
1607
1608 if (command_id == SERVICE_EXEC_START)
cfbf7538 1609 return flags|cred_flag|EXEC_PASS_FDS|EXEC_SET_WATCHDOG;
81006ebb
MY
1610
1611 flags |= EXEC_IS_CONTROL;
1612
1613 /* Put control processes spawned later than main process under .control sub-cgroup if appropriate */
1614 if (!IN_SET(command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE))
1615 flags |= EXEC_CONTROL_CGROUP;
1616
1617 if (IN_SET(command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
1618 flags |= EXEC_SETENV_RESULT;
1619
1620 return flags;
1621}
1622
edbf8984
ZJS
1623static int service_spawn_internal(
1624 const char *caller,
81a2b7ce
LP
1625 Service *s,
1626 ExecCommand *c,
cfbf7538 1627 ExecFlags flags,
21b2ce39 1628 usec_t timeout,
c79ab77c 1629 PidRef *ret_pid) {
81a2b7ce 1630
cfbf7538 1631 _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(flags);
5686391b 1632 _cleanup_(sd_event_source_unrefp) sd_event_source *exec_fd_source = NULL;
c3f8a065 1633 _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL;
c79ab77c 1634 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
c3f8a065 1635 size_t n_env = 0;
8dd4c05b
LP
1636 int r;
1637
edbf8984 1638 assert(caller);
034c6ed7
LP
1639 assert(s);
1640 assert(c);
e78695d4 1641 assert(ret_pid);
034c6ed7 1642
edbf8984
ZJS
1643 log_unit_debug(UNIT(s), "Will spawn child (%s): %s", caller, c->path);
1644
78f93209 1645 r = unit_prepare_exec(UNIT(s)); /* This realizes the cgroup, among other things */
3c7416b6
LP
1646 if (r < 0)
1647 return r;
1648
bc989831
ZJS
1649 assert(!s->exec_fd_event_source);
1650
81006ebb 1651 if (FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL)) {
9c1a61ad
LP
1652 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1653 if (s->permissions_start_only)
1703fa41 1654 exec_params.flags &= ~EXEC_APPLY_SANDBOXING;
9c1a61ad
LP
1655 if (s->root_directory_start_only)
1656 exec_params.flags &= ~EXEC_APPLY_CHROOT;
1657 }
1658
81006ebb 1659 if (FLAGS_SET(exec_params.flags, EXEC_PASS_FDS) ||
6cf6bbc2
LP
1660 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1661 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1662 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1663
c3f8a065
LP
1664 r = service_collect_fds(s,
1665 &exec_params.fds,
1666 &exec_params.fd_names,
1667 &exec_params.n_socket_fds,
1668 &exec_params.n_storage_fds);
8dd4c05b 1669 if (r < 0)
36c16a7c 1670 return r;
6cf6bbc2 1671
cd48e23f
RP
1672 exec_params.open_files = s->open_files;
1673
07ff03d6
MY
1674 exec_params.flags |= EXEC_PASS_FDS;
1675
c3f8a065 1676 log_unit_debug(UNIT(s), "Passing %zu fds to service", exec_params.n_socket_fds + exec_params.n_storage_fds);
4f2d528d 1677 }
44d8db9e 1678
12001b1b 1679 if (!FLAGS_SET(exec_params.flags, EXEC_IS_CONTROL) && s->type == SERVICE_EXEC) {
c3f8a065 1680 r = service_allocate_exec_fd(s, &exec_fd_source, &exec_params.exec_fd);
5686391b
LP
1681 if (r < 0)
1682 return r;
1683 }
1684
e5d6dcce 1685 r = service_arm_timer(s, /* relative= */ true, timeout);
36c16a7c
LP
1686 if (r < 0)
1687 return r;
034c6ed7 1688
75b29fda 1689 our_env = new0(char*, 13);
36c16a7c
LP
1690 if (!our_env)
1691 return -ENOMEM;
c952c6ec 1692
81006ebb 1693 if (service_exec_needs_notify_socket(s, exec_params.flags)) {
36c16a7c
LP
1694 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1695 return -ENOMEM;
c952c6ec 1696
3bdc25a4 1697 exec_params.notify_socket = UNIT(s)->manager->notify_socket;
75b29fda
LP
1698
1699 if (s->n_fd_store_max > 0)
1700 if (asprintf(our_env + n_env++, "FDSTORE=%u", s->n_fd_store_max) < 0)
1701 return -ENOMEM;
3bdc25a4
LP
1702 }
1703
c79ab77c
LP
1704 if (pidref_is_set(&s->main_pid))
1705 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid.pid) < 0)
36c16a7c 1706 return -ENOMEM;
2105e76a 1707
c39f1ce2 1708 if (MANAGER_IS_USER(UNIT(s)->manager))
df0ff127 1709 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid_cached()) < 0)
36c16a7c 1710 return -ENOMEM;
97ae63e2 1711
dcf3c3c3
LP
1712 if (s->pid_file)
1713 if (asprintf(our_env + n_env++, "PIDFILE=%s", s->pid_file) < 0)
1714 return -ENOMEM;
1715
8dd4c05b 1716 if (s->socket_fd >= 0) {
3b1c5241
SL
1717 union sockaddr_union sa;
1718 socklen_t salen = sizeof(sa);
1719
f56e7bfe
LP
1720 /* If this is a per-connection service instance, let's set $REMOTE_ADDR and $REMOTE_PORT to something
1721 * useful. Note that we do this only when we are still connected at this point in time, which we might
1722 * very well not be. Hence we ignore all errors when retrieving peer information (as that might result
1723 * in ENOTCONN), and just use whate we can use. */
f2dbd059 1724
f56e7bfe
LP
1725 if (getpeername(s->socket_fd, &sa.sa, &salen) >= 0 &&
1726 IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
3b1c5241
SL
1727 _cleanup_free_ char *addr = NULL;
1728 char *t;
882ac6e7 1729 unsigned port;
3b1c5241
SL
1730
1731 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1732 if (r < 0)
36c16a7c 1733 return r;
3b1c5241 1734
b910cc72 1735 t = strjoin("REMOTE_ADDR=", addr);
36c16a7c
LP
1736 if (!t)
1737 return -ENOMEM;
3b1c5241
SL
1738 our_env[n_env++] = t;
1739
882ac6e7
SH
1740 r = sockaddr_port(&sa.sa, &port);
1741 if (r < 0)
1742 return r;
3b1c5241 1743
36c16a7c
LP
1744 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1745 return -ENOMEM;
3b1c5241
SL
1746 our_env[n_env++] = t;
1747 }
1748 }
1749
95c81c55
LB
1750 Service *env_source = NULL;
1751 const char *monitor_prefix;
81006ebb 1752 if (FLAGS_SET(exec_params.flags, EXEC_SETENV_RESULT)) {
95c81c55
LB
1753 env_source = s;
1754 monitor_prefix = "";
81006ebb 1755 } else if (FLAGS_SET(exec_params.flags, EXEC_SETENV_MONITOR_RESULT)) {
95c81c55
LB
1756 env_source = service_get_triggering_service(s);
1757 monitor_prefix = "MONITOR_";
1758 }
1759
1760 if (env_source) {
1761 if (asprintf(our_env + n_env++, "%sSERVICE_RESULT=%s", monitor_prefix, service_result_to_string(env_source->result)) < 0)
136dc4c4
LP
1762 return -ENOMEM;
1763
95c81c55
LB
1764 if (env_source->main_exec_status.pid > 0 &&
1765 dual_timestamp_is_set(&env_source->main_exec_status.exit_timestamp)) {
1766 if (asprintf(our_env + n_env++, "%sEXIT_CODE=%s", monitor_prefix, sigchld_code_to_string(env_source->main_exec_status.code)) < 0)
136dc4c4
LP
1767 return -ENOMEM;
1768
95c81c55
LB
1769 if (env_source->main_exec_status.code == CLD_EXITED)
1770 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%i", monitor_prefix, env_source->main_exec_status.status);
136dc4c4 1771 else
95c81c55 1772 r = asprintf(our_env + n_env++, "%sEXIT_STATUS=%s", monitor_prefix, signal_to_string(env_source->main_exec_status.status));
136dc4c4
LP
1773 if (r < 0)
1774 return -ENOMEM;
1775 }
cdebedb4 1776
95c81c55 1777 if (env_source != s) {
81006ebb
MY
1778 if (!sd_id128_is_null(UNIT(env_source)->invocation_id))
1779 if (asprintf(our_env + n_env++, "%sINVOCATION_ID=" SD_ID128_FORMAT_STR,
1780 monitor_prefix, SD_ID128_FORMAT_VAL(UNIT(env_source)->invocation_id)) < 0)
95c81c55 1781 return -ENOMEM;
95c81c55
LB
1782
1783 if (asprintf(our_env + n_env++, "%sUNIT=%s", monitor_prefix, UNIT(env_source)->id) < 0)
1784 return -ENOMEM;
cdebedb4 1785 }
136dc4c4
LP
1786 }
1787
48b92b37
LB
1788 if (UNIT(s)->activation_details) {
1789 r = activation_details_append_env(UNIT(s)->activation_details, &our_env);
1790 if (r < 0)
1791 return r;
1792 /* The number of env vars added here can vary, rather than keeping the allocation block in
1793 * sync manually, these functions simply use the strv methods to append to it, so we need
1794 * to update n_env when we are done in case of future usage. */
1795 n_env += r;
1796 }
1797
1ad6e8b3
LP
1798 r = unit_set_exec_params(UNIT(s), &exec_params);
1799 if (r < 0)
1800 return r;
3536f49e 1801
4ab3d29f 1802 final_env = strv_env_merge(exec_params.environment, our_env);
36c16a7c
LP
1803 if (!final_env)
1804 return -ENOMEM;
c952c6ec 1805
ac647978 1806 /* System D-Bus needs nss-systemd disabled, so that we don't deadlock */
de90700f 1807 SET_FLAG(exec_params.flags, EXEC_NSS_DYNAMIC_BYPASS,
ac647978 1808 MANAGER_IS_SYSTEM(UNIT(s)->manager) && unit_has_name(UNIT(s), SPECIAL_DBUS_SERVICE));
4ad49000 1809
b9c04eaf 1810 strv_free_and_replace(exec_params.environment, final_env);
34b3f625 1811 exec_params.watchdog_usec = service_get_watchdog_usec(s);
a34ceba6 1812 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
9fa95f85
DM
1813 if (s->type == SERVICE_IDLE)
1814 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
a34ceba6
LP
1815 exec_params.stdin_fd = s->stdin_fd;
1816 exec_params.stdout_fd = s->stdout_fd;
1817 exec_params.stderr_fd = s->stderr_fd;
9fa95f85 1818
f2341e0a
LP
1819 r = exec_spawn(UNIT(s),
1820 c,
9e2f7c11 1821 &s->exec_context,
9fa95f85 1822 &exec_params,
613b411c 1823 s->exec_runtime,
6bb00842 1824 &s->cgroup_context,
556d2bc4 1825 &pidref);
9e2f7c11 1826 if (r < 0)
36c16a7c 1827 return r;
034c6ed7 1828
5686391b
LP
1829 s->exec_fd_event_source = TAKE_PTR(exec_fd_source);
1830 s->exec_fd_hot = false;
1831
495e75ed 1832 r = unit_watch_pidref(UNIT(s), &pidref, /* exclusive= */ true);
c79ab77c
LP
1833 if (r < 0)
1834 return r;
034c6ed7 1835
c79ab77c 1836 *ret_pid = TAKE_PIDREF(pidref);
5cb5a6ff 1837 return 0;
034c6ed7
LP
1838}
1839
80876c20
LP
1840static int main_pid_good(Service *s) {
1841 assert(s);
1842
51894d70 1843 /* Returns 0 if the pid is dead, > 0 if it is good, < 0 if we don't know */
80876c20 1844
c79ab77c 1845 /* If we know the pid file, then let's just check if it is still valid */
6dfa5494
LP
1846 if (s->main_pid_known) {
1847
c79ab77c
LP
1848 /* If it's an alien child let's check if it is still alive ... */
1849 if (s->main_pid_alien && pidref_is_set(&s->main_pid))
becdfcb9 1850 return pidref_is_alive(&s->main_pid);
6dfa5494 1851
c79ab77c
LP
1852 /* .. otherwise assume we'll get a SIGCHLD for it, which we really should wait for to collect
1853 * exit status and code */
1854 return pidref_is_set(&s->main_pid);
6dfa5494 1855 }
80876c20
LP
1856
1857 /* We don't know the pid */
1858 return -EAGAIN;
1859}
1860
019be286 1861static int control_pid_good(Service *s) {
80876c20
LP
1862 assert(s);
1863
07697d7e
LP
1864 /* Returns 0 if the control PID is dead, > 0 if it is good. We never actually return < 0 here, but in order to
1865 * make this function as similar as possible to main_pid_good() and cgroup_good(), we pretend that < 0 also
1866 * means: we can't figure it out. */
1867
c79ab77c 1868 return pidref_is_set(&s->control_pid);
80876c20
LP
1869}
1870
cb0e818f
HC
1871static int cgroup_good(Service *s) {
1872 int r;
1873
abaf5edd
ZJS
1874 assert(s);
1875
cb0e818f
HC
1876 /* Returns 0 if the cgroup is empty or doesn't exist, > 0 if it is exists and is populated, < 0 if we can't
1877 * figure it out */
1878
9cc54544 1879 if (!s->cgroup_runtime || !s->cgroup_runtime->cgroup_path)
abaf5edd
ZJS
1880 return 0;
1881
9cc54544 1882 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, s->cgroup_runtime->cgroup_path);
117dcc57 1883 if (r < 0)
80876c20
LP
1884 return r;
1885
b13ddbbc 1886 return r == 0;
80876c20
LP
1887}
1888
ebc57b89 1889static bool service_shall_restart(Service *s, const char **reason) {
a509f0e6 1890 assert(s);
189a08e8 1891 assert(reason);
a509f0e6
LP
1892
1893 /* Don't restart after manual stops */
ebc57b89
ZJS
1894 if (s->forbid_restart) {
1895 *reason = "manual stop";
a509f0e6 1896 return false;
ebc57b89 1897 }
a509f0e6
LP
1898
1899 /* Never restart if this is configured as special exception */
ebc57b89
ZJS
1900 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status)) {
1901 *reason = "prevented by exit status";
a509f0e6 1902 return false;
ebc57b89 1903 }
a509f0e6
LP
1904
1905 /* Restart if the exit code/status are configured as restart triggers */
ebc57b89 1906 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status)) {
189a08e8
MY
1907 /* Don't allow Type=oneshot services to restart on success. Note that Restart=always/on-success
1908 * is already rejected in service_verify. */
1909 if (s->type == SERVICE_ONESHOT && s->result == SERVICE_SUCCESS) {
1910 *reason = "service type and exit status";
1911 return false;
1912 }
1913
ebc57b89 1914 *reason = "forced by exit status";
a509f0e6 1915 return true;
ebc57b89 1916 }
a509f0e6 1917
ebc57b89 1918 *reason = "restart setting";
a509f0e6
LP
1919 switch (s->restart) {
1920
1921 case SERVICE_RESTART_NO:
1922 return false;
1923
1924 case SERVICE_RESTART_ALWAYS:
abb99360 1925 return s->result != SERVICE_SKIP_CONDITION;
a509f0e6
LP
1926
1927 case SERVICE_RESTART_ON_SUCCESS:
1928 return s->result == SERVICE_SUCCESS;
1929
1930 case SERVICE_RESTART_ON_FAILURE:
bb924478 1931 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_SKIP_CONDITION);
a509f0e6
LP
1932
1933 case SERVICE_RESTART_ON_ABNORMAL:
bb924478 1934 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE, SERVICE_SKIP_CONDITION);
a509f0e6
LP
1935
1936 case SERVICE_RESTART_ON_WATCHDOG:
1937 return s->result == SERVICE_FAILURE_WATCHDOG;
1938
1939 case SERVICE_RESTART_ON_ABORT:
1940 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1941
1942 default:
04499a70 1943 assert_not_reached();
a509f0e6
LP
1944 }
1945}
1946
deb4e708
MK
1947static bool service_will_restart(Unit *u) {
1948 Service *s = SERVICE(u);
1949
53f47dfc
YW
1950 assert(s);
1951
09d04ad3 1952 if (IN_SET(s->state, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED))
53f47dfc 1953 return true;
2ad2e41a 1954
52a12341 1955 return unit_will_restart_default(u);
53f47dfc
YW
1956}
1957
b9c1883a
LP
1958static ServiceState service_determine_dead_state(Service *s) {
1959 assert(s);
1960
1961 return s->fd_store && s->fd_store_preserve_mode == EXEC_PRESERVE_YES ? SERVICE_DEAD_RESOURCES_PINNED : SERVICE_DEAD;
1962}
1963
f42806df 1964static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
a1d31573 1965 ServiceState end_state, restart_state;
034c6ed7 1966 int r;
0f52f8e5 1967
034c6ed7
LP
1968 assert(s);
1969
0f52f8e5
LP
1970 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1971 * undo what has already been enqueued. */
1972 if (unit_stop_pending(UNIT(s)))
1973 allow_restart = false;
1974
a0fef983 1975 if (s->result == SERVICE_SUCCESS)
f42806df 1976 s->result = f;
034c6ed7 1977
31cd5f63
AZ
1978 if (s->result == SERVICE_SUCCESS) {
1979 unit_log_success(UNIT(s));
b9c1883a 1980 end_state = service_determine_dead_state(s);
a1d31573 1981 restart_state = SERVICE_DEAD_BEFORE_AUTO_RESTART;
31cd5f63
AZ
1982 } else if (s->result == SERVICE_SKIP_CONDITION) {
1983 unit_log_skip(UNIT(s), service_result_to_string(s->result));
b9c1883a 1984 end_state = service_determine_dead_state(s);
8959e17d 1985 restart_state = _SERVICE_STATE_INVALID; /* Never restart if skipped due to condition failure */
31cd5f63
AZ
1986 } else {
1987 unit_log_failure(UNIT(s), service_result_to_string(s->result));
1988 end_state = SERVICE_FAILED;
a1d31573 1989 restart_state = SERVICE_FAILED_BEFORE_AUTO_RESTART;
31cd5f63 1990 }
4c425434 1991 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
ed77d407 1992
ebc57b89
ZJS
1993 if (!allow_restart)
1994 log_unit_debug(UNIT(s), "Service restart not allowed.");
1995 else {
1996 const char *reason;
ebc57b89 1997
49b34f75 1998 allow_restart = service_shall_restart(s, &reason);
ebc57b89 1999 log_unit_debug(UNIT(s), "Service will %srestart (%s)",
49b34f75 2000 allow_restart ? "" : "not ",
ebc57b89 2001 reason);
ebc57b89 2002 }
deb4e708 2003
49b34f75 2004 if (allow_restart) {
fe3d33c1
MY
2005 usec_t restart_usec_next;
2006
8959e17d
MY
2007 assert(restart_state >= 0 && restart_state < _SERVICE_STATE_MAX);
2008
a1d31573 2009 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
c309b9e9 2010 * state (i.e. a state indicating deactivation), and then one that maps to the
a1d31573
LP
2011 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
2012 * external software can watch the state changes and see all service failures, even if they
2013 * are only transitionary and followed by an automatic restart. We have fine-grained
2014 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
2015 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
e568fea9
RP
2016 if (s->restart_mode != SERVICE_RESTART_MODE_DIRECT)
2017 service_set_state(s, restart_state);
a1d31573 2018
fe3d33c1
MY
2019 restart_usec_next = service_restart_usec_next(s);
2020
2021 r = service_arm_timer(s, /* relative= */ true, restart_usec_next);
10691b9e
LP
2022 if (r < 0) {
2023 log_unit_warning_errno(UNIT(s), r, "Failed to install restart timer: %m");
2024 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
2025 return;
2026 }
034c6ed7 2027
fe3d33c1
MY
2028 log_unit_debug(UNIT(s), "Next restart interval calculated as: %s", FORMAT_TIMESPAN(restart_usec_next, 0));
2029
034c6ed7 2030 service_set_state(s, SERVICE_AUTO_RESTART);
a1d31573
LP
2031 } else {
2032 service_set_state(s, end_state);
2033
7a0019d3
LP
2034 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
2035 * user can still introspect the counter. Do so on the next start. */
2036 s->flush_n_restarts = true;
a1d31573 2037 }
034c6ed7 2038
5238e957 2039 /* 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 2040 * queue, so that the fd store is possibly gc'ed again */
7eb2a8a1
LP
2041 unit_add_to_gc_queue(UNIT(s));
2042
f2341e0a 2043 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
47342320
LP
2044 s->forbid_restart = false;
2045
19dff691
MY
2046 /* Reset NotifyAccess override */
2047 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
2048
9c0c6701 2049 /* We want fresh tmpdirs and ephemeral snapshots in case the service is started again immediately. */
28135da3 2050 s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
c17ec25e 2051
95939aed 2052 /* Also, remove the runtime directory */
bb0c0d6f 2053 unit_destroy_runtime_data(UNIT(s), &s->exec_context);
e66cf1a3 2054
b9c1883a
LP
2055 /* Also get rid of the fd store, if that's configured. */
2056 if (s->fd_store_preserve_mode == EXEC_PRESERVE_NO)
2057 service_release_fd_store(s);
2058
00d9ef85
LP
2059 /* Get rid of the IPC bits of the user */
2060 unit_unref_uid_gid(UNIT(s), true);
2061
9285c9ff
LN
2062 /* Try to delete the pid file. At this point it will be
2063 * out-of-date, and some software might be confused by it, so
2064 * let's remove it. */
2065 if (s->pid_file)
fabab190 2066 (void) unlink(s->pid_file);
9285c9ff 2067
6f765baf
LP
2068 /* Reset TTY ownership if necessary */
2069 exec_context_revert_tty(&s->exec_context);
034c6ed7
LP
2070}
2071
f42806df 2072static void service_enter_stop_post(Service *s, ServiceResult f) {
034c6ed7
LP
2073 int r;
2074 assert(s);
2075
a0fef983 2076 if (s->result == SERVICE_SUCCESS)
f42806df 2077 s->result = f;
034c6ed7 2078
5e94833f 2079 service_unwatch_control_pid(s);
50be4f4a 2080 (void) unit_enqueue_rewatch_pids(UNIT(s));
5e94833f 2081
117dcc57
ZJS
2082 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
2083 if (s->control_command) {
867b3b7d 2084 s->control_command_id = SERVICE_EXEC_STOP_POST;
c79ab77c 2085 pidref_done(&s->control_pid);
867b3b7d 2086
ecedd90f
LP
2087 r = service_spawn(s,
2088 s->control_command,
cfbf7538 2089 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2090 s->timeout_stop_usec,
ecedd90f 2091 &s->control_pid);
10691b9e
LP
2092 if (r < 0) {
2093 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-post' task: %m");
2094 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2095 return;
2096 }
034c6ed7 2097
80876c20
LP
2098 service_set_state(s, SERVICE_STOP_POST);
2099 } else
ac84d1fb 2100 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2101}
2102
a232ebcc 2103static int state_to_kill_operation(Service *s, ServiceState state) {
4940c0b0
LP
2104 switch (state) {
2105
c87700a1 2106 case SERVICE_STOP_WATCHDOG:
bf760801 2107 case SERVICE_FINAL_WATCHDOG:
c87700a1 2108 return KILL_WATCHDOG;
4940c0b0
LP
2109
2110 case SERVICE_STOP_SIGTERM:
a232ebcc
ZJS
2111 if (unit_has_job_type(UNIT(s), JOB_RESTART))
2112 return KILL_RESTART;
2113 _fallthrough_;
2114
4940c0b0
LP
2115 case SERVICE_FINAL_SIGTERM:
2116 return KILL_TERMINATE;
2117
2118 case SERVICE_STOP_SIGKILL:
2119 case SERVICE_FINAL_SIGKILL:
2120 return KILL_KILL;
2121
2122 default:
2123 return _KILL_OPERATION_INVALID;
2124 }
2125}
2126
f42806df 2127static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
bf760801 2128 int kill_operation, r;
034c6ed7
LP
2129
2130 assert(s);
2131
a0fef983 2132 if (s->result == SERVICE_SUCCESS)
f42806df 2133 s->result = f;
034c6ed7 2134
50be4f4a
LP
2135 /* Before sending any signal, make sure we track all members of this cgroup */
2136 (void) unit_watch_all_pids(UNIT(s));
2137
2138 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2139 * died now */
2140 (void) unit_enqueue_rewatch_pids(UNIT(s));
a911bb9a 2141
bf760801 2142 kill_operation = state_to_kill_operation(s, state);
b826e317 2143 r = unit_kill_context(UNIT(s), kill_operation);
10691b9e
LP
2144 if (r < 0) {
2145 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
cd2086fe 2146 goto fail;
10691b9e 2147 }
034c6ed7 2148
cd2086fe 2149 if (r > 0) {
e5d6dcce
LP
2150 r = service_arm_timer(s, /* relative= */ true,
2151 kill_operation == KILL_WATCHDOG ? service_timeout_abort_usec(s) : s->timeout_stop_usec);
10691b9e
LP
2152 if (r < 0) {
2153 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
36c16a7c 2154 goto fail;
10691b9e 2155 }
d6ea93e3 2156
80876c20 2157 service_set_state(s, state);
c87700a1 2158 } else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2159 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
c87700a1 2160 else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2161 service_enter_stop_post(s, SERVICE_SUCCESS);
bf760801 2162 else if (IN_SET(state, SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2163 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
80876c20 2164 else
10691b9e 2165 service_enter_dead(s, SERVICE_SUCCESS, /* allow_restart= */ true);
034c6ed7
LP
2166
2167 return;
2168
2169fail:
c87700a1 2170 if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2171 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
034c6ed7 2172 else
10691b9e 2173 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
034c6ed7
LP
2174}
2175
308d72dc 2176static void service_enter_stop_by_notify(Service *s) {
3dde96d8
LP
2177 int r;
2178
308d72dc
LP
2179 assert(s);
2180
50be4f4a 2181 (void) unit_enqueue_rewatch_pids(UNIT(s));
308d72dc 2182
3dde96d8
LP
2183 r = service_arm_timer(s, /* relative= */ true, s->timeout_stop_usec);
2184 if (r < 0) {
2185 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2186 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2187 return;
2188 }
308d72dc 2189
6041a7ee
MS
2190 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2191 service_set_state(s, SERVICE_STOP_SIGTERM);
308d72dc
LP
2192}
2193
f42806df 2194static void service_enter_stop(Service *s, ServiceResult f) {
034c6ed7 2195 int r;
5925dd3c 2196
034c6ed7
LP
2197 assert(s);
2198
a0fef983 2199 if (s->result == SERVICE_SUCCESS)
f42806df 2200 s->result = f;
034c6ed7 2201
5e94833f 2202 service_unwatch_control_pid(s);
50be4f4a 2203 (void) unit_enqueue_rewatch_pids(UNIT(s));
5e94833f 2204
117dcc57
ZJS
2205 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2206 if (s->control_command) {
867b3b7d 2207 s->control_command_id = SERVICE_EXEC_STOP;
c79ab77c 2208 pidref_done(&s->control_pid);
867b3b7d 2209
ecedd90f
LP
2210 r = service_spawn(s,
2211 s->control_command,
cfbf7538 2212 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2213 s->timeout_stop_usec,
ecedd90f 2214 &s->control_pid);
10691b9e
LP
2215 if (r < 0) {
2216 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop' task: %m");
2217 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2218 return;
2219 }
034c6ed7 2220
80876c20
LP
2221 service_set_state(s, SERVICE_STOP);
2222 } else
f42806df 2223 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2224}
2225
957c3cf9
LP
2226static bool service_good(Service *s) {
2227 int main_pid_ok;
e9fa1bf7 2228
957c3cf9
LP
2229 assert(s);
2230
2231 if (s->type == SERVICE_DBUS && !s->bus_name_good)
2232 return false;
2233
2234 main_pid_ok = main_pid_good(s);
2235 if (main_pid_ok > 0) /* It's alive */
2236 return true;
ef430065 2237 if (main_pid_ok == 0 && s->exit_type == SERVICE_EXIT_MAIN) /* It's dead */
957c3cf9
LP
2238 return false;
2239
2240 /* OK, we don't know anything about the main PID, maybe
2241 * because there is none. Let's check the control group
2242 * instead. */
2243
2244 return cgroup_good(s) != 0;
2245}
2246
f42806df 2247static void service_enter_running(Service *s, ServiceResult f) {
3dde96d8
LP
2248 int r;
2249
80876c20
LP
2250 assert(s);
2251
a0fef983 2252 if (s->result == SERVICE_SUCCESS)
f42806df 2253 s->result = f;
80876c20 2254
089b64d5
LP
2255 service_unwatch_control_pid(s);
2256
ec5b1452
LP
2257 if (s->result != SERVICE_SUCCESS)
2258 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2259 else if (service_good(s)) {
308d72dc 2260
ec5b1452 2261 /* If there are any queued up sd_notify() notifications, process them now */
308d72dc
LP
2262 if (s->notify_state == NOTIFY_RELOADING)
2263 service_enter_reload_by_notify(s);
2264 else if (s->notify_state == NOTIFY_STOPPING)
2265 service_enter_stop_by_notify(s);
36c16a7c 2266 else {
308d72dc 2267 service_set_state(s, SERVICE_RUNNING);
3dde96d8
LP
2268
2269 r = service_arm_timer(s, /* relative= */ false, service_running_timeout(s));
2270 if (r < 0) {
2271 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2272 service_enter_running(s, SERVICE_FAILURE_RESOURCES);
2273 return;
2274 }
36c16a7c 2275 }
308d72dc 2276
ec5b1452 2277 } else if (s->remain_after_exit)
80876c20
LP
2278 service_set_state(s, SERVICE_EXITED);
2279 else
f42806df 2280 service_enter_stop(s, SERVICE_SUCCESS);
80876c20
LP
2281}
2282
034c6ed7
LP
2283static void service_enter_start_post(Service *s) {
2284 int r;
e9fa1bf7 2285
034c6ed7
LP
2286 assert(s);
2287
5e94833f 2288 service_unwatch_control_pid(s);
842129f5 2289 service_reset_watchdog(s);
bb242b7b 2290
117dcc57
ZJS
2291 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2292 if (s->control_command) {
867b3b7d 2293 s->control_command_id = SERVICE_EXEC_START_POST;
c79ab77c 2294 pidref_done(&s->control_pid);
867b3b7d 2295
ecedd90f
LP
2296 r = service_spawn(s,
2297 s->control_command,
cfbf7538 2298 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2299 s->timeout_start_usec,
ecedd90f 2300 &s->control_pid);
10691b9e
LP
2301 if (r < 0) {
2302 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-post' task: %m");
2303 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2304 return;
2305 }
034c6ed7 2306
80876c20
LP
2307 service_set_state(s, SERVICE_START_POST);
2308 } else
f42806df 2309 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2310}
2311
e9a4f676 2312static void service_kill_control_process(Service *s) {
a6951a50 2313 int r;
4ad49000 2314
a6951a50
LP
2315 assert(s);
2316
c79ab77c 2317 if (!pidref_is_set(&s->control_pid))
e9a4f676 2318 return;
4ad49000 2319
c79ab77c 2320 r = pidref_kill_and_sigcont(&s->control_pid, SIGKILL);
e9a4f676
LP
2321 if (r < 0) {
2322 _cleanup_free_ char *comm = NULL;
a6951a50 2323
d7d74854 2324 (void) pidref_get_comm(&s->control_pid, &comm);
a6951a50 2325
e9a4f676 2326 log_unit_debug_errno(UNIT(s), r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m",
c79ab77c 2327 s->control_pid.pid, strna(comm));
a6951a50 2328 }
4ad49000
LP
2329}
2330
c53d2d54
DB
2331static int service_adverse_to_leftover_processes(Service *s) {
2332 assert(s);
2333
2334 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
4c425434
LP
2335 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2336 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2337 * time is quite variable (so Timeout settings aren't of use).
c53d2d54
DB
2338 *
2339 * Here we take these two factors and refuse to start a service if there are existing processes
2340 * within a control group. Databases, while generally having some protection against multiple
4c425434 2341 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
c53d2d54 2342 * aren't as rigoriously written to protect aganst against multiple use. */
4c425434
LP
2343
2344 if (unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start) > 0 &&
c53d2d54 2345 IN_SET(s->kill_context.kill_mode, KILL_MIXED, KILL_CONTROL_GROUP) &&
569554d9
ZJS
2346 !s->kill_context.send_sigkill)
2347 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EBUSY),
2348 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2349
c53d2d54
DB
2350 return 0;
2351}
2352
034c6ed7 2353static void service_enter_start(Service *s) {
c79ab77c 2354 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
4ad49000 2355 ExecCommand *c;
36c16a7c 2356 usec_t timeout;
034c6ed7
LP
2357 int r;
2358
2359 assert(s);
2360
41efeaec
LP
2361 service_unwatch_control_pid(s);
2362 service_unwatch_main_pid(s);
80876c20 2363
c53d2d54
DB
2364 r = service_adverse_to_leftover_processes(s);
2365 if (r < 0)
2366 goto fail;
a4634b21 2367
867b3b7d
LP
2368 if (s->type == SERVICE_FORKING) {
2369 s->control_command_id = SERVICE_EXEC_START;
2370 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2371
2372 s->main_command = NULL;
2373 } else {
2374 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2375 s->control_command = NULL;
2376
2377 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2378 }
34e9ba66 2379
96fb8242 2380 if (!c) {
47fffb35 2381 if (s->type != SERVICE_ONESHOT) {
cbc056c8
ZJS
2382 /* There's no command line configured for the main command? Hmm, that is strange.
2383 * This can only happen if the configuration changes at runtime. In this case,
2384 * let's enter a failure state. */
d85ff944 2385 r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENXIO), "There's no 'start' task anymore we could start.");
47fffb35
LP
2386 goto fail;
2387 }
2388
ef5ae8e7
ZJS
2389 /* We force a fake state transition here. Otherwise, the unit would go directly from
2390 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
5238e957 2391 * in between. This way we can later trigger actions that depend on the state
ef5ae8e7
ZJS
2392 * transition, including SuccessAction=. */
2393 service_set_state(s, SERVICE_START);
2394
96fb8242
LP
2395 service_enter_start_post(s);
2396 return;
2397 }
2398
36c16a7c
LP
2399 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
2400 /* For simple + idle this is the main process. We don't apply any timeout here, but
2401 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2402 timeout = USEC_INFINITY;
2403 else
2404 timeout = s->timeout_start_usec;
2405
ecedd90f
LP
2406 r = service_spawn(s,
2407 c,
cfbf7538 2408 service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS_FRESH),
36c16a7c 2409 timeout,
c79ab77c 2410 &pidref);
10691b9e
LP
2411 if (r < 0) {
2412 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start' task: %m");
034c6ed7 2413 goto fail;
10691b9e 2414 }
034c6ed7 2415
36c16a7c 2416 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
034c6ed7
LP
2417 /* For simple services we immediately start
2418 * the START_POST binaries. */
2419
c603f523 2420 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref));
034c6ed7
LP
2421 service_enter_start_post(s);
2422
2423 } else if (s->type == SERVICE_FORKING) {
2424
2425 /* For forking services we wait until the start
2426 * process exited. */
2427
c79ab77c
LP
2428 pidref_done(&s->control_pid);
2429 s->control_pid = TAKE_PIDREF(pidref);
80876c20
LP
2430 service_set_state(s, SERVICE_START);
2431
3bd28bf7 2432 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD, SERVICE_EXEC)) {
7d55e835 2433
5686391b 2434 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
7d55e835 2435
5686391b
LP
2436 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2437 * bus. 'notify' and 'exec' services are similar. */
05e343b7 2438
c603f523 2439 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref));
80876c20 2440 service_set_state(s, SERVICE_START);
034c6ed7 2441 } else
04499a70 2442 assert_not_reached();
034c6ed7
LP
2443
2444 return;
2445
2446fail:
c3fda31d 2447 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2448}
2449
2450static void service_enter_start_pre(Service *s) {
2451 int r;
2452
2453 assert(s);
2454
5e94833f
LP
2455 service_unwatch_control_pid(s);
2456
117dcc57
ZJS
2457 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2458 if (s->control_command) {
8f53a7b8 2459
c53d2d54
DB
2460 r = service_adverse_to_leftover_processes(s);
2461 if (r < 0)
2462 goto fail;
a4634b21 2463
867b3b7d
LP
2464 s->control_command_id = SERVICE_EXEC_START_PRE;
2465
ecedd90f
LP
2466 r = service_spawn(s,
2467 s->control_command,
cfbf7538 2468 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2469 s->timeout_start_usec,
ecedd90f 2470 &s->control_pid);
10691b9e
LP
2471 if (r < 0) {
2472 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-pre' task: %m");
034c6ed7 2473 goto fail;
10691b9e 2474 }
034c6ed7 2475
80876c20
LP
2476 service_set_state(s, SERVICE_START_PRE);
2477 } else
034c6ed7
LP
2478 service_enter_start(s);
2479
2480 return;
2481
2482fail:
10691b9e 2483 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
034c6ed7
LP
2484}
2485
31cd5f63
AZ
2486static void service_enter_condition(Service *s) {
2487 int r;
2488
2489 assert(s);
2490
2491 service_unwatch_control_pid(s);
2492
2493 s->control_command = s->exec_command[SERVICE_EXEC_CONDITION];
2494 if (s->control_command) {
2495
2496 r = service_adverse_to_leftover_processes(s);
2497 if (r < 0)
2498 goto fail;
2499
2500 s->control_command_id = SERVICE_EXEC_CONDITION;
c79ab77c 2501 pidref_done(&s->control_pid);
31cd5f63
AZ
2502
2503 r = service_spawn(s,
2504 s->control_command,
cfbf7538 2505 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
31cd5f63 2506 s->timeout_start_usec,
31cd5f63 2507 &s->control_pid);
10691b9e
LP
2508 if (r < 0) {
2509 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'exec-condition' task: %m");
31cd5f63 2510 goto fail;
10691b9e 2511 }
31cd5f63
AZ
2512
2513 service_set_state(s, SERVICE_CONDITION);
2514 } else
2515 service_enter_start_pre(s);
2516
2517 return;
2518
2519fail:
10691b9e 2520 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
31cd5f63
AZ
2521}
2522
034c6ed7 2523static void service_enter_restart(Service *s) {
4afd3348 2524 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7 2525 int r;
398ef8ba 2526
034c6ed7
LP
2527 assert(s);
2528
28a2dfe8 2529 if (unit_has_job_type(UNIT(s), JOB_STOP)) {
a8bb2e65 2530 /* Don't restart things if we are going down anyway */
c9728806 2531 log_unit_info(UNIT(s), "Stop job pending for unit, skipping automatic restart.");
feae8adb 2532 return;
2edfa366
LP
2533 }
2534
09d04ad3
LP
2535 /* Any units that are bound to this service must also be restarted. We use JOB_START for ourselves
2536 * but then set JOB_RESTART_DEPENDENCIES which will enqueue JOB_RESTART for those dependency jobs. */
2537 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(s), JOB_RESTART_DEPENDENCIES, NULL, &error, NULL);
10691b9e
LP
2538 if (r < 0) {
2539 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, r));
2540 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ false);
2541 return;
2542 }
034c6ed7 2543
0c59d2e4
LP
2544 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't
2545 * fully stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset
2546 * the counter explicitly however via the usual "systemctl reset-failure" logic. */
b3a9d980 2547 s->n_restarts++;
7a0019d3
LP
2548 s->flush_n_restarts = false;
2549
19dff691
MY
2550 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
2551
c2503e35
RH
2552 log_unit_struct(UNIT(s), LOG_INFO,
2553 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR,
2554 LOG_UNIT_INVOCATION_ID(UNIT(s)),
92663a5e
ZJS
2555 LOG_UNIT_MESSAGE(UNIT(s),
2556 "Scheduled restart job, restart counter is at %u.", s->n_restarts),
c2503e35 2557 "N_RESTARTS=%u", s->n_restarts);
7a0019d3 2558
09d04ad3
LP
2559 service_set_state(s, SERVICE_AUTO_RESTART_QUEUED);
2560
7a0019d3
LP
2561 /* Notify clients about changed restart counter */
2562 unit_add_to_dbus_queue(UNIT(s));
034c6ed7
LP
2563}
2564
308d72dc 2565static void service_enter_reload_by_notify(Service *s) {
15d167f8
JW
2566 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2567 int r;
2568
308d72dc
LP
2569 assert(s);
2570
3dde96d8
LP
2571 r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
2572 if (r < 0) {
2573 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2574 s->reload_result = SERVICE_FAILURE_RESOURCES;
2575 service_enter_running(s, SERVICE_SUCCESS);
2576 return;
2577 }
2578
3bd28bf7 2579 service_set_state(s, SERVICE_RELOAD_NOTIFY);
15d167f8
JW
2580
2581 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2582 r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
2583 if (r < 0)
3dde96d8 2584 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error, r));
308d72dc
LP
2585}
2586
034c6ed7 2587static void service_enter_reload(Service *s) {
3bd28bf7 2588 bool killed = false;
034c6ed7
LP
2589 int r;
2590
2591 assert(s);
2592
5e94833f 2593 service_unwatch_control_pid(s);
95c906ae 2594 s->reload_result = SERVICE_SUCCESS;
5e94833f 2595
3bd28bf7
LP
2596 usec_t ts = now(CLOCK_MONOTONIC);
2597
c79ab77c
LP
2598 if (s->type == SERVICE_NOTIFY_RELOAD && pidref_is_set(&s->main_pid)) {
2599 r = pidref_kill_and_sigcont(&s->main_pid, s->reload_signal);
3bd28bf7
LP
2600 if (r < 0) {
2601 log_unit_warning_errno(UNIT(s), r, "Failed to send reload signal: %m");
2602 goto fail;
2603 }
2604
2605 killed = true;
2606 }
2607
117dcc57
ZJS
2608 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2609 if (s->control_command) {
867b3b7d 2610 s->control_command_id = SERVICE_EXEC_RELOAD;
c79ab77c 2611 pidref_done(&s->control_pid);
867b3b7d 2612
ecedd90f
LP
2613 r = service_spawn(s,
2614 s->control_command,
cfbf7538 2615 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
21b2ce39 2616 s->timeout_start_usec,
ecedd90f 2617 &s->control_pid);
3bd28bf7 2618 if (r < 0) {
10691b9e 2619 log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'reload' task: %m");
034c6ed7 2620 goto fail;
3bd28bf7 2621 }
034c6ed7 2622
80876c20 2623 service_set_state(s, SERVICE_RELOAD);
3bd28bf7 2624 } else if (killed) {
3dde96d8
LP
2625 r = service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
2626 if (r < 0) {
2627 log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
2628 goto fail;
2629 }
2630
3bd28bf7
LP
2631 service_set_state(s, SERVICE_RELOAD_SIGNAL);
2632 } else {
f42806df 2633 service_enter_running(s, SERVICE_SUCCESS);
3bd28bf7
LP
2634 return;
2635 }
034c6ed7 2636
3bd28bf7
LP
2637 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2638 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2639 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2640 * that was already in progress before. */
2641 s->reload_begin_usec = ts;
034c6ed7
LP
2642 return;
2643
2644fail:
f42806df
LP
2645 s->reload_result = SERVICE_FAILURE_RESOURCES;
2646 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2647}
2648
f42806df 2649static void service_run_next_control(Service *s) {
36c16a7c 2650 usec_t timeout;
034c6ed7
LP
2651 int r;
2652
2653 assert(s);
2654 assert(s->control_command);
2655 assert(s->control_command->command_next);
2656
34e9ba66 2657 assert(s->control_command_id != SERVICE_EXEC_START);
034c6ed7 2658
34e9ba66 2659 s->control_command = s->control_command->command_next;
5e94833f
LP
2660 service_unwatch_control_pid(s);
2661
31cd5f63 2662 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
36c16a7c
LP
2663 timeout = s->timeout_start_usec;
2664 else
2665 timeout = s->timeout_stop_usec;
2666
c79ab77c
LP
2667 pidref_done(&s->control_pid);
2668
ecedd90f
LP
2669 r = service_spawn(s,
2670 s->control_command,
cfbf7538 2671 service_exec_flags(s->control_command_id, /* cred_flag = */ 0),
36c16a7c 2672 timeout,
ecedd90f 2673 &s->control_pid);
10691b9e
LP
2674 if (r < 0) {
2675 log_unit_warning_errno(UNIT(s), r, "Failed to spawn next control task: %m");
2676
2677 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START_POST, SERVICE_STOP))
2678 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2679 else if (s->state == SERVICE_STOP_POST)
2680 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, /* allow_restart= */ true);
2681 else if (s->state == SERVICE_RELOAD) {
2682 s->reload_result = SERVICE_FAILURE_RESOURCES;
2683 service_enter_running(s, SERVICE_SUCCESS);
2684 } else
2685 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2686 }
5cb5a6ff
LP
2687}
2688
f42806df 2689static void service_run_next_main(Service *s) {
c79ab77c 2690 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
34e9ba66
LP
2691 int r;
2692
2693 assert(s);
867b3b7d
LP
2694 assert(s->main_command);
2695 assert(s->main_command->command_next);
2696 assert(s->type == SERVICE_ONESHOT);
34e9ba66 2697
867b3b7d 2698 s->main_command = s->main_command->command_next;
34e9ba66
LP
2699 service_unwatch_main_pid(s);
2700
ecedd90f
LP
2701 r = service_spawn(s,
2702 s->main_command,
cfbf7538 2703 service_exec_flags(SERVICE_EXEC_START, EXEC_SETUP_CREDENTIALS),
21b2ce39 2704 s->timeout_start_usec,
c79ab77c 2705 &pidref);
10691b9e
LP
2706 if (r < 0) {
2707 log_unit_warning_errno(UNIT(s), r, "Failed to spawn next main task: %m");
2708 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2709 return;
2710 }
34e9ba66 2711
c603f523 2712 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref));
34e9ba66
LP
2713}
2714
87f0e418
LP
2715static int service_start(Unit *u) {
2716 Service *s = SERVICE(u);
07299350 2717 int r;
5cb5a6ff
LP
2718
2719 assert(s);
2720
034c6ed7
LP
2721 /* We cannot fulfill this request right now, try again later
2722 * please! */
a00973af 2723 if (IN_SET(s->state,
c87700a1 2724 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
bf760801 2725 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
5cb5a6ff
LP
2726 return -EAGAIN;
2727
034c6ed7 2728 /* Already on it! */
31cd5f63 2729 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
034c6ed7
LP
2730 return 0;
2731
a1d31573
LP
2732 /* A service that will be restarted must be stopped first to trigger BindsTo and/or OnFailure
2733 * dependencies. If a user does not want to wait for the holdoff time to elapse, the service should
2734 * be manually restarted, not started. We simply return EAGAIN here, so that any start jobs stay
2735 * queued, and assume that the auto restart timer will eventually trigger the restart. */
2736 if (IN_SET(s->state, SERVICE_AUTO_RESTART, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART))
a8bb2e65 2737 return -EAGAIN;
2e9d6c12 2738
09d04ad3 2739 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED, SERVICE_AUTO_RESTART_QUEUED));
5cb5a6ff 2740
4b58153d
LP
2741 r = unit_acquire_invocation_id(u);
2742 if (r < 0)
2743 return r;
2744
f42806df
LP
2745 s->result = SERVICE_SUCCESS;
2746 s->reload_result = SERVICE_SUCCESS;
034c6ed7 2747 s->main_pid_known = false;
6dfa5494 2748 s->main_pid_alien = false;
47342320 2749 s->forbid_restart = false;
3c7416b6 2750
a1e58e8e 2751 s->status_text = mfree(s->status_text);
8cfdb077
LP
2752 s->status_errno = 0;
2753
19dff691 2754 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
308d72dc
LP
2755 s->notify_state = NOTIFY_UNKNOWN;
2756
aa8c4bbf 2757 s->watchdog_original_usec = s->watchdog_usec;
2787d83c 2758 s->watchdog_override_enable = false;
aa8c4bbf 2759 s->watchdog_override_usec = USEC_INFINITY;
2787d83c 2760
6a1d4d9f
LP
2761 exec_command_reset_status_list_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
2762 exec_status_reset(&s->main_exec_status);
2763
7a0019d3
LP
2764 /* This is not an automatic restart? Flush the restart counter then */
2765 if (s->flush_n_restarts) {
2766 s->n_restarts = 0;
2767 s->flush_n_restarts = false;
2768 }
2769
9cc54544
LP
2770 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2771 if (crt)
2772 crt->reset_accounting = true;
6a1d4d9f 2773
31cd5f63 2774 service_enter_condition(s);
82a2b6bb 2775 return 1;
5cb5a6ff
LP
2776}
2777
87f0e418 2778static int service_stop(Unit *u) {
e9fa1bf7 2779 Service *s = ASSERT_PTR(SERVICE(u));
5cb5a6ff 2780
a509f0e6 2781 /* Don't create restart jobs from manual stops. */
47342320 2782 s->forbid_restart = true;
034c6ed7 2783
a1d31573
LP
2784 switch (s->state) {
2785
2786 case SERVICE_STOP:
2787 case SERVICE_STOP_SIGTERM:
2788 case SERVICE_STOP_SIGKILL:
2789 case SERVICE_STOP_POST:
2790 case SERVICE_FINAL_WATCHDOG:
2791 case SERVICE_FINAL_SIGTERM:
2792 case SERVICE_FINAL_SIGKILL:
2793 /* Already on it */
e537352b
LP
2794 return 0;
2795
a1d31573 2796 case SERVICE_AUTO_RESTART:
09d04ad3
LP
2797 case SERVICE_AUTO_RESTART_QUEUED:
2798 /* Give up on the auto restart */
b9c1883a 2799 service_set_state(s, service_determine_dead_state(s));
034c6ed7 2800 return 0;
034c6ed7 2801
a1d31573
LP
2802 case SERVICE_CONDITION:
2803 case SERVICE_START_PRE:
2804 case SERVICE_START:
2805 case SERVICE_START_POST:
2806 case SERVICE_RELOAD:
2807 case SERVICE_RELOAD_SIGNAL:
2808 case SERVICE_RELOAD_NOTIFY:
2809 case SERVICE_STOP_WATCHDOG:
2810 /* If there's already something running we go directly into kill mode. */
f42806df 2811 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
3f6c78dc 2812 return 0;
5cb5a6ff 2813
a1d31573
LP
2814 case SERVICE_CLEANING:
2815 /* If we are currently cleaning, then abort it, brutally. */
4c2f5842
LP
2816 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
2817 return 0;
a1d31573
LP
2818
2819 case SERVICE_RUNNING:
2820 case SERVICE_EXITED:
2821 service_enter_stop(s, SERVICE_SUCCESS);
2822 return 1;
2823
2824 case SERVICE_DEAD_BEFORE_AUTO_RESTART:
2825 case SERVICE_FAILED_BEFORE_AUTO_RESTART:
2826 case SERVICE_DEAD:
2827 case SERVICE_FAILED:
b9c1883a 2828 case SERVICE_DEAD_RESOURCES_PINNED:
a1d31573
LP
2829 default:
2830 /* Unknown state, or unit_stop() should already have handled these */
2831 assert_not_reached();
4c2f5842 2832 }
5cb5a6ff
LP
2833}
2834
87f0e418 2835static int service_reload(Unit *u) {
e9fa1bf7 2836 Service *s = ASSERT_PTR(SERVICE(u));
034c6ed7 2837
3742095b 2838 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
034c6ed7
LP
2839
2840 service_enter_reload(s);
2d018ae2 2841 return 1;
5cb5a6ff
LP
2842}
2843
d1e8e8b5 2844static bool service_can_reload(Unit *u) {
e9fa1bf7 2845 Service *s = ASSERT_PTR(SERVICE(u));
034c6ed7 2846
3bd28bf7
LP
2847 return s->exec_command[SERVICE_EXEC_RELOAD] ||
2848 s->type == SERVICE_NOTIFY_RELOAD;
034c6ed7
LP
2849}
2850
502096b5 2851static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, const ExecCommand *current) {
e266c068
MS
2852 Service *s = SERVICE(u);
2853 unsigned idx = 0;
e266c068
MS
2854
2855 assert(s);
5b99bd5f
LP
2856 assert(id >= 0);
2857 assert(id < _SERVICE_EXEC_COMMAND_MAX);
e266c068 2858
502096b5 2859 const ExecCommand *first = s->exec_command[id];
e266c068
MS
2860
2861 /* Figure out where we are in the list by walking back to the beginning */
502096b5 2862 for (const ExecCommand *c = current; c != first; c = c->command_prev)
e266c068
MS
2863 idx++;
2864
2865 return idx;
2866}
2867
502096b5 2868static int service_serialize_exec_command(Unit *u, FILE *f, const ExecCommand *command) {
e9fa1bf7 2869 Service *s = ASSERT_PTR(SERVICE(u));
d68c645b 2870 _cleanup_free_ char *args = NULL, *p = NULL;
d68c645b 2871 const char *type, *key;
e266c068 2872 ServiceExecCommand id;
319a4f4b 2873 size_t length = 0;
e266c068 2874 unsigned idx;
e266c068 2875
e266c068
MS
2876 assert(f);
2877
2878 if (!command)
2879 return 0;
2880
2881 if (command == s->control_command) {
2882 type = "control";
2883 id = s->control_command_id;
2884 } else {
2885 type = "main";
2886 id = SERVICE_EXEC_START;
2887 }
2888
2889 idx = service_exec_command_index(u, id, command);
2890
2891 STRV_FOREACH(arg, command->argv) {
e266c068 2892 _cleanup_free_ char *e = NULL;
d68c645b 2893 size_t n;
e266c068 2894
d68c645b 2895 e = cescape(*arg);
e266c068 2896 if (!e)
d68c645b 2897 return log_oom();
e266c068
MS
2898
2899 n = strlen(e);
319a4f4b 2900 if (!GREEDY_REALLOC(args, length + 2 + n + 2))
d68c645b 2901 return log_oom();
e266c068
MS
2902
2903 if (length > 0)
2904 args[length++] = ' ';
2905
334c0979 2906 args[length++] = '"';
e266c068
MS
2907 memcpy(args + length, e, n);
2908 length += n;
334c0979 2909 args[length++] = '"';
e266c068
MS
2910 }
2911
319a4f4b 2912 if (!GREEDY_REALLOC(args, length + 1))
d68c645b
LP
2913 return log_oom();
2914
e266c068
MS
2915 args[length++] = 0;
2916
d68c645b 2917 p = cescape(command->path);
e266c068 2918 if (!p)
5b99bd5f 2919 return log_oom();
e266c068 2920
d68c645b 2921 key = strjoina(type, "-command");
a99bd455
ZJS
2922
2923 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2924 * This is used in service_deserialize_exec_command(). */
2925 (void) serialize_item_format(
2926 f, key,
2927 "%s %s%u %s %s",
2928 service_exec_command_to_string(id),
2929 command->command_next ? "" : "+",
2930 idx,
2931 p, args);
5b99bd5f
LP
2932
2933 return 0;
e266c068
MS
2934}
2935
a16e1123 2936static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
e9fa1bf7 2937 Service *s = ASSERT_PTR(SERVICE(u));
a34ceba6 2938 int r;
a16e1123 2939
a16e1123
LP
2940 assert(f);
2941 assert(fds);
2942
d68c645b
LP
2943 (void) serialize_item(f, "state", service_state_to_string(s->state));
2944 (void) serialize_item(f, "result", service_result_to_string(s->result));
2945 (void) serialize_item(f, "reload-result", service_result_to_string(s->reload_result));
a16e1123 2946
2a7451dc
LP
2947 (void) serialize_pidref(f, fds, "control-pid", &s->control_pid);
2948 if (s->main_pid_known)
2949 (void) serialize_pidref(f, fds, "main-pid", &s->main_pid);
a16e1123 2950
d68c645b
LP
2951 (void) serialize_bool(f, "main-pid-known", s->main_pid_known);
2952 (void) serialize_bool(f, "bus-name-good", s->bus_name_good);
2953 (void) serialize_bool(f, "bus-name-owner", s->bus_name_owner);
a16e1123 2954
d68c645b
LP
2955 (void) serialize_item_format(f, "n-restarts", "%u", s->n_restarts);
2956 (void) serialize_bool(f, "flush-n-restarts", s->flush_n_restarts);
7a0019d3 2957
d68c645b 2958 r = serialize_item_escaped(f, "status-text", s->status_text);
a34ceba6
LP
2959 if (r < 0)
2960 return r;
3a2776bc 2961
e266c068
MS
2962 service_serialize_exec_command(u, f, s->control_command);
2963 service_serialize_exec_command(u, f, s->main_command);
a16e1123 2964
d68c645b 2965 r = serialize_fd(f, fds, "stdin-fd", s->stdin_fd);
a34ceba6
LP
2966 if (r < 0)
2967 return r;
d68c645b 2968 r = serialize_fd(f, fds, "stdout-fd", s->stdout_fd);
a34ceba6
LP
2969 if (r < 0)
2970 return r;
d68c645b 2971 r = serialize_fd(f, fds, "stderr-fd", s->stderr_fd);
a34ceba6
LP
2972 if (r < 0)
2973 return r;
e44da745 2974
5686391b 2975 if (s->exec_fd_event_source) {
d68c645b 2976 r = serialize_fd(f, fds, "exec-fd", sd_event_source_get_io_fd(s->exec_fd_event_source));
5686391b
LP
2977 if (r < 0)
2978 return r;
d68c645b
LP
2979
2980 (void) serialize_bool(f, "exec-fd-hot", s->exec_fd_hot);
5686391b
LP
2981 }
2982
9dfb64f8 2983 if (UNIT_ISSET(s->accept_socket)) {
d68c645b 2984 r = serialize_item(f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
9dfb64f8
ZJS
2985 if (r < 0)
2986 return r;
2987 }
2988
d68c645b 2989 r = serialize_fd(f, fds, "socket-fd", s->socket_fd);
a34ceba6
LP
2990 if (r < 0)
2991 return r;
e44da745 2992
2339fc93 2993 LIST_FOREACH(fd_store, fs, s->fd_store) {
8dd4c05b 2994 _cleanup_free_ char *c = NULL;
2339fc93
LP
2995 int copy;
2996
2997 copy = fdset_put_dup(fds, fs->fd);
2998 if (copy < 0)
d68c645b 2999 return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
2339fc93 3000
8dd4c05b 3001 c = cescape(fs->fdname);
d68c645b
LP
3002 if (!c)
3003 return log_oom();
8dd4c05b 3004
9b85bf02 3005 (void) serialize_item_format(f, "fd-store-fd", "%i \"%s\" %s", copy, c, one_zero(fs->do_poll));
2339fc93
LP
3006 }
3007
ecdbca40 3008 if (s->main_exec_status.pid > 0) {
d68c645b
LP
3009 (void) serialize_item_format(f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
3010 (void) serialize_dual_timestamp(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
3011 (void) serialize_dual_timestamp(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
3c1d1ca1 3012 (void) serialize_dual_timestamp(f, "main-exec-status-handoff", &s->main_exec_status.handoff_timestamp);
ecdbca40 3013
799fd0fd 3014 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
d68c645b
LP
3015 (void) serialize_item_format(f, "main-exec-status-code", "%i", s->main_exec_status.code);
3016 (void) serialize_item_format(f, "main-exec-status-status", "%i", s->main_exec_status.status);
ecdbca40
LP
3017 }
3018 }
f06db334 3019
19dff691
MY
3020 if (s->notify_access_override >= 0)
3021 (void) serialize_item(f, "notify-access-override", notify_access_to_string(s->notify_access_override));
3022
d68c645b
LP
3023 (void) serialize_dual_timestamp(f, "watchdog-timestamp", &s->watchdog_timestamp);
3024 (void) serialize_bool(f, "forbid-restart", s->forbid_restart);
6aca9a58 3025
2787d83c 3026 if (s->watchdog_override_enable)
d68c645b 3027 (void) serialize_item_format(f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2787d83c 3028
aa8c4bbf
LP
3029 if (s->watchdog_original_usec != USEC_INFINITY)
3030 (void) serialize_item_format(f, "watchdog-original-usec", USEC_FMT, s->watchdog_original_usec);
3031
3bd28bf7
LP
3032 if (s->reload_begin_usec != USEC_INFINITY)
3033 (void) serialize_item_format(f, "reload-begin-usec", USEC_FMT, s->reload_begin_usec);
3034
a16e1123
LP
3035 return 0;
3036}
3037
35243b77 3038int service_deserialize_exec_command(
5b99bd5f
LP
3039 Unit *u,
3040 const char *key,
3041 const char *value) {
3042
e9fa1bf7 3043 Service *s = ASSERT_PTR(SERVICE(u));
e266c068 3044 ExecCommand *command = NULL;
e9fa1bf7 3045 ServiceExecCommand id = _SERVICE_EXEC_COMMAND_INVALID;
6eeec374 3046 _cleanup_free_ char *path = NULL;
e266c068 3047 _cleanup_strv_free_ char **argv = NULL;
e9fa1bf7
MY
3048 unsigned idx = 0, i;
3049 bool control, found = false, last = false;
3050 int r;
e266c068
MS
3051
3052 enum ExecCommandState {
3053 STATE_EXEC_COMMAND_TYPE,
3054 STATE_EXEC_COMMAND_INDEX,
3055 STATE_EXEC_COMMAND_PATH,
3056 STATE_EXEC_COMMAND_ARGS,
3057 _STATE_EXEC_COMMAND_MAX,
2d93c20e 3058 _STATE_EXEC_COMMAND_INVALID = -EINVAL,
e266c068
MS
3059 } state;
3060
e266c068
MS
3061 assert(key);
3062 assert(value);
3063
3064 control = streq(key, "control-command");
3065
3066 state = STATE_EXEC_COMMAND_TYPE;
3067
3068 for (;;) {
3069 _cleanup_free_ char *arg = NULL;
3070
334c0979 3071 r = extract_first_word(&value, &arg, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
efa3f34e
LP
3072 if (r < 0)
3073 return r;
e266c068
MS
3074 if (r == 0)
3075 break;
e266c068
MS
3076
3077 switch (state) {
3078 case STATE_EXEC_COMMAND_TYPE:
3079 id = service_exec_command_from_string(arg);
3080 if (id < 0)
7211c853 3081 return id;
e266c068
MS
3082
3083 state = STATE_EXEC_COMMAND_INDEX;
3084 break;
3085 case STATE_EXEC_COMMAND_INDEX:
a99bd455
ZJS
3086 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3087 * mark the last command in a sequence. We warn if the deserialized command doesn't
3088 * match what we have loaded from the unit, but we don't need to warn if that is the
3089 * last command. */
3090
e266c068
MS
3091 r = safe_atou(arg, &idx);
3092 if (r < 0)
7211c853 3093 return r;
a99bd455 3094 last = arg[0] == '+';
e266c068
MS
3095
3096 state = STATE_EXEC_COMMAND_PATH;
3097 break;
3098 case STATE_EXEC_COMMAND_PATH:
ae2a15bc 3099 path = TAKE_PTR(arg);
e266c068 3100 state = STATE_EXEC_COMMAND_ARGS;
e266c068
MS
3101 break;
3102 case STATE_EXEC_COMMAND_ARGS:
3103 r = strv_extend(&argv, arg);
3104 if (r < 0)
010cd1dc 3105 return r;
e266c068
MS
3106 break;
3107 default:
04499a70 3108 assert_not_reached();
e266c068
MS
3109 }
3110 }
3111
3112 if (state != STATE_EXEC_COMMAND_ARGS)
3113 return -EINVAL;
90204792
ZJS
3114 if (strv_isempty(argv))
3115 return -EINVAL; /* At least argv[0] must be always present. */
e266c068
MS
3116
3117 /* Let's check whether exec command on given offset matches data that we just deserialized */
3118 for (command = s->exec_command[id], i = 0; command; command = command->command_next, i++) {
3119 if (i != idx)
3120 continue;
3121
3122 found = strv_equal(argv, command->argv) && streq(command->path, path);
3123 break;
3124 }
3125
3126 if (!found) {
3127 /* Command at the index we serialized is different, let's look for command that exactly
3128 * matches but is on different index. If there is no such command we will not resume execution. */
3129 for (command = s->exec_command[id]; command; command = command->command_next)
3130 if (strv_equal(command->argv, argv) && streq(command->path, path))
3131 break;
3132 }
3133
e9da62b1 3134 if (command && control) {
e266c068 3135 s->control_command = command;
e9da62b1
LP
3136 s->control_command_id = id;
3137 } else if (command)
e266c068 3138 s->main_command = command;
a99bd455
ZJS
3139 else if (last)
3140 log_unit_debug(u, "Current command vanished from the unit file.");
e266c068
MS
3141 else
3142 log_unit_warning(u, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3143
3144 return 0;
3145}
3146
a16e1123 3147static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
e9fa1bf7 3148 Service *s = ASSERT_PTR(SERVICE(u));
2339fc93 3149 int r;
a16e1123 3150
a16e1123
LP
3151 assert(key);
3152 assert(value);
3153 assert(fds);
3154
3155 if (streq(key, "state")) {
3156 ServiceState state;
3157
117dcc57
ZJS
3158 state = service_state_from_string(value);
3159 if (state < 0)
f2341e0a 3160 log_unit_debug(u, "Failed to parse state value: %s", value);
a16e1123
LP
3161 else
3162 s->deserialized_state = state;
f42806df
LP
3163 } else if (streq(key, "result")) {
3164 ServiceResult f;
3165
3166 f = service_result_from_string(value);
3167 if (f < 0)
f2341e0a 3168 log_unit_debug(u, "Failed to parse result value: %s", value);
f42806df
LP
3169 else if (f != SERVICE_SUCCESS)
3170 s->result = f;
3171
3172 } else if (streq(key, "reload-result")) {
3173 ServiceResult f;
3174
3175 f = service_result_from_string(value);
3176 if (f < 0)
f2341e0a 3177 log_unit_debug(u, "Failed to parse reload result value: %s", value);
f42806df
LP
3178 else if (f != SERVICE_SUCCESS)
3179 s->reload_result = f;
a16e1123 3180
a16e1123 3181 } else if (streq(key, "control-pid")) {
2a7451dc 3182
aaa872a7
DDM
3183 if (!pidref_is_set(&s->control_pid))
3184 (void) deserialize_pidref(fds, value, &s->control_pid);
2a7451dc 3185
a16e1123 3186 } else if (streq(key, "main-pid")) {
c603f523 3187 PidRef pidref;
2a7451dc 3188
70727771 3189 if (!pidref_is_set(&s->main_pid) && deserialize_pidref(fds, value, &pidref) >= 0)
c603f523 3190 (void) service_set_main_pidref(s, pidref);
a16e1123 3191
a16e1123
LP
3192 } else if (streq(key, "main-pid-known")) {
3193 int b;
3194
117dcc57
ZJS
3195 b = parse_boolean(value);
3196 if (b < 0)
f2341e0a 3197 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
a16e1123
LP
3198 else
3199 s->main_pid_known = b;
de1d4f9b
WF
3200 } else if (streq(key, "bus-name-good")) {
3201 int b;
3202
3203 b = parse_boolean(value);
3204 if (b < 0)
3205 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
3206 else
3207 s->bus_name_good = b;
d8ccf5fd
DM
3208 } else if (streq(key, "bus-name-owner")) {
3209 r = free_and_strdup(&s->bus_name_owner, value);
3210 if (r < 0)
3211 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
3a2776bc
LP
3212 } else if (streq(key, "status-text")) {
3213 char *t;
e437538f 3214 ssize_t l;
3a2776bc 3215
e437538f
ZJS
3216 l = cunescape(value, 0, &t);
3217 if (l < 0)
3218 log_unit_debug_errno(u, l, "Failed to unescape status text '%s': %m", value);
efa3f34e
LP
3219 else
3220 free_and_replace(s->status_text, t);
3a2776bc 3221
9dfb64f8
ZJS
3222 } else if (streq(key, "accept-socket")) {
3223 Unit *socket;
3224
45b10174
FS
3225 if (u->type != UNIT_SOCKET) {
3226 log_unit_debug(u, "Failed to deserialize accept-socket: unit is not a socket");
3227 return 0;
3228 }
3229
9dfb64f8
ZJS
3230 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
3231 if (r < 0)
5e1ee764 3232 log_unit_debug_errno(u, r, "Failed to load accept-socket unit '%s': %m", value);
9dfb64f8 3233 else {
7f7d01ed 3234 unit_ref_set(&s->accept_socket, u, socket);
9dfb64f8
ZJS
3235 SOCKET(socket)->n_connections++;
3236 }
3237
a16e1123 3238 } else if (streq(key, "socket-fd")) {
dff9808a
LP
3239 asynchronous_close(s->socket_fd);
3240 s->socket_fd = deserialize_fd(fds, value);
a16e1123 3241
2339fc93 3242 } else if (streq(key, "fd-store-fd")) {
30520492 3243 _cleanup_free_ char *fdv = NULL, *fdn = NULL, *fdp = NULL;
dff9808a
LP
3244 _cleanup_close_ int fd = -EBADF;
3245 int do_poll;
2339fc93 3246
9b85bf02
MY
3247 r = extract_many_words(&value, " ", EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE, &fdv, &fdn, &fdp);
3248 if (r < 2 || r > 3) {
3249 log_unit_debug(u, "Failed to deserialize fd-store-fd, ignoring: %s", value);
30520492
KL
3250 return 0;
3251 }
8dd4c05b 3252
dff9808a
LP
3253 fd = deserialize_fd(fds, fdv);
3254 if (fd < 0)
3255 return 0;
3256
9b85bf02
MY
3257 do_poll = r == 3 ? parse_boolean(fdp) : true;
3258 if (do_poll < 0) {
3259 log_unit_debug_errno(u, do_poll,
3260 "Failed to deserialize fd-store-fd do_poll, ignoring: %s", fdp);
30520492 3261 return 0;
2339fc93
LP
3262 }
3263
30520492 3264 r = service_add_fd_store(s, fd, fdn, do_poll);
a02287ea 3265 if (r < 0) {
9b85bf02
MY
3266 log_unit_debug_errno(u, r,
3267 "Failed to store deserialized fd '%s', ignoring: %m", fdn);
a02287ea
YW
3268 return 0;
3269 }
dff9808a
LP
3270
3271 TAKE_FD(fd);
ecdbca40
LP
3272 } else if (streq(key, "main-exec-status-pid")) {
3273 pid_t pid;
3274
e364ad06 3275 if (parse_pid(value, &pid) < 0)
f2341e0a 3276 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
ecdbca40
LP
3277 else
3278 s->main_exec_status.pid = pid;
3279 } else if (streq(key, "main-exec-status-code")) {
3280 int i;
3281
e364ad06 3282 if (safe_atoi(value, &i) < 0)
f2341e0a 3283 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
ecdbca40
LP
3284 else
3285 s->main_exec_status.code = i;
3286 } else if (streq(key, "main-exec-status-status")) {
3287 int i;
3288
e364ad06 3289 if (safe_atoi(value, &i) < 0)
f2341e0a 3290 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
ecdbca40
LP
3291 else
3292 s->main_exec_status.status = i;
799fd0fd 3293 } else if (streq(key, "main-exec-status-start"))
d68c645b 3294 deserialize_dual_timestamp(value, &s->main_exec_status.start_timestamp);
799fd0fd 3295 else if (streq(key, "main-exec-status-exit"))
d68c645b 3296 deserialize_dual_timestamp(value, &s->main_exec_status.exit_timestamp);
3c1d1ca1
LP
3297 else if (streq(key, "main-exec-status-handoff"))
3298 deserialize_dual_timestamp(value, &s->main_exec_status.handoff_timestamp);
19dff691
MY
3299 else if (streq(key, "notify-access-override")) {
3300 NotifyAccess notify_access;
3301
3302 notify_access = notify_access_from_string(value);
3303 if (notify_access < 0)
3304 log_unit_debug(u, "Failed to parse notify-access-override value: %s", value);
3305 else
3306 s->notify_access_override = notify_access;
3307 } else if (streq(key, "watchdog-timestamp"))
d68c645b 3308 deserialize_dual_timestamp(value, &s->watchdog_timestamp);
613b411c 3309 else if (streq(key, "forbid-restart")) {
6aca9a58
SE
3310 int b;
3311
3312 b = parse_boolean(value);
3313 if (b < 0)
f2341e0a 3314 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
6aca9a58
SE
3315 else
3316 s->forbid_restart = b;
a34ceba6 3317 } else if (streq(key, "stdin-fd")) {
a34ceba6 3318
dff9808a
LP
3319 asynchronous_close(s->stdin_fd);
3320 s->stdin_fd = deserialize_fd(fds, value);
3321 if (s->stdin_fd >= 0)
1e22b5cd 3322 s->exec_context.stdio_as_fds = true;
dff9808a 3323
a34ceba6 3324 } else if (streq(key, "stdout-fd")) {
a34ceba6 3325
dff9808a
LP
3326 asynchronous_close(s->stdout_fd);
3327 s->stdout_fd = deserialize_fd(fds, value);
3328 if (s->stdout_fd >= 0)
1e22b5cd 3329 s->exec_context.stdio_as_fds = true;
dff9808a 3330
a34ceba6 3331 } else if (streq(key, "stderr-fd")) {
a34ceba6 3332
dff9808a
LP
3333 asynchronous_close(s->stderr_fd);
3334 s->stderr_fd = deserialize_fd(fds, value);
3335 if (s->stderr_fd >= 0)
1e22b5cd 3336 s->exec_context.stdio_as_fds = true;
dff9808a 3337
5686391b 3338 } else if (streq(key, "exec-fd")) {
dff9808a 3339 _cleanup_close_ int fd = -EBADF;
5686391b 3340
dff9808a
LP
3341 fd = deserialize_fd(fds, value);
3342 if (fd >= 0) {
5dcadb4c 3343 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b 3344
dff9808a
LP
3345 if (service_allocate_exec_fd_event_source(s, fd, &s->exec_fd_event_source) >= 0)
3346 TAKE_FD(fd);
5686391b 3347 }
dff9808a 3348
2787d83c 3349 } else if (streq(key, "watchdog-override-usec")) {
d68c645b 3350 if (deserialize_usec(value, &s->watchdog_override_usec) < 0)
2787d83c 3351 log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
d68c645b 3352 else
2787d83c 3353 s->watchdog_override_enable = true;
d68c645b 3354
aa8c4bbf
LP
3355 } else if (streq(key, "watchdog-original-usec")) {
3356 if (deserialize_usec(value, &s->watchdog_original_usec) < 0)
3357 log_unit_debug(u, "Failed to parse watchdog_original_usec value: %s", value);
3358
e266c068
MS
3359 } else if (STR_IN_SET(key, "main-command", "control-command")) {
3360 r = service_deserialize_exec_command(u, key, value);
3361 if (r < 0)
3362 log_unit_debug_errno(u, r, "Failed to parse serialized command \"%s\": %m", value);
7a0019d3
LP
3363
3364 } else if (streq(key, "n-restarts")) {
3365 r = safe_atou(value, &s->n_restarts);
3366 if (r < 0)
3367 log_unit_debug_errno(u, r, "Failed to parse serialized restart counter '%s': %m", value);
3368
3369 } else if (streq(key, "flush-n-restarts")) {
3370 r = parse_boolean(value);
3371 if (r < 0)
3372 log_unit_debug_errno(u, r, "Failed to parse serialized flush restart counter setting '%s': %m", value);
3373 else
3374 s->flush_n_restarts = r;
3bd28bf7
LP
3375 } else if (streq(key, "reload-begin-usec")) {
3376 r = deserialize_usec(value, &s->reload_begin_usec);
3377 if (r < 0)
3378 log_unit_debug_errno(u, r, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value);
c17ec25e 3379 } else
f2341e0a 3380 log_unit_debug(u, "Unknown serialization key: %s", key);
a16e1123
LP
3381
3382 return 0;
3383}
3384
d1e8e8b5 3385static UnitActiveState service_active_state(Unit *u) {
e9fa1bf7 3386 Service *s = ASSERT_PTR(SERVICE(u));
e056b01d
LP
3387 const UnitActiveState *table;
3388
e9fa1bf7 3389 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
e056b01d 3390
e9fa1bf7 3391 return table[s->state];
034c6ed7
LP
3392}
3393
10a94420
LP
3394static const char *service_sub_state_to_string(Unit *u) {
3395 assert(u);
3396
3397 return service_state_to_string(SERVICE(u)->state);
3398}
3399
f2f725e5 3400static bool service_may_gc(Unit *u) {
e9fa1bf7 3401 Service *s = ASSERT_PTR(SERVICE(u));
701cc384 3402
e98b2fbb 3403 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
f2f725e5 3404 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
e98b2fbb
LP
3405 * have moved outside of the cgroup. */
3406
3407 if (main_pid_good(s) > 0 ||
6d55002a 3408 control_pid_good(s) > 0)
f2f725e5 3409 return false;
6d55002a 3410
a1d31573
LP
3411 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3412 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
b9c1883a 3413 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
a1d31573
LP
3414 return false;
3415
f2f725e5 3416 return true;
6d55002a
LP
3417}
3418
3a111838
MS
3419static int service_retry_pid_file(Service *s) {
3420 int r;
3421
e9fa1bf7 3422 assert(s);
3a111838 3423 assert(s->pid_file);
3742095b 3424 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838
MS
3425
3426 r = service_load_pid_file(s, false);
3427 if (r < 0)
3428 return r;
3429
3430 service_unwatch_pid_file(s);
3431
f42806df 3432 service_enter_running(s, SERVICE_SUCCESS);
3a111838
MS
3433 return 0;
3434}
3435
3436static int service_watch_pid_file(Service *s) {
3437 int r;
3438
e9fa1bf7
MY
3439 assert(s);
3440
f2341e0a 3441 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
8bb2d17d 3442
5686391b 3443 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_inotify_io);
10691b9e
LP
3444 if (r < 0) {
3445 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
3446 service_unwatch_pid_file(s);
3447 return r;
3448 }
3a111838
MS
3449
3450 /* the pidfile might have appeared just before we set the watch */
f2341e0a 3451 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
3a111838
MS
3452 service_retry_pid_file(s);
3453
3454 return 0;
3a111838
MS
3455}
3456
3457static int service_demand_pid_file(Service *s) {
51339a9a 3458 _cleanup_free_ PathSpec *ps = NULL;
3a111838 3459
e9fa1bf7 3460 assert(s);
3a111838
MS
3461 assert(s->pid_file);
3462 assert(!s->pid_file_pathspec);
3463
51339a9a 3464 ps = new(PathSpec, 1);
3a111838
MS
3465 if (!ps)
3466 return -ENOMEM;
3467
51339a9a
LP
3468 *ps = (PathSpec) {
3469 .unit = UNIT(s),
3470 .path = strdup(s->pid_file),
3471 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3472 * open all the time. */
3473 .type = PATH_MODIFIED,
3474 .inotify_fd = -EBADF,
3475 };
3476
3477 if (!ps->path)
3a111838 3478 return -ENOMEM;
3a111838 3479
4ff361cc 3480 path_simplify(ps->path);
3a111838 3481
51339a9a 3482 s->pid_file_pathspec = TAKE_PTR(ps);
3a111838
MS
3483
3484 return service_watch_pid_file(s);
3485}
3486
5686391b 3487static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
99534007 3488 PathSpec *p = ASSERT_PTR(userdata);
e9fa1bf7 3489 Service *s = ASSERT_PTR(SERVICE(p->unit));
3a111838 3490
3a111838 3491 assert(fd >= 0);
3742095b 3492 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838 3493 assert(s->pid_file_pathspec);
57020a3a 3494 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3a111838 3495
f2341e0a 3496 log_unit_debug(UNIT(s), "inotify event");
3a111838 3497
e14c2802 3498 if (path_spec_fd_event(p, events) < 0)
3a111838
MS
3499 goto fail;
3500
3501 if (service_retry_pid_file(s) == 0)
718db961 3502 return 0;
3a111838
MS
3503
3504 if (service_watch_pid_file(s) < 0)
3505 goto fail;
3506
718db961
LP
3507 return 0;
3508
3a111838
MS
3509fail:
3510 service_unwatch_pid_file(s);
f42806df 3511 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
718db961 3512 return 0;
3a111838
MS
3513}
3514
5686391b 3515static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
e9fa1bf7 3516 Service *s = ASSERT_PTR(SERVICE(userdata));
5686391b
LP
3517
3518 log_unit_debug(UNIT(s), "got exec-fd event");
3519
3520 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
12001b1b
LP
3521 * successfully for it. We implement this through a pipe() towards the child, which the kernel
3522 * automatically closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on
3523 * the pipe in the parent. We need to be careful however, as there are other reasons that we might
3524 * cause the child's side of the pipe to be closed (for example, a simple exit()). To deal with that
3525 * we'll ignore EOFs on the pipe unless the child signalled us first that it is about to call the
3526 * execve(). It does so by sending us a simple non-zero byte via the pipe. We also provide the child
3527 * with a way to inform us in case execve() failed: if it sends a zero byte we'll ignore POLLHUP on
3528 * the fd again. */
5686391b
LP
3529
3530 for (;;) {
12001b1b 3531 uint8_t x;
5686391b
LP
3532 ssize_t n;
3533
12001b1b
LP
3534 n = read(fd, &x, sizeof(x));
3535 if (n < 0) {
3536 if (errno == EAGAIN) /* O_NONBLOCK in effect → everything queued has now been processed. */
3537 return 0;
3538
3539 return log_unit_error_errno(UNIT(s), errno, "Failed to read from exec_fd: %m");
3540 }
3541 if (n == 0) { /* EOF → the event we are waiting for in case of Type=exec */
5dcadb4c 3542 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b
LP
3543
3544 if (s->exec_fd_hot) { /* Did the child tell us to expect EOF now? */
3545 log_unit_debug(UNIT(s), "Got EOF on exec-fd");
3546
3547 s->exec_fd_hot = false;
3548
3549 /* Nice! This is what we have been waiting for. Transition to next state. */
3550 if (s->type == SERVICE_EXEC && s->state == SERVICE_START)
3551 service_enter_start_post(s);
3552 } else
3553 log_unit_debug(UNIT(s), "Got EOF on exec-fd while it was disabled, ignoring.");
3554
3555 return 0;
3556 }
5686391b 3557
12001b1b
LP
3558 /* A byte was read → this turns on/off the exec fd logic */
3559 assert(n == sizeof(x));
93cb78ae 3560
12001b1b 3561 s->exec_fd_hot = x;
93cb78ae 3562 }
5686391b
LP
3563}
3564
a911bb9a 3565static void service_notify_cgroup_empty_event(Unit *u) {
e9fa1bf7 3566 Service *s = ASSERT_PTR(SERVICE(u));
a911bb9a 3567
a5b5aece 3568 log_unit_debug(u, "Control group is empty.");
a911bb9a
LP
3569
3570 switch (s->state) {
3571
a1d31573
LP
3572 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3573 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3574 * don't know pid which to expect the SIGCHLD for. */
a911bb9a
LP
3575
3576 case SERVICE_START:
3bd28bf7 3577 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
3c751b1b
LP
3578 main_pid_good(s) == 0 &&
3579 control_pid_good(s) == 0) {
3d474ef7 3580 /* No chance of getting a ready notification anymore */
c3fda31d 3581 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
71e529fc
JW
3582 break;
3583 }
3584
f52e9ed6
MY
3585 if (s->exit_type == SERVICE_EXIT_CGROUP && main_pid_good(s) <= 0) {
3586 service_enter_stop_post(s, SERVICE_SUCCESS);
3587 break;
3588 }
596e4470 3589
4831981d 3590 _fallthrough_;
71e529fc 3591 case SERVICE_START_POST:
3c751b1b
LP
3592 if (s->pid_file_pathspec &&
3593 main_pid_good(s) == 0 &&
3594 control_pid_good(s) == 0) {
3595
3d474ef7 3596 /* Give up hoping for the daemon to write its PID file */
f2341e0a 3597 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
8bb2d17d 3598
a911bb9a
LP
3599 service_unwatch_pid_file(s);
3600 if (s->state == SERVICE_START)
c3fda31d 3601 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a 3602 else
c35755fb 3603 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a
LP
3604 }
3605 break;
3606
3607 case SERVICE_RUNNING:
3608 /* service_enter_running() will figure out what to do */
3609 service_enter_running(s, SERVICE_SUCCESS);
3610 break;
3611
c87700a1 3612 case SERVICE_STOP_WATCHDOG:
a911bb9a
LP
3613 case SERVICE_STOP_SIGTERM:
3614 case SERVICE_STOP_SIGKILL:
3615
b13ddbbc 3616 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3617 service_enter_stop_post(s, SERVICE_SUCCESS);
3618
3619 break;
3620
3621 case SERVICE_STOP_POST:
bf760801 3622 case SERVICE_FINAL_WATCHDOG:
a911bb9a
LP
3623 case SERVICE_FINAL_SIGTERM:
3624 case SERVICE_FINAL_SIGKILL:
b13ddbbc 3625 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3626 service_enter_dead(s, SERVICE_SUCCESS, true);
3627
3628 break;
3629
e08dabfe
AZ
3630 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3631 * up the cgroup earlier and should do it now. */
a1d31573 3632 case SERVICE_AUTO_RESTART:
09d04ad3 3633 case SERVICE_AUTO_RESTART_QUEUED:
e08dabfe
AZ
3634 unit_prune_cgroup(u);
3635 break;
3636
a911bb9a
LP
3637 default:
3638 ;
3639 }
3640}
3641
38c41427 3642static void service_notify_cgroup_oom_event(Unit *u, bool managed_oom) {
e9fa1bf7 3643 Service *s = ASSERT_PTR(SERVICE(u));
afcfaa69 3644
38c41427
NK
3645 if (managed_oom)
3646 log_unit_debug(u, "Process(es) of control group were killed by systemd-oomd.");
3647 else
3648 log_unit_debug(u, "Process of control group was killed by the OOM killer.");
afcfaa69
LP
3649
3650 if (s->oom_policy == OOM_CONTINUE)
3651 return;
3652
3653 switch (s->state) {
3654
31cd5f63 3655 case SERVICE_CONDITION:
afcfaa69
LP
3656 case SERVICE_START_PRE:
3657 case SERVICE_START:
3658 case SERVICE_START_POST:
3659 case SERVICE_STOP:
3660 if (s->oom_policy == OOM_STOP)
3661 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_OOM_KILL);
3662 else if (s->oom_policy == OOM_KILL)
3663 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3664
3665 break;
3666
3667 case SERVICE_EXITED:
3668 case SERVICE_RUNNING:
3669 if (s->oom_policy == OOM_STOP)
3670 service_enter_stop(s, SERVICE_FAILURE_OOM_KILL);
3671 else if (s->oom_policy == OOM_KILL)
3672 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3673
3674 break;
3675
3676 case SERVICE_STOP_WATCHDOG:
3677 case SERVICE_STOP_SIGTERM:
3678 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3679 break;
3680
3681 case SERVICE_STOP_SIGKILL:
3682 case SERVICE_FINAL_SIGKILL:
3683 if (s->result == SERVICE_SUCCESS)
3684 s->result = SERVICE_FAILURE_OOM_KILL;
3685 break;
3686
3687 case SERVICE_STOP_POST:
3688 case SERVICE_FINAL_SIGTERM:
3689 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3690 break;
3691
3692 default:
3693 ;
3694 }
3695}
3696
87f0e418 3697static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
e9fa1bf7 3698 Service *s = ASSERT_PTR(SERVICE(u));
5cdabc8d 3699 bool notify_dbus = true;
f42806df 3700 ServiceResult f;
e5123725 3701 ExitClean clean_mode;
c917a807 3702 int r;
5cb5a6ff 3703
034c6ed7
LP
3704 assert(pid >= 0);
3705
e5123725
AZ
3706 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3707 * considered daemons as they are typically not long running. */
c79ab77c 3708 if (s->type == SERVICE_ONESHOT || (s->control_pid.pid == pid && s->control_command_id != SERVICE_EXEC_START))
e5123725
AZ
3709 clean_mode = EXIT_CLEAN_COMMAND;
3710 else
3711 clean_mode = EXIT_CLEAN_DAEMON;
3712
3713 if (is_clean_exit(code, status, clean_mode, &s->success_status))
f42806df
LP
3714 f = SERVICE_SUCCESS;
3715 else if (code == CLD_EXITED)
3716 f = SERVICE_FAILURE_EXIT_CODE;
3717 else if (code == CLD_KILLED)
3718 f = SERVICE_FAILURE_SIGNAL;
3719 else if (code == CLD_DUMPED)
3720 f = SERVICE_FAILURE_CORE_DUMP;
d06dacd0 3721 else
04499a70 3722 assert_not_reached();
034c6ed7 3723
c79ab77c 3724 if (s->main_pid.pid == pid) {
13bb1ffb
ZJS
3725 /* Clean up the exec_fd event source. We want to do this here, not later in
3726 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3727 * The source owns its end of the pipe, so this will close that too. */
3728 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
3729
db01f8b3
MS
3730 /* Forking services may occasionally move to a new PID.
3731 * As long as they update the PID file before exiting the old
3732 * PID, they're fine. */
db256aab 3733 if (service_load_pid_file(s, false) > 0)
db01f8b3 3734 return;
034c6ed7 3735
c79ab77c 3736 pidref_done(&s->main_pid);
6ea832a2 3737 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
034c6ed7 3738
867b3b7d 3739 if (s->main_command) {
fbeefb45
LP
3740 /* If this is not a forking service than the
3741 * main process got started and hence we copy
3742 * the exit status so that it is recorded both
3743 * as main and as control process exit
3744 * status */
3745
867b3b7d 3746 s->main_command->exec_status = s->main_exec_status;
b708e7ce 3747
3ed0cd26 3748 if (s->main_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 3749 f = SERVICE_SUCCESS;
fbeefb45
LP
3750 } else if (s->exec_command[SERVICE_EXEC_START]) {
3751
3752 /* If this is a forked process, then we should
3753 * ignore the return value if this was
3754 * configured for the starter process */
3755
3ed0cd26 3756 if (s->exec_command[SERVICE_EXEC_START]->flags & EXEC_COMMAND_IGNORE_FAILURE)
fbeefb45 3757 f = SERVICE_SUCCESS;
034c6ed7
LP
3758 }
3759
91bbd9b7 3760 unit_log_process_exit(
5cc2cd1c 3761 u,
abaf5edd 3762 "Main process",
91bbd9b7 3763 service_exec_command_to_string(SERVICE_EXEC_START),
5cc2cd1c 3764 f == SERVICE_SUCCESS,
91bbd9b7 3765 code, status);
f42806df 3766
a0fef983 3767 if (s->result == SERVICE_SUCCESS)
f42806df 3768 s->result = f;
034c6ed7 3769
867b3b7d
LP
3770 if (s->main_command &&
3771 s->main_command->command_next &&
b58aeb70 3772 s->type == SERVICE_ONESHOT &&
f42806df 3773 f == SERVICE_SUCCESS) {
034c6ed7 3774
e78695d4 3775 /* There is another command to execute, so let's do that. */
034c6ed7 3776
f2341e0a 3777 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
f42806df 3778 service_run_next_main(s);
034c6ed7 3779
34e9ba66 3780 } else {
867b3b7d 3781 s->main_command = NULL;
34e9ba66 3782
3bd28bf7
LP
3783 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3784 * already empty */
596e4470
HC
3785 if (s->exit_type == SERVICE_EXIT_MAIN || cgroup_good(s) <= 0) {
3786 /* The service exited, so the service is officially gone. */
3787 switch (s->state) {
3788
3789 case SERVICE_START_POST:
3790 case SERVICE_RELOAD:
3bd28bf7
LP
3791 case SERVICE_RELOAD_SIGNAL:
3792 case SERVICE_RELOAD_NOTIFY:
3793 /* If neither main nor control processes are running then the current
3794 * state can never exit cleanly, hence immediately terminate the
3795 * service. */
596e4470
HC
3796 if (control_pid_good(s) <= 0)
3797 service_enter_stop(s, f);
3798
3799 /* Otherwise need to wait until the operation is done. */
3800 break;
bbe19f68 3801
596e4470
HC
3802 case SERVICE_STOP:
3803 /* Need to wait until the operation is done. */
3804 break;
bbe19f68 3805
596e4470
HC
3806 case SERVICE_START:
3807 if (s->type == SERVICE_ONESHOT) {
3808 /* This was our main goal, so let's go on */
3809 if (f == SERVICE_SUCCESS)
3810 service_enter_start_post(s);
3811 else
3812 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3813 break;
3bd28bf7 3814 } else if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD)) {
596e4470
HC
3815 /* Only enter running through a notification, so that the
3816 * SERVICE_START state signifies that no ready notification
3817 * has been received */
3818 if (f != SERVICE_SUCCESS)
3819 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
19dff691 3820 else if (!s->remain_after_exit || service_get_notify_access(s) == NOTIFY_MAIN)
596e4470
HC
3821 /* The service has never been and will never be active */
3822 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3823 break;
3824 }
7d55e835 3825
596e4470
HC
3826 _fallthrough_;
3827 case SERVICE_RUNNING:
3828 service_enter_running(s, f);
3d474ef7 3829 break;
034c6ed7 3830
596e4470
HC
3831 case SERVICE_STOP_WATCHDOG:
3832 case SERVICE_STOP_SIGTERM:
3833 case SERVICE_STOP_SIGKILL:
5cb5a6ff 3834
596e4470
HC
3835 if (control_pid_good(s) <= 0)
3836 service_enter_stop_post(s, f);
5cb5a6ff 3837
596e4470
HC
3838 /* If there is still a control process, wait for that first */
3839 break;
34e9ba66 3840
596e4470 3841 case SERVICE_STOP_POST:
c1566ef0 3842
596e4470
HC
3843 if (control_pid_good(s) <= 0)
3844 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
c1566ef0 3845
596e4470 3846 break;
c1566ef0 3847
596e4470
HC
3848 case SERVICE_FINAL_WATCHDOG:
3849 case SERVICE_FINAL_SIGTERM:
3850 case SERVICE_FINAL_SIGKILL:
bf108e55 3851
596e4470
HC
3852 if (control_pid_good(s) <= 0)
3853 service_enter_dead(s, f, true);
3854 break;
bf108e55 3855
596e4470
HC
3856 default:
3857 assert_not_reached();
3858 }
1651ce09
MY
3859 } else if (s->exit_type == SERVICE_EXIT_CGROUP && s->state == SERVICE_START &&
3860 !IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD, SERVICE_DBUS))
ef430065
FT
3861 /* If a main process exits very quickly, this function might be executed
3862 * before service_dispatch_exec_io(). Since this function disabled IO events
3863 * to monitor the main process above, we need to update the state here too.
1651ce09
MY
3864 * Let's consider the process is successfully launched and exited, but
3865 * only when we're not expecting a readiness notification or dbus name. */
ef430065 3866 service_enter_start_post(s);
034c6ed7 3867 }
5cb5a6ff 3868
c79ab77c 3869 } else if (s->control_pid.pid == pid) {
58441bc1
ZJS
3870 const char *kind;
3871 bool success;
3872
c79ab77c 3873 pidref_done(&s->control_pid);
34e9ba66 3874
b708e7ce 3875 if (s->control_command) {
8bb2d17d 3876 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 3877
3ed0cd26 3878 if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 3879 f = SERVICE_SUCCESS;
b708e7ce
LP
3880 }
3881
42e6f549
AZ
3882 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3883 if (s->state == SERVICE_CONDITION) {
3884 if (f == SERVICE_FAILURE_EXIT_CODE && status < 255) {
3885 UNIT(s)->condition_result = false;
3886 f = SERVICE_SKIP_CONDITION;
58441bc1
ZJS
3887 success = true;
3888 } else if (f == SERVICE_SUCCESS) {
42e6f549 3889 UNIT(s)->condition_result = true;
58441bc1
ZJS
3890 success = true;
3891 } else
3892 success = false;
3893
3894 kind = "Condition check process";
3895 } else {
3896 kind = "Control process";
3897 success = f == SERVICE_SUCCESS;
42e6f549
AZ
3898 }
3899
91bbd9b7 3900 unit_log_process_exit(
5cc2cd1c 3901 u,
58441bc1 3902 kind,
91bbd9b7 3903 service_exec_command_to_string(s->control_command_id),
58441bc1 3904 success,
91bbd9b7 3905 code, status);
f42806df 3906
d611cfa7 3907 if (s->state != SERVICE_RELOAD && s->result == SERVICE_SUCCESS)
f42806df 3908 s->result = f;
034c6ed7 3909
34e9ba66
LP
3910 if (s->control_command &&
3911 s->control_command->command_next &&
f42806df 3912 f == SERVICE_SUCCESS) {
034c6ed7 3913
81006ebb 3914 /* There is another command to execute, so let's do that. */
034c6ed7 3915
f2341e0a 3916 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
f42806df 3917 service_run_next_control(s);
034c6ed7 3918
80876c20 3919 } else {
3bd28bf7 3920 /* No further commands for this step, so let's figure out what to do next */
034c6ed7 3921
a16e1123
LP
3922 s->control_command = NULL;
3923 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3924
f2341e0a 3925 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
bd982a8b 3926
034c6ed7
LP
3927 switch (s->state) {
3928
31cd5f63
AZ
3929 case SERVICE_CONDITION:
3930 if (f == SERVICE_SUCCESS)
3931 service_enter_start_pre(s);
3932 else
3933 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3934 break;
3935
034c6ed7 3936 case SERVICE_START_PRE:
f42806df 3937 if (f == SERVICE_SUCCESS)
034c6ed7
LP
3938 service_enter_start(s);
3939 else
c3fda31d 3940 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
3941 break;
3942
3943 case SERVICE_START:
bfba3256
LP
3944 if (s->type != SERVICE_FORKING)
3945 /* Maybe spurious event due to a reload that changed the type? */
3946 break;
034c6ed7 3947
f42806df 3948 if (f != SERVICE_SUCCESS) {
c3fda31d 3949 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3a111838
MS
3950 break;
3951 }
034c6ed7 3952
3a111838 3953 if (s->pid_file) {
f42806df 3954 bool has_start_post;
f42806df 3955
3a111838
MS
3956 /* Let's try to load the pid file here if we can.
3957 * The PID file might actually be created by a START_POST
3958 * script. In that case don't worry if the loading fails. */
f42806df 3959
5d904a6a 3960 has_start_post = s->exec_command[SERVICE_EXEC_START_POST];
f42806df 3961 r = service_load_pid_file(s, !has_start_post);
3a111838
MS
3962 if (!has_start_post && r < 0) {
3963 r = service_demand_pid_file(s);
b13ddbbc 3964 if (r < 0 || cgroup_good(s) == 0)
c3fda31d 3965 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3a111838
MS
3966 break;
3967 }
034c6ed7 3968 } else
783e05d6 3969 service_search_main_pid(s);
034c6ed7 3970
3a111838 3971 service_enter_start_post(s);
034c6ed7
LP
3972 break;
3973
3974 case SERVICE_START_POST:
f42806df 3975 if (f != SERVICE_SUCCESS) {
ce359e98 3976 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2096e009 3977 break;
034c6ed7
LP
3978 }
3979
2096e009 3980 if (s->pid_file) {
f42806df 3981 r = service_load_pid_file(s, true);
2096e009
MS
3982 if (r < 0) {
3983 r = service_demand_pid_file(s);
b13ddbbc 3984 if (r < 0 || cgroup_good(s) == 0)
c35755fb 3985 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2096e009
MS
3986 break;
3987 }
3988 } else
783e05d6 3989 service_search_main_pid(s);
2096e009 3990
f42806df 3991 service_enter_running(s, SERVICE_SUCCESS);
3185a36b 3992 break;
034c6ed7
LP
3993
3994 case SERVICE_RELOAD:
3bd28bf7
LP
3995 case SERVICE_RELOAD_SIGNAL:
3996 case SERVICE_RELOAD_NOTIFY:
7236ce6e
ZJS
3997 if (f == SERVICE_SUCCESS)
3998 if (service_load_pid_file(s, true) < 0)
3999 service_search_main_pid(s);
3185a36b 4000
f42806df 4001 s->reload_result = f;
3bd28bf7 4002
d09df6b9 4003 /* If the last notification we received from the service process indicates
3bd28bf7
LP
4004 * we are still reloading, then don't leave reloading state just yet, just
4005 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4006 * too. */
4007 if (s->notify_state == NOTIFY_RELOADING)
4008 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4009 else
4010 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
4011 break;
4012
4013 case SERVICE_STOP:
f42806df 4014 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
4015 break;
4016
c87700a1 4017 case SERVICE_STOP_WATCHDOG:
034c6ed7
LP
4018 case SERVICE_STOP_SIGTERM:
4019 case SERVICE_STOP_SIGKILL:
4020 if (main_pid_good(s) <= 0)
f42806df 4021 service_enter_stop_post(s, f);
034c6ed7 4022
846a07b5 4023 /* If there is still a service process around, wait until
034c6ed7
LP
4024 * that one quit, too */
4025 break;
4026
4027 case SERVICE_STOP_POST:
c1566ef0
AZ
4028 if (main_pid_good(s) <= 0)
4029 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
4030 break;
4031
bf760801 4032 case SERVICE_FINAL_WATCHDOG:
034c6ed7
LP
4033 case SERVICE_FINAL_SIGTERM:
4034 case SERVICE_FINAL_SIGKILL:
bf108e55
LP
4035 if (main_pid_good(s) <= 0)
4036 service_enter_dead(s, f, true);
034c6ed7
LP
4037 break;
4038
4c2f5842
LP
4039 case SERVICE_CLEANING:
4040
4041 if (s->clean_result == SERVICE_SUCCESS)
4042 s->clean_result = f;
4043
4044 service_enter_dead(s, SERVICE_SUCCESS, false);
4045 break;
4046
034c6ed7 4047 default:
04499a70 4048 assert_not_reached();
034c6ed7
LP
4049 }
4050 }
5cdabc8d
LP
4051 } else /* Neither control nor main PID? If so, don't notify about anything */
4052 notify_dbus = false;
c4e2ceae
LP
4053
4054 /* Notify clients about changed exit status */
5cdabc8d
LP
4055 if (notify_dbus)
4056 unit_add_to_dbus_queue(u);
a911bb9a 4057
846a07b5
FB
4058 /* We watch the main/control process otherwise we can't retrieve the unit they
4059 * belong to with cgroupv1. But if they are not our direct child, we won't get a
4060 * SIGCHLD for them. Therefore we need to look for others to watch so we can
4061 * detect when the cgroup becomes empty. Note that the control process is always
4062 * our child so it's pointless to watch all other processes. */
4063 if (!control_pid_good(s))
4064 if (!s->main_pid_known || s->main_pid_alien)
4065 (void) unit_enqueue_rewatch_pids(u);
034c6ed7
LP
4066}
4067
718db961 4068static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
e9fa1bf7 4069 Service *s = ASSERT_PTR(SERVICE(userdata));
034c6ed7 4070
718db961 4071 assert(source == s->timer_event_source);
034c6ed7
LP
4072
4073 switch (s->state) {
4074
31cd5f63 4075 case SERVICE_CONDITION:
034c6ed7
LP
4076 case SERVICE_START_PRE:
4077 case SERVICE_START:
4078 case SERVICE_START_POST:
bf760801
JK
4079 switch (s->timeout_start_failure_mode) {
4080
4081 case SERVICE_TIMEOUT_TERMINATE:
4082 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", service_state_to_string(s->state));
4083 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4084 break;
4085
4086 case SERVICE_TIMEOUT_ABORT:
4087 log_unit_warning(UNIT(s), "%s operation timed out. Aborting.", service_state_to_string(s->state));
4088 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4089 break;
4090
4091 case SERVICE_TIMEOUT_KILL:
4092 if (s->kill_context.send_sigkill) {
4093 log_unit_warning(UNIT(s), "%s operation timed out. Killing.", service_state_to_string(s->state));
4094 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4095 } else {
4096 log_unit_warning(UNIT(s), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s->state));
4097 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4098 }
4099 break;
4100
4101 default:
04499a70 4102 assert_not_reached();
bf760801 4103 }
034c6ed7
LP
4104 break;
4105
36c16a7c
LP
4106 case SERVICE_RUNNING:
4107 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
4108 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
4109 break;
4110
e2f3b44c 4111 case SERVICE_RELOAD:
3bd28bf7
LP
4112 case SERVICE_RELOAD_SIGNAL:
4113 case SERVICE_RELOAD_NOTIFY:
089b64d5 4114 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
e9a4f676 4115 service_kill_control_process(s);
f42806df
LP
4116 s->reload_result = SERVICE_FAILURE_TIMEOUT;
4117 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c
LP
4118 break;
4119
034c6ed7 4120 case SERVICE_STOP:
bf760801
JK
4121 switch (s->timeout_stop_failure_mode) {
4122
4123 case SERVICE_TIMEOUT_TERMINATE:
4124 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
4125 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4126 break;
4127
4128 case SERVICE_TIMEOUT_ABORT:
4129 log_unit_warning(UNIT(s), "Stopping timed out. Aborting.");
4130 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4131 break;
4132
4133 case SERVICE_TIMEOUT_KILL:
4134 if (s->kill_context.send_sigkill) {
4135 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
4136 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4137 } else {
4138 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
4139 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4140 }
4141 break;
4142
4143 default:
04499a70 4144 assert_not_reached();
bf760801 4145 }
034c6ed7
LP
4146 break;
4147
c87700a1 4148 case SERVICE_STOP_WATCHDOG:
bf760801
JK
4149 if (s->kill_context.send_sigkill) {
4150 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Killing.");
4151 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4152 } else {
4153 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4154 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4155 }
db2cb23b
UTL
4156 break;
4157
034c6ed7 4158 case SERVICE_STOP_SIGTERM:
bf760801
JK
4159 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4160 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Aborting.");
4161 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4162 } else if (s->kill_context.send_sigkill) {
f2341e0a 4163 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
f42806df 4164 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4165 } else {
f2341e0a 4166 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
f42806df 4167 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
ba035df2
LP
4168 }
4169
034c6ed7
LP
4170 break;
4171
4172 case SERVICE_STOP_SIGKILL:
35b8ca3a 4173 /* Uh, we sent a SIGKILL and it is still not gone?
034c6ed7
LP
4174 * Must be something we cannot kill, so let's just be
4175 * weirded out and continue */
4176
f2341e0a 4177 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
f42806df 4178 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
4179 break;
4180
4181 case SERVICE_STOP_POST:
bf760801
JK
4182 switch (s->timeout_stop_failure_mode) {
4183
4184 case SERVICE_TIMEOUT_TERMINATE:
4185 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
4186 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4187 break;
4188
4189 case SERVICE_TIMEOUT_ABORT:
4190 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Aborting.");
4191 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4192 break;
4193
4194 case SERVICE_TIMEOUT_KILL:
4195 if (s->kill_context.send_sigkill) {
4196 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Killing.");
4197 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4198 } else {
4199 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4200 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4201 }
4202 break;
4203
4204 default:
04499a70 4205 assert_not_reached();
bf760801 4206 }
034c6ed7
LP
4207 break;
4208
bf760801 4209 case SERVICE_FINAL_WATCHDOG:
4819ff03 4210 if (s->kill_context.send_sigkill) {
bf760801 4211 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Killing.");
f42806df 4212 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4213 } else {
bf760801
JK
4214 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4215 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4216 }
4217 break;
4218
4219 case SERVICE_FINAL_SIGTERM:
4220 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4221 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Aborting.");
4222 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4223 } else if (s->kill_context.send_sigkill) {
4224 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Killing.");
4225 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4226 } else {
4227 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
f42806df 4228 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
ba035df2
LP
4229 }
4230
034c6ed7
LP
4231 break;
4232
4233 case SERVICE_FINAL_SIGKILL:
f2341e0a 4234 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
f42806df 4235 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
034c6ed7
LP
4236 break;
4237
4238 case SERVICE_AUTO_RESTART:
5291f26d 4239 if (s->restart_usec > 0)
868f7d36 4240 log_unit_debug(UNIT(s),
be1adc27 4241 "Service restart interval %s expired, scheduling restart.",
5171356e 4242 FORMAT_TIMESPAN(service_restart_usec_next(s), USEC_PER_SEC));
5291f26d 4243 else
868f7d36
ZJS
4244 log_unit_debug(UNIT(s),
4245 "Service has no hold-off time (RestartSec=0), scheduling restart.");
5ce6e7f5 4246
034c6ed7
LP
4247 service_enter_restart(s);
4248 break;
4249
4c2f5842
LP
4250 case SERVICE_CLEANING:
4251 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
4252
4253 if (s->clean_result == SERVICE_SUCCESS)
4254 s->clean_result = SERVICE_FAILURE_TIMEOUT;
4255
4256 service_enter_signal(s, SERVICE_FINAL_SIGKILL, 0);
4257 break;
4258
034c6ed7 4259 default:
04499a70 4260 assert_not_reached();
034c6ed7 4261 }
718db961
LP
4262
4263 return 0;
4264}
4265
4266static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
e9fa1bf7 4267 Service *s = ASSERT_PTR(SERVICE(userdata));
2787d83c 4268 usec_t watchdog_usec;
718db961 4269
718db961
LP
4270 assert(source == s->watchdog_event_source);
4271
2787d83c
M
4272 watchdog_usec = service_get_watchdog_usec(s);
4273
2a12e32e
JK
4274 if (UNIT(s)->manager->service_watchdogs) {
4275 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
5291f26d 4276 FORMAT_TIMESPAN(watchdog_usec, 1));
8bb2d17d 4277
c87700a1 4278 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
2a12e32e
JK
4279 } else
4280 log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
5291f26d 4281 FORMAT_TIMESPAN(watchdog_usec, 1));
842129f5 4282
718db961 4283 return 0;
5cb5a6ff
LP
4284}
4285
3a45fdfc 4286static void service_force_watchdog(Service *s) {
e9fa1bf7
MY
4287 assert(s);
4288
3a45fdfc
MY
4289 if (!UNIT(s)->manager->service_watchdogs)
4290 return;
4291
4292 log_unit_error(UNIT(s), "Watchdog request (last status: %s)!",
4293 s->status_text ?: "<unset>");
4294
4295 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
4296}
4297
f8d66947 4298static bool service_notify_message_authorized(Service *s, pid_t pid) {
e3285237 4299 assert(s);
f8d66947 4300 assert(pid_is_valid(pid));
8c47c732 4301
19dff691
MY
4302 NotifyAccess notify_access = service_get_notify_access(s);
4303
4304 if (notify_access == NOTIFY_NONE) {
5734d5d0 4305 /* Warn level only if no notifications are expected */
f8d66947 4306 log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception is disabled", pid);
e3285237
LP
4307 return false;
4308 }
4309
c79ab77c
LP
4310 if (notify_access == NOTIFY_MAIN && pid != s->main_pid.pid) {
4311 if (pidref_is_set(&s->main_pid))
5734d5d0 4312 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 4313 else
5734d5d0 4314 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
4315
4316 return false;
4317 }
4318
c79ab77c
LP
4319 if (notify_access == NOTIFY_EXEC && pid != s->main_pid.pid && pid != s->control_pid.pid) {
4320 if (pidref_is_set(&s->main_pid) && pidref_is_set(&s->control_pid))
5734d5d0 4321 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 4322 pid, s->main_pid.pid, s->control_pid.pid);
c79ab77c 4323 else if (pidref_is_set(&s->main_pid))
5734d5d0 4324 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 4325 else if (pidref_is_set(&s->control_pid))
5734d5d0 4326 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 4327 else
5734d5d0 4328 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
4329
4330 return false;
9711848f
LP
4331 }
4332
e3285237
LP
4333 return true;
4334}
4335
db256aab
LP
4336static void service_notify_message(
4337 Unit *u,
4338 const struct ucred *ucred,
fcee2755 4339 char * const *tags,
db256aab
LP
4340 FDSet *fds) {
4341
b7a22068 4342 Service *s = ASSERT_PTR(SERVICE(u));
db256aab 4343 int r;
e3285237 4344
db256aab 4345 assert(ucred);
e3285237 4346
f8d66947 4347 if (!service_notify_message_authorized(s, ucred->pid))
e3285237
LP
4348 return;
4349
f1d34068 4350 if (DEBUG_LOGGING) {
b7a22068 4351 _cleanup_free_ char *cc = strv_join(tags, ", ");
0964cfb0 4352 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", ucred->pid, empty_to_na(cc));
9711848f 4353 }
c952c6ec 4354
b7a22068
MY
4355 usec_t monotonic_usec = USEC_INFINITY;
4356 bool notify_dbus = false;
4357 const char *e;
4358
8c47c732 4359 /* Interpret MAINPID= */
28849dba 4360 e = strv_find_startswith(tags, "MAINPID=");
31197c68
MY
4361 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING,
4362 SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY,
4363 SERVICE_STOP, SERVICE_STOP_SIGTERM)) {
4364
495e75ed 4365 _cleanup_(pidref_done) PidRef new_main_pid = PIDREF_NULL;
db256aab 4366
495e75ed
LP
4367 r = pidref_set_pidstr(&new_main_pid, e);
4368 if (r < 0)
4369 log_unit_warning_errno(u, r, "Failed to parse MAINPID=%s field in notification message, ignoring: %m", e);
4370 else if (!s->main_pid_known || !pidref_equal(&new_main_pid, &s->main_pid)) {
db256aab 4371
495e75ed 4372 r = service_is_suitable_main_pid(s, &new_main_pid, LOG_WARNING);
db256aab 4373 if (r == 0) {
5238e957 4374 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
db256aab
LP
4375
4376 if (ucred->uid == 0) {
495e75ed 4377 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
4378 r = 1;
4379 } else
a3980843 4380 log_unit_warning(u, "New main PID "PID_FMT" does not belong to service, refusing.", new_main_pid.pid);
db256aab
LP
4381 }
4382 if (r > 0) {
c603f523 4383 (void) service_set_main_pidref(s, TAKE_PIDREF(new_main_pid));
cdc2af3e 4384
495e75ed 4385 r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
cdc2af3e 4386 if (r < 0)
495e75ed 4387 log_unit_warning_errno(UNIT(s), r, "Failed to watch new main PID "PID_FMT" for service: %m", s->main_pid.pid);
cdc2af3e 4388
db256aab
LP
4389 notify_dbus = true;
4390 }
8c47c732
LP
4391 }
4392 }
4393
3bd28bf7
LP
4394 /* Parse MONOTONIC_USEC= */
4395 e = strv_find_startswith(tags, "MONOTONIC_USEC=");
4396 if (e) {
4397 r = safe_atou64(e, &monotonic_usec);
4398 if (r < 0)
4399 log_unit_warning_errno(u, r, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e);
4400 }
308d72dc 4401
3bd28bf7
LP
4402 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4403 if (strv_contains(tags, "STOPPING=1")) {
4404 s->notify_state = NOTIFY_STOPPING;
308d72dc 4405
3bd28bf7
LP
4406 if (IN_SET(s->state, SERVICE_RUNNING, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY))
4407 service_enter_stop_by_notify(s);
308d72dc 4408
3bd28bf7 4409 notify_dbus = true;
308d72dc 4410
3bd28bf7 4411 } else if (strv_contains(tags, "READY=1")) {
308d72dc 4412
3bd28bf7 4413 s->notify_state = NOTIFY_READY;
308d72dc 4414
3bd28bf7
LP
4415 /* Type=notify services inform us about completed initialization with READY=1 */
4416 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
4417 s->state == SERVICE_START)
4418 service_enter_start_post(s);
308d72dc 4419
3bd28bf7
LP
4420 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4421 if (s->state == SERVICE_RELOAD_NOTIFY)
4422 service_enter_running(s, SERVICE_SUCCESS);
308d72dc 4423
3bd28bf7
LP
4424 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4425 * immediately finished reloading. */
4426 if (s->state == SERVICE_RELOAD_SIGNAL &&
4427 strv_contains(tags, "RELOADING=1") &&
4428 monotonic_usec != USEC_INFINITY &&
4429 monotonic_usec >= s->reload_begin_usec) {
4430 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
308d72dc 4431
3bd28bf7
LP
4432 /* Propagate a reload explicitly */
4433 r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
4434 if (r < 0)
4435 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error, r));
308d72dc 4436
3bd28bf7 4437 service_enter_running(s, SERVICE_SUCCESS);
cc2b7b11 4438 }
3bd28bf7
LP
4439
4440 notify_dbus = true;
4441
4442 } else if (strv_contains(tags, "RELOADING=1")) {
4443
4444 s->notify_state = NOTIFY_RELOADING;
4445
4446 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4447 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4448 * reload is done. Note that we insist on a timestamp being sent along here, so that
4449 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4450 if (s->state == SERVICE_RELOAD_SIGNAL &&
4451 monotonic_usec != USEC_INFINITY &&
4452 monotonic_usec >= s->reload_begin_usec)
4453 /* Note, we don't call service_enter_reload_by_notify() here, because we
4454 * don't need reload propagation nor do we want to restart the time-out. */
4455 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4456
4457 if (s->state == SERVICE_RUNNING)
4458 service_enter_reload_by_notify(s);
4459
4460 notify_dbus = true;
8c47c732
LP
4461 }
4462
4463 /* Interpret STATUS= */
28849dba 4464 e = strv_find_startswith(tags, "STATUS=");
7f110ff9 4465 if (e) {
28849dba 4466 _cleanup_free_ char *t = NULL;
8c47c732 4467
28849dba 4468 if (!isempty(e)) {
3eac1bca
LP
4469 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4470 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4471 if (strlen(e) > STATUS_TEXT_MAX)
4472 log_unit_warning(u, "Status message overly long (%zu > %u), ignoring.", strlen(e), STATUS_TEXT_MAX);
4473 else if (!utf8_is_valid(e))
4474 log_unit_warning(u, "Status message in notification message is not UTF-8 clean, ignoring.");
28849dba 4475 else {
28849dba
LP
4476 t = strdup(e);
4477 if (!t)
4478 log_oom();
3a2776bc 4479 }
28849dba 4480 }
8c47c732 4481
30b5275a 4482 if (!streq_ptr(s->status_text, t)) {
3b319885 4483 free_and_replace(s->status_text, t);
30b5275a 4484 notify_dbus = true;
28849dba 4485 }
8c47c732 4486 }
842129f5 4487
19dff691
MY
4488 /* Interpret NOTIFYACCESS= */
4489 e = strv_find_startswith(tags, "NOTIFYACCESS=");
4490 if (e) {
4491 NotifyAccess notify_access;
4492
4493 notify_access = notify_access_from_string(e);
4494 if (notify_access < 0)
4495 log_unit_warning_errno(u, notify_access,
4496 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e);
4497
4498 /* We don't need to check whether the new access mode is more strict than what is
4499 * already in use, since only the privileged process is allowed to change it
4500 * in the first place. */
4501 if (service_get_notify_access(s) != notify_access) {
4502 service_override_notify_access(s, notify_access);
4503 notify_dbus = true;
4504 }
4505 }
4506
4774e357 4507 /* Interpret ERRNO= */
28849dba 4508 e = strv_find_startswith(tags, "ERRNO=");
4774e357
MAA
4509 if (e) {
4510 int status_errno;
4511
2fa40742
LP
4512 status_errno = parse_errno(e);
4513 if (status_errno < 0)
4514 log_unit_warning_errno(u, status_errno,
5e1ee764 4515 "Failed to parse ERRNO= field value '%s' in notification message: %m", e);
2fa40742
LP
4516 else if (s->status_errno != status_errno) {
4517 s->status_errno = status_errno;
4518 notify_dbus = true;
4774e357
MAA
4519 }
4520 }
4521
a327431b
DB
4522 /* Interpret EXTEND_TIMEOUT= */
4523 e = strv_find_startswith(tags, "EXTEND_TIMEOUT_USEC=");
4524 if (e) {
4525 usec_t extend_timeout_usec;
4526 if (safe_atou64(e, &extend_timeout_usec) < 0)
4527 log_unit_warning(u, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e);
4528 else
4529 service_extend_timeout(s, extend_timeout_usec);
4530 }
4531
6f285378 4532 /* Interpret WATCHDOG= */
99b43caf
JK
4533 e = strv_find_startswith(tags, "WATCHDOG=");
4534 if (e) {
4535 if (streq(e, "1"))
4536 service_reset_watchdog(s);
4537 else if (streq(e, "trigger"))
4538 service_force_watchdog(s);
4539 else
4540 log_unit_warning(u, "Passed WATCHDOG= field is invalid, ignoring.");
4541 }
c4e2ceae 4542
c45d11cb
LP
4543 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
4544 if (e) {
4545 usec_t watchdog_override_usec;
4546 if (safe_atou64(e, &watchdog_override_usec) < 0)
4547 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
4548 else
95d0d8ed 4549 service_override_watchdog_timeout(s, watchdog_override_usec);
c45d11cb
LP
4550 }
4551
e78ee06d
LP
4552 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4553 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4554 * fds, but optional when pushing in new fds, for compatibility reasons. */
d29cc4d6 4555 if (strv_contains(tags, "FDSTOREREMOVE=1")) {
e78ee06d
LP
4556 const char *name;
4557
4558 name = strv_find_startswith(tags, "FDNAME=");
4559 if (!name || !fdname_is_valid(name))
4560 log_unit_warning(u, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4561 else
4562 service_remove_fd_store(s, name);
4563
d29cc4d6 4564 } else if (strv_contains(tags, "FDSTORE=1")) {
8dd4c05b
LP
4565 const char *name;
4566
4567 name = strv_find_startswith(tags, "FDNAME=");
4568 if (name && !fdname_is_valid(name)) {
4569 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
4570 name = NULL;
4571 }
4572
cb5a46b8 4573 (void) service_add_fd_store_set(s, fds, name, !strv_contains(tags, "FDPOLL=0"));
8dd4c05b 4574 }
a354329f 4575
c4e2ceae 4576 /* Notify clients about changed status or main pid */
30b5275a
LP
4577 if (notify_dbus)
4578 unit_add_to_dbus_queue(u);
8c47c732
LP
4579}
4580
3c1d1ca1
LP
4581static void service_handoff_timestamp(
4582 Unit *u,
4583 const struct ucred *ucred,
4584 const dual_timestamp *ts) {
4585
4586 Service *s = ASSERT_PTR(SERVICE(u));
4587
4588 assert(ucred);
4589 assert(ts);
4590
4591 if (s->main_pid.pid == ucred->pid) {
4592 if (s->main_command)
4593 exec_status_handoff(&s->main_command->exec_status, ucred, ts);
4594
4595 exec_status_handoff(&s->main_exec_status, ucred, ts);
4596 } else if (s->control_pid.pid == ucred->pid && s->control_command)
4597 exec_status_handoff(&s->control_command->exec_status, ucred, ts);
4598 else
4599 return;
4600
4601 unit_add_to_dbus_queue(u);
4602}
4603
7a7821c8 4604static int service_get_timeout(Unit *u, usec_t *timeout) {
e9fa1bf7 4605 Service *s = ASSERT_PTR(SERVICE(u));
7a7821c8 4606 uint64_t t;
68db7a3b
ZJS
4607 int r;
4608
e9fa1bf7
MY
4609 assert(timeout);
4610
68db7a3b
ZJS
4611 if (!s->timer_event_source)
4612 return 0;
4613
7a7821c8 4614 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
4615 if (r < 0)
4616 return r;
7a7821c8
LP
4617 if (t == USEC_INFINITY)
4618 return 0;
68db7a3b 4619
7a7821c8 4620 *timeout = t;
68db7a3b
ZJS
4621 return 1;
4622}
4623
f5a9d2ee 4624static usec_t service_get_timeout_start_usec(Unit *u) {
e9fa1bf7 4625 Service *s = ASSERT_PTR(SERVICE(u));
f5a9d2ee 4626 return s->timeout_start_usec;
4627}
4628
e39eb045
LP
4629static bool pick_up_pid_from_bus_name(Service *s) {
4630 assert(s);
4631
4632 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4633
c79ab77c 4634 return !pidref_is_set(&s->main_pid) &&
e39eb045
LP
4635 IN_SET(s->state,
4636 SERVICE_START,
4637 SERVICE_START_POST,
4638 SERVICE_RUNNING,
3bd28bf7
LP
4639 SERVICE_RELOAD,
4640 SERVICE_RELOAD_SIGNAL,
4641 SERVICE_RELOAD_NOTIFY);
e39eb045
LP
4642}
4643
4644static int bus_name_pid_lookup_callback(sd_bus_message *reply, void *userdata, sd_bus_error *ret_error) {
e9fa1bf7 4645 Service *s = ASSERT_PTR(SERVICE(userdata));
495e75ed 4646 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
e39eb045 4647 const sd_bus_error *e;
e39eb045 4648 uint32_t pid;
e39eb045
LP
4649 int r;
4650
4651 assert(reply);
e39eb045 4652
e39eb045
LP
4653 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4654
4655 if (!s->bus_name || !pick_up_pid_from_bus_name(s))
4656 return 1;
4657
4658 e = sd_bus_message_get_error(reply);
4659 if (e) {
4660 r = sd_bus_error_get_errno(e);
4661 log_warning_errno(r, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e, r));
4662 return 1;
4663 }
4664
4665 r = sd_bus_message_read(reply, "u", &pid);
4666 if (r < 0) {
4667 bus_log_parse_error(r);
4668 return 1;
4669 }
4670
495e75ed
LP
4671 r = pidref_set_pid(&pidref, pid);
4672 if (r < 0) {
4673 log_debug_errno(r, "GetConnectionUnixProcessID() returned invalid PID: %m");
e39eb045
LP
4674 return 1;
4675 }
4676
e9fa1bf7 4677 log_unit_debug(UNIT(s), "D-Bus name %s is now owned by process " PID_FMT, s->bus_name, pidref.pid);
e39eb045 4678
c603f523 4679 (void) service_set_main_pidref(s, TAKE_PIDREF(pidref));
495e75ed 4680 (void) unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
e39eb045
LP
4681 return 1;
4682}
4683
fc67a943 4684static void service_bus_name_owner_change(Unit *u, const char *new_owner) {
e9fa1bf7 4685 Service *s = ASSERT_PTR(SERVICE(u));
718db961 4686 int r;
05e343b7 4687
fc67a943
LP
4688 if (new_owner)
4689 log_unit_debug(u, "D-Bus name %s now owned by %s", s->bus_name, new_owner);
05e343b7 4690 else
fc67a943 4691 log_unit_debug(u, "D-Bus name %s now not owned by anyone.", s->bus_name);
05e343b7 4692
d7a0f1f4 4693 s->bus_name_good = new_owner;
05e343b7 4694
d8ccf5fd
DM
4695 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4696 r = free_and_strdup(&s->bus_name_owner, new_owner);
4697 if (r < 0) {
4698 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
4699 return;
4700 }
4701
05e343b7
LP
4702 if (s->type == SERVICE_DBUS) {
4703
4704 /* service_enter_running() will figure out what to
4705 * do */
4706 if (s->state == SERVICE_RUNNING)
f42806df 4707 service_enter_running(s, SERVICE_SUCCESS);
05e343b7
LP
4708 else if (s->state == SERVICE_START && new_owner)
4709 service_enter_start_post(s);
4710
e39eb045 4711 } else if (new_owner && pick_up_pid_from_bus_name(s)) {
05e343b7 4712
718db961 4713 /* Try to acquire PID from bus service */
05e343b7 4714
e39eb045
LP
4715 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4716
4717 r = sd_bus_call_method_async(
4718 u->manager->api_bus,
4719 &s->bus_name_pid_lookup_slot,
4720 "org.freedesktop.DBus",
4721 "/org/freedesktop/DBus",
4722 "org.freedesktop.DBus",
4723 "GetConnectionUnixProcessID",
4724 bus_name_pid_lookup_callback,
4725 s,
4726 "s",
4727 s->bus_name);
4728 if (r < 0)
4729 log_debug_errno(r, "Failed to request owner PID of service name, ignoring: %m");
7400b9d2 4730 }
05e343b7
LP
4731}
4732
3fabebf4
LP
4733int service_set_socket_fd(
4734 Service *s,
4735 int fd,
4736 Socket *sock,
82bdb3ed 4737 SocketPeer *peer, /* reference to object is donated to us on success */
3fabebf4
LP
4738 bool selinux_context_net) {
4739
4740 _cleanup_free_ char *peer_text = NULL;
79a98c60 4741 int r;
57020a3a 4742
4f2d528d
LP
4743 assert(s);
4744 assert(fd >= 0);
23908d84 4745 assert(sock);
4f2d528d 4746
7f2fbbff
LP
4747 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4748 * to be configured. We take ownership of the passed fd on success. */
4f2d528d 4749
1124fe6f 4750 if (UNIT(s)->load_state != UNIT_LOADED)
4f2d528d
LP
4751 return -EINVAL;
4752
4753 if (s->socket_fd >= 0)
4754 return -EBUSY;
4755
3fabebf4
LP
4756 assert(!s->socket_peer);
4757
b9c1883a 4758 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4f2d528d
LP
4759 return -EAGAIN;
4760
3fabebf4 4761 if (getpeername_pretty(fd, true, &peer_text) >= 0) {
79a98c60
LP
4762
4763 if (UNIT(s)->description) {
c2b2df60 4764 _cleanup_free_ char *a = NULL;
79a98c60 4765
3fabebf4 4766 a = strjoin(UNIT(s)->description, " (", peer_text, ")");
79a98c60
LP
4767 if (!a)
4768 return -ENOMEM;
4769
4770 r = unit_set_description(UNIT(s), a);
4771 } else
3fabebf4 4772 r = unit_set_description(UNIT(s), peer_text);
79a98c60
LP
4773 if (r < 0)
4774 return r;
4775 }
4776
23908d84 4777 r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_TRIGGERED_BY, UNIT(sock), false, UNIT_DEPENDENCY_IMPLICIT);
7f2fbbff 4778 if (r < 0)
23908d84
MY
4779 return log_unit_debug_errno(UNIT(s), r,
4780 "Failed to add After=/TriggeredBy= dependencies on socket unit: %m");
7f2fbbff 4781
4f2d528d 4782 s->socket_fd = fd;
d6a911e9 4783 s->socket_peer = peer;
16115b0a 4784 s->socket_fd_selinux_context_net = selinux_context_net;
6cf6bbc2 4785
7f7d01ed 4786 unit_ref_set(&s->accept_socket, UNIT(s), UNIT(sock));
7f2fbbff 4787 return 0;
4f2d528d
LP
4788}
4789
fdf20a31 4790static void service_reset_failed(Unit *u) {
e9fa1bf7 4791 Service *s = ASSERT_PTR(SERVICE(u));
5632e374 4792
fdf20a31 4793 if (s->state == SERVICE_FAILED)
b9c1883a 4794 service_set_state(s, service_determine_dead_state(s));
5632e374 4795
f42806df
LP
4796 s->result = SERVICE_SUCCESS;
4797 s->reload_result = SERVICE_SUCCESS;
4c2f5842 4798 s->clean_result = SERVICE_SUCCESS;
7a0019d3
LP
4799 s->n_restarts = 0;
4800 s->flush_n_restarts = false;
5632e374
LP
4801}
4802
3e22239d
YW
4803static PidRef* service_main_pid(Unit *u, bool *ret_is_alien) {
4804 Service *s = ASSERT_PTR(SERVICE(u));
4805
4806 if (ret_is_alien)
4807 *ret_is_alien = s->main_pid_alien;
4808
4809 return &s->main_pid;
291d565a
LP
4810}
4811
37eb258e
LP
4812static PidRef* service_control_pid(Unit *u) {
4813 return &ASSERT_PTR(SERVICE(u))->control_pid;
291d565a
LP
4814}
4815
bb2c7685 4816static bool service_needs_console(Unit *u) {
e9fa1bf7 4817 Service *s = ASSERT_PTR(SERVICE(u));
bb2c7685
LP
4818
4819 /* We provide our own implementation of this here, instead of relying of the generic implementation
4820 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4821
4822 if (!exec_context_may_touch_console(&s->exec_context))
4823 return false;
4824
4825 return IN_SET(s->state,
31cd5f63 4826 SERVICE_CONDITION,
bb2c7685
LP
4827 SERVICE_START_PRE,
4828 SERVICE_START,
4829 SERVICE_START_POST,
4830 SERVICE_RUNNING,
4831 SERVICE_RELOAD,
3bd28bf7
LP
4832 SERVICE_RELOAD_SIGNAL,
4833 SERVICE_RELOAD_NOTIFY,
bb2c7685 4834 SERVICE_STOP,
c87700a1 4835 SERVICE_STOP_WATCHDOG,
bb2c7685
LP
4836 SERVICE_STOP_SIGTERM,
4837 SERVICE_STOP_SIGKILL,
4838 SERVICE_STOP_POST,
bf760801 4839 SERVICE_FINAL_WATCHDOG,
bb2c7685
LP
4840 SERVICE_FINAL_SIGTERM,
4841 SERVICE_FINAL_SIGKILL);
4842}
4843
7af67e9a 4844static int service_exit_status(Unit *u) {
e9fa1bf7 4845 Service *s = ASSERT_PTR(SERVICE(u));
7af67e9a
LP
4846
4847 if (s->main_exec_status.pid <= 0 ||
4848 !dual_timestamp_is_set(&s->main_exec_status.exit_timestamp))
4849 return -ENODATA;
4850
4851 if (s->main_exec_status.code != CLD_EXITED)
4852 return -EBADE;
4853
4854 return s->main_exec_status.status;
4855}
4856
5e1669ff 4857static const char* service_status_text(Unit *u) {
e9fa1bf7 4858 Service *s = ASSERT_PTR(SERVICE(u));
5e1669ff
ZJS
4859
4860 return s->status_text;
4861}
4862
4c2f5842 4863static int service_clean(Unit *u, ExecCleanMask mask) {
e9fa1bf7 4864 Service *s = ASSERT_PTR(SERVICE(u));
4c2f5842 4865 _cleanup_strv_free_ char **l = NULL;
4fb8f1e8 4866 bool may_clean_fdstore = false;
4c2f5842
LP
4867 int r;
4868
4c2f5842
LP
4869 assert(mask != 0);
4870
4fb8f1e8 4871 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4c2f5842
LP
4872 return -EBUSY;
4873
4fb8f1e8 4874 /* Determine if there's anything we could potentially clean */
4c2f5842
LP
4875 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
4876 if (r < 0)
4877 return r;
4878
4fb8f1e8
LP
4879 if (mask & EXEC_CLEAN_FDSTORE)
4880 may_clean_fdstore = s->n_fd_store > 0 || s->n_fd_store_max > 0;
4881
4882 if (strv_isempty(l) && !may_clean_fdstore)
4883 return -EUNATCH; /* Nothing to potentially clean */
4884
4885 /* Let's clean the stuff we can clean quickly */
4886 if (may_clean_fdstore)
4887 service_release_fd_store(s);
4888
4889 /* If we are done, leave quickly */
4890 if (strv_isempty(l)) {
4891 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
4892 service_set_state(s, SERVICE_DEAD);
4893 return 0;
4894 }
4c2f5842 4895
4fb8f1e8 4896 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4c2f5842
LP
4897 service_unwatch_control_pid(s);
4898 s->clean_result = SERVICE_SUCCESS;
4899 s->control_command = NULL;
4900 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
4901
e5d6dcce 4902 r = service_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
10691b9e
LP
4903 if (r < 0) {
4904 log_unit_warning_errno(u, r, "Failed to install timer: %m");
4c2f5842 4905 goto fail;
10691b9e 4906 }
4c2f5842 4907
4775b55d 4908 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
10691b9e
LP
4909 if (r < 0) {
4910 log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
c79ab77c 4911 goto fail;
10691b9e 4912 }
4c2f5842 4913
c79ab77c 4914 service_set_state(s, SERVICE_CLEANING);
4c2f5842
LP
4915 return 0;
4916
4917fail:
4c2f5842 4918 s->clean_result = SERVICE_FAILURE_RESOURCES;
5dcadb4c 4919 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
4c2f5842
LP
4920 return r;
4921}
4922
4923static int service_can_clean(Unit *u, ExecCleanMask *ret) {
e9fa1bf7 4924 Service *s = ASSERT_PTR(SERVICE(u));
4fb8f1e8
LP
4925 ExecCleanMask mask = 0;
4926 int r;
4c2f5842 4927
4fb8f1e8
LP
4928 assert(ret);
4929
4930 r = exec_context_get_clean_mask(&s->exec_context, &mask);
4931 if (r < 0)
4932 return r;
4c2f5842 4933
4fb8f1e8
LP
4934 if (s->n_fd_store_max > 0)
4935 mask |= EXEC_CLEAN_FDSTORE;
4936
4937 *ret = mask;
4938 return 0;
4c2f5842
LP
4939}
4940
e9fa1bf7
MY
4941static const char* service_finished_job(Unit *u, JobType t, JobResult result) {
4942 Service *s = ASSERT_PTR(SERVICE(u));
4943
04d232d8
ZJS
4944 if (t == JOB_START &&
4945 result == JOB_DONE &&
e9fa1bf7 4946 s->type == SERVICE_ONESHOT)
04d232d8 4947 return "Finished %s.";
eda0cbf0
ZJS
4948
4949 /* Fall back to generic */
4950 return NULL;
4951}
4952
705578c3 4953static int service_can_start(Unit *u) {
e9fa1bf7 4954 Service *s = ASSERT_PTR(SERVICE(u));
9727f242
DDM
4955 int r;
4956
9727f242
DDM
4957 /* Make sure we don't enter a busy loop of some kind. */
4958 r = unit_test_start_limit(u);
4959 if (r < 0) {
4960 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
4961 return r;
4962 }
4963
705578c3 4964 return 1;
9727f242
DDM
4965}
4966
c25fac9a 4967static void service_release_resources(Unit *u) {
e9fa1bf7 4968 Service *s = ASSERT_PTR(SERVICE(u));
c25fac9a
LP
4969
4970 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
4971 * anymore for it, and it hence is a good idea to release resources */
4972
4973 /* Don't release resources if this is a transitionary failed/dead state
4974 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
4975 * failure state. */
b9c1883a 4976 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
c25fac9a
LP
4977 return;
4978
4979 log_unit_debug(u, "Releasing resources...");
4980
81a1d6d6 4981 service_release_socket_fd(s);
c25fac9a 4982 service_release_stdio_fd(s);
b9c1883a
LP
4983
4984 if (s->fd_store_preserve_mode != EXEC_PRESERVE_YES)
4985 service_release_fd_store(s);
4986
4987 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
4988 service_set_state(s, SERVICE_DEAD);
c25fac9a
LP
4989}
4990
8017ed7e
LP
4991int service_determine_exec_selinux_label(Service *s, char **ret) {
4992 int r;
4993
4994 assert(s);
4995 assert(ret);
4996
4997 if (!mac_selinux_use())
4998 return -ENODATA;
4999
5000 /* Returns the SELinux label used for execution of the main service binary */
5001
045d9424
ZJS
5002 if (s->exec_context.selinux_context)
5003 /* Prefer the explicitly configured label if there is one */
5004 return strdup_to(ret, s->exec_context.selinux_context);
8017ed7e
LP
5005
5006 if (s->exec_context.root_image ||
5007 s->exec_context.n_extension_images > 0 ||
5008 !strv_isempty(s->exec_context.extension_directories)) /* We cannot chase paths through images */
5009 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.");
5010
5011 ExecCommand *c = s->exec_command[SERVICE_EXEC_START];
5012 if (!c)
5013 return -ENODATA;
5014
5015 _cleanup_free_ char *path = NULL;
5016 r = chase(c->path, s->exec_context.root_directory, CHASE_PREFIX_ROOT, &path, NULL);
5017 if (r < 0) {
5018 log_unit_debug_errno(UNIT(s), r, "Failed to resolve service binary '%s', ignoring.", c->path);
5019 return -ENODATA;
5020 }
5021
5022 r = mac_selinux_get_create_label_from_exe(path, ret);
5023 if (ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
5024 log_unit_debug_errno(UNIT(s), r, "Reading SELinux label off binary '%s' is not supported, ignoring.", path);
5025 return -ENODATA;
5026 }
5027 if (ERRNO_IS_NEG_PRIVILEGE(r)) {
5028 log_unit_debug_errno(UNIT(s), r, "Can't read SELinux label off binary '%s', due to privileges, ignoring.", path);
5029 return -ENODATA;
5030 }
5031 if (r < 0)
5032 return log_unit_debug_errno(UNIT(s), r, "Failed to read SELinux label off binary '%s': %m", path);
5033
5034 return 0;
5035}
5036
94f04347 5037static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
48d83e33
ZJS
5038 [SERVICE_RESTART_NO] = "no",
5039 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
5040 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
6cfe2fde 5041 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
dc99a976 5042 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
48d83e33
ZJS
5043 [SERVICE_RESTART_ON_ABORT] = "on-abort",
5044 [SERVICE_RESTART_ALWAYS] = "always",
94f04347
LP
5045};
5046
5047DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
5048
e568fea9
RP
5049static const char* const service_restart_mode_table[_SERVICE_RESTART_MODE_MAX] = {
5050 [SERVICE_RESTART_MODE_NORMAL] = "normal",
17f6b640 5051 [SERVICE_RESTART_MODE_DIRECT] = "direct",
e568fea9
RP
5052};
5053
5054DEFINE_STRING_TABLE_LOOKUP(service_restart_mode, ServiceRestartMode);
5055
94f04347 5056static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3bd28bf7
LP
5057 [SERVICE_SIMPLE] = "simple",
5058 [SERVICE_FORKING] = "forking",
5059 [SERVICE_ONESHOT] = "oneshot",
5060 [SERVICE_DBUS] = "dbus",
5061 [SERVICE_NOTIFY] = "notify",
5062 [SERVICE_NOTIFY_RELOAD] = "notify-reload",
5063 [SERVICE_IDLE] = "idle",
5064 [SERVICE_EXEC] = "exec",
94f04347
LP
5065};
5066
5067DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
5068
596e4470 5069static const char* const service_exit_type_table[_SERVICE_EXIT_TYPE_MAX] = {
fb138166 5070 [SERVICE_EXIT_MAIN] = "main",
596e4470
HC
5071 [SERVICE_EXIT_CGROUP] = "cgroup",
5072};
5073
5074DEFINE_STRING_TABLE_LOOKUP(service_exit_type, ServiceExitType);
5075
e537352b 5076static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5077 [SERVICE_EXEC_CONDITION] = "ExecCondition",
5078 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
5079 [SERVICE_EXEC_START] = "ExecStart",
94f04347 5080 [SERVICE_EXEC_START_POST] = "ExecStartPost",
48d83e33
ZJS
5081 [SERVICE_EXEC_RELOAD] = "ExecReload",
5082 [SERVICE_EXEC_STOP] = "ExecStop",
5083 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
94f04347
LP
5084};
5085
5086DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
5087
b3d59367 5088static const char* const service_exec_ex_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5089 [SERVICE_EXEC_CONDITION] = "ExecConditionEx",
5090 [SERVICE_EXEC_START_PRE] = "ExecStartPreEx",
5091 [SERVICE_EXEC_START] = "ExecStartEx",
b3d59367 5092 [SERVICE_EXEC_START_POST] = "ExecStartPostEx",
48d83e33
ZJS
5093 [SERVICE_EXEC_RELOAD] = "ExecReloadEx",
5094 [SERVICE_EXEC_STOP] = "ExecStopEx",
5095 [SERVICE_EXEC_STOP_POST] = "ExecStopPostEx",
b3d59367
AZ
5096};
5097
5098DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command, ServiceExecCommand);
5099
308d72dc 5100static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
48d83e33
ZJS
5101 [NOTIFY_UNKNOWN] = "unknown",
5102 [NOTIFY_READY] = "ready",
308d72dc 5103 [NOTIFY_RELOADING] = "reloading",
48d83e33 5104 [NOTIFY_STOPPING] = "stopping",
308d72dc
LP
5105};
5106
5107DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
5108
f42806df 5109static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
48d83e33
ZJS
5110 [SERVICE_SUCCESS] = "success",
5111 [SERVICE_FAILURE_RESOURCES] = "resources",
5112 [SERVICE_FAILURE_PROTOCOL] = "protocol",
5113 [SERVICE_FAILURE_TIMEOUT] = "timeout",
5114 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
5115 [SERVICE_FAILURE_SIGNAL] = "signal",
5116 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
5117 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
07299350 5118 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
48d83e33
ZJS
5119 [SERVICE_FAILURE_OOM_KILL] = "oom-kill",
5120 [SERVICE_SKIP_CONDITION] = "exec-condition",
f42806df
LP
5121};
5122
5123DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
5124
bf760801
JK
5125static const char* const service_timeout_failure_mode_table[_SERVICE_TIMEOUT_FAILURE_MODE_MAX] = {
5126 [SERVICE_TIMEOUT_TERMINATE] = "terminate",
48d83e33
ZJS
5127 [SERVICE_TIMEOUT_ABORT] = "abort",
5128 [SERVICE_TIMEOUT_KILL] = "kill",
bf760801
JK
5129};
5130
5131DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode, ServiceTimeoutFailureMode);
5132
87f0e418 5133const UnitVTable service_vtable = {
7d17cfbc 5134 .object_size = sizeof(Service),
718db961
LP
5135 .exec_context_offset = offsetof(Service, exec_context),
5136 .cgroup_context_offset = offsetof(Service, cgroup_context),
5137 .kill_context_offset = offsetof(Service, kill_context),
613b411c 5138 .exec_runtime_offset = offsetof(Service, exec_runtime),
9cc54544 5139 .cgroup_runtime_offset = offsetof(Service, cgroup_runtime),
3ef63c31 5140
f975e971
LP
5141 .sections =
5142 "Unit\0"
5143 "Service\0"
5144 "Install\0",
4ad49000 5145 .private_section = "Service",
71645aca 5146
1d9cc876
LP
5147 .can_transient = true,
5148 .can_delegate = true,
c80a9a33 5149 .can_fail = true,
4d824a4e 5150 .can_set_managed_oom = true,
1d9cc876 5151
034c6ed7
LP
5152 .init = service_init,
5153 .done = service_done,
a16e1123 5154 .load = service_load,
a354329f 5155 .release_resources = service_release_resources,
a16e1123
LP
5156
5157 .coldplug = service_coldplug,
034c6ed7 5158
5cb5a6ff
LP
5159 .dump = service_dump,
5160
5161 .start = service_start,
5162 .stop = service_stop,
5163 .reload = service_reload,
5164
034c6ed7
LP
5165 .can_reload = service_can_reload,
5166
4c2f5842
LP
5167 .clean = service_clean,
5168 .can_clean = service_can_clean,
8a0867d6 5169
16b6af6a 5170 .freezer_action = unit_cgroup_freezer_action,
d9e45bc3 5171
a16e1123
LP
5172 .serialize = service_serialize,
5173 .deserialize_item = service_deserialize_item,
5174
5cb5a6ff 5175 .active_state = service_active_state,
10a94420 5176 .sub_state_to_string = service_sub_state_to_string,
5cb5a6ff 5177
deb4e708
MK
5178 .will_restart = service_will_restart,
5179
f2f725e5 5180 .may_gc = service_may_gc,
701cc384 5181
034c6ed7 5182 .sigchld_event = service_sigchld_event,
2c4104f0 5183
fdf20a31 5184 .reset_failed = service_reset_failed,
5632e374 5185
4ad49000 5186 .notify_cgroup_empty = service_notify_cgroup_empty_event,
afcfaa69 5187 .notify_cgroup_oom = service_notify_cgroup_oom_event,
8c47c732 5188 .notify_message = service_notify_message,
3c1d1ca1 5189 .notify_handoff_timestamp = service_handoff_timestamp,
8e274523 5190
291d565a
LP
5191 .main_pid = service_main_pid,
5192 .control_pid = service_control_pid,
5193
05e343b7 5194 .bus_name_owner_change = service_bus_name_owner_change,
05e343b7 5195
74c964d3
LP
5196 .bus_set_property = bus_service_set_property,
5197 .bus_commit_properties = bus_service_commit_properties,
4139c1b2 5198
68db7a3b 5199 .get_timeout = service_get_timeout,
f5a9d2ee 5200 .get_timeout_start_usec = service_get_timeout_start_usec,
bb2c7685 5201 .needs_console = service_needs_console,
7af67e9a 5202 .exit_status = service_exit_status,
5e1669ff 5203 .status_text = service_status_text,
718db961 5204
c6918296 5205 .status_message_formats = {
c6918296 5206 .finished_start_job = {
c6918296 5207 [JOB_FAILED] = "Failed to start %s.",
c6918296
MS
5208 },
5209 .finished_stop_job = {
5210 [JOB_DONE] = "Stopped %s.",
5211 [JOB_FAILED] = "Stopped (with error) %s.",
c6918296 5212 },
eda0cbf0 5213 .finished_job = service_finished_job,
c6918296 5214 },
9727f242 5215
705578c3 5216 .can_start = service_can_start,
d52b8493 5217
b2bfd121
LP
5218 .notify_plymouth = true,
5219
d52b8493
LP
5220 .audit_start_message_type = AUDIT_SERVICE_START,
5221 .audit_stop_message_type = AUDIT_SERVICE_STOP,
5cb5a6ff 5222};