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