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