]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
core/service: drop return value that is always ignored anyway
[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 void 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;
845
846 if (!s->guess_main_pid)
847 return;
848
849 assert(s->main_pid <= 0);
850
851 if (unit_search_main_pid(UNIT(s), &pid) < 0)
852 return;
853
854 log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid);
855 if (service_set_main_pid(s, pid) < 0)
856 return;
857
858 r = unit_watch_pid(UNIT(s), pid);
859 if (r < 0)
860 /* FIXME: we need to do something here */
861 log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" from: %m", pid);
862 }
863
864 static void service_set_state(Service *s, ServiceState state) {
865 ServiceState old_state;
866 const UnitActiveState *table;
867
868 assert(s);
869
870 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
871
872 old_state = s->state;
873 s->state = state;
874
875 service_unwatch_pid_file(s);
876
877 if (!IN_SET(state,
878 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
879 SERVICE_RUNNING,
880 SERVICE_RELOAD,
881 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
882 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
883 SERVICE_AUTO_RESTART))
884 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
885
886 if (!IN_SET(state,
887 SERVICE_START, SERVICE_START_POST,
888 SERVICE_RUNNING, SERVICE_RELOAD,
889 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
890 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
891 service_unwatch_main_pid(s);
892 s->main_command = NULL;
893 }
894
895 if (!IN_SET(state,
896 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
897 SERVICE_RELOAD,
898 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
899 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
900 service_unwatch_control_pid(s);
901 s->control_command = NULL;
902 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
903 }
904
905 if (IN_SET(state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
906 unit_unwatch_all_pids(UNIT(s));
907
908 if (!IN_SET(state,
909 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
910 SERVICE_RUNNING, SERVICE_RELOAD,
911 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
912 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL) &&
913 !(state == SERVICE_DEAD && UNIT(s)->job)) {
914 service_close_socket_fd(s);
915 service_connection_unref(s);
916 }
917
918 if (!IN_SET(state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
919 service_stop_watchdog(s);
920
921 /* For the inactive states unit_notify() will trim the cgroup,
922 * but for exit we have to do that ourselves... */
923 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
924 unit_prune_cgroup(UNIT(s));
925
926 /* For remain_after_exit services, let's see if we can "release" the
927 * hold on the console, since unit_notify() only does that in case of
928 * change of state */
929 if (state == SERVICE_EXITED &&
930 s->remain_after_exit &&
931 UNIT(s)->manager->n_on_console > 0) {
932
933 ExecContext *ec;
934
935 ec = unit_get_exec_context(UNIT(s));
936 if (ec && exec_context_may_touch_console(ec)) {
937 Manager *m = UNIT(s)->manager;
938
939 m->n_on_console--;
940 if (m->n_on_console == 0)
941 /* unset no_console_output flag, since the console is free */
942 m->no_console_output = false;
943 }
944 }
945
946 if (old_state != state)
947 log_unit_debug(UNIT(s), "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
948
949 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
950 }
951
952 static usec_t service_coldplug_timeout(Service *s) {
953 assert(s);
954
955 switch (s->deserialized_state) {
956
957 case SERVICE_START_PRE:
958 case SERVICE_START:
959 case SERVICE_START_POST:
960 case SERVICE_RELOAD:
961 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
962
963 case SERVICE_RUNNING:
964 return usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec);
965
966 case SERVICE_STOP:
967 case SERVICE_STOP_SIGABRT:
968 case SERVICE_STOP_SIGTERM:
969 case SERVICE_STOP_SIGKILL:
970 case SERVICE_STOP_POST:
971 case SERVICE_FINAL_SIGTERM:
972 case SERVICE_FINAL_SIGKILL:
973 return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
974
975 case SERVICE_AUTO_RESTART:
976 return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic, s->restart_usec);
977
978 default:
979 return USEC_INFINITY;
980 }
981 }
982
983 static int service_coldplug(Unit *u) {
984 Service *s = SERVICE(u);
985 int r;
986
987 assert(s);
988 assert(s->state == SERVICE_DEAD);
989
990 if (s->deserialized_state == s->state)
991 return 0;
992
993 r = service_arm_timer(s, service_coldplug_timeout(s));
994 if (r < 0)
995 return r;
996
997 if (s->main_pid > 0 &&
998 pid_is_unwaited(s->main_pid) &&
999 ((s->deserialized_state == SERVICE_START && IN_SET(s->type, SERVICE_FORKING, SERVICE_DBUS, SERVICE_ONESHOT, SERVICE_NOTIFY)) ||
1000 IN_SET(s->deserialized_state,
1001 SERVICE_START, SERVICE_START_POST,
1002 SERVICE_RUNNING, SERVICE_RELOAD,
1003 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1004 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))) {
1005 r = unit_watch_pid(UNIT(s), s->main_pid);
1006 if (r < 0)
1007 return r;
1008 }
1009
1010 if (s->control_pid > 0 &&
1011 pid_is_unwaited(s->control_pid) &&
1012 IN_SET(s->deserialized_state,
1013 SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
1014 SERVICE_RELOAD,
1015 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1016 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL)) {
1017 r = unit_watch_pid(UNIT(s), s->control_pid);
1018 if (r < 0)
1019 return r;
1020 }
1021
1022 if (!IN_SET(s->deserialized_state, SERVICE_DEAD, SERVICE_FAILED, SERVICE_AUTO_RESTART))
1023 unit_watch_all_pids(UNIT(s));
1024
1025 if (IN_SET(s->deserialized_state, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1026 service_start_watchdog(s);
1027
1028 service_set_state(s, s->deserialized_state);
1029 return 0;
1030 }
1031
1032 static int service_collect_fds(Service *s, int **fds, char ***fd_names) {
1033 _cleanup_strv_free_ char **rfd_names = NULL;
1034 _cleanup_free_ int *rfds = NULL;
1035 int rn_fds = 0, r;
1036
1037 assert(s);
1038 assert(fds);
1039 assert(fd_names);
1040
1041 if (s->socket_fd >= 0) {
1042
1043 /* Pass the per-connection socket */
1044
1045 rfds = new(int, 1);
1046 if (!rfds)
1047 return -ENOMEM;
1048 rfds[0] = s->socket_fd;
1049
1050 rfd_names = strv_new("connection", NULL);
1051 if (!rfd_names)
1052 return -ENOMEM;
1053
1054 rn_fds = 1;
1055 } else {
1056 Iterator i;
1057 Unit *u;
1058
1059 /* Pass all our configured sockets for singleton services */
1060
1061 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1062 _cleanup_free_ int *cfds = NULL;
1063 Socket *sock;
1064 int cn_fds;
1065
1066 if (u->type != UNIT_SOCKET)
1067 continue;
1068
1069 sock = SOCKET(u);
1070
1071 cn_fds = socket_collect_fds(sock, &cfds);
1072 if (cn_fds < 0)
1073 return cn_fds;
1074
1075 if (cn_fds <= 0)
1076 continue;
1077
1078 if (!rfds) {
1079 rfds = cfds;
1080 rn_fds = cn_fds;
1081
1082 cfds = NULL;
1083 } else {
1084 int *t;
1085
1086 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
1087 if (!t)
1088 return -ENOMEM;
1089
1090 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
1091
1092 rfds = t;
1093 rn_fds += cn_fds;
1094 }
1095
1096 r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1097 if (r < 0)
1098 return r;
1099 }
1100 }
1101
1102 if (s->n_fd_store > 0) {
1103 ServiceFDStore *fs;
1104 char **nl;
1105 int *t;
1106
1107 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
1108 if (!t)
1109 return -ENOMEM;
1110
1111 rfds = t;
1112
1113 nl = realloc(rfd_names, (rn_fds + s->n_fd_store + 1) * sizeof(char*));
1114 if (!nl)
1115 return -ENOMEM;
1116
1117 rfd_names = nl;
1118
1119 LIST_FOREACH(fd_store, fs, s->fd_store) {
1120 rfds[rn_fds] = fs->fd;
1121 rfd_names[rn_fds] = strdup(strempty(fs->fdname));
1122 if (!rfd_names[rn_fds])
1123 return -ENOMEM;
1124
1125 rn_fds++;
1126 }
1127
1128 rfd_names[rn_fds] = NULL;
1129 }
1130
1131 *fds = rfds;
1132 *fd_names = rfd_names;
1133
1134 rfds = NULL;
1135 rfd_names = NULL;
1136
1137 return rn_fds;
1138 }
1139
1140 static int service_spawn(
1141 Service *s,
1142 ExecCommand *c,
1143 usec_t timeout,
1144 bool pass_fds,
1145 bool apply_permissions,
1146 bool apply_chroot,
1147 bool apply_tty_stdin,
1148 bool is_control,
1149 pid_t *_pid) {
1150
1151 _cleanup_strv_free_ char **argv = NULL, **final_env = NULL, **our_env = NULL, **fd_names = NULL;
1152 _cleanup_free_ int *fds = NULL;
1153 unsigned n_fds = 0, n_env = 0;
1154 const char *path;
1155 pid_t pid;
1156
1157 ExecParameters exec_params = {
1158 .apply_permissions = apply_permissions,
1159 .apply_chroot = apply_chroot,
1160 .apply_tty_stdin = apply_tty_stdin,
1161 .stdin_fd = -1,
1162 .stdout_fd = -1,
1163 .stderr_fd = -1,
1164 };
1165
1166 int r;
1167
1168 assert(s);
1169 assert(c);
1170 assert(_pid);
1171
1172 (void) unit_realize_cgroup(UNIT(s));
1173 if (s->reset_cpu_usage) {
1174 (void) unit_reset_cpu_usage(UNIT(s));
1175 s->reset_cpu_usage = false;
1176 }
1177
1178 r = unit_setup_exec_runtime(UNIT(s));
1179 if (r < 0)
1180 return r;
1181
1182 if (pass_fds ||
1183 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1184 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1185 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1186
1187 r = service_collect_fds(s, &fds, &fd_names);
1188 if (r < 0)
1189 return r;
1190
1191 n_fds = r;
1192 }
1193
1194 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), timeout));
1195 if (r < 0)
1196 return r;
1197
1198 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1199 if (r < 0)
1200 return r;
1201
1202 our_env = new0(char*, 6);
1203 if (!our_env)
1204 return -ENOMEM;
1205
1206 if (is_control ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1207 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1208 return -ENOMEM;
1209
1210 if (s->main_pid > 0)
1211 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0)
1212 return -ENOMEM;
1213
1214 if (UNIT(s)->manager->running_as != MANAGER_SYSTEM)
1215 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0)
1216 return -ENOMEM;
1217
1218 if (s->socket_fd >= 0) {
1219 union sockaddr_union sa;
1220 socklen_t salen = sizeof(sa);
1221
1222 r = getpeername(s->socket_fd, &sa.sa, &salen);
1223 if (r < 0)
1224 return -errno;
1225
1226 if (IN_SET(sa.sa.sa_family, AF_INET, AF_INET6)) {
1227 _cleanup_free_ char *addr = NULL;
1228 char *t;
1229 int port;
1230
1231 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1232 if (r < 0)
1233 return r;
1234
1235 t = strappend("REMOTE_ADDR=", addr);
1236 if (!t)
1237 return -ENOMEM;
1238 our_env[n_env++] = t;
1239
1240 port = sockaddr_port(&sa.sa);
1241 if (port < 0)
1242 return port;
1243
1244 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1245 return -ENOMEM;
1246 our_env[n_env++] = t;
1247 }
1248 }
1249
1250 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1251 if (!final_env)
1252 return -ENOMEM;
1253
1254 if (is_control && UNIT(s)->cgroup_path) {
1255 path = strjoina(UNIT(s)->cgroup_path, "/control");
1256 (void) cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1257 } else
1258 path = UNIT(s)->cgroup_path;
1259
1260 exec_params.argv = argv;
1261 exec_params.fds = fds;
1262 exec_params.fd_names = fd_names;
1263 exec_params.n_fds = n_fds;
1264 exec_params.environment = final_env;
1265 exec_params.confirm_spawn = UNIT(s)->manager->confirm_spawn;
1266 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1267 exec_params.cgroup_path = path;
1268 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1269 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1270 exec_params.watchdog_usec = s->watchdog_usec;
1271 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
1272 if (s->type == SERVICE_IDLE)
1273 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1274 exec_params.stdin_fd = s->stdin_fd;
1275 exec_params.stdout_fd = s->stdout_fd;
1276 exec_params.stderr_fd = s->stderr_fd;
1277
1278 r = exec_spawn(UNIT(s),
1279 c,
1280 &s->exec_context,
1281 &exec_params,
1282 s->exec_runtime,
1283 &pid);
1284 if (r < 0)
1285 return r;
1286
1287 r = unit_watch_pid(UNIT(s), pid);
1288 if (r < 0)
1289 /* FIXME: we need to do something here */
1290 return r;
1291
1292 *_pid = pid;
1293
1294 return 0;
1295 }
1296
1297 static int main_pid_good(Service *s) {
1298 assert(s);
1299
1300 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1301 * don't know */
1302
1303 /* If we know the pid file, then let's just check if it is
1304 * still valid */
1305 if (s->main_pid_known) {
1306
1307 /* If it's an alien child let's check if it is still
1308 * alive ... */
1309 if (s->main_pid_alien && s->main_pid > 0)
1310 return pid_is_alive(s->main_pid);
1311
1312 /* .. otherwise assume we'll get a SIGCHLD for it,
1313 * which we really should wait for to collect exit
1314 * status and code */
1315 return s->main_pid > 0;
1316 }
1317
1318 /* We don't know the pid */
1319 return -EAGAIN;
1320 }
1321
1322 _pure_ static int control_pid_good(Service *s) {
1323 assert(s);
1324
1325 return s->control_pid > 0;
1326 }
1327
1328 static int cgroup_good(Service *s) {
1329 int r;
1330
1331 assert(s);
1332
1333 if (!UNIT(s)->cgroup_path)
1334 return 0;
1335
1336 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
1337 if (r < 0)
1338 return r;
1339
1340 return !r;
1341 }
1342
1343 static bool service_shall_restart(Service *s) {
1344 assert(s);
1345
1346 /* Don't restart after manual stops */
1347 if (s->forbid_restart)
1348 return false;
1349
1350 /* Never restart if this is configured as special exception */
1351 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status))
1352 return false;
1353
1354 /* Restart if the exit code/status are configured as restart triggers */
1355 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status))
1356 return true;
1357
1358 switch (s->restart) {
1359
1360 case SERVICE_RESTART_NO:
1361 return false;
1362
1363 case SERVICE_RESTART_ALWAYS:
1364 return true;
1365
1366 case SERVICE_RESTART_ON_SUCCESS:
1367 return s->result == SERVICE_SUCCESS;
1368
1369 case SERVICE_RESTART_ON_FAILURE:
1370 return s->result != SERVICE_SUCCESS;
1371
1372 case SERVICE_RESTART_ON_ABNORMAL:
1373 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE);
1374
1375 case SERVICE_RESTART_ON_WATCHDOG:
1376 return s->result == SERVICE_FAILURE_WATCHDOG;
1377
1378 case SERVICE_RESTART_ON_ABORT:
1379 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1380
1381 default:
1382 assert_not_reached("unknown restart setting");
1383 }
1384 }
1385
1386 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1387 int r;
1388 assert(s);
1389
1390 if (f != SERVICE_SUCCESS)
1391 s->result = f;
1392
1393 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1394
1395 if (s->result != SERVICE_SUCCESS) {
1396 log_unit_warning(UNIT(s), "Failed with result '%s'.", service_result_to_string(s->result));
1397 failure_action(UNIT(s)->manager, s->failure_action, UNIT(s)->reboot_arg);
1398 }
1399
1400 if (allow_restart && service_shall_restart(s)) {
1401
1402 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1403 if (r < 0)
1404 goto fail;
1405
1406 service_set_state(s, SERVICE_AUTO_RESTART);
1407 }
1408
1409 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1410 s->forbid_restart = false;
1411
1412 /* We want fresh tmpdirs in case service is started again immediately */
1413 exec_runtime_destroy(s->exec_runtime);
1414 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1415
1416 /* Also, remove the runtime directory in */
1417 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1418
1419 /* Try to delete the pid file. At this point it will be
1420 * out-of-date, and some software might be confused by it, so
1421 * let's remove it. */
1422 if (s->pid_file)
1423 (void) unlink(s->pid_file);
1424
1425 return;
1426
1427 fail:
1428 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
1429 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1430 }
1431
1432 static void service_enter_stop_post(Service *s, ServiceResult f) {
1433 int r;
1434 assert(s);
1435
1436 if (f != SERVICE_SUCCESS)
1437 s->result = f;
1438
1439 service_unwatch_control_pid(s);
1440 unit_watch_all_pids(UNIT(s));
1441
1442 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1443 if (s->control_command) {
1444 s->control_command_id = SERVICE_EXEC_STOP_POST;
1445
1446 r = service_spawn(s,
1447 s->control_command,
1448 s->timeout_stop_usec,
1449 false,
1450 !s->permissions_start_only,
1451 !s->root_directory_start_only,
1452 true,
1453 true,
1454 &s->control_pid);
1455 if (r < 0)
1456 goto fail;
1457
1458 service_set_state(s, SERVICE_STOP_POST);
1459 } else
1460 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1461
1462 return;
1463
1464 fail:
1465 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
1466 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1467 }
1468
1469 static int state_to_kill_operation(ServiceState state) {
1470 switch (state) {
1471
1472 case SERVICE_STOP_SIGABRT:
1473 return KILL_ABORT;
1474
1475 case SERVICE_STOP_SIGTERM:
1476 case SERVICE_FINAL_SIGTERM:
1477 return KILL_TERMINATE;
1478
1479 case SERVICE_STOP_SIGKILL:
1480 case SERVICE_FINAL_SIGKILL:
1481 return KILL_KILL;
1482
1483 default:
1484 return _KILL_OPERATION_INVALID;
1485 }
1486 }
1487
1488 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1489 int r;
1490
1491 assert(s);
1492
1493 if (f != SERVICE_SUCCESS)
1494 s->result = f;
1495
1496 unit_watch_all_pids(UNIT(s));
1497
1498 r = unit_kill_context(
1499 UNIT(s),
1500 &s->kill_context,
1501 state_to_kill_operation(state),
1502 s->main_pid,
1503 s->control_pid,
1504 s->main_pid_alien);
1505
1506 if (r < 0)
1507 goto fail;
1508
1509 if (r > 0) {
1510 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1511 if (r < 0)
1512 goto fail;
1513
1514 service_set_state(s, state);
1515 } else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
1516 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1517 else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1518 service_enter_stop_post(s, SERVICE_SUCCESS);
1519 else if (state == SERVICE_FINAL_SIGTERM && s->kill_context.send_sigkill)
1520 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1521 else
1522 service_enter_dead(s, SERVICE_SUCCESS, true);
1523
1524 return;
1525
1526 fail:
1527 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
1528
1529 if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1530 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1531 else
1532 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1533 }
1534
1535 static void service_enter_stop_by_notify(Service *s) {
1536 assert(s);
1537
1538 unit_watch_all_pids(UNIT(s));
1539
1540 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1541
1542 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1543 service_set_state(s, SERVICE_STOP_SIGTERM);
1544 }
1545
1546 static void service_enter_stop(Service *s, ServiceResult f) {
1547 int r;
1548
1549 assert(s);
1550
1551 if (f != SERVICE_SUCCESS)
1552 s->result = f;
1553
1554 service_unwatch_control_pid(s);
1555 unit_watch_all_pids(UNIT(s));
1556
1557 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1558 if (s->control_command) {
1559 s->control_command_id = SERVICE_EXEC_STOP;
1560
1561 r = service_spawn(s,
1562 s->control_command,
1563 s->timeout_stop_usec,
1564 false,
1565 !s->permissions_start_only,
1566 !s->root_directory_start_only,
1567 false,
1568 true,
1569 &s->control_pid);
1570 if (r < 0)
1571 goto fail;
1572
1573 service_set_state(s, SERVICE_STOP);
1574 } else
1575 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1576
1577 return;
1578
1579 fail:
1580 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
1581 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1582 }
1583
1584 static bool service_good(Service *s) {
1585 int main_pid_ok;
1586 assert(s);
1587
1588 if (s->type == SERVICE_DBUS && !s->bus_name_good)
1589 return false;
1590
1591 main_pid_ok = main_pid_good(s);
1592 if (main_pid_ok > 0) /* It's alive */
1593 return true;
1594 if (main_pid_ok == 0) /* It's dead */
1595 return false;
1596
1597 /* OK, we don't know anything about the main PID, maybe
1598 * because there is none. Let's check the control group
1599 * instead. */
1600
1601 return cgroup_good(s) != 0;
1602 }
1603
1604 static void service_enter_running(Service *s, ServiceResult f) {
1605 assert(s);
1606
1607 if (f != SERVICE_SUCCESS)
1608 s->result = f;
1609
1610 service_unwatch_control_pid(s);
1611
1612 if (service_good(s)) {
1613
1614 /* If there are any queued up sd_notify()
1615 * notifications, process them now */
1616 if (s->notify_state == NOTIFY_RELOADING)
1617 service_enter_reload_by_notify(s);
1618 else if (s->notify_state == NOTIFY_STOPPING)
1619 service_enter_stop_by_notify(s);
1620 else {
1621 service_set_state(s, SERVICE_RUNNING);
1622 service_arm_timer(s, usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec));
1623 }
1624
1625 } else if (s->remain_after_exit)
1626 service_set_state(s, SERVICE_EXITED);
1627 else
1628 service_enter_stop(s, SERVICE_SUCCESS);
1629 }
1630
1631 static void service_enter_start_post(Service *s) {
1632 int r;
1633 assert(s);
1634
1635 service_unwatch_control_pid(s);
1636 service_reset_watchdog(s);
1637
1638 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1639 if (s->control_command) {
1640 s->control_command_id = SERVICE_EXEC_START_POST;
1641
1642 r = service_spawn(s,
1643 s->control_command,
1644 s->timeout_start_usec,
1645 false,
1646 !s->permissions_start_only,
1647 !s->root_directory_start_only,
1648 false,
1649 true,
1650 &s->control_pid);
1651 if (r < 0)
1652 goto fail;
1653
1654 service_set_state(s, SERVICE_START_POST);
1655 } else
1656 service_enter_running(s, SERVICE_SUCCESS);
1657
1658 return;
1659
1660 fail:
1661 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
1662 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1663 }
1664
1665 static void service_kill_control_processes(Service *s) {
1666 char *p;
1667
1668 if (!UNIT(s)->cgroup_path)
1669 return;
1670
1671 p = strjoina(UNIT(s)->cgroup_path, "/control");
1672 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
1673 }
1674
1675 static void service_enter_start(Service *s) {
1676 ExecCommand *c;
1677 usec_t timeout;
1678 pid_t pid;
1679 int r;
1680
1681 assert(s);
1682
1683 service_unwatch_control_pid(s);
1684 service_unwatch_main_pid(s);
1685
1686 /* We want to ensure that nobody leaks processes from
1687 * START_PRE here, so let's go on a killing spree, People
1688 * should not spawn long running processes from START_PRE. */
1689 service_kill_control_processes(s);
1690
1691 if (s->type == SERVICE_FORKING) {
1692 s->control_command_id = SERVICE_EXEC_START;
1693 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1694
1695 s->main_command = NULL;
1696 } else {
1697 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1698 s->control_command = NULL;
1699
1700 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1701 }
1702
1703 if (!c) {
1704 assert(s->type == SERVICE_ONESHOT);
1705 service_enter_start_post(s);
1706 return;
1707 }
1708
1709 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
1710 /* For simple + idle this is the main process. We don't apply any timeout here, but
1711 * service_enter_running() will later apply the .runtime_max_usec timeout. */
1712 timeout = USEC_INFINITY;
1713 else
1714 timeout = s->timeout_start_usec;
1715
1716 r = service_spawn(s,
1717 c,
1718 timeout,
1719 true,
1720 true,
1721 true,
1722 true,
1723 false,
1724 &pid);
1725 if (r < 0)
1726 goto fail;
1727
1728 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
1729 /* For simple services we immediately start
1730 * the START_POST binaries. */
1731
1732 service_set_main_pid(s, pid);
1733 service_enter_start_post(s);
1734
1735 } else if (s->type == SERVICE_FORKING) {
1736
1737 /* For forking services we wait until the start
1738 * process exited. */
1739
1740 s->control_pid = pid;
1741 service_set_state(s, SERVICE_START);
1742
1743 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY)) {
1744
1745 /* For oneshot services we wait until the start
1746 * process exited, too, but it is our main process. */
1747
1748 /* For D-Bus services we know the main pid right away,
1749 * but wait for the bus name to appear on the
1750 * bus. Notify services are similar. */
1751
1752 service_set_main_pid(s, pid);
1753 service_set_state(s, SERVICE_START);
1754 } else
1755 assert_not_reached("Unknown service type");
1756
1757 return;
1758
1759 fail:
1760 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
1761 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1762 }
1763
1764 static void service_enter_start_pre(Service *s) {
1765 int r;
1766
1767 assert(s);
1768
1769 service_unwatch_control_pid(s);
1770
1771 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1772 if (s->control_command) {
1773 /* Before we start anything, let's clear up what might
1774 * be left from previous runs. */
1775 service_kill_control_processes(s);
1776
1777 s->control_command_id = SERVICE_EXEC_START_PRE;
1778
1779 r = service_spawn(s,
1780 s->control_command,
1781 s->timeout_start_usec,
1782 false,
1783 !s->permissions_start_only,
1784 !s->root_directory_start_only,
1785 true,
1786 true,
1787 &s->control_pid);
1788 if (r < 0)
1789 goto fail;
1790
1791 service_set_state(s, SERVICE_START_PRE);
1792 } else
1793 service_enter_start(s);
1794
1795 return;
1796
1797 fail:
1798 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
1799 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1800 }
1801
1802 static void service_enter_restart(Service *s) {
1803 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1804 int r;
1805
1806 assert(s);
1807
1808 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1809 /* Don't restart things if we are going down anyway */
1810 log_unit_info(UNIT(s), "Stop job pending for unit, delaying automatic restart.");
1811
1812 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1813 if (r < 0)
1814 goto fail;
1815
1816 return;
1817 }
1818
1819 /* Any units that are bound to this service must also be
1820 * restarted. We use JOB_RESTART (instead of the more obvious
1821 * JOB_START) here so that those dependency jobs will be added
1822 * as well. */
1823 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, &error, NULL);
1824 if (r < 0)
1825 goto fail;
1826
1827 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1828 * it will be canceled as part of the service_stop() call that
1829 * is executed as part of JOB_RESTART. */
1830
1831 log_unit_debug(UNIT(s), "Scheduled restart job.");
1832 return;
1833
1834 fail:
1835 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, -r));
1836 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1837 }
1838
1839 static void service_enter_reload_by_notify(Service *s) {
1840 assert(s);
1841
1842 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_start_usec));
1843 service_set_state(s, SERVICE_RELOAD);
1844 }
1845
1846 static void service_enter_reload(Service *s) {
1847 int r;
1848
1849 assert(s);
1850
1851 service_unwatch_control_pid(s);
1852 s->reload_result = SERVICE_SUCCESS;
1853
1854 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1855 if (s->control_command) {
1856 s->control_command_id = SERVICE_EXEC_RELOAD;
1857
1858 r = service_spawn(s,
1859 s->control_command,
1860 s->timeout_start_usec,
1861 false,
1862 !s->permissions_start_only,
1863 !s->root_directory_start_only,
1864 false,
1865 true,
1866 &s->control_pid);
1867 if (r < 0)
1868 goto fail;
1869
1870 service_set_state(s, SERVICE_RELOAD);
1871 } else
1872 service_enter_running(s, SERVICE_SUCCESS);
1873
1874 return;
1875
1876 fail:
1877 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
1878 s->reload_result = SERVICE_FAILURE_RESOURCES;
1879 service_enter_running(s, SERVICE_SUCCESS);
1880 }
1881
1882 static void service_run_next_control(Service *s) {
1883 usec_t timeout;
1884 int r;
1885
1886 assert(s);
1887 assert(s->control_command);
1888 assert(s->control_command->command_next);
1889
1890 assert(s->control_command_id != SERVICE_EXEC_START);
1891
1892 s->control_command = s->control_command->command_next;
1893 service_unwatch_control_pid(s);
1894
1895 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1896 timeout = s->timeout_start_usec;
1897 else
1898 timeout = s->timeout_stop_usec;
1899
1900 r = service_spawn(s,
1901 s->control_command,
1902 timeout,
1903 false,
1904 !s->permissions_start_only,
1905 !s->root_directory_start_only,
1906 s->control_command_id == SERVICE_EXEC_START_PRE ||
1907 s->control_command_id == SERVICE_EXEC_STOP_POST,
1908 true,
1909 &s->control_pid);
1910 if (r < 0)
1911 goto fail;
1912
1913 return;
1914
1915 fail:
1916 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
1917
1918 if (s->state == SERVICE_START_PRE)
1919 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1920 else if (s->state == SERVICE_STOP)
1921 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1922 else if (s->state == SERVICE_STOP_POST)
1923 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1924 else if (s->state == SERVICE_RELOAD) {
1925 s->reload_result = SERVICE_FAILURE_RESOURCES;
1926 service_enter_running(s, SERVICE_SUCCESS);
1927 } else
1928 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1929 }
1930
1931 static void service_run_next_main(Service *s) {
1932 pid_t pid;
1933 int r;
1934
1935 assert(s);
1936 assert(s->main_command);
1937 assert(s->main_command->command_next);
1938 assert(s->type == SERVICE_ONESHOT);
1939
1940 s->main_command = s->main_command->command_next;
1941 service_unwatch_main_pid(s);
1942
1943 r = service_spawn(s,
1944 s->main_command,
1945 s->timeout_start_usec,
1946 true,
1947 true,
1948 true,
1949 true,
1950 false,
1951 &pid);
1952 if (r < 0)
1953 goto fail;
1954
1955 service_set_main_pid(s, pid);
1956
1957 return;
1958
1959 fail:
1960 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
1961 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1962 }
1963
1964 static int service_start(Unit *u) {
1965 Service *s = SERVICE(u);
1966
1967 assert(s);
1968
1969 /* We cannot fulfill this request right now, try again later
1970 * please! */
1971 if (IN_SET(s->state,
1972 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
1973 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
1974 return -EAGAIN;
1975
1976 /* Already on it! */
1977 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
1978 return 0;
1979
1980 /* A service that will be restarted must be stopped first to
1981 * trigger BindsTo and/or OnFailure dependencies. If a user
1982 * does not want to wait for the holdoff time to elapse, the
1983 * service should be manually restarted, not started. We
1984 * simply return EAGAIN here, so that any start jobs stay
1985 * queued, and assume that the auto restart timer will
1986 * eventually trigger the restart. */
1987 if (s->state == SERVICE_AUTO_RESTART)
1988 return -EAGAIN;
1989
1990 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
1991
1992 s->result = SERVICE_SUCCESS;
1993 s->reload_result = SERVICE_SUCCESS;
1994 s->main_pid_known = false;
1995 s->main_pid_alien = false;
1996 s->forbid_restart = false;
1997 s->reset_cpu_usage = true;
1998
1999 s->status_text = mfree(s->status_text);
2000 s->status_errno = 0;
2001
2002 s->notify_state = NOTIFY_UNKNOWN;
2003
2004 service_enter_start_pre(s);
2005 return 1;
2006 }
2007
2008 static int service_stop(Unit *u) {
2009 Service *s = SERVICE(u);
2010
2011 assert(s);
2012
2013 /* Don't create restart jobs from manual stops. */
2014 s->forbid_restart = true;
2015
2016 /* Already on it */
2017 if (IN_SET(s->state,
2018 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2019 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2020 return 0;
2021
2022 /* A restart will be scheduled or is in progress. */
2023 if (s->state == SERVICE_AUTO_RESTART) {
2024 service_set_state(s, SERVICE_DEAD);
2025 return 0;
2026 }
2027
2028 /* If there's already something running we go directly into
2029 * kill mode. */
2030 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD)) {
2031 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2032 return 0;
2033 }
2034
2035 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
2036
2037 service_enter_stop(s, SERVICE_SUCCESS);
2038 return 1;
2039 }
2040
2041 static int service_reload(Unit *u) {
2042 Service *s = SERVICE(u);
2043
2044 assert(s);
2045
2046 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2047
2048 service_enter_reload(s);
2049 return 1;
2050 }
2051
2052 _pure_ static bool service_can_reload(Unit *u) {
2053 Service *s = SERVICE(u);
2054
2055 assert(s);
2056
2057 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2058 }
2059
2060 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2061 Service *s = SERVICE(u);
2062 ServiceFDStore *fs;
2063 int r;
2064
2065 assert(u);
2066 assert(f);
2067 assert(fds);
2068
2069 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2070 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2071 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2072
2073 if (s->control_pid > 0)
2074 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
2075
2076 if (s->main_pid_known && s->main_pid > 0)
2077 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
2078
2079 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2080 unit_serialize_item(u, f, "bus-name-good", yes_no(s->bus_name_good));
2081 unit_serialize_item(u, f, "bus-name-owner", s->bus_name_owner);
2082
2083 r = unit_serialize_item_escaped(u, f, "status-text", s->status_text);
2084 if (r < 0)
2085 return r;
2086
2087 /* FIXME: There's a minor uncleanliness here: if there are
2088 * multiple commands attached here, we will start from the
2089 * first one again */
2090 if (s->control_command_id >= 0)
2091 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2092
2093 r = unit_serialize_item_fd(u, f, fds, "stdin-fd", s->stdin_fd);
2094 if (r < 0)
2095 return r;
2096 r = unit_serialize_item_fd(u, f, fds, "stdout-fd", s->stdout_fd);
2097 if (r < 0)
2098 return r;
2099 r = unit_serialize_item_fd(u, f, fds, "stderr-fd", s->stderr_fd);
2100 if (r < 0)
2101 return r;
2102
2103 r = unit_serialize_item_fd(u, f, fds, "socket-fd", s->socket_fd);
2104 if (r < 0)
2105 return r;
2106
2107 LIST_FOREACH(fd_store, fs, s->fd_store) {
2108 _cleanup_free_ char *c = NULL;
2109 int copy;
2110
2111 copy = fdset_put_dup(fds, fs->fd);
2112 if (copy < 0)
2113 return copy;
2114
2115 c = cescape(fs->fdname);
2116
2117 unit_serialize_item_format(u, f, "fd-store-fd", "%i %s", copy, strempty(c));
2118 }
2119
2120 if (s->main_exec_status.pid > 0) {
2121 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2122 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2123 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2124
2125 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2126 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2127 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2128 }
2129 }
2130
2131 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2132
2133 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2134
2135 return 0;
2136 }
2137
2138 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2139 Service *s = SERVICE(u);
2140 int r;
2141
2142 assert(u);
2143 assert(key);
2144 assert(value);
2145 assert(fds);
2146
2147 if (streq(key, "state")) {
2148 ServiceState state;
2149
2150 state = service_state_from_string(value);
2151 if (state < 0)
2152 log_unit_debug(u, "Failed to parse state value: %s", value);
2153 else
2154 s->deserialized_state = state;
2155 } else if (streq(key, "result")) {
2156 ServiceResult f;
2157
2158 f = service_result_from_string(value);
2159 if (f < 0)
2160 log_unit_debug(u, "Failed to parse result value: %s", value);
2161 else if (f != SERVICE_SUCCESS)
2162 s->result = f;
2163
2164 } else if (streq(key, "reload-result")) {
2165 ServiceResult f;
2166
2167 f = service_result_from_string(value);
2168 if (f < 0)
2169 log_unit_debug(u, "Failed to parse reload result value: %s", value);
2170 else if (f != SERVICE_SUCCESS)
2171 s->reload_result = f;
2172
2173 } else if (streq(key, "control-pid")) {
2174 pid_t pid;
2175
2176 if (parse_pid(value, &pid) < 0)
2177 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2178 else
2179 s->control_pid = pid;
2180 } else if (streq(key, "main-pid")) {
2181 pid_t pid;
2182
2183 if (parse_pid(value, &pid) < 0)
2184 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2185 else {
2186 service_set_main_pid(s, pid);
2187 unit_watch_pid(UNIT(s), pid);
2188 }
2189 } else if (streq(key, "main-pid-known")) {
2190 int b;
2191
2192 b = parse_boolean(value);
2193 if (b < 0)
2194 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2195 else
2196 s->main_pid_known = b;
2197 } else if (streq(key, "bus-name-good")) {
2198 int b;
2199
2200 b = parse_boolean(value);
2201 if (b < 0)
2202 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2203 else
2204 s->bus_name_good = b;
2205 } else if (streq(key, "bus-name-owner")) {
2206 r = free_and_strdup(&s->bus_name_owner, value);
2207 if (r < 0)
2208 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
2209 } else if (streq(key, "status-text")) {
2210 char *t;
2211
2212 r = cunescape(value, 0, &t);
2213 if (r < 0)
2214 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
2215 else {
2216 free(s->status_text);
2217 s->status_text = t;
2218 }
2219
2220 } else if (streq(key, "control-command")) {
2221 ServiceExecCommand id;
2222
2223 id = service_exec_command_from_string(value);
2224 if (id < 0)
2225 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
2226 else {
2227 s->control_command_id = id;
2228 s->control_command = s->exec_command[id];
2229 }
2230 } else if (streq(key, "socket-fd")) {
2231 int fd;
2232
2233 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2234 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
2235 else {
2236 asynchronous_close(s->socket_fd);
2237 s->socket_fd = fdset_remove(fds, fd);
2238 }
2239 } else if (streq(key, "fd-store-fd")) {
2240 const char *fdv;
2241 size_t pf;
2242 int fd;
2243
2244 pf = strcspn(value, WHITESPACE);
2245 fdv = strndupa(value, pf);
2246
2247 if (safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2248 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2249 else {
2250 _cleanup_free_ char *t = NULL;
2251 const char *fdn;
2252
2253 fdn = value + pf;
2254 fdn += strspn(fdn, WHITESPACE);
2255 (void) cunescape(fdn, 0, &t);
2256
2257 r = service_add_fd_store(s, fd, t);
2258 if (r < 0)
2259 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
2260 else if (r > 0)
2261 fdset_remove(fds, fd);
2262 }
2263
2264 } else if (streq(key, "main-exec-status-pid")) {
2265 pid_t pid;
2266
2267 if (parse_pid(value, &pid) < 0)
2268 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
2269 else
2270 s->main_exec_status.pid = pid;
2271 } else if (streq(key, "main-exec-status-code")) {
2272 int i;
2273
2274 if (safe_atoi(value, &i) < 0)
2275 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
2276 else
2277 s->main_exec_status.code = i;
2278 } else if (streq(key, "main-exec-status-status")) {
2279 int i;
2280
2281 if (safe_atoi(value, &i) < 0)
2282 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
2283 else
2284 s->main_exec_status.status = i;
2285 } else if (streq(key, "main-exec-status-start"))
2286 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2287 else if (streq(key, "main-exec-status-exit"))
2288 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2289 else if (streq(key, "watchdog-timestamp"))
2290 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2291 else if (streq(key, "forbid-restart")) {
2292 int b;
2293
2294 b = parse_boolean(value);
2295 if (b < 0)
2296 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
2297 else
2298 s->forbid_restart = b;
2299 } else if (streq(key, "stdin-fd")) {
2300 int fd;
2301
2302 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2303 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
2304 else {
2305 asynchronous_close(s->stdin_fd);
2306 s->stdin_fd = fdset_remove(fds, fd);
2307 s->exec_context.stdio_as_fds = true;
2308 }
2309 } else if (streq(key, "stdout-fd")) {
2310 int fd;
2311
2312 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2313 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
2314 else {
2315 asynchronous_close(s->stdout_fd);
2316 s->stdout_fd = fdset_remove(fds, fd);
2317 s->exec_context.stdio_as_fds = true;
2318 }
2319 } else if (streq(key, "stderr-fd")) {
2320 int fd;
2321
2322 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2323 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
2324 else {
2325 asynchronous_close(s->stderr_fd);
2326 s->stderr_fd = fdset_remove(fds, fd);
2327 s->exec_context.stdio_as_fds = true;
2328 }
2329 } else
2330 log_unit_debug(u, "Unknown serialization key: %s", key);
2331
2332 return 0;
2333 }
2334
2335 _pure_ static UnitActiveState service_active_state(Unit *u) {
2336 const UnitActiveState *table;
2337
2338 assert(u);
2339
2340 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2341
2342 return table[SERVICE(u)->state];
2343 }
2344
2345 static const char *service_sub_state_to_string(Unit *u) {
2346 assert(u);
2347
2348 return service_state_to_string(SERVICE(u)->state);
2349 }
2350
2351 static bool service_check_gc(Unit *u) {
2352 Service *s = SERVICE(u);
2353
2354 assert(s);
2355
2356 /* Never clean up services that still have a process around,
2357 * even if the service is formally dead. */
2358 if (cgroup_good(s) > 0 ||
2359 main_pid_good(s) > 0 ||
2360 control_pid_good(s) > 0)
2361 return true;
2362
2363 return false;
2364 }
2365
2366 static int service_retry_pid_file(Service *s) {
2367 int r;
2368
2369 assert(s->pid_file);
2370 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2371
2372 r = service_load_pid_file(s, false);
2373 if (r < 0)
2374 return r;
2375
2376 service_unwatch_pid_file(s);
2377
2378 service_enter_running(s, SERVICE_SUCCESS);
2379 return 0;
2380 }
2381
2382 static int service_watch_pid_file(Service *s) {
2383 int r;
2384
2385 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
2386
2387 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2388 if (r < 0)
2389 goto fail;
2390
2391 /* the pidfile might have appeared just before we set the watch */
2392 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
2393 service_retry_pid_file(s);
2394
2395 return 0;
2396 fail:
2397 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
2398 service_unwatch_pid_file(s);
2399 return r;
2400 }
2401
2402 static int service_demand_pid_file(Service *s) {
2403 PathSpec *ps;
2404
2405 assert(s->pid_file);
2406 assert(!s->pid_file_pathspec);
2407
2408 ps = new0(PathSpec, 1);
2409 if (!ps)
2410 return -ENOMEM;
2411
2412 ps->unit = UNIT(s);
2413 ps->path = strdup(s->pid_file);
2414 if (!ps->path) {
2415 free(ps);
2416 return -ENOMEM;
2417 }
2418
2419 path_kill_slashes(ps->path);
2420
2421 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2422 * keep their PID file open all the time. */
2423 ps->type = PATH_MODIFIED;
2424 ps->inotify_fd = -1;
2425
2426 s->pid_file_pathspec = ps;
2427
2428 return service_watch_pid_file(s);
2429 }
2430
2431 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2432 PathSpec *p = userdata;
2433 Service *s;
2434
2435 assert(p);
2436
2437 s = SERVICE(p->unit);
2438
2439 assert(s);
2440 assert(fd >= 0);
2441 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2442 assert(s->pid_file_pathspec);
2443 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2444
2445 log_unit_debug(UNIT(s), "inotify event");
2446
2447 if (path_spec_fd_event(p, events) < 0)
2448 goto fail;
2449
2450 if (service_retry_pid_file(s) == 0)
2451 return 0;
2452
2453 if (service_watch_pid_file(s) < 0)
2454 goto fail;
2455
2456 return 0;
2457
2458 fail:
2459 service_unwatch_pid_file(s);
2460 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2461 return 0;
2462 }
2463
2464 static void service_notify_cgroup_empty_event(Unit *u) {
2465 Service *s = SERVICE(u);
2466
2467 assert(u);
2468
2469 log_unit_debug(u, "cgroup is empty");
2470
2471 switch (s->state) {
2472
2473 /* Waiting for SIGCHLD is usually more interesting,
2474 * because it includes return codes/signals. Which is
2475 * why we ignore the cgroup events for most cases,
2476 * except when we don't know pid which to expect the
2477 * SIGCHLD for. */
2478
2479 case SERVICE_START:
2480 case SERVICE_START_POST:
2481 /* If we were hoping for the daemon to write its PID file,
2482 * we can give up now. */
2483 if (s->pid_file_pathspec) {
2484 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
2485
2486 service_unwatch_pid_file(s);
2487 if (s->state == SERVICE_START)
2488 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2489 else
2490 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2491 }
2492 break;
2493
2494 case SERVICE_RUNNING:
2495 /* service_enter_running() will figure out what to do */
2496 service_enter_running(s, SERVICE_SUCCESS);
2497 break;
2498
2499 case SERVICE_STOP_SIGABRT:
2500 case SERVICE_STOP_SIGTERM:
2501 case SERVICE_STOP_SIGKILL:
2502
2503 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2504 service_enter_stop_post(s, SERVICE_SUCCESS);
2505
2506 break;
2507
2508 case SERVICE_STOP_POST:
2509 case SERVICE_FINAL_SIGTERM:
2510 case SERVICE_FINAL_SIGKILL:
2511 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2512 service_enter_dead(s, SERVICE_SUCCESS, true);
2513
2514 break;
2515
2516 default:
2517 ;
2518 }
2519 }
2520
2521 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2522 Service *s = SERVICE(u);
2523 ServiceResult f;
2524
2525 assert(s);
2526 assert(pid >= 0);
2527
2528 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2529 is_clean_exit_lsb(code, status, &s->success_status))
2530 f = SERVICE_SUCCESS;
2531 else if (code == CLD_EXITED)
2532 f = SERVICE_FAILURE_EXIT_CODE;
2533 else if (code == CLD_KILLED)
2534 f = SERVICE_FAILURE_SIGNAL;
2535 else if (code == CLD_DUMPED)
2536 f = SERVICE_FAILURE_CORE_DUMP;
2537 else
2538 assert_not_reached("Unknown code");
2539
2540 if (s->main_pid == pid) {
2541 /* Forking services may occasionally move to a new PID.
2542 * As long as they update the PID file before exiting the old
2543 * PID, they're fine. */
2544 if (service_load_pid_file(s, false) == 0)
2545 return;
2546
2547 s->main_pid = 0;
2548 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2549
2550 if (s->main_command) {
2551 /* If this is not a forking service than the
2552 * main process got started and hence we copy
2553 * the exit status so that it is recorded both
2554 * as main and as control process exit
2555 * status */
2556
2557 s->main_command->exec_status = s->main_exec_status;
2558
2559 if (s->main_command->ignore)
2560 f = SERVICE_SUCCESS;
2561 } else if (s->exec_command[SERVICE_EXEC_START]) {
2562
2563 /* If this is a forked process, then we should
2564 * ignore the return value if this was
2565 * configured for the starter process */
2566
2567 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2568 f = SERVICE_SUCCESS;
2569 }
2570
2571 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2572 LOG_UNIT_ID(u),
2573 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2574 sigchld_code_to_string(code), status,
2575 strna(code == CLD_EXITED
2576 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2577 : signal_to_string(status))),
2578 "EXIT_CODE=%s", sigchld_code_to_string(code),
2579 "EXIT_STATUS=%i", status,
2580 NULL);
2581
2582 if (f != SERVICE_SUCCESS)
2583 s->result = f;
2584
2585 if (s->main_command &&
2586 s->main_command->command_next &&
2587 f == SERVICE_SUCCESS) {
2588
2589 /* There is another command to *
2590 * execute, so let's do that. */
2591
2592 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2593 service_run_next_main(s);
2594
2595 } else {
2596
2597 /* The service exited, so the service is officially
2598 * gone. */
2599 s->main_command = NULL;
2600
2601 switch (s->state) {
2602
2603 case SERVICE_START_POST:
2604 case SERVICE_RELOAD:
2605 case SERVICE_STOP:
2606 /* Need to wait until the operation is
2607 * done */
2608 break;
2609
2610 case SERVICE_START:
2611 if (s->type == SERVICE_ONESHOT) {
2612 /* This was our main goal, so let's go on */
2613 if (f == SERVICE_SUCCESS)
2614 service_enter_start_post(s);
2615 else
2616 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2617 break;
2618 }
2619
2620 /* Fall through */
2621
2622 case SERVICE_RUNNING:
2623 service_enter_running(s, f);
2624 break;
2625
2626 case SERVICE_STOP_SIGABRT:
2627 case SERVICE_STOP_SIGTERM:
2628 case SERVICE_STOP_SIGKILL:
2629
2630 if (!control_pid_good(s))
2631 service_enter_stop_post(s, f);
2632
2633 /* If there is still a control process, wait for that first */
2634 break;
2635
2636 case SERVICE_STOP_POST:
2637 case SERVICE_FINAL_SIGTERM:
2638 case SERVICE_FINAL_SIGKILL:
2639
2640 if (!control_pid_good(s))
2641 service_enter_dead(s, f, true);
2642 break;
2643
2644 default:
2645 assert_not_reached("Uh, main process died at wrong time.");
2646 }
2647 }
2648
2649 } else if (s->control_pid == pid) {
2650 s->control_pid = 0;
2651
2652 if (s->control_command) {
2653 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2654
2655 if (s->control_command->ignore)
2656 f = SERVICE_SUCCESS;
2657 }
2658
2659 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2660 "Control process exited, code=%s status=%i",
2661 sigchld_code_to_string(code), status);
2662
2663 if (f != SERVICE_SUCCESS)
2664 s->result = f;
2665
2666 /* Immediately get rid of the cgroup, so that the
2667 * kernel doesn't delay the cgroup empty messages for
2668 * the service cgroup any longer than necessary */
2669 service_kill_control_processes(s);
2670
2671 if (s->control_command &&
2672 s->control_command->command_next &&
2673 f == SERVICE_SUCCESS) {
2674
2675 /* There is another command to *
2676 * execute, so let's do that. */
2677
2678 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
2679 service_run_next_control(s);
2680
2681 } else {
2682 /* No further commands for this step, so let's
2683 * figure out what to do next */
2684
2685 s->control_command = NULL;
2686 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2687
2688 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
2689
2690 switch (s->state) {
2691
2692 case SERVICE_START_PRE:
2693 if (f == SERVICE_SUCCESS)
2694 service_enter_start(s);
2695 else
2696 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2697 break;
2698
2699 case SERVICE_START:
2700 if (s->type != SERVICE_FORKING)
2701 /* Maybe spurious event due to a reload that changed the type? */
2702 break;
2703
2704 if (f != SERVICE_SUCCESS) {
2705 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2706 break;
2707 }
2708
2709 if (s->pid_file) {
2710 bool has_start_post;
2711 int r;
2712
2713 /* Let's try to load the pid file here if we can.
2714 * The PID file might actually be created by a START_POST
2715 * script. In that case don't worry if the loading fails. */
2716
2717 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2718 r = service_load_pid_file(s, !has_start_post);
2719 if (!has_start_post && r < 0) {
2720 r = service_demand_pid_file(s);
2721 if (r < 0 || !cgroup_good(s))
2722 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2723 break;
2724 }
2725 } else
2726 service_search_main_pid(s);
2727
2728 service_enter_start_post(s);
2729 break;
2730
2731 case SERVICE_START_POST:
2732 if (f != SERVICE_SUCCESS) {
2733 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2734 break;
2735 }
2736
2737 if (s->pid_file) {
2738 int r;
2739
2740 r = service_load_pid_file(s, true);
2741 if (r < 0) {
2742 r = service_demand_pid_file(s);
2743 if (r < 0 || !cgroup_good(s))
2744 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2745 break;
2746 }
2747 } else
2748 service_search_main_pid(s);
2749
2750 service_enter_running(s, SERVICE_SUCCESS);
2751 break;
2752
2753 case SERVICE_RELOAD:
2754 if (f == SERVICE_SUCCESS) {
2755 service_load_pid_file(s, true);
2756 service_search_main_pid(s);
2757 }
2758
2759 s->reload_result = f;
2760 service_enter_running(s, SERVICE_SUCCESS);
2761 break;
2762
2763 case SERVICE_STOP:
2764 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2765 break;
2766
2767 case SERVICE_STOP_SIGABRT:
2768 case SERVICE_STOP_SIGTERM:
2769 case SERVICE_STOP_SIGKILL:
2770 if (main_pid_good(s) <= 0)
2771 service_enter_stop_post(s, f);
2772
2773 /* If there is still a service
2774 * process around, wait until
2775 * that one quit, too */
2776 break;
2777
2778 case SERVICE_STOP_POST:
2779 case SERVICE_FINAL_SIGTERM:
2780 case SERVICE_FINAL_SIGKILL:
2781 if (main_pid_good(s) <= 0)
2782 service_enter_dead(s, f, true);
2783 break;
2784
2785 default:
2786 assert_not_reached("Uh, control process died at wrong time.");
2787 }
2788 }
2789 }
2790
2791 /* Notify clients about changed exit status */
2792 unit_add_to_dbus_queue(u);
2793
2794 /* We got one SIGCHLD for the service, let's watch all
2795 * processes that are now running of the service, and watch
2796 * that. Among the PIDs we then watch will be children
2797 * reassigned to us, which hopefully allows us to identify
2798 * when all children are gone */
2799 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2800 unit_watch_all_pids(u);
2801
2802 /* If the PID set is empty now, then let's finish this off */
2803 if (set_isempty(u->pids))
2804 service_notify_cgroup_empty_event(u);
2805 }
2806
2807 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2808 Service *s = SERVICE(userdata);
2809
2810 assert(s);
2811 assert(source == s->timer_event_source);
2812
2813 switch (s->state) {
2814
2815 case SERVICE_START_PRE:
2816 case SERVICE_START:
2817 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
2818 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2819 break;
2820
2821 case SERVICE_START_POST:
2822 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
2823 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2824 break;
2825
2826 case SERVICE_RUNNING:
2827 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2828 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2829 break;
2830
2831 case SERVICE_RELOAD:
2832 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
2833 service_kill_control_processes(s);
2834 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2835 service_enter_running(s, SERVICE_SUCCESS);
2836 break;
2837
2838 case SERVICE_STOP:
2839 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
2840 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2841 break;
2842
2843 case SERVICE_STOP_SIGABRT:
2844 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2845 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2846 break;
2847
2848 case SERVICE_STOP_SIGTERM:
2849 if (s->kill_context.send_sigkill) {
2850 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
2851 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2852 } else {
2853 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
2854 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2855 }
2856
2857 break;
2858
2859 case SERVICE_STOP_SIGKILL:
2860 /* Uh, we sent a SIGKILL and it is still not gone?
2861 * Must be something we cannot kill, so let's just be
2862 * weirded out and continue */
2863
2864 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
2865 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2866 break;
2867
2868 case SERVICE_STOP_POST:
2869 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
2870 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2871 break;
2872
2873 case SERVICE_FINAL_SIGTERM:
2874 if (s->kill_context.send_sigkill) {
2875 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
2876 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2877 } else {
2878 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
2879 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2880 }
2881
2882 break;
2883
2884 case SERVICE_FINAL_SIGKILL:
2885 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
2886 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2887 break;
2888
2889 case SERVICE_AUTO_RESTART:
2890 log_unit_info(UNIT(s),
2891 s->restart_usec > 0 ?
2892 "Service hold-off time over, scheduling restart." :
2893 "Service has no hold-off time, scheduling restart.");
2894 service_enter_restart(s);
2895 break;
2896
2897 default:
2898 assert_not_reached("Timeout at wrong time.");
2899 }
2900
2901 return 0;
2902 }
2903
2904 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
2905 Service *s = SERVICE(userdata);
2906 char t[FORMAT_TIMESPAN_MAX];
2907
2908 assert(s);
2909 assert(source == s->watchdog_event_source);
2910
2911 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
2912 format_timespan(t, sizeof(t), s->watchdog_usec, 1));
2913
2914 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
2915
2916 return 0;
2917 }
2918
2919 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
2920 Service *s = SERVICE(u);
2921 _cleanup_free_ char *cc = NULL;
2922 bool notify_dbus = false;
2923 const char *e;
2924
2925 assert(u);
2926
2927 cc = strv_join(tags, ", ");
2928
2929 if (s->notify_access == NOTIFY_NONE) {
2930 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
2931 return;
2932 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
2933 if (s->main_pid != 0)
2934 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
2935 else
2936 log_unit_debug(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
2937 return;
2938 } else
2939 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
2940
2941 /* Interpret MAINPID= */
2942 e = strv_find_startswith(tags, "MAINPID=");
2943 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
2944 if (parse_pid(e, &pid) < 0)
2945 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
2946 else {
2947 service_set_main_pid(s, pid);
2948 unit_watch_pid(UNIT(s), pid);
2949 notify_dbus = true;
2950 }
2951 }
2952
2953 /* Interpret RELOADING= */
2954 if (strv_find(tags, "RELOADING=1")) {
2955
2956 s->notify_state = NOTIFY_RELOADING;
2957
2958 if (s->state == SERVICE_RUNNING)
2959 service_enter_reload_by_notify(s);
2960
2961 notify_dbus = true;
2962 }
2963
2964 /* Interpret READY= */
2965 if (strv_find(tags, "READY=1")) {
2966
2967 s->notify_state = NOTIFY_READY;
2968
2969 /* Type=notify services inform us about completed
2970 * initialization with READY=1 */
2971 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
2972 service_enter_start_post(s);
2973
2974 /* Sending READY=1 while we are reloading informs us
2975 * that the reloading is complete */
2976 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
2977 service_enter_running(s, SERVICE_SUCCESS);
2978
2979 notify_dbus = true;
2980 }
2981
2982 /* Interpret STOPPING= */
2983 if (strv_find(tags, "STOPPING=1")) {
2984
2985 s->notify_state = NOTIFY_STOPPING;
2986
2987 if (s->state == SERVICE_RUNNING)
2988 service_enter_stop_by_notify(s);
2989
2990 notify_dbus = true;
2991 }
2992
2993 /* Interpret STATUS= */
2994 e = strv_find_startswith(tags, "STATUS=");
2995 if (e) {
2996 _cleanup_free_ char *t = NULL;
2997
2998 if (!isempty(e)) {
2999 if (!utf8_is_valid(e))
3000 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
3001 else {
3002 t = strdup(e);
3003 if (!t)
3004 log_oom();
3005 }
3006 }
3007
3008 if (!streq_ptr(s->status_text, t)) {
3009
3010 free(s->status_text);
3011 s->status_text = t;
3012 t = NULL;
3013
3014 notify_dbus = true;
3015 }
3016 }
3017
3018 /* Interpret ERRNO= */
3019 e = strv_find_startswith(tags, "ERRNO=");
3020 if (e) {
3021 int status_errno;
3022
3023 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
3024 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
3025 else {
3026 if (s->status_errno != status_errno) {
3027 s->status_errno = status_errno;
3028 notify_dbus = true;
3029 }
3030 }
3031 }
3032
3033 /* Interpret WATCHDOG= */
3034 if (strv_find(tags, "WATCHDOG=1"))
3035 service_reset_watchdog(s);
3036
3037 if (strv_find(tags, "FDSTORE=1")) {
3038 const char *name;
3039
3040 name = strv_find_startswith(tags, "FDNAME=");
3041 if (name && !fdname_is_valid(name)) {
3042 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
3043 name = NULL;
3044 }
3045
3046 service_add_fd_store_set(s, fds, name);
3047 }
3048
3049 /* Notify clients about changed status or main pid */
3050 if (notify_dbus)
3051 unit_add_to_dbus_queue(u);
3052 }
3053
3054 static int service_get_timeout(Unit *u, usec_t *timeout) {
3055 Service *s = SERVICE(u);
3056 uint64_t t;
3057 int r;
3058
3059 if (!s->timer_event_source)
3060 return 0;
3061
3062 r = sd_event_source_get_time(s->timer_event_source, &t);
3063 if (r < 0)
3064 return r;
3065 if (t == USEC_INFINITY)
3066 return 0;
3067
3068 *timeout = t;
3069 return 1;
3070 }
3071
3072 static void service_bus_name_owner_change(
3073 Unit *u,
3074 const char *name,
3075 const char *old_owner,
3076 const char *new_owner) {
3077
3078 Service *s = SERVICE(u);
3079 int r;
3080
3081 assert(s);
3082 assert(name);
3083
3084 assert(streq(s->bus_name, name));
3085 assert(old_owner || new_owner);
3086
3087 if (old_owner && new_owner)
3088 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
3089 else if (old_owner)
3090 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
3091 else
3092 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
3093
3094 s->bus_name_good = !!new_owner;
3095
3096 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3097 r = free_and_strdup(&s->bus_name_owner, new_owner);
3098 if (r < 0) {
3099 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
3100 return;
3101 }
3102
3103 if (s->type == SERVICE_DBUS) {
3104
3105 /* service_enter_running() will figure out what to
3106 * do */
3107 if (s->state == SERVICE_RUNNING)
3108 service_enter_running(s, SERVICE_SUCCESS);
3109 else if (s->state == SERVICE_START && new_owner)
3110 service_enter_start_post(s);
3111
3112 } else if (new_owner &&
3113 s->main_pid <= 0 &&
3114 (s->state == SERVICE_START ||
3115 s->state == SERVICE_START_POST ||
3116 s->state == SERVICE_RUNNING ||
3117 s->state == SERVICE_RELOAD)) {
3118
3119 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
3120 pid_t pid;
3121
3122 /* Try to acquire PID from bus service */
3123
3124 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3125 if (r >= 0)
3126 r = sd_bus_creds_get_pid(creds, &pid);
3127 if (r >= 0) {
3128 log_unit_debug(u, "D-Bus name %s is now owned by process %u", name, (unsigned) pid);
3129
3130 service_set_main_pid(s, pid);
3131 unit_watch_pid(UNIT(s), pid);
3132 }
3133 }
3134 }
3135
3136 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
3137 _cleanup_free_ char *peer = NULL;
3138 int r;
3139
3140 assert(s);
3141 assert(fd >= 0);
3142
3143 /* This is called by the socket code when instantiating a new
3144 * service for a stream socket and the socket needs to be
3145 * configured. */
3146
3147 if (UNIT(s)->load_state != UNIT_LOADED)
3148 return -EINVAL;
3149
3150 if (s->socket_fd >= 0)
3151 return -EBUSY;
3152
3153 if (s->state != SERVICE_DEAD)
3154 return -EAGAIN;
3155
3156 if (getpeername_pretty(fd, true, &peer) >= 0) {
3157
3158 if (UNIT(s)->description) {
3159 _cleanup_free_ char *a;
3160
3161 a = strjoin(UNIT(s)->description, " (", peer, ")", NULL);
3162 if (!a)
3163 return -ENOMEM;
3164
3165 r = unit_set_description(UNIT(s), a);
3166 } else
3167 r = unit_set_description(UNIT(s), peer);
3168
3169 if (r < 0)
3170 return r;
3171 }
3172
3173 s->socket_fd = fd;
3174 s->socket_fd_selinux_context_net = selinux_context_net;
3175
3176 unit_ref_set(&s->accept_socket, UNIT(sock));
3177
3178 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3179 }
3180
3181 static void service_reset_failed(Unit *u) {
3182 Service *s = SERVICE(u);
3183
3184 assert(s);
3185
3186 if (s->state == SERVICE_FAILED)
3187 service_set_state(s, SERVICE_DEAD);
3188
3189 s->result = SERVICE_SUCCESS;
3190 s->reload_result = SERVICE_SUCCESS;
3191 }
3192
3193 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3194 Service *s = SERVICE(u);
3195
3196 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3197 }
3198
3199 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3200 [SERVICE_RESTART_NO] = "no",
3201 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3202 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3203 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3204 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3205 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3206 [SERVICE_RESTART_ALWAYS] = "always",
3207 };
3208
3209 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3210
3211 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3212 [SERVICE_SIMPLE] = "simple",
3213 [SERVICE_FORKING] = "forking",
3214 [SERVICE_ONESHOT] = "oneshot",
3215 [SERVICE_DBUS] = "dbus",
3216 [SERVICE_NOTIFY] = "notify",
3217 [SERVICE_IDLE] = "idle"
3218 };
3219
3220 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3221
3222 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3223 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3224 [SERVICE_EXEC_START] = "ExecStart",
3225 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3226 [SERVICE_EXEC_RELOAD] = "ExecReload",
3227 [SERVICE_EXEC_STOP] = "ExecStop",
3228 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3229 };
3230
3231 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3232
3233 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3234 [NOTIFY_NONE] = "none",
3235 [NOTIFY_MAIN] = "main",
3236 [NOTIFY_ALL] = "all"
3237 };
3238
3239 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3240
3241 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3242 [NOTIFY_UNKNOWN] = "unknown",
3243 [NOTIFY_READY] = "ready",
3244 [NOTIFY_RELOADING] = "reloading",
3245 [NOTIFY_STOPPING] = "stopping",
3246 };
3247
3248 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3249
3250 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3251 [SERVICE_SUCCESS] = "success",
3252 [SERVICE_FAILURE_RESOURCES] = "resources",
3253 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3254 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3255 [SERVICE_FAILURE_SIGNAL] = "signal",
3256 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3257 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3258 };
3259
3260 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3261
3262 const UnitVTable service_vtable = {
3263 .object_size = sizeof(Service),
3264 .exec_context_offset = offsetof(Service, exec_context),
3265 .cgroup_context_offset = offsetof(Service, cgroup_context),
3266 .kill_context_offset = offsetof(Service, kill_context),
3267 .exec_runtime_offset = offsetof(Service, exec_runtime),
3268
3269 .sections =
3270 "Unit\0"
3271 "Service\0"
3272 "Install\0",
3273 .private_section = "Service",
3274
3275 .init = service_init,
3276 .done = service_done,
3277 .load = service_load,
3278 .release_resources = service_release_resources,
3279
3280 .coldplug = service_coldplug,
3281
3282 .dump = service_dump,
3283
3284 .start = service_start,
3285 .stop = service_stop,
3286 .reload = service_reload,
3287
3288 .can_reload = service_can_reload,
3289
3290 .kill = service_kill,
3291
3292 .serialize = service_serialize,
3293 .deserialize_item = service_deserialize_item,
3294
3295 .active_state = service_active_state,
3296 .sub_state_to_string = service_sub_state_to_string,
3297
3298 .check_gc = service_check_gc,
3299
3300 .sigchld_event = service_sigchld_event,
3301
3302 .reset_failed = service_reset_failed,
3303
3304 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3305 .notify_message = service_notify_message,
3306
3307 .bus_name_owner_change = service_bus_name_owner_change,
3308
3309 .bus_vtable = bus_service_vtable,
3310 .bus_set_property = bus_service_set_property,
3311 .bus_commit_properties = bus_service_commit_properties,
3312
3313 .get_timeout = service_get_timeout,
3314 .can_transient = true,
3315
3316 .status_message_formats = {
3317 .starting_stopping = {
3318 [0] = "Starting %s...",
3319 [1] = "Stopping %s...",
3320 },
3321 .finished_start_job = {
3322 [JOB_DONE] = "Started %s.",
3323 [JOB_FAILED] = "Failed to start %s.",
3324 },
3325 .finished_stop_job = {
3326 [JOB_DONE] = "Stopped %s.",
3327 [JOB_FAILED] = "Stopped (with error) %s.",
3328 },
3329 },
3330 };