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