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