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