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