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