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