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