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