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