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