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