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