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