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