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