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