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