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