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