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