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