]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
Merge pull request #2717 from keszybz/networkctl-prettification
[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 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2138
2139 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2140
2141 return 0;
2142 }
2143
2144 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2145 Service *s = SERVICE(u);
2146 int r;
2147
2148 assert(u);
2149 assert(key);
2150 assert(value);
2151 assert(fds);
2152
2153 if (streq(key, "state")) {
2154 ServiceState state;
2155
2156 state = service_state_from_string(value);
2157 if (state < 0)
2158 log_unit_debug(u, "Failed to parse state value: %s", value);
2159 else
2160 s->deserialized_state = state;
2161 } else if (streq(key, "result")) {
2162 ServiceResult f;
2163
2164 f = service_result_from_string(value);
2165 if (f < 0)
2166 log_unit_debug(u, "Failed to parse result value: %s", value);
2167 else if (f != SERVICE_SUCCESS)
2168 s->result = f;
2169
2170 } else if (streq(key, "reload-result")) {
2171 ServiceResult f;
2172
2173 f = service_result_from_string(value);
2174 if (f < 0)
2175 log_unit_debug(u, "Failed to parse reload result value: %s", value);
2176 else if (f != SERVICE_SUCCESS)
2177 s->reload_result = f;
2178
2179 } else if (streq(key, "control-pid")) {
2180 pid_t pid;
2181
2182 if (parse_pid(value, &pid) < 0)
2183 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2184 else
2185 s->control_pid = pid;
2186 } else if (streq(key, "main-pid")) {
2187 pid_t pid;
2188
2189 if (parse_pid(value, &pid) < 0)
2190 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2191 else {
2192 service_set_main_pid(s, pid);
2193 unit_watch_pid(UNIT(s), pid);
2194 }
2195 } else if (streq(key, "main-pid-known")) {
2196 int b;
2197
2198 b = parse_boolean(value);
2199 if (b < 0)
2200 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2201 else
2202 s->main_pid_known = b;
2203 } else if (streq(key, "bus-name-good")) {
2204 int b;
2205
2206 b = parse_boolean(value);
2207 if (b < 0)
2208 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2209 else
2210 s->bus_name_good = b;
2211 } else if (streq(key, "bus-name-owner")) {
2212 r = free_and_strdup(&s->bus_name_owner, value);
2213 if (r < 0)
2214 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
2215 } else if (streq(key, "status-text")) {
2216 char *t;
2217
2218 r = cunescape(value, 0, &t);
2219 if (r < 0)
2220 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
2221 else {
2222 free(s->status_text);
2223 s->status_text = t;
2224 }
2225
2226 } else if (streq(key, "control-command")) {
2227 ServiceExecCommand id;
2228
2229 id = service_exec_command_from_string(value);
2230 if (id < 0)
2231 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
2232 else {
2233 s->control_command_id = id;
2234 s->control_command = s->exec_command[id];
2235 }
2236 } else if (streq(key, "socket-fd")) {
2237 int fd;
2238
2239 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2240 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
2241 else {
2242 asynchronous_close(s->socket_fd);
2243 s->socket_fd = fdset_remove(fds, fd);
2244 }
2245 } else if (streq(key, "fd-store-fd")) {
2246 const char *fdv;
2247 size_t pf;
2248 int fd;
2249
2250 pf = strcspn(value, WHITESPACE);
2251 fdv = strndupa(value, pf);
2252
2253 if (safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2254 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2255 else {
2256 _cleanup_free_ char *t = NULL;
2257 const char *fdn;
2258
2259 fdn = value + pf;
2260 fdn += strspn(fdn, WHITESPACE);
2261 (void) cunescape(fdn, 0, &t);
2262
2263 r = service_add_fd_store(s, fd, t);
2264 if (r < 0)
2265 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
2266 else if (r > 0)
2267 fdset_remove(fds, fd);
2268 }
2269
2270 } else if (streq(key, "main-exec-status-pid")) {
2271 pid_t pid;
2272
2273 if (parse_pid(value, &pid) < 0)
2274 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
2275 else
2276 s->main_exec_status.pid = pid;
2277 } else if (streq(key, "main-exec-status-code")) {
2278 int i;
2279
2280 if (safe_atoi(value, &i) < 0)
2281 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
2282 else
2283 s->main_exec_status.code = i;
2284 } else if (streq(key, "main-exec-status-status")) {
2285 int i;
2286
2287 if (safe_atoi(value, &i) < 0)
2288 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
2289 else
2290 s->main_exec_status.status = i;
2291 } else if (streq(key, "main-exec-status-start"))
2292 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2293 else if (streq(key, "main-exec-status-exit"))
2294 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2295 else if (streq(key, "watchdog-timestamp"))
2296 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2297 else if (streq(key, "forbid-restart")) {
2298 int b;
2299
2300 b = parse_boolean(value);
2301 if (b < 0)
2302 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
2303 else
2304 s->forbid_restart = b;
2305 } else if (streq(key, "stdin-fd")) {
2306 int fd;
2307
2308 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2309 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
2310 else {
2311 asynchronous_close(s->stdin_fd);
2312 s->stdin_fd = fdset_remove(fds, fd);
2313 s->exec_context.stdio_as_fds = true;
2314 }
2315 } else if (streq(key, "stdout-fd")) {
2316 int fd;
2317
2318 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2319 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
2320 else {
2321 asynchronous_close(s->stdout_fd);
2322 s->stdout_fd = fdset_remove(fds, fd);
2323 s->exec_context.stdio_as_fds = true;
2324 }
2325 } else if (streq(key, "stderr-fd")) {
2326 int fd;
2327
2328 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2329 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
2330 else {
2331 asynchronous_close(s->stderr_fd);
2332 s->stderr_fd = fdset_remove(fds, fd);
2333 s->exec_context.stdio_as_fds = true;
2334 }
2335 } else
2336 log_unit_debug(u, "Unknown serialization key: %s", key);
2337
2338 return 0;
2339 }
2340
2341 _pure_ static UnitActiveState service_active_state(Unit *u) {
2342 const UnitActiveState *table;
2343
2344 assert(u);
2345
2346 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2347
2348 return table[SERVICE(u)->state];
2349 }
2350
2351 static const char *service_sub_state_to_string(Unit *u) {
2352 assert(u);
2353
2354 return service_state_to_string(SERVICE(u)->state);
2355 }
2356
2357 static bool service_check_gc(Unit *u) {
2358 Service *s = SERVICE(u);
2359
2360 assert(s);
2361
2362 /* Never clean up services that still have a process around,
2363 * even if the service is formally dead. */
2364 if (cgroup_good(s) > 0 ||
2365 main_pid_good(s) > 0 ||
2366 control_pid_good(s) > 0)
2367 return true;
2368
2369 return false;
2370 }
2371
2372 static int service_retry_pid_file(Service *s) {
2373 int r;
2374
2375 assert(s->pid_file);
2376 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2377
2378 r = service_load_pid_file(s, false);
2379 if (r < 0)
2380 return r;
2381
2382 service_unwatch_pid_file(s);
2383
2384 service_enter_running(s, SERVICE_SUCCESS);
2385 return 0;
2386 }
2387
2388 static int service_watch_pid_file(Service *s) {
2389 int r;
2390
2391 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
2392
2393 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2394 if (r < 0)
2395 goto fail;
2396
2397 /* the pidfile might have appeared just before we set the watch */
2398 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
2399 service_retry_pid_file(s);
2400
2401 return 0;
2402 fail:
2403 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
2404 service_unwatch_pid_file(s);
2405 return r;
2406 }
2407
2408 static int service_demand_pid_file(Service *s) {
2409 PathSpec *ps;
2410
2411 assert(s->pid_file);
2412 assert(!s->pid_file_pathspec);
2413
2414 ps = new0(PathSpec, 1);
2415 if (!ps)
2416 return -ENOMEM;
2417
2418 ps->unit = UNIT(s);
2419 ps->path = strdup(s->pid_file);
2420 if (!ps->path) {
2421 free(ps);
2422 return -ENOMEM;
2423 }
2424
2425 path_kill_slashes(ps->path);
2426
2427 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2428 * keep their PID file open all the time. */
2429 ps->type = PATH_MODIFIED;
2430 ps->inotify_fd = -1;
2431
2432 s->pid_file_pathspec = ps;
2433
2434 return service_watch_pid_file(s);
2435 }
2436
2437 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2438 PathSpec *p = userdata;
2439 Service *s;
2440
2441 assert(p);
2442
2443 s = SERVICE(p->unit);
2444
2445 assert(s);
2446 assert(fd >= 0);
2447 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2448 assert(s->pid_file_pathspec);
2449 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2450
2451 log_unit_debug(UNIT(s), "inotify event");
2452
2453 if (path_spec_fd_event(p, events) < 0)
2454 goto fail;
2455
2456 if (service_retry_pid_file(s) == 0)
2457 return 0;
2458
2459 if (service_watch_pid_file(s) < 0)
2460 goto fail;
2461
2462 return 0;
2463
2464 fail:
2465 service_unwatch_pid_file(s);
2466 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2467 return 0;
2468 }
2469
2470 static void service_notify_cgroup_empty_event(Unit *u) {
2471 Service *s = SERVICE(u);
2472
2473 assert(u);
2474
2475 log_unit_debug(u, "cgroup is empty");
2476
2477 switch (s->state) {
2478
2479 /* Waiting for SIGCHLD is usually more interesting,
2480 * because it includes return codes/signals. Which is
2481 * why we ignore the cgroup events for most cases,
2482 * except when we don't know pid which to expect the
2483 * SIGCHLD for. */
2484
2485 case SERVICE_START:
2486 case SERVICE_START_POST:
2487 /* If we were hoping for the daemon to write its PID file,
2488 * we can give up now. */
2489 if (s->pid_file_pathspec) {
2490 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
2491
2492 service_unwatch_pid_file(s);
2493 if (s->state == SERVICE_START)
2494 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2495 else
2496 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2497 }
2498 break;
2499
2500 case SERVICE_RUNNING:
2501 /* service_enter_running() will figure out what to do */
2502 service_enter_running(s, SERVICE_SUCCESS);
2503 break;
2504
2505 case SERVICE_STOP_SIGABRT:
2506 case SERVICE_STOP_SIGTERM:
2507 case SERVICE_STOP_SIGKILL:
2508
2509 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2510 service_enter_stop_post(s, SERVICE_SUCCESS);
2511
2512 break;
2513
2514 case SERVICE_STOP_POST:
2515 case SERVICE_FINAL_SIGTERM:
2516 case SERVICE_FINAL_SIGKILL:
2517 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2518 service_enter_dead(s, SERVICE_SUCCESS, true);
2519
2520 break;
2521
2522 default:
2523 ;
2524 }
2525 }
2526
2527 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2528 Service *s = SERVICE(u);
2529 ServiceResult f;
2530
2531 assert(s);
2532 assert(pid >= 0);
2533
2534 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2535 is_clean_exit_lsb(code, status, &s->success_status))
2536 f = SERVICE_SUCCESS;
2537 else if (code == CLD_EXITED)
2538 f = SERVICE_FAILURE_EXIT_CODE;
2539 else if (code == CLD_KILLED)
2540 f = SERVICE_FAILURE_SIGNAL;
2541 else if (code == CLD_DUMPED)
2542 f = SERVICE_FAILURE_CORE_DUMP;
2543 else
2544 assert_not_reached("Unknown code");
2545
2546 if (s->main_pid == pid) {
2547 /* Forking services may occasionally move to a new PID.
2548 * As long as they update the PID file before exiting the old
2549 * PID, they're fine. */
2550 if (service_load_pid_file(s, false) == 0)
2551 return;
2552
2553 s->main_pid = 0;
2554 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2555
2556 if (s->main_command) {
2557 /* If this is not a forking service than the
2558 * main process got started and hence we copy
2559 * the exit status so that it is recorded both
2560 * as main and as control process exit
2561 * status */
2562
2563 s->main_command->exec_status = s->main_exec_status;
2564
2565 if (s->main_command->ignore)
2566 f = SERVICE_SUCCESS;
2567 } else if (s->exec_command[SERVICE_EXEC_START]) {
2568
2569 /* If this is a forked process, then we should
2570 * ignore the return value if this was
2571 * configured for the starter process */
2572
2573 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2574 f = SERVICE_SUCCESS;
2575 }
2576
2577 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2578 LOG_UNIT_ID(u),
2579 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2580 sigchld_code_to_string(code), status,
2581 strna(code == CLD_EXITED
2582 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2583 : signal_to_string(status))),
2584 "EXIT_CODE=%s", sigchld_code_to_string(code),
2585 "EXIT_STATUS=%i", status,
2586 NULL);
2587
2588 if (f != SERVICE_SUCCESS)
2589 s->result = f;
2590
2591 if (s->main_command &&
2592 s->main_command->command_next &&
2593 f == SERVICE_SUCCESS) {
2594
2595 /* There is another command to *
2596 * execute, so let's do that. */
2597
2598 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2599 service_run_next_main(s);
2600
2601 } else {
2602
2603 /* The service exited, so the service is officially
2604 * gone. */
2605 s->main_command = NULL;
2606
2607 switch (s->state) {
2608
2609 case SERVICE_START_POST:
2610 case SERVICE_RELOAD:
2611 case SERVICE_STOP:
2612 /* Need to wait until the operation is
2613 * done */
2614 break;
2615
2616 case SERVICE_START:
2617 if (s->type == SERVICE_ONESHOT) {
2618 /* This was our main goal, so let's go on */
2619 if (f == SERVICE_SUCCESS)
2620 service_enter_start_post(s);
2621 else
2622 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2623 break;
2624 }
2625
2626 /* Fall through */
2627
2628 case SERVICE_RUNNING:
2629 service_enter_running(s, f);
2630 break;
2631
2632 case SERVICE_STOP_SIGABRT:
2633 case SERVICE_STOP_SIGTERM:
2634 case SERVICE_STOP_SIGKILL:
2635
2636 if (!control_pid_good(s))
2637 service_enter_stop_post(s, f);
2638
2639 /* If there is still a control process, wait for that first */
2640 break;
2641
2642 case SERVICE_STOP_POST:
2643 case SERVICE_FINAL_SIGTERM:
2644 case SERVICE_FINAL_SIGKILL:
2645
2646 if (!control_pid_good(s))
2647 service_enter_dead(s, f, true);
2648 break;
2649
2650 default:
2651 assert_not_reached("Uh, main process died at wrong time.");
2652 }
2653 }
2654
2655 } else if (s->control_pid == pid) {
2656 s->control_pid = 0;
2657
2658 if (s->control_command) {
2659 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2660
2661 if (s->control_command->ignore)
2662 f = SERVICE_SUCCESS;
2663 }
2664
2665 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2666 "Control process exited, code=%s status=%i",
2667 sigchld_code_to_string(code), status);
2668
2669 if (f != SERVICE_SUCCESS)
2670 s->result = f;
2671
2672 /* Immediately get rid of the cgroup, so that the
2673 * kernel doesn't delay the cgroup empty messages for
2674 * the service cgroup any longer than necessary */
2675 service_kill_control_processes(s);
2676
2677 if (s->control_command &&
2678 s->control_command->command_next &&
2679 f == SERVICE_SUCCESS) {
2680
2681 /* There is another command to *
2682 * execute, so let's do that. */
2683
2684 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
2685 service_run_next_control(s);
2686
2687 } else {
2688 /* No further commands for this step, so let's
2689 * figure out what to do next */
2690
2691 s->control_command = NULL;
2692 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2693
2694 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
2695
2696 switch (s->state) {
2697
2698 case SERVICE_START_PRE:
2699 if (f == SERVICE_SUCCESS)
2700 service_enter_start(s);
2701 else
2702 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2703 break;
2704
2705 case SERVICE_START:
2706 if (s->type != SERVICE_FORKING)
2707 /* Maybe spurious event due to a reload that changed the type? */
2708 break;
2709
2710 if (f != SERVICE_SUCCESS) {
2711 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2712 break;
2713 }
2714
2715 if (s->pid_file) {
2716 bool has_start_post;
2717 int r;
2718
2719 /* Let's try to load the pid file here if we can.
2720 * The PID file might actually be created by a START_POST
2721 * script. In that case don't worry if the loading fails. */
2722
2723 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2724 r = service_load_pid_file(s, !has_start_post);
2725 if (!has_start_post && r < 0) {
2726 r = service_demand_pid_file(s);
2727 if (r < 0 || !cgroup_good(s))
2728 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2729 break;
2730 }
2731 } else
2732 (void) service_search_main_pid(s);
2733
2734 service_enter_start_post(s);
2735 break;
2736
2737 case SERVICE_START_POST:
2738 if (f != SERVICE_SUCCESS) {
2739 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2740 break;
2741 }
2742
2743 if (s->pid_file) {
2744 int r;
2745
2746 r = service_load_pid_file(s, true);
2747 if (r < 0) {
2748 r = service_demand_pid_file(s);
2749 if (r < 0 || !cgroup_good(s))
2750 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2751 break;
2752 }
2753 } else
2754 (void) service_search_main_pid(s);
2755
2756 service_enter_running(s, SERVICE_SUCCESS);
2757 break;
2758
2759 case SERVICE_RELOAD:
2760 if (f == SERVICE_SUCCESS) {
2761 service_load_pid_file(s, true);
2762 (void) service_search_main_pid(s);
2763 }
2764
2765 s->reload_result = f;
2766 service_enter_running(s, SERVICE_SUCCESS);
2767 break;
2768
2769 case SERVICE_STOP:
2770 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2771 break;
2772
2773 case SERVICE_STOP_SIGABRT:
2774 case SERVICE_STOP_SIGTERM:
2775 case SERVICE_STOP_SIGKILL:
2776 if (main_pid_good(s) <= 0)
2777 service_enter_stop_post(s, f);
2778
2779 /* If there is still a service
2780 * process around, wait until
2781 * that one quit, too */
2782 break;
2783
2784 case SERVICE_STOP_POST:
2785 case SERVICE_FINAL_SIGTERM:
2786 case SERVICE_FINAL_SIGKILL:
2787 if (main_pid_good(s) <= 0)
2788 service_enter_dead(s, f, true);
2789 break;
2790
2791 default:
2792 assert_not_reached("Uh, control process died at wrong time.");
2793 }
2794 }
2795 }
2796
2797 /* Notify clients about changed exit status */
2798 unit_add_to_dbus_queue(u);
2799
2800 /* We got one SIGCHLD for the service, let's watch all
2801 * processes that are now running of the service, and watch
2802 * that. Among the PIDs we then watch will be children
2803 * reassigned to us, which hopefully allows us to identify
2804 * when all children are gone */
2805 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2806 unit_watch_all_pids(u);
2807
2808 /* If the PID set is empty now, then let's finish this off */
2809 if (set_isempty(u->pids))
2810 service_notify_cgroup_empty_event(u);
2811 }
2812
2813 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2814 Service *s = SERVICE(userdata);
2815
2816 assert(s);
2817 assert(source == s->timer_event_source);
2818
2819 switch (s->state) {
2820
2821 case SERVICE_START_PRE:
2822 case SERVICE_START:
2823 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
2824 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2825 break;
2826
2827 case SERVICE_START_POST:
2828 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
2829 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2830 break;
2831
2832 case SERVICE_RUNNING:
2833 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2834 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2835 break;
2836
2837 case SERVICE_RELOAD:
2838 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
2839 service_kill_control_processes(s);
2840 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2841 service_enter_running(s, SERVICE_SUCCESS);
2842 break;
2843
2844 case SERVICE_STOP:
2845 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
2846 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2847 break;
2848
2849 case SERVICE_STOP_SIGABRT:
2850 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2851 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2852 break;
2853
2854 case SERVICE_STOP_SIGTERM:
2855 if (s->kill_context.send_sigkill) {
2856 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
2857 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2858 } else {
2859 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
2860 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2861 }
2862
2863 break;
2864
2865 case SERVICE_STOP_SIGKILL:
2866 /* Uh, we sent a SIGKILL and it is still not gone?
2867 * Must be something we cannot kill, so let's just be
2868 * weirded out and continue */
2869
2870 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
2871 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2872 break;
2873
2874 case SERVICE_STOP_POST:
2875 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
2876 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2877 break;
2878
2879 case SERVICE_FINAL_SIGTERM:
2880 if (s->kill_context.send_sigkill) {
2881 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
2882 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2883 } else {
2884 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
2885 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2886 }
2887
2888 break;
2889
2890 case SERVICE_FINAL_SIGKILL:
2891 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
2892 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2893 break;
2894
2895 case SERVICE_AUTO_RESTART:
2896 log_unit_info(UNIT(s),
2897 s->restart_usec > 0 ?
2898 "Service hold-off time over, scheduling restart." :
2899 "Service has no hold-off time, scheduling restart.");
2900 service_enter_restart(s);
2901 break;
2902
2903 default:
2904 assert_not_reached("Timeout at wrong time.");
2905 }
2906
2907 return 0;
2908 }
2909
2910 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2911 Service *s = SERVICE(userdata);
2912 char t[FORMAT_TIMESPAN_MAX];
2913
2914 assert(s);
2915 assert(source == s->watchdog_event_source);
2916
2917 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
2918 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2919
2920 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2921
2922 return 0;
2923 }
2924
2925 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
2926 Service *s = SERVICE(u);
2927 _cleanup_free_ char *cc = NULL;
2928 bool notify_dbus = false;
2929 const char *e;
2930
2931 assert(u);
2932
2933 cc = strv_join(tags, ", ");
2934
2935 if (s->notify_access == NOTIFY_NONE) {
2936 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
2937 return;
2938 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2939 if (s->main_pid != 0)
2940 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
2941 else
2942 log_unit_debug(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
2943 return;
2944 } else
2945 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
2946
2947 /* Interpret MAINPID= */
2948 e = strv_find_startswith(tags, "MAINPID=");
2949 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2950 if (parse_pid(e, &pid) < 0)
2951 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
2952 else {
2953 service_set_main_pid(s, pid);
2954 unit_watch_pid(UNIT(s), pid);
2955 notify_dbus = true;
2956 }
2957 }
2958
2959 /* Interpret RELOADING= */
2960 if (strv_find(tags, "RELOADING=1")) {
2961
2962 s->notify_state = NOTIFY_RELOADING;
2963
2964 if (s->state == SERVICE_RUNNING)
2965 service_enter_reload_by_notify(s);
2966
2967 notify_dbus = true;
2968 }
2969
2970 /* Interpret READY= */
2971 if (strv_find(tags, "READY=1")) {
2972
2973 s->notify_state = NOTIFY_READY;
2974
2975 /* Type=notify services inform us about completed
2976 * initialization with READY=1 */
2977 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2978 service_enter_start_post(s);
2979
2980 /* Sending READY=1 while we are reloading informs us
2981 * that the reloading is complete */
2982 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2983 service_enter_running(s, SERVICE_SUCCESS);
2984
2985 notify_dbus = true;
2986 }
2987
2988 /* Interpret STOPPING= */
2989 if (strv_find(tags, "STOPPING=1")) {
2990
2991 s->notify_state = NOTIFY_STOPPING;
2992
2993 if (s->state == SERVICE_RUNNING)
2994 service_enter_stop_by_notify(s);
2995
2996 notify_dbus = true;
2997 }
2998
2999 /* Interpret STATUS= */
3000 e = strv_find_startswith(tags, "STATUS=");
3001 if (e) {
3002 _cleanup_free_ char *t = NULL;
3003
3004 if (!isempty(e)) {
3005 if (!utf8_is_valid(e))
3006 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
3007 else {
3008 t = strdup(e);
3009 if (!t)
3010 log_oom();
3011 }
3012 }
3013
3014 if (!streq_ptr(s->status_text, t)) {
3015
3016 free(s->status_text);
3017 s->status_text = t;
3018 t = NULL;
3019
3020 notify_dbus = true;
3021 }
3022 }
3023
3024 /* Interpret ERRNO= */
3025 e = strv_find_startswith(tags, "ERRNO=");
3026 if (e) {
3027 int status_errno;
3028
3029 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
3030 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
3031 else {
3032 if (s->status_errno != status_errno) {
3033 s->status_errno = status_errno;
3034 notify_dbus = true;
3035 }
3036 }
3037 }
3038
3039 /* Interpret WATCHDOG= */
3040 if (strv_find(tags, "WATCHDOG=1"))
3041 service_reset_watchdog(s);
3042
3043 if (strv_find(tags, "FDSTORE=1")) {
3044 const char *name;
3045
3046 name = strv_find_startswith(tags, "FDNAME=");
3047 if (name && !fdname_is_valid(name)) {
3048 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
3049 name = NULL;
3050 }
3051
3052 service_add_fd_store_set(s, fds, name);
3053 }
3054
3055 /* Notify clients about changed status or main pid */
3056 if (notify_dbus)
3057 unit_add_to_dbus_queue(u);
3058 }
3059
3060 static int service_get_timeout(Unit *u, usec_t *timeout) {
3061 Service *s = SERVICE(u);
3062 uint64_t t;
3063 int r;
3064
3065 if (!s->timer_event_source)
3066 return 0;
3067
3068 r = sd_event_source_get_time(s->timer_event_source, &t);
3069 if (r < 0)
3070 return r;
3071 if (t == USEC_INFINITY)
3072 return 0;
3073
3074 *timeout = t;
3075 return 1;
3076 }
3077
3078 static void service_bus_name_owner_change(
3079 Unit *u,
3080 const char *name,
3081 const char *old_owner,
3082 const char *new_owner) {
3083
3084 Service *s = SERVICE(u);
3085 int r;
3086
3087 assert(s);
3088 assert(name);
3089
3090 assert(streq(s->bus_name, name));
3091 assert(old_owner || new_owner);
3092
3093 if (old_owner && new_owner)
3094 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
3095 else if (old_owner)
3096 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
3097 else
3098 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
3099
3100 s->bus_name_good = !!new_owner;
3101
3102 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3103 r = free_and_strdup(&s->bus_name_owner, new_owner);
3104 if (r < 0) {
3105 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
3106 return;
3107 }
3108
3109 if (s->type == SERVICE_DBUS) {
3110
3111 /* service_enter_running() will figure out what to
3112 * do */
3113 if (s->state == SERVICE_RUNNING)
3114 service_enter_running(s, SERVICE_SUCCESS);
3115 else if (s->state == SERVICE_START && new_owner)
3116 service_enter_start_post(s);
3117
3118 } else if (new_owner &&
3119 s->main_pid <= 0 &&
3120 (s->state == SERVICE_START ||
3121 s->state == SERVICE_START_POST ||
3122 s->state == SERVICE_RUNNING ||
3123 s->state == SERVICE_RELOAD)) {
3124
3125 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
3126 pid_t pid;
3127
3128 /* Try to acquire PID from bus service */
3129
3130 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3131 if (r >= 0)
3132 r = sd_bus_creds_get_pid(creds, &pid);
3133 if (r >= 0) {
3134 log_unit_debug(u, "D-Bus name %s is now owned by process %u", name, (unsigned) pid);
3135
3136 service_set_main_pid(s, pid);
3137 unit_watch_pid(UNIT(s), pid);
3138 }
3139 }
3140 }
3141
3142 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
3143 _cleanup_free_ char *peer = NULL;
3144 int r;
3145
3146 assert(s);
3147 assert(fd >= 0);
3148
3149 /* This is called by the socket code when instantiating a new
3150 * service for a stream socket and the socket needs to be
3151 * configured. */
3152
3153 if (UNIT(s)->load_state != UNIT_LOADED)
3154 return -EINVAL;
3155
3156 if (s->socket_fd >= 0)
3157 return -EBUSY;
3158
3159 if (s->state != SERVICE_DEAD)
3160 return -EAGAIN;
3161
3162 if (getpeername_pretty(fd, true, &peer) >= 0) {
3163
3164 if (UNIT(s)->description) {
3165 _cleanup_free_ char *a;
3166
3167 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
3168 if (!a)
3169 return -ENOMEM;
3170
3171 r = unit_set_description(UNIT(s), a);
3172 } else
3173 r = unit_set_description(UNIT(s), peer);
3174
3175 if (r < 0)
3176 return r;
3177 }
3178
3179 s->socket_fd = fd;
3180 s->socket_fd_selinux_context_net = selinux_context_net;
3181
3182 unit_ref_set(&s->accept_socket, UNIT(sock));
3183
3184 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3185 }
3186
3187 static void service_reset_failed(Unit *u) {
3188 Service *s = SERVICE(u);
3189
3190 assert(s);
3191
3192 if (s->state == SERVICE_FAILED)
3193 service_set_state(s, SERVICE_DEAD);
3194
3195 s->result = SERVICE_SUCCESS;
3196 s->reload_result = SERVICE_SUCCESS;
3197 }
3198
3199 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3200 Service *s = SERVICE(u);
3201
3202 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3203 }
3204
3205 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3206 [SERVICE_RESTART_NO] = "no",
3207 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3208 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3209 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3210 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3211 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3212 [SERVICE_RESTART_ALWAYS] = "always",
3213 };
3214
3215 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3216
3217 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3218 [SERVICE_SIMPLE] = "simple",
3219 [SERVICE_FORKING] = "forking",
3220 [SERVICE_ONESHOT] = "oneshot",
3221 [SERVICE_DBUS] = "dbus",
3222 [SERVICE_NOTIFY] = "notify",
3223 [SERVICE_IDLE] = "idle"
3224 };
3225
3226 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3227
3228 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3229 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3230 [SERVICE_EXEC_START] = "ExecStart",
3231 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3232 [SERVICE_EXEC_RELOAD] = "ExecReload",
3233 [SERVICE_EXEC_STOP] = "ExecStop",
3234 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3235 };
3236
3237 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3238
3239 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3240 [NOTIFY_NONE] = "none",
3241 [NOTIFY_MAIN] = "main",
3242 [NOTIFY_ALL] = "all"
3243 };
3244
3245 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3246
3247 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3248 [NOTIFY_UNKNOWN] = "unknown",
3249 [NOTIFY_READY] = "ready",
3250 [NOTIFY_RELOADING] = "reloading",
3251 [NOTIFY_STOPPING] = "stopping",
3252 };
3253
3254 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3255
3256 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3257 [SERVICE_SUCCESS] = "success",
3258 [SERVICE_FAILURE_RESOURCES] = "resources",
3259 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3260 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3261 [SERVICE_FAILURE_SIGNAL] = "signal",
3262 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3263 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3264 };
3265
3266 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3267
3268 const UnitVTable service_vtable = {
3269 .object_size = sizeof(Service),
3270 .exec_context_offset = offsetof(Service, exec_context),
3271 .cgroup_context_offset = offsetof(Service, cgroup_context),
3272 .kill_context_offset = offsetof(Service, kill_context),
3273 .exec_runtime_offset = offsetof(Service, exec_runtime),
3274
3275 .sections =
3276 "Unit\0"
3277 "Service\0"
3278 "Install\0",
3279 .private_section = "Service",
3280
3281 .init = service_init,
3282 .done = service_done,
3283 .load = service_load,
3284 .release_resources = service_release_resources,
3285
3286 .coldplug = service_coldplug,
3287
3288 .dump = service_dump,
3289
3290 .start = service_start,
3291 .stop = service_stop,
3292 .reload = service_reload,
3293
3294 .can_reload = service_can_reload,
3295
3296 .kill = service_kill,
3297
3298 .serialize = service_serialize,
3299 .deserialize_item = service_deserialize_item,
3300
3301 .active_state = service_active_state,
3302 .sub_state_to_string = service_sub_state_to_string,
3303
3304 .check_gc = service_check_gc,
3305
3306 .sigchld_event = service_sigchld_event,
3307
3308 .reset_failed = service_reset_failed,
3309
3310 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3311 .notify_message = service_notify_message,
3312
3313 .bus_name_owner_change = service_bus_name_owner_change,
3314
3315 .bus_vtable = bus_service_vtable,
3316 .bus_set_property = bus_service_set_property,
3317 .bus_commit_properties = bus_service_commit_properties,
3318
3319 .get_timeout = service_get_timeout,
3320 .can_transient = true,
3321
3322 .status_message_formats = {
3323 .starting_stopping = {
3324 [0] = "Starting %s...",
3325 [1] = "Stopping %s...",
3326 },
3327 .finished_start_job = {
3328 [JOB_DONE] = "Started %s.",
3329 [JOB_FAILED] = "Failed to start %s.",
3330 },
3331 .finished_stop_job = {
3332 [JOB_DONE] = "Stopped %s.",
3333 [JOB_FAILED] = "Stopped (with error) %s.",
3334 },
3335 },
3336 };