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