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