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