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