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