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