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