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