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