]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/service.c
Merge pull request #4612 from keszybz/format-strings
[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 int service_spawn(
1183 Service *s,
1184 ExecCommand *c,
1185 usec_t timeout,
1186 ExecFlags flags,
1187 pid_t *_pid) {
1188
1189 _cleanup_strv_free_ char **argv = NULL, **final_env = NULL, **our_env = NULL, **fd_names = NULL;
1190 _cleanup_free_ int *fds = NULL;
1191 unsigned n_fds = 0, n_env = 0;
1192 const char *path;
1193 pid_t pid;
1194
1195 ExecParameters exec_params = {
1196 .flags = flags,
1197 .stdin_fd = -1,
1198 .stdout_fd = -1,
1199 .stderr_fd = -1,
1200 };
1201
1202 int r;
1203
1204 assert(s);
1205 assert(c);
1206 assert(_pid);
1207
1208 if (flags & EXEC_IS_CONTROL) {
1209 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1210 if (s->permissions_start_only)
1211 exec_params.flags &= ~EXEC_APPLY_PERMISSIONS;
1212 if (s->root_directory_start_only)
1213 exec_params.flags &= ~EXEC_APPLY_CHROOT;
1214 }
1215
1216 (void) unit_realize_cgroup(UNIT(s));
1217 if (s->reset_cpu_usage) {
1218 (void) unit_reset_cpu_usage(UNIT(s));
1219 s->reset_cpu_usage = false;
1220 }
1221
1222 r = unit_setup_exec_runtime(UNIT(s));
1223 if (r < 0)
1224 return r;
1225
1226 r = unit_setup_dynamic_creds(UNIT(s));
1227 if (r < 0)
1228 return r;
1229
1230 if ((flags & EXEC_PASS_FDS) ||
1231 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1232 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1233 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1234
1235 r = service_collect_fds(s, &fds, &fd_names);
1236 if (r < 0)
1237 return r;
1238
1239 n_fds = r;
1240 log_unit_debug(UNIT(s), "Passing %i fds to service", n_fds);
1241 }
1242
1243 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), timeout));
1244 if (r < 0)
1245 return r;
1246
1247 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1248 if (r < 0)
1249 return r;
1250
1251 our_env = new0(char*, 9);
1252 if (!our_env)
1253 return -ENOMEM;
1254
1255 if ((flags & EXEC_IS_CONTROL) ? s->notify_access == NOTIFY_ALL : s->notify_access != NOTIFY_NONE)
1256 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1257 return -ENOMEM;
1258
1259 if (s->main_pid > 0)
1260 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0)
1261 return -ENOMEM;
1262
1263 if (MANAGER_IS_USER(UNIT(s)->manager))
1264 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0)
1265 return -ENOMEM;
1266
1267 if (s->socket_fd >= 0) {
1268 union sockaddr_union sa;
1269 socklen_t salen = sizeof(sa);
1270
1271 r = getpeername(s->socket_fd, &sa.sa, &salen);
1272 if (r < 0) {
1273 r = -errno;
1274
1275 /* ENOTCONN is legitimate if the endpoint disappeared on shutdown.
1276 * This connection is over, but the socket unit lives on. */
1277 if (r != -ENOTCONN || !IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
1278 return r;
1279 }
1280
1281 if (r == 0 && IN_SET(sa.sa.sa_family, AF_INET, AF_INET6)) {
1282 _cleanup_free_ char *addr = NULL;
1283 char *t;
1284 int port;
1285
1286 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1287 if (r < 0)
1288 return r;
1289
1290 t = strappend("REMOTE_ADDR=", addr);
1291 if (!t)
1292 return -ENOMEM;
1293 our_env[n_env++] = t;
1294
1295 port = sockaddr_port(&sa.sa);
1296 if (port < 0)
1297 return port;
1298
1299 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1300 return -ENOMEM;
1301 our_env[n_env++] = t;
1302 }
1303 }
1304
1305 if (flags & EXEC_SETENV_RESULT) {
1306 if (asprintf(our_env + n_env++, "SERVICE_RESULT=%s", service_result_to_string(s->result)) < 0)
1307 return -ENOMEM;
1308
1309 if (s->main_exec_status.pid > 0 &&
1310 dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1311 if (asprintf(our_env + n_env++, "EXIT_CODE=%s", sigchld_code_to_string(s->main_exec_status.code)) < 0)
1312 return -ENOMEM;
1313
1314 if (s->main_exec_status.code == CLD_EXITED)
1315 r = asprintf(our_env + n_env++, "EXIT_STATUS=%i", s->main_exec_status.status);
1316 else
1317 r = asprintf(our_env + n_env++, "EXIT_STATUS=%s", signal_to_string(s->main_exec_status.status));
1318 if (r < 0)
1319 return -ENOMEM;
1320 }
1321 }
1322
1323 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1324 if (!final_env)
1325 return -ENOMEM;
1326
1327 if ((flags & EXEC_IS_CONTROL) && UNIT(s)->cgroup_path) {
1328 path = strjoina(UNIT(s)->cgroup_path, "/control");
1329 (void) cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1330 } else
1331 path = UNIT(s)->cgroup_path;
1332
1333 exec_params.argv = argv;
1334 exec_params.environment = final_env;
1335 exec_params.fds = fds;
1336 exec_params.fd_names = fd_names;
1337 exec_params.n_fds = n_fds;
1338 exec_params.flags |= UNIT(s)->manager->confirm_spawn ? EXEC_CONFIRM_SPAWN : 0;
1339 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1340 exec_params.cgroup_path = path;
1341 exec_params.cgroup_delegate = s->cgroup_context.delegate;
1342 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
1343 exec_params.watchdog_usec = s->watchdog_usec;
1344 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
1345 if (s->type == SERVICE_IDLE)
1346 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
1347 exec_params.stdin_fd = s->stdin_fd;
1348 exec_params.stdout_fd = s->stdout_fd;
1349 exec_params.stderr_fd = s->stderr_fd;
1350
1351 r = exec_spawn(UNIT(s),
1352 c,
1353 &s->exec_context,
1354 &exec_params,
1355 s->exec_runtime,
1356 &s->dynamic_creds,
1357 &pid);
1358 if (r < 0)
1359 return r;
1360
1361 r = unit_watch_pid(UNIT(s), pid);
1362 if (r < 0)
1363 /* FIXME: we need to do something here */
1364 return r;
1365
1366 *_pid = pid;
1367
1368 return 0;
1369 }
1370
1371 static int main_pid_good(Service *s) {
1372 assert(s);
1373
1374 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1375 * don't know */
1376
1377 /* If we know the pid file, then let's just check if it is
1378 * still valid */
1379 if (s->main_pid_known) {
1380
1381 /* If it's an alien child let's check if it is still
1382 * alive ... */
1383 if (s->main_pid_alien && s->main_pid > 0)
1384 return pid_is_alive(s->main_pid);
1385
1386 /* .. otherwise assume we'll get a SIGCHLD for it,
1387 * which we really should wait for to collect exit
1388 * status and code */
1389 return s->main_pid > 0;
1390 }
1391
1392 /* We don't know the pid */
1393 return -EAGAIN;
1394 }
1395
1396 _pure_ static int control_pid_good(Service *s) {
1397 assert(s);
1398
1399 return s->control_pid > 0;
1400 }
1401
1402 static int cgroup_good(Service *s) {
1403 int r;
1404
1405 assert(s);
1406
1407 if (!UNIT(s)->cgroup_path)
1408 return 0;
1409
1410 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
1411 if (r < 0)
1412 return r;
1413
1414 return !r;
1415 }
1416
1417 static bool service_shall_restart(Service *s) {
1418 assert(s);
1419
1420 /* Don't restart after manual stops */
1421 if (s->forbid_restart)
1422 return false;
1423
1424 /* Never restart if this is configured as special exception */
1425 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status))
1426 return false;
1427
1428 /* Restart if the exit code/status are configured as restart triggers */
1429 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status))
1430 return true;
1431
1432 switch (s->restart) {
1433
1434 case SERVICE_RESTART_NO:
1435 return false;
1436
1437 case SERVICE_RESTART_ALWAYS:
1438 return true;
1439
1440 case SERVICE_RESTART_ON_SUCCESS:
1441 return s->result == SERVICE_SUCCESS;
1442
1443 case SERVICE_RESTART_ON_FAILURE:
1444 return s->result != SERVICE_SUCCESS;
1445
1446 case SERVICE_RESTART_ON_ABNORMAL:
1447 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE);
1448
1449 case SERVICE_RESTART_ON_WATCHDOG:
1450 return s->result == SERVICE_FAILURE_WATCHDOG;
1451
1452 case SERVICE_RESTART_ON_ABORT:
1453 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1454
1455 default:
1456 assert_not_reached("unknown restart setting");
1457 }
1458 }
1459
1460 static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
1461 int r;
1462 assert(s);
1463
1464 if (s->result == SERVICE_SUCCESS)
1465 s->result = f;
1466
1467 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1468
1469 if (s->result != SERVICE_SUCCESS) {
1470 log_unit_warning(UNIT(s), "Failed with result '%s'.", service_result_to_string(s->result));
1471 emergency_action(UNIT(s)->manager, s->emergency_action, UNIT(s)->reboot_arg, "service failed");
1472 }
1473
1474 if (allow_restart && service_shall_restart(s)) {
1475
1476 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1477 if (r < 0)
1478 goto fail;
1479
1480 service_set_state(s, SERVICE_AUTO_RESTART);
1481 }
1482
1483 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
1484 s->forbid_restart = false;
1485
1486 /* We want fresh tmpdirs in case service is started again immediately */
1487 exec_runtime_destroy(s->exec_runtime);
1488 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1489
1490 /* Also, remove the runtime directory */
1491 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1492
1493 /* Get rid of the IPC bits of the user */
1494 unit_unref_uid_gid(UNIT(s), true);
1495
1496 /* Release the user, and destroy it if we are the only remaining owner */
1497 dynamic_creds_destroy(&s->dynamic_creds);
1498
1499 /* Try to delete the pid file. At this point it will be
1500 * out-of-date, and some software might be confused by it, so
1501 * let's remove it. */
1502 if (s->pid_file)
1503 (void) unlink(s->pid_file);
1504
1505 return;
1506
1507 fail:
1508 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
1509 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1510 }
1511
1512 static void service_enter_stop_post(Service *s, ServiceResult f) {
1513 int r;
1514 assert(s);
1515
1516 if (s->result == SERVICE_SUCCESS)
1517 s->result = f;
1518
1519 service_unwatch_control_pid(s);
1520 unit_watch_all_pids(UNIT(s));
1521
1522 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1523 if (s->control_command) {
1524 s->control_command_id = SERVICE_EXEC_STOP_POST;
1525
1526 r = service_spawn(s,
1527 s->control_command,
1528 s->timeout_stop_usec,
1529 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
1530 &s->control_pid);
1531 if (r < 0)
1532 goto fail;
1533
1534 service_set_state(s, SERVICE_STOP_POST);
1535 } else
1536 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
1537
1538 return;
1539
1540 fail:
1541 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
1542 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1543 }
1544
1545 static int state_to_kill_operation(ServiceState state) {
1546 switch (state) {
1547
1548 case SERVICE_STOP_SIGABRT:
1549 return KILL_ABORT;
1550
1551 case SERVICE_STOP_SIGTERM:
1552 case SERVICE_FINAL_SIGTERM:
1553 return KILL_TERMINATE;
1554
1555 case SERVICE_STOP_SIGKILL:
1556 case SERVICE_FINAL_SIGKILL:
1557 return KILL_KILL;
1558
1559 default:
1560 return _KILL_OPERATION_INVALID;
1561 }
1562 }
1563
1564 static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
1565 int r;
1566
1567 assert(s);
1568
1569 if (s->result == SERVICE_SUCCESS)
1570 s->result = f;
1571
1572 unit_watch_all_pids(UNIT(s));
1573
1574 r = unit_kill_context(
1575 UNIT(s),
1576 &s->kill_context,
1577 state_to_kill_operation(state),
1578 s->main_pid,
1579 s->control_pid,
1580 s->main_pid_alien);
1581
1582 if (r < 0)
1583 goto fail;
1584
1585 if (r > 0) {
1586 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1587 if (r < 0)
1588 goto fail;
1589
1590 service_set_state(s, state);
1591 } else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
1592 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1593 else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1594 service_enter_stop_post(s, SERVICE_SUCCESS);
1595 else if (state == SERVICE_FINAL_SIGTERM && s->kill_context.send_sigkill)
1596 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
1597 else
1598 service_enter_dead(s, SERVICE_SUCCESS, true);
1599
1600 return;
1601
1602 fail:
1603 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
1604
1605 if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
1606 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
1607 else
1608 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1609 }
1610
1611 static void service_enter_stop_by_notify(Service *s) {
1612 assert(s);
1613
1614 unit_watch_all_pids(UNIT(s));
1615
1616 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1617
1618 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1619 service_set_state(s, SERVICE_STOP_SIGTERM);
1620 }
1621
1622 static void service_enter_stop(Service *s, ServiceResult f) {
1623 int r;
1624
1625 assert(s);
1626
1627 if (s->result == SERVICE_SUCCESS)
1628 s->result = f;
1629
1630 service_unwatch_control_pid(s);
1631 unit_watch_all_pids(UNIT(s));
1632
1633 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1634 if (s->control_command) {
1635 s->control_command_id = SERVICE_EXEC_STOP;
1636
1637 r = service_spawn(s,
1638 s->control_command,
1639 s->timeout_stop_usec,
1640 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
1641 &s->control_pid);
1642 if (r < 0)
1643 goto fail;
1644
1645 service_set_state(s, SERVICE_STOP);
1646 } else
1647 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
1648
1649 return;
1650
1651 fail:
1652 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
1653 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1654 }
1655
1656 static bool service_good(Service *s) {
1657 int main_pid_ok;
1658 assert(s);
1659
1660 if (s->type == SERVICE_DBUS && !s->bus_name_good)
1661 return false;
1662
1663 main_pid_ok = main_pid_good(s);
1664 if (main_pid_ok > 0) /* It's alive */
1665 return true;
1666 if (main_pid_ok == 0) /* It's dead */
1667 return false;
1668
1669 /* OK, we don't know anything about the main PID, maybe
1670 * because there is none. Let's check the control group
1671 * instead. */
1672
1673 return cgroup_good(s) != 0;
1674 }
1675
1676 static void service_enter_running(Service *s, ServiceResult f) {
1677 assert(s);
1678
1679 if (s->result == SERVICE_SUCCESS)
1680 s->result = f;
1681
1682 service_unwatch_control_pid(s);
1683
1684 if (service_good(s)) {
1685
1686 /* If there are any queued up sd_notify()
1687 * notifications, process them now */
1688 if (s->notify_state == NOTIFY_RELOADING)
1689 service_enter_reload_by_notify(s);
1690 else if (s->notify_state == NOTIFY_STOPPING)
1691 service_enter_stop_by_notify(s);
1692 else {
1693 service_set_state(s, SERVICE_RUNNING);
1694 service_arm_timer(s, usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec));
1695 }
1696
1697 } else if (s->remain_after_exit)
1698 service_set_state(s, SERVICE_EXITED);
1699 else
1700 service_enter_stop(s, SERVICE_SUCCESS);
1701 }
1702
1703 static void service_enter_start_post(Service *s) {
1704 int r;
1705 assert(s);
1706
1707 service_unwatch_control_pid(s);
1708 service_reset_watchdog(s);
1709
1710 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1711 if (s->control_command) {
1712 s->control_command_id = SERVICE_EXEC_START_POST;
1713
1714 r = service_spawn(s,
1715 s->control_command,
1716 s->timeout_start_usec,
1717 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
1718 &s->control_pid);
1719 if (r < 0)
1720 goto fail;
1721
1722 service_set_state(s, SERVICE_START_POST);
1723 } else
1724 service_enter_running(s, SERVICE_SUCCESS);
1725
1726 return;
1727
1728 fail:
1729 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
1730 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1731 }
1732
1733 static void service_kill_control_processes(Service *s) {
1734 char *p;
1735
1736 if (!UNIT(s)->cgroup_path)
1737 return;
1738
1739 p = strjoina(UNIT(s)->cgroup_path, "/control");
1740 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, CGROUP_SIGCONT|CGROUP_IGNORE_SELF|CGROUP_REMOVE, NULL, NULL, NULL);
1741 }
1742
1743 static void service_enter_start(Service *s) {
1744 ExecCommand *c;
1745 usec_t timeout;
1746 pid_t pid;
1747 int r;
1748
1749 assert(s);
1750
1751 service_unwatch_control_pid(s);
1752 service_unwatch_main_pid(s);
1753
1754 /* We want to ensure that nobody leaks processes from
1755 * START_PRE here, so let's go on a killing spree, People
1756 * should not spawn long running processes from START_PRE. */
1757 service_kill_control_processes(s);
1758
1759 if (s->type == SERVICE_FORKING) {
1760 s->control_command_id = SERVICE_EXEC_START;
1761 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1762
1763 s->main_command = NULL;
1764 } else {
1765 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1766 s->control_command = NULL;
1767
1768 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1769 }
1770
1771 if (!c) {
1772 if (s->type != SERVICE_ONESHOT) {
1773 /* There's no command line configured for the main command? Hmm, that is strange. This can only
1774 * happen if the configuration changes at runtime. In this case, let's enter a failure
1775 * state. */
1776 log_unit_error(UNIT(s), "There's no 'start' task anymore we could start: %m");
1777 r = -ENXIO;
1778 goto fail;
1779 }
1780
1781 service_enter_start_post(s);
1782 return;
1783 }
1784
1785 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
1786 /* For simple + idle this is the main process. We don't apply any timeout here, but
1787 * service_enter_running() will later apply the .runtime_max_usec timeout. */
1788 timeout = USEC_INFINITY;
1789 else
1790 timeout = s->timeout_start_usec;
1791
1792 r = service_spawn(s,
1793 c,
1794 timeout,
1795 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
1796 &pid);
1797 if (r < 0)
1798 goto fail;
1799
1800 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
1801 /* For simple services we immediately start
1802 * the START_POST binaries. */
1803
1804 service_set_main_pid(s, pid);
1805 service_enter_start_post(s);
1806
1807 } else if (s->type == SERVICE_FORKING) {
1808
1809 /* For forking services we wait until the start
1810 * process exited. */
1811
1812 s->control_pid = pid;
1813 service_set_state(s, SERVICE_START);
1814
1815 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY)) {
1816
1817 /* For oneshot services we wait until the start
1818 * process exited, too, but it is our main process. */
1819
1820 /* For D-Bus services we know the main pid right away,
1821 * but wait for the bus name to appear on the
1822 * bus. Notify services are similar. */
1823
1824 service_set_main_pid(s, pid);
1825 service_set_state(s, SERVICE_START);
1826 } else
1827 assert_not_reached("Unknown service type");
1828
1829 return;
1830
1831 fail:
1832 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
1833 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1834 }
1835
1836 static void service_enter_start_pre(Service *s) {
1837 int r;
1838
1839 assert(s);
1840
1841 service_unwatch_control_pid(s);
1842
1843 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1844 if (s->control_command) {
1845 /* Before we start anything, let's clear up what might
1846 * be left from previous runs. */
1847 service_kill_control_processes(s);
1848
1849 s->control_command_id = SERVICE_EXEC_START_PRE;
1850
1851 r = service_spawn(s,
1852 s->control_command,
1853 s->timeout_start_usec,
1854 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN,
1855 &s->control_pid);
1856 if (r < 0)
1857 goto fail;
1858
1859 service_set_state(s, SERVICE_START_PRE);
1860 } else
1861 service_enter_start(s);
1862
1863 return;
1864
1865 fail:
1866 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
1867 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1868 }
1869
1870 static void service_enter_restart(Service *s) {
1871 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1872 int r;
1873
1874 assert(s);
1875
1876 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1877 /* Don't restart things if we are going down anyway */
1878 log_unit_info(UNIT(s), "Stop job pending for unit, delaying automatic restart.");
1879
1880 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
1881 if (r < 0)
1882 goto fail;
1883
1884 return;
1885 }
1886
1887 /* Any units that are bound to this service must also be
1888 * restarted. We use JOB_RESTART (instead of the more obvious
1889 * JOB_START) here so that those dependency jobs will be added
1890 * as well. */
1891 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, &error, NULL);
1892 if (r < 0)
1893 goto fail;
1894
1895 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1896 * it will be canceled as part of the service_stop() call that
1897 * is executed as part of JOB_RESTART. */
1898
1899 log_unit_debug(UNIT(s), "Scheduled restart job.");
1900 return;
1901
1902 fail:
1903 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, -r));
1904 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
1905 }
1906
1907 static void service_enter_reload_by_notify(Service *s) {
1908 assert(s);
1909
1910 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_start_usec));
1911 service_set_state(s, SERVICE_RELOAD);
1912 }
1913
1914 static void service_enter_reload(Service *s) {
1915 int r;
1916
1917 assert(s);
1918
1919 service_unwatch_control_pid(s);
1920 s->reload_result = SERVICE_SUCCESS;
1921
1922 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1923 if (s->control_command) {
1924 s->control_command_id = SERVICE_EXEC_RELOAD;
1925
1926 r = service_spawn(s,
1927 s->control_command,
1928 s->timeout_start_usec,
1929 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
1930 &s->control_pid);
1931 if (r < 0)
1932 goto fail;
1933
1934 service_set_state(s, SERVICE_RELOAD);
1935 } else
1936 service_enter_running(s, SERVICE_SUCCESS);
1937
1938 return;
1939
1940 fail:
1941 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
1942 s->reload_result = SERVICE_FAILURE_RESOURCES;
1943 service_enter_running(s, SERVICE_SUCCESS);
1944 }
1945
1946 static void service_run_next_control(Service *s) {
1947 usec_t timeout;
1948 int r;
1949
1950 assert(s);
1951 assert(s->control_command);
1952 assert(s->control_command->command_next);
1953
1954 assert(s->control_command_id != SERVICE_EXEC_START);
1955
1956 s->control_command = s->control_command->command_next;
1957 service_unwatch_control_pid(s);
1958
1959 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1960 timeout = s->timeout_start_usec;
1961 else
1962 timeout = s->timeout_stop_usec;
1963
1964 r = service_spawn(s,
1965 s->control_command,
1966 timeout,
1967 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|
1968 (IN_SET(s->control_command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_STOP_POST) ? EXEC_APPLY_TTY_STDIN : 0)|
1969 (IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_SETENV_RESULT : 0),
1970 &s->control_pid);
1971 if (r < 0)
1972 goto fail;
1973
1974 return;
1975
1976 fail:
1977 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
1978
1979 if (s->state == SERVICE_START_PRE)
1980 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
1981 else if (s->state == SERVICE_STOP)
1982 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
1983 else if (s->state == SERVICE_STOP_POST)
1984 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
1985 else if (s->state == SERVICE_RELOAD) {
1986 s->reload_result = SERVICE_FAILURE_RESOURCES;
1987 service_enter_running(s, SERVICE_SUCCESS);
1988 } else
1989 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
1990 }
1991
1992 static void service_run_next_main(Service *s) {
1993 pid_t pid;
1994 int r;
1995
1996 assert(s);
1997 assert(s->main_command);
1998 assert(s->main_command->command_next);
1999 assert(s->type == SERVICE_ONESHOT);
2000
2001 s->main_command = s->main_command->command_next;
2002 service_unwatch_main_pid(s);
2003
2004 r = service_spawn(s,
2005 s->main_command,
2006 s->timeout_start_usec,
2007 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
2008 &pid);
2009 if (r < 0)
2010 goto fail;
2011
2012 service_set_main_pid(s, pid);
2013
2014 return;
2015
2016 fail:
2017 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
2018 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2019 }
2020
2021 static int service_start(Unit *u) {
2022 Service *s = SERVICE(u);
2023 int r;
2024
2025 assert(s);
2026
2027 /* We cannot fulfill this request right now, try again later
2028 * please! */
2029 if (IN_SET(s->state,
2030 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2031 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2032 return -EAGAIN;
2033
2034 /* Already on it! */
2035 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
2036 return 0;
2037
2038 /* A service that will be restarted must be stopped first to
2039 * trigger BindsTo and/or OnFailure dependencies. If a user
2040 * does not want to wait for the holdoff time to elapse, the
2041 * service should be manually restarted, not started. We
2042 * simply return EAGAIN here, so that any start jobs stay
2043 * queued, and assume that the auto restart timer will
2044 * eventually trigger the restart. */
2045 if (s->state == SERVICE_AUTO_RESTART)
2046 return -EAGAIN;
2047
2048 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
2049
2050 /* Make sure we don't enter a busy loop of some kind. */
2051 r = unit_start_limit_test(u);
2052 if (r < 0) {
2053 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
2054 return r;
2055 }
2056
2057 r = unit_acquire_invocation_id(u);
2058 if (r < 0)
2059 return r;
2060
2061 s->result = SERVICE_SUCCESS;
2062 s->reload_result = SERVICE_SUCCESS;
2063 s->main_pid_known = false;
2064 s->main_pid_alien = false;
2065 s->forbid_restart = false;
2066 s->reset_cpu_usage = true;
2067
2068 s->status_text = mfree(s->status_text);
2069 s->status_errno = 0;
2070
2071 s->notify_state = NOTIFY_UNKNOWN;
2072
2073 s->watchdog_override_enable = false;
2074 s->watchdog_override_usec = 0;
2075
2076 service_enter_start_pre(s);
2077 return 1;
2078 }
2079
2080 static int service_stop(Unit *u) {
2081 Service *s = SERVICE(u);
2082
2083 assert(s);
2084
2085 /* Don't create restart jobs from manual stops. */
2086 s->forbid_restart = true;
2087
2088 /* Already on it */
2089 if (IN_SET(s->state,
2090 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2091 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
2092 return 0;
2093
2094 /* A restart will be scheduled or is in progress. */
2095 if (s->state == SERVICE_AUTO_RESTART) {
2096 service_set_state(s, SERVICE_DEAD);
2097 return 0;
2098 }
2099
2100 /* If there's already something running we go directly into
2101 * kill mode. */
2102 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD)) {
2103 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
2104 return 0;
2105 }
2106
2107 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
2108
2109 service_enter_stop(s, SERVICE_SUCCESS);
2110 return 1;
2111 }
2112
2113 static int service_reload(Unit *u) {
2114 Service *s = SERVICE(u);
2115
2116 assert(s);
2117
2118 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
2119
2120 service_enter_reload(s);
2121 return 1;
2122 }
2123
2124 _pure_ static bool service_can_reload(Unit *u) {
2125 Service *s = SERVICE(u);
2126
2127 assert(s);
2128
2129 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2130 }
2131
2132 static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2133 Service *s = SERVICE(u);
2134 ServiceFDStore *fs;
2135 int r;
2136
2137 assert(u);
2138 assert(f);
2139 assert(fds);
2140
2141 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
2142 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2143 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
2144
2145 if (s->control_pid > 0)
2146 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
2147
2148 if (s->main_pid_known && s->main_pid > 0)
2149 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
2150
2151 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2152 unit_serialize_item(u, f, "bus-name-good", yes_no(s->bus_name_good));
2153 unit_serialize_item(u, f, "bus-name-owner", s->bus_name_owner);
2154
2155 r = unit_serialize_item_escaped(u, f, "status-text", s->status_text);
2156 if (r < 0)
2157 return r;
2158
2159 /* FIXME: There's a minor uncleanliness here: if there are
2160 * multiple commands attached here, we will start from the
2161 * first one again */
2162 if (s->control_command_id >= 0)
2163 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
2164
2165 r = unit_serialize_item_fd(u, f, fds, "stdin-fd", s->stdin_fd);
2166 if (r < 0)
2167 return r;
2168 r = unit_serialize_item_fd(u, f, fds, "stdout-fd", s->stdout_fd);
2169 if (r < 0)
2170 return r;
2171 r = unit_serialize_item_fd(u, f, fds, "stderr-fd", s->stderr_fd);
2172 if (r < 0)
2173 return r;
2174
2175 if (UNIT_ISSET(s->accept_socket)) {
2176 r = unit_serialize_item(u, f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
2177 if (r < 0)
2178 return r;
2179 }
2180
2181 r = unit_serialize_item_fd(u, f, fds, "socket-fd", s->socket_fd);
2182 if (r < 0)
2183 return r;
2184
2185 LIST_FOREACH(fd_store, fs, s->fd_store) {
2186 _cleanup_free_ char *c = NULL;
2187 int copy;
2188
2189 copy = fdset_put_dup(fds, fs->fd);
2190 if (copy < 0)
2191 return copy;
2192
2193 c = cescape(fs->fdname);
2194
2195 unit_serialize_item_format(u, f, "fd-store-fd", "%i %s", copy, strempty(c));
2196 }
2197
2198 if (s->main_exec_status.pid > 0) {
2199 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2200 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2201 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
2202
2203 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
2204 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2205 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
2206 }
2207 }
2208
2209 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
2210
2211 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
2212
2213 if (s->watchdog_override_enable)
2214 unit_serialize_item_format(u, f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2215
2216 return 0;
2217 }
2218
2219 static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2220 Service *s = SERVICE(u);
2221 int r;
2222
2223 assert(u);
2224 assert(key);
2225 assert(value);
2226 assert(fds);
2227
2228 if (streq(key, "state")) {
2229 ServiceState state;
2230
2231 state = service_state_from_string(value);
2232 if (state < 0)
2233 log_unit_debug(u, "Failed to parse state value: %s", value);
2234 else
2235 s->deserialized_state = state;
2236 } else if (streq(key, "result")) {
2237 ServiceResult f;
2238
2239 f = service_result_from_string(value);
2240 if (f < 0)
2241 log_unit_debug(u, "Failed to parse result value: %s", value);
2242 else if (f != SERVICE_SUCCESS)
2243 s->result = f;
2244
2245 } else if (streq(key, "reload-result")) {
2246 ServiceResult f;
2247
2248 f = service_result_from_string(value);
2249 if (f < 0)
2250 log_unit_debug(u, "Failed to parse reload result value: %s", value);
2251 else if (f != SERVICE_SUCCESS)
2252 s->reload_result = f;
2253
2254 } else if (streq(key, "control-pid")) {
2255 pid_t pid;
2256
2257 if (parse_pid(value, &pid) < 0)
2258 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
2259 else
2260 s->control_pid = pid;
2261 } else if (streq(key, "main-pid")) {
2262 pid_t pid;
2263
2264 if (parse_pid(value, &pid) < 0)
2265 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
2266 else {
2267 service_set_main_pid(s, pid);
2268 unit_watch_pid(UNIT(s), pid);
2269 }
2270 } else if (streq(key, "main-pid-known")) {
2271 int b;
2272
2273 b = parse_boolean(value);
2274 if (b < 0)
2275 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
2276 else
2277 s->main_pid_known = b;
2278 } else if (streq(key, "bus-name-good")) {
2279 int b;
2280
2281 b = parse_boolean(value);
2282 if (b < 0)
2283 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2284 else
2285 s->bus_name_good = b;
2286 } else if (streq(key, "bus-name-owner")) {
2287 r = free_and_strdup(&s->bus_name_owner, value);
2288 if (r < 0)
2289 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
2290 } else if (streq(key, "status-text")) {
2291 char *t;
2292
2293 r = cunescape(value, 0, &t);
2294 if (r < 0)
2295 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
2296 else {
2297 free(s->status_text);
2298 s->status_text = t;
2299 }
2300
2301 } else if (streq(key, "control-command")) {
2302 ServiceExecCommand id;
2303
2304 id = service_exec_command_from_string(value);
2305 if (id < 0)
2306 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
2307 else {
2308 s->control_command_id = id;
2309 s->control_command = s->exec_command[id];
2310 }
2311 } else if (streq(key, "accept-socket")) {
2312 Unit *socket;
2313
2314 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
2315 if (r < 0)
2316 log_unit_debug_errno(u, r, "Failed to load accept-socket unit: %s", value);
2317 else {
2318 unit_ref_set(&s->accept_socket, socket);
2319 SOCKET(socket)->n_connections++;
2320 }
2321
2322 } else if (streq(key, "socket-fd")) {
2323 int fd;
2324
2325 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2326 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
2327 else {
2328 asynchronous_close(s->socket_fd);
2329 s->socket_fd = fdset_remove(fds, fd);
2330 }
2331 } else if (streq(key, "fd-store-fd")) {
2332 const char *fdv;
2333 size_t pf;
2334 int fd;
2335
2336 pf = strcspn(value, WHITESPACE);
2337 fdv = strndupa(value, pf);
2338
2339 if (safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2340 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2341 else {
2342 _cleanup_free_ char *t = NULL;
2343 const char *fdn;
2344
2345 fdn = value + pf;
2346 fdn += strspn(fdn, WHITESPACE);
2347 (void) cunescape(fdn, 0, &t);
2348
2349 r = service_add_fd_store(s, fd, t);
2350 if (r < 0)
2351 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
2352 else
2353 fdset_remove(fds, fd);
2354 }
2355
2356 } else if (streq(key, "main-exec-status-pid")) {
2357 pid_t pid;
2358
2359 if (parse_pid(value, &pid) < 0)
2360 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
2361 else
2362 s->main_exec_status.pid = pid;
2363 } else if (streq(key, "main-exec-status-code")) {
2364 int i;
2365
2366 if (safe_atoi(value, &i) < 0)
2367 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
2368 else
2369 s->main_exec_status.code = i;
2370 } else if (streq(key, "main-exec-status-status")) {
2371 int i;
2372
2373 if (safe_atoi(value, &i) < 0)
2374 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
2375 else
2376 s->main_exec_status.status = i;
2377 } else if (streq(key, "main-exec-status-start"))
2378 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2379 else if (streq(key, "main-exec-status-exit"))
2380 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
2381 else if (streq(key, "watchdog-timestamp"))
2382 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
2383 else if (streq(key, "forbid-restart")) {
2384 int b;
2385
2386 b = parse_boolean(value);
2387 if (b < 0)
2388 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
2389 else
2390 s->forbid_restart = b;
2391 } else if (streq(key, "stdin-fd")) {
2392 int fd;
2393
2394 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2395 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
2396 else {
2397 asynchronous_close(s->stdin_fd);
2398 s->stdin_fd = fdset_remove(fds, fd);
2399 s->exec_context.stdio_as_fds = true;
2400 }
2401 } else if (streq(key, "stdout-fd")) {
2402 int fd;
2403
2404 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2405 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
2406 else {
2407 asynchronous_close(s->stdout_fd);
2408 s->stdout_fd = fdset_remove(fds, fd);
2409 s->exec_context.stdio_as_fds = true;
2410 }
2411 } else if (streq(key, "stderr-fd")) {
2412 int fd;
2413
2414 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2415 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
2416 else {
2417 asynchronous_close(s->stderr_fd);
2418 s->stderr_fd = fdset_remove(fds, fd);
2419 s->exec_context.stdio_as_fds = true;
2420 }
2421 } else if (streq(key, "watchdog-override-usec")) {
2422 usec_t watchdog_override_usec;
2423 if (timestamp_deserialize(value, &watchdog_override_usec) < 0)
2424 log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
2425 else {
2426 s->watchdog_override_enable = true;
2427 s->watchdog_override_usec = watchdog_override_usec;
2428 }
2429 } else
2430 log_unit_debug(u, "Unknown serialization key: %s", key);
2431
2432 return 0;
2433 }
2434
2435 _pure_ static UnitActiveState service_active_state(Unit *u) {
2436 const UnitActiveState *table;
2437
2438 assert(u);
2439
2440 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2441
2442 return table[SERVICE(u)->state];
2443 }
2444
2445 static const char *service_sub_state_to_string(Unit *u) {
2446 assert(u);
2447
2448 return service_state_to_string(SERVICE(u)->state);
2449 }
2450
2451 static bool service_check_gc(Unit *u) {
2452 Service *s = SERVICE(u);
2453
2454 assert(s);
2455
2456 /* Never clean up services that still have a process around,
2457 * even if the service is formally dead. */
2458 if (cgroup_good(s) > 0 ||
2459 main_pid_good(s) > 0 ||
2460 control_pid_good(s) > 0)
2461 return true;
2462
2463 return false;
2464 }
2465
2466 static int service_retry_pid_file(Service *s) {
2467 int r;
2468
2469 assert(s->pid_file);
2470 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2471
2472 r = service_load_pid_file(s, false);
2473 if (r < 0)
2474 return r;
2475
2476 service_unwatch_pid_file(s);
2477
2478 service_enter_running(s, SERVICE_SUCCESS);
2479 return 0;
2480 }
2481
2482 static int service_watch_pid_file(Service *s) {
2483 int r;
2484
2485 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
2486
2487 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
2488 if (r < 0)
2489 goto fail;
2490
2491 /* the pidfile might have appeared just before we set the watch */
2492 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
2493 service_retry_pid_file(s);
2494
2495 return 0;
2496 fail:
2497 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
2498 service_unwatch_pid_file(s);
2499 return r;
2500 }
2501
2502 static int service_demand_pid_file(Service *s) {
2503 PathSpec *ps;
2504
2505 assert(s->pid_file);
2506 assert(!s->pid_file_pathspec);
2507
2508 ps = new0(PathSpec, 1);
2509 if (!ps)
2510 return -ENOMEM;
2511
2512 ps->unit = UNIT(s);
2513 ps->path = strdup(s->pid_file);
2514 if (!ps->path) {
2515 free(ps);
2516 return -ENOMEM;
2517 }
2518
2519 path_kill_slashes(ps->path);
2520
2521 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2522 * keep their PID file open all the time. */
2523 ps->type = PATH_MODIFIED;
2524 ps->inotify_fd = -1;
2525
2526 s->pid_file_pathspec = ps;
2527
2528 return service_watch_pid_file(s);
2529 }
2530
2531 static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
2532 PathSpec *p = userdata;
2533 Service *s;
2534
2535 assert(p);
2536
2537 s = SERVICE(p->unit);
2538
2539 assert(s);
2540 assert(fd >= 0);
2541 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2542 assert(s->pid_file_pathspec);
2543 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
2544
2545 log_unit_debug(UNIT(s), "inotify event");
2546
2547 if (path_spec_fd_event(p, events) < 0)
2548 goto fail;
2549
2550 if (service_retry_pid_file(s) == 0)
2551 return 0;
2552
2553 if (service_watch_pid_file(s) < 0)
2554 goto fail;
2555
2556 return 0;
2557
2558 fail:
2559 service_unwatch_pid_file(s);
2560 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
2561 return 0;
2562 }
2563
2564 static void service_notify_cgroup_empty_event(Unit *u) {
2565 Service *s = SERVICE(u);
2566
2567 assert(u);
2568
2569 log_unit_debug(u, "cgroup is empty");
2570
2571 switch (s->state) {
2572
2573 /* Waiting for SIGCHLD is usually more interesting,
2574 * because it includes return codes/signals. Which is
2575 * why we ignore the cgroup events for most cases,
2576 * except when we don't know pid which to expect the
2577 * SIGCHLD for. */
2578
2579 case SERVICE_START:
2580 case SERVICE_START_POST:
2581 /* If we were hoping for the daemon to write its PID file,
2582 * we can give up now. */
2583 if (s->pid_file_pathspec) {
2584 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
2585
2586 service_unwatch_pid_file(s);
2587 if (s->state == SERVICE_START)
2588 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2589 else
2590 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2591 }
2592 break;
2593
2594 case SERVICE_RUNNING:
2595 /* service_enter_running() will figure out what to do */
2596 service_enter_running(s, SERVICE_SUCCESS);
2597 break;
2598
2599 case SERVICE_STOP_SIGABRT:
2600 case SERVICE_STOP_SIGTERM:
2601 case SERVICE_STOP_SIGKILL:
2602
2603 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2604 service_enter_stop_post(s, SERVICE_SUCCESS);
2605
2606 break;
2607
2608 case SERVICE_STOP_POST:
2609 case SERVICE_FINAL_SIGTERM:
2610 case SERVICE_FINAL_SIGKILL:
2611 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2612 service_enter_dead(s, SERVICE_SUCCESS, true);
2613
2614 break;
2615
2616 default:
2617 ;
2618 }
2619 }
2620
2621 static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2622 Service *s = SERVICE(u);
2623 ServiceResult f;
2624
2625 assert(s);
2626 assert(pid >= 0);
2627
2628 if (is_clean_exit(code, status, s->type == SERVICE_ONESHOT ? EXIT_CLEAN_COMMAND : EXIT_CLEAN_DAEMON, &s->success_status))
2629 f = SERVICE_SUCCESS;
2630 else if (code == CLD_EXITED)
2631 f = SERVICE_FAILURE_EXIT_CODE;
2632 else if (code == CLD_KILLED)
2633 f = SERVICE_FAILURE_SIGNAL;
2634 else if (code == CLD_DUMPED)
2635 f = SERVICE_FAILURE_CORE_DUMP;
2636 else
2637 assert_not_reached("Unknown code");
2638
2639 if (s->main_pid == pid) {
2640 /* Forking services may occasionally move to a new PID.
2641 * As long as they update the PID file before exiting the old
2642 * PID, they're fine. */
2643 if (service_load_pid_file(s, false) == 0)
2644 return;
2645
2646 s->main_pid = 0;
2647 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
2648
2649 if (s->main_command) {
2650 /* If this is not a forking service than the
2651 * main process got started and hence we copy
2652 * the exit status so that it is recorded both
2653 * as main and as control process exit
2654 * status */
2655
2656 s->main_command->exec_status = s->main_exec_status;
2657
2658 if (s->main_command->ignore)
2659 f = SERVICE_SUCCESS;
2660 } else if (s->exec_command[SERVICE_EXEC_START]) {
2661
2662 /* If this is a forked process, then we should
2663 * ignore the return value if this was
2664 * configured for the starter process */
2665
2666 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2667 f = SERVICE_SUCCESS;
2668 }
2669
2670 /* When this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
2671 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
2672 * that the service already logged the reason at a higher log level on its own. However, if the service
2673 * died due to a signal, then it most likely didn't say anything about any reason, hence let's raise
2674 * our log level to WARNING then. */
2675
2676 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG :
2677 (code == CLD_EXITED ? LOG_NOTICE : LOG_WARNING),
2678 LOG_UNIT_ID(u),
2679 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2680 sigchld_code_to_string(code), status,
2681 strna(code == CLD_EXITED
2682 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2683 : signal_to_string(status))),
2684 "EXIT_CODE=%s", sigchld_code_to_string(code),
2685 "EXIT_STATUS=%i", status,
2686 NULL);
2687
2688 if (s->result == SERVICE_SUCCESS)
2689 s->result = f;
2690
2691 if (s->main_command &&
2692 s->main_command->command_next &&
2693 f == SERVICE_SUCCESS) {
2694
2695 /* There is another command to *
2696 * execute, so let's do that. */
2697
2698 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
2699 service_run_next_main(s);
2700
2701 } else {
2702
2703 /* The service exited, so the service is officially
2704 * gone. */
2705 s->main_command = NULL;
2706
2707 switch (s->state) {
2708
2709 case SERVICE_START_POST:
2710 case SERVICE_RELOAD:
2711 case SERVICE_STOP:
2712 /* Need to wait until the operation is
2713 * done */
2714 break;
2715
2716 case SERVICE_START:
2717 if (s->type == SERVICE_ONESHOT) {
2718 /* This was our main goal, so let's go on */
2719 if (f == SERVICE_SUCCESS)
2720 service_enter_start_post(s);
2721 else
2722 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2723 break;
2724 }
2725
2726 /* Fall through */
2727
2728 case SERVICE_RUNNING:
2729 service_enter_running(s, f);
2730 break;
2731
2732 case SERVICE_STOP_SIGABRT:
2733 case SERVICE_STOP_SIGTERM:
2734 case SERVICE_STOP_SIGKILL:
2735
2736 if (!control_pid_good(s))
2737 service_enter_stop_post(s, f);
2738
2739 /* If there is still a control process, wait for that first */
2740 break;
2741
2742 case SERVICE_STOP_POST:
2743 case SERVICE_FINAL_SIGTERM:
2744 case SERVICE_FINAL_SIGKILL:
2745
2746 if (!control_pid_good(s))
2747 service_enter_dead(s, f, true);
2748 break;
2749
2750 default:
2751 assert_not_reached("Uh, main process died at wrong time.");
2752 }
2753 }
2754
2755 } else if (s->control_pid == pid) {
2756 s->control_pid = 0;
2757
2758 if (s->control_command) {
2759 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2760
2761 if (s->control_command->ignore)
2762 f = SERVICE_SUCCESS;
2763 }
2764
2765 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2766 "Control process exited, code=%s status=%i",
2767 sigchld_code_to_string(code), status);
2768
2769 if (s->result == SERVICE_SUCCESS)
2770 s->result = f;
2771
2772 /* Immediately get rid of the cgroup, so that the
2773 * kernel doesn't delay the cgroup empty messages for
2774 * the service cgroup any longer than necessary */
2775 service_kill_control_processes(s);
2776
2777 if (s->control_command &&
2778 s->control_command->command_next &&
2779 f == SERVICE_SUCCESS) {
2780
2781 /* There is another command to *
2782 * execute, so let's do that. */
2783
2784 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
2785 service_run_next_control(s);
2786
2787 } else {
2788 /* No further commands for this step, so let's
2789 * figure out what to do next */
2790
2791 s->control_command = NULL;
2792 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2793
2794 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
2795
2796 switch (s->state) {
2797
2798 case SERVICE_START_PRE:
2799 if (f == SERVICE_SUCCESS)
2800 service_enter_start(s);
2801 else
2802 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2803 break;
2804
2805 case SERVICE_START:
2806 if (s->type != SERVICE_FORKING)
2807 /* Maybe spurious event due to a reload that changed the type? */
2808 break;
2809
2810 if (f != SERVICE_SUCCESS) {
2811 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
2812 break;
2813 }
2814
2815 if (s->pid_file) {
2816 bool has_start_post;
2817 int r;
2818
2819 /* Let's try to load the pid file here if we can.
2820 * The PID file might actually be created by a START_POST
2821 * script. In that case don't worry if the loading fails. */
2822
2823 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2824 r = service_load_pid_file(s, !has_start_post);
2825 if (!has_start_post && r < 0) {
2826 r = service_demand_pid_file(s);
2827 if (r < 0 || !cgroup_good(s))
2828 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
2829 break;
2830 }
2831 } else
2832 service_search_main_pid(s);
2833
2834 service_enter_start_post(s);
2835 break;
2836
2837 case SERVICE_START_POST:
2838 if (f != SERVICE_SUCCESS) {
2839 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2840 break;
2841 }
2842
2843 if (s->pid_file) {
2844 int r;
2845
2846 r = service_load_pid_file(s, true);
2847 if (r < 0) {
2848 r = service_demand_pid_file(s);
2849 if (r < 0 || !cgroup_good(s))
2850 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2851 break;
2852 }
2853 } else
2854 service_search_main_pid(s);
2855
2856 service_enter_running(s, SERVICE_SUCCESS);
2857 break;
2858
2859 case SERVICE_RELOAD:
2860 if (f == SERVICE_SUCCESS)
2861 if (service_load_pid_file(s, true) < 0)
2862 service_search_main_pid(s);
2863
2864 s->reload_result = f;
2865 service_enter_running(s, SERVICE_SUCCESS);
2866 break;
2867
2868 case SERVICE_STOP:
2869 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2870 break;
2871
2872 case SERVICE_STOP_SIGABRT:
2873 case SERVICE_STOP_SIGTERM:
2874 case SERVICE_STOP_SIGKILL:
2875 if (main_pid_good(s) <= 0)
2876 service_enter_stop_post(s, f);
2877
2878 /* If there is still a service
2879 * process around, wait until
2880 * that one quit, too */
2881 break;
2882
2883 case SERVICE_STOP_POST:
2884 case SERVICE_FINAL_SIGTERM:
2885 case SERVICE_FINAL_SIGKILL:
2886 if (main_pid_good(s) <= 0)
2887 service_enter_dead(s, f, true);
2888 break;
2889
2890 default:
2891 assert_not_reached("Uh, control process died at wrong time.");
2892 }
2893 }
2894 }
2895
2896 /* Notify clients about changed exit status */
2897 unit_add_to_dbus_queue(u);
2898
2899 /* We got one SIGCHLD for the service, let's watch all
2900 * processes that are now running of the service, and watch
2901 * that. Among the PIDs we then watch will be children
2902 * reassigned to us, which hopefully allows us to identify
2903 * when all children are gone */
2904 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2905 unit_watch_all_pids(u);
2906
2907 /* If the PID set is empty now, then let's finish this off
2908 (On unified we use proper notifications) */
2909 if (cg_unified(SYSTEMD_CGROUP_CONTROLLER) <= 0 && set_isempty(u->pids))
2910 service_notify_cgroup_empty_event(u);
2911 }
2912
2913 static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2914 Service *s = SERVICE(userdata);
2915
2916 assert(s);
2917 assert(source == s->timer_event_source);
2918
2919 switch (s->state) {
2920
2921 case SERVICE_START_PRE:
2922 case SERVICE_START:
2923 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
2924 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2925 break;
2926
2927 case SERVICE_START_POST:
2928 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
2929 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2930 break;
2931
2932 case SERVICE_RUNNING:
2933 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2934 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2935 break;
2936
2937 case SERVICE_RELOAD:
2938 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
2939 service_kill_control_processes(s);
2940 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2941 service_enter_running(s, SERVICE_SUCCESS);
2942 break;
2943
2944 case SERVICE_STOP:
2945 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
2946 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2947 break;
2948
2949 case SERVICE_STOP_SIGABRT:
2950 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2951 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2952 break;
2953
2954 case SERVICE_STOP_SIGTERM:
2955 if (s->kill_context.send_sigkill) {
2956 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
2957 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2958 } else {
2959 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
2960 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2961 }
2962
2963 break;
2964
2965 case SERVICE_STOP_SIGKILL:
2966 /* Uh, we sent a SIGKILL and it is still not gone?
2967 * Must be something we cannot kill, so let's just be
2968 * weirded out and continue */
2969
2970 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
2971 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
2972 break;
2973
2974 case SERVICE_STOP_POST:
2975 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
2976 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
2977 break;
2978
2979 case SERVICE_FINAL_SIGTERM:
2980 if (s->kill_context.send_sigkill) {
2981 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
2982 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
2983 } else {
2984 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
2985 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
2986 }
2987
2988 break;
2989
2990 case SERVICE_FINAL_SIGKILL:
2991 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
2992 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
2993 break;
2994
2995 case SERVICE_AUTO_RESTART:
2996 log_unit_info(UNIT(s),
2997 s->restart_usec > 0 ?
2998 "Service hold-off time over, scheduling restart." :
2999 "Service has no hold-off time, scheduling restart.");
3000 service_enter_restart(s);
3001 break;
3002
3003 default:
3004 assert_not_reached("Timeout at wrong time.");
3005 }
3006
3007 return 0;
3008 }
3009
3010 static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
3011 Service *s = SERVICE(userdata);
3012 char t[FORMAT_TIMESPAN_MAX];
3013 usec_t watchdog_usec;
3014
3015 assert(s);
3016 assert(source == s->watchdog_event_source);
3017
3018 watchdog_usec = service_get_watchdog_usec(s);
3019
3020 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
3021 format_timespan(t, sizeof(t), watchdog_usec, 1));
3022
3023 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
3024
3025 return 0;
3026 }
3027
3028 static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
3029 Service *s = SERVICE(u);
3030 _cleanup_free_ char *cc = NULL;
3031 bool notify_dbus = false;
3032 const char *e;
3033
3034 assert(u);
3035
3036 cc = strv_join(tags, ", ");
3037
3038 if (s->notify_access == NOTIFY_NONE) {
3039 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
3040 return;
3041 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
3042 if (s->main_pid != 0)
3043 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
3044 else
3045 log_unit_debug(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
3046 return;
3047 } else
3048 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
3049
3050 /* Interpret MAINPID= */
3051 e = strv_find_startswith(tags, "MAINPID=");
3052 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
3053 if (parse_pid(e, &pid) < 0)
3054 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
3055 else {
3056 service_set_main_pid(s, pid);
3057 unit_watch_pid(UNIT(s), pid);
3058 notify_dbus = true;
3059 }
3060 }
3061
3062 /* Interpret RELOADING= */
3063 if (strv_find(tags, "RELOADING=1")) {
3064
3065 s->notify_state = NOTIFY_RELOADING;
3066
3067 if (s->state == SERVICE_RUNNING)
3068 service_enter_reload_by_notify(s);
3069
3070 notify_dbus = true;
3071 }
3072
3073 /* Interpret READY= */
3074 if (strv_find(tags, "READY=1")) {
3075
3076 s->notify_state = NOTIFY_READY;
3077
3078 /* Type=notify services inform us about completed
3079 * initialization with READY=1 */
3080 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
3081 service_enter_start_post(s);
3082
3083 /* Sending READY=1 while we are reloading informs us
3084 * that the reloading is complete */
3085 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
3086 service_enter_running(s, SERVICE_SUCCESS);
3087
3088 notify_dbus = true;
3089 }
3090
3091 /* Interpret STOPPING= */
3092 if (strv_find(tags, "STOPPING=1")) {
3093
3094 s->notify_state = NOTIFY_STOPPING;
3095
3096 if (s->state == SERVICE_RUNNING)
3097 service_enter_stop_by_notify(s);
3098
3099 notify_dbus = true;
3100 }
3101
3102 /* Interpret STATUS= */
3103 e = strv_find_startswith(tags, "STATUS=");
3104 if (e) {
3105 _cleanup_free_ char *t = NULL;
3106
3107 if (!isempty(e)) {
3108 if (!utf8_is_valid(e))
3109 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
3110 else {
3111 t = strdup(e);
3112 if (!t)
3113 log_oom();
3114 }
3115 }
3116
3117 if (!streq_ptr(s->status_text, t)) {
3118
3119 free_and_replace(s->status_text, t);
3120
3121 notify_dbus = true;
3122 }
3123 }
3124
3125 /* Interpret ERRNO= */
3126 e = strv_find_startswith(tags, "ERRNO=");
3127 if (e) {
3128 int status_errno;
3129
3130 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
3131 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
3132 else {
3133 if (s->status_errno != status_errno) {
3134 s->status_errno = status_errno;
3135 notify_dbus = true;
3136 }
3137 }
3138 }
3139
3140 /* Interpret WATCHDOG= */
3141 if (strv_find(tags, "WATCHDOG=1"))
3142 service_reset_watchdog(s);
3143
3144 if (strv_find(tags, "FDSTORE=1")) {
3145 const char *name;
3146
3147 name = strv_find_startswith(tags, "FDNAME=");
3148 if (name && !fdname_is_valid(name)) {
3149 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
3150 name = NULL;
3151 }
3152
3153 service_add_fd_store_set(s, fds, name);
3154 }
3155
3156 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
3157 if (e) {
3158 usec_t watchdog_override_usec;
3159 if (safe_atou64(e, &watchdog_override_usec) < 0)
3160 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
3161 else
3162 service_reset_watchdog_timeout(s, watchdog_override_usec);
3163 }
3164
3165 /* Notify clients about changed status or main pid */
3166 if (notify_dbus)
3167 unit_add_to_dbus_queue(u);
3168 }
3169
3170 static int service_get_timeout(Unit *u, usec_t *timeout) {
3171 Service *s = SERVICE(u);
3172 uint64_t t;
3173 int r;
3174
3175 if (!s->timer_event_source)
3176 return 0;
3177
3178 r = sd_event_source_get_time(s->timer_event_source, &t);
3179 if (r < 0)
3180 return r;
3181 if (t == USEC_INFINITY)
3182 return 0;
3183
3184 *timeout = t;
3185 return 1;
3186 }
3187
3188 static void service_bus_name_owner_change(
3189 Unit *u,
3190 const char *name,
3191 const char *old_owner,
3192 const char *new_owner) {
3193
3194 Service *s = SERVICE(u);
3195 int r;
3196
3197 assert(s);
3198 assert(name);
3199
3200 assert(streq(s->bus_name, name));
3201 assert(old_owner || new_owner);
3202
3203 if (old_owner && new_owner)
3204 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
3205 else if (old_owner)
3206 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
3207 else
3208 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
3209
3210 s->bus_name_good = !!new_owner;
3211
3212 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3213 r = free_and_strdup(&s->bus_name_owner, new_owner);
3214 if (r < 0) {
3215 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
3216 return;
3217 }
3218
3219 if (s->type == SERVICE_DBUS) {
3220
3221 /* service_enter_running() will figure out what to
3222 * do */
3223 if (s->state == SERVICE_RUNNING)
3224 service_enter_running(s, SERVICE_SUCCESS);
3225 else if (s->state == SERVICE_START && new_owner)
3226 service_enter_start_post(s);
3227
3228 } else if (new_owner &&
3229 s->main_pid <= 0 &&
3230 (s->state == SERVICE_START ||
3231 s->state == SERVICE_START_POST ||
3232 s->state == SERVICE_RUNNING ||
3233 s->state == SERVICE_RELOAD)) {
3234
3235 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
3236 pid_t pid;
3237
3238 /* Try to acquire PID from bus service */
3239
3240 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
3241 if (r >= 0)
3242 r = sd_bus_creds_get_pid(creds, &pid);
3243 if (r >= 0) {
3244 log_unit_debug(u, "D-Bus name %s is now owned by process %u", name, (unsigned) pid);
3245
3246 service_set_main_pid(s, pid);
3247 unit_watch_pid(UNIT(s), pid);
3248 }
3249 }
3250 }
3251
3252 int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
3253 _cleanup_free_ char *peer = NULL;
3254 int r;
3255
3256 assert(s);
3257 assert(fd >= 0);
3258
3259 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
3260 * to be configured. We take ownership of the passed fd on success. */
3261
3262 if (UNIT(s)->load_state != UNIT_LOADED)
3263 return -EINVAL;
3264
3265 if (s->socket_fd >= 0)
3266 return -EBUSY;
3267
3268 if (s->state != SERVICE_DEAD)
3269 return -EAGAIN;
3270
3271 if (getpeername_pretty(fd, true, &peer) >= 0) {
3272
3273 if (UNIT(s)->description) {
3274 _cleanup_free_ char *a;
3275
3276 a = strjoin(UNIT(s)->description, " (", peer, ")");
3277 if (!a)
3278 return -ENOMEM;
3279
3280 r = unit_set_description(UNIT(s), a);
3281 } else
3282 r = unit_set_description(UNIT(s), peer);
3283
3284 if (r < 0)
3285 return r;
3286 }
3287
3288 r = unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3289 if (r < 0)
3290 return r;
3291
3292 s->socket_fd = fd;
3293 s->socket_fd_selinux_context_net = selinux_context_net;
3294
3295 unit_ref_set(&s->accept_socket, UNIT(sock));
3296 return 0;
3297 }
3298
3299 static void service_reset_failed(Unit *u) {
3300 Service *s = SERVICE(u);
3301
3302 assert(s);
3303
3304 if (s->state == SERVICE_FAILED)
3305 service_set_state(s, SERVICE_DEAD);
3306
3307 s->result = SERVICE_SUCCESS;
3308 s->reload_result = SERVICE_SUCCESS;
3309 }
3310
3311 static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
3312 Service *s = SERVICE(u);
3313
3314 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
3315 }
3316
3317 static int service_main_pid(Unit *u) {
3318 Service *s = SERVICE(u);
3319
3320 assert(s);
3321
3322 return s->main_pid;
3323 }
3324
3325 static int service_control_pid(Unit *u) {
3326 Service *s = SERVICE(u);
3327
3328 assert(s);
3329
3330 return s->control_pid;
3331 }
3332
3333 static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
3334 [SERVICE_RESTART_NO] = "no",
3335 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
3336 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
3337 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
3338 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
3339 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3340 [SERVICE_RESTART_ALWAYS] = "always",
3341 };
3342
3343 DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3344
3345 static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
3346 [SERVICE_SIMPLE] = "simple",
3347 [SERVICE_FORKING] = "forking",
3348 [SERVICE_ONESHOT] = "oneshot",
3349 [SERVICE_DBUS] = "dbus",
3350 [SERVICE_NOTIFY] = "notify",
3351 [SERVICE_IDLE] = "idle"
3352 };
3353
3354 DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3355
3356 static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
3357 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3358 [SERVICE_EXEC_START] = "ExecStart",
3359 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3360 [SERVICE_EXEC_RELOAD] = "ExecReload",
3361 [SERVICE_EXEC_STOP] = "ExecStop",
3362 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3363 };
3364
3365 DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3366
3367 static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3368 [NOTIFY_NONE] = "none",
3369 [NOTIFY_MAIN] = "main",
3370 [NOTIFY_ALL] = "all"
3371 };
3372
3373 DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3374
3375 static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3376 [NOTIFY_UNKNOWN] = "unknown",
3377 [NOTIFY_READY] = "ready",
3378 [NOTIFY_RELOADING] = "reloading",
3379 [NOTIFY_STOPPING] = "stopping",
3380 };
3381
3382 DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3383
3384 static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3385 [SERVICE_SUCCESS] = "success",
3386 [SERVICE_FAILURE_RESOURCES] = "resources",
3387 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3388 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3389 [SERVICE_FAILURE_SIGNAL] = "signal",
3390 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
3391 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3392 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
3393 };
3394
3395 DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3396
3397 const UnitVTable service_vtable = {
3398 .object_size = sizeof(Service),
3399 .exec_context_offset = offsetof(Service, exec_context),
3400 .cgroup_context_offset = offsetof(Service, cgroup_context),
3401 .kill_context_offset = offsetof(Service, kill_context),
3402 .exec_runtime_offset = offsetof(Service, exec_runtime),
3403 .dynamic_creds_offset = offsetof(Service, dynamic_creds),
3404
3405 .sections =
3406 "Unit\0"
3407 "Service\0"
3408 "Install\0",
3409 .private_section = "Service",
3410
3411 .init = service_init,
3412 .done = service_done,
3413 .load = service_load,
3414 .release_resources = service_release_resources,
3415
3416 .coldplug = service_coldplug,
3417
3418 .dump = service_dump,
3419
3420 .start = service_start,
3421 .stop = service_stop,
3422 .reload = service_reload,
3423
3424 .can_reload = service_can_reload,
3425
3426 .kill = service_kill,
3427
3428 .serialize = service_serialize,
3429 .deserialize_item = service_deserialize_item,
3430
3431 .active_state = service_active_state,
3432 .sub_state_to_string = service_sub_state_to_string,
3433
3434 .check_gc = service_check_gc,
3435
3436 .sigchld_event = service_sigchld_event,
3437
3438 .reset_failed = service_reset_failed,
3439
3440 .notify_cgroup_empty = service_notify_cgroup_empty_event,
3441 .notify_message = service_notify_message,
3442
3443 .main_pid = service_main_pid,
3444 .control_pid = service_control_pid,
3445
3446 .bus_name_owner_change = service_bus_name_owner_change,
3447
3448 .bus_vtable = bus_service_vtable,
3449 .bus_set_property = bus_service_set_property,
3450 .bus_commit_properties = bus_service_commit_properties,
3451
3452 .get_timeout = service_get_timeout,
3453 .can_transient = true,
3454
3455 .status_message_formats = {
3456 .starting_stopping = {
3457 [0] = "Starting %s...",
3458 [1] = "Stopping %s...",
3459 },
3460 .finished_start_job = {
3461 [JOB_DONE] = "Started %s.",
3462 [JOB_FAILED] = "Failed to start %s.",
3463 },
3464 .finished_stop_job = {
3465 [JOB_DONE] = "Stopped %s.",
3466 [JOB_FAILED] = "Stopped (with error) %s.",
3467 },
3468 },
3469 };