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