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