]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
service: only fail notify services on empty cgroup during start
[thirdparty/systemd.git] / src / core / service.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <signal.h>
22 #include <unistd.h>
23
24 #include "alloc-util.h"
25 #include "async.h"
26 #include "bus-error.h"
27 #include "bus-kernel.h"
28 #include "bus-util.h"
29 #include "dbus-service.h"
30 #include "def.h"
31 #include "env-util.h"
32 #include "escape.h"
33 #include "exit-status.h"
34 #include "fd-util.h"
35 #include "fileio.h"
36 #include "format-util.h"
37 #include "fs-util.h"
38 #include "load-dropin.h"
39 #include "load-fragment.h"
40 #include "log.h"
41 #include "manager.h"
42 #include "parse-util.h"
43 #include "path-util.h"
44 #include "process-util.h"
45 #include "service.h"
46 #include "signal-util.h"
47 #include "special.h"
48 #include "string-table.h"
49 #include "string-util.h"
50 #include "strv.h"
51 #include "unit-name.h"
52 #include "unit-printf.h"
53 #include "unit.h"
54 #include "utf8.h"
55 #include "util.h"
56
57 static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
58 [SERVICE_DEAD] = UNIT_INACTIVE,
59 [SERVICE_START_PRE] = UNIT_ACTIVATING,
60 [SERVICE_START] = UNIT_ACTIVATING,
61 [SERVICE_START_POST] = UNIT_ACTIVATING,
62 [SERVICE_RUNNING] = UNIT_ACTIVE,
63 [SERVICE_EXITED] = UNIT_ACTIVE,
64 [SERVICE_RELOAD] = UNIT_RELOADING,
65 [SERVICE_STOP] = UNIT_DEACTIVATING,
66 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
67 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
68 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
69 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
70 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
71 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
72 [SERVICE_FAILED] = UNIT_FAILED,
73 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
74 };
75
76 /* For Type=idle we never want to delay any other jobs, hence we
77 * consider idle jobs active as soon as we start working on them */
78 static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
79 [SERVICE_DEAD] = UNIT_INACTIVE,
80 [SERVICE_START_PRE] = UNIT_ACTIVE,
81 [SERVICE_START] = UNIT_ACTIVE,
82 [SERVICE_START_POST] = UNIT_ACTIVE,
83 [SERVICE_RUNNING] = UNIT_ACTIVE,
84 [SERVICE_EXITED] = UNIT_ACTIVE,
85 [SERVICE_RELOAD] = UNIT_RELOADING,
86 [SERVICE_STOP] = UNIT_DEACTIVATING,
87 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
88 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
89 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
90 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
91 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
92 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
93 [SERVICE_FAILED] = UNIT_FAILED,
94 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
95 };
96
97 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
98 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
99 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
100
101 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
102 static void service_enter_reload_by_notify(Service *s);
103
104 static void service_init(Unit *u) {
105 Service *s = SERVICE(u);
106
107 assert(u);
108 assert(u->load_state == UNIT_STUB);
109
110 s->timeout_start_usec = u->manager->default_timeout_start_usec;
111 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
112 s->restart_usec = u->manager->default_restart_usec;
113 s->runtime_max_usec = USEC_INFINITY;
114 s->type = _SERVICE_TYPE_INVALID;
115 s->socket_fd = -1;
116 s->stdin_fd = s->stdout_fd = s->stderr_fd = -1;
117 s->guess_main_pid = true;
118
119 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
120 }
121
122 static void service_unwatch_control_pid(Service *s) {
123 assert(s);
124
125 if (s->control_pid <= 0)
126 return;
127
128 unit_unwatch_pid(UNIT(s), s->control_pid);
129 s->control_pid = 0;
130 }
131
132 static void service_unwatch_main_pid(Service *s) {
133 assert(s);
134
135 if (s->main_pid <= 0)
136 return;
137
138 unit_unwatch_pid(UNIT(s), s->main_pid);
139 s->main_pid = 0;
140 }
141
142 static void service_unwatch_pid_file(Service *s) {
143 if (!s->pid_file_pathspec)
144 return;
145
146 log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
147 path_spec_unwatch(s->pid_file_pathspec);
148 path_spec_done(s->pid_file_pathspec);
149 s->pid_file_pathspec = mfree(s->pid_file_pathspec);
150 }
151
152 static int service_set_main_pid(Service *s, pid_t pid) {
153 pid_t ppid;
154
155 assert(s);
156
157 if (pid <= 1)
158 return -EINVAL;
159
160 if (pid == getpid())
161 return -EINVAL;
162
163 if (s->main_pid == pid && s->main_pid_known)
164 return 0;
165
166 if (s->main_pid != pid) {
167 service_unwatch_main_pid(s);
168 exec_status_start(&s->main_exec_status, pid);
169 }
170
171 s->main_pid = pid;
172 s->main_pid_known = true;
173
174 if (get_process_ppid(pid, &ppid) >= 0 && ppid != getpid()) {
175 log_unit_warning(UNIT(s), "Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", pid);
176 s->main_pid_alien = true;
177 } else
178 s->main_pid_alien = false;
179
180 return 0;
181 }
182
183 void service_close_socket_fd(Service *s) {
184 assert(s);
185
186 /* Undo the effect of service_set_socket_fd(). */
187
188 s->socket_fd = asynchronous_close(s->socket_fd);
189
190 if (UNIT_ISSET(s->accept_socket)) {
191 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
192 unit_ref_unset(&s->accept_socket);
193 }
194 }
195
196 static void service_stop_watchdog(Service *s) {
197 assert(s);
198
199 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
200 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
201 }
202
203 static usec_t service_get_watchdog_usec(Service *s) {
204 assert(s);
205
206 if (s->watchdog_override_enable)
207 return s->watchdog_override_usec;
208 else
209 return s->watchdog_usec;
210 }
211
212 static void service_start_watchdog(Service *s) {
213 int r;
214 usec_t watchdog_usec;
215
216 assert(s);
217
218 watchdog_usec = service_get_watchdog_usec(s);
219 if (watchdog_usec == 0 || watchdog_usec == USEC_INFINITY)
220 return;
221
222 if (s->watchdog_event_source) {
223 r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
224 if (r < 0) {
225 log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
226 return;
227 }
228
229 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
230 } else {
231 r = sd_event_add_time(
232 UNIT(s)->manager->event,
233 &s->watchdog_event_source,
234 CLOCK_MONOTONIC,
235 usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
236 service_dispatch_watchdog, s);
237 if (r < 0) {
238 log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
239 return;
240 }
241
242 (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
243
244 /* Let's process everything else which might be a sign
245 * of living before we consider a service died. */
246 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
247 }
248
249 if (r < 0)
250 log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
251 }
252
253 static void service_reset_watchdog(Service *s) {
254 assert(s);
255
256 dual_timestamp_get(&s->watchdog_timestamp);
257 service_start_watchdog(s);
258 }
259
260 static void service_reset_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
261 assert(s);
262
263 s->watchdog_override_enable = true;
264 s->watchdog_override_usec = watchdog_override_usec;
265 service_reset_watchdog(s);
266
267 log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
268 log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
269 }
270
271 static void service_fd_store_unlink(ServiceFDStore *fs) {
272
273 if (!fs)
274 return;
275
276 if (fs->service) {
277 assert(fs->service->n_fd_store > 0);
278 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
279 fs->service->n_fd_store--;
280 }
281
282 if (fs->event_source) {
283 sd_event_source_set_enabled(fs->event_source, SD_EVENT_OFF);
284 sd_event_source_unref(fs->event_source);
285 }
286
287 free(fs->fdname);
288 safe_close(fs->fd);
289 free(fs);
290 }
291
292 static void service_release_fd_store(Service *s) {
293 assert(s);
294
295 log_unit_debug(UNIT(s), "Releasing all stored fds");
296 while (s->fd_store)
297 service_fd_store_unlink(s->fd_store);
298
299 assert(s->n_fd_store == 0);
300 }
301
302 static void service_release_resources(Unit *u, bool inactive) {
303 Service *s = SERVICE(u);
304
305 assert(s);
306
307 if (!s->fd_store && s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
308 return;
309
310 log_unit_debug(u, "Releasing resources.");
311
312 s->stdin_fd = safe_close(s->stdin_fd);
313 s->stdout_fd = safe_close(s->stdout_fd);
314 s->stderr_fd = safe_close(s->stderr_fd);
315
316 if (inactive)
317 service_release_fd_store(s);
318 }
319
320 static void service_done(Unit *u) {
321 Service *s = SERVICE(u);
322
323 assert(s);
324
325 s->pid_file = mfree(s->pid_file);
326 s->status_text = mfree(s->status_text);
327
328 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
329 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
330 s->control_command = NULL;
331 s->main_command = NULL;
332
333 dynamic_creds_unref(&s->dynamic_creds);
334
335 exit_status_set_free(&s->restart_prevent_status);
336 exit_status_set_free(&s->restart_force_status);
337 exit_status_set_free(&s->success_status);
338
339 /* This will leak a process, but at least no memory or any of
340 * our resources */
341 service_unwatch_main_pid(s);
342 service_unwatch_control_pid(s);
343 service_unwatch_pid_file(s);
344
345 if (s->bus_name) {
346 unit_unwatch_bus_name(u, s->bus_name);
347 s->bus_name = mfree(s->bus_name);
348 }
349
350 s->bus_name_owner = mfree(s->bus_name_owner);
351
352 service_close_socket_fd(s);
353 s->peer = socket_peer_unref(s->peer);
354
355 unit_ref_unset(&s->accept_socket);
356
357 service_stop_watchdog(s);
358
359 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
360
361 service_release_resources(u, true);
362 }
363
364 static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
365 ServiceFDStore *fs = userdata;
366
367 assert(e);
368 assert(fs);
369
370 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
371 log_unit_debug(UNIT(fs->service),
372 "Received %s on stored fd %d (%s), closing.",
373 revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
374 fs->fd, strna(fs->fdname));
375 service_fd_store_unlink(fs);
376 return 0;
377 }
378
379 static int service_add_fd_store(Service *s, int fd, const char *name) {
380 ServiceFDStore *fs;
381 int r;
382
383 /* fd is always consumed if we return >= 0 */
384
385 assert(s);
386 assert(fd >= 0);
387
388 if (s->n_fd_store >= s->n_fd_store_max)
389 return -EXFULL; /* Our store is full.
390 * Use this errno rather than E[NM]FILE to distinguish from
391 * the case where systemd itself hits the file limit. */
392
393 LIST_FOREACH(fd_store, fs, s->fd_store) {
394 r = same_fd(fs->fd, fd);
395 if (r < 0)
396 return r;
397 if (r > 0) {
398 safe_close(fd);
399 return 0; /* fd already included */
400 }
401 }
402
403 fs = new0(ServiceFDStore, 1);
404 if (!fs)
405 return -ENOMEM;
406
407 fs->fd = fd;
408 fs->service = s;
409 fs->fdname = strdup(name ?: "stored");
410 if (!fs->fdname) {
411 free(fs);
412 return -ENOMEM;
413 }
414
415 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
416 if (r < 0) {
417 free(fs->fdname);
418 free(fs);
419 return r;
420 }
421
422 (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
423
424 LIST_PREPEND(fd_store, s->fd_store, fs);
425 s->n_fd_store++;
426
427 return 1; /* fd newly stored */
428 }
429
430 static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name) {
431 int r;
432
433 assert(s);
434
435 while (fdset_size(fds) > 0) {
436 _cleanup_close_ int fd = -1;
437
438 fd = fdset_steal_first(fds);
439 if (fd < 0)
440 break;
441
442 r = service_add_fd_store(s, fd, name);
443 if (r == -EXFULL)
444 return log_unit_warning_errno(UNIT(s), r,
445 "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
446 s->n_fd_store_max);
447 if (r < 0)
448 return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
449 if (r > 0)
450 log_unit_debug(UNIT(s), "Added fd %u (%s) to fd store.", fd, strna(name));
451 fd = -1;
452 }
453
454 return 0;
455 }
456
457 static int service_arm_timer(Service *s, usec_t usec) {
458 int r;
459
460 assert(s);
461
462 if (s->timer_event_source) {
463 r = sd_event_source_set_time(s->timer_event_source, usec);
464 if (r < 0)
465 return r;
466
467 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
468 }
469
470 if (usec == USEC_INFINITY)
471 return 0;
472
473 r = sd_event_add_time(
474 UNIT(s)->manager->event,
475 &s->timer_event_source,
476 CLOCK_MONOTONIC,
477 usec, 0,
478 service_dispatch_timer, s);
479 if (r < 0)
480 return r;
481
482 (void) sd_event_source_set_description(s->timer_event_source, "service-timer");
483
484 return 0;
485 }
486
487 static int service_verify(Service *s) {
488 assert(s);
489
490 if (UNIT(s)->load_state != UNIT_LOADED)
491 return 0;
492
493 if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP]) {
494 log_unit_error(UNIT(s), "Service lacks both ExecStart= and ExecStop= setting. Refusing.");
495 return -EINVAL;
496 }
497
498 if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START]) {
499 log_unit_error(UNIT(s), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
500 return -EINVAL;
501 }
502
503 if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START]) {
504 log_unit_error(UNIT(s), "Service has no ExecStart= setting, which is only allowed for RemainAfterExit=yes services. Refusing.");
505 return -EINVAL;
506 }
507
508 if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next) {
509 log_unit_error(UNIT(s), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
510 return -EINVAL;
511 }
512
513 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
514 log_unit_error(UNIT(s), "Service has Restart= setting other than no, which isn't allowed for Type=oneshot services. Refusing.");
515 return -EINVAL;
516 }
517
518 if (s->type == SERVICE_ONESHOT && !exit_status_set_is_empty(&s->restart_force_status)) {
519 log_unit_error(UNIT(s), "Service has RestartForceStatus= set, which isn't allowed for Type=oneshot services. Refusing.");
520 return -EINVAL;
521 }
522
523 if (s->type == SERVICE_DBUS && !s->bus_name) {
524 log_unit_error(UNIT(s), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
525 return -EINVAL;
526 }
527
528 if (s->bus_name && s->type != SERVICE_DBUS)
529 log_unit_warning(UNIT(s), "Service has a D-Bus service name specified, but is not of type dbus. Ignoring.");
530
531 if (s->exec_context.pam_name && !(s->kill_context.kill_mode == KILL_CONTROL_GROUP || s->kill_context.kill_mode == KILL_MIXED)) {
532 log_unit_error(UNIT(s), "Service has PAM enabled. Kill mode must be set to 'control-group' or 'mixed'. Refusing.");
533 return -EINVAL;
534 }
535
536 if (s->usb_function_descriptors && !s->usb_function_strings)
537 log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
538
539 if (!s->usb_function_descriptors && s->usb_function_strings)
540 log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
541
542 if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
543 log_unit_warning(UNIT(s), "MaxRuntimeSec= has no effect in combination with Type=oneshot. Ignoring.");
544
545 return 0;
546 }
547
548 static int service_add_default_dependencies(Service *s) {
549 int r;
550
551 assert(s);
552
553 if (!UNIT(s)->default_dependencies)
554 return 0;
555
556 /* Add a number of automatic dependencies useful for the
557 * majority of services. */
558
559 if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
560 /* First, pull in the really early boot stuff, and
561 * require it, so that we fail if we can't acquire
562 * it. */
563
564 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
565 if (r < 0)
566 return r;
567 } else {
568
569 /* In the --user instance there's no sysinit.target,
570 * in that case require basic.target instead. */
571
572 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, NULL, true);
573 if (r < 0)
574 return r;
575 }
576
577 /* Second, if the rest of the base system is in the same
578 * transaction, order us after it, but do not pull it in or
579 * even require it. */
580 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, NULL, true);
581 if (r < 0)
582 return r;
583
584 /* Third, add us in for normal shutdown. */
585 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
586 }
587
588 static void service_fix_output(Service *s) {
589 assert(s);
590
591 /* If nothing has been explicitly configured, patch default
592 * output in. If input is socket/tty we avoid this however,
593 * since in that case we want output to default to the same
594 * place as we read input from. */
595
596 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
597 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
598 s->exec_context.std_input == EXEC_INPUT_NULL)
599 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
600
601 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
602 s->exec_context.std_input == EXEC_INPUT_NULL)
603 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
604 }
605
606 static int service_setup_bus_name(Service *s) {
607 int r;
608
609 assert(s);
610
611 if (!s->bus_name)
612 return 0;
613
614 r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, NULL, true);
615 if (r < 0)
616 return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
617
618 /* Regardless if kdbus is used or not, we always want to be ordered against dbus.socket if both are in the transaction. */
619 r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_DBUS_SOCKET, NULL, true);
620 if (r < 0)
621 return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on " SPECIAL_DBUS_SOCKET ": %m");
622
623 r = unit_watch_bus_name(UNIT(s), s->bus_name);
624 if (r == -EEXIST)
625 return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
626 if (r < 0)
627 return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
628
629 return 0;
630 }
631
632 static int service_add_extras(Service *s) {
633 int r;
634
635 assert(s);
636
637 if (s->type == _SERVICE_TYPE_INVALID) {
638 /* Figure out a type automatically */
639 if (s->bus_name)
640 s->type = SERVICE_DBUS;
641 else if (s->exec_command[SERVICE_EXEC_START])
642 s->type = SERVICE_SIMPLE;
643 else
644 s->type = SERVICE_ONESHOT;
645 }
646
647 /* Oneshot services have disabled start timeout by default */
648 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
649 s->timeout_start_usec = USEC_INFINITY;
650
651 service_fix_output(s);
652
653 r = unit_patch_contexts(UNIT(s));
654 if (r < 0)
655 return r;
656
657 r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
658 if (r < 0)
659 return r;
660
661 r = unit_set_default_slice(UNIT(s));
662 if (r < 0)
663 return r;
664
665 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
666 s->notify_access = NOTIFY_MAIN;
667
668 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
669 s->notify_access = NOTIFY_MAIN;
670
671 r = service_add_default_dependencies(s);
672 if (r < 0)
673 return r;
674
675 r = service_setup_bus_name(s);
676 if (r < 0)
677 return r;
678
679 return 0;
680 }
681
682 static int service_load(Unit *u) {
683 Service *s = SERVICE(u);
684 int r;
685
686 assert(s);
687
688 /* Load a .service file */
689 r = unit_load_fragment(u);
690 if (r < 0)
691 return r;
692
693 /* Still nothing found? Then let's give up */
694 if (u->load_state == UNIT_STUB)
695 return -ENOENT;
696
697 /* This is a new unit? Then let's add in some extras */
698 if (u->load_state == UNIT_LOADED) {
699
700 /* We were able to load something, then let's add in
701 * the dropin directories. */
702 r = unit_load_dropin(u);
703 if (r < 0)
704 return r;
705
706 /* This is a new unit? Then let's add in some
707 * extras */
708 r = service_add_extras(s);
709 if (r < 0)
710 return r;
711 }
712
713 return service_verify(s);
714 }
715
716 static void service_dump(Unit *u, FILE *f, const char *prefix) {
717 ServiceExecCommand c;
718 Service *s = SERVICE(u);
719 const char *prefix2;
720
721 assert(s);
722
723 prefix = strempty(prefix);
724 prefix2 = strjoina(prefix, "\t");
725
726 fprintf(f,
727 "%sService State: %s\n"
728 "%sResult: %s\n"
729 "%sReload Result: %s\n"
730 "%sPermissionsStartOnly: %s\n"
731 "%sRootDirectoryStartOnly: %s\n"
732 "%sRemainAfterExit: %s\n"
733 "%sGuessMainPID: %s\n"
734 "%sType: %s\n"
735 "%sRestart: %s\n"
736 "%sNotifyAccess: %s\n"
737 "%sNotifyState: %s\n",
738 prefix, service_state_to_string(s->state),
739 prefix, service_result_to_string(s->result),
740 prefix, service_result_to_string(s->reload_result),
741 prefix, yes_no(s->permissions_start_only),
742 prefix, yes_no(s->root_directory_start_only),
743 prefix, yes_no(s->remain_after_exit),
744 prefix, yes_no(s->guess_main_pid),
745 prefix, service_type_to_string(s->type),
746 prefix, service_restart_to_string(s->restart),
747 prefix, notify_access_to_string(s->notify_access),
748 prefix, notify_state_to_string(s->notify_state));
749
750 if (s->control_pid > 0)
751 fprintf(f,
752 "%sControl PID: "PID_FMT"\n",
753 prefix, s->control_pid);
754
755 if (s->main_pid > 0)
756 fprintf(f,
757 "%sMain PID: "PID_FMT"\n"
758 "%sMain PID Known: %s\n"
759 "%sMain PID Alien: %s\n",
760 prefix, s->main_pid,
761 prefix, yes_no(s->main_pid_known),
762 prefix, yes_no(s->main_pid_alien));
763
764 if (s->pid_file)
765 fprintf(f,
766 "%sPIDFile: %s\n",
767 prefix, s->pid_file);
768
769 if (s->bus_name)
770 fprintf(f,
771 "%sBusName: %s\n"
772 "%sBus Name Good: %s\n",
773 prefix, s->bus_name,
774 prefix, yes_no(s->bus_name_good));
775
776 if (UNIT_ISSET(s->accept_socket))
777 fprintf(f,
778 "%sAccept Socket: %s\n",
779 prefix, UNIT_DEREF(s->accept_socket)->id);
780
781 kill_context_dump(&s->kill_context, f, prefix);
782 exec_context_dump(&s->exec_context, f, prefix);
783
784 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
785
786 if (!s->exec_command[c])
787 continue;
788
789 fprintf(f, "%s-> %s:\n",
790 prefix, service_exec_command_to_string(c));
791
792 exec_command_dump_list(s->exec_command[c], f, prefix2);
793 }
794
795 if (s->status_text)
796 fprintf(f, "%sStatus Text: %s\n",
797 prefix, s->status_text);
798
799 if (s->n_fd_store_max > 0)
800 fprintf(f,
801 "%sFile Descriptor Store Max: %u\n"
802 "%sFile Descriptor Store Current: %u\n",
803 prefix, s->n_fd_store_max,
804 prefix, s->n_fd_store);
805 }
806
807 static int service_load_pid_file(Service *s, bool may_warn) {
808 _cleanup_free_ char *k = NULL;
809 int r;
810 pid_t pid;
811
812 assert(s);
813
814 if (!s->pid_file)
815 return -ENOENT;
816
817 r = read_one_line_file(s->pid_file, &k);
818 if (r < 0) {
819 if (may_warn)
820 log_unit_info_errno(UNIT(s), r, "PID file %s not readable (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
821 return r;
822 }
823
824 r = parse_pid(k, &pid);
825 if (r < 0) {
826 if (may_warn)
827 log_unit_info_errno(UNIT(s), r, "Failed to read PID from file %s: %m", s->pid_file);
828 return r;
829 }
830
831 if (!pid_is_alive(pid)) {
832 if (may_warn)
833 log_unit_info(UNIT(s), "PID "PID_FMT" read from file %s does not exist or is a zombie.", pid, s->pid_file);
834 return -ESRCH;
835 }
836
837 if (s->main_pid_known) {
838 if (pid == s->main_pid)
839 return 0;
840
841 log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid, pid);
842
843 service_unwatch_main_pid(s);
844 s->main_pid_known = false;
845 } else
846 log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pid);
847
848 r = service_set_main_pid(s, pid);
849 if (r < 0)
850 return r;
851
852 r = unit_watch_pid(UNIT(s), pid);
853 if (r < 0) {
854 /* FIXME: we need to do something here */
855 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", pid);
856 return r;
857 }
858
859 return 0;
860 }
861
862 static void service_search_main_pid(Service *s) {
863 pid_t pid = 0;
864 int r;
865
866 assert(s);
867
868 /* If we know it anyway, don't ever fallback to unreliable
869 * heuristics */
870 if (s->main_pid_known)
871 return;
872
873 if (!s->guess_main_pid)
874 return;
875
876 assert(s->main_pid <= 0);
877
878 if (unit_search_main_pid(UNIT(s), &pid) < 0)
879 return;
880
881 log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid);
882 if (service_set_main_pid(s, pid) < 0)
883 return;
884
885 r = unit_watch_pid(UNIT(s), pid);
886 if (r < 0)
887 /* FIXME: we need to do something here */
888 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" from: %m", pid);
889 }
890
891 static void service_set_state(Service *s, ServiceState state) {
892 ServiceState old_state;
893 const UnitActiveState *table;
894
895 assert(s);
896
897 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
898
899 old_state = s->state;
900 s->state = state;
901
902 service_unwatch_pid_file(s);
903
904 if (!IN_SET(state,
905 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
906 SERVICE_RUNNING,
907 SERVICE_RELOAD,
908 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
909 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
910 SERVICE_AUTO_RESTART))
911 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
912
913 if (!IN_SET(state,
914 SERVICE_START, SERVICE_START_POST,
915 SERVICE_RUNNING, SERVICE_RELOAD,
916 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
917 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
918 service_unwatch_main_pid(s);
919 s->main_command = NULL;
920 }
921
922 if (!IN_SET(state,
923 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
924 SERVICE_RELOAD,
925 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
926 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
927 service_unwatch_control_pid(s);
928 s->control_command = NULL;
929 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
930 }
931
932 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
933 unit_unwatch_all_pids(UNIT(s));
934
935 if (!IN_SET(state,
936 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
937 SERVICE_RUNNING, SERVICE_RELOAD,
938 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
939 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
940 !(state == SERVICE_DEAD && UNIT(s)->job))
941 service_close_socket_fd(s);
942
943 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
944 service_stop_watchdog(s);
945
946 /* For the inactive states unit_notify() will trim the cgroup,
947 * but for exit we have to do that ourselves... */
948 if (state == SERVICE_EXITED && !MANAGER_IS_RELOADING(UNIT(s)->manager))
949 unit_prune_cgroup(UNIT(s));
950
951 /* For remain_after_exit services, let's see if we can "release" the
952 * hold on the console, since unit_notify() only does that in case of
953 * change of state */
954 if (state == SERVICE_EXITED &&
955 s->remain_after_exit &&
956 UNIT(s)->manager->n_on_console > 0) {
957
958 ExecContext *ec;
959
960 ec = unit_get_exec_context(UNIT(s));
961 if (ec && exec_context_may_touch_console(ec)) {
962 Manager *m = UNIT(s)->manager;
963
964 m->n_on_console--;
965 if (m->n_on_console == 0)
966 /* unset no_console_output flag, since the console is free */
967 m->no_console_output = false;
968 }
969 }
970
971 if (old_state != state)
972 log_unit_debug(UNIT(s), "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
973
974 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
975 }
976
977 static usec_t service_coldplug_timeout(Service *s) {
978 assert(s);
979
980 switch (s->deserialized_state) {
981
982 case SERVICE_START_PRE:
983 case SERVICE_START:
984 case SERVICE_START_POST:
985 case SERVICE_RELOAD:
986 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
987
988 case SERVICE_RUNNING:
989 return usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec);
990
991 case SERVICE_STOP:
992 case SERVICE_STOP_SIGABRT:
993 case SERVICE_STOP_SIGTERM:
994 case SERVICE_STOP_SIGKILL:
995 case SERVICE_STOP_POST:
996 case SERVICE_FINAL_SIGTERM:
997 case SERVICE_FINAL_SIGKILL:
998 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
999
1000 case SERVICE_AUTO_RESTART:
1001 return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic, s->restart_usec);
1002
1003 default:
1004 return USEC_INFINITY;
1005 }
1006 }
1007
1008 static int service_coldplug(Unit *u) {
1009 Service *s = SERVICE(u);
1010 int r;
1011
1012 assert(s);
1013 assert(s->state == SERVICE_DEAD);
1014
1015 if (s->deserialized_state == s->state)
1016 return 0;
1017
1018 r = service_arm_timer(s, service_coldplug_timeout(s));
1019 if (r < 0)
1020 return r;
1021
1022 if (s->main_pid > 0 &&
1023 pid_is_unwaited(s->main_pid) &&
1024 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
1025 IN_SET(s->deserialized_state,
1026 SERVICE_START, SERVICE_START_POST,
1027 SERVICE_RUNNING, SERVICE_RELOAD,
1028 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1029 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
1030 r = unit_watch_pid(UNIT(s), s->main_pid);
1031 if (r < 0)
1032 return r;
1033 }
1034
1035 if (s->control_pid > 0 &&
1036 pid_is_unwaited(s->control_pid) &&
1037 IN_SET(s->deserialized_state,
1038 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1039 SERVICE_RELOAD,
1040 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1041 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1042 r = unit_watch_pid(UNIT(s), s->control_pid);
1043 if (r < 0)
1044 return r;
1045 }
1046
1047 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
1048 unit_watch_all_pids(UNIT(s));
1049
1050 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1051 service_start_watchdog(s);
1052
1053 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
1054 (void) unit_setup_dynamic_creds(u);
1055
1056 if (UNIT_ISSET(s->accept_socket)) {
1057 Socket* socket = SOCKET(UNIT_DEREF(s->accept_socket));
1058
1059 if (socket->max_connections_per_source > 0) {
1060 SocketPeer *peer;
1061
1062 /* Make a best-effort attempt at bumping the connection count */
1063 if (socket_acquire_peer(socket, s->socket_fd, &peer) > 0) {
1064 socket_peer_unref(s->peer);
1065 s->peer = peer;
1066 }
1067 }
1068 }
1069
1070 service_set_state(s, s->deserialized_state);
1071 return 0;
1072 }
1073
1074 static int service_collect_fds(Service *s, int **fds, char ***fd_names) {
1075 _cleanup_strv_free_ char **rfd_names = NULL;
1076 _cleanup_free_ int *rfds = NULL;
1077 int rn_fds = 0, r;
1078
1079 assert(s);
1080 assert(fds);
1081 assert(fd_names);
1082
1083 if (s->socket_fd >= 0) {
1084
1085 /* Pass the per-connection socket */
1086
1087 rfds = new(int, 1);
1088 if (!rfds)
1089 return -ENOMEM;
1090 rfds[0] = s->socket_fd;
1091
1092 rfd_names = strv_new("connection", NULL);
1093 if (!rfd_names)
1094 return -ENOMEM;
1095
1096 rn_fds = 1;
1097 } else {
1098 Iterator i;
1099 Unit *u;
1100
1101 /* Pass all our configured sockets for singleton services */
1102
1103 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1104 _cleanup_free_ int *cfds = NULL;
1105 Socket *sock;
1106 int cn_fds;
1107
1108 if (u->type != UNIT_SOCKET)
1109 continue;
1110
1111 sock = SOCKET(u);
1112
1113 cn_fds = socket_collect_fds(sock, &cfds);
1114 if (cn_fds < 0)
1115 return cn_fds;
1116
1117 if (cn_fds <= 0)
1118 continue;
1119
1120 if (!rfds) {
1121 rfds = cfds;
1122 rn_fds = cn_fds;
1123
1124 cfds = NULL;
1125 } else {
1126 int *t;
1127
1128 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
1129 if (!t)
1130 return -ENOMEM;
1131
1132 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
1133
1134 rfds = t;
1135 rn_fds += cn_fds;
1136 }
1137
1138 r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1139 if (r < 0)
1140 return r;
1141 }
1142 }
1143
1144 if (s->n_fd_store > 0) {
1145 ServiceFDStore *fs;
1146 char **nl;
1147 int *t;
1148
1149 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
1150 if (!t)
1151 return -ENOMEM;
1152
1153 rfds = t;
1154
1155 nl = realloc(rfd_names, (rn_fds + s->n_fd_store + 1) * sizeof(char*));
1156 if (!nl)
1157 return -ENOMEM;
1158
1159 rfd_names = nl;
1160
1161 LIST_FOREACH(fd_store, fs, s->fd_store) {
1162 rfds[rn_fds] = fs->fd;
1163 rfd_names[rn_fds] = strdup(strempty(fs->fdname));
1164 if (!rfd_names[rn_fds])
1165 return -ENOMEM;
1166
1167 rn_fds++;
1168 }
1169
1170 rfd_names[rn_fds] = NULL;
1171 }
1172
1173 *fds = rfds;
1174 *fd_names = rfd_names;
1175
1176 rfds = NULL;
1177 rfd_names = NULL;
1178
1179 return rn_fds;
1180 }
1181
1182 static int service_spawn(
1183 Service *s,
1184 ExecCommand *c,
1185 usec_t timeout,
1186 ExecFlags flags,
1187 pid_t *_pid) {
1188
1189 _cleanup_strv_free_ char **argv = NULL, **final_env = NULL, **our_env = NULL, **fd_names = NULL;
1190 _cleanup_free_ int *fds = NULL;
1191 unsigned n_fds = 0, n_env = 0;
1192 const char *path;
1193 pid_t pid;
1194
1195 ExecParameters exec_params = {
1196 .flags = flags,
1197 .stdin_fd = -1,
1198 .stdout_fd = -1,
1199 .stderr_fd = -1,
1200 };
1201
1202 int r;
1203
1204 assert(s);
1205 assert(c);
1206 assert(_pid);
1207
1208 if (flags & EXEC_IS_CONTROL) {
1209 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1210 if (s->permissions_start_only)
1211 exec_params.flags &= ~EXEC_APPLY_PERMISSIONS;
1212 if (s->root_directory_start_only)
1213 exec_params.flags &= ~EXEC_APPLY_CHROOT;
1214 }
1215
1216 (void) unit_realize_cgroup(UNIT(s));
1217 if (s->reset_cpu_usage) {
1218 (void) unit_reset_cpu_usage(UNIT(s));
1219 s->reset_cpu_usage = false;
1220 }
1221
1222 r = unit_setup_exec_runtime(UNIT(s));
1223 if (r < 0)
1224 return r;
1225
1226 r = unit_setup_dynamic_creds(UNIT(s));
1227 if (r < 0)
1228 return r;
1229
1230 if ((flags & EXEC_PASS_FDS) ||
1231 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1232 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1233 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1234
1235 r = service_collect_fds(s, &fds, &fd_names);
1236 if (r < 0)
1237 return r;
1238
1239 n_fds = r;
1240 log_unit_debug(UNIT(s), "Passing %i fds to service", n_fds);
1241 }
1242
1243 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), timeout));
1244 if (r < 0)
1245 return r;
1246
1247 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1248 if (r < 0)
1249 return r;
1250
1251 our_env = new0(char*, 9);
1252 if (!our_env)
1253 return -ENOMEM;
1254
1255 if ((flags & EXEC_IS_CONTROL) ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1256 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1257 return -ENOMEM;
1258
1259 if (s->main_pid > 0)
1260 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0)
1261 return -ENOMEM;
1262
1263 if (MANAGER_IS_USER(UNIT(s)->manager))
1264 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0)
1265 return -ENOMEM;
1266
1267 if (s->socket_fd >= 0) {
1268 union sockaddr_union sa;
1269 socklen_t salen = sizeof(sa);
1270
1271 r = getpeername(s->socket_fd, &sa.sa, &salen);
1272 if (r < 0) {
1273 r = -errno;
1274
1275 /* ENOTCONN is legitimate if the endpoint disappeared on shutdown.
1276 * This connection is over, but the socket unit lives on. */
1277 if (r != -ENOTCONN || !IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
1278 return r;
1279 }
1280
1281 if (r == 0 && IN_SET(sa.sa.sa_family, AF_INET, AF_INET6)) {
1282 _cleanup_free_ char *addr = NULL;
1283 char *t;
1284 int port;
1285
1286 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1287 if (r < 0)
1288 return r;
1289
1290 t = strappend("REMOTE_ADDR=", addr);
1291 if (!t)
1292 return -ENOMEM;
1293 our_env[n_env++] = t;
1294
1295 port = sockaddr_port(&sa.sa);
1296 if (port < 0)
1297 return port;
1298
1299 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1300 return -ENOMEM;
1301 our_env[n_env++] = t;
1302 }
1303 }
1304
1305 if (flags & EXEC_SETENV_RESULT) {
1306 if (asprintf(our_env + n_env++, "SERVICE_RESULT=%s", service_result_to_string(s->result)) < 0)
1307 return -ENOMEM;
1308
1309 if (s->main_exec_status.pid > 0 &&
1310 dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1311 if (asprintf(our_env + n_env++, "EXIT_CODE=%s", sigchld_code_to_string(s->main_exec_status.code)) < 0)
1312 return -ENOMEM;
1313
1314 if (s->main_exec_status.code == CLD_EXITED)
1315 r = asprintf(our_env + n_env++, "EXIT_STATUS=%i", s->main_exec_status.status);
1316 else
1317 r = asprintf(our_env + n_env++, "EXIT_STATUS=%s", signal_to_string(s->main_exec_status.status));
1318 if (r < 0)
1319 return -ENOMEM;
1320 }
1321 }
1322
1323 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1324 if (!final_env)
1325 return -ENOMEM;
1326
1327 if ((flags & EXEC_IS_CONTROL) && UNIT(s)->cgroup_path) {
1328 path = strjoina(UNIT(s)->cgroup_path, "/control");
1329 (void) cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1330 } else
1331 path = UNIT(s)->cgroup_path;
1332
1333 exec_params.argv = argv;
1334 exec_params.environment = final_env;
1335 exec_params.fds = fds;
1336 exec_params.fd_names = fd_names;
1337 exec_params.n_fds = n_fds;
1338 exec_params.confirm_spawn = manager_get_confirm_spawn(UNIT(s)->manager);
1339 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1340 exec_params.cgroup_path = path;
1341 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1342 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1343 exec_params.watchdog_usec = s->watchdog_usec;
1344 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
1345 if (s->type == SERVICE_IDLE)
1346 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1347 exec_params.stdin_fd = s->stdin_fd;
1348 exec_params.stdout_fd = s->stdout_fd;
1349 exec_params.stderr_fd = s->stderr_fd;
1350
1351 r = exec_spawn(UNIT(s),
1352 c,
1353 &s->exec_context,
1354 &exec_params,
1355 s->exec_runtime,
1356 &s->dynamic_creds,
1357 &pid);
1358 if (r < 0)
1359 return r;
1360
1361 r = unit_watch_pid(UNIT(s), pid);
1362 if (r < 0)
1363 /* FIXME: we need to do something here */
1364 return r;
1365
1366 *_pid = pid;
1367
1368 return 0;
1369 }
1370
1371 static int main_pid_good(Service *s) {
1372 assert(s);
1373
1374 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1375 * don't know */
1376
1377 /* If we know the pid file, then let's just check if it is
1378 * still valid */
1379 if (s->main_pid_known) {
1380
1381 /* If it's an alien child let's check if it is still
1382 * alive ... */
1383 if (s->main_pid_alien && s->main_pid > 0)
1384 return pid_is_alive(s->main_pid);
1385
1386 /* .. otherwise assume we'll get a SIGCHLD for it,
1387 * which we really should wait for to collect exit
1388 * status and code */
1389 return s->main_pid > 0;
1390 }
1391
1392 /* We don't know the pid */
1393 return -EAGAIN;
1394 }
1395
1396 _pure_ static int control_pid_good(Service *s) {
1397 assert(s);
1398
1399 return s->control_pid > 0;
1400 }
1401
1402 static int cgroup_good(Service *s) {
1403 int r;
1404
1405 assert(s);
1406
1407 if (!UNIT(s)->cgroup_path)
1408 return 0;
1409
1410 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
1411 if (r < 0)
1412 return r;
1413
1414 return !r;
1415 }
1416
1417 static bool service_shall_restart(Service *s) {
1418 assert(s);
1419
1420 /* Don't restart after manual stops */
1421 if (s->forbid_restart)
1422 return false;
1423
1424 /* Never restart if this is configured as special exception */
1425 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status))
1426 return false;
1427
1428 /* Restart if the exit code/status are configured as restart triggers */
1429 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status))
1430 return true;
1431
1432 switch (s->restart) {
1433
1434 case SERVICE_RESTART_NO:
1435 return false;
1436
1437 case SERVICE_RESTART_ALWAYS:
1438 return true;
1439
1440 case SERVICE_RESTART_ON_SUCCESS:
1441 return s->result == SERVICE_SUCCESS;
1442
1443 case SERVICE_RESTART_ON_FAILURE:
1444 return s->result != SERVICE_SUCCESS;
1445
1446 case SERVICE_RESTART_ON_ABNORMAL:
1447 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE);
1448
1449 case SERVICE_RESTART_ON_WATCHDOG:
1450 return s->result == SERVICE_FAILURE_WATCHDOG;
1451
1452 case SERVICE_RESTART_ON_ABORT:
1453 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1454
1455 default:
1456 assert_not_reached("unknown restart setting");
1457 }
1458 }
1459
1460 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1461 int r;
1462 assert(s);
1463
1464 if (s->result == SERVICE_SUCCESS)
1465 s->result = f;
1466
1467 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1468
1469 if (s->result != SERVICE_SUCCESS) {
1470 log_unit_warning(UNIT(s), "Failed with result '%s'.", service_result_to_string(s->result));
1471 emergency_action(UNIT(s)->manager, s->emergency_action, UNIT(s)->reboot_arg, "service failed");
1472 }
1473
1474 if (allow_restart && service_shall_restart(s)) {
1475
1476 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1477 if (r < 0)
1478 goto fail;
1479
1480 service_set_state(s, SERVICE_AUTO_RESTART);
1481 }
1482
1483 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1484 s->forbid_restart = false;
1485
1486 /* We want fresh tmpdirs in case service is started again immediately */
1487 exec_runtime_destroy(s->exec_runtime);
1488 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1489
1490 /* Also, remove the runtime directory */
1491 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1492
1493 /* Get rid of the IPC bits of the user */
1494 unit_unref_uid_gid(UNIT(s), true);
1495
1496 /* Release the user, and destroy it if we are the only remaining owner */
1497 dynamic_creds_destroy(&s->dynamic_creds);
1498
1499 /* Try to delete the pid file. At this point it will be
1500 * out-of-date, and some software might be confused by it, so
1501 * let's remove it. */
1502 if (s->pid_file)
1503 (void) unlink(s->pid_file);
1504
1505 return;
1506
1507 fail:
1508 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
1509 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1510 }
1511
1512 static void service_enter_stop_post(Service *s, ServiceResult f) {
1513 int r;
1514 assert(s);
1515
1516 if (s->result == SERVICE_SUCCESS)
1517 s->result = f;
1518
1519 service_unwatch_control_pid(s);
1520 unit_watch_all_pids(UNIT(s));
1521
1522 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1523 if (s->control_command) {
1524 s->control_command_id = SERVICE_EXEC_STOP_POST;
1525
1526 r = service_spawn(s,
1527 s->control_command,
1528 s->timeout_stop_usec,
1529 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
1530 &s->control_pid);
1531 if (r < 0)
1532 goto fail;
1533
1534 service_set_state(s, SERVICE_STOP_POST);
1535 } else
1536 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1537
1538 return;
1539
1540 fail:
1541 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
1542 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1543 }
1544
1545 static int state_to_kill_operation(ServiceState state) {
1546 switch (state) {
1547
1548 case SERVICE_STOP_SIGABRT:
1549 return KILL_ABORT;
1550
1551 case SERVICE_STOP_SIGTERM:
1552 case SERVICE_FINAL_SIGTERM:
1553 return KILL_TERMINATE;
1554
1555 case SERVICE_STOP_SIGKILL:
1556 case SERVICE_FINAL_SIGKILL:
1557 return KILL_KILL;
1558
1559 default:
1560 return _KILL_OPERATION_INVALID;
1561 }
1562 }
1563
1564 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1565 int r;
1566
1567 assert(s);
1568
1569 if (s->result == SERVICE_SUCCESS)
1570 s->result = f;
1571
1572 unit_watch_all_pids(UNIT(s));
1573
1574 r = unit_kill_context(
1575 UNIT(s),
1576 &s->kill_context,
1577 state_to_kill_operation(state),
1578 s->main_pid,
1579 s->control_pid,
1580 s->main_pid_alien);
1581
1582 if (r < 0)
1583 goto fail;
1584
1585 if (r > 0) {
1586 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1587 if (r < 0)
1588 goto fail;
1589
1590 service_set_state(s, state);
1591 } else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
1592 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1593 else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1594 service_enter_stop_post(s, SERVICE_SUCCESS);
1595 else if (state == SERVICE_FINAL_SIGTERM && s->kill_context.send_sigkill)
1596 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1597 else
1598 service_enter_dead(s, SERVICE_SUCCESS, true);
1599
1600 return;
1601
1602 fail:
1603 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
1604
1605 if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1606 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1607 else
1608 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1609 }
1610
1611 static void service_enter_stop_by_notify(Service *s) {
1612 assert(s);
1613
1614 unit_watch_all_pids(UNIT(s));
1615
1616 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1617
1618 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1619 service_set_state(s, SERVICE_STOP_SIGTERM);
1620 }
1621
1622 static void service_enter_stop(Service *s, ServiceResult f) {
1623 int r;
1624
1625 assert(s);
1626
1627 if (s->result == SERVICE_SUCCESS)
1628 s->result = f;
1629
1630 service_unwatch_control_pid(s);
1631 unit_watch_all_pids(UNIT(s));
1632
1633 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1634 if (s->control_command) {
1635 s->control_command_id = SERVICE_EXEC_STOP;
1636
1637 r = service_spawn(s,
1638 s->control_command,
1639 s->timeout_stop_usec,
1640 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
1641 &s->control_pid);
1642 if (r < 0)
1643 goto fail;
1644
1645 service_set_state(s, SERVICE_STOP);
1646 } else
1647 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1648
1649 return;
1650
1651 fail:
1652 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
1653 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1654 }
1655
1656 static bool service_good(Service *s) {
1657 int main_pid_ok;
1658 assert(s);
1659
1660 if (s->type == SERVICE_DBUS && !s->bus_name_good)
1661 return false;
1662
1663 main_pid_ok = main_pid_good(s);
1664 if (main_pid_ok > 0) /* It's alive */
1665 return true;
1666 if (main_pid_ok == 0) /* It's dead */
1667 return false;
1668
1669 /* OK, we don't know anything about the main PID, maybe
1670 * because there is none. Let's check the control group
1671 * instead. */
1672
1673 return cgroup_good(s) != 0;
1674 }
1675
1676 static void service_enter_running(Service *s, ServiceResult f) {
1677 assert(s);
1678
1679 if (s->result == SERVICE_SUCCESS)
1680 s->result = f;
1681
1682 service_unwatch_control_pid(s);
1683
1684 if (service_good(s)) {
1685
1686 /* If there are any queued up sd_notify()
1687 * notifications, process them now */
1688 if (s->notify_state == NOTIFY_RELOADING)
1689 service_enter_reload_by_notify(s);
1690 else if (s->notify_state == NOTIFY_STOPPING)
1691 service_enter_stop_by_notify(s);
1692 else {
1693 service_set_state(s, SERVICE_RUNNING);
1694 service_arm_timer(s, usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec));
1695 }
1696
1697 } else if (f != SERVICE_SUCCESS)
1698 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
1699 else if (s->remain_after_exit)
1700 service_set_state(s, SERVICE_EXITED);
1701 else
1702 service_enter_stop(s, SERVICE_SUCCESS);
1703 }
1704
1705 static void service_enter_start_post(Service *s) {
1706 int r;
1707 assert(s);
1708
1709 service_unwatch_control_pid(s);
1710 service_reset_watchdog(s);
1711
1712 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1713 if (s->control_command) {
1714 s->control_command_id = SERVICE_EXEC_START_POST;
1715
1716 r = service_spawn(s,
1717 s->control_command,
1718 s->timeout_start_usec,
1719 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
1720 &s->control_pid);
1721 if (r < 0)
1722 goto fail;
1723
1724 service_set_state(s, SERVICE_START_POST);
1725 } else
1726 service_enter_running(s, SERVICE_SUCCESS);
1727
1728 return;
1729
1730 fail:
1731 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
1732 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1733 }
1734
1735 static void service_kill_control_processes(Service *s) {
1736 char *p;
1737
1738 if (!UNIT(s)->cgroup_path)
1739 return;
1740
1741 p = strjoina(UNIT(s)->cgroup_path, "/control");
1742 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, CGROUP_SIGCONT|CGROUP_IGNORE_SELF|CGROUP_REMOVE, NULL, NULL, NULL);
1743 }
1744
1745 static void service_enter_start(Service *s) {
1746 ExecCommand *c;
1747 usec_t timeout;
1748 pid_t pid;
1749 int r;
1750
1751 assert(s);
1752
1753 service_unwatch_control_pid(s);
1754 service_unwatch_main_pid(s);
1755
1756 /* We want to ensure that nobody leaks processes from
1757 * START_PRE here, so let's go on a killing spree, People
1758 * should not spawn long running processes from START_PRE. */
1759 service_kill_control_processes(s);
1760
1761 if (s->type == SERVICE_FORKING) {
1762 s->control_command_id = SERVICE_EXEC_START;
1763 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1764
1765 s->main_command = NULL;
1766 } else {
1767 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1768 s->control_command = NULL;
1769
1770 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1771 }
1772
1773 if (!c) {
1774 if (s->type != SERVICE_ONESHOT) {
1775 /* There's no command line configured for the main command? Hmm, that is strange. This can only
1776 * happen if the configuration changes at runtime. In this case, let's enter a failure
1777 * state. */
1778 log_unit_error(UNIT(s), "There's no 'start' task anymore we could start: %m");
1779 r = -ENXIO;
1780 goto fail;
1781 }
1782
1783 service_enter_start_post(s);
1784 return;
1785 }
1786
1787 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
1788 /* For simple + idle this is the main process. We don't apply any timeout here, but
1789 * service_enter_running() will later apply the .runtime_max_usec timeout. */
1790 timeout = USEC_INFINITY;
1791 else
1792 timeout = s->timeout_start_usec;
1793
1794 r = service_spawn(s,
1795 c,
1796 timeout,
1797 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
1798 &pid);
1799 if (r < 0)
1800 goto fail;
1801
1802 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
1803 /* For simple services we immediately start
1804 * the START_POST binaries. */
1805
1806 service_set_main_pid(s, pid);
1807 service_enter_start_post(s);
1808
1809 } else if (s->type == SERVICE_FORKING) {
1810
1811 /* For forking services we wait until the start
1812 * process exited. */
1813
1814 s->control_pid = pid;
1815 service_set_state(s, SERVICE_START);
1816
1817 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY)) {
1818
1819 /* For oneshot services we wait until the start
1820 * process exited, too, but it is our main process. */
1821
1822 /* For D-Bus services we know the main pid right away,
1823 * but wait for the bus name to appear on the
1824 * bus. Notify services are similar. */
1825
1826 service_set_main_pid(s, pid);
1827 service_set_state(s, SERVICE_START);
1828 } else
1829 assert_not_reached("Unknown service type");
1830
1831 return;
1832
1833 fail:
1834 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
1835 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1836 }
1837
1838 static void service_enter_start_pre(Service *s) {
1839 int r;
1840
1841 assert(s);
1842
1843 service_unwatch_control_pid(s);
1844
1845 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1846 if (s->control_command) {
1847 /* Before we start anything, let's clear up what might
1848 * be left from previous runs. */
1849 service_kill_control_processes(s);
1850
1851 s->control_command_id = SERVICE_EXEC_START_PRE;
1852
1853 r = service_spawn(s,
1854 s->control_command,
1855 s->timeout_start_usec,
1856 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN,
1857 &s->control_pid);
1858 if (r < 0)
1859 goto fail;
1860
1861 service_set_state(s, SERVICE_START_PRE);
1862 } else
1863 service_enter_start(s);
1864
1865 return;
1866
1867 fail:
1868 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
1869 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1870 }
1871
1872 static void service_enter_restart(Service *s) {
1873 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1874 int r;
1875
1876 assert(s);
1877
1878 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1879 /* Don't restart things if we are going down anyway */
1880 log_unit_info(UNIT(s), "Stop job pending for unit, delaying automatic restart.");
1881
1882 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1883 if (r < 0)
1884 goto fail;
1885
1886 return;
1887 }
1888
1889 /* Any units that are bound to this service must also be
1890 * restarted. We use JOB_RESTART (instead of the more obvious
1891 * JOB_START) here so that those dependency jobs will be added
1892 * as well. */
1893 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, &error, NULL);
1894 if (r < 0)
1895 goto fail;
1896
1897 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1898 * it will be canceled as part of the service_stop() call that
1899 * is executed as part of JOB_RESTART. */
1900
1901 log_unit_debug(UNIT(s), "Scheduled restart job.");
1902 return;
1903
1904 fail:
1905 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, -r));
1906 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1907 }
1908
1909 static void service_enter_reload_by_notify(Service *s) {
1910 assert(s);
1911
1912 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_start_usec));
1913 service_set_state(s, SERVICE_RELOAD);
1914 }
1915
1916 static void service_enter_reload(Service *s) {
1917 int r;
1918
1919 assert(s);
1920
1921 service_unwatch_control_pid(s);
1922 s->reload_result = SERVICE_SUCCESS;
1923
1924 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1925 if (s->control_command) {
1926 s->control_command_id = SERVICE_EXEC_RELOAD;
1927
1928 r = service_spawn(s,
1929 s->control_command,
1930 s->timeout_start_usec,
1931 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
1932 &s->control_pid);
1933 if (r < 0)
1934 goto fail;
1935
1936 service_set_state(s, SERVICE_RELOAD);
1937 } else
1938 service_enter_running(s, SERVICE_SUCCESS);
1939
1940 return;
1941
1942 fail:
1943 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
1944 s->reload_result = SERVICE_FAILURE_RESOURCES;
1945 service_enter_running(s, SERVICE_SUCCESS);
1946 }
1947
1948 static void service_run_next_control(Service *s) {
1949 usec_t timeout;
1950 int r;
1951
1952 assert(s);
1953 assert(s->control_command);
1954 assert(s->control_command->command_next);
1955
1956 assert(s->control_command_id != SERVICE_EXEC_START);
1957
1958 s->control_command = s->control_command->command_next;
1959 service_unwatch_control_pid(s);
1960
1961 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1962 timeout = s->timeout_start_usec;
1963 else
1964 timeout = s->timeout_stop_usec;
1965
1966 r = service_spawn(s,
1967 s->control_command,
1968 timeout,
1969 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|
1970 (IN_SET(s->control_command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_STOP_POST) ? EXEC_APPLY_TTY_STDIN : 0)|
1971 (IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_SETENV_RESULT : 0),
1972 &s->control_pid);
1973 if (r < 0)
1974 goto fail;
1975
1976 return;
1977
1978 fail:
1979 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
1980
1981 if (s->state == SERVICE_START_PRE)
1982 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1983 else if (s->state == SERVICE_STOP)
1984 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1985 else if (s->state == SERVICE_STOP_POST)
1986 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1987 else if (s->state == SERVICE_RELOAD) {
1988 s->reload_result = SERVICE_FAILURE_RESOURCES;
1989 service_enter_running(s, SERVICE_SUCCESS);
1990 } else
1991 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1992 }
1993
1994 static void service_run_next_main(Service *s) {
1995 pid_t pid;
1996 int r;
1997
1998 assert(s);
1999 assert(s->main_command);
2000 assert(s->main_command->command_next);
2001 assert(s->type == SERVICE_ONESHOT);
2002
2003 s->main_command = s->main_command->command_next;
2004 service_unwatch_main_pid(s);
2005
2006 r = service_spawn(s,
2007 s->main_command,
2008 s->timeout_start_usec,
2009 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
2010 &pid);
2011 if (r < 0)
2012 goto fail;
2013
2014 service_set_main_pid(s, pid);
2015
2016 return;
2017
2018 fail:
2019 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
2020 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2021 }
2022
2023 static int service_start(Unit *u) {
2024 Service *s = SERVICE(u);
2025 int r;
2026
2027 assert(s);
2028
2029 /* We cannot fulfill this request right now, try again later
2030 * please! */
2031 if (IN_SET(s->state,
2032 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2033 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2034 return -EAGAIN;
2035
2036 /* Already on it! */
2037 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
2038 return 0;
2039
2040 /* A service that will be restarted must be stopped first to
2041 * trigger BindsTo and/or OnFailure dependencies. If a user
2042 * does not want to wait for the holdoff time to elapse, the
2043 * service should be manually restarted, not started. We
2044 * simply return EAGAIN here, so that any start jobs stay
2045 * queued, and assume that the auto restart timer will
2046 * eventually trigger the restart. */
2047 if (s->state == SERVICE_AUTO_RESTART)
2048 return -EAGAIN;
2049
2050 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
2051
2052 /* Make sure we don't enter a busy loop of some kind. */
2053 r = unit_start_limit_test(u);
2054 if (r < 0) {
2055 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
2056 return r;
2057 }
2058
2059 r = unit_acquire_invocation_id(u);
2060 if (r < 0)
2061 return r;
2062
2063 s->result = SERVICE_SUCCESS;
2064 s->reload_result = SERVICE_SUCCESS;
2065 s->main_pid_known = false;
2066 s->main_pid_alien = false;
2067 s->forbid_restart = false;
2068 s->reset_cpu_usage = true;
2069
2070 s->status_text = mfree(s->status_text);
2071 s->status_errno = 0;
2072
2073 s->notify_state = NOTIFY_UNKNOWN;
2074
2075 s->watchdog_override_enable = false;
2076 s->watchdog_override_usec = 0;
2077
2078 service_enter_start_pre(s);
2079 return 1;
2080 }
2081
2082 static int service_stop(Unit *u) {
2083 Service *s = SERVICE(u);
2084
2085 assert(s);
2086
2087 /* Don't create restart jobs from manual stops. */
2088 s->forbid_restart = true;
2089
2090 /* Already on it */
2091 if (IN_SET(s->state,
2092 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2093 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2094 return 0;
2095
2096 /* A restart will be scheduled or is in progress. */
2097 if (s->state == SERVICE_AUTO_RESTART) {
2098 service_set_state(s, SERVICE_DEAD);
2099 return 0;
2100 }
2101
2102 /* If there's already something running we go directly into
2103 * kill mode. */
2104 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD)) {
2105 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2106 return 0;
2107 }
2108
2109 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
2110
2111 service_enter_stop(s, SERVICE_SUCCESS);
2112 return 1;
2113 }
2114
2115 static int service_reload(Unit *u) {
2116 Service *s = SERVICE(u);
2117
2118 assert(s);
2119
2120 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2121
2122 service_enter_reload(s);
2123 return 1;
2124 }
2125
2126 _pure_ static bool service_can_reload(Unit *u) {
2127 Service *s = SERVICE(u);
2128
2129 assert(s);
2130
2131 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2132 }
2133
2134 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2135 Service *s = SERVICE(u);
2136 ServiceFDStore *fs;
2137 int r;
2138
2139 assert(u);
2140 assert(f);
2141 assert(fds);
2142
2143 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2144 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2145 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2146
2147 if (s->control_pid > 0)
2148 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
2149
2150 if (s->main_pid_known && s->main_pid > 0)
2151 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
2152
2153 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2154 unit_serialize_item(u, f, "bus-name-good", yes_no(s->bus_name_good));
2155 unit_serialize_item(u, f, "bus-name-owner", s->bus_name_owner);
2156
2157 r = unit_serialize_item_escaped(u, f, "status-text", s->status_text);
2158 if (r < 0)
2159 return r;
2160
2161 /* FIXME: There's a minor uncleanliness here: if there are
2162 * multiple commands attached here, we will start from the
2163 * first one again */
2164 if (s->control_command_id >= 0)
2165 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2166
2167 r = unit_serialize_item_fd(u, f, fds, "stdin-fd", s->stdin_fd);
2168 if (r < 0)
2169 return r;
2170 r = unit_serialize_item_fd(u, f, fds, "stdout-fd", s->stdout_fd);
2171 if (r < 0)
2172 return r;
2173 r = unit_serialize_item_fd(u, f, fds, "stderr-fd", s->stderr_fd);
2174 if (r < 0)
2175 return r;
2176
2177 if (UNIT_ISSET(s->accept_socket)) {
2178 r = unit_serialize_item(u, f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
2179 if (r < 0)
2180 return r;
2181 }
2182
2183 r = unit_serialize_item_fd(u, f, fds, "socket-fd", s->socket_fd);
2184 if (r < 0)
2185 return r;
2186
2187 LIST_FOREACH(fd_store, fs, s->fd_store) {
2188 _cleanup_free_ char *c = NULL;
2189 int copy;
2190
2191 copy = fdset_put_dup(fds, fs->fd);
2192 if (copy < 0)
2193 return copy;
2194
2195 c = cescape(fs->fdname);
2196
2197 unit_serialize_item_format(u, f, "fd-store-fd", "%i %s", copy, strempty(c));
2198 }
2199
2200 if (s->main_exec_status.pid > 0) {
2201 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2202 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2203 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2204
2205 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2206 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2207 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2208 }
2209 }
2210
2211 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2212
2213 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2214
2215 if (s->watchdog_override_enable)
2216 unit_serialize_item_format(u, f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2217
2218 return 0;
2219 }
2220
2221 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2222 Service *s = SERVICE(u);
2223 int r;
2224
2225 assert(u);
2226 assert(key);
2227 assert(value);
2228 assert(fds);
2229
2230 if (streq(key, "state")) {
2231 ServiceState state;
2232
2233 state = service_state_from_string(value);
2234 if (state < 0)
2235 log_unit_debug(u, "Failed to parse state value: %s", value);
2236 else
2237 s->deserialized_state = state;
2238 } else if (streq(key, "result")) {
2239 ServiceResult f;
2240
2241 f = service_result_from_string(value);
2242 if (f < 0)
2243 log_unit_debug(u, "Failed to parse result value: %s", value);
2244 else if (f != SERVICE_SUCCESS)
2245 s->result = f;
2246
2247 } else if (streq(key, "reload-result")) {
2248 ServiceResult f;
2249
2250 f = service_result_from_string(value);
2251 if (f < 0)
2252 log_unit_debug(u, "Failed to parse reload result value: %s", value);
2253 else if (f != SERVICE_SUCCESS)
2254 s->reload_result = f;
2255
2256 } else if (streq(key, "control-pid")) {
2257 pid_t pid;
2258
2259 if (parse_pid(value, &pid) < 0)
2260 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2261 else
2262 s->control_pid = pid;
2263 } else if (streq(key, "main-pid")) {
2264 pid_t pid;
2265
2266 if (parse_pid(value, &pid) < 0)
2267 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2268 else {
2269 service_set_main_pid(s, pid);
2270 unit_watch_pid(UNIT(s), pid);
2271 }
2272 } else if (streq(key, "main-pid-known")) {
2273 int b;
2274
2275 b = parse_boolean(value);
2276 if (b < 0)
2277 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2278 else
2279 s->main_pid_known = b;
2280 } else if (streq(key, "bus-name-good")) {
2281 int b;
2282
2283 b = parse_boolean(value);
2284 if (b < 0)
2285 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2286 else
2287 s->bus_name_good = b;
2288 } else if (streq(key, "bus-name-owner")) {
2289 r = free_and_strdup(&s->bus_name_owner, value);
2290 if (r < 0)
2291 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
2292 } else if (streq(key, "status-text")) {
2293 char *t;
2294
2295 r = cunescape(value, 0, &t);
2296 if (r < 0)
2297 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
2298 else {
2299 free(s->status_text);
2300 s->status_text = t;
2301 }
2302
2303 } else if (streq(key, "control-command")) {
2304 ServiceExecCommand id;
2305
2306 id = service_exec_command_from_string(value);
2307 if (id < 0)
2308 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
2309 else {
2310 s->control_command_id = id;
2311 s->control_command = s->exec_command[id];
2312 }
2313 } else if (streq(key, "accept-socket")) {
2314 Unit *socket;
2315
2316 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
2317 if (r < 0)
2318 log_unit_debug_errno(u, r, "Failed to load accept-socket unit: %s", value);
2319 else {
2320 unit_ref_set(&s->accept_socket, socket);
2321 SOCKET(socket)->n_connections++;
2322 }
2323
2324 } else if (streq(key, "socket-fd")) {
2325 int fd;
2326
2327 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2328 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
2329 else {
2330 asynchronous_close(s->socket_fd);
2331 s->socket_fd = fdset_remove(fds, fd);
2332 }
2333 } else if (streq(key, "fd-store-fd")) {
2334 const char *fdv;
2335 size_t pf;
2336 int fd;
2337
2338 pf = strcspn(value, WHITESPACE);
2339 fdv = strndupa(value, pf);
2340
2341 if (safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2342 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2343 else {
2344 _cleanup_free_ char *t = NULL;
2345 const char *fdn;
2346
2347 fdn = value + pf;
2348 fdn += strspn(fdn, WHITESPACE);
2349 (void) cunescape(fdn, 0, &t);
2350
2351 r = service_add_fd_store(s, fd, t);
2352 if (r < 0)
2353 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
2354 else
2355 fdset_remove(fds, fd);
2356 }
2357
2358 } else if (streq(key, "main-exec-status-pid")) {
2359 pid_t pid;
2360
2361 if (parse_pid(value, &pid) < 0)
2362 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
2363 else
2364 s->main_exec_status.pid = pid;
2365 } else if (streq(key, "main-exec-status-code")) {
2366 int i;
2367
2368 if (safe_atoi(value, &i) < 0)
2369 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
2370 else
2371 s->main_exec_status.code = i;
2372 } else if (streq(key, "main-exec-status-status")) {
2373 int i;
2374
2375 if (safe_atoi(value, &i) < 0)
2376 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
2377 else
2378 s->main_exec_status.status = i;
2379 } else if (streq(key, "main-exec-status-start"))
2380 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2381 else if (streq(key, "main-exec-status-exit"))
2382 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2383 else if (streq(key, "watchdog-timestamp"))
2384 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2385 else if (streq(key, "forbid-restart")) {
2386 int b;
2387
2388 b = parse_boolean(value);
2389 if (b < 0)
2390 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
2391 else
2392 s->forbid_restart = b;
2393 } else if (streq(key, "stdin-fd")) {
2394 int fd;
2395
2396 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2397 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
2398 else {
2399 asynchronous_close(s->stdin_fd);
2400 s->stdin_fd = fdset_remove(fds, fd);
2401 s->exec_context.stdio_as_fds = true;
2402 }
2403 } else if (streq(key, "stdout-fd")) {
2404 int fd;
2405
2406 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2407 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
2408 else {
2409 asynchronous_close(s->stdout_fd);
2410 s->stdout_fd = fdset_remove(fds, fd);
2411 s->exec_context.stdio_as_fds = true;
2412 }
2413 } else if (streq(key, "stderr-fd")) {
2414 int fd;
2415
2416 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2417 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
2418 else {
2419 asynchronous_close(s->stderr_fd);
2420 s->stderr_fd = fdset_remove(fds, fd);
2421 s->exec_context.stdio_as_fds = true;
2422 }
2423 } else if (streq(key, "watchdog-override-usec")) {
2424 usec_t watchdog_override_usec;
2425 if (timestamp_deserialize(value, &watchdog_override_usec) < 0)
2426 log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
2427 else {
2428 s->watchdog_override_enable = true;
2429 s->watchdog_override_usec = watchdog_override_usec;
2430 }
2431 } else
2432 log_unit_debug(u, "Unknown serialization key: %s", key);
2433
2434 return 0;
2435 }
2436
2437 _pure_ static UnitActiveState service_active_state(Unit *u) {
2438 const UnitActiveState *table;
2439
2440 assert(u);
2441
2442 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2443
2444 return table[SERVICE(u)->state];
2445 }
2446
2447 static const char *service_sub_state_to_string(Unit *u) {
2448 assert(u);
2449
2450 return service_state_to_string(SERVICE(u)->state);
2451 }
2452
2453 static bool service_check_gc(Unit *u) {
2454 Service *s = SERVICE(u);
2455
2456 assert(s);
2457
2458 /* Never clean up services that still have a process around,
2459 * even if the service is formally dead. */
2460 if (cgroup_good(s) > 0 ||
2461 main_pid_good(s) > 0 ||
2462 control_pid_good(s) > 0)
2463 return true;
2464
2465 return false;
2466 }
2467
2468 static int service_retry_pid_file(Service *s) {
2469 int r;
2470
2471 assert(s->pid_file);
2472 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2473
2474 r = service_load_pid_file(s, false);
2475 if (r < 0)
2476 return r;
2477
2478 service_unwatch_pid_file(s);
2479
2480 service_enter_running(s, SERVICE_SUCCESS);
2481 return 0;
2482 }
2483
2484 static int service_watch_pid_file(Service *s) {
2485 int r;
2486
2487 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
2488
2489 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2490 if (r < 0)
2491 goto fail;
2492
2493 /* the pidfile might have appeared just before we set the watch */
2494 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
2495 service_retry_pid_file(s);
2496
2497 return 0;
2498 fail:
2499 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
2500 service_unwatch_pid_file(s);
2501 return r;
2502 }
2503
2504 static int service_demand_pid_file(Service *s) {
2505 PathSpec *ps;
2506
2507 assert(s->pid_file);
2508 assert(!s->pid_file_pathspec);
2509
2510 ps = new0(PathSpec, 1);
2511 if (!ps)
2512 return -ENOMEM;
2513
2514 ps->unit = UNIT(s);
2515 ps->path = strdup(s->pid_file);
2516 if (!ps->path) {
2517 free(ps);
2518 return -ENOMEM;
2519 }
2520
2521 path_kill_slashes(ps->path);
2522
2523 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2524 * keep their PID file open all the time. */
2525 ps->type = PATH_MODIFIED;
2526 ps->inotify_fd = -1;
2527
2528 s->pid_file_pathspec = ps;
2529
2530 return service_watch_pid_file(s);
2531 }
2532
2533 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2534 PathSpec *p = userdata;
2535 Service *s;
2536
2537 assert(p);
2538
2539 s = SERVICE(p->unit);
2540
2541 assert(s);
2542 assert(fd >= 0);
2543 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2544 assert(s->pid_file_pathspec);
2545 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2546
2547 log_unit_debug(UNIT(s), "inotify event");
2548
2549 if (path_spec_fd_event(p, events) < 0)
2550 goto fail;
2551
2552 if (service_retry_pid_file(s) == 0)
2553 return 0;
2554
2555 if (service_watch_pid_file(s) < 0)
2556 goto fail;
2557
2558 return 0;
2559
2560 fail:
2561 service_unwatch_pid_file(s);
2562 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2563 return 0;
2564 }
2565
2566 static void service_notify_cgroup_empty_event(Unit *u) {
2567 Service *s = SERVICE(u);
2568
2569 assert(u);
2570
2571 log_unit_debug(u, "cgroup is empty");
2572
2573 switch (s->state) {
2574
2575 /* Waiting for SIGCHLD is usually more interesting,
2576 * because it includes return codes/signals. Which is
2577 * why we ignore the cgroup events for most cases,
2578 * except when we don't know pid which to expect the
2579 * SIGCHLD for. */
2580
2581 case SERVICE_START:
2582 if (s->type == SERVICE_NOTIFY) {
2583 /* No chance of getting a ready notification anymore */
2584 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_PROTOCOL);
2585 break;
2586 }
2587
2588 /* Fall through */
2589
2590 case SERVICE_START_POST:
2591 if (s->pid_file_pathspec) {
2592 /* Give up hoping for the daemon to write its PID file */
2593 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
2594
2595 service_unwatch_pid_file(s);
2596 if (s->state == SERVICE_START)
2597 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_PROTOCOL);
2598 else
2599 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2600 }
2601 break;
2602
2603 case SERVICE_RUNNING:
2604 /* service_enter_running() will figure out what to do */
2605 service_enter_running(s, SERVICE_SUCCESS);
2606 break;
2607
2608 case SERVICE_STOP_SIGABRT:
2609 case SERVICE_STOP_SIGTERM:
2610 case SERVICE_STOP_SIGKILL:
2611
2612 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2613 service_enter_stop_post(s, SERVICE_SUCCESS);
2614
2615 break;
2616
2617 case SERVICE_STOP_POST:
2618 case SERVICE_FINAL_SIGTERM:
2619 case SERVICE_FINAL_SIGKILL:
2620 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2621 service_enter_dead(s, SERVICE_SUCCESS, true);
2622
2623 break;
2624
2625 default:
2626 ;
2627 }
2628 }
2629
2630 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2631 Service *s = SERVICE(u);
2632 ServiceResult f;
2633
2634 assert(s);
2635 assert(pid >= 0);
2636
2637 if (is_clean_exit(code, status, s->type == SERVICE_ONESHOT ? EXIT_CLEAN_COMMAND : EXIT_CLEAN_DAEMON, &s->success_status))
2638 f = SERVICE_SUCCESS;
2639 else if (code == CLD_EXITED)
2640 f = SERVICE_FAILURE_EXIT_CODE;
2641 else if (code == CLD_KILLED)
2642 f = SERVICE_FAILURE_SIGNAL;
2643 else if (code == CLD_DUMPED)
2644 f = SERVICE_FAILURE_CORE_DUMP;
2645 else
2646 assert_not_reached("Unknown code");
2647
2648 if (s->main_pid == pid) {
2649 /* Forking services may occasionally move to a new PID.
2650 * As long as they update the PID file before exiting the old
2651 * PID, they're fine. */
2652 if (service_load_pid_file(s, false) == 0)
2653 return;
2654
2655 s->main_pid = 0;
2656 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2657
2658 if (s->main_command) {
2659 /* If this is not a forking service than the
2660 * main process got started and hence we copy
2661 * the exit status so that it is recorded both
2662 * as main and as control process exit
2663 * status */
2664
2665 s->main_command->exec_status = s->main_exec_status;
2666
2667 if (s->main_command->ignore)
2668 f = SERVICE_SUCCESS;
2669 } else if (s->exec_command[SERVICE_EXEC_START]) {
2670
2671 /* If this is a forked process, then we should
2672 * ignore the return value if this was
2673 * configured for the starter process */
2674
2675 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2676 f = SERVICE_SUCCESS;
2677 }
2678
2679 /* When this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
2680 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
2681 * that the service already logged the reason at a higher log level on its own. However, if the service
2682 * died due to a signal, then it most likely didn't say anything about any reason, hence let's raise
2683 * our log level to WARNING then. */
2684
2685 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG :
2686 (code == CLD_EXITED ? LOG_NOTICE : LOG_WARNING),
2687 LOG_UNIT_ID(u),
2688 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2689 sigchld_code_to_string(code), status,
2690 strna(code == CLD_EXITED
2691 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2692 : signal_to_string(status))),
2693 "EXIT_CODE=%s", sigchld_code_to_string(code),
2694 "EXIT_STATUS=%i", status,
2695 NULL);
2696
2697 if (s->result == SERVICE_SUCCESS)
2698 s->result = f;
2699
2700 if (s->main_command &&
2701 s->main_command->command_next &&
2702 f == SERVICE_SUCCESS) {
2703
2704 /* There is another command to *
2705 * execute, so let's do that. */
2706
2707 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2708 service_run_next_main(s);
2709
2710 } else {
2711
2712 /* The service exited, so the service is officially
2713 * gone. */
2714 s->main_command = NULL;
2715
2716 switch (s->state) {
2717
2718 case SERVICE_START_POST:
2719 case SERVICE_RELOAD:
2720 case SERVICE_STOP:
2721 /* Need to wait until the operation is
2722 * done */
2723 break;
2724
2725 case SERVICE_START:
2726 if (s->type == SERVICE_ONESHOT) {
2727 /* This was our main goal, so let's go on */
2728 if (f == SERVICE_SUCCESS)
2729 service_enter_start_post(s);
2730 else
2731 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2732 break;
2733 } else if (s->type == SERVICE_NOTIFY) {
2734 /* Only enter running through a notification, so that the
2735 * SERVICE_START state signifies that no ready notification
2736 * has been received */
2737 if (f != SERVICE_SUCCESS)
2738 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2739 else if (!s->remain_after_exit)
2740 /* The service has never been active */
2741 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_PROTOCOL);
2742 break;
2743 }
2744
2745 /* Fall through */
2746
2747 case SERVICE_RUNNING:
2748 service_enter_running(s, f);
2749 break;
2750
2751 case SERVICE_STOP_SIGABRT:
2752 case SERVICE_STOP_SIGTERM:
2753 case SERVICE_STOP_SIGKILL:
2754
2755 if (!control_pid_good(s))
2756 service_enter_stop_post(s, f);
2757
2758 /* If there is still a control process, wait for that first */
2759 break;
2760
2761 case SERVICE_STOP_POST:
2762 case SERVICE_FINAL_SIGTERM:
2763 case SERVICE_FINAL_SIGKILL:
2764
2765 if (!control_pid_good(s))
2766 service_enter_dead(s, f, true);
2767 break;
2768
2769 default:
2770 assert_not_reached("Uh, main process died at wrong time.");
2771 }
2772 }
2773
2774 } else if (s->control_pid == pid) {
2775 s->control_pid = 0;
2776
2777 if (s->control_command) {
2778 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2779
2780 if (s->control_command->ignore)
2781 f = SERVICE_SUCCESS;
2782 }
2783
2784 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2785 "Control process exited, code=%s status=%i",
2786 sigchld_code_to_string(code), status);
2787
2788 if (s->result == SERVICE_SUCCESS)
2789 s->result = f;
2790
2791 /* Immediately get rid of the cgroup, so that the
2792 * kernel doesn't delay the cgroup empty messages for
2793 * the service cgroup any longer than necessary */
2794 service_kill_control_processes(s);
2795
2796 if (s->control_command &&
2797 s->control_command->command_next &&
2798 f == SERVICE_SUCCESS) {
2799
2800 /* There is another command to *
2801 * execute, so let's do that. */
2802
2803 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
2804 service_run_next_control(s);
2805
2806 } else {
2807 /* No further commands for this step, so let's
2808 * figure out what to do next */
2809
2810 s->control_command = NULL;
2811 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2812
2813 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
2814
2815 switch (s->state) {
2816
2817 case SERVICE_START_PRE:
2818 if (f == SERVICE_SUCCESS)
2819 service_enter_start(s);
2820 else
2821 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2822 break;
2823
2824 case SERVICE_START:
2825 if (s->type != SERVICE_FORKING)
2826 /* Maybe spurious event due to a reload that changed the type? */
2827 break;
2828
2829 if (f != SERVICE_SUCCESS) {
2830 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2831 break;
2832 }
2833
2834 if (s->pid_file) {
2835 bool has_start_post;
2836 int r;
2837
2838 /* Let's try to load the pid file here if we can.
2839 * The PID file might actually be created by a START_POST
2840 * script. In that case don't worry if the loading fails. */
2841
2842 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2843 r = service_load_pid_file(s, !has_start_post);
2844 if (!has_start_post && r < 0) {
2845 r = service_demand_pid_file(s);
2846 if (r < 0 || !cgroup_good(s))
2847 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_PROTOCOL);
2848 break;
2849 }
2850 } else
2851 service_search_main_pid(s);
2852
2853 service_enter_start_post(s);
2854 break;
2855
2856 case SERVICE_START_POST:
2857 if (f != SERVICE_SUCCESS) {
2858 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2859 break;
2860 }
2861
2862 if (s->pid_file) {
2863 int r;
2864
2865 r = service_load_pid_file(s, true);
2866 if (r < 0) {
2867 r = service_demand_pid_file(s);
2868 if (r < 0 || !cgroup_good(s))
2869 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2870 break;
2871 }
2872 } else
2873 service_search_main_pid(s);
2874
2875 service_enter_running(s, SERVICE_SUCCESS);
2876 break;
2877
2878 case SERVICE_RELOAD:
2879 if (f == SERVICE_SUCCESS)
2880 if (service_load_pid_file(s, true) < 0)
2881 service_search_main_pid(s);
2882
2883 s->reload_result = f;
2884 service_enter_running(s, SERVICE_SUCCESS);
2885 break;
2886
2887 case SERVICE_STOP:
2888 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2889 break;
2890
2891 case SERVICE_STOP_SIGABRT:
2892 case SERVICE_STOP_SIGTERM:
2893 case SERVICE_STOP_SIGKILL:
2894 if (main_pid_good(s) <= 0)
2895 service_enter_stop_post(s, f);
2896
2897 /* If there is still a service
2898 * process around, wait until
2899 * that one quit, too */
2900 break;
2901
2902 case SERVICE_STOP_POST:
2903 case SERVICE_FINAL_SIGTERM:
2904 case SERVICE_FINAL_SIGKILL:
2905 if (main_pid_good(s) <= 0)
2906 service_enter_dead(s, f, true);
2907 break;
2908
2909 default:
2910 assert_not_reached("Uh, control process died at wrong time.");
2911 }
2912 }
2913 }
2914
2915 /* Notify clients about changed exit status */
2916 unit_add_to_dbus_queue(u);
2917
2918 /* We got one SIGCHLD for the service, let's watch all
2919 * processes that are now running of the service, and watch
2920 * that. Among the PIDs we then watch will be children
2921 * reassigned to us, which hopefully allows us to identify
2922 * when all children are gone */
2923 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2924 unit_watch_all_pids(u);
2925
2926 /* If the PID set is empty now, then let's finish this off
2927 (On unified we use proper notifications) */
2928 if (cg_unified(SYSTEMD_CGROUP_CONTROLLER) <= 0 && set_isempty(u->pids))
2929 service_notify_cgroup_empty_event(u);
2930 }
2931
2932 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2933 Service *s = SERVICE(userdata);
2934
2935 assert(s);
2936 assert(source == s->timer_event_source);
2937
2938 switch (s->state) {
2939
2940 case SERVICE_START_PRE:
2941 case SERVICE_START:
2942 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
2943 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2944 break;
2945
2946 case SERVICE_START_POST:
2947 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
2948 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2949 break;
2950
2951 case SERVICE_RUNNING:
2952 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2953 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2954 break;
2955
2956 case SERVICE_RELOAD:
2957 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
2958 service_kill_control_processes(s);
2959 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2960 service_enter_running(s, SERVICE_SUCCESS);
2961 break;
2962
2963 case SERVICE_STOP:
2964 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
2965 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2966 break;
2967
2968 case SERVICE_STOP_SIGABRT:
2969 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2970 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2971 break;
2972
2973 case SERVICE_STOP_SIGTERM:
2974 if (s->kill_context.send_sigkill) {
2975 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
2976 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2977 } else {
2978 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
2979 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2980 }
2981
2982 break;
2983
2984 case SERVICE_STOP_SIGKILL:
2985 /* Uh, we sent a SIGKILL and it is still not gone?
2986 * Must be something we cannot kill, so let's just be
2987 * weirded out and continue */
2988
2989 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
2990 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2991 break;
2992
2993 case SERVICE_STOP_POST:
2994 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
2995 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2996 break;
2997
2998 case SERVICE_FINAL_SIGTERM:
2999 if (s->kill_context.send_sigkill) {
3000 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
3001 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
3002 } else {
3003 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
3004 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
3005 }
3006
3007 break;
3008
3009 case SERVICE_FINAL_SIGKILL:
3010 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
3011 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
3012 break;
3013
3014 case SERVICE_AUTO_RESTART:
3015 log_unit_info(UNIT(s),
3016 s->restart_usec > 0 ?
3017 "Service hold-off time over, scheduling restart." :
3018 "Service has no hold-off time, scheduling restart.");
3019 service_enter_restart(s);
3020 break;
3021
3022 default:
3023 assert_not_reached("Timeout at wrong time.");
3024 }
3025
3026 return 0;
3027 }
3028
3029 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
3030 Service *s = SERVICE(userdata);
3031 char t[FORMAT_TIMESPAN_MAX];
3032 usec_t watchdog_usec;
3033
3034 assert(s);
3035 assert(source == s->watchdog_event_source);
3036
3037 watchdog_usec = service_get_watchdog_usec(s);
3038
3039 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
3040 format_timespan(t, sizeof(t), watchdog_usec, 1));
3041
3042 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
3043
3044 return 0;
3045 }
3046
3047 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
3048 Service *s = SERVICE(u);
3049 _cleanup_free_ char *cc = NULL;
3050 bool notify_dbus = false;
3051 const char *e;
3052
3053 assert(u);
3054
3055 cc = strv_join(tags, ", ");
3056
3057 if (s->notify_access == NOTIFY_NONE) {
3058 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
3059 return;
3060 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3061 if (s->main_pid != 0)
3062 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
3063 else
3064 log_unit_debug(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
3065 return;
3066 } else
3067 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
3068
3069 /* Interpret MAINPID= */
3070 e = strv_find_startswith(tags, "MAINPID=");
3071 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
3072 if (parse_pid(e, &pid) < 0)
3073 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
3074 else {
3075 service_set_main_pid(s, pid);
3076 unit_watch_pid(UNIT(s), pid);
3077 notify_dbus = true;
3078 }
3079 }
3080
3081 /* Interpret RELOADING= */
3082 if (strv_find(tags, "RELOADING=1")) {
3083
3084 s->notify_state = NOTIFY_RELOADING;
3085
3086 if (s->state == SERVICE_RUNNING)
3087 service_enter_reload_by_notify(s);
3088
3089 notify_dbus = true;
3090 }
3091
3092 /* Interpret READY= */
3093 if (strv_find(tags, "READY=1")) {
3094
3095 s->notify_state = NOTIFY_READY;
3096
3097 /* Type=notify services inform us about completed
3098 * initialization with READY=1 */
3099 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
3100 service_enter_start_post(s);
3101
3102 /* Sending READY=1 while we are reloading informs us
3103 * that the reloading is complete */
3104 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
3105 service_enter_running(s, SERVICE_SUCCESS);
3106
3107 notify_dbus = true;
3108 }
3109
3110 /* Interpret STOPPING= */
3111 if (strv_find(tags, "STOPPING=1")) {
3112
3113 s->notify_state = NOTIFY_STOPPING;
3114
3115 if (s->state == SERVICE_RUNNING)
3116 service_enter_stop_by_notify(s);
3117
3118 notify_dbus = true;
3119 }
3120
3121 /* Interpret STATUS= */
3122 e = strv_find_startswith(tags, "STATUS=");
3123 if (e) {
3124 _cleanup_free_ char *t = NULL;
3125
3126 if (!isempty(e)) {
3127 if (!utf8_is_valid(e))
3128 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
3129 else {
3130 t = strdup(e);
3131 if (!t)
3132 log_oom();
3133 }
3134 }
3135
3136 if (!streq_ptr(s->status_text, t)) {
3137
3138 free_and_replace(s->status_text, t);
3139
3140 notify_dbus = true;
3141 }
3142 }
3143
3144 /* Interpret ERRNO= */
3145 e = strv_find_startswith(tags, "ERRNO=");
3146 if (e) {
3147 int status_errno;
3148
3149 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
3150 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
3151 else {
3152 if (s->status_errno != status_errno) {
3153 s->status_errno = status_errno;
3154 notify_dbus = true;
3155 }
3156 }
3157 }
3158
3159 /* Interpret WATCHDOG= */
3160 if (strv_find(tags, "WATCHDOG=1"))
3161 service_reset_watchdog(s);
3162
3163 if (strv_find(tags, "FDSTORE=1")) {
3164 const char *name;
3165
3166 name = strv_find_startswith(tags, "FDNAME=");
3167 if (name && !fdname_is_valid(name)) {
3168 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
3169 name = NULL;
3170 }
3171
3172 service_add_fd_store_set(s, fds, name);
3173 }
3174
3175 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
3176 if (e) {
3177 usec_t watchdog_override_usec;
3178 if (safe_atou64(e, &watchdog_override_usec) < 0)
3179 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
3180 else
3181 service_reset_watchdog_timeout(s, watchdog_override_usec);
3182 }
3183
3184 /* Notify clients about changed status or main pid */
3185 if (notify_dbus)
3186 unit_add_to_dbus_queue(u);
3187 }
3188
3189 static int service_get_timeout(Unit *u, usec_t *timeout) {
3190 Service *s = SERVICE(u);
3191 uint64_t t;
3192 int r;
3193
3194 if (!s->timer_event_source)
3195 return 0;
3196
3197 r = sd_event_source_get_time(s->timer_event_source, &t);
3198 if (r < 0)
3199 return r;
3200 if (t == USEC_INFINITY)
3201 return 0;
3202
3203 *timeout = t;
3204 return 1;
3205 }
3206
3207 static void service_bus_name_owner_change(
3208 Unit *u,
3209 const char *name,
3210 const char *old_owner,
3211 const char *new_owner) {
3212
3213 Service *s = SERVICE(u);
3214 int r;
3215
3216 assert(s);
3217 assert(name);
3218
3219 assert(streq(s->bus_name, name));
3220 assert(old_owner || new_owner);
3221
3222 if (old_owner && new_owner)
3223 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
3224 else if (old_owner)
3225 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
3226 else
3227 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
3228
3229 s->bus_name_good = !!new_owner;
3230
3231 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3232 r = free_and_strdup(&s->bus_name_owner, new_owner);
3233 if (r < 0) {
3234 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
3235 return;
3236 }
3237
3238 if (s->type == SERVICE_DBUS) {
3239
3240 /* service_enter_running() will figure out what to
3241 * do */
3242 if (s->state == SERVICE_RUNNING)
3243 service_enter_running(s, SERVICE_SUCCESS);
3244 else if (s->state == SERVICE_START && new_owner)
3245 service_enter_start_post(s);
3246
3247 } else if (new_owner &&
3248 s->main_pid <= 0 &&
3249 (s->state == SERVICE_START ||
3250 s->state == SERVICE_START_POST ||
3251 s->state == SERVICE_RUNNING ||
3252 s->state == SERVICE_RELOAD)) {
3253
3254 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
3255 pid_t pid;
3256
3257 /* Try to acquire PID from bus service */
3258
3259 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3260 if (r >= 0)
3261 r = sd_bus_creds_get_pid(creds, &pid);
3262 if (r >= 0) {
3263 log_unit_debug(u, "D-Bus name %s is now owned by process %u", name, (unsigned) pid);
3264
3265 service_set_main_pid(s, pid);
3266 unit_watch_pid(UNIT(s), pid);
3267 }
3268 }
3269 }
3270
3271 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
3272 _cleanup_free_ char *peer = NULL;
3273 int r;
3274
3275 assert(s);
3276 assert(fd >= 0);
3277
3278 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
3279 * to be configured. We take ownership of the passed fd on success. */
3280
3281 if (UNIT(s)->load_state != UNIT_LOADED)
3282 return -EINVAL;
3283
3284 if (s->socket_fd >= 0)
3285 return -EBUSY;
3286
3287 if (s->state != SERVICE_DEAD)
3288 return -EAGAIN;
3289
3290 if (getpeername_pretty(fd, true, &peer) >= 0) {
3291
3292 if (UNIT(s)->description) {
3293 _cleanup_free_ char *a;
3294
3295 a = strjoin(UNIT(s)->description, " (", peer, ")");
3296 if (!a)
3297 return -ENOMEM;
3298
3299 r = unit_set_description(UNIT(s), a);
3300 } else
3301 r = unit_set_description(UNIT(s), peer);
3302
3303 if (r < 0)
3304 return r;
3305 }
3306
3307 r = unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3308 if (r < 0)
3309 return r;
3310
3311 s->socket_fd = fd;
3312 s->socket_fd_selinux_context_net = selinux_context_net;
3313
3314 unit_ref_set(&s->accept_socket, UNIT(sock));
3315 return 0;
3316 }
3317
3318 static void service_reset_failed(Unit *u) {
3319 Service *s = SERVICE(u);
3320
3321 assert(s);
3322
3323 if (s->state == SERVICE_FAILED)
3324 service_set_state(s, SERVICE_DEAD);
3325
3326 s->result = SERVICE_SUCCESS;
3327 s->reload_result = SERVICE_SUCCESS;
3328 }
3329
3330 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3331 Service *s = SERVICE(u);
3332
3333 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3334 }
3335
3336 static int service_main_pid(Unit *u) {
3337 Service *s = SERVICE(u);
3338
3339 assert(s);
3340
3341 return s->main_pid;
3342 }
3343
3344 static int service_control_pid(Unit *u) {
3345 Service *s = SERVICE(u);
3346
3347 assert(s);
3348
3349 return s->control_pid;
3350 }
3351
3352 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3353 [SERVICE_RESTART_NO] = "no",
3354 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3355 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3356 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3357 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3358 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3359 [SERVICE_RESTART_ALWAYS] = "always",
3360 };
3361
3362 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3363
3364 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3365 [SERVICE_SIMPLE] = "simple",
3366 [SERVICE_FORKING] = "forking",
3367 [SERVICE_ONESHOT] = "oneshot",
3368 [SERVICE_DBUS] = "dbus",
3369 [SERVICE_NOTIFY] = "notify",
3370 [SERVICE_IDLE] = "idle"
3371 };
3372
3373 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3374
3375 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3376 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3377 [SERVICE_EXEC_START] = "ExecStart",
3378 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3379 [SERVICE_EXEC_RELOAD] = "ExecReload",
3380 [SERVICE_EXEC_STOP] = "ExecStop",
3381 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3382 };
3383
3384 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3385
3386 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3387 [NOTIFY_NONE] = "none",
3388 [NOTIFY_MAIN] = "main",
3389 [NOTIFY_ALL] = "all"
3390 };
3391
3392 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3393
3394 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3395 [NOTIFY_UNKNOWN] = "unknown",
3396 [NOTIFY_READY] = "ready",
3397 [NOTIFY_RELOADING] = "reloading",
3398 [NOTIFY_STOPPING] = "stopping",
3399 };
3400
3401 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3402
3403 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3404 [SERVICE_SUCCESS] = "success",
3405 [SERVICE_FAILURE_RESOURCES] = "resources",
3406 [SERVICE_FAILURE_PROTOCOL] = "protocol",
3407 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3408 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3409 [SERVICE_FAILURE_SIGNAL] = "signal",
3410 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3411 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3412 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
3413 };
3414
3415 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3416
3417 const UnitVTable service_vtable = {
3418 .object_size = sizeof(Service),
3419 .exec_context_offset = offsetof(Service, exec_context),
3420 .cgroup_context_offset = offsetof(Service, cgroup_context),
3421 .kill_context_offset = offsetof(Service, kill_context),
3422 .exec_runtime_offset = offsetof(Service, exec_runtime),
3423 .dynamic_creds_offset = offsetof(Service, dynamic_creds),
3424
3425 .sections =
3426 "Unit\0"
3427 "Service\0"
3428 "Install\0",
3429 .private_section = "Service",
3430
3431 .init = service_init,
3432 .done = service_done,
3433 .load = service_load,
3434 .release_resources = service_release_resources,
3435
3436 .coldplug = service_coldplug,
3437
3438 .dump = service_dump,
3439
3440 .start = service_start,
3441 .stop = service_stop,
3442 .reload = service_reload,
3443
3444 .can_reload = service_can_reload,
3445
3446 .kill = service_kill,
3447
3448 .serialize = service_serialize,
3449 .deserialize_item = service_deserialize_item,
3450
3451 .active_state = service_active_state,
3452 .sub_state_to_string = service_sub_state_to_string,
3453
3454 .check_gc = service_check_gc,
3455
3456 .sigchld_event = service_sigchld_event,
3457
3458 .reset_failed = service_reset_failed,
3459
3460 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3461 .notify_message = service_notify_message,
3462
3463 .main_pid = service_main_pid,
3464 .control_pid = service_control_pid,
3465
3466 .bus_name_owner_change = service_bus_name_owner_change,
3467
3468 .bus_vtable = bus_service_vtable,
3469 .bus_set_property = bus_service_set_property,
3470 .bus_commit_properties = bus_service_commit_properties,
3471
3472 .get_timeout = service_get_timeout,
3473 .can_transient = true,
3474
3475 .status_message_formats = {
3476 .starting_stopping = {
3477 [0] = "Starting %s...",
3478 [1] = "Stopping %s...",
3479 },
3480 .finished_start_job = {
3481 [JOB_DONE] = "Started %s.",
3482 [JOB_FAILED] = "Failed to start %s.",
3483 },
3484 .finished_stop_job = {
3485 [JOB_DONE] = "Stopped %s.",
3486 [JOB_FAILED] = "Stopped (with error) %s.",
3487 },
3488 },
3489 };