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