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