]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/service.c
core: get rid of unused Service.will_auto_restart logic
[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;
e9f17fa8 125 s->restart_max_delay_usec = 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 295 s->restart_steps == 0 ||
e9f17fa8
MY
296 s->restart_max_delay_usec == USEC_INFINITY ||
297 s->restart_usec >= s->restart_max_delay_usec)
8d12e219 298 value = s->restart_usec;
5171356e 299 else if (n_restarts_next > s->restart_steps)
e9f17fa8 300 value = s->restart_max_delay_usec;
8d12e219
LP
301 else {
302 /* Enforced in service_verify() and above */
e9f17fa8 303 assert(s->restart_max_delay_usec > 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,
e9f17fa8 307 (usec_t) powl(s->restart_max_delay_usec - s->restart_usec,
5171356e 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
a02287ea 378static ServiceFDStore* service_fd_store_unlink(ServiceFDStore *fs) {
a354329f 379 if (!fs)
a02287ea 380 return NULL;
a354329f
LP
381
382 if (fs->service) {
383 assert(fs->service->n_fd_store > 0);
384 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
385 fs->service->n_fd_store--;
386 }
387
1d3fe304 388 sd_event_source_disable_unref(fs->event_source);
a354329f 389
8dd4c05b 390 free(fs->fdname);
99620f45 391 asynchronous_close(fs->fd);
a02287ea 392 return mfree(fs);
a354329f
LP
393}
394
a02287ea
YW
395DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore*, service_fd_store_unlink);
396
f0bfbfac
ZJS
397static void service_release_fd_store(Service *s) {
398 assert(s);
399
c25fac9a
LP
400 if (!s->fd_store)
401 return;
402
f0bfbfac 403 log_unit_debug(UNIT(s), "Releasing all stored fds");
c25fac9a 404
f0bfbfac
ZJS
405 while (s->fd_store)
406 service_fd_store_unlink(s->fd_store);
407
408 assert(s->n_fd_store == 0);
409}
410
c25fac9a 411static void service_release_stdio_fd(Service *s) {
a354329f
LP
412 assert(s);
413
c25fac9a 414 if (s->stdin_fd < 0 && s->stdout_fd < 0 && s->stdout_fd < 0)
a354329f
LP
415 return;
416
c25fac9a 417 log_unit_debug(UNIT(s), "Releasing stdin/stdout/stderr file descriptors.");
a354329f 418
99620f45
LP
419 s->stdin_fd = asynchronous_close(s->stdin_fd);
420 s->stdout_fd = asynchronous_close(s->stdout_fd);
421 s->stderr_fd = asynchronous_close(s->stderr_fd);
a354329f 422}
87f0e418
LP
423static void service_done(Unit *u) {
424 Service *s = SERVICE(u);
44d8db9e
LP
425
426 assert(s);
427
cd48e23f
RP
428 open_file_free_many(&s->open_files);
429
a1e58e8e
LP
430 s->pid_file = mfree(s->pid_file);
431 s->status_text = mfree(s->status_text);
efe6e7d3 432
28135da3 433 s->exec_runtime = exec_runtime_free(s->exec_runtime);
e537352b 434 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
44d8db9e 435 s->control_command = NULL;
867b3b7d 436 s->main_command = NULL;
44d8db9e 437
37520c1b
LP
438 exit_status_set_free(&s->restart_prevent_status);
439 exit_status_set_free(&s->restart_force_status);
440 exit_status_set_free(&s->success_status);
96342de6 441
44d8db9e
LP
442 /* This will leak a process, but at least no memory or any of
443 * our resources */
5e94833f
LP
444 service_unwatch_main_pid(s);
445 service_unwatch_control_pid(s);
3e52541e 446 service_unwatch_pid_file(s);
44d8db9e 447
05e343b7 448 if (s->bus_name) {
ac155bb8 449 unit_unwatch_bus_name(u, s->bus_name);
a1e58e8e 450 s->bus_name = mfree(s->bus_name);
05e343b7
LP
451 }
452
d8ccf5fd
DM
453 s->bus_name_owner = mfree(s->bus_name_owner);
454
064c5938
ZJS
455 s->usb_function_descriptors = mfree(s->usb_function_descriptors);
456 s->usb_function_strings = mfree(s->usb_function_strings);
457
bb242b7b
MO
458 service_stop_watchdog(s);
459
5dcadb4c
ZJS
460 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
461 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
a354329f 462
e39eb045
LP
463 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
464
81a1d6d6 465 service_release_socket_fd(s);
c25fac9a 466 service_release_stdio_fd(s);
81a1d6d6 467 service_release_fd_store(s);
718db961
LP
468}
469
2339fc93 470static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
99534007 471 ServiceFDStore *fs = ASSERT_PTR(userdata);
2339fc93
LP
472
473 assert(e);
2339fc93
LP
474
475 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
16f70d63
ZJS
476 log_unit_debug(UNIT(fs->service),
477 "Received %s on stored fd %d (%s), closing.",
478 revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
479 fs->fd, strna(fs->fdname));
2339fc93
LP
480 service_fd_store_unlink(fs);
481 return 0;
482}
483
a02287ea
YW
484static int service_add_fd_store(Service *s, int fd_in, const char *name, bool do_poll) {
485 _cleanup_(service_fd_store_unlinkp) ServiceFDStore *fs = NULL;
486 _cleanup_(asynchronous_closep) int fd = ASSERT_FD(fd_in);
e8783d76 487 struct stat st;
2339fc93
LP
488 int r;
489
a02287ea 490 /* fd is always consumed even if the function fails. */
9021ff17 491
2339fc93 492 assert(s);
2339fc93 493
e8783d76
LP
494 if (fstat(fd, &st) < 0)
495 return -errno;
496
497 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);
498
2339fc93 499 if (s->n_fd_store >= s->n_fd_store_max)
e8783d76
LP
500 /* Our store is full. Use this errno rather than E[NM]FILE to distinguish from the case
501 * where systemd itself hits the file limit. */
502 return log_unit_debug_errno(UNIT(s), SYNTHETIC_ERRNO(EXFULL), "Hit fd store limit.");
2339fc93 503
03677889
YW
504 LIST_FOREACH(fd_store, i, s->fd_store) {
505 r = same_fd(i->fd, fd);
2339fc93
LP
506 if (r < 0)
507 return r;
508 if (r > 0) {
a02287ea 509 log_unit_debug(UNIT(s), "Suppressing duplicate fd %i in fd store.", 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 518 *fs = (ServiceFDStore) {
a02287ea 519 .fd = TAKE_FD(fd),
b0cea477
LP
520 .do_poll = do_poll,
521 .fdname = strdup(name ?: "stored"),
522 };
523
a02287ea 524 if (!fs->fdname)
8dd4c05b 525 return -ENOMEM;
2339fc93 526
cb5a46b8 527 if (do_poll) {
a02287ea
YW
528 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fs->fd, 0, on_fd_store_io, fs);
529 if (r < 0 && r != -EPERM) /* EPERM indicates fds that aren't pollable, which is OK */
cb5a46b8 530 return r;
a02287ea 531 else if (r >= 0)
cb5a46b8
KL
532 (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
533 }
7dfbe2e3 534
a02287ea 535 fs->service = s;
2339fc93
LP
536 LIST_PREPEND(fd_store, s->fd_store, fs);
537 s->n_fd_store++;
538
a02287ea
YW
539 log_unit_debug(UNIT(s), "Added fd %i (%s) to fd store.", fs->fd, fs->fdname);
540
541 TAKE_PTR(fs);
9021ff17 542 return 1; /* fd newly stored */
2339fc93
LP
543}
544
cb5a46b8 545static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name, bool do_poll) {
2339fc93
LP
546 int r;
547
548 assert(s);
549
a02287ea
YW
550 for (;;) {
551 int fd;
2339fc93
LP
552
553 fd = fdset_steal_first(fds);
554 if (fd < 0)
555 break;
556
cb5a46b8 557 r = service_add_fd_store(s, fd, name, do_poll);
b0924635
ZJS
558 if (r == -EXFULL)
559 return log_unit_warning_errno(UNIT(s), r,
560 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
561 s->n_fd_store_max);
2339fc93 562 if (r < 0)
b0924635 563 return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
2339fc93
LP
564 }
565
2339fc93
LP
566 return 0;
567}
568
e78ee06d 569static void service_remove_fd_store(Service *s, const char *name) {
e78ee06d
LP
570 assert(s);
571 assert(name);
572
80a226b2 573 LIST_FOREACH(fd_store, fs, s->fd_store) {
e78ee06d
LP
574 if (!streq(fs->fdname, name))
575 continue;
576
577 log_unit_debug(UNIT(s), "Got explicit request to remove fd %i (%s), closing.", fs->fd, name);
578 service_fd_store_unlink(fs);
579 }
580}
581
ecea250d 582static usec_t service_running_timeout(Service *s) {
5918a933
AB
583 usec_t delta = 0;
584
585 assert(s);
586
587 if (s->runtime_rand_extra_usec != 0) {
588 delta = random_u64_range(s->runtime_rand_extra_usec);
589 log_unit_debug(UNIT(s), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta, USEC_PER_SEC));
590 }
591
592 return usec_add(usec_add(UNIT(s)->active_enter_timestamp.monotonic,
593 s->runtime_max_usec),
594 delta);
595}
596
e5d6dcce 597static int service_arm_timer(Service *s, bool relative, usec_t usec) {
718db961
LP
598 int r;
599
600 assert(s);
601
718db961 602 if (s->timer_event_source) {
e5d6dcce 603 r = (relative ? sd_event_source_set_time_relative : sd_event_source_set_time)(s->timer_event_source, usec);
718db961
LP
604 if (r < 0)
605 return r;
606
607 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
608 }
609
36c16a7c
LP
610 if (usec == USEC_INFINITY)
611 return 0;
612
e5d6dcce 613 r = (relative ? sd_event_add_time_relative : sd_event_add_time)(
6a0f1f6d
LP
614 UNIT(s)->manager->event,
615 &s->timer_event_source,
616 CLOCK_MONOTONIC,
36c16a7c 617 usec, 0,
6a0f1f6d 618 service_dispatch_timer, s);
7dfbe2e3
TG
619 if (r < 0)
620 return r;
621
622 (void) sd_event_source_set_description(s->timer_event_source, "service-timer");
623
624 return 0;
44d8db9e
LP
625}
626
243b1432
LP
627static int service_verify(Service *s) {
628 assert(s);
e0cfed4c 629 assert(UNIT(s)->load_state == UNIT_LOADED);
243b1432 630
03677889 631 for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++)
8688a389
YW
632 LIST_FOREACH(command, command, s->exec_command[c]) {
633 if (!path_is_absolute(command->path) && !filename_is_valid(command->path))
634 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
635 "Service %s= binary path \"%s\" is neither a valid executable name nor an absolute path. Refusing.",
636 command->path,
637 service_exec_command_to_string(c));
29500cf8
HC
638 if (strv_isempty(command->argv))
639 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC),
640 "Service has an empty argv in %s=. Refusing.",
641 service_exec_command_to_string(c));
8688a389 642 }
29500cf8 643
d85ff944
YW
644 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP] &&
645 UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
3f00d379
ZJS
646 /* FailureAction= only makes sense if one of the start or stop commands is specified.
647 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
648 * either a command or SuccessAction= are required. */
649
d85ff944 650 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
243b1432 651
d85ff944
YW
652 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START])
653 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 654
d85ff944
YW
655 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START] && UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
656 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 657
d85ff944
YW
658 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next)
659 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 660
d85ff944
YW
661 if (s->type == SERVICE_ONESHOT &&
662 !IN_SET(s->restart, SERVICE_RESTART_NO, SERVICE_RESTART_ON_FAILURE, SERVICE_RESTART_ON_ABNORMAL, SERVICE_RESTART_ON_WATCHDOG, SERVICE_RESTART_ON_ABORT))
663 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 664
d85ff944 665 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status))
9e670fdc 666 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has RestartForceExitStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
b0693d30 667
596e4470
HC
668 if (s->type == SERVICE_ONESHOT && s->exit_type == SERVICE_EXIT_CGROUP)
669 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
670
d85ff944
YW
671 if (s->type == SERVICE_DBUS && !s->bus_name)
672 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
4d0e5dbd 673
d85ff944
YW
674 if (s->exec_context.pam_name && !IN_SET(s->kill_context.kill_mode, KILL_CONTROL_GROUP, KILL_MIXED))
675 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
05e343b7 676
6b7e5923
PS
677 if (s->usb_function_descriptors && !s->usb_function_strings)
678 log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
679
680 if (!s->usb_function_descriptors && s->usb_function_strings)
681 log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
682
36c16a7c 683 if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
226a08f2 684 log_unit_warning(UNIT(s), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
36c16a7c 685
5918a933
AB
686 if (s->runtime_max_usec == USEC_INFINITY && s->runtime_rand_extra_usec != 0)
687 log_unit_warning(UNIT(s), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
688
86838bf0
LB
689 if (s->exit_type == SERVICE_EXIT_CGROUP && cg_unified() < CGROUP_UNIFIED_SYSTEMD)
690 log_unit_warning(UNIT(s), "Service has ExitType=cgroup set, but we are running with legacy cgroups v1, which might not work correctly. Continuing.");
691
e9f17fa8
MY
692 if (s->restart_max_delay_usec == USEC_INFINITY && s->restart_steps > 0)
693 log_unit_warning(UNIT(s), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
be1adc27 694
e9f17fa8
MY
695 if (s->restart_max_delay_usec != USEC_INFINITY && s->restart_steps == 0)
696 log_unit_warning(UNIT(s), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
be1adc27 697
e9f17fa8
MY
698 if (s->restart_max_delay_usec < s->restart_usec) {
699 log_unit_warning(UNIT(s), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
700 s->restart_usec = s->restart_max_delay_usec;
be1adc27
MY
701 }
702
243b1432
LP
703 return 0;
704}
705
a40eb732
LP
706static int service_add_default_dependencies(Service *s) {
707 int r;
708
709 assert(s);
710
45f06b34
LP
711 if (!UNIT(s)->default_dependencies)
712 return 0;
713
a40eb732
LP
714 /* Add a number of automatic dependencies useful for the
715 * majority of services. */
716
463d0d15 717 if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
cb4c247d
LP
718 /* First, pull in the really early boot stuff, and
719 * require it, so that we fail if we can't acquire
720 * it. */
721
5a724170 722 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
cb4c247d
LP
723 if (r < 0)
724 return r;
725 } else {
726
727 /* In the --user instance there's no sysinit.target,
728 * in that case require basic.target instead. */
729
35d8c19a 730 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
cb4c247d
LP
731 if (r < 0)
732 return r;
733 }
734
735 /* Second, if the rest of the base system is in the same
736 * transaction, order us after it, but do not pull it in or
737 * even require it. */
35d8c19a 738 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
fccd44ec
KS
739 if (r < 0)
740 return r;
a40eb732 741
cb4c247d 742 /* Third, add us in for normal shutdown. */
e019ea73
ZJS
743 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
744 if (r < 0)
745 return r;
746
747 /* Fourth, add generic dependencies */
748 return exec_context_add_default_dependencies(UNIT(s), &s->exec_context);
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 998 "%sRestartSteps: %u\n"
e9f17fa8 999 "%sRestartMaxDelaySec: %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 1005 prefix, s->restart_steps,
e9f17fa8 1006 prefix, FORMAT_TIMESPAN(s->restart_max_delay_usec, 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)
f86a388d 1123 return log_unit_full_errno(UNIT(s), prio, r,
8ed6f81b 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
a1d31573 1949 if (IN_SET(s->state, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART))
53f47dfc 1950 return true;
2ad2e41a 1951
52a12341 1952 return unit_will_restart_default(u);
53f47dfc
YW
1953}
1954
b9c1883a
LP
1955static ServiceState service_determine_dead_state(Service *s) {
1956 assert(s);
1957
1958 return s->fd_store && s->fd_store_preserve_mode == EXEC_PRESERVE_YES ? SERVICE_DEAD_RESOURCES_PINNED : SERVICE_DEAD;
1959}
1960
f42806df 1961static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
a1d31573 1962 ServiceState end_state, restart_state;
034c6ed7 1963 int r;
0f52f8e5 1964
034c6ed7
LP
1965 assert(s);
1966
0f52f8e5
LP
1967 /* If there's a stop job queued before we enter the DEAD state, we shouldn't act on Restart=, in order to not
1968 * undo what has already been enqueued. */
1969 if (unit_stop_pending(UNIT(s)))
1970 allow_restart = false;
1971
a0fef983 1972 if (s->result == SERVICE_SUCCESS)
f42806df 1973 s->result = f;
034c6ed7 1974
31cd5f63
AZ
1975 if (s->result == SERVICE_SUCCESS) {
1976 unit_log_success(UNIT(s));
b9c1883a 1977 end_state = service_determine_dead_state(s);
a1d31573 1978 restart_state = SERVICE_DEAD_BEFORE_AUTO_RESTART;
31cd5f63
AZ
1979 } else if (s->result == SERVICE_SKIP_CONDITION) {
1980 unit_log_skip(UNIT(s), service_result_to_string(s->result));
b9c1883a 1981 end_state = service_determine_dead_state(s);
a1d31573 1982 restart_state = SERVICE_DEAD_BEFORE_AUTO_RESTART;
31cd5f63
AZ
1983 } else {
1984 unit_log_failure(UNIT(s), service_result_to_string(s->result));
1985 end_state = SERVICE_FAILED;
a1d31573 1986 restart_state = SERVICE_FAILED_BEFORE_AUTO_RESTART;
31cd5f63 1987 }
4c425434 1988 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
ed77d407 1989
ebc57b89
ZJS
1990 if (!allow_restart)
1991 log_unit_debug(UNIT(s), "Service restart not allowed.");
1992 else {
1993 const char *reason;
ebc57b89 1994
49b34f75 1995 allow_restart = service_shall_restart(s, &reason);
ebc57b89 1996 log_unit_debug(UNIT(s), "Service will %srestart (%s)",
49b34f75 1997 allow_restart ? "" : "not ",
ebc57b89 1998 reason);
ebc57b89 1999 }
deb4e708 2000
49b34f75 2001 if (allow_restart) {
a1d31573
LP
2002 /* We make two state changes here: one that maps to the high-level UNIT_INACTIVE/UNIT_FAILED
2003 * state (i.e. a state indicating deactivation), and then one that that maps to the
2004 * high-level UNIT_STARTING state (i.e. a state indicating activation). We do this so that
2005 * external software can watch the state changes and see all service failures, even if they
2006 * are only transitionary and followed by an automatic restart. We have fine-grained
2007 * low-level states for this though so that software can distinguish the permanent UNIT_INACTIVE
2008 * state from this transitionary UNIT_INACTIVE state by looking at the low-level states. */
2009 service_set_state(s, restart_state);
2010
5171356e 2011 r = service_arm_timer(s, /* relative= */ true, service_restart_usec_next(s));
a1d31573 2012 if (r < 0)
034c6ed7
LP
2013 goto fail;
2014
2015 service_set_state(s, SERVICE_AUTO_RESTART);
a1d31573
LP
2016 } else {
2017 service_set_state(s, end_state);
2018
7a0019d3
LP
2019 /* If we shan't restart, then flush out the restart counter. But don't do that immediately, so that the
2020 * user can still introspect the counter. Do so on the next start. */
2021 s->flush_n_restarts = true;
a1d31573 2022 }
034c6ed7 2023
5238e957 2024 /* The new state is in effect, let's decrease the fd store ref counter again. Let's also re-add us to the GC
7eb2a8a1 2025 * queue, so that the fd store is possibly gc'ed again */
7eb2a8a1
LP
2026 unit_add_to_gc_queue(UNIT(s));
2027
f2341e0a 2028 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
47342320
LP
2029 s->forbid_restart = false;
2030
19dff691
MY
2031 /* Reset NotifyAccess override */
2032 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
2033
e66cf1a3 2034 /* We want fresh tmpdirs in case service is started again immediately */
28135da3 2035 s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
c17ec25e 2036
95939aed 2037 /* Also, remove the runtime directory */
bb0c0d6f 2038 unit_destroy_runtime_data(UNIT(s), &s->exec_context);
e66cf1a3 2039
b9c1883a
LP
2040 /* Also get rid of the fd store, if that's configured. */
2041 if (s->fd_store_preserve_mode == EXEC_PRESERVE_NO)
2042 service_release_fd_store(s);
2043
00d9ef85
LP
2044 /* Get rid of the IPC bits of the user */
2045 unit_unref_uid_gid(UNIT(s), true);
2046
9285c9ff
LN
2047 /* Try to delete the pid file. At this point it will be
2048 * out-of-date, and some software might be confused by it, so
2049 * let's remove it. */
2050 if (s->pid_file)
fabab190 2051 (void) unlink(s->pid_file);
9285c9ff 2052
6f765baf
LP
2053 /* Reset TTY ownership if necessary */
2054 exec_context_revert_tty(&s->exec_context);
2055
034c6ed7
LP
2056 return;
2057
2058fail:
f2341e0a 2059 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
f42806df 2060 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
2061}
2062
f42806df 2063static void service_enter_stop_post(Service *s, ServiceResult f) {
034c6ed7
LP
2064 int r;
2065 assert(s);
2066
a0fef983 2067 if (s->result == SERVICE_SUCCESS)
f42806df 2068 s->result = f;
034c6ed7 2069
5e94833f 2070 service_unwatch_control_pid(s);
50be4f4a 2071 (void) unit_enqueue_rewatch_pids(UNIT(s));
5e94833f 2072
117dcc57
ZJS
2073 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
2074 if (s->control_command) {
867b3b7d
LP
2075 s->control_command_id = SERVICE_EXEC_STOP_POST;
2076
ecedd90f
LP
2077 r = service_spawn(s,
2078 s->control_command,
21b2ce39 2079 s->timeout_stop_usec,
78f93209 2080 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_IS_CONTROL|EXEC_SETENV_RESULT|EXEC_CONTROL_CGROUP,
ecedd90f
LP
2081 &s->control_pid);
2082 if (r < 0)
034c6ed7
LP
2083 goto fail;
2084
80876c20
LP
2085 service_set_state(s, SERVICE_STOP_POST);
2086 } else
ac84d1fb 2087 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2088
2089 return;
2090
2091fail:
f2341e0a 2092 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
f42806df 2093 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2094}
2095
a232ebcc 2096static int state_to_kill_operation(Service *s, ServiceState state) {
4940c0b0
LP
2097 switch (state) {
2098
c87700a1 2099 case SERVICE_STOP_WATCHDOG:
bf760801 2100 case SERVICE_FINAL_WATCHDOG:
c87700a1 2101 return KILL_WATCHDOG;
4940c0b0
LP
2102
2103 case SERVICE_STOP_SIGTERM:
a232ebcc
ZJS
2104 if (unit_has_job_type(UNIT(s), JOB_RESTART))
2105 return KILL_RESTART;
2106 _fallthrough_;
2107
4940c0b0
LP
2108 case SERVICE_FINAL_SIGTERM:
2109 return KILL_TERMINATE;
2110
2111 case SERVICE_STOP_SIGKILL:
2112 case SERVICE_FINAL_SIGKILL:
2113 return KILL_KILL;
2114
2115 default:
2116 return _KILL_OPERATION_INVALID;
2117 }
2118}
2119
f42806df 2120static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
bf760801 2121 int kill_operation, r;
034c6ed7
LP
2122
2123 assert(s);
2124
a0fef983 2125 if (s->result == SERVICE_SUCCESS)
f42806df 2126 s->result = f;
034c6ed7 2127
50be4f4a
LP
2128 /* Before sending any signal, make sure we track all members of this cgroup */
2129 (void) unit_watch_all_pids(UNIT(s));
2130
2131 /* Also, enqueue a job that we recheck all our PIDs a bit later, given that it's likely some processes have
2132 * died now */
2133 (void) unit_enqueue_rewatch_pids(UNIT(s));
a911bb9a 2134
bf760801 2135 kill_operation = state_to_kill_operation(s, state);
cd2086fe
LP
2136 r = unit_kill_context(
2137 UNIT(s),
2138 &s->kill_context,
bf760801 2139 kill_operation,
cd2086fe
LP
2140 s->main_pid,
2141 s->control_pid,
2142 s->main_pid_alien);
2143 if (r < 0)
2144 goto fail;
034c6ed7 2145
cd2086fe 2146 if (r > 0) {
e5d6dcce
LP
2147 r = service_arm_timer(s, /* relative= */ true,
2148 kill_operation == KILL_WATCHDOG ? service_timeout_abort_usec(s) : s->timeout_stop_usec);
36c16a7c
LP
2149 if (r < 0)
2150 goto fail;
d6ea93e3 2151
80876c20 2152 service_set_state(s, state);
c87700a1 2153 } else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2154 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
c87700a1 2155 else if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2156 service_enter_stop_post(s, SERVICE_SUCCESS);
bf760801 2157 else if (IN_SET(state, SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 2158 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
80876c20 2159 else
f42806df 2160 service_enter_dead(s, SERVICE_SUCCESS, true);
034c6ed7
LP
2161
2162 return;
2163
2164fail:
f2341e0a 2165 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
034c6ed7 2166
c87700a1 2167 if (IN_SET(state, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 2168 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
034c6ed7 2169 else
f42806df 2170 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
2171}
2172
308d72dc
LP
2173static void service_enter_stop_by_notify(Service *s) {
2174 assert(s);
2175
50be4f4a 2176 (void) unit_enqueue_rewatch_pids(UNIT(s));
308d72dc 2177
e5d6dcce 2178 service_arm_timer(s, /* relative= */ true, s->timeout_stop_usec);
308d72dc 2179
6041a7ee
MS
2180 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
2181 service_set_state(s, SERVICE_STOP_SIGTERM);
308d72dc
LP
2182}
2183
f42806df 2184static void service_enter_stop(Service *s, ServiceResult f) {
034c6ed7 2185 int r;
5925dd3c 2186
034c6ed7
LP
2187 assert(s);
2188
a0fef983 2189 if (s->result == SERVICE_SUCCESS)
f42806df 2190 s->result = f;
034c6ed7 2191
5e94833f 2192 service_unwatch_control_pid(s);
50be4f4a 2193 (void) unit_enqueue_rewatch_pids(UNIT(s));
5e94833f 2194
117dcc57
ZJS
2195 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2196 if (s->control_command) {
867b3b7d
LP
2197 s->control_command_id = SERVICE_EXEC_STOP;
2198
ecedd90f
LP
2199 r = service_spawn(s,
2200 s->control_command,
21b2ce39 2201 s->timeout_stop_usec,
78f93209 2202 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_SETENV_RESULT|EXEC_CONTROL_CGROUP,
ecedd90f
LP
2203 &s->control_pid);
2204 if (r < 0)
034c6ed7
LP
2205 goto fail;
2206
80876c20
LP
2207 service_set_state(s, SERVICE_STOP);
2208 } else
f42806df 2209 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2210
2211 return;
2212
2213fail:
f2341e0a 2214 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
f42806df 2215 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2216}
2217
957c3cf9
LP
2218static bool service_good(Service *s) {
2219 int main_pid_ok;
2220 assert(s);
2221
2222 if (s->type == SERVICE_DBUS && !s->bus_name_good)
2223 return false;
2224
2225 main_pid_ok = main_pid_good(s);
2226 if (main_pid_ok > 0) /* It's alive */
2227 return true;
2228 if (main_pid_ok == 0) /* It's dead */
2229 return false;
2230
2231 /* OK, we don't know anything about the main PID, maybe
2232 * because there is none. Let's check the control group
2233 * instead. */
2234
2235 return cgroup_good(s) != 0;
2236}
2237
f42806df 2238static void service_enter_running(Service *s, ServiceResult f) {
80876c20
LP
2239 assert(s);
2240
a0fef983 2241 if (s->result == SERVICE_SUCCESS)
f42806df 2242 s->result = f;
80876c20 2243
089b64d5
LP
2244 service_unwatch_control_pid(s);
2245
ec5b1452
LP
2246 if (s->result != SERVICE_SUCCESS)
2247 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2248 else if (service_good(s)) {
308d72dc 2249
ec5b1452 2250 /* If there are any queued up sd_notify() notifications, process them now */
308d72dc
LP
2251 if (s->notify_state == NOTIFY_RELOADING)
2252 service_enter_reload_by_notify(s);
2253 else if (s->notify_state == NOTIFY_STOPPING)
2254 service_enter_stop_by_notify(s);
36c16a7c 2255 else {
308d72dc 2256 service_set_state(s, SERVICE_RUNNING);
e5d6dcce 2257 service_arm_timer(s, /* relative= */ false, service_running_timeout(s));
36c16a7c 2258 }
308d72dc 2259
ec5b1452 2260 } else if (s->remain_after_exit)
80876c20
LP
2261 service_set_state(s, SERVICE_EXITED);
2262 else
f42806df 2263 service_enter_stop(s, SERVICE_SUCCESS);
80876c20
LP
2264}
2265
034c6ed7
LP
2266static void service_enter_start_post(Service *s) {
2267 int r;
2268 assert(s);
2269
5e94833f 2270 service_unwatch_control_pid(s);
842129f5 2271 service_reset_watchdog(s);
bb242b7b 2272
117dcc57
ZJS
2273 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2274 if (s->control_command) {
867b3b7d
LP
2275 s->control_command_id = SERVICE_EXEC_START_POST;
2276
ecedd90f
LP
2277 r = service_spawn(s,
2278 s->control_command,
21b2ce39 2279 s->timeout_start_usec,
78f93209 2280 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_CONTROL_CGROUP,
ecedd90f
LP
2281 &s->control_pid);
2282 if (r < 0)
034c6ed7
LP
2283 goto fail;
2284
80876c20
LP
2285 service_set_state(s, SERVICE_START_POST);
2286 } else
f42806df 2287 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2288
2289 return;
2290
2291fail:
f2341e0a 2292 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
f42806df 2293 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2294}
2295
e9a4f676 2296static void service_kill_control_process(Service *s) {
a6951a50 2297 int r;
4ad49000 2298
a6951a50
LP
2299 assert(s);
2300
e9a4f676
LP
2301 if (s->control_pid <= 0)
2302 return;
4ad49000 2303
e9a4f676
LP
2304 r = kill_and_sigcont(s->control_pid, SIGKILL);
2305 if (r < 0) {
2306 _cleanup_free_ char *comm = NULL;
a6951a50 2307
e9a4f676 2308 (void) get_process_comm(s->control_pid, &comm);
a6951a50 2309
e9a4f676
LP
2310 log_unit_debug_errno(UNIT(s), r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m",
2311 s->control_pid, strna(comm));
a6951a50 2312 }
4ad49000
LP
2313}
2314
c53d2d54
DB
2315static int service_adverse_to_leftover_processes(Service *s) {
2316 assert(s);
2317
2318 /* KillMode=mixed and control group are used to indicate that all process should be killed off.
4c425434
LP
2319 * SendSIGKILL= is used for services that require a clean shutdown. These are typically database
2320 * service where a SigKilled process would result in a lengthy recovery and who's shutdown or startup
2321 * time is quite variable (so Timeout settings aren't of use).
c53d2d54
DB
2322 *
2323 * Here we take these two factors and refuse to start a service if there are existing processes
2324 * within a control group. Databases, while generally having some protection against multiple
4c425434 2325 * instances running, lets not stress the rigor of these. Also ExecStartPre= parts of the service
c53d2d54 2326 * aren't as rigoriously written to protect aganst against multiple use. */
4c425434
LP
2327
2328 if (unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start) > 0 &&
c53d2d54 2329 IN_SET(s->kill_context.kill_mode, KILL_MIXED, KILL_CONTROL_GROUP) &&
569554d9
ZJS
2330 !s->kill_context.send_sigkill)
2331 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EBUSY),
2332 "Will not start SendSIGKILL=no service of type KillMode=control-group or mixed while processes exist");
2333
c53d2d54
DB
2334 return 0;
2335}
2336
034c6ed7 2337static void service_enter_start(Service *s) {
4ad49000 2338 ExecCommand *c;
36c16a7c 2339 usec_t timeout;
034c6ed7
LP
2340 pid_t pid;
2341 int r;
2342
2343 assert(s);
2344
41efeaec
LP
2345 service_unwatch_control_pid(s);
2346 service_unwatch_main_pid(s);
80876c20 2347
c53d2d54
DB
2348 r = service_adverse_to_leftover_processes(s);
2349 if (r < 0)
2350 goto fail;
a4634b21 2351
867b3b7d
LP
2352 if (s->type == SERVICE_FORKING) {
2353 s->control_command_id = SERVICE_EXEC_START;
2354 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2355
2356 s->main_command = NULL;
2357 } else {
2358 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2359 s->control_command = NULL;
2360
2361 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2362 }
34e9ba66 2363
96fb8242 2364 if (!c) {
47fffb35 2365 if (s->type != SERVICE_ONESHOT) {
cbc056c8
ZJS
2366 /* There's no command line configured for the main command? Hmm, that is strange.
2367 * This can only happen if the configuration changes at runtime. In this case,
2368 * let's enter a failure state. */
d85ff944 2369 r = log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENXIO), "There's no 'start' task anymore we could start.");
47fffb35
LP
2370 goto fail;
2371 }
2372
ef5ae8e7
ZJS
2373 /* We force a fake state transition here. Otherwise, the unit would go directly from
2374 * SERVICE_DEAD to SERVICE_DEAD without SERVICE_ACTIVATING or SERVICE_ACTIVE
5238e957 2375 * in between. This way we can later trigger actions that depend on the state
ef5ae8e7
ZJS
2376 * transition, including SuccessAction=. */
2377 service_set_state(s, SERVICE_START);
2378
96fb8242
LP
2379 service_enter_start_post(s);
2380 return;
2381 }
2382
36c16a7c
LP
2383 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
2384 /* For simple + idle this is the main process. We don't apply any timeout here, but
2385 * service_enter_running() will later apply the .runtime_max_usec timeout. */
2386 timeout = USEC_INFINITY;
2387 else
2388 timeout = s->timeout_start_usec;
2389
ecedd90f
LP
2390 r = service_spawn(s,
2391 c,
36c16a7c 2392 timeout,
cdebedb4 2393 EXEC_PASS_FDS|EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG|EXEC_WRITE_CREDENTIALS|EXEC_SETENV_MONITOR_RESULT,
ecedd90f
LP
2394 &pid);
2395 if (r < 0)
034c6ed7
LP
2396 goto fail;
2397
36c16a7c 2398 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
034c6ed7
LP
2399 /* For simple services we immediately start
2400 * the START_POST binaries. */
2401
5c95eb28 2402 (void) service_set_main_pid(s, pid);
034c6ed7
LP
2403 service_enter_start_post(s);
2404
2405 } else if (s->type == SERVICE_FORKING) {
2406
2407 /* For forking services we wait until the start
2408 * process exited. */
2409
e55224ca 2410 s->control_pid = pid;
80876c20
LP
2411 service_set_state(s, SERVICE_START);
2412
3bd28bf7 2413 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD, SERVICE_EXEC)) {
7d55e835 2414
5686391b 2415 /* For oneshot services we wait until the start process exited, too, but it is our main process. */
7d55e835 2416
5686391b
LP
2417 /* For D-Bus services we know the main pid right away, but wait for the bus name to appear on the
2418 * bus. 'notify' and 'exec' services are similar. */
05e343b7 2419
5c95eb28 2420 (void) service_set_main_pid(s, pid);
80876c20 2421 service_set_state(s, SERVICE_START);
034c6ed7 2422 } else
04499a70 2423 assert_not_reached();
034c6ed7
LP
2424
2425 return;
2426
2427fail:
f2341e0a 2428 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
c3fda31d 2429 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2430}
2431
2432static void service_enter_start_pre(Service *s) {
2433 int r;
2434
2435 assert(s);
2436
5e94833f
LP
2437 service_unwatch_control_pid(s);
2438
117dcc57
ZJS
2439 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2440 if (s->control_command) {
8f53a7b8 2441
c53d2d54
DB
2442 r = service_adverse_to_leftover_processes(s);
2443 if (r < 0)
2444 goto fail;
a4634b21 2445
867b3b7d
LP
2446 s->control_command_id = SERVICE_EXEC_START_PRE;
2447
ecedd90f
LP
2448 r = service_spawn(s,
2449 s->control_command,
21b2ce39 2450 s->timeout_start_usec,
e7f64b89 2451 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN|EXEC_SETENV_MONITOR_RESULT|EXEC_WRITE_CREDENTIALS,
ecedd90f
LP
2452 &s->control_pid);
2453 if (r < 0)
034c6ed7
LP
2454 goto fail;
2455
80876c20
LP
2456 service_set_state(s, SERVICE_START_PRE);
2457 } else
034c6ed7
LP
2458 service_enter_start(s);
2459
2460 return;
2461
2462fail:
f2341e0a 2463 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
f42806df 2464 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
2465}
2466
31cd5f63
AZ
2467static void service_enter_condition(Service *s) {
2468 int r;
2469
2470 assert(s);
2471
2472 service_unwatch_control_pid(s);
2473
2474 s->control_command = s->exec_command[SERVICE_EXEC_CONDITION];
2475 if (s->control_command) {
2476
2477 r = service_adverse_to_leftover_processes(s);
2478 if (r < 0)
2479 goto fail;
2480
2481 s->control_command_id = SERVICE_EXEC_CONDITION;
2482
2483 r = service_spawn(s,
2484 s->control_command,
2485 s->timeout_start_usec,
2486 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN,
2487 &s->control_pid);
2488
2489 if (r < 0)
2490 goto fail;
2491
2492 service_set_state(s, SERVICE_CONDITION);
2493 } else
2494 service_enter_start_pre(s);
2495
2496 return;
2497
2498fail:
2499 log_unit_warning_errno(UNIT(s), r, "Failed to run 'exec-condition' task: %m");
2500 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
2501}
2502
034c6ed7 2503static void service_enter_restart(Service *s) {
4afd3348 2504 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7 2505 int r;
398ef8ba 2506
034c6ed7
LP
2507 assert(s);
2508
28a2dfe8 2509 if (unit_has_job_type(UNIT(s), JOB_STOP)) {
a8bb2e65 2510 /* Don't restart things if we are going down anyway */
c9728806 2511 log_unit_info(UNIT(s), "Stop job pending for unit, skipping automatic restart.");
feae8adb 2512 return;
2edfa366
LP
2513 }
2514
48bb5876
DW
2515 /* Any units that are bound to this service must also be
2516 * restarted. We use JOB_RESTART (instead of the more obvious
2517 * JOB_START) here so that those dependency jobs will be added
2518 * as well. */
50cbaba4 2519 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_REPLACE, NULL, &error, NULL);
48bb5876 2520 if (r < 0)
034c6ed7
LP
2521 goto fail;
2522
7a0019d3 2523 /* Count the jobs we enqueue for restarting. This counter is maintained as long as the unit isn't fully
f0c7e594 2524 * stopped, i.e. as long as it remains up or remains in auto-start states. The user can reset the counter
7a0019d3
LP
2525 * explicitly however via the usual "systemctl reset-failure" logic. */
2526 s->n_restarts ++;
2527 s->flush_n_restarts = false;
2528
19dff691
MY
2529 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
2530
c2503e35
RH
2531 log_unit_struct(UNIT(s), LOG_INFO,
2532 "MESSAGE_ID=" SD_MESSAGE_UNIT_RESTART_SCHEDULED_STR,
2533 LOG_UNIT_INVOCATION_ID(UNIT(s)),
92663a5e
ZJS
2534 LOG_UNIT_MESSAGE(UNIT(s),
2535 "Scheduled restart job, restart counter is at %u.", s->n_restarts),
c2503e35 2536 "N_RESTARTS=%u", s->n_restarts);
7a0019d3
LP
2537
2538 /* Notify clients about changed restart counter */
2539 unit_add_to_dbus_queue(UNIT(s));
2540
a8bb2e65
LP
2541 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2542 * it will be canceled as part of the service_stop() call that
2543 * is executed as part of JOB_RESTART. */
2544
034c6ed7
LP
2545 return;
2546
2547fail:
2a03b9ed 2548 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, r));
f42806df 2549 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
2550}
2551
308d72dc 2552static void service_enter_reload_by_notify(Service *s) {
15d167f8
JW
2553 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2554 int r;
2555
308d72dc
LP
2556 assert(s);
2557
e5d6dcce 2558 service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
3bd28bf7 2559 service_set_state(s, SERVICE_RELOAD_NOTIFY);
15d167f8
JW
2560
2561 /* service_enter_reload_by_notify is never called during a reload, thus no loops are possible. */
2562 r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
2563 if (r < 0)
2a03b9ed 2564 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload: %s", bus_error_message(&error, r));
308d72dc
LP
2565}
2566
034c6ed7 2567static void service_enter_reload(Service *s) {
3bd28bf7 2568 bool killed = false;
034c6ed7
LP
2569 int r;
2570
2571 assert(s);
2572
5e94833f 2573 service_unwatch_control_pid(s);
95c906ae 2574 s->reload_result = SERVICE_SUCCESS;
5e94833f 2575
3bd28bf7
LP
2576 usec_t ts = now(CLOCK_MONOTONIC);
2577
2578 if (s->type == SERVICE_NOTIFY_RELOAD && s->main_pid > 0) {
2579 r = kill_and_sigcont(s->main_pid, s->reload_signal);
2580 if (r < 0) {
2581 log_unit_warning_errno(UNIT(s), r, "Failed to send reload signal: %m");
2582 goto fail;
2583 }
2584
2585 killed = true;
2586 }
2587
117dcc57
ZJS
2588 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2589 if (s->control_command) {
867b3b7d
LP
2590 s->control_command_id = SERVICE_EXEC_RELOAD;
2591
ecedd90f
LP
2592 r = service_spawn(s,
2593 s->control_command,
21b2ce39 2594 s->timeout_start_usec,
f8a8f613 2595 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_CONTROL_CGROUP,
ecedd90f 2596 &s->control_pid);
3bd28bf7
LP
2597 if (r < 0) {
2598 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
034c6ed7 2599 goto fail;
3bd28bf7 2600 }
034c6ed7 2601
80876c20 2602 service_set_state(s, SERVICE_RELOAD);
3bd28bf7
LP
2603 } else if (killed) {
2604 service_arm_timer(s, /* relative= */ true, s->timeout_start_usec);
2605 service_set_state(s, SERVICE_RELOAD_SIGNAL);
2606 } else {
f42806df 2607 service_enter_running(s, SERVICE_SUCCESS);
3bd28bf7
LP
2608 return;
2609 }
034c6ed7 2610
3bd28bf7
LP
2611 /* Store the timestamp when we started reloading: when reloading via SIGHUP we won't leave the reload
2612 * state until we received both RELOADING=1 and READY=1 with MONOTONIC_USEC= set to a value above
2613 * this. Thus we know for sure the reload cycle was executed *after* we requested it, and is not one
2614 * that was already in progress before. */
2615 s->reload_begin_usec = ts;
034c6ed7
LP
2616 return;
2617
2618fail:
f42806df
LP
2619 s->reload_result = SERVICE_FAILURE_RESOURCES;
2620 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2621}
2622
f42806df 2623static void service_run_next_control(Service *s) {
36c16a7c 2624 usec_t timeout;
034c6ed7
LP
2625 int r;
2626
2627 assert(s);
2628 assert(s->control_command);
2629 assert(s->control_command->command_next);
2630
34e9ba66 2631 assert(s->control_command_id != SERVICE_EXEC_START);
034c6ed7 2632
34e9ba66 2633 s->control_command = s->control_command->command_next;
5e94833f
LP
2634 service_unwatch_control_pid(s);
2635
31cd5f63 2636 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
36c16a7c
LP
2637 timeout = s->timeout_start_usec;
2638 else
2639 timeout = s->timeout_stop_usec;
2640
ecedd90f
LP
2641 r = service_spawn(s,
2642 s->control_command,
36c16a7c 2643 timeout,
1703fa41 2644 EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|
c9210b74 2645 (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD) ? EXEC_WRITE_CREDENTIALS : 0)|
31cd5f63 2646 (IN_SET(s->control_command_id, SERVICE_EXEC_CONDITION, SERVICE_EXEC_START_PRE, SERVICE_EXEC_STOP_POST) ? EXEC_APPLY_TTY_STDIN : 0)|
78f93209 2647 (IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_SETENV_RESULT : 0)|
a257c941 2648 (IN_SET(s->control_command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_START) ? EXEC_SETENV_MONITOR_RESULT : 0)|
78f93209 2649 (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
2650 &s->control_pid);
2651 if (r < 0)
034c6ed7
LP
2652 goto fail;
2653
2654 return;
2655
2656fail:
f2341e0a 2657 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
034c6ed7 2658
31cd5f63 2659 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START_POST, SERVICE_STOP))
f42806df 2660 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7 2661 else if (s->state == SERVICE_STOP_POST)
f42806df 2662 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
e2f3b44c 2663 else if (s->state == SERVICE_RELOAD) {
f42806df
LP
2664 s->reload_result = SERVICE_FAILURE_RESOURCES;
2665 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c 2666 } else
f42806df 2667 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
5cb5a6ff
LP
2668}
2669
f42806df 2670static void service_run_next_main(Service *s) {
34e9ba66
LP
2671 pid_t pid;
2672 int r;
2673
2674 assert(s);
867b3b7d
LP
2675 assert(s->main_command);
2676 assert(s->main_command->command_next);
2677 assert(s->type == SERVICE_ONESHOT);
34e9ba66 2678
867b3b7d 2679 s->main_command = s->main_command->command_next;
34e9ba66
LP
2680 service_unwatch_main_pid(s);
2681
ecedd90f
LP
2682 r = service_spawn(s,
2683 s->main_command,
21b2ce39 2684 s->timeout_start_usec,
c9210b74 2685 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
2686 &pid);
2687 if (r < 0)
34e9ba66
LP
2688 goto fail;
2689
5c95eb28 2690 (void) service_set_main_pid(s, pid);
34e9ba66
LP
2691
2692 return;
2693
2694fail:
f2341e0a 2695 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
f42806df 2696 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
34e9ba66
LP
2697}
2698
87f0e418
LP
2699static int service_start(Unit *u) {
2700 Service *s = SERVICE(u);
07299350 2701 int r;
5cb5a6ff
LP
2702
2703 assert(s);
2704
034c6ed7
LP
2705 /* We cannot fulfill this request right now, try again later
2706 * please! */
a00973af 2707 if (IN_SET(s->state,
c87700a1 2708 SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
bf760801 2709 SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
5cb5a6ff
LP
2710 return -EAGAIN;
2711
034c6ed7 2712 /* Already on it! */
31cd5f63 2713 if (IN_SET(s->state, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
034c6ed7
LP
2714 return 0;
2715
a1d31573
LP
2716 /* A service that will be restarted must be stopped first to trigger BindsTo and/or OnFailure
2717 * dependencies. If a user does not want to wait for the holdoff time to elapse, the service should
2718 * be manually restarted, not started. We simply return EAGAIN here, so that any start jobs stay
2719 * queued, and assume that the auto restart timer will eventually trigger the restart. */
2720 if (IN_SET(s->state, SERVICE_AUTO_RESTART, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART))
a8bb2e65 2721 return -EAGAIN;
2e9d6c12 2722
b9c1883a 2723 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED));
5cb5a6ff 2724
4b58153d
LP
2725 r = unit_acquire_invocation_id(u);
2726 if (r < 0)
2727 return r;
2728
f42806df
LP
2729 s->result = SERVICE_SUCCESS;
2730 s->reload_result = SERVICE_SUCCESS;
034c6ed7 2731 s->main_pid_known = false;
6dfa5494 2732 s->main_pid_alien = false;
47342320 2733 s->forbid_restart = false;
3c7416b6 2734
a1e58e8e 2735 s->status_text = mfree(s->status_text);
8cfdb077
LP
2736 s->status_errno = 0;
2737
19dff691 2738 s->notify_access_override = _NOTIFY_ACCESS_INVALID;
308d72dc
LP
2739 s->notify_state = NOTIFY_UNKNOWN;
2740
aa8c4bbf 2741 s->watchdog_original_usec = s->watchdog_usec;
2787d83c 2742 s->watchdog_override_enable = false;
aa8c4bbf 2743 s->watchdog_override_usec = USEC_INFINITY;
2787d83c 2744
6a1d4d9f
LP
2745 exec_command_reset_status_list_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
2746 exec_status_reset(&s->main_exec_status);
2747
7a0019d3
LP
2748 /* This is not an automatic restart? Flush the restart counter then */
2749 if (s->flush_n_restarts) {
2750 s->n_restarts = 0;
2751 s->flush_n_restarts = false;
2752 }
2753
6a1d4d9f
LP
2754 u->reset_accounting = true;
2755
31cd5f63 2756 service_enter_condition(s);
82a2b6bb 2757 return 1;
5cb5a6ff
LP
2758}
2759
87f0e418
LP
2760static int service_stop(Unit *u) {
2761 Service *s = SERVICE(u);
5cb5a6ff
LP
2762
2763 assert(s);
2764
a509f0e6 2765 /* Don't create restart jobs from manual stops. */
47342320 2766 s->forbid_restart = true;
034c6ed7 2767
a1d31573
LP
2768 switch (s->state) {
2769
2770 case SERVICE_STOP:
2771 case SERVICE_STOP_SIGTERM:
2772 case SERVICE_STOP_SIGKILL:
2773 case SERVICE_STOP_POST:
2774 case SERVICE_FINAL_WATCHDOG:
2775 case SERVICE_FINAL_SIGTERM:
2776 case SERVICE_FINAL_SIGKILL:
2777 /* Already on it */
e537352b
LP
2778 return 0;
2779
a1d31573
LP
2780 case SERVICE_AUTO_RESTART:
2781 /* A restart will be scheduled or is in progress. */
b9c1883a 2782 service_set_state(s, service_determine_dead_state(s));
034c6ed7 2783 return 0;
034c6ed7 2784
a1d31573
LP
2785 case SERVICE_CONDITION:
2786 case SERVICE_START_PRE:
2787 case SERVICE_START:
2788 case SERVICE_START_POST:
2789 case SERVICE_RELOAD:
2790 case SERVICE_RELOAD_SIGNAL:
2791 case SERVICE_RELOAD_NOTIFY:
2792 case SERVICE_STOP_WATCHDOG:
2793 /* If there's already something running we go directly into kill mode. */
f42806df 2794 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
3f6c78dc 2795 return 0;
5cb5a6ff 2796
a1d31573
LP
2797 case SERVICE_CLEANING:
2798 /* If we are currently cleaning, then abort it, brutally. */
4c2f5842
LP
2799 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
2800 return 0;
a1d31573
LP
2801
2802 case SERVICE_RUNNING:
2803 case SERVICE_EXITED:
2804 service_enter_stop(s, SERVICE_SUCCESS);
2805 return 1;
2806
2807 case SERVICE_DEAD_BEFORE_AUTO_RESTART:
2808 case SERVICE_FAILED_BEFORE_AUTO_RESTART:
2809 case SERVICE_DEAD:
2810 case SERVICE_FAILED:
b9c1883a 2811 case SERVICE_DEAD_RESOURCES_PINNED:
a1d31573
LP
2812 default:
2813 /* Unknown state, or unit_stop() should already have handled these */
2814 assert_not_reached();
4c2f5842 2815 }
5cb5a6ff
LP
2816}
2817
87f0e418
LP
2818static int service_reload(Unit *u) {
2819 Service *s = SERVICE(u);
034c6ed7
LP
2820
2821 assert(s);
2822
3742095b 2823 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
034c6ed7
LP
2824
2825 service_enter_reload(s);
2d018ae2 2826 return 1;
5cb5a6ff
LP
2827}
2828
44a6b1b6 2829_pure_ static bool service_can_reload(Unit *u) {
87f0e418 2830 Service *s = SERVICE(u);
034c6ed7
LP
2831
2832 assert(s);
2833
3bd28bf7
LP
2834 return s->exec_command[SERVICE_EXEC_RELOAD] ||
2835 s->type == SERVICE_NOTIFY_RELOAD;
034c6ed7
LP
2836}
2837
502096b5 2838static unsigned service_exec_command_index(Unit *u, ServiceExecCommand id, const ExecCommand *current) {
e266c068
MS
2839 Service *s = SERVICE(u);
2840 unsigned idx = 0;
e266c068
MS
2841
2842 assert(s);
5b99bd5f
LP
2843 assert(id >= 0);
2844 assert(id < _SERVICE_EXEC_COMMAND_MAX);
e266c068 2845
502096b5 2846 const ExecCommand *first = s->exec_command[id];
e266c068
MS
2847
2848 /* Figure out where we are in the list by walking back to the beginning */
502096b5 2849 for (const ExecCommand *c = current; c != first; c = c->command_prev)
e266c068
MS
2850 idx++;
2851
2852 return idx;
2853}
2854
502096b5 2855static int service_serialize_exec_command(Unit *u, FILE *f, const ExecCommand *command) {
d68c645b 2856 _cleanup_free_ char *args = NULL, *p = NULL;
e266c068 2857 Service *s = SERVICE(u);
d68c645b 2858 const char *type, *key;
e266c068 2859 ServiceExecCommand id;
319a4f4b 2860 size_t length = 0;
e266c068 2861 unsigned idx;
e266c068
MS
2862
2863 assert(s);
2864 assert(f);
2865
2866 if (!command)
2867 return 0;
2868
2869 if (command == s->control_command) {
2870 type = "control";
2871 id = s->control_command_id;
2872 } else {
2873 type = "main";
2874 id = SERVICE_EXEC_START;
2875 }
2876
2877 idx = service_exec_command_index(u, id, command);
2878
2879 STRV_FOREACH(arg, command->argv) {
e266c068 2880 _cleanup_free_ char *e = NULL;
d68c645b 2881 size_t n;
e266c068 2882
d68c645b 2883 e = cescape(*arg);
e266c068 2884 if (!e)
d68c645b 2885 return log_oom();
e266c068
MS
2886
2887 n = strlen(e);
319a4f4b 2888 if (!GREEDY_REALLOC(args, length + 2 + n + 2))
d68c645b 2889 return log_oom();
e266c068
MS
2890
2891 if (length > 0)
2892 args[length++] = ' ';
2893
334c0979 2894 args[length++] = '"';
e266c068
MS
2895 memcpy(args + length, e, n);
2896 length += n;
334c0979 2897 args[length++] = '"';
e266c068
MS
2898 }
2899
319a4f4b 2900 if (!GREEDY_REALLOC(args, length + 1))
d68c645b
LP
2901 return log_oom();
2902
e266c068
MS
2903 args[length++] = 0;
2904
d68c645b 2905 p = cescape(command->path);
e266c068 2906 if (!p)
5b99bd5f 2907 return log_oom();
e266c068 2908
d68c645b 2909 key = strjoina(type, "-command");
a99bd455
ZJS
2910
2911 /* We use '+1234' instead of '1234' to mark the last command in a sequence.
2912 * This is used in service_deserialize_exec_command(). */
2913 (void) serialize_item_format(
2914 f, key,
2915 "%s %s%u %s %s",
2916 service_exec_command_to_string(id),
2917 command->command_next ? "" : "+",
2918 idx,
2919 p, args);
5b99bd5f
LP
2920
2921 return 0;
e266c068
MS
2922}
2923
a16e1123
LP
2924static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2925 Service *s = SERVICE(u);
a34ceba6 2926 int r;
a16e1123
LP
2927
2928 assert(u);
2929 assert(f);
2930 assert(fds);
2931
d68c645b
LP
2932 (void) serialize_item(f, "state", service_state_to_string(s->state));
2933 (void) serialize_item(f, "result", service_result_to_string(s->result));
2934 (void) serialize_item(f, "reload-result", service_result_to_string(s->reload_result));
a16e1123
LP
2935
2936 if (s->control_pid > 0)
d68c645b 2937 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
a16e1123 2938
5925dd3c 2939 if (s->main_pid_known && s->main_pid > 0)
d68c645b 2940 (void) serialize_item_format(f, "main-pid", PID_FMT, s->main_pid);
a16e1123 2941
d68c645b
LP
2942 (void) serialize_bool(f, "main-pid-known", s->main_pid_known);
2943 (void) serialize_bool(f, "bus-name-good", s->bus_name_good);
2944 (void) serialize_bool(f, "bus-name-owner", s->bus_name_owner);
a16e1123 2945
d68c645b
LP
2946 (void) serialize_item_format(f, "n-restarts", "%u", s->n_restarts);
2947 (void) serialize_bool(f, "flush-n-restarts", s->flush_n_restarts);
7a0019d3 2948
d68c645b 2949 r = serialize_item_escaped(f, "status-text", s->status_text);
a34ceba6
LP
2950 if (r < 0)
2951 return r;
3a2776bc 2952
e266c068
MS
2953 service_serialize_exec_command(u, f, s->control_command);
2954 service_serialize_exec_command(u, f, s->main_command);
a16e1123 2955
d68c645b 2956 r = serialize_fd(f, fds, "stdin-fd", s->stdin_fd);
a34ceba6
LP
2957 if (r < 0)
2958 return r;
d68c645b 2959 r = serialize_fd(f, fds, "stdout-fd", s->stdout_fd);
a34ceba6
LP
2960 if (r < 0)
2961 return r;
d68c645b 2962 r = serialize_fd(f, fds, "stderr-fd", s->stderr_fd);
a34ceba6
LP
2963 if (r < 0)
2964 return r;
e44da745 2965
5686391b 2966 if (s->exec_fd_event_source) {
d68c645b 2967 r = serialize_fd(f, fds, "exec-fd", sd_event_source_get_io_fd(s->exec_fd_event_source));
5686391b
LP
2968 if (r < 0)
2969 return r;
d68c645b
LP
2970
2971 (void) serialize_bool(f, "exec-fd-hot", s->exec_fd_hot);
5686391b
LP
2972 }
2973
9dfb64f8 2974 if (UNIT_ISSET(s->accept_socket)) {
d68c645b 2975 r = serialize_item(f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
9dfb64f8
ZJS
2976 if (r < 0)
2977 return r;
2978 }
2979
d68c645b 2980 r = serialize_fd(f, fds, "socket-fd", s->socket_fd);
a34ceba6
LP
2981 if (r < 0)
2982 return r;
e44da745 2983
2339fc93 2984 LIST_FOREACH(fd_store, fs, s->fd_store) {
8dd4c05b 2985 _cleanup_free_ char *c = NULL;
2339fc93
LP
2986 int copy;
2987
2988 copy = fdset_put_dup(fds, fs->fd);
2989 if (copy < 0)
d68c645b 2990 return log_error_errno(copy, "Failed to copy file descriptor for serialization: %m");
2339fc93 2991
8dd4c05b 2992 c = cescape(fs->fdname);
d68c645b
LP
2993 if (!c)
2994 return log_oom();
8dd4c05b 2995
30520492 2996 (void) serialize_item_format(f, "fd-store-fd", "%i \"%s\" %i", copy, c, fs->do_poll);
2339fc93
LP
2997 }
2998
ecdbca40 2999 if (s->main_exec_status.pid > 0) {
d68c645b
LP
3000 (void) serialize_item_format(f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
3001 (void) serialize_dual_timestamp(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
3002 (void) serialize_dual_timestamp(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
ecdbca40 3003
799fd0fd 3004 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
d68c645b
LP
3005 (void) serialize_item_format(f, "main-exec-status-code", "%i", s->main_exec_status.code);
3006 (void) serialize_item_format(f, "main-exec-status-status", "%i", s->main_exec_status.status);
ecdbca40
LP
3007 }
3008 }
f06db334 3009
19dff691
MY
3010 if (s->notify_access_override >= 0)
3011 (void) serialize_item(f, "notify-access-override", notify_access_to_string(s->notify_access_override));
3012
d68c645b
LP
3013 (void) serialize_dual_timestamp(f, "watchdog-timestamp", &s->watchdog_timestamp);
3014 (void) serialize_bool(f, "forbid-restart", s->forbid_restart);
6aca9a58 3015
2787d83c 3016 if (s->watchdog_override_enable)
d68c645b 3017 (void) serialize_item_format(f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2787d83c 3018
aa8c4bbf
LP
3019 if (s->watchdog_original_usec != USEC_INFINITY)
3020 (void) serialize_item_format(f, "watchdog-original-usec", USEC_FMT, s->watchdog_original_usec);
3021
3bd28bf7
LP
3022 if (s->reload_begin_usec != USEC_INFINITY)
3023 (void) serialize_item_format(f, "reload-begin-usec", USEC_FMT, s->reload_begin_usec);
3024
a16e1123
LP
3025 return 0;
3026}
3027
35243b77 3028int service_deserialize_exec_command(
5b99bd5f
LP
3029 Unit *u,
3030 const char *key,
3031 const char *value) {
3032
e266c068
MS
3033 Service *s = SERVICE(u);
3034 int r;
3035 unsigned idx = 0, i;
a99bd455 3036 bool control, found = false, last = false;
e266c068
MS
3037 ServiceExecCommand id = _SERVICE_EXEC_COMMAND_INVALID;
3038 ExecCommand *command = NULL;
6eeec374 3039 _cleanup_free_ char *path = NULL;
e266c068
MS
3040 _cleanup_strv_free_ char **argv = NULL;
3041
3042 enum ExecCommandState {
3043 STATE_EXEC_COMMAND_TYPE,
3044 STATE_EXEC_COMMAND_INDEX,
3045 STATE_EXEC_COMMAND_PATH,
3046 STATE_EXEC_COMMAND_ARGS,
3047 _STATE_EXEC_COMMAND_MAX,
2d93c20e 3048 _STATE_EXEC_COMMAND_INVALID = -EINVAL,
e266c068
MS
3049 } state;
3050
3051 assert(s);
3052 assert(key);
3053 assert(value);
3054
3055 control = streq(key, "control-command");
3056
3057 state = STATE_EXEC_COMMAND_TYPE;
3058
3059 for (;;) {
3060 _cleanup_free_ char *arg = NULL;
3061
334c0979 3062 r = extract_first_word(&value, &arg, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
efa3f34e
LP
3063 if (r < 0)
3064 return r;
e266c068
MS
3065 if (r == 0)
3066 break;
e266c068
MS
3067
3068 switch (state) {
3069 case STATE_EXEC_COMMAND_TYPE:
3070 id = service_exec_command_from_string(arg);
3071 if (id < 0)
7211c853 3072 return id;
e266c068
MS
3073
3074 state = STATE_EXEC_COMMAND_INDEX;
3075 break;
3076 case STATE_EXEC_COMMAND_INDEX:
a99bd455
ZJS
3077 /* PID 1234 is serialized as either '1234' or '+1234'. The second form is used to
3078 * mark the last command in a sequence. We warn if the deserialized command doesn't
3079 * match what we have loaded from the unit, but we don't need to warn if that is the
3080 * last command. */
3081
e266c068
MS
3082 r = safe_atou(arg, &idx);
3083 if (r < 0)
7211c853 3084 return r;
a99bd455 3085 last = arg[0] == '+';
e266c068
MS
3086
3087 state = STATE_EXEC_COMMAND_PATH;
3088 break;
3089 case STATE_EXEC_COMMAND_PATH:
ae2a15bc 3090 path = TAKE_PTR(arg);
e266c068 3091 state = STATE_EXEC_COMMAND_ARGS;
e266c068
MS
3092 break;
3093 case STATE_EXEC_COMMAND_ARGS:
3094 r = strv_extend(&argv, arg);
3095 if (r < 0)
3096 return -ENOMEM;
3097 break;
3098 default:
04499a70 3099 assert_not_reached();
e266c068
MS
3100 }
3101 }
3102
3103 if (state != STATE_EXEC_COMMAND_ARGS)
3104 return -EINVAL;
90204792
ZJS
3105 if (strv_isempty(argv))
3106 return -EINVAL; /* At least argv[0] must be always present. */
e266c068
MS
3107
3108 /* Let's check whether exec command on given offset matches data that we just deserialized */
3109 for (command = s->exec_command[id], i = 0; command; command = command->command_next, i++) {
3110 if (i != idx)
3111 continue;
3112
3113 found = strv_equal(argv, command->argv) && streq(command->path, path);
3114 break;
3115 }
3116
3117 if (!found) {
3118 /* Command at the index we serialized is different, let's look for command that exactly
3119 * matches but is on different index. If there is no such command we will not resume execution. */
3120 for (command = s->exec_command[id]; command; command = command->command_next)
3121 if (strv_equal(command->argv, argv) && streq(command->path, path))
3122 break;
3123 }
3124
e9da62b1 3125 if (command && control) {
e266c068 3126 s->control_command = command;
e9da62b1
LP
3127 s->control_command_id = id;
3128 } else if (command)
e266c068 3129 s->main_command = command;
a99bd455
ZJS
3130 else if (last)
3131 log_unit_debug(u, "Current command vanished from the unit file.");
e266c068
MS
3132 else
3133 log_unit_warning(u, "Current command vanished from the unit file, execution of the command list won't be resumed.");
3134
3135 return 0;
3136}
3137
a16e1123
LP
3138static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
3139 Service *s = SERVICE(u);
2339fc93 3140 int r;
a16e1123
LP
3141
3142 assert(u);
3143 assert(key);
3144 assert(value);
3145 assert(fds);
3146
3147 if (streq(key, "state")) {
3148 ServiceState state;
3149
117dcc57
ZJS
3150 state = service_state_from_string(value);
3151 if (state < 0)
f2341e0a 3152 log_unit_debug(u, "Failed to parse state value: %s", value);
a16e1123
LP
3153 else
3154 s->deserialized_state = state;
f42806df
LP
3155 } else if (streq(key, "result")) {
3156 ServiceResult f;
3157
3158 f = service_result_from_string(value);
3159 if (f < 0)
f2341e0a 3160 log_unit_debug(u, "Failed to parse result value: %s", value);
f42806df
LP
3161 else if (f != SERVICE_SUCCESS)
3162 s->result = f;
3163
3164 } else if (streq(key, "reload-result")) {
3165 ServiceResult f;
3166
3167 f = service_result_from_string(value);
3168 if (f < 0)
f2341e0a 3169 log_unit_debug(u, "Failed to parse reload result value: %s", value);
f42806df
LP
3170 else if (f != SERVICE_SUCCESS)
3171 s->reload_result = f;
a16e1123 3172
a16e1123 3173 } else if (streq(key, "control-pid")) {
5925dd3c 3174 pid_t pid;
a16e1123 3175
e364ad06 3176 if (parse_pid(value, &pid) < 0)
f2341e0a 3177 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
a16e1123 3178 else
e55224ca 3179 s->control_pid = pid;
a16e1123 3180 } else if (streq(key, "main-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 main-pid value: %s", value);
eabd3e56
LP
3185 else
3186 (void) service_set_main_pid(s, pid);
a16e1123
LP
3187 } else if (streq(key, "main-pid-known")) {
3188 int b;
3189
117dcc57
ZJS
3190 b = parse_boolean(value);
3191 if (b < 0)
f2341e0a 3192 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
a16e1123
LP
3193 else
3194 s->main_pid_known = b;
de1d4f9b
WF
3195 } else if (streq(key, "bus-name-good")) {
3196 int b;
3197
3198 b = parse_boolean(value);
3199 if (b < 0)
3200 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
3201 else
3202 s->bus_name_good = b;
d8ccf5fd
DM
3203 } else if (streq(key, "bus-name-owner")) {
3204 r = free_and_strdup(&s->bus_name_owner, value);
3205 if (r < 0)
3206 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
3a2776bc
LP
3207 } else if (streq(key, "status-text")) {
3208 char *t;
e437538f 3209 ssize_t l;
3a2776bc 3210
e437538f
ZJS
3211 l = cunescape(value, 0, &t);
3212 if (l < 0)
3213 log_unit_debug_errno(u, l, "Failed to unescape status text '%s': %m", value);
efa3f34e
LP
3214 else
3215 free_and_replace(s->status_text, t);
3a2776bc 3216
9dfb64f8
ZJS
3217 } else if (streq(key, "accept-socket")) {
3218 Unit *socket;
3219
45b10174
FS
3220 if (u->type != UNIT_SOCKET) {
3221 log_unit_debug(u, "Failed to deserialize accept-socket: unit is not a socket");
3222 return 0;
3223 }
3224
9dfb64f8
ZJS
3225 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
3226 if (r < 0)
5e1ee764 3227 log_unit_debug_errno(u, r, "Failed to load accept-socket unit '%s': %m", value);
9dfb64f8 3228 else {
7f7d01ed 3229 unit_ref_set(&s->accept_socket, u, socket);
9dfb64f8
ZJS
3230 SOCKET(socket)->n_connections++;
3231 }
3232
a16e1123
LP
3233 } else if (streq(key, "socket-fd")) {
3234 int fd;
3235
e652663a 3236 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd))
f2341e0a 3237 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
a16e1123 3238 else {
574634bc 3239 asynchronous_close(s->socket_fd);
a16e1123
LP
3240 s->socket_fd = fdset_remove(fds, fd);
3241 }
2339fc93 3242 } else if (streq(key, "fd-store-fd")) {
30520492 3243 _cleanup_free_ char *fdv = NULL, *fdn = NULL, *fdp = NULL;
a02287ea 3244 int fd, do_poll;
2339fc93 3245
30520492 3246 r = extract_first_word(&value, &fdv, NULL, 0);
e652663a 3247 if (r <= 0 || (fd = parse_fd(fdv)) < 0 || !fdset_contains(fds, fd)) {
f2341e0a 3248 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
30520492
KL
3249 return 0;
3250 }
8dd4c05b 3251
30520492
KL
3252 r = extract_first_word(&value, &fdn, NULL, EXTRACT_CUNESCAPE | EXTRACT_UNQUOTE);
3253 if (r <= 0) {
95599cac 3254 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
30520492
KL
3255 return 0;
3256 }
8dd4c05b 3257
30520492
KL
3258 r = extract_first_word(&value, &fdp, NULL, 0);
3259 if (r == 0) {
3260 /* If the value is not present, we assume the default */
3261 do_poll = 1;
3262 } else if (r < 0 || safe_atoi(fdp, &do_poll) < 0) {
3263 log_unit_debug_errno(u, r, "Failed to parse fd-store-fd value \"%s\": %m", value);
3264 return 0;
2339fc93
LP
3265 }
3266
a02287ea
YW
3267 r = fdset_remove(fds, fd);
3268 if (r < 0) {
3269 log_unit_error_errno(u, r, "Could not find deserialized fd %i in fdset: %m", fd);
3270 return 0;
3271 }
3272 assert(r == fd);
3273
30520492 3274 r = service_add_fd_store(s, fd, fdn, do_poll);
a02287ea
YW
3275 if (r < 0) {
3276 log_unit_error_errno(u, r, "Failed to store deserialized fd %i: %m", fd);
3277 return 0;
3278 }
ecdbca40
LP
3279 } else if (streq(key, "main-exec-status-pid")) {
3280 pid_t pid;
3281
e364ad06 3282 if (parse_pid(value, &pid) < 0)
f2341e0a 3283 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
ecdbca40
LP
3284 else
3285 s->main_exec_status.pid = pid;
3286 } else if (streq(key, "main-exec-status-code")) {
3287 int i;
3288
e364ad06 3289 if (safe_atoi(value, &i) < 0)
f2341e0a 3290 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
ecdbca40
LP
3291 else
3292 s->main_exec_status.code = i;
3293 } else if (streq(key, "main-exec-status-status")) {
3294 int i;
3295
e364ad06 3296 if (safe_atoi(value, &i) < 0)
f2341e0a 3297 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
ecdbca40
LP
3298 else
3299 s->main_exec_status.status = i;
799fd0fd 3300 } else if (streq(key, "main-exec-status-start"))
d68c645b 3301 deserialize_dual_timestamp(value, &s->main_exec_status.start_timestamp);
799fd0fd 3302 else if (streq(key, "main-exec-status-exit"))
d68c645b 3303 deserialize_dual_timestamp(value, &s->main_exec_status.exit_timestamp);
19dff691
MY
3304 else if (streq(key, "notify-access-override")) {
3305 NotifyAccess notify_access;
3306
3307 notify_access = notify_access_from_string(value);
3308 if (notify_access < 0)
3309 log_unit_debug(u, "Failed to parse notify-access-override value: %s", value);
3310 else
3311 s->notify_access_override = notify_access;
3312 } else if (streq(key, "watchdog-timestamp"))
d68c645b 3313 deserialize_dual_timestamp(value, &s->watchdog_timestamp);
613b411c 3314 else if (streq(key, "forbid-restart")) {
6aca9a58
SE
3315 int b;
3316
3317 b = parse_boolean(value);
3318 if (b < 0)
f2341e0a 3319 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
6aca9a58
SE
3320 else
3321 s->forbid_restart = b;
a34ceba6
LP
3322 } else if (streq(key, "stdin-fd")) {
3323 int fd;
3324
e652663a 3325 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd))
a34ceba6
LP
3326 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
3327 else {
3328 asynchronous_close(s->stdin_fd);
3329 s->stdin_fd = fdset_remove(fds, fd);
1e22b5cd 3330 s->exec_context.stdio_as_fds = true;
a34ceba6
LP
3331 }
3332 } else if (streq(key, "stdout-fd")) {
3333 int fd;
3334
e652663a 3335 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd))
a34ceba6
LP
3336 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
3337 else {
3338 asynchronous_close(s->stdout_fd);
3339 s->stdout_fd = fdset_remove(fds, fd);
1e22b5cd 3340 s->exec_context.stdio_as_fds = true;
a34ceba6
LP
3341 }
3342 } else if (streq(key, "stderr-fd")) {
3343 int fd;
3344
e652663a 3345 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd))
a34ceba6
LP
3346 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
3347 else {
3348 asynchronous_close(s->stderr_fd);
3349 s->stderr_fd = fdset_remove(fds, fd);
1e22b5cd 3350 s->exec_context.stdio_as_fds = true;
a34ceba6 3351 }
5686391b
LP
3352 } else if (streq(key, "exec-fd")) {
3353 int fd;
3354
e652663a 3355 if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd))
5686391b
LP
3356 log_unit_debug(u, "Failed to parse exec-fd value: %s", value);
3357 else {
5dcadb4c 3358 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b
LP
3359
3360 fd = fdset_remove(fds, fd);
3361 if (service_allocate_exec_fd_event_source(s, fd, &s->exec_fd_event_source) < 0)
3362 safe_close(fd);
3363 }
2787d83c 3364 } else if (streq(key, "watchdog-override-usec")) {
d68c645b 3365 if (deserialize_usec(value, &s->watchdog_override_usec) < 0)
2787d83c 3366 log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
d68c645b 3367 else
2787d83c 3368 s->watchdog_override_enable = true;
d68c645b 3369
aa8c4bbf
LP
3370 } else if (streq(key, "watchdog-original-usec")) {
3371 if (deserialize_usec(value, &s->watchdog_original_usec) < 0)
3372 log_unit_debug(u, "Failed to parse watchdog_original_usec value: %s", value);
3373
e266c068
MS
3374 } else if (STR_IN_SET(key, "main-command", "control-command")) {
3375 r = service_deserialize_exec_command(u, key, value);
3376 if (r < 0)
3377 log_unit_debug_errno(u, r, "Failed to parse serialized command \"%s\": %m", value);
7a0019d3
LP
3378
3379 } else if (streq(key, "n-restarts")) {
3380 r = safe_atou(value, &s->n_restarts);
3381 if (r < 0)
3382 log_unit_debug_errno(u, r, "Failed to parse serialized restart counter '%s': %m", value);
3383
3384 } else if (streq(key, "flush-n-restarts")) {
3385 r = parse_boolean(value);
3386 if (r < 0)
3387 log_unit_debug_errno(u, r, "Failed to parse serialized flush restart counter setting '%s': %m", value);
3388 else
3389 s->flush_n_restarts = r;
3bd28bf7
LP
3390 } else if (streq(key, "reload-begin-usec")) {
3391 r = deserialize_usec(value, &s->reload_begin_usec);
3392 if (r < 0)
3393 log_unit_debug_errno(u, r, "Failed to parse serialized reload begin timestamp '%s', ignoring: %m", value);
c17ec25e 3394 } else
f2341e0a 3395 log_unit_debug(u, "Unknown serialization key: %s", key);
a16e1123
LP
3396
3397 return 0;
3398}
3399
44a6b1b6 3400_pure_ static UnitActiveState service_active_state(Unit *u) {
e056b01d
LP
3401 const UnitActiveState *table;
3402
87f0e418 3403 assert(u);
5cb5a6ff 3404
e056b01d
LP
3405 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
3406
3407 return table[SERVICE(u)->state];
034c6ed7
LP
3408}
3409
10a94420
LP
3410static const char *service_sub_state_to_string(Unit *u) {
3411 assert(u);
3412
3413 return service_state_to_string(SERVICE(u)->state);
3414}
3415
f2f725e5 3416static bool service_may_gc(Unit *u) {
701cc384
LP
3417 Service *s = SERVICE(u);
3418
3419 assert(s);
3420
e98b2fbb 3421 /* Never clean up services that still have a process around, even if the service is formally dead. Note that
f2f725e5 3422 * unit_may_gc() already checked our cgroup for us, we just check our two additional PIDs, too, in case they
e98b2fbb
LP
3423 * have moved outside of the cgroup. */
3424
3425 if (main_pid_good(s) > 0 ||
6d55002a 3426 control_pid_good(s) > 0)
f2f725e5 3427 return false;
6d55002a 3428
a1d31573
LP
3429 /* Only allow collection of actually dead services, i.e. not those that are in the transitionary
3430 * SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART states. */
b9c1883a 3431 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
a1d31573
LP
3432 return false;
3433
f2f725e5 3434 return true;
6d55002a
LP
3435}
3436
3a111838
MS
3437static int service_retry_pid_file(Service *s) {
3438 int r;
3439
3440 assert(s->pid_file);
3742095b 3441 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838
MS
3442
3443 r = service_load_pid_file(s, false);
3444 if (r < 0)
3445 return r;
3446
3447 service_unwatch_pid_file(s);
3448
f42806df 3449 service_enter_running(s, SERVICE_SUCCESS);
3a111838
MS
3450 return 0;
3451}
3452
3453static int service_watch_pid_file(Service *s) {
3454 int r;
3455
f2341e0a 3456 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
8bb2d17d 3457
5686391b 3458 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_inotify_io);
3a111838
MS
3459 if (r < 0)
3460 goto fail;
3461
3462 /* the pidfile might have appeared just before we set the watch */
f2341e0a 3463 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
3a111838
MS
3464 service_retry_pid_file(s);
3465
3466 return 0;
3467fail:
f2341e0a 3468 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
3a111838
MS
3469 service_unwatch_pid_file(s);
3470 return r;
3471}
3472
3473static int service_demand_pid_file(Service *s) {
51339a9a 3474 _cleanup_free_ PathSpec *ps = NULL;
3a111838
MS
3475
3476 assert(s->pid_file);
3477 assert(!s->pid_file_pathspec);
3478
51339a9a 3479 ps = new(PathSpec, 1);
3a111838
MS
3480 if (!ps)
3481 return -ENOMEM;
3482
51339a9a
LP
3483 *ps = (PathSpec) {
3484 .unit = UNIT(s),
3485 .path = strdup(s->pid_file),
3486 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that keep their PID file
3487 * open all the time. */
3488 .type = PATH_MODIFIED,
3489 .inotify_fd = -EBADF,
3490 };
3491
3492 if (!ps->path)
3a111838 3493 return -ENOMEM;
3a111838 3494
4ff361cc 3495 path_simplify(ps->path);
3a111838 3496
51339a9a 3497 s->pid_file_pathspec = TAKE_PTR(ps);
3a111838
MS
3498
3499 return service_watch_pid_file(s);
3500}
3501
5686391b 3502static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
99534007 3503 PathSpec *p = ASSERT_PTR(userdata);
e14c2802
LP
3504 Service *s;
3505
e14c2802 3506 s = SERVICE(p->unit);
3a111838
MS
3507
3508 assert(s);
3509 assert(fd >= 0);
3742095b 3510 assert(IN_SET(s->state, SERVICE_START, SERVICE_START_POST));
3a111838 3511 assert(s->pid_file_pathspec);
57020a3a 3512 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3a111838 3513
f2341e0a 3514 log_unit_debug(UNIT(s), "inotify event");
3a111838 3515
e14c2802 3516 if (path_spec_fd_event(p, events) < 0)
3a111838
MS
3517 goto fail;
3518
3519 if (service_retry_pid_file(s) == 0)
718db961 3520 return 0;
3a111838
MS
3521
3522 if (service_watch_pid_file(s) < 0)
3523 goto fail;
3524
718db961
LP
3525 return 0;
3526
3a111838
MS
3527fail:
3528 service_unwatch_pid_file(s);
f42806df 3529 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
718db961 3530 return 0;
3a111838
MS
3531}
3532
5686391b
LP
3533static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
3534 Service *s = SERVICE(userdata);
3535
3536 assert(s);
3537
3538 log_unit_debug(UNIT(s), "got exec-fd event");
3539
3540 /* If Type=exec is set, we'll consider a service started successfully the instant we invoked execve()
3541 * successfully for it. We implement this through a pipe() towards the child, which the kernel automatically
3542 * closes for us due to O_CLOEXEC on execve() in the child, which then triggers EOF on the pipe in the
3543 * parent. We need to be careful however, as there are other reasons that we might cause the child's side of
3544 * the pipe to be closed (for example, a simple exit()). To deal with that we'll ignore EOFs on the pipe unless
3545 * the child signalled us first that it is about to call the execve(). It does so by sending us a simple
3546 * non-zero byte via the pipe. We also provide the child with a way to inform us in case execve() failed: if it
3547 * sends a zero byte we'll ignore POLLHUP on the fd again. */
3548
3549 for (;;) {
3550 uint8_t x;
3551 ssize_t n;
3552
3553 n = read(fd, &x, sizeof(x));
3554 if (n < 0) {
3555 if (errno == EAGAIN) /* O_NONBLOCK in effect → everything queued has now been processed. */
3556 return 0;
3557
3558 return log_unit_error_errno(UNIT(s), errno, "Failed to read from exec_fd: %m");
3559 }
3560 if (n == 0) { /* EOF → the event we are waiting for */
3561
5dcadb4c 3562 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
5686391b
LP
3563
3564 if (s->exec_fd_hot) { /* Did the child tell us to expect EOF now? */
3565 log_unit_debug(UNIT(s), "Got EOF on exec-fd");
3566
3567 s->exec_fd_hot = false;
3568
3569 /* Nice! This is what we have been waiting for. Transition to next state. */
3570 if (s->type == SERVICE_EXEC && s->state == SERVICE_START)
3571 service_enter_start_post(s);
3572 } else
3573 log_unit_debug(UNIT(s), "Got EOF on exec-fd while it was disabled, ignoring.");
3574
3575 return 0;
3576 }
3577
3578 /* A byte was read → this turns on/off the exec fd logic */
3579 assert(n == sizeof(x));
3580 s->exec_fd_hot = x;
3581 }
3582
3583 return 0;
3584}
3585
a911bb9a
LP
3586static void service_notify_cgroup_empty_event(Unit *u) {
3587 Service *s = SERVICE(u);
3588
3589 assert(u);
3590
a5b5aece 3591 log_unit_debug(u, "Control group is empty.");
a911bb9a
LP
3592
3593 switch (s->state) {
3594
a1d31573
LP
3595 /* Waiting for SIGCHLD is usually more interesting, because it includes return
3596 * codes/signals. Which is why we ignore the cgroup events for most cases, except when we
3597 * don't know pid which to expect the SIGCHLD for. */
a911bb9a
LP
3598
3599 case SERVICE_START:
3bd28bf7 3600 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
3c751b1b
LP
3601 main_pid_good(s) == 0 &&
3602 control_pid_good(s) == 0) {
3d474ef7 3603 /* No chance of getting a ready notification anymore */
c3fda31d 3604 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
71e529fc
JW
3605 break;
3606 }
3607
596e4470
HC
3608 if (s->exit_type == SERVICE_EXIT_CGROUP && main_pid_good(s) <= 0)
3609 service_enter_start_post(s);
3610
4831981d 3611 _fallthrough_;
71e529fc 3612 case SERVICE_START_POST:
3c751b1b
LP
3613 if (s->pid_file_pathspec &&
3614 main_pid_good(s) == 0 &&
3615 control_pid_good(s) == 0) {
3616
3d474ef7 3617 /* Give up hoping for the daemon to write its PID file */
f2341e0a 3618 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
8bb2d17d 3619
a911bb9a
LP
3620 service_unwatch_pid_file(s);
3621 if (s->state == SERVICE_START)
c3fda31d 3622 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a 3623 else
c35755fb 3624 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a
LP
3625 }
3626 break;
3627
3628 case SERVICE_RUNNING:
3629 /* service_enter_running() will figure out what to do */
3630 service_enter_running(s, SERVICE_SUCCESS);
3631 break;
3632
c87700a1 3633 case SERVICE_STOP_WATCHDOG:
a911bb9a
LP
3634 case SERVICE_STOP_SIGTERM:
3635 case SERVICE_STOP_SIGKILL:
3636
b13ddbbc 3637 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3638 service_enter_stop_post(s, SERVICE_SUCCESS);
3639
3640 break;
3641
3642 case SERVICE_STOP_POST:
bf760801 3643 case SERVICE_FINAL_WATCHDOG:
a911bb9a
LP
3644 case SERVICE_FINAL_SIGTERM:
3645 case SERVICE_FINAL_SIGKILL:
b13ddbbc 3646 if (main_pid_good(s) <= 0 && control_pid_good(s) <= 0)
a911bb9a
LP
3647 service_enter_dead(s, SERVICE_SUCCESS, true);
3648
3649 break;
3650
e08dabfe
AZ
3651 /* If the cgroup empty notification comes when the unit is not active, we must have failed to clean
3652 * up the cgroup earlier and should do it now. */
3653 case SERVICE_DEAD:
3654 case SERVICE_FAILED:
a1d31573
LP
3655 case SERVICE_DEAD_BEFORE_AUTO_RESTART:
3656 case SERVICE_FAILED_BEFORE_AUTO_RESTART:
3657 case SERVICE_AUTO_RESTART:
b9c1883a 3658 case SERVICE_DEAD_RESOURCES_PINNED:
e08dabfe
AZ
3659 unit_prune_cgroup(u);
3660 break;
3661
a911bb9a
LP
3662 default:
3663 ;
3664 }
3665}
3666
38c41427 3667static void service_notify_cgroup_oom_event(Unit *u, bool managed_oom) {
afcfaa69
LP
3668 Service *s = SERVICE(u);
3669
38c41427
NK
3670 if (managed_oom)
3671 log_unit_debug(u, "Process(es) of control group were killed by systemd-oomd.");
3672 else
3673 log_unit_debug(u, "Process of control group was killed by the OOM killer.");
afcfaa69
LP
3674
3675 if (s->oom_policy == OOM_CONTINUE)
3676 return;
3677
3678 switch (s->state) {
3679
31cd5f63 3680 case SERVICE_CONDITION:
afcfaa69
LP
3681 case SERVICE_START_PRE:
3682 case SERVICE_START:
3683 case SERVICE_START_POST:
3684 case SERVICE_STOP:
3685 if (s->oom_policy == OOM_STOP)
3686 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_OOM_KILL);
3687 else if (s->oom_policy == OOM_KILL)
3688 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3689
3690 break;
3691
3692 case SERVICE_EXITED:
3693 case SERVICE_RUNNING:
3694 if (s->oom_policy == OOM_STOP)
3695 service_enter_stop(s, SERVICE_FAILURE_OOM_KILL);
3696 else if (s->oom_policy == OOM_KILL)
3697 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3698
3699 break;
3700
3701 case SERVICE_STOP_WATCHDOG:
3702 case SERVICE_STOP_SIGTERM:
3703 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3704 break;
3705
3706 case SERVICE_STOP_SIGKILL:
3707 case SERVICE_FINAL_SIGKILL:
3708 if (s->result == SERVICE_SUCCESS)
3709 s->result = SERVICE_FAILURE_OOM_KILL;
3710 break;
3711
3712 case SERVICE_STOP_POST:
3713 case SERVICE_FINAL_SIGTERM:
3714 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_OOM_KILL);
3715 break;
3716
3717 default:
3718 ;
3719 }
3720}
3721
87f0e418 3722static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
5cdabc8d 3723 bool notify_dbus = true;
87f0e418 3724 Service *s = SERVICE(u);
f42806df 3725 ServiceResult f;
e5123725 3726 ExitClean clean_mode;
5cb5a6ff
LP
3727
3728 assert(s);
034c6ed7
LP
3729 assert(pid >= 0);
3730
e5123725
AZ
3731 /* Oneshot services and non-SERVICE_EXEC_START commands should not be
3732 * considered daemons as they are typically not long running. */
3733 if (s->type == SERVICE_ONESHOT || (s->control_pid == pid && s->control_command_id != SERVICE_EXEC_START))
3734 clean_mode = EXIT_CLEAN_COMMAND;
3735 else
3736 clean_mode = EXIT_CLEAN_DAEMON;
3737
3738 if (is_clean_exit(code, status, clean_mode, &s->success_status))
f42806df
LP
3739 f = SERVICE_SUCCESS;
3740 else if (code == CLD_EXITED)
3741 f = SERVICE_FAILURE_EXIT_CODE;
3742 else if (code == CLD_KILLED)
3743 f = SERVICE_FAILURE_SIGNAL;
3744 else if (code == CLD_DUMPED)
3745 f = SERVICE_FAILURE_CORE_DUMP;
d06dacd0 3746 else
04499a70 3747 assert_not_reached();
034c6ed7 3748
abaf5edd 3749 if (s->main_pid == pid) {
13bb1ffb
ZJS
3750 /* Clean up the exec_fd event source. We want to do this here, not later in
3751 * service_set_state(), because service_enter_stop_post() calls service_spawn().
3752 * The source owns its end of the pipe, so this will close that too. */
3753 s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
3754
db01f8b3
MS
3755 /* Forking services may occasionally move to a new PID.
3756 * As long as they update the PID file before exiting the old
3757 * PID, they're fine. */
db256aab 3758 if (service_load_pid_file(s, false) > 0)
db01f8b3 3759 return;
034c6ed7 3760
034c6ed7 3761 s->main_pid = 0;
ff32060f 3762 s->main_pid_known = false;
6ea832a2 3763 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
034c6ed7 3764
867b3b7d 3765 if (s->main_command) {
fbeefb45
LP
3766 /* If this is not a forking service than the
3767 * main process got started and hence we copy
3768 * the exit status so that it is recorded both
3769 * as main and as control process exit
3770 * status */
3771
867b3b7d 3772 s->main_command->exec_status = s->main_exec_status;
b708e7ce 3773
3ed0cd26 3774 if (s->main_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 3775 f = SERVICE_SUCCESS;
fbeefb45
LP
3776 } else if (s->exec_command[SERVICE_EXEC_START]) {
3777
3778 /* If this is a forked process, then we should
3779 * ignore the return value if this was
3780 * configured for the starter process */
3781
3ed0cd26 3782 if (s->exec_command[SERVICE_EXEC_START]->flags & EXEC_COMMAND_IGNORE_FAILURE)
fbeefb45 3783 f = SERVICE_SUCCESS;
034c6ed7
LP
3784 }
3785
91bbd9b7 3786 unit_log_process_exit(
5cc2cd1c 3787 u,
abaf5edd 3788 "Main process",
91bbd9b7 3789 service_exec_command_to_string(SERVICE_EXEC_START),
5cc2cd1c 3790 f == SERVICE_SUCCESS,
91bbd9b7 3791 code, status);
f42806df 3792
a0fef983 3793 if (s->result == SERVICE_SUCCESS)
f42806df 3794 s->result = f;
034c6ed7 3795
867b3b7d
LP
3796 if (s->main_command &&
3797 s->main_command->command_next &&
b58aeb70 3798 s->type == SERVICE_ONESHOT &&
f42806df 3799 f == SERVICE_SUCCESS) {
034c6ed7 3800
e78695d4 3801 /* There is another command to execute, so let's do that. */
034c6ed7 3802
f2341e0a 3803 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
f42806df 3804 service_run_next_main(s);
034c6ed7 3805
34e9ba66 3806 } else {
867b3b7d 3807 s->main_command = NULL;
34e9ba66 3808
3bd28bf7
LP
3809 /* Services with ExitType=cgroup do not act on main PID exiting, unless the cgroup is
3810 * already empty */
596e4470
HC
3811 if (s->exit_type == SERVICE_EXIT_MAIN || cgroup_good(s) <= 0) {
3812 /* The service exited, so the service is officially gone. */
3813 switch (s->state) {
3814
3815 case SERVICE_START_POST:
3816 case SERVICE_RELOAD:
3bd28bf7
LP
3817 case SERVICE_RELOAD_SIGNAL:
3818 case SERVICE_RELOAD_NOTIFY:
3819 /* If neither main nor control processes are running then the current
3820 * state can never exit cleanly, hence immediately terminate the
3821 * service. */
596e4470
HC
3822 if (control_pid_good(s) <= 0)
3823 service_enter_stop(s, f);
3824
3825 /* Otherwise need to wait until the operation is done. */
3826 break;
bbe19f68 3827
596e4470
HC
3828 case SERVICE_STOP:
3829 /* Need to wait until the operation is done. */
3830 break;
bbe19f68 3831
596e4470
HC
3832 case SERVICE_START:
3833 if (s->type == SERVICE_ONESHOT) {
3834 /* This was our main goal, so let's go on */
3835 if (f == SERVICE_SUCCESS)
3836 service_enter_start_post(s);
3837 else
3838 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3839 break;
3bd28bf7 3840 } else if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD)) {
596e4470
HC
3841 /* Only enter running through a notification, so that the
3842 * SERVICE_START state signifies that no ready notification
3843 * has been received */
3844 if (f != SERVICE_SUCCESS)
3845 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
19dff691 3846 else if (!s->remain_after_exit || service_get_notify_access(s) == NOTIFY_MAIN)
596e4470
HC
3847 /* The service has never been and will never be active */
3848 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3849 break;
3850 }
7d55e835 3851
596e4470
HC
3852 _fallthrough_;
3853 case SERVICE_RUNNING:
3854 service_enter_running(s, f);
3d474ef7 3855 break;
034c6ed7 3856
596e4470
HC
3857 case SERVICE_STOP_WATCHDOG:
3858 case SERVICE_STOP_SIGTERM:
3859 case SERVICE_STOP_SIGKILL:
5cb5a6ff 3860
596e4470
HC
3861 if (control_pid_good(s) <= 0)
3862 service_enter_stop_post(s, f);
5cb5a6ff 3863
596e4470
HC
3864 /* If there is still a control process, wait for that first */
3865 break;
34e9ba66 3866
596e4470 3867 case SERVICE_STOP_POST:
c1566ef0 3868
596e4470
HC
3869 if (control_pid_good(s) <= 0)
3870 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
c1566ef0 3871
596e4470 3872 break;
c1566ef0 3873
596e4470
HC
3874 case SERVICE_FINAL_WATCHDOG:
3875 case SERVICE_FINAL_SIGTERM:
3876 case SERVICE_FINAL_SIGKILL:
bf108e55 3877
596e4470
HC
3878 if (control_pid_good(s) <= 0)
3879 service_enter_dead(s, f, true);
3880 break;
bf108e55 3881
596e4470
HC
3882 default:
3883 assert_not_reached();
3884 }
34e9ba66 3885 }
034c6ed7 3886 }
5cb5a6ff 3887
034c6ed7 3888 } else if (s->control_pid == pid) {
58441bc1
ZJS
3889 const char *kind;
3890 bool success;
3891
34e9ba66
LP
3892 s->control_pid = 0;
3893
b708e7ce 3894 if (s->control_command) {
8bb2d17d 3895 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 3896
3ed0cd26 3897 if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
f42806df 3898 f = SERVICE_SUCCESS;
b708e7ce
LP
3899 }
3900
42e6f549
AZ
3901 /* ExecCondition= calls that exit with (0, 254] should invoke skip-like behavior instead of failing */
3902 if (s->state == SERVICE_CONDITION) {
3903 if (f == SERVICE_FAILURE_EXIT_CODE && status < 255) {
3904 UNIT(s)->condition_result = false;
3905 f = SERVICE_SKIP_CONDITION;
58441bc1
ZJS
3906 success = true;
3907 } else if (f == SERVICE_SUCCESS) {
42e6f549 3908 UNIT(s)->condition_result = true;
58441bc1
ZJS
3909 success = true;
3910 } else
3911 success = false;
3912
3913 kind = "Condition check process";
3914 } else {
3915 kind = "Control process";
3916 success = f == SERVICE_SUCCESS;
42e6f549
AZ
3917 }
3918
91bbd9b7 3919 unit_log_process_exit(
5cc2cd1c 3920 u,
58441bc1 3921 kind,
91bbd9b7 3922 service_exec_command_to_string(s->control_command_id),
58441bc1 3923 success,
91bbd9b7 3924 code, status);
f42806df 3925
d611cfa7 3926 if (s->state != SERVICE_RELOAD && s->result == SERVICE_SUCCESS)
f42806df 3927 s->result = f;
034c6ed7 3928
34e9ba66
LP
3929 if (s->control_command &&
3930 s->control_command->command_next &&
f42806df 3931 f == SERVICE_SUCCESS) {
034c6ed7 3932
3bd28bf7 3933 /* There is another command to * execute, so let's do that. */
034c6ed7 3934
f2341e0a 3935 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
f42806df 3936 service_run_next_control(s);
034c6ed7 3937
80876c20 3938 } else {
3bd28bf7 3939 /* No further commands for this step, so let's figure out what to do next */
034c6ed7 3940
a16e1123
LP
3941 s->control_command = NULL;
3942 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3943
f2341e0a 3944 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
bd982a8b 3945
034c6ed7
LP
3946 switch (s->state) {
3947
31cd5f63
AZ
3948 case SERVICE_CONDITION:
3949 if (f == SERVICE_SUCCESS)
3950 service_enter_start_pre(s);
3951 else
3952 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3953 break;
3954
034c6ed7 3955 case SERVICE_START_PRE:
f42806df 3956 if (f == SERVICE_SUCCESS)
034c6ed7
LP
3957 service_enter_start(s);
3958 else
c3fda31d 3959 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
3960 break;
3961
3962 case SERVICE_START:
bfba3256
LP
3963 if (s->type != SERVICE_FORKING)
3964 /* Maybe spurious event due to a reload that changed the type? */
3965 break;
034c6ed7 3966
f42806df 3967 if (f != SERVICE_SUCCESS) {
c3fda31d 3968 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3a111838
MS
3969 break;
3970 }
034c6ed7 3971
3a111838 3972 if (s->pid_file) {
f42806df
LP
3973 bool has_start_post;
3974 int r;
3975
3a111838
MS
3976 /* Let's try to load the pid file here if we can.
3977 * The PID file might actually be created by a START_POST
3978 * script. In that case don't worry if the loading fails. */
f42806df 3979
5d904a6a 3980 has_start_post = s->exec_command[SERVICE_EXEC_START_POST];
f42806df 3981 r = service_load_pid_file(s, !has_start_post);
3a111838
MS
3982 if (!has_start_post && r < 0) {
3983 r = service_demand_pid_file(s);
b13ddbbc 3984 if (r < 0 || cgroup_good(s) == 0)
c3fda31d 3985 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3a111838
MS
3986 break;
3987 }
034c6ed7 3988 } else
783e05d6 3989 service_search_main_pid(s);
034c6ed7 3990
3a111838 3991 service_enter_start_post(s);
034c6ed7
LP
3992 break;
3993
3994 case SERVICE_START_POST:
f42806df 3995 if (f != SERVICE_SUCCESS) {
ce359e98 3996 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2096e009 3997 break;
034c6ed7
LP
3998 }
3999
2096e009 4000 if (s->pid_file) {
f42806df
LP
4001 int r;
4002
4003 r = service_load_pid_file(s, true);
2096e009
MS
4004 if (r < 0) {
4005 r = service_demand_pid_file(s);
b13ddbbc 4006 if (r < 0 || cgroup_good(s) == 0)
c35755fb 4007 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2096e009
MS
4008 break;
4009 }
4010 } else
783e05d6 4011 service_search_main_pid(s);
2096e009 4012
f42806df 4013 service_enter_running(s, SERVICE_SUCCESS);
3185a36b 4014 break;
034c6ed7
LP
4015
4016 case SERVICE_RELOAD:
3bd28bf7
LP
4017 case SERVICE_RELOAD_SIGNAL:
4018 case SERVICE_RELOAD_NOTIFY:
7236ce6e
ZJS
4019 if (f == SERVICE_SUCCESS)
4020 if (service_load_pid_file(s, true) < 0)
4021 service_search_main_pid(s);
3185a36b 4022
f42806df 4023 s->reload_result = f;
3bd28bf7 4024
d09df6b9 4025 /* If the last notification we received from the service process indicates
3bd28bf7
LP
4026 * we are still reloading, then don't leave reloading state just yet, just
4027 * transition into SERVICE_RELOAD_NOTIFY, to wait for the READY=1 coming,
4028 * too. */
4029 if (s->notify_state == NOTIFY_RELOADING)
4030 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4031 else
4032 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
4033 break;
4034
4035 case SERVICE_STOP:
f42806df 4036 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
4037 break;
4038
c87700a1 4039 case SERVICE_STOP_WATCHDOG:
034c6ed7
LP
4040 case SERVICE_STOP_SIGTERM:
4041 case SERVICE_STOP_SIGKILL:
4042 if (main_pid_good(s) <= 0)
f42806df 4043 service_enter_stop_post(s, f);
034c6ed7 4044
846a07b5 4045 /* If there is still a service process around, wait until
034c6ed7
LP
4046 * that one quit, too */
4047 break;
4048
4049 case SERVICE_STOP_POST:
c1566ef0
AZ
4050 if (main_pid_good(s) <= 0)
4051 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
4052 break;
4053
bf760801 4054 case SERVICE_FINAL_WATCHDOG:
034c6ed7
LP
4055 case SERVICE_FINAL_SIGTERM:
4056 case SERVICE_FINAL_SIGKILL:
bf108e55
LP
4057 if (main_pid_good(s) <= 0)
4058 service_enter_dead(s, f, true);
034c6ed7
LP
4059 break;
4060
4c2f5842
LP
4061 case SERVICE_CLEANING:
4062
4063 if (s->clean_result == SERVICE_SUCCESS)
4064 s->clean_result = f;
4065
4066 service_enter_dead(s, SERVICE_SUCCESS, false);
4067 break;
4068
034c6ed7 4069 default:
04499a70 4070 assert_not_reached();
034c6ed7
LP
4071 }
4072 }
5cdabc8d
LP
4073 } else /* Neither control nor main PID? If so, don't notify about anything */
4074 notify_dbus = false;
c4e2ceae
LP
4075
4076 /* Notify clients about changed exit status */
5cdabc8d
LP
4077 if (notify_dbus)
4078 unit_add_to_dbus_queue(u);
a911bb9a 4079
846a07b5
FB
4080 /* We watch the main/control process otherwise we can't retrieve the unit they
4081 * belong to with cgroupv1. But if they are not our direct child, we won't get a
4082 * SIGCHLD for them. Therefore we need to look for others to watch so we can
4083 * detect when the cgroup becomes empty. Note that the control process is always
4084 * our child so it's pointless to watch all other processes. */
4085 if (!control_pid_good(s))
4086 if (!s->main_pid_known || s->main_pid_alien)
4087 (void) unit_enqueue_rewatch_pids(u);
034c6ed7
LP
4088}
4089
718db961
LP
4090static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
4091 Service *s = SERVICE(userdata);
034c6ed7
LP
4092
4093 assert(s);
718db961 4094 assert(source == s->timer_event_source);
034c6ed7
LP
4095
4096 switch (s->state) {
4097
31cd5f63 4098 case SERVICE_CONDITION:
034c6ed7
LP
4099 case SERVICE_START_PRE:
4100 case SERVICE_START:
4101 case SERVICE_START_POST:
bf760801
JK
4102 switch (s->timeout_start_failure_mode) {
4103
4104 case SERVICE_TIMEOUT_TERMINATE:
4105 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", service_state_to_string(s->state));
4106 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4107 break;
4108
4109 case SERVICE_TIMEOUT_ABORT:
4110 log_unit_warning(UNIT(s), "%s operation timed out. Aborting.", service_state_to_string(s->state));
4111 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4112 break;
4113
4114 case SERVICE_TIMEOUT_KILL:
4115 if (s->kill_context.send_sigkill) {
4116 log_unit_warning(UNIT(s), "%s operation timed out. Killing.", service_state_to_string(s->state));
4117 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4118 } else {
4119 log_unit_warning(UNIT(s), "%s operation timed out. Skipping SIGKILL.", service_state_to_string(s->state));
4120 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4121 }
4122 break;
4123
4124 default:
04499a70 4125 assert_not_reached();
bf760801 4126 }
034c6ed7
LP
4127 break;
4128
36c16a7c
LP
4129 case SERVICE_RUNNING:
4130 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
4131 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
4132 break;
4133
e2f3b44c 4134 case SERVICE_RELOAD:
3bd28bf7
LP
4135 case SERVICE_RELOAD_SIGNAL:
4136 case SERVICE_RELOAD_NOTIFY:
089b64d5 4137 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
e9a4f676 4138 service_kill_control_process(s);
f42806df
LP
4139 s->reload_result = SERVICE_FAILURE_TIMEOUT;
4140 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c
LP
4141 break;
4142
034c6ed7 4143 case SERVICE_STOP:
bf760801
JK
4144 switch (s->timeout_stop_failure_mode) {
4145
4146 case SERVICE_TIMEOUT_TERMINATE:
4147 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
4148 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4149 break;
4150
4151 case SERVICE_TIMEOUT_ABORT:
4152 log_unit_warning(UNIT(s), "Stopping timed out. Aborting.");
4153 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4154 break;
4155
4156 case SERVICE_TIMEOUT_KILL:
4157 if (s->kill_context.send_sigkill) {
4158 log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
4159 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4160 } else {
4161 log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL.");
4162 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4163 }
4164 break;
4165
4166 default:
04499a70 4167 assert_not_reached();
bf760801 4168 }
034c6ed7
LP
4169 break;
4170
c87700a1 4171 case SERVICE_STOP_WATCHDOG:
bf760801
JK
4172 if (s->kill_context.send_sigkill) {
4173 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Killing.");
4174 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4175 } else {
4176 log_unit_warning(UNIT(s), "State 'stop-watchdog' timed out. Skipping SIGKILL.");
4177 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
4178 }
db2cb23b
UTL
4179 break;
4180
034c6ed7 4181 case SERVICE_STOP_SIGTERM:
bf760801
JK
4182 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4183 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Aborting.");
4184 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4185 } else if (s->kill_context.send_sigkill) {
f2341e0a 4186 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
f42806df 4187 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4188 } else {
f2341e0a 4189 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
f42806df 4190 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
ba035df2
LP
4191 }
4192
034c6ed7
LP
4193 break;
4194
4195 case SERVICE_STOP_SIGKILL:
35b8ca3a 4196 /* Uh, we sent a SIGKILL and it is still not gone?
034c6ed7
LP
4197 * Must be something we cannot kill, so let's just be
4198 * weirded out and continue */
4199
f2341e0a 4200 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
f42806df 4201 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
4202 break;
4203
4204 case SERVICE_STOP_POST:
bf760801
JK
4205 switch (s->timeout_stop_failure_mode) {
4206
4207 case SERVICE_TIMEOUT_TERMINATE:
4208 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
4209 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
4210 break;
4211
4212 case SERVICE_TIMEOUT_ABORT:
4213 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Aborting.");
4214 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4215 break;
4216
4217 case SERVICE_TIMEOUT_KILL:
4218 if (s->kill_context.send_sigkill) {
4219 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Killing.");
4220 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4221 } else {
4222 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Skipping SIGKILL. Entering failed mode.");
4223 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4224 }
4225 break;
4226
4227 default:
04499a70 4228 assert_not_reached();
bf760801 4229 }
034c6ed7
LP
4230 break;
4231
bf760801 4232 case SERVICE_FINAL_WATCHDOG:
4819ff03 4233 if (s->kill_context.send_sigkill) {
bf760801 4234 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Killing.");
f42806df 4235 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 4236 } else {
bf760801
JK
4237 log_unit_warning(UNIT(s), "State 'final-watchdog' timed out. Skipping SIGKILL. Entering failed mode.");
4238 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
4239 }
4240 break;
4241
4242 case SERVICE_FINAL_SIGTERM:
4243 if (s->timeout_stop_failure_mode == SERVICE_TIMEOUT_ABORT) {
4244 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Aborting.");
4245 service_enter_signal(s, SERVICE_FINAL_WATCHDOG, SERVICE_FAILURE_TIMEOUT);
4246 } else if (s->kill_context.send_sigkill) {
4247 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Killing.");
4248 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
4249 } else {
4250 log_unit_warning(UNIT(s), "State 'final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
f42806df 4251 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
ba035df2
LP
4252 }
4253
034c6ed7
LP
4254 break;
4255
4256 case SERVICE_FINAL_SIGKILL:
f2341e0a 4257 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
f42806df 4258 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
034c6ed7
LP
4259 break;
4260
4261 case SERVICE_AUTO_RESTART:
5291f26d 4262 if (s->restart_usec > 0)
868f7d36 4263 log_unit_debug(UNIT(s),
be1adc27 4264 "Service restart interval %s expired, scheduling restart.",
5171356e 4265 FORMAT_TIMESPAN(service_restart_usec_next(s), USEC_PER_SEC));
5291f26d 4266 else
868f7d36
ZJS
4267 log_unit_debug(UNIT(s),
4268 "Service has no hold-off time (RestartSec=0), scheduling restart.");
5ce6e7f5 4269
034c6ed7
LP
4270 service_enter_restart(s);
4271 break;
4272
4c2f5842
LP
4273 case SERVICE_CLEANING:
4274 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
4275
4276 if (s->clean_result == SERVICE_SUCCESS)
4277 s->clean_result = SERVICE_FAILURE_TIMEOUT;
4278
4279 service_enter_signal(s, SERVICE_FINAL_SIGKILL, 0);
4280 break;
4281
034c6ed7 4282 default:
04499a70 4283 assert_not_reached();
034c6ed7 4284 }
718db961
LP
4285
4286 return 0;
4287}
4288
4289static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
4290 Service *s = SERVICE(userdata);
2787d83c 4291 usec_t watchdog_usec;
718db961
LP
4292
4293 assert(s);
4294 assert(source == s->watchdog_event_source);
4295
2787d83c
M
4296 watchdog_usec = service_get_watchdog_usec(s);
4297
2a12e32e
JK
4298 if (UNIT(s)->manager->service_watchdogs) {
4299 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
5291f26d 4300 FORMAT_TIMESPAN(watchdog_usec, 1));
8bb2d17d 4301
c87700a1 4302 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
2a12e32e
JK
4303 } else
4304 log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
5291f26d 4305 FORMAT_TIMESPAN(watchdog_usec, 1));
842129f5 4306
718db961 4307 return 0;
5cb5a6ff
LP
4308}
4309
fcee2755 4310static bool service_notify_message_authorized(Service *s, pid_t pid, FDSet *fds) {
e3285237 4311 assert(s);
8c47c732 4312
19dff691
MY
4313 NotifyAccess notify_access = service_get_notify_access(s);
4314
4315 if (notify_access == NOTIFY_NONE) {
e3285237
LP
4316 log_unit_warning(UNIT(s), "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
4317 return false;
4318 }
4319
19dff691 4320 if (notify_access == NOTIFY_MAIN && pid != s->main_pid) {
336c6e46 4321 if (s->main_pid != 0)
e3285237 4322 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 4323 else
e3285237
LP
4324 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);
4325
4326 return false;
4327 }
4328
19dff691 4329 if (notify_access == NOTIFY_EXEC && pid != s->main_pid && pid != s->control_pid) {
6375bd20 4330 if (s->main_pid != 0 && s->control_pid != 0)
e3285237 4331 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
4332 pid, s->main_pid, s->control_pid);
4333 else if (s->main_pid != 0)
e3285237 4334 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 4335 else if (s->control_pid != 0)
e3285237 4336 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 4337 else
e3285237
LP
4338 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);
4339
4340 return false;
9711848f
LP
4341 }
4342
e3285237
LP
4343 return true;
4344}
4345
99b43caf
JK
4346static void service_force_watchdog(Service *s) {
4347 if (!UNIT(s)->manager->service_watchdogs)
4348 return;
4349
4350 log_unit_error(UNIT(s), "Watchdog request (last status: %s)!",
1da3cb81 4351 s->status_text ?: "<unset>");
99b43caf
JK
4352
4353 service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
4354}
4355
db256aab
LP
4356static void service_notify_message(
4357 Unit *u,
4358 const struct ucred *ucred,
fcee2755 4359 char * const *tags,
db256aab
LP
4360 FDSet *fds) {
4361
e3285237
LP
4362 Service *s = SERVICE(u);
4363 bool notify_dbus = false;
3bd28bf7 4364 usec_t monotonic_usec = USEC_INFINITY;
e3285237 4365 const char *e;
db256aab 4366 int r;
e3285237
LP
4367
4368 assert(u);
db256aab 4369 assert(ucred);
e3285237 4370
19dff691 4371 if (!service_notify_message_authorized(s, ucred->pid, fds))
e3285237
LP
4372 return;
4373
f1d34068 4374 if (DEBUG_LOGGING) {
9711848f
LP
4375 _cleanup_free_ char *cc = NULL;
4376
4377 cc = strv_join(tags, ", ");
db256aab 4378 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", ucred->pid, isempty(cc) ? "n/a" : cc);
9711848f 4379 }
c952c6ec 4380
8c47c732 4381 /* Interpret MAINPID= */
28849dba 4382 e = strv_find_startswith(tags, "MAINPID=");
3bd28bf7 4383 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY)) {
db256aab
LP
4384 pid_t new_main_pid;
4385
4386 if (parse_pid(e, &new_main_pid) < 0)
4387 log_unit_warning(u, "Failed to parse MAINPID= field in notification message, ignoring: %s", e);
4388 else if (!s->main_pid_known || new_main_pid != s->main_pid) {
4389
4390 r = service_is_suitable_main_pid(s, new_main_pid, LOG_WARNING);
4391 if (r == 0) {
5238e957 4392 /* The new main PID is a bit suspicious, which is OK if the sender is privileged. */
db256aab
LP
4393
4394 if (ucred->uid == 0) {
4395 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);
4396 r = 1;
4397 } else
4398 log_unit_debug(u, "New main PID "PID_FMT" does not belong to service, refusing.", new_main_pid);
4399 }
4400 if (r > 0) {
5c95eb28 4401 (void) service_set_main_pid(s, new_main_pid);
cdc2af3e 4402
f75f613d 4403 r = unit_watch_pid(UNIT(s), new_main_pid, false);
cdc2af3e
LP
4404 if (r < 0)
4405 log_unit_warning_errno(UNIT(s), r, "Failed to watch new main PID "PID_FMT" for service: %m", new_main_pid);
4406
db256aab
LP
4407 notify_dbus = true;
4408 }
8c47c732
LP
4409 }
4410 }
4411
3bd28bf7
LP
4412 /* Parse MONOTONIC_USEC= */
4413 e = strv_find_startswith(tags, "MONOTONIC_USEC=");
4414 if (e) {
4415 r = safe_atou64(e, &monotonic_usec);
4416 if (r < 0)
4417 log_unit_warning_errno(u, r, "Failed to parse MONOTONIC_USEC= field in notification message, ignoring: %s", e);
4418 }
308d72dc 4419
3bd28bf7
LP
4420 /* Interpret READY=/STOPPING=/RELOADING=. STOPPING= wins over the others, and READY= over RELOADING= */
4421 if (strv_contains(tags, "STOPPING=1")) {
4422 s->notify_state = NOTIFY_STOPPING;
308d72dc 4423
3bd28bf7
LP
4424 if (IN_SET(s->state, SERVICE_RUNNING, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY))
4425 service_enter_stop_by_notify(s);
308d72dc 4426
3bd28bf7 4427 notify_dbus = true;
308d72dc 4428
3bd28bf7 4429 } else if (strv_contains(tags, "READY=1")) {
308d72dc 4430
3bd28bf7 4431 s->notify_state = NOTIFY_READY;
308d72dc 4432
3bd28bf7
LP
4433 /* Type=notify services inform us about completed initialization with READY=1 */
4434 if (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) &&
4435 s->state == SERVICE_START)
4436 service_enter_start_post(s);
308d72dc 4437
3bd28bf7
LP
4438 /* Sending READY=1 while we are reloading informs us that the reloading is complete. */
4439 if (s->state == SERVICE_RELOAD_NOTIFY)
4440 service_enter_running(s, SERVICE_SUCCESS);
308d72dc 4441
3bd28bf7
LP
4442 /* Combined RELOADING=1 and READY=1? Then this is indication that the service started and
4443 * immediately finished reloading. */
4444 if (s->state == SERVICE_RELOAD_SIGNAL &&
4445 strv_contains(tags, "RELOADING=1") &&
4446 monotonic_usec != USEC_INFINITY &&
4447 monotonic_usec >= s->reload_begin_usec) {
4448 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
308d72dc 4449
3bd28bf7
LP
4450 /* Propagate a reload explicitly */
4451 r = manager_propagate_reload(UNIT(s)->manager, UNIT(s), JOB_FAIL, &error);
4452 if (r < 0)
4453 log_unit_warning(UNIT(s), "Failed to schedule propagation of reload, ignoring: %s", bus_error_message(&error, r));
308d72dc 4454
3bd28bf7 4455 service_enter_running(s, SERVICE_SUCCESS);
cc2b7b11 4456 }
3bd28bf7
LP
4457
4458 notify_dbus = true;
4459
4460 } else if (strv_contains(tags, "RELOADING=1")) {
4461
4462 s->notify_state = NOTIFY_RELOADING;
4463
4464 /* Sending RELOADING=1 after we send SIGHUP to request a reload will transition
4465 * things to "reload-notify" state, where we'll wait for READY=1 to let us know the
4466 * reload is done. Note that we insist on a timestamp being sent along here, so that
4467 * we know for sure this is a reload cycle initiated *after* we sent the signal */
4468 if (s->state == SERVICE_RELOAD_SIGNAL &&
4469 monotonic_usec != USEC_INFINITY &&
4470 monotonic_usec >= s->reload_begin_usec)
4471 /* Note, we don't call service_enter_reload_by_notify() here, because we
4472 * don't need reload propagation nor do we want to restart the time-out. */
4473 service_set_state(s, SERVICE_RELOAD_NOTIFY);
4474
4475 if (s->state == SERVICE_RUNNING)
4476 service_enter_reload_by_notify(s);
4477
4478 notify_dbus = true;
8c47c732
LP
4479 }
4480
4481 /* Interpret STATUS= */
28849dba 4482 e = strv_find_startswith(tags, "STATUS=");
7f110ff9 4483 if (e) {
28849dba 4484 _cleanup_free_ char *t = NULL;
8c47c732 4485
28849dba 4486 if (!isempty(e)) {
3eac1bca
LP
4487 /* Note that this size limit check is mostly paranoia: since the datagram size we are willing
4488 * to process is already limited to NOTIFY_BUFFER_MAX, this limit here should never be hit. */
4489 if (strlen(e) > STATUS_TEXT_MAX)
4490 log_unit_warning(u, "Status message overly long (%zu > %u), ignoring.", strlen(e), STATUS_TEXT_MAX);
4491 else if (!utf8_is_valid(e))
4492 log_unit_warning(u, "Status message in notification message is not UTF-8 clean, ignoring.");
28849dba 4493 else {
28849dba
LP
4494 t = strdup(e);
4495 if (!t)
4496 log_oom();
3a2776bc 4497 }
28849dba 4498 }
8c47c732 4499
30b5275a 4500 if (!streq_ptr(s->status_text, t)) {
3b319885 4501 free_and_replace(s->status_text, t);
30b5275a 4502 notify_dbus = true;
28849dba 4503 }
8c47c732 4504 }
842129f5 4505
19dff691
MY
4506 /* Interpret NOTIFYACCESS= */
4507 e = strv_find_startswith(tags, "NOTIFYACCESS=");
4508 if (e) {
4509 NotifyAccess notify_access;
4510
4511 notify_access = notify_access_from_string(e);
4512 if (notify_access < 0)
4513 log_unit_warning_errno(u, notify_access,
4514 "Failed to parse NOTIFYACCESS= field value '%s' in notification message, ignoring: %m", e);
4515
4516 /* We don't need to check whether the new access mode is more strict than what is
4517 * already in use, since only the privileged process is allowed to change it
4518 * in the first place. */
4519 if (service_get_notify_access(s) != notify_access) {
4520 service_override_notify_access(s, notify_access);
4521 notify_dbus = true;
4522 }
4523 }
4524
4774e357 4525 /* Interpret ERRNO= */
28849dba 4526 e = strv_find_startswith(tags, "ERRNO=");
4774e357
MAA
4527 if (e) {
4528 int status_errno;
4529
2fa40742
LP
4530 status_errno = parse_errno(e);
4531 if (status_errno < 0)
4532 log_unit_warning_errno(u, status_errno,
5e1ee764 4533 "Failed to parse ERRNO= field value '%s' in notification message: %m", e);
2fa40742
LP
4534 else if (s->status_errno != status_errno) {
4535 s->status_errno = status_errno;
4536 notify_dbus = true;
4774e357
MAA
4537 }
4538 }
4539
a327431b
DB
4540 /* Interpret EXTEND_TIMEOUT= */
4541 e = strv_find_startswith(tags, "EXTEND_TIMEOUT_USEC=");
4542 if (e) {
4543 usec_t extend_timeout_usec;
4544 if (safe_atou64(e, &extend_timeout_usec) < 0)
4545 log_unit_warning(u, "Failed to parse EXTEND_TIMEOUT_USEC=%s", e);
4546 else
4547 service_extend_timeout(s, extend_timeout_usec);
4548 }
4549
6f285378 4550 /* Interpret WATCHDOG= */
99b43caf
JK
4551 e = strv_find_startswith(tags, "WATCHDOG=");
4552 if (e) {
4553 if (streq(e, "1"))
4554 service_reset_watchdog(s);
4555 else if (streq(e, "trigger"))
4556 service_force_watchdog(s);
4557 else
4558 log_unit_warning(u, "Passed WATCHDOG= field is invalid, ignoring.");
4559 }
c4e2ceae 4560
c45d11cb
LP
4561 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
4562 if (e) {
4563 usec_t watchdog_override_usec;
4564 if (safe_atou64(e, &watchdog_override_usec) < 0)
4565 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
4566 else
95d0d8ed 4567 service_override_watchdog_timeout(s, watchdog_override_usec);
c45d11cb
LP
4568 }
4569
e78ee06d
LP
4570 /* Process FD store messages. Either FDSTOREREMOVE=1 for removal, or FDSTORE=1 for addition. In both cases,
4571 * process FDNAME= for picking the file descriptor name to use. Note that FDNAME= is required when removing
4572 * fds, but optional when pushing in new fds, for compatibility reasons. */
d29cc4d6 4573 if (strv_contains(tags, "FDSTOREREMOVE=1")) {
e78ee06d
LP
4574 const char *name;
4575
4576 name = strv_find_startswith(tags, "FDNAME=");
4577 if (!name || !fdname_is_valid(name))
4578 log_unit_warning(u, "FDSTOREREMOVE=1 requested, but no valid file descriptor name passed, ignoring.");
4579 else
4580 service_remove_fd_store(s, name);
4581
d29cc4d6 4582 } else if (strv_contains(tags, "FDSTORE=1")) {
8dd4c05b
LP
4583 const char *name;
4584
4585 name = strv_find_startswith(tags, "FDNAME=");
4586 if (name && !fdname_is_valid(name)) {
4587 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
4588 name = NULL;
4589 }
4590
cb5a46b8 4591 (void) service_add_fd_store_set(s, fds, name, !strv_contains(tags, "FDPOLL=0"));
8dd4c05b 4592 }
a354329f 4593
c4e2ceae 4594 /* Notify clients about changed status or main pid */
30b5275a
LP
4595 if (notify_dbus)
4596 unit_add_to_dbus_queue(u);
8c47c732
LP
4597}
4598
7a7821c8 4599static int service_get_timeout(Unit *u, usec_t *timeout) {
68db7a3b 4600 Service *s = SERVICE(u);
7a7821c8 4601 uint64_t t;
68db7a3b
ZJS
4602 int r;
4603
4604 if (!s->timer_event_source)
4605 return 0;
4606
7a7821c8 4607 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
4608 if (r < 0)
4609 return r;
7a7821c8
LP
4610 if (t == USEC_INFINITY)
4611 return 0;
68db7a3b 4612
7a7821c8 4613 *timeout = t;
68db7a3b
ZJS
4614 return 1;
4615}
4616
e39eb045
LP
4617static bool pick_up_pid_from_bus_name(Service *s) {
4618 assert(s);
4619
4620 /* If the service is running but we have no main PID yet, get it from the owner of the D-Bus name */
4621
4622 return !pid_is_valid(s->main_pid) &&
4623 IN_SET(s->state,
4624 SERVICE_START,
4625 SERVICE_START_POST,
4626 SERVICE_RUNNING,
3bd28bf7
LP
4627 SERVICE_RELOAD,
4628 SERVICE_RELOAD_SIGNAL,
4629 SERVICE_RELOAD_NOTIFY);
e39eb045
LP
4630}
4631
4632static int bus_name_pid_lookup_callback(sd_bus_message *reply, void *userdata, sd_bus_error *ret_error) {
4633 const sd_bus_error *e;
99534007 4634 Unit *u = ASSERT_PTR(userdata);
e39eb045
LP
4635 uint32_t pid;
4636 Service *s;
4637 int r;
4638
4639 assert(reply);
e39eb045
LP
4640
4641 s = SERVICE(u);
4642 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4643
4644 if (!s->bus_name || !pick_up_pid_from_bus_name(s))
4645 return 1;
4646
4647 e = sd_bus_message_get_error(reply);
4648 if (e) {
4649 r = sd_bus_error_get_errno(e);
4650 log_warning_errno(r, "GetConnectionUnixProcessID() failed: %s", bus_error_message(e, r));
4651 return 1;
4652 }
4653
4654 r = sd_bus_message_read(reply, "u", &pid);
4655 if (r < 0) {
4656 bus_log_parse_error(r);
4657 return 1;
4658 }
4659
4660 if (!pid_is_valid(pid)) {
4661 log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "GetConnectionUnixProcessID() returned invalid PID");
4662 return 1;
4663 }
4664
4665 log_unit_debug(u, "D-Bus name %s is now owned by process " PID_FMT, s->bus_name, (pid_t) pid);
4666
5c95eb28
SS
4667 (void) service_set_main_pid(s, pid);
4668 (void) unit_watch_pid(UNIT(s), pid, false);
e39eb045
LP
4669 return 1;
4670}
4671
fc67a943 4672static void service_bus_name_owner_change(Unit *u, const char *new_owner) {
05e343b7
LP
4673
4674 Service *s = SERVICE(u);
718db961 4675 int r;
05e343b7
LP
4676
4677 assert(s);
05e343b7 4678
fc67a943
LP
4679 if (new_owner)
4680 log_unit_debug(u, "D-Bus name %s now owned by %s", s->bus_name, new_owner);
05e343b7 4681 else
fc67a943 4682 log_unit_debug(u, "D-Bus name %s now not owned by anyone.", s->bus_name);
05e343b7 4683
d7a0f1f4 4684 s->bus_name_good = new_owner;
05e343b7 4685
d8ccf5fd
DM
4686 /* Track the current owner, so we can reconstruct changes after a daemon reload */
4687 r = free_and_strdup(&s->bus_name_owner, new_owner);
4688 if (r < 0) {
4689 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
4690 return;
4691 }
4692
05e343b7
LP
4693 if (s->type == SERVICE_DBUS) {
4694
4695 /* service_enter_running() will figure out what to
4696 * do */
4697 if (s->state == SERVICE_RUNNING)
f42806df 4698 service_enter_running(s, SERVICE_SUCCESS);
05e343b7
LP
4699 else if (s->state == SERVICE_START && new_owner)
4700 service_enter_start_post(s);
4701
e39eb045 4702 } else if (new_owner && pick_up_pid_from_bus_name(s)) {
05e343b7 4703
718db961 4704 /* Try to acquire PID from bus service */
05e343b7 4705
e39eb045
LP
4706 s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
4707
4708 r = sd_bus_call_method_async(
4709 u->manager->api_bus,
4710 &s->bus_name_pid_lookup_slot,
4711 "org.freedesktop.DBus",
4712 "/org/freedesktop/DBus",
4713 "org.freedesktop.DBus",
4714 "GetConnectionUnixProcessID",
4715 bus_name_pid_lookup_callback,
4716 s,
4717 "s",
4718 s->bus_name);
4719 if (r < 0)
4720 log_debug_errno(r, "Failed to request owner PID of service name, ignoring: %m");
7400b9d2 4721 }
05e343b7
LP
4722}
4723
3fabebf4
LP
4724int service_set_socket_fd(
4725 Service *s,
4726 int fd,
4727 Socket *sock,
4728 SocketPeer *peer,
4729 bool selinux_context_net) {
4730
4731 _cleanup_free_ char *peer_text = NULL;
79a98c60 4732 int r;
57020a3a 4733
4f2d528d
LP
4734 assert(s);
4735 assert(fd >= 0);
4736
7f2fbbff
LP
4737 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
4738 * to be configured. We take ownership of the passed fd on success. */
4f2d528d 4739
1124fe6f 4740 if (UNIT(s)->load_state != UNIT_LOADED)
4f2d528d
LP
4741 return -EINVAL;
4742
4743 if (s->socket_fd >= 0)
4744 return -EBUSY;
4745
3fabebf4
LP
4746 assert(!s->socket_peer);
4747
b9c1883a 4748 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4f2d528d
LP
4749 return -EAGAIN;
4750
3fabebf4 4751 if (getpeername_pretty(fd, true, &peer_text) >= 0) {
79a98c60
LP
4752
4753 if (UNIT(s)->description) {
c2b2df60 4754 _cleanup_free_ char *a = NULL;
79a98c60 4755
3fabebf4 4756 a = strjoin(UNIT(s)->description, " (", peer_text, ")");
79a98c60
LP
4757 if (!a)
4758 return -ENOMEM;
4759
4760 r = unit_set_description(UNIT(s), a);
4761 } else
3fabebf4 4762 r = unit_set_description(UNIT(s), peer_text);
79a98c60
LP
4763 if (r < 0)
4764 return r;
4765 }
4766
eef85c4a 4767 r = unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false, UNIT_DEPENDENCY_IMPLICIT);
7f2fbbff
LP
4768 if (r < 0)
4769 return r;
4770
4f2d528d 4771 s->socket_fd = fd;
3fabebf4 4772 s->socket_peer = socket_peer_ref(peer);
16115b0a 4773 s->socket_fd_selinux_context_net = selinux_context_net;
6cf6bbc2 4774
7f7d01ed 4775 unit_ref_set(&s->accept_socket, UNIT(s), UNIT(sock));
7f2fbbff 4776 return 0;
4f2d528d
LP
4777}
4778
fdf20a31 4779static void service_reset_failed(Unit *u) {
5632e374
LP
4780 Service *s = SERVICE(u);
4781
4782 assert(s);
4783
fdf20a31 4784 if (s->state == SERVICE_FAILED)
b9c1883a 4785 service_set_state(s, service_determine_dead_state(s));
5632e374 4786
f42806df
LP
4787 s->result = SERVICE_SUCCESS;
4788 s->reload_result = SERVICE_SUCCESS;
4c2f5842 4789 s->clean_result = SERVICE_SUCCESS;
7a0019d3
LP
4790 s->n_restarts = 0;
4791 s->flush_n_restarts = false;
5632e374
LP
4792}
4793
a721cd00 4794static int service_kill(Unit *u, KillWho who, int signo, int code, int value, sd_bus_error *error) {
8a0867d6 4795 Service *s = SERVICE(u);
41efeaec 4796
a6951a50
LP
4797 assert(s);
4798
a721cd00 4799 return unit_kill_common(u, who, signo, code, value, s->main_pid, s->control_pid, error);
8a0867d6
LP
4800}
4801
291d565a
LP
4802static int service_main_pid(Unit *u) {
4803 Service *s = SERVICE(u);
4804
4805 assert(s);
4806
4807 return s->main_pid;
4808}
4809
4810static int service_control_pid(Unit *u) {
4811 Service *s = SERVICE(u);
4812
4813 assert(s);
4814
4815 return s->control_pid;
4816}
4817
bb2c7685
LP
4818static bool service_needs_console(Unit *u) {
4819 Service *s = SERVICE(u);
4820
4821 assert(s);
4822
4823 /* We provide our own implementation of this here, instead of relying of the generic implementation
4824 * unit_needs_console() provides, since we want to return false if we are in SERVICE_EXITED state. */
4825
4826 if (!exec_context_may_touch_console(&s->exec_context))
4827 return false;
4828
4829 return IN_SET(s->state,
31cd5f63 4830 SERVICE_CONDITION,
bb2c7685
LP
4831 SERVICE_START_PRE,
4832 SERVICE_START,
4833 SERVICE_START_POST,
4834 SERVICE_RUNNING,
4835 SERVICE_RELOAD,
3bd28bf7
LP
4836 SERVICE_RELOAD_SIGNAL,
4837 SERVICE_RELOAD_NOTIFY,
bb2c7685 4838 SERVICE_STOP,
c87700a1 4839 SERVICE_STOP_WATCHDOG,
bb2c7685
LP
4840 SERVICE_STOP_SIGTERM,
4841 SERVICE_STOP_SIGKILL,
4842 SERVICE_STOP_POST,
bf760801 4843 SERVICE_FINAL_WATCHDOG,
bb2c7685
LP
4844 SERVICE_FINAL_SIGTERM,
4845 SERVICE_FINAL_SIGKILL);
4846}
4847
7af67e9a
LP
4848static int service_exit_status(Unit *u) {
4849 Service *s = SERVICE(u);
4850
4851 assert(u);
4852
4853 if (s->main_exec_status.pid <= 0 ||
4854 !dual_timestamp_is_set(&s->main_exec_status.exit_timestamp))
4855 return -ENODATA;
4856
4857 if (s->main_exec_status.code != CLD_EXITED)
4858 return -EBADE;
4859
4860 return s->main_exec_status.status;
4861}
4862
5e1669ff
ZJS
4863static const char* service_status_text(Unit *u) {
4864 Service *s = SERVICE(u);
4865
4866 assert(s);
4867
4868 return s->status_text;
4869}
4870
4c2f5842
LP
4871static int service_clean(Unit *u, ExecCleanMask mask) {
4872 _cleanup_strv_free_ char **l = NULL;
4fb8f1e8 4873 bool may_clean_fdstore = false;
4c2f5842 4874 Service *s = SERVICE(u);
4c2f5842
LP
4875 int r;
4876
4877 assert(s);
4878 assert(mask != 0);
4879
4fb8f1e8 4880 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED))
4c2f5842
LP
4881 return -EBUSY;
4882
4fb8f1e8 4883 /* Determine if there's anything we could potentially clean */
4c2f5842
LP
4884 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
4885 if (r < 0)
4886 return r;
4887
4fb8f1e8
LP
4888 if (mask & EXEC_CLEAN_FDSTORE)
4889 may_clean_fdstore = s->n_fd_store > 0 || s->n_fd_store_max > 0;
4890
4891 if (strv_isempty(l) && !may_clean_fdstore)
4892 return -EUNATCH; /* Nothing to potentially clean */
4893
4894 /* Let's clean the stuff we can clean quickly */
4895 if (may_clean_fdstore)
4896 service_release_fd_store(s);
4897
4898 /* If we are done, leave quickly */
4899 if (strv_isempty(l)) {
4900 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
4901 service_set_state(s, SERVICE_DEAD);
4902 return 0;
4903 }
4c2f5842 4904
4fb8f1e8 4905 /* We need to clean disk stuff. This is slow, hence do it out of process, and change state */
4c2f5842
LP
4906 service_unwatch_control_pid(s);
4907 s->clean_result = SERVICE_SUCCESS;
4908 s->control_command = NULL;
4909 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
4910
e5d6dcce 4911 r = service_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
4c2f5842
LP
4912 if (r < 0)
4913 goto fail;
4914
810ef318 4915 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
4c2f5842
LP
4916 if (r < 0)
4917 goto fail;
4918
4c2f5842
LP
4919 service_set_state(s, SERVICE_CLEANING);
4920
4921 return 0;
4922
4923fail:
810ef318 4924 log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
4c2f5842 4925 s->clean_result = SERVICE_FAILURE_RESOURCES;
5dcadb4c 4926 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
4c2f5842
LP
4927 return r;
4928}
4929
4930static int service_can_clean(Unit *u, ExecCleanMask *ret) {
4931 Service *s = SERVICE(u);
4fb8f1e8
LP
4932 ExecCleanMask mask = 0;
4933 int r;
4c2f5842
LP
4934
4935 assert(s);
4fb8f1e8
LP
4936 assert(ret);
4937
4938 r = exec_context_get_clean_mask(&s->exec_context, &mask);
4939 if (r < 0)
4940 return r;
4c2f5842 4941
4fb8f1e8
LP
4942 if (s->n_fd_store_max > 0)
4943 mask |= EXEC_CLEAN_FDSTORE;
4944
4945 *ret = mask;
4946 return 0;
4c2f5842
LP
4947}
4948
eda0cbf0 4949static const char *service_finished_job(Unit *u, JobType t, JobResult result) {
04d232d8
ZJS
4950 if (t == JOB_START &&
4951 result == JOB_DONE &&
4952 SERVICE(u)->type == SERVICE_ONESHOT)
4953 return "Finished %s.";
eda0cbf0
ZJS
4954
4955 /* Fall back to generic */
4956 return NULL;
4957}
4958
705578c3 4959static int service_can_start(Unit *u) {
9727f242
DDM
4960 Service *s = SERVICE(u);
4961 int r;
4962
4963 assert(s);
4964
4965 /* Make sure we don't enter a busy loop of some kind. */
4966 r = unit_test_start_limit(u);
4967 if (r < 0) {
4968 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
4969 return r;
4970 }
4971
705578c3 4972 return 1;
9727f242
DDM
4973}
4974
c25fac9a
LP
4975static void service_release_resources(Unit *u) {
4976 Service *s = SERVICE(ASSERT_PTR(u));
4977
4978 /* Invoked by the unit state engine, whenever it realizes that unit is dead and there's no job
4979 * anymore for it, and it hence is a good idea to release resources */
4980
4981 /* Don't release resources if this is a transitionary failed/dead state
4982 * (i.e. SERVICE_DEAD_BEFORE_AUTO_RESTART/SERVICE_FAILED_BEFORE_AUTO_RESTART), insist on a permanent
4983 * failure state. */
b9c1883a 4984 if (!IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_DEAD_RESOURCES_PINNED))
c25fac9a
LP
4985 return;
4986
4987 log_unit_debug(u, "Releasing resources...");
4988
81a1d6d6 4989 service_release_socket_fd(s);
c25fac9a 4990 service_release_stdio_fd(s);
b9c1883a
LP
4991
4992 if (s->fd_store_preserve_mode != EXEC_PRESERVE_YES)
4993 service_release_fd_store(s);
4994
4995 if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !s->fd_store)
4996 service_set_state(s, SERVICE_DEAD);
c25fac9a
LP
4997}
4998
94f04347 4999static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
48d83e33
ZJS
5000 [SERVICE_RESTART_NO] = "no",
5001 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
5002 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
6cfe2fde 5003 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
dc99a976 5004 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
48d83e33
ZJS
5005 [SERVICE_RESTART_ON_ABORT] = "on-abort",
5006 [SERVICE_RESTART_ALWAYS] = "always",
94f04347
LP
5007};
5008
5009DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
5010
5011static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3bd28bf7
LP
5012 [SERVICE_SIMPLE] = "simple",
5013 [SERVICE_FORKING] = "forking",
5014 [SERVICE_ONESHOT] = "oneshot",
5015 [SERVICE_DBUS] = "dbus",
5016 [SERVICE_NOTIFY] = "notify",
5017 [SERVICE_NOTIFY_RELOAD] = "notify-reload",
5018 [SERVICE_IDLE] = "idle",
5019 [SERVICE_EXEC] = "exec",
94f04347
LP
5020};
5021
5022DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
5023
596e4470 5024static const char* const service_exit_type_table[_SERVICE_EXIT_TYPE_MAX] = {
fb138166 5025 [SERVICE_EXIT_MAIN] = "main",
596e4470
HC
5026 [SERVICE_EXIT_CGROUP] = "cgroup",
5027};
5028
5029DEFINE_STRING_TABLE_LOOKUP(service_exit_type, ServiceExitType);
5030
e537352b 5031static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5032 [SERVICE_EXEC_CONDITION] = "ExecCondition",
5033 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
5034 [SERVICE_EXEC_START] = "ExecStart",
94f04347 5035 [SERVICE_EXEC_START_POST] = "ExecStartPost",
48d83e33
ZJS
5036 [SERVICE_EXEC_RELOAD] = "ExecReload",
5037 [SERVICE_EXEC_STOP] = "ExecStop",
5038 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
94f04347
LP
5039};
5040
5041DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
5042
b3d59367 5043static const char* const service_exec_ex_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
48d83e33
ZJS
5044 [SERVICE_EXEC_CONDITION] = "ExecConditionEx",
5045 [SERVICE_EXEC_START_PRE] = "ExecStartPreEx",
5046 [SERVICE_EXEC_START] = "ExecStartEx",
b3d59367 5047 [SERVICE_EXEC_START_POST] = "ExecStartPostEx",
48d83e33
ZJS
5048 [SERVICE_EXEC_RELOAD] = "ExecReloadEx",
5049 [SERVICE_EXEC_STOP] = "ExecStopEx",
5050 [SERVICE_EXEC_STOP_POST] = "ExecStopPostEx",
b3d59367
AZ
5051};
5052
5053DEFINE_STRING_TABLE_LOOKUP(service_exec_ex_command, ServiceExecCommand);
5054
308d72dc 5055static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
48d83e33
ZJS
5056 [NOTIFY_UNKNOWN] = "unknown",
5057 [NOTIFY_READY] = "ready",
308d72dc 5058 [NOTIFY_RELOADING] = "reloading",
48d83e33 5059 [NOTIFY_STOPPING] = "stopping",
308d72dc
LP
5060};
5061
5062DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
5063
f42806df 5064static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
48d83e33
ZJS
5065 [SERVICE_SUCCESS] = "success",
5066 [SERVICE_FAILURE_RESOURCES] = "resources",
5067 [SERVICE_FAILURE_PROTOCOL] = "protocol",
5068 [SERVICE_FAILURE_TIMEOUT] = "timeout",
5069 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
5070 [SERVICE_FAILURE_SIGNAL] = "signal",
5071 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
5072 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
07299350 5073 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
48d83e33
ZJS
5074 [SERVICE_FAILURE_OOM_KILL] = "oom-kill",
5075 [SERVICE_SKIP_CONDITION] = "exec-condition",
f42806df
LP
5076};
5077
5078DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
5079
bf760801
JK
5080static const char* const service_timeout_failure_mode_table[_SERVICE_TIMEOUT_FAILURE_MODE_MAX] = {
5081 [SERVICE_TIMEOUT_TERMINATE] = "terminate",
48d83e33
ZJS
5082 [SERVICE_TIMEOUT_ABORT] = "abort",
5083 [SERVICE_TIMEOUT_KILL] = "kill",
bf760801
JK
5084};
5085
5086DEFINE_STRING_TABLE_LOOKUP(service_timeout_failure_mode, ServiceTimeoutFailureMode);
5087
87f0e418 5088const UnitVTable service_vtable = {
7d17cfbc 5089 .object_size = sizeof(Service),
718db961
LP
5090 .exec_context_offset = offsetof(Service, exec_context),
5091 .cgroup_context_offset = offsetof(Service, cgroup_context),
5092 .kill_context_offset = offsetof(Service, kill_context),
613b411c 5093 .exec_runtime_offset = offsetof(Service, exec_runtime),
3ef63c31 5094
f975e971
LP
5095 .sections =
5096 "Unit\0"
5097 "Service\0"
5098 "Install\0",
4ad49000 5099 .private_section = "Service",
71645aca 5100
1d9cc876
LP
5101 .can_transient = true,
5102 .can_delegate = true,
c80a9a33 5103 .can_fail = true,
4d824a4e 5104 .can_set_managed_oom = true,
1d9cc876 5105
034c6ed7
LP
5106 .init = service_init,
5107 .done = service_done,
a16e1123 5108 .load = service_load,
a354329f 5109 .release_resources = service_release_resources,
a16e1123
LP
5110
5111 .coldplug = service_coldplug,
034c6ed7 5112
5cb5a6ff
LP
5113 .dump = service_dump,
5114
5115 .start = service_start,
5116 .stop = service_stop,
5117 .reload = service_reload,
5118
034c6ed7
LP
5119 .can_reload = service_can_reload,
5120
8a0867d6 5121 .kill = service_kill,
4c2f5842
LP
5122 .clean = service_clean,
5123 .can_clean = service_can_clean,
8a0867d6 5124
d9e45bc3
MS
5125 .freeze = unit_freeze_vtable_common,
5126 .thaw = unit_thaw_vtable_common,
5127
a16e1123
LP
5128 .serialize = service_serialize,
5129 .deserialize_item = service_deserialize_item,
5130
5cb5a6ff 5131 .active_state = service_active_state,
10a94420 5132 .sub_state_to_string = service_sub_state_to_string,
5cb5a6ff 5133
deb4e708
MK
5134 .will_restart = service_will_restart,
5135
f2f725e5 5136 .may_gc = service_may_gc,
701cc384 5137
034c6ed7 5138 .sigchld_event = service_sigchld_event,
2c4104f0 5139
fdf20a31 5140 .reset_failed = service_reset_failed,
5632e374 5141
4ad49000 5142 .notify_cgroup_empty = service_notify_cgroup_empty_event,
afcfaa69 5143 .notify_cgroup_oom = service_notify_cgroup_oom_event,
8c47c732 5144 .notify_message = service_notify_message,
8e274523 5145
291d565a
LP
5146 .main_pid = service_main_pid,
5147 .control_pid = service_control_pid,
5148
05e343b7 5149 .bus_name_owner_change = service_bus_name_owner_change,
05e343b7 5150
74c964d3
LP
5151 .bus_set_property = bus_service_set_property,
5152 .bus_commit_properties = bus_service_commit_properties,
4139c1b2 5153
68db7a3b 5154 .get_timeout = service_get_timeout,
bb2c7685 5155 .needs_console = service_needs_console,
7af67e9a 5156 .exit_status = service_exit_status,
5e1669ff 5157 .status_text = service_status_text,
718db961 5158
c6918296 5159 .status_message_formats = {
c6918296 5160 .finished_start_job = {
c6918296 5161 [JOB_FAILED] = "Failed to start %s.",
c6918296
MS
5162 },
5163 .finished_stop_job = {
5164 [JOB_DONE] = "Stopped %s.",
5165 [JOB_FAILED] = "Stopped (with error) %s.",
c6918296 5166 },
eda0cbf0 5167 .finished_job = service_finished_job,
c6918296 5168 },
9727f242 5169
705578c3 5170 .can_start = service_can_start,
5cb5a6ff 5171};