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