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