]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/service.c
tmpfiles: downgrade error message when operation is not supported (#5692)
[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"
8b43440b 48#include "string-table.h"
07630cea 49#include "string-util.h"
4f5dd394
LP
50#include "strv.h"
51#include "unit-name.h"
4f5dd394
LP
52#include "unit.h"
53#include "utf8.h"
54#include "util.h"
034c6ed7 55
acbb0225 56static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
87f0e418
LP
57 [SERVICE_DEAD] = UNIT_INACTIVE,
58 [SERVICE_START_PRE] = UNIT_ACTIVATING,
59 [SERVICE_START] = UNIT_ACTIVATING,
60 [SERVICE_START_POST] = UNIT_ACTIVATING,
61 [SERVICE_RUNNING] = UNIT_ACTIVE,
80876c20 62 [SERVICE_EXITED] = UNIT_ACTIVE,
032ff4af 63 [SERVICE_RELOAD] = UNIT_RELOADING,
87f0e418 64 [SERVICE_STOP] = UNIT_DEACTIVATING,
db2cb23b 65 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
87f0e418
LP
66 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
67 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
68 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
69 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
70 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
fdf20a31 71 [SERVICE_FAILED] = UNIT_FAILED,
6124958c 72 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
034c6ed7 73};
5cb5a6ff 74
e056b01d
LP
75/* For Type=idle we never want to delay any other jobs, hence we
76 * consider idle jobs active as soon as we start working on them */
77static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
78 [SERVICE_DEAD] = UNIT_INACTIVE,
79 [SERVICE_START_PRE] = UNIT_ACTIVE,
80 [SERVICE_START] = UNIT_ACTIVE,
81 [SERVICE_START_POST] = UNIT_ACTIVE,
82 [SERVICE_RUNNING] = UNIT_ACTIVE,
83 [SERVICE_EXITED] = UNIT_ACTIVE,
84 [SERVICE_RELOAD] = UNIT_RELOADING,
85 [SERVICE_STOP] = UNIT_DEACTIVATING,
db2cb23b 86 [SERVICE_STOP_SIGABRT] = UNIT_DEACTIVATING,
e056b01d
LP
87 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
88 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
89 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
90 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
91 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
92 [SERVICE_FAILED] = UNIT_FAILED,
93 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
94};
95
718db961
LP
96static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
97static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
98static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
99
842129f5 100static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
308d72dc 101static void service_enter_reload_by_notify(Service *s);
842129f5 102
a16e1123
LP
103static void service_init(Unit *u) {
104 Service *s = SERVICE(u);
105
106 assert(u);
ac155bb8 107 assert(u->load_state == UNIT_STUB);
a16e1123 108
1f19a534
OS
109 s->timeout_start_usec = u->manager->default_timeout_start_usec;
110 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
111 s->restart_usec = u->manager->default_restart_usec;
36c16a7c 112 s->runtime_max_usec = USEC_INFINITY;
0b86feac 113 s->type = _SERVICE_TYPE_INVALID;
a16e1123 114 s->socket_fd = -1;
a34ceba6 115 s->stdin_fd = s->stdout_fd = s->stderr_fd = -1;
3185a36b 116 s->guess_main_pid = true;
a16e1123 117
a16e1123
LP
118 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
119}
120
5e94833f
LP
121static void service_unwatch_control_pid(Service *s) {
122 assert(s);
123
124 if (s->control_pid <= 0)
125 return;
126
127 unit_unwatch_pid(UNIT(s), s->control_pid);
128 s->control_pid = 0;
129}
130
131static void service_unwatch_main_pid(Service *s) {
132 assert(s);
133
134 if (s->main_pid <= 0)
135 return;
136
137 unit_unwatch_pid(UNIT(s), s->main_pid);
138 s->main_pid = 0;
139}
140
3e52541e
MS
141static void service_unwatch_pid_file(Service *s) {
142 if (!s->pid_file_pathspec)
143 return;
144
f2341e0a 145 log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
718db961 146 path_spec_unwatch(s->pid_file_pathspec);
3e52541e 147 path_spec_done(s->pid_file_pathspec);
a1e58e8e 148 s->pid_file_pathspec = mfree(s->pid_file_pathspec);
3e52541e
MS
149}
150
5925dd3c 151static int service_set_main_pid(Service *s, pid_t pid) {
e55224ca
LP
152 pid_t ppid;
153
5925dd3c
LP
154 assert(s);
155
156 if (pid <= 1)
157 return -EINVAL;
158
159 if (pid == getpid())
160 return -EINVAL;
161
7400b9d2
LP
162 if (s->main_pid == pid && s->main_pid_known)
163 return 0;
164
165 if (s->main_pid != pid) {
166 service_unwatch_main_pid(s);
167 exec_status_start(&s->main_exec_status, pid);
168 }
41efeaec 169
6dfa5494
LP
170 s->main_pid = pid;
171 s->main_pid_known = true;
172
6bc73acb 173 if (get_process_ppid(pid, &ppid) >= 0 && ppid != getpid()) {
f2341e0a 174 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
175 s->main_pid_alien = true;
176 } else
177 s->main_pid_alien = false;
5925dd3c
LP
178
179 return 0;
180}
181
3e7a1f50 182void service_close_socket_fd(Service *s) {
4f2d528d
LP
183 assert(s);
184
5cc3985e 185 /* Undo the effect of service_set_socket_fd(). */
4f2d528d 186
5cc3985e 187 s->socket_fd = asynchronous_close(s->socket_fd);
6cf6bbc2 188
5cc3985e
LP
189 if (UNIT_ISSET(s->accept_socket)) {
190 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
191 unit_ref_unset(&s->accept_socket);
192 }
6cf6bbc2
LP
193}
194
a6927d7f
MO
195static void service_stop_watchdog(Service *s) {
196 assert(s);
197
718db961 198 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
842129f5 199 s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
a6927d7f
MO
200}
201
2787d83c
M
202static usec_t service_get_watchdog_usec(Service *s) {
203 assert(s);
204
205 if (s->watchdog_override_enable)
206 return s->watchdog_override_usec;
207 else
208 return s->watchdog_usec;
209}
210
842129f5 211static void service_start_watchdog(Service *s) {
bb242b7b 212 int r;
2787d83c 213 usec_t watchdog_usec;
bb242b7b
MO
214
215 assert(s);
216
2787d83c
M
217 watchdog_usec = service_get_watchdog_usec(s);
218 if (watchdog_usec == 0 || watchdog_usec == USEC_INFINITY)
bb242b7b
MO
219 return;
220
718db961 221 if (s->watchdog_event_source) {
2787d83c 222 r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
718db961 223 if (r < 0) {
f2341e0a 224 log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
718db961
LP
225 return;
226 }
227
842129f5 228 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
c4ef3317 229 } else {
6a0f1f6d
LP
230 r = sd_event_add_time(
231 UNIT(s)->manager->event,
232 &s->watchdog_event_source,
233 CLOCK_MONOTONIC,
2787d83c 234 usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
6a0f1f6d 235 service_dispatch_watchdog, s);
c4ef3317 236 if (r < 0) {
f2341e0a 237 log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
c4ef3317
LP
238 return;
239 }
240
7dfbe2e3
TG
241 (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
242
c4ef3317
LP
243 /* Let's process everything else which might be a sign
244 * of living before we consider a service died. */
245 r = sd_event_source_set_priority(s->watchdog_event_source, SD_EVENT_PRIORITY_IDLE);
246 }
718db961 247
bb242b7b 248 if (r < 0)
f2341e0a 249 log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
bb242b7b
MO
250}
251
a6927d7f
MO
252static void service_reset_watchdog(Service *s) {
253 assert(s);
254
255 dual_timestamp_get(&s->watchdog_timestamp);
842129f5 256 service_start_watchdog(s);
a6927d7f
MO
257}
258
2787d83c
M
259static void service_reset_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
260 assert(s);
261
262 s->watchdog_override_enable = true;
263 s->watchdog_override_usec = watchdog_override_usec;
264 service_reset_watchdog(s);
265
266 log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
267 log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
268}
269
a354329f
LP
270static void service_fd_store_unlink(ServiceFDStore *fs) {
271
272 if (!fs)
273 return;
274
275 if (fs->service) {
276 assert(fs->service->n_fd_store > 0);
277 LIST_REMOVE(fd_store, fs->service->fd_store, fs);
278 fs->service->n_fd_store--;
279 }
280
281 if (fs->event_source) {
282 sd_event_source_set_enabled(fs->event_source, SD_EVENT_OFF);
283 sd_event_source_unref(fs->event_source);
284 }
285
8dd4c05b 286 free(fs->fdname);
a354329f
LP
287 safe_close(fs->fd);
288 free(fs);
289}
290
f0bfbfac
ZJS
291static void service_release_fd_store(Service *s) {
292 assert(s);
293
294 log_unit_debug(UNIT(s), "Releasing all stored fds");
295 while (s->fd_store)
296 service_fd_store_unlink(s->fd_store);
297
298 assert(s->n_fd_store == 0);
299}
300
301static void service_release_resources(Unit *u, bool inactive) {
a354329f
LP
302 Service *s = SERVICE(u);
303
304 assert(s);
305
a34ceba6 306 if (!s->fd_store && s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
a354329f
LP
307 return;
308
f0bfbfac 309 log_unit_debug(u, "Releasing resources.");
a354329f 310
a34ceba6
LP
311 s->stdin_fd = safe_close(s->stdin_fd);
312 s->stdout_fd = safe_close(s->stdout_fd);
313 s->stderr_fd = safe_close(s->stderr_fd);
314
f0bfbfac
ZJS
315 if (inactive)
316 service_release_fd_store(s);
a354329f
LP
317}
318
87f0e418
LP
319static void service_done(Unit *u) {
320 Service *s = SERVICE(u);
44d8db9e
LP
321
322 assert(s);
323
a1e58e8e
LP
324 s->pid_file = mfree(s->pid_file);
325 s->status_text = mfree(s->status_text);
efe6e7d3 326
613b411c 327 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
e537352b 328 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
44d8db9e 329 s->control_command = NULL;
867b3b7d 330 s->main_command = NULL;
44d8db9e 331
29206d46
LP
332 dynamic_creds_unref(&s->dynamic_creds);
333
37520c1b
LP
334 exit_status_set_free(&s->restart_prevent_status);
335 exit_status_set_free(&s->restart_force_status);
336 exit_status_set_free(&s->success_status);
96342de6 337
44d8db9e
LP
338 /* This will leak a process, but at least no memory or any of
339 * our resources */
5e94833f
LP
340 service_unwatch_main_pid(s);
341 service_unwatch_control_pid(s);
3e52541e 342 service_unwatch_pid_file(s);
44d8db9e 343
05e343b7 344 if (s->bus_name) {
ac155bb8 345 unit_unwatch_bus_name(u, s->bus_name);
a1e58e8e 346 s->bus_name = mfree(s->bus_name);
05e343b7
LP
347 }
348
d8ccf5fd
DM
349 s->bus_name_owner = mfree(s->bus_name_owner);
350
4f2d528d 351 service_close_socket_fd(s);
9d565427 352 s->peer = socket_peer_unref(s->peer);
4f2d528d 353
57020a3a 354 unit_ref_unset(&s->accept_socket);
f976f3f6 355
bb242b7b
MO
356 service_stop_watchdog(s);
357
718db961 358 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
a354329f 359
f0bfbfac 360 service_release_resources(u, true);
718db961
LP
361}
362
2339fc93
LP
363static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
364 ServiceFDStore *fs = userdata;
365
366 assert(e);
367 assert(fs);
368
369 /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
16f70d63
ZJS
370 log_unit_debug(UNIT(fs->service),
371 "Received %s on stored fd %d (%s), closing.",
372 revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
373 fs->fd, strna(fs->fdname));
2339fc93
LP
374 service_fd_store_unlink(fs);
375 return 0;
376}
377
8dd4c05b 378static int service_add_fd_store(Service *s, int fd, const char *name) {
2339fc93
LP
379 ServiceFDStore *fs;
380 int r;
381
9021ff17
ZJS
382 /* fd is always consumed if we return >= 0 */
383
2339fc93
LP
384 assert(s);
385 assert(fd >= 0);
386
387 if (s->n_fd_store >= s->n_fd_store_max)
b0924635
ZJS
388 return -EXFULL; /* Our store is full.
389 * Use this errno rather than E[NM]FILE to distinguish from
390 * the case where systemd itself hits the file limit. */
2339fc93
LP
391
392 LIST_FOREACH(fd_store, fs, s->fd_store) {
393 r = same_fd(fs->fd, fd);
394 if (r < 0)
395 return r;
396 if (r > 0) {
2339fc93 397 safe_close(fd);
9021ff17 398 return 0; /* fd already included */
2339fc93
LP
399 }
400 }
401
402 fs = new0(ServiceFDStore, 1);
403 if (!fs)
404 return -ENOMEM;
405
406 fs->fd = fd;
407 fs->service = s;
8dd4c05b 408 fs->fdname = strdup(name ?: "stored");
17dec0f7 409 if (!fs->fdname) {
410 free(fs);
8dd4c05b 411 return -ENOMEM;
17dec0f7 412 }
2339fc93
LP
413
414 r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fd, 0, on_fd_store_io, fs);
415 if (r < 0) {
8dd4c05b 416 free(fs->fdname);
2339fc93
LP
417 free(fs);
418 return r;
419 }
420
7dfbe2e3
TG
421 (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
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
LP
616
617 /* Regardless if kdbus is used or not, we always want to be ordered against dbus.socket if both are in the transaction. */
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
8dd4c05b
LP
1070static int service_collect_fds(Service *s, int **fds, char ***fd_names) {
1071 _cleanup_strv_free_ char **rfd_names = NULL;
a354329f 1072 _cleanup_free_ int *rfds = NULL;
8dd4c05b 1073 int rn_fds = 0, r;
44d8db9e
LP
1074
1075 assert(s);
1076 assert(fds);
8dd4c05b 1077 assert(fd_names);
44d8db9e 1078
8dd4c05b 1079 if (s->socket_fd >= 0) {
6cf6bbc2 1080
8dd4c05b 1081 /* Pass the per-connection socket */
57020a3a 1082
8dd4c05b
LP
1083 rfds = new(int, 1);
1084 if (!rfds)
1085 return -ENOMEM;
1086 rfds[0] = s->socket_fd;
57020a3a 1087
8dd4c05b
LP
1088 rfd_names = strv_new("connection", NULL);
1089 if (!rfd_names)
1090 return -ENOMEM;
44d8db9e 1091
8dd4c05b
LP
1092 rn_fds = 1;
1093 } else {
1094 Iterator i;
1095 Unit *u;
44d8db9e 1096
8dd4c05b 1097 /* Pass all our configured sockets for singleton services */
44d8db9e 1098
8dd4c05b
LP
1099 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
1100 _cleanup_free_ int *cfds = NULL;
1101 Socket *sock;
1102 int cn_fds;
44d8db9e 1103
8dd4c05b
LP
1104 if (u->type != UNIT_SOCKET)
1105 continue;
44d8db9e 1106
8dd4c05b 1107 sock = SOCKET(u);
a354329f 1108
8dd4c05b
LP
1109 cn_fds = socket_collect_fds(sock, &cfds);
1110 if (cn_fds < 0)
1111 return cn_fds;
44d8db9e 1112
8dd4c05b
LP
1113 if (cn_fds <= 0)
1114 continue;
79c7626d 1115
8dd4c05b
LP
1116 if (!rfds) {
1117 rfds = cfds;
1118 rn_fds = cn_fds;
1119
1120 cfds = NULL;
1121 } else {
1122 int *t;
1123
1124 t = realloc(rfds, (rn_fds + cn_fds) * sizeof(int));
1125 if (!t)
1126 return -ENOMEM;
1127
1128 memcpy(t + rn_fds, cfds, cn_fds * sizeof(int));
1129
1130 rfds = t;
1131 rn_fds += cn_fds;
1132 }
1133
1134 r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
1135 if (r < 0)
1136 return r;
44d8db9e
LP
1137 }
1138 }
1139
a354329f
LP
1140 if (s->n_fd_store > 0) {
1141 ServiceFDStore *fs;
8dd4c05b 1142 char **nl;
a354329f
LP
1143 int *t;
1144
1145 t = realloc(rfds, (rn_fds + s->n_fd_store) * sizeof(int));
1146 if (!t)
1147 return -ENOMEM;
1148
1149 rfds = t;
8dd4c05b
LP
1150
1151 nl = realloc(rfd_names, (rn_fds + s->n_fd_store + 1) * sizeof(char*));
1152 if (!nl)
1153 return -ENOMEM;
1154
1155 rfd_names = nl;
1156
1157 LIST_FOREACH(fd_store, fs, s->fd_store) {
1158 rfds[rn_fds] = fs->fd;
1159 rfd_names[rn_fds] = strdup(strempty(fs->fdname));
1160 if (!rfd_names[rn_fds])
1161 return -ENOMEM;
1162
1163 rn_fds++;
1164 }
1165
1166 rfd_names[rn_fds] = NULL;
a354329f
LP
1167 }
1168
44d8db9e 1169 *fds = rfds;
8dd4c05b 1170 *fd_names = rfd_names;
3e33402a 1171
a354329f 1172 rfds = NULL;
8dd4c05b 1173 rfd_names = NULL;
79c7626d
LP
1174
1175 return rn_fds;
44d8db9e
LP
1176}
1177
6375bd20
JW
1178static bool service_exec_needs_notify_socket(Service *s, ExecFlags flags) {
1179 assert(s);
1180
1181 /* Notifications are accepted depending on the process and
1182 * the access setting of the service:
1183 * process: \ access: NONE MAIN EXEC ALL
1184 * main no yes yes yes
1185 * control no no yes yes
1186 * other (forked) no no no yes */
1187
1188 if (flags & EXEC_IS_CONTROL)
1189 /* A control process */
1190 return IN_SET(s->notify_access, NOTIFY_EXEC, NOTIFY_ALL);
1191
1192 /* We only spawn main processes and control processes, so any
1193 * process that is not a control process is a main process */
1194 return s->notify_access != NOTIFY_NONE;
1195}
1196
81a2b7ce
LP
1197static int service_spawn(
1198 Service *s,
1199 ExecCommand *c,
21b2ce39 1200 usec_t timeout,
c39f1ce2 1201 ExecFlags flags,
81a2b7ce
LP
1202 pid_t *_pid) {
1203
5125e762 1204 _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL, **fd_names = NULL;
8dd4c05b
LP
1205 _cleanup_free_ int *fds = NULL;
1206 unsigned n_fds = 0, n_env = 0;
4ad49000 1207 const char *path;
8dd4c05b
LP
1208 pid_t pid;
1209
9fa95f85 1210 ExecParameters exec_params = {
c39f1ce2
LP
1211 .flags = flags,
1212 .stdin_fd = -1,
1213 .stdout_fd = -1,
1214 .stderr_fd = -1,
9fa95f85 1215 };
034c6ed7 1216
8dd4c05b
LP
1217 int r;
1218
034c6ed7
LP
1219 assert(s);
1220 assert(c);
1221 assert(_pid);
1222
9c1a61ad
LP
1223 if (flags & EXEC_IS_CONTROL) {
1224 /* If this is a control process, mask the permissions/chroot application if this is requested. */
1225 if (s->permissions_start_only)
1226 exec_params.flags &= ~EXEC_APPLY_PERMISSIONS;
1227 if (s->root_directory_start_only)
1228 exec_params.flags &= ~EXEC_APPLY_CHROOT;
1229 }
1230
5ad096b3
LP
1231 (void) unit_realize_cgroup(UNIT(s));
1232 if (s->reset_cpu_usage) {
1233 (void) unit_reset_cpu_usage(UNIT(s));
1234 s->reset_cpu_usage = false;
1235 }
4ad49000 1236
613b411c
LP
1237 r = unit_setup_exec_runtime(UNIT(s));
1238 if (r < 0)
36c16a7c 1239 return r;
613b411c 1240
29206d46
LP
1241 r = unit_setup_dynamic_creds(UNIT(s));
1242 if (r < 0)
1243 return r;
1244
c39f1ce2 1245 if ((flags & EXEC_PASS_FDS) ||
6cf6bbc2
LP
1246 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1247 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1248 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1249
8dd4c05b
LP
1250 r = service_collect_fds(s, &fds, &fd_names);
1251 if (r < 0)
36c16a7c 1252 return r;
6cf6bbc2 1253
8dd4c05b 1254 n_fds = r;
16f70d63 1255 log_unit_debug(UNIT(s), "Passing %i fds to service", n_fds);
4f2d528d 1256 }
44d8db9e 1257
36c16a7c
LP
1258 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), timeout));
1259 if (r < 0)
1260 return r;
034c6ed7 1261
136dc4c4 1262 our_env = new0(char*, 9);
36c16a7c
LP
1263 if (!our_env)
1264 return -ENOMEM;
c952c6ec 1265
6375bd20 1266 if (service_exec_needs_notify_socket(s, flags))
36c16a7c
LP
1267 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0)
1268 return -ENOMEM;
c952c6ec 1269
2105e76a 1270 if (s->main_pid > 0)
36c16a7c
LP
1271 if (asprintf(our_env + n_env++, "MAINPID="PID_FMT, s->main_pid) < 0)
1272 return -ENOMEM;
2105e76a 1273
c39f1ce2 1274 if (MANAGER_IS_USER(UNIT(s)->manager))
36c16a7c
LP
1275 if (asprintf(our_env + n_env++, "MANAGERPID="PID_FMT, getpid()) < 0)
1276 return -ENOMEM;
97ae63e2 1277
8dd4c05b 1278 if (s->socket_fd >= 0) {
3b1c5241
SL
1279 union sockaddr_union sa;
1280 socklen_t salen = sizeof(sa);
1281
1282 r = getpeername(s->socket_fd, &sa.sa, &salen);
f2dbd059
KR
1283 if (r < 0) {
1284 r = -errno;
1285
1286 /* ENOTCONN is legitimate if the endpoint disappeared on shutdown.
1287 * This connection is over, but the socket unit lives on. */
7dd736ab 1288 if (r != -ENOTCONN || !IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST))
f2dbd059
KR
1289 return r;
1290 }
3b1c5241 1291
359a5bcf 1292 if (r == 0 && IN_SET(sa.sa.sa_family, AF_INET, AF_INET6, AF_VSOCK)) {
3b1c5241
SL
1293 _cleanup_free_ char *addr = NULL;
1294 char *t;
882ac6e7 1295 unsigned port;
3b1c5241
SL
1296
1297 r = sockaddr_pretty(&sa.sa, salen, true, false, &addr);
1298 if (r < 0)
36c16a7c 1299 return r;
3b1c5241
SL
1300
1301 t = strappend("REMOTE_ADDR=", addr);
36c16a7c
LP
1302 if (!t)
1303 return -ENOMEM;
3b1c5241
SL
1304 our_env[n_env++] = t;
1305
882ac6e7
SH
1306 r = sockaddr_port(&sa.sa, &port);
1307 if (r < 0)
1308 return r;
3b1c5241 1309
36c16a7c
LP
1310 if (asprintf(&t, "REMOTE_PORT=%u", port) < 0)
1311 return -ENOMEM;
3b1c5241
SL
1312 our_env[n_env++] = t;
1313 }
1314 }
1315
136dc4c4
LP
1316 if (flags & EXEC_SETENV_RESULT) {
1317 if (asprintf(our_env + n_env++, "SERVICE_RESULT=%s", service_result_to_string(s->result)) < 0)
1318 return -ENOMEM;
1319
1320 if (s->main_exec_status.pid > 0 &&
1321 dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
1322 if (asprintf(our_env + n_env++, "EXIT_CODE=%s", sigchld_code_to_string(s->main_exec_status.code)) < 0)
1323 return -ENOMEM;
1324
1325 if (s->main_exec_status.code == CLD_EXITED)
1326 r = asprintf(our_env + n_env++, "EXIT_STATUS=%i", s->main_exec_status.status);
1327 else
1328 r = asprintf(our_env + n_env++, "EXIT_STATUS=%s", signal_to_string(s->main_exec_status.status));
1329 if (r < 0)
1330 return -ENOMEM;
1331 }
1332 }
1333
97ae63e2 1334 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
36c16a7c
LP
1335 if (!final_env)
1336 return -ENOMEM;
c952c6ec 1337
c39f1ce2 1338 if ((flags & EXEC_IS_CONTROL) && UNIT(s)->cgroup_path) {
63c372cb 1339 path = strjoina(UNIT(s)->cgroup_path, "/control");
ac5b0c13 1340 (void) cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
4ad49000
LP
1341 } else
1342 path = UNIT(s)->cgroup_path;
1343
74dd6b51 1344 exec_params.flags |= MANAGER_IS_SYSTEM(UNIT(s)->manager) ? EXEC_NEW_KEYRING : 0;
5125e762 1345 exec_params.argv = c->argv;
c39f1ce2 1346 exec_params.environment = final_env;
9fa95f85 1347 exec_params.fds = fds;
8dd4c05b 1348 exec_params.fd_names = fd_names;
9fa95f85 1349 exec_params.n_fds = n_fds;
7d5ceb64 1350 exec_params.confirm_spawn = manager_get_confirm_spawn(UNIT(s)->manager);
9fa95f85
DM
1351 exec_params.cgroup_supported = UNIT(s)->manager->cgroup_supported;
1352 exec_params.cgroup_path = path;
a931ad47 1353 exec_params.cgroup_delegate = s->cgroup_context.delegate;
9fa95f85 1354 exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
9fa95f85 1355 exec_params.watchdog_usec = s->watchdog_usec;
a34ceba6 1356 exec_params.selinux_context_net = s->socket_fd_selinux_context_net;
9fa95f85
DM
1357 if (s->type == SERVICE_IDLE)
1358 exec_params.idle_pipe = UNIT(s)->manager->idle_pipe;
a34ceba6
LP
1359 exec_params.stdin_fd = s->stdin_fd;
1360 exec_params.stdout_fd = s->stdout_fd;
1361 exec_params.stderr_fd = s->stderr_fd;
9fa95f85 1362
f2341e0a
LP
1363 r = exec_spawn(UNIT(s),
1364 c,
9e2f7c11 1365 &s->exec_context,
9fa95f85 1366 &exec_params,
613b411c 1367 s->exec_runtime,
29206d46 1368 &s->dynamic_creds,
9e2f7c11 1369 &pid);
9e2f7c11 1370 if (r < 0)
36c16a7c 1371 return r;
034c6ed7 1372
117dcc57 1373 r = unit_watch_pid(UNIT(s), pid);
e8b509d3 1374 if (r < 0) /* FIXME: we need to do something here */
36c16a7c 1375 return r;
034c6ed7
LP
1376
1377 *_pid = pid;
1378
5cb5a6ff 1379 return 0;
034c6ed7
LP
1380}
1381
80876c20
LP
1382static int main_pid_good(Service *s) {
1383 assert(s);
1384
1385 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1386 * don't know */
1387
fc08079e 1388 /* If we know the pid file, then let's just check if it is
80876c20 1389 * still valid */
6dfa5494
LP
1390 if (s->main_pid_known) {
1391
1392 /* If it's an alien child let's check if it is still
1393 * alive ... */
62220cf7 1394 if (s->main_pid_alien && s->main_pid > 0)
9f5650ae 1395 return pid_is_alive(s->main_pid);
6dfa5494
LP
1396
1397 /* .. otherwise assume we'll get a SIGCHLD for it,
1398 * which we really should wait for to collect exit
1399 * status and code */
80876c20 1400 return s->main_pid > 0;
6dfa5494 1401 }
80876c20
LP
1402
1403 /* We don't know the pid */
1404 return -EAGAIN;
1405}
1406
44a6b1b6 1407_pure_ static int control_pid_good(Service *s) {
80876c20
LP
1408 assert(s);
1409
1410 return s->control_pid > 0;
1411}
1412
1413static int cgroup_good(Service *s) {
1414 int r;
1415
1416 assert(s);
1417
4ad49000
LP
1418 if (!UNIT(s)->cgroup_path)
1419 return 0;
1420
6f883237 1421 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path);
117dcc57 1422 if (r < 0)
80876c20
LP
1423 return r;
1424
1425 return !r;
1426}
1427
a509f0e6
LP
1428static bool service_shall_restart(Service *s) {
1429 assert(s);
1430
1431 /* Don't restart after manual stops */
1432 if (s->forbid_restart)
1433 return false;
1434
1435 /* Never restart if this is configured as special exception */
1436 if (exit_status_set_test(&s->restart_prevent_status, s->main_exec_status.code, s->main_exec_status.status))
1437 return false;
1438
1439 /* Restart if the exit code/status are configured as restart triggers */
1440 if (exit_status_set_test(&s->restart_force_status, s->main_exec_status.code, s->main_exec_status.status))
1441 return true;
1442
1443 switch (s->restart) {
1444
1445 case SERVICE_RESTART_NO:
1446 return false;
1447
1448 case SERVICE_RESTART_ALWAYS:
1449 return true;
1450
1451 case SERVICE_RESTART_ON_SUCCESS:
1452 return s->result == SERVICE_SUCCESS;
1453
1454 case SERVICE_RESTART_ON_FAILURE:
1455 return s->result != SERVICE_SUCCESS;
1456
1457 case SERVICE_RESTART_ON_ABNORMAL:
1458 return !IN_SET(s->result, SERVICE_SUCCESS, SERVICE_FAILURE_EXIT_CODE);
1459
1460 case SERVICE_RESTART_ON_WATCHDOG:
1461 return s->result == SERVICE_FAILURE_WATCHDOG;
1462
1463 case SERVICE_RESTART_ON_ABORT:
1464 return IN_SET(s->result, SERVICE_FAILURE_SIGNAL, SERVICE_FAILURE_CORE_DUMP);
1465
1466 default:
1467 assert_not_reached("unknown restart setting");
1468 }
1469}
1470
f42806df 1471static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
034c6ed7
LP
1472 int r;
1473 assert(s);
1474
a0fef983 1475 if (s->result == SERVICE_SUCCESS)
f42806df 1476 s->result = f;
034c6ed7 1477
0c7f15b3
MS
1478 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1479
2928b0a8 1480 if (s->result != SERVICE_SUCCESS) {
f2341e0a 1481 log_unit_warning(UNIT(s), "Failed with result '%s'.", service_result_to_string(s->result));
87a47f99 1482 emergency_action(UNIT(s)->manager, s->emergency_action, UNIT(s)->reboot_arg, "service failed");
2928b0a8 1483 }
93ae25e6 1484
a509f0e6 1485 if (allow_restart && service_shall_restart(s)) {
034c6ed7 1486
36c16a7c 1487 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
f42806df 1488 if (r < 0)
034c6ed7
LP
1489 goto fail;
1490
1491 service_set_state(s, SERVICE_AUTO_RESTART);
0c7f15b3 1492 }
034c6ed7 1493
f2341e0a 1494 /* The next restart might not be a manual stop, hence reset the flag indicating manual stops */
47342320
LP
1495 s->forbid_restart = false;
1496
e66cf1a3 1497 /* We want fresh tmpdirs in case service is started again immediately */
613b411c
LP
1498 exec_runtime_destroy(s->exec_runtime);
1499 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
c17ec25e 1500
29206d46 1501 /* Also, remove the runtime directory */
e66cf1a3
LP
1502 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1503
00d9ef85
LP
1504 /* Get rid of the IPC bits of the user */
1505 unit_unref_uid_gid(UNIT(s), true);
1506
29206d46
LP
1507 /* Release the user, and destroy it if we are the only remaining owner */
1508 dynamic_creds_destroy(&s->dynamic_creds);
1509
9285c9ff
LN
1510 /* Try to delete the pid file. At this point it will be
1511 * out-of-date, and some software might be confused by it, so
1512 * let's remove it. */
1513 if (s->pid_file)
fabab190 1514 (void) unlink(s->pid_file);
9285c9ff 1515
034c6ed7
LP
1516 return;
1517
1518fail:
f2341e0a 1519 log_unit_warning_errno(UNIT(s), r, "Failed to run install restart timer: %m");
f42806df 1520 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
1521}
1522
f42806df 1523static void service_enter_stop_post(Service *s, ServiceResult f) {
034c6ed7
LP
1524 int r;
1525 assert(s);
1526
a0fef983 1527 if (s->result == SERVICE_SUCCESS)
f42806df 1528 s->result = f;
034c6ed7 1529
5e94833f 1530 service_unwatch_control_pid(s);
a911bb9a 1531 unit_watch_all_pids(UNIT(s));
5e94833f 1532
117dcc57
ZJS
1533 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1534 if (s->control_command) {
867b3b7d
LP
1535 s->control_command_id = SERVICE_EXEC_STOP_POST;
1536
ecedd90f
LP
1537 r = service_spawn(s,
1538 s->control_command,
21b2ce39 1539 s->timeout_stop_usec,
136dc4c4 1540 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
ecedd90f
LP
1541 &s->control_pid);
1542 if (r < 0)
034c6ed7
LP
1543 goto fail;
1544
80876c20
LP
1545 service_set_state(s, SERVICE_STOP_POST);
1546 } else
ac84d1fb 1547 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
1548
1549 return;
1550
1551fail:
f2341e0a 1552 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop-post' task: %m");
f42806df 1553 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
1554}
1555
4940c0b0
LP
1556static int state_to_kill_operation(ServiceState state) {
1557 switch (state) {
1558
1559 case SERVICE_STOP_SIGABRT:
1560 return KILL_ABORT;
1561
1562 case SERVICE_STOP_SIGTERM:
1563 case SERVICE_FINAL_SIGTERM:
1564 return KILL_TERMINATE;
1565
1566 case SERVICE_STOP_SIGKILL:
1567 case SERVICE_FINAL_SIGKILL:
1568 return KILL_KILL;
1569
1570 default:
1571 return _KILL_OPERATION_INVALID;
1572 }
1573}
1574
f42806df 1575static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
034c6ed7 1576 int r;
034c6ed7
LP
1577
1578 assert(s);
1579
a0fef983 1580 if (s->result == SERVICE_SUCCESS)
f42806df 1581 s->result = f;
034c6ed7 1582
a911bb9a
LP
1583 unit_watch_all_pids(UNIT(s));
1584
cd2086fe
LP
1585 r = unit_kill_context(
1586 UNIT(s),
1587 &s->kill_context,
4940c0b0 1588 state_to_kill_operation(state),
cd2086fe
LP
1589 s->main_pid,
1590 s->control_pid,
1591 s->main_pid_alien);
ac84d1fb 1592
cd2086fe
LP
1593 if (r < 0)
1594 goto fail;
034c6ed7 1595
cd2086fe 1596 if (r > 0) {
36c16a7c
LP
1597 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
1598 if (r < 0)
1599 goto fail;
d6ea93e3 1600
80876c20 1601 service_set_state(s, state);
1db0db4b 1602 } else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM) && s->kill_context.send_sigkill)
ac84d1fb 1603 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_SUCCESS);
1db0db4b 1604 else if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 1605 service_enter_stop_post(s, SERVICE_SUCCESS);
1db0db4b 1606 else if (state == SERVICE_FINAL_SIGTERM && s->kill_context.send_sigkill)
ac84d1fb 1607 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_SUCCESS);
80876c20 1608 else
f42806df 1609 service_enter_dead(s, SERVICE_SUCCESS, true);
034c6ed7
LP
1610
1611 return;
1612
1613fail:
f2341e0a 1614 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
034c6ed7 1615
a00973af 1616 if (IN_SET(state, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL))
f42806df 1617 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
034c6ed7 1618 else
f42806df 1619 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
1620}
1621
308d72dc
LP
1622static void service_enter_stop_by_notify(Service *s) {
1623 assert(s);
1624
1625 unit_watch_all_pids(UNIT(s));
1626
36c16a7c 1627 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_stop_usec));
308d72dc 1628
6041a7ee
MS
1629 /* The service told us it's stopping, so it's as if we SIGTERM'd it. */
1630 service_set_state(s, SERVICE_STOP_SIGTERM);
308d72dc
LP
1631}
1632
f42806df 1633static void service_enter_stop(Service *s, ServiceResult f) {
034c6ed7 1634 int r;
5925dd3c 1635
034c6ed7
LP
1636 assert(s);
1637
a0fef983 1638 if (s->result == SERVICE_SUCCESS)
f42806df 1639 s->result = f;
034c6ed7 1640
5e94833f 1641 service_unwatch_control_pid(s);
a911bb9a 1642 unit_watch_all_pids(UNIT(s));
5e94833f 1643
117dcc57
ZJS
1644 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
1645 if (s->control_command) {
867b3b7d
LP
1646 s->control_command_id = SERVICE_EXEC_STOP;
1647
ecedd90f
LP
1648 r = service_spawn(s,
1649 s->control_command,
21b2ce39 1650 s->timeout_stop_usec,
136dc4c4 1651 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_SETENV_RESULT,
ecedd90f
LP
1652 &s->control_pid);
1653 if (r < 0)
034c6ed7
LP
1654 goto fail;
1655
80876c20
LP
1656 service_set_state(s, SERVICE_STOP);
1657 } else
f42806df 1658 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
1659
1660 return;
1661
1662fail:
f2341e0a 1663 log_unit_warning_errno(UNIT(s), r, "Failed to run 'stop' task: %m");
f42806df 1664 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
1665}
1666
957c3cf9
LP
1667static bool service_good(Service *s) {
1668 int main_pid_ok;
1669 assert(s);
1670
1671 if (s->type == SERVICE_DBUS && !s->bus_name_good)
1672 return false;
1673
1674 main_pid_ok = main_pid_good(s);
1675 if (main_pid_ok > 0) /* It's alive */
1676 return true;
1677 if (main_pid_ok == 0) /* It's dead */
1678 return false;
1679
1680 /* OK, we don't know anything about the main PID, maybe
1681 * because there is none. Let's check the control group
1682 * instead. */
1683
1684 return cgroup_good(s) != 0;
1685}
1686
f42806df 1687static void service_enter_running(Service *s, ServiceResult f) {
80876c20
LP
1688 assert(s);
1689
a0fef983 1690 if (s->result == SERVICE_SUCCESS)
f42806df 1691 s->result = f;
80876c20 1692
089b64d5
LP
1693 service_unwatch_control_pid(s);
1694
957c3cf9 1695 if (service_good(s)) {
308d72dc
LP
1696
1697 /* If there are any queued up sd_notify()
1698 * notifications, process them now */
1699 if (s->notify_state == NOTIFY_RELOADING)
1700 service_enter_reload_by_notify(s);
1701 else if (s->notify_state == NOTIFY_STOPPING)
1702 service_enter_stop_by_notify(s);
36c16a7c 1703 else {
308d72dc 1704 service_set_state(s, SERVICE_RUNNING);
36c16a7c
LP
1705 service_arm_timer(s, usec_add(UNIT(s)->active_enter_timestamp.monotonic, s->runtime_max_usec));
1706 }
308d72dc 1707
3d474ef7 1708 } else if (f != SERVICE_SUCCESS)
c3fda31d 1709 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3d474ef7 1710 else if (s->remain_after_exit)
80876c20
LP
1711 service_set_state(s, SERVICE_EXITED);
1712 else
f42806df 1713 service_enter_stop(s, SERVICE_SUCCESS);
80876c20
LP
1714}
1715
034c6ed7
LP
1716static void service_enter_start_post(Service *s) {
1717 int r;
1718 assert(s);
1719
5e94833f 1720 service_unwatch_control_pid(s);
842129f5 1721 service_reset_watchdog(s);
bb242b7b 1722
117dcc57
ZJS
1723 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
1724 if (s->control_command) {
867b3b7d
LP
1725 s->control_command_id = SERVICE_EXEC_START_POST;
1726
ecedd90f
LP
1727 r = service_spawn(s,
1728 s->control_command,
21b2ce39 1729 s->timeout_start_usec,
9c1a61ad 1730 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
ecedd90f
LP
1731 &s->control_pid);
1732 if (r < 0)
034c6ed7
LP
1733 goto fail;
1734
80876c20
LP
1735 service_set_state(s, SERVICE_START_POST);
1736 } else
f42806df 1737 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
1738
1739 return;
1740
1741fail:
f2341e0a 1742 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-post' task: %m");
f42806df 1743 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
1744}
1745
4ad49000
LP
1746static void service_kill_control_processes(Service *s) {
1747 char *p;
1748
1749 if (!UNIT(s)->cgroup_path)
1750 return;
1751
63c372cb 1752 p = strjoina(UNIT(s)->cgroup_path, "/control");
1d98fef1 1753 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, CGROUP_SIGCONT|CGROUP_IGNORE_SELF|CGROUP_REMOVE, NULL, NULL, NULL);
4ad49000
LP
1754}
1755
034c6ed7 1756static void service_enter_start(Service *s) {
4ad49000 1757 ExecCommand *c;
36c16a7c 1758 usec_t timeout;
034c6ed7
LP
1759 pid_t pid;
1760 int r;
1761
1762 assert(s);
1763
41efeaec
LP
1764 service_unwatch_control_pid(s);
1765 service_unwatch_main_pid(s);
80876c20 1766
8f53a7b8
LP
1767 /* We want to ensure that nobody leaks processes from
1768 * START_PRE here, so let's go on a killing spree, People
1769 * should not spawn long running processes from START_PRE. */
4ad49000 1770 service_kill_control_processes(s);
8f53a7b8 1771
867b3b7d
LP
1772 if (s->type == SERVICE_FORKING) {
1773 s->control_command_id = SERVICE_EXEC_START;
1774 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
1775
1776 s->main_command = NULL;
1777 } else {
1778 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
1779 s->control_command = NULL;
1780
1781 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
1782 }
34e9ba66 1783
96fb8242 1784 if (!c) {
47fffb35
LP
1785 if (s->type != SERVICE_ONESHOT) {
1786 /* There's no command line configured for the main command? Hmm, that is strange. This can only
1787 * happen if the configuration changes at runtime. In this case, let's enter a failure
1788 * state. */
1789 log_unit_error(UNIT(s), "There's no 'start' task anymore we could start: %m");
1790 r = -ENXIO;
1791 goto fail;
1792 }
1793
96fb8242
LP
1794 service_enter_start_post(s);
1795 return;
1796 }
1797
36c16a7c
LP
1798 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE))
1799 /* For simple + idle this is the main process. We don't apply any timeout here, but
1800 * service_enter_running() will later apply the .runtime_max_usec timeout. */
1801 timeout = USEC_INFINITY;
1802 else
1803 timeout = s->timeout_start_usec;
1804
ecedd90f
LP
1805 r = service_spawn(s,
1806 c,
36c16a7c 1807 timeout,
b08af3b1 1808 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
ecedd90f
LP
1809 &pid);
1810 if (r < 0)
034c6ed7
LP
1811 goto fail;
1812
36c16a7c 1813 if (IN_SET(s->type, SERVICE_SIMPLE, SERVICE_IDLE)) {
034c6ed7
LP
1814 /* For simple services we immediately start
1815 * the START_POST binaries. */
1816
5925dd3c 1817 service_set_main_pid(s, pid);
034c6ed7
LP
1818 service_enter_start_post(s);
1819
1820 } else if (s->type == SERVICE_FORKING) {
1821
1822 /* For forking services we wait until the start
1823 * process exited. */
1824
e55224ca 1825 s->control_pid = pid;
80876c20
LP
1826 service_set_state(s, SERVICE_START);
1827
36c16a7c 1828 } else if (IN_SET(s->type, SERVICE_ONESHOT, SERVICE_DBUS, SERVICE_NOTIFY)) {
7d55e835 1829
34e9ba66 1830 /* For oneshot services we wait until the start
7d55e835
LP
1831 * process exited, too, but it is our main process. */
1832
05e343b7 1833 /* For D-Bus services we know the main pid right away,
8c47c732
LP
1834 * but wait for the bus name to appear on the
1835 * bus. Notify services are similar. */
05e343b7 1836
5925dd3c 1837 service_set_main_pid(s, pid);
80876c20 1838 service_set_state(s, SERVICE_START);
034c6ed7
LP
1839 } else
1840 assert_not_reached("Unknown service type");
1841
1842 return;
1843
1844fail:
f2341e0a 1845 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start' task: %m");
c3fda31d 1846 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
1847}
1848
1849static void service_enter_start_pre(Service *s) {
1850 int r;
1851
1852 assert(s);
1853
5e94833f
LP
1854 service_unwatch_control_pid(s);
1855
117dcc57
ZJS
1856 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
1857 if (s->control_command) {
8f53a7b8
LP
1858 /* Before we start anything, let's clear up what might
1859 * be left from previous runs. */
4ad49000 1860 service_kill_control_processes(s);
8f53a7b8 1861
867b3b7d
LP
1862 s->control_command_id = SERVICE_EXEC_START_PRE;
1863
ecedd90f
LP
1864 r = service_spawn(s,
1865 s->control_command,
21b2ce39 1866 s->timeout_start_usec,
9c1a61ad 1867 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|EXEC_APPLY_TTY_STDIN,
ecedd90f
LP
1868 &s->control_pid);
1869 if (r < 0)
034c6ed7
LP
1870 goto fail;
1871
80876c20
LP
1872 service_set_state(s, SERVICE_START_PRE);
1873 } else
034c6ed7
LP
1874 service_enter_start(s);
1875
1876 return;
1877
1878fail:
f2341e0a 1879 log_unit_warning_errno(UNIT(s), r, "Failed to run 'start-pre' task: %m");
f42806df 1880 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
1881}
1882
1883static void service_enter_restart(Service *s) {
4afd3348 1884 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7 1885 int r;
398ef8ba 1886
034c6ed7
LP
1887 assert(s);
1888
a8bb2e65
LP
1889 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
1890 /* Don't restart things if we are going down anyway */
f2341e0a 1891 log_unit_info(UNIT(s), "Stop job pending for unit, delaying automatic restart.");
2edfa366 1892
36c16a7c 1893 r = service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->restart_usec));
a8bb2e65 1894 if (r < 0)
2edfa366 1895 goto fail;
feae8adb
DW
1896
1897 return;
2edfa366
LP
1898 }
1899
48bb5876
DW
1900 /* Any units that are bound to this service must also be
1901 * restarted. We use JOB_RESTART (instead of the more obvious
1902 * JOB_START) here so that those dependency jobs will be added
1903 * as well. */
4bd29fe5 1904 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, &error, NULL);
48bb5876 1905 if (r < 0)
034c6ed7
LP
1906 goto fail;
1907
a8bb2e65
LP
1908 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
1909 * it will be canceled as part of the service_stop() call that
1910 * is executed as part of JOB_RESTART. */
1911
f2341e0a 1912 log_unit_debug(UNIT(s), "Scheduled restart job.");
034c6ed7
LP
1913 return;
1914
1915fail:
f2341e0a 1916 log_unit_warning(UNIT(s), "Failed to schedule restart job: %s", bus_error_message(&error, -r));
f42806df 1917 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
1918}
1919
308d72dc
LP
1920static void service_enter_reload_by_notify(Service *s) {
1921 assert(s);
1922
36c16a7c 1923 service_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_start_usec));
308d72dc
LP
1924 service_set_state(s, SERVICE_RELOAD);
1925}
1926
034c6ed7
LP
1927static void service_enter_reload(Service *s) {
1928 int r;
1929
1930 assert(s);
1931
5e94833f 1932 service_unwatch_control_pid(s);
95c906ae 1933 s->reload_result = SERVICE_SUCCESS;
5e94833f 1934
117dcc57
ZJS
1935 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
1936 if (s->control_command) {
867b3b7d
LP
1937 s->control_command_id = SERVICE_EXEC_RELOAD;
1938
ecedd90f
LP
1939 r = service_spawn(s,
1940 s->control_command,
21b2ce39 1941 s->timeout_start_usec,
9c1a61ad 1942 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL,
ecedd90f
LP
1943 &s->control_pid);
1944 if (r < 0)
034c6ed7
LP
1945 goto fail;
1946
80876c20
LP
1947 service_set_state(s, SERVICE_RELOAD);
1948 } else
f42806df 1949 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
1950
1951 return;
1952
1953fail:
f2341e0a 1954 log_unit_warning_errno(UNIT(s), r, "Failed to run 'reload' task: %m");
f42806df
LP
1955 s->reload_result = SERVICE_FAILURE_RESOURCES;
1956 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
1957}
1958
f42806df 1959static void service_run_next_control(Service *s) {
36c16a7c 1960 usec_t timeout;
034c6ed7
LP
1961 int r;
1962
1963 assert(s);
1964 assert(s->control_command);
1965 assert(s->control_command->command_next);
1966
34e9ba66 1967 assert(s->control_command_id != SERVICE_EXEC_START);
034c6ed7 1968
34e9ba66 1969 s->control_command = s->control_command->command_next;
5e94833f
LP
1970 service_unwatch_control_pid(s);
1971
36c16a7c
LP
1972 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD))
1973 timeout = s->timeout_start_usec;
1974 else
1975 timeout = s->timeout_stop_usec;
1976
ecedd90f
LP
1977 r = service_spawn(s,
1978 s->control_command,
36c16a7c 1979 timeout,
9c1a61ad 1980 EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_IS_CONTROL|
136dc4c4
LP
1981 (IN_SET(s->control_command_id, SERVICE_EXEC_START_PRE, SERVICE_EXEC_STOP_POST) ? EXEC_APPLY_TTY_STDIN : 0)|
1982 (IN_SET(s->control_command_id, SERVICE_EXEC_STOP, SERVICE_EXEC_STOP_POST) ? EXEC_SETENV_RESULT : 0),
ecedd90f
LP
1983 &s->control_pid);
1984 if (r < 0)
034c6ed7
LP
1985 goto fail;
1986
1987 return;
1988
1989fail:
f2341e0a 1990 log_unit_warning_errno(UNIT(s), r, "Failed to run next control task: %m");
034c6ed7 1991
c3fda31d 1992 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_STOP))
f42806df 1993 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7 1994 else if (s->state == SERVICE_STOP_POST)
f42806df 1995 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
e2f3b44c 1996 else if (s->state == SERVICE_RELOAD) {
f42806df
LP
1997 s->reload_result = SERVICE_FAILURE_RESOURCES;
1998 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c 1999 } else
f42806df 2000 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
5cb5a6ff
LP
2001}
2002
f42806df 2003static void service_run_next_main(Service *s) {
34e9ba66
LP
2004 pid_t pid;
2005 int r;
2006
2007 assert(s);
867b3b7d
LP
2008 assert(s->main_command);
2009 assert(s->main_command->command_next);
2010 assert(s->type == SERVICE_ONESHOT);
34e9ba66 2011
867b3b7d 2012 s->main_command = s->main_command->command_next;
34e9ba66
LP
2013 service_unwatch_main_pid(s);
2014
ecedd90f
LP
2015 r = service_spawn(s,
2016 s->main_command,
21b2ce39 2017 s->timeout_start_usec,
b08af3b1 2018 EXEC_PASS_FDS|EXEC_APPLY_PERMISSIONS|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN|EXEC_SET_WATCHDOG,
ecedd90f
LP
2019 &pid);
2020 if (r < 0)
34e9ba66
LP
2021 goto fail;
2022
2023 service_set_main_pid(s, pid);
2024
2025 return;
2026
2027fail:
f2341e0a 2028 log_unit_warning_errno(UNIT(s), r, "Failed to run next main task: %m");
f42806df 2029 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
34e9ba66
LP
2030}
2031
87f0e418
LP
2032static int service_start(Unit *u) {
2033 Service *s = SERVICE(u);
07299350 2034 int r;
5cb5a6ff
LP
2035
2036 assert(s);
2037
034c6ed7
LP
2038 /* We cannot fulfill this request right now, try again later
2039 * please! */
a00973af
LP
2040 if (IN_SET(s->state,
2041 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2042 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
5cb5a6ff
LP
2043 return -EAGAIN;
2044
034c6ed7 2045 /* Already on it! */
a00973af 2046 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST))
034c6ed7
LP
2047 return 0;
2048
2e9d6c12 2049 /* A service that will be restarted must be stopped first to
7f2cddae 2050 * trigger BindsTo and/or OnFailure dependencies. If a user
2e9d6c12 2051 * does not want to wait for the holdoff time to elapse, the
d4943dc7
LP
2052 * service should be manually restarted, not started. We
2053 * simply return EAGAIN here, so that any start jobs stay
2054 * queued, and assume that the auto restart timer will
2055 * eventually trigger the restart. */
2056 if (s->state == SERVICE_AUTO_RESTART)
a8bb2e65 2057 return -EAGAIN;
2e9d6c12 2058
a00973af 2059 assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_FAILED));
5cb5a6ff 2060
07299350
LP
2061 /* Make sure we don't enter a busy loop of some kind. */
2062 r = unit_start_limit_test(u);
2063 if (r < 0) {
2064 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT_HIT, false);
2065 return r;
2066 }
2067
4b58153d
LP
2068 r = unit_acquire_invocation_id(u);
2069 if (r < 0)
2070 return r;
2071
f42806df
LP
2072 s->result = SERVICE_SUCCESS;
2073 s->reload_result = SERVICE_SUCCESS;
034c6ed7 2074 s->main_pid_known = false;
6dfa5494 2075 s->main_pid_alien = false;
47342320 2076 s->forbid_restart = false;
5ad096b3 2077 s->reset_cpu_usage = true;
034c6ed7 2078
a1e58e8e 2079 s->status_text = mfree(s->status_text);
8cfdb077
LP
2080 s->status_errno = 0;
2081
308d72dc
LP
2082 s->notify_state = NOTIFY_UNKNOWN;
2083
2787d83c
M
2084 s->watchdog_override_enable = false;
2085 s->watchdog_override_usec = 0;
2086
034c6ed7 2087 service_enter_start_pre(s);
82a2b6bb 2088 return 1;
5cb5a6ff
LP
2089}
2090
87f0e418
LP
2091static int service_stop(Unit *u) {
2092 Service *s = SERVICE(u);
5cb5a6ff
LP
2093
2094 assert(s);
2095
a509f0e6 2096 /* Don't create restart jobs from manual stops. */
47342320 2097 s->forbid_restart = true;
034c6ed7 2098
e537352b 2099 /* Already on it */
a00973af
LP
2100 if (IN_SET(s->state,
2101 SERVICE_STOP, SERVICE_STOP_SIGABRT, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
2102 SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL))
e537352b
LP
2103 return 0;
2104
f0c7b229 2105 /* A restart will be scheduled or is in progress. */
034c6ed7 2106 if (s->state == SERVICE_AUTO_RESTART) {
0c7f15b3 2107 service_set_state(s, SERVICE_DEAD);
034c6ed7
LP
2108 return 0;
2109 }
2110
3f6c78dc
LP
2111 /* If there's already something running we go directly into
2112 * kill mode. */
a00973af 2113 if (IN_SET(s->state, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RELOAD)) {
f42806df 2114 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
3f6c78dc
LP
2115 return 0;
2116 }
5cb5a6ff 2117
a00973af 2118 assert(IN_SET(s->state, SERVICE_RUNNING, SERVICE_EXITED));
3a762661 2119
f42806df 2120 service_enter_stop(s, SERVICE_SUCCESS);
82a2b6bb 2121 return 1;
5cb5a6ff
LP
2122}
2123
87f0e418
LP
2124static int service_reload(Unit *u) {
2125 Service *s = SERVICE(u);
034c6ed7
LP
2126
2127 assert(s);
2128
80876c20 2129 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
034c6ed7
LP
2130
2131 service_enter_reload(s);
2d018ae2 2132 return 1;
5cb5a6ff
LP
2133}
2134
44a6b1b6 2135_pure_ static bool service_can_reload(Unit *u) {
87f0e418 2136 Service *s = SERVICE(u);
034c6ed7
LP
2137
2138 assert(s);
2139
2140 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2141}
2142
a16e1123
LP
2143static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2144 Service *s = SERVICE(u);
2339fc93 2145 ServiceFDStore *fs;
a34ceba6 2146 int r;
a16e1123
LP
2147
2148 assert(u);
2149 assert(f);
2150 assert(fds);
2151
2152 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
f42806df
LP
2153 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2154 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
a16e1123
LP
2155
2156 if (s->control_pid > 0)
f06db334 2157 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
a16e1123 2158
5925dd3c 2159 if (s->main_pid_known && s->main_pid > 0)
ccd06097 2160 unit_serialize_item_format(u, f, "main-pid", PID_FMT, s->main_pid);
a16e1123
LP
2161
2162 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
de1d4f9b 2163 unit_serialize_item(u, f, "bus-name-good", yes_no(s->bus_name_good));
d8ccf5fd 2164 unit_serialize_item(u, f, "bus-name-owner", s->bus_name_owner);
a16e1123 2165
a34ceba6
LP
2166 r = unit_serialize_item_escaped(u, f, "status-text", s->status_text);
2167 if (r < 0)
2168 return r;
3a2776bc 2169
cfc4eb4c
LP
2170 /* FIXME: There's a minor uncleanliness here: if there are
2171 * multiple commands attached here, we will start from the
2172 * first one again */
a16e1123 2173 if (s->control_command_id >= 0)
f06db334 2174 unit_serialize_item(u, f, "control-command", service_exec_command_to_string(s->control_command_id));
a16e1123 2175
a34ceba6
LP
2176 r = unit_serialize_item_fd(u, f, fds, "stdin-fd", s->stdin_fd);
2177 if (r < 0)
2178 return r;
2179 r = unit_serialize_item_fd(u, f, fds, "stdout-fd", s->stdout_fd);
2180 if (r < 0)
2181 return r;
2182 r = unit_serialize_item_fd(u, f, fds, "stderr-fd", s->stderr_fd);
2183 if (r < 0)
2184 return r;
e44da745 2185
9dfb64f8
ZJS
2186 if (UNIT_ISSET(s->accept_socket)) {
2187 r = unit_serialize_item(u, f, "accept-socket", UNIT_DEREF(s->accept_socket)->id);
2188 if (r < 0)
2189 return r;
2190 }
2191
a34ceba6 2192 r = unit_serialize_item_fd(u, f, fds, "socket-fd", s->socket_fd);
a34ceba6
LP
2193 if (r < 0)
2194 return r;
e44da745 2195
2339fc93 2196 LIST_FOREACH(fd_store, fs, s->fd_store) {
8dd4c05b 2197 _cleanup_free_ char *c = NULL;
2339fc93
LP
2198 int copy;
2199
2200 copy = fdset_put_dup(fds, fs->fd);
2201 if (copy < 0)
2202 return copy;
2203
8dd4c05b
LP
2204 c = cescape(fs->fdname);
2205
2206 unit_serialize_item_format(u, f, "fd-store-fd", "%i %s", copy, strempty(c));
2339fc93
LP
2207 }
2208
ecdbca40 2209 if (s->main_exec_status.pid > 0) {
f06db334
LP
2210 unit_serialize_item_format(u, f, "main-exec-status-pid", PID_FMT, s->main_exec_status.pid);
2211 dual_timestamp_serialize(f, "main-exec-status-start", &s->main_exec_status.start_timestamp);
2212 dual_timestamp_serialize(f, "main-exec-status-exit", &s->main_exec_status.exit_timestamp);
ecdbca40 2213
799fd0fd 2214 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
f06db334
LP
2215 unit_serialize_item_format(u, f, "main-exec-status-code", "%i", s->main_exec_status.code);
2216 unit_serialize_item_format(u, f, "main-exec-status-status", "%i", s->main_exec_status.status);
ecdbca40
LP
2217 }
2218 }
f06db334 2219
36b693a6 2220 dual_timestamp_serialize(f, "watchdog-timestamp", &s->watchdog_timestamp);
ecdbca40 2221
a34ceba6 2222 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
6aca9a58 2223
2787d83c
M
2224 if (s->watchdog_override_enable)
2225 unit_serialize_item_format(u, f, "watchdog-override-usec", USEC_FMT, s->watchdog_override_usec);
2226
a16e1123
LP
2227 return 0;
2228}
2229
2230static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2231 Service *s = SERVICE(u);
2339fc93 2232 int r;
a16e1123
LP
2233
2234 assert(u);
2235 assert(key);
2236 assert(value);
2237 assert(fds);
2238
2239 if (streq(key, "state")) {
2240 ServiceState state;
2241
117dcc57
ZJS
2242 state = service_state_from_string(value);
2243 if (state < 0)
f2341e0a 2244 log_unit_debug(u, "Failed to parse state value: %s", value);
a16e1123
LP
2245 else
2246 s->deserialized_state = state;
f42806df
LP
2247 } else if (streq(key, "result")) {
2248 ServiceResult f;
2249
2250 f = service_result_from_string(value);
2251 if (f < 0)
f2341e0a 2252 log_unit_debug(u, "Failed to parse result value: %s", value);
f42806df
LP
2253 else if (f != SERVICE_SUCCESS)
2254 s->result = f;
2255
2256 } else if (streq(key, "reload-result")) {
2257 ServiceResult f;
2258
2259 f = service_result_from_string(value);
2260 if (f < 0)
f2341e0a 2261 log_unit_debug(u, "Failed to parse reload result value: %s", value);
f42806df
LP
2262 else if (f != SERVICE_SUCCESS)
2263 s->reload_result = f;
a16e1123 2264
a16e1123 2265 } else if (streq(key, "control-pid")) {
5925dd3c 2266 pid_t pid;
a16e1123 2267
e364ad06 2268 if (parse_pid(value, &pid) < 0)
f2341e0a 2269 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
a16e1123 2270 else
e55224ca 2271 s->control_pid = pid;
a16e1123 2272 } else if (streq(key, "main-pid")) {
5925dd3c 2273 pid_t pid;
a16e1123 2274
e364ad06 2275 if (parse_pid(value, &pid) < 0)
f2341e0a 2276 log_unit_debug(u, "Failed to parse main-pid value: %s", value);
7400b9d2
LP
2277 else {
2278 service_set_main_pid(s, pid);
2279 unit_watch_pid(UNIT(s), pid);
2280 }
a16e1123
LP
2281 } else if (streq(key, "main-pid-known")) {
2282 int b;
2283
117dcc57
ZJS
2284 b = parse_boolean(value);
2285 if (b < 0)
f2341e0a 2286 log_unit_debug(u, "Failed to parse main-pid-known value: %s", value);
a16e1123
LP
2287 else
2288 s->main_pid_known = b;
de1d4f9b
WF
2289 } else if (streq(key, "bus-name-good")) {
2290 int b;
2291
2292 b = parse_boolean(value);
2293 if (b < 0)
2294 log_unit_debug(u, "Failed to parse bus-name-good value: %s", value);
2295 else
2296 s->bus_name_good = b;
d8ccf5fd
DM
2297 } else if (streq(key, "bus-name-owner")) {
2298 r = free_and_strdup(&s->bus_name_owner, value);
2299 if (r < 0)
2300 log_unit_error_errno(u, r, "Unable to deserialize current bus owner %s: %m", value);
3a2776bc
LP
2301 } else if (streq(key, "status-text")) {
2302 char *t;
2303
f2341e0a
LP
2304 r = cunescape(value, 0, &t);
2305 if (r < 0)
2306 log_unit_debug_errno(u, r, "Failed to unescape status text: %s", value);
117dcc57 2307 else {
3a2776bc
LP
2308 free(s->status_text);
2309 s->status_text = t;
2310 }
2311
a16e1123
LP
2312 } else if (streq(key, "control-command")) {
2313 ServiceExecCommand id;
2314
117dcc57
ZJS
2315 id = service_exec_command_from_string(value);
2316 if (id < 0)
f2341e0a 2317 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
a16e1123
LP
2318 else {
2319 s->control_command_id = id;
2320 s->control_command = s->exec_command[id];
2321 }
9dfb64f8
ZJS
2322 } else if (streq(key, "accept-socket")) {
2323 Unit *socket;
2324
2325 r = manager_load_unit(u->manager, value, NULL, NULL, &socket);
2326 if (r < 0)
2327 log_unit_debug_errno(u, r, "Failed to load accept-socket unit: %s", value);
2328 else {
2329 unit_ref_set(&s->accept_socket, socket);
2330 SOCKET(socket)->n_connections++;
2331 }
2332
a16e1123
LP
2333 } else if (streq(key, "socket-fd")) {
2334 int fd;
2335
2336 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2337 log_unit_debug(u, "Failed to parse socket-fd value: %s", value);
a16e1123 2338 else {
574634bc 2339 asynchronous_close(s->socket_fd);
a16e1123
LP
2340 s->socket_fd = fdset_remove(fds, fd);
2341 }
2339fc93 2342 } else if (streq(key, "fd-store-fd")) {
8dd4c05b
LP
2343 const char *fdv;
2344 size_t pf;
2339fc93
LP
2345 int fd;
2346
8dd4c05b
LP
2347 pf = strcspn(value, WHITESPACE);
2348 fdv = strndupa(value, pf);
2349
2350 if (safe_atoi(fdv, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
f2341e0a 2351 log_unit_debug(u, "Failed to parse fd-store-fd value: %s", value);
2339fc93 2352 else {
8dd4c05b
LP
2353 _cleanup_free_ char *t = NULL;
2354 const char *fdn;
2355
2356 fdn = value + pf;
2357 fdn += strspn(fdn, WHITESPACE);
2358 (void) cunescape(fdn, 0, &t);
2359
2360 r = service_add_fd_store(s, fd, t);
2339fc93 2361 if (r < 0)
f2341e0a 2362 log_unit_error_errno(u, r, "Failed to add fd to store: %m");
9021ff17 2363 else
2339fc93
LP
2364 fdset_remove(fds, fd);
2365 }
2366
ecdbca40
LP
2367 } else if (streq(key, "main-exec-status-pid")) {
2368 pid_t pid;
2369
e364ad06 2370 if (parse_pid(value, &pid) < 0)
f2341e0a 2371 log_unit_debug(u, "Failed to parse main-exec-status-pid value: %s", value);
ecdbca40
LP
2372 else
2373 s->main_exec_status.pid = pid;
2374 } else if (streq(key, "main-exec-status-code")) {
2375 int i;
2376
e364ad06 2377 if (safe_atoi(value, &i) < 0)
f2341e0a 2378 log_unit_debug(u, "Failed to parse main-exec-status-code value: %s", value);
ecdbca40
LP
2379 else
2380 s->main_exec_status.code = i;
2381 } else if (streq(key, "main-exec-status-status")) {
2382 int i;
2383
e364ad06 2384 if (safe_atoi(value, &i) < 0)
f2341e0a 2385 log_unit_debug(u, "Failed to parse main-exec-status-status value: %s", value);
ecdbca40
LP
2386 else
2387 s->main_exec_status.status = i;
799fd0fd
LP
2388 } else if (streq(key, "main-exec-status-start"))
2389 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2390 else if (streq(key, "main-exec-status-exit"))
2391 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
a6927d7f
MO
2392 else if (streq(key, "watchdog-timestamp"))
2393 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
613b411c 2394 else if (streq(key, "forbid-restart")) {
6aca9a58
SE
2395 int b;
2396
2397 b = parse_boolean(value);
2398 if (b < 0)
f2341e0a 2399 log_unit_debug(u, "Failed to parse forbid-restart value: %s", value);
6aca9a58
SE
2400 else
2401 s->forbid_restart = b;
a34ceba6
LP
2402 } else if (streq(key, "stdin-fd")) {
2403 int fd;
2404
2405 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2406 log_unit_debug(u, "Failed to parse stdin-fd value: %s", value);
2407 else {
2408 asynchronous_close(s->stdin_fd);
2409 s->stdin_fd = fdset_remove(fds, fd);
1e22b5cd 2410 s->exec_context.stdio_as_fds = true;
a34ceba6
LP
2411 }
2412 } else if (streq(key, "stdout-fd")) {
2413 int fd;
2414
2415 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2416 log_unit_debug(u, "Failed to parse stdout-fd value: %s", value);
2417 else {
2418 asynchronous_close(s->stdout_fd);
2419 s->stdout_fd = fdset_remove(fds, fd);
1e22b5cd 2420 s->exec_context.stdio_as_fds = true;
a34ceba6
LP
2421 }
2422 } else if (streq(key, "stderr-fd")) {
2423 int fd;
2424
2425 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2426 log_unit_debug(u, "Failed to parse stderr-fd value: %s", value);
2427 else {
2428 asynchronous_close(s->stderr_fd);
2429 s->stderr_fd = fdset_remove(fds, fd);
1e22b5cd 2430 s->exec_context.stdio_as_fds = true;
a34ceba6 2431 }
2787d83c
M
2432 } else if (streq(key, "watchdog-override-usec")) {
2433 usec_t watchdog_override_usec;
2434 if (timestamp_deserialize(value, &watchdog_override_usec) < 0)
2435 log_unit_debug(u, "Failed to parse watchdog_override_usec value: %s", value);
2436 else {
2437 s->watchdog_override_enable = true;
2438 s->watchdog_override_usec = watchdog_override_usec;
2439 }
c17ec25e 2440 } else
f2341e0a 2441 log_unit_debug(u, "Unknown serialization key: %s", key);
a16e1123
LP
2442
2443 return 0;
2444}
2445
44a6b1b6 2446_pure_ static UnitActiveState service_active_state(Unit *u) {
e056b01d
LP
2447 const UnitActiveState *table;
2448
87f0e418 2449 assert(u);
5cb5a6ff 2450
e056b01d
LP
2451 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2452
2453 return table[SERVICE(u)->state];
034c6ed7
LP
2454}
2455
10a94420
LP
2456static const char *service_sub_state_to_string(Unit *u) {
2457 assert(u);
2458
2459 return service_state_to_string(SERVICE(u)->state);
2460}
2461
701cc384
LP
2462static bool service_check_gc(Unit *u) {
2463 Service *s = SERVICE(u);
2464
2465 assert(s);
2466
6d55002a
LP
2467 /* Never clean up services that still have a process around,
2468 * even if the service is formally dead. */
2469 if (cgroup_good(s) > 0 ||
2470 main_pid_good(s) > 0 ||
2471 control_pid_good(s) > 0)
2472 return true;
2473
6d55002a
LP
2474 return false;
2475}
2476
3a111838
MS
2477static int service_retry_pid_file(Service *s) {
2478 int r;
2479
2480 assert(s->pid_file);
2481 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2482
2483 r = service_load_pid_file(s, false);
2484 if (r < 0)
2485 return r;
2486
2487 service_unwatch_pid_file(s);
2488
f42806df 2489 service_enter_running(s, SERVICE_SUCCESS);
3a111838
MS
2490 return 0;
2491}
2492
2493static int service_watch_pid_file(Service *s) {
2494 int r;
2495
f2341e0a 2496 log_unit_debug(UNIT(s), "Setting watch for PID file %s", s->pid_file_pathspec->path);
8bb2d17d 2497
718db961 2498 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
3a111838
MS
2499 if (r < 0)
2500 goto fail;
2501
2502 /* the pidfile might have appeared just before we set the watch */
f2341e0a 2503 log_unit_debug(UNIT(s), "Trying to read PID file %s in case it changed", s->pid_file_pathspec->path);
3a111838
MS
2504 service_retry_pid_file(s);
2505
2506 return 0;
2507fail:
f2341e0a 2508 log_unit_error_errno(UNIT(s), r, "Failed to set a watch for PID file %s: %m", s->pid_file_pathspec->path);
3a111838
MS
2509 service_unwatch_pid_file(s);
2510 return r;
2511}
2512
2513static int service_demand_pid_file(Service *s) {
2514 PathSpec *ps;
2515
2516 assert(s->pid_file);
2517 assert(!s->pid_file_pathspec);
2518
2519 ps = new0(PathSpec, 1);
2520 if (!ps)
2521 return -ENOMEM;
2522
718db961 2523 ps->unit = UNIT(s);
3a111838
MS
2524 ps->path = strdup(s->pid_file);
2525 if (!ps->path) {
2526 free(ps);
2527 return -ENOMEM;
2528 }
2529
2530 path_kill_slashes(ps->path);
2531
2532 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2533 * keep their PID file open all the time. */
2534 ps->type = PATH_MODIFIED;
2535 ps->inotify_fd = -1;
2536
2537 s->pid_file_pathspec = ps;
2538
2539 return service_watch_pid_file(s);
2540}
2541
718db961 2542static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
e14c2802
LP
2543 PathSpec *p = userdata;
2544 Service *s;
2545
2546 assert(p);
2547
2548 s = SERVICE(p->unit);
3a111838
MS
2549
2550 assert(s);
2551 assert(fd >= 0);
2552 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2553 assert(s->pid_file_pathspec);
57020a3a 2554 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3a111838 2555
f2341e0a 2556 log_unit_debug(UNIT(s), "inotify event");
3a111838 2557
e14c2802 2558 if (path_spec_fd_event(p, events) < 0)
3a111838
MS
2559 goto fail;
2560
2561 if (service_retry_pid_file(s) == 0)
718db961 2562 return 0;
3a111838
MS
2563
2564 if (service_watch_pid_file(s) < 0)
2565 goto fail;
2566
718db961
LP
2567 return 0;
2568
3a111838
MS
2569fail:
2570 service_unwatch_pid_file(s);
f42806df 2571 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
718db961 2572 return 0;
3a111838
MS
2573}
2574
a911bb9a
LP
2575static void service_notify_cgroup_empty_event(Unit *u) {
2576 Service *s = SERVICE(u);
2577
2578 assert(u);
2579
f2341e0a 2580 log_unit_debug(u, "cgroup is empty");
a911bb9a
LP
2581
2582 switch (s->state) {
2583
2584 /* Waiting for SIGCHLD is usually more interesting,
2585 * because it includes return codes/signals. Which is
2586 * why we ignore the cgroup events for most cases,
2587 * except when we don't know pid which to expect the
2588 * SIGCHLD for. */
2589
2590 case SERVICE_START:
71e529fc 2591 if (s->type == SERVICE_NOTIFY) {
3d474ef7 2592 /* No chance of getting a ready notification anymore */
c3fda31d 2593 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
71e529fc
JW
2594 break;
2595 }
2596
2597 /* Fall through */
2598
2599 case SERVICE_START_POST:
2600 if (s->pid_file_pathspec) {
3d474ef7 2601 /* Give up hoping for the daemon to write its PID file */
f2341e0a 2602 log_unit_warning(u, "Daemon never wrote its PID file. Failing.");
8bb2d17d 2603
a911bb9a
LP
2604 service_unwatch_pid_file(s);
2605 if (s->state == SERVICE_START)
c3fda31d 2606 service_enter_stop_post(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a 2607 else
c35755fb 2608 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
a911bb9a
LP
2609 }
2610 break;
2611
2612 case SERVICE_RUNNING:
2613 /* service_enter_running() will figure out what to do */
2614 service_enter_running(s, SERVICE_SUCCESS);
2615 break;
2616
db2cb23b 2617 case SERVICE_STOP_SIGABRT:
a911bb9a
LP
2618 case SERVICE_STOP_SIGTERM:
2619 case SERVICE_STOP_SIGKILL:
2620
2621 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2622 service_enter_stop_post(s, SERVICE_SUCCESS);
2623
2624 break;
2625
2626 case SERVICE_STOP_POST:
2627 case SERVICE_FINAL_SIGTERM:
2628 case SERVICE_FINAL_SIGKILL:
2629 if (main_pid_good(s) <= 0 && !control_pid_good(s))
2630 service_enter_dead(s, SERVICE_SUCCESS, true);
2631
2632 break;
2633
2634 default:
2635 ;
2636 }
2637}
2638
87f0e418
LP
2639static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2640 Service *s = SERVICE(u);
f42806df 2641 ServiceResult f;
5cb5a6ff
LP
2642
2643 assert(s);
034c6ed7
LP
2644 assert(pid >= 0);
2645
1f0958f6 2646 if (is_clean_exit(code, status, s->type == SERVICE_ONESHOT ? EXIT_CLEAN_COMMAND : EXIT_CLEAN_DAEMON, &s->success_status))
f42806df
LP
2647 f = SERVICE_SUCCESS;
2648 else if (code == CLD_EXITED)
2649 f = SERVICE_FAILURE_EXIT_CODE;
2650 else if (code == CLD_KILLED)
2651 f = SERVICE_FAILURE_SIGNAL;
2652 else if (code == CLD_DUMPED)
2653 f = SERVICE_FAILURE_CORE_DUMP;
d06dacd0 2654 else
cfc4eb4c 2655 assert_not_reached("Unknown code");
034c6ed7
LP
2656
2657 if (s->main_pid == pid) {
db01f8b3
MS
2658 /* Forking services may occasionally move to a new PID.
2659 * As long as they update the PID file before exiting the old
2660 * PID, they're fine. */
5375410b 2661 if (service_load_pid_file(s, false) == 0)
db01f8b3 2662 return;
034c6ed7 2663
034c6ed7 2664 s->main_pid = 0;
6ea832a2 2665 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
034c6ed7 2666
867b3b7d 2667 if (s->main_command) {
fbeefb45
LP
2668 /* If this is not a forking service than the
2669 * main process got started and hence we copy
2670 * the exit status so that it is recorded both
2671 * as main and as control process exit
2672 * status */
2673
867b3b7d 2674 s->main_command->exec_status = s->main_exec_status;
b708e7ce 2675
867b3b7d 2676 if (s->main_command->ignore)
f42806df 2677 f = SERVICE_SUCCESS;
fbeefb45
LP
2678 } else if (s->exec_command[SERVICE_EXEC_START]) {
2679
2680 /* If this is a forked process, then we should
2681 * ignore the return value if this was
2682 * configured for the starter process */
2683
2684 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2685 f = SERVICE_SUCCESS;
034c6ed7
LP
2686 }
2687
5368222d
LP
2688 /* When this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
2689 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
2690 * that the service already logged the reason at a higher log level on its own. However, if the service
2691 * died due to a signal, then it most likely didn't say anything about any reason, hence let's raise
2692 * our log level to WARNING then. */
2693
2694 log_struct(f == SERVICE_SUCCESS ? LOG_DEBUG :
2695 (code == CLD_EXITED ? LOG_NOTICE : LOG_WARNING),
f2341e0a
LP
2696 LOG_UNIT_ID(u),
2697 LOG_UNIT_MESSAGE(u, "Main process exited, code=%s, status=%i/%s",
2698 sigchld_code_to_string(code), status,
e2cc6eca
LP
2699 strna(code == CLD_EXITED
2700 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2701 : signal_to_string(status))),
f2341e0a
LP
2702 "EXIT_CODE=%s", sigchld_code_to_string(code),
2703 "EXIT_STATUS=%i", status,
2704 NULL);
f42806df 2705
a0fef983 2706 if (s->result == SERVICE_SUCCESS)
f42806df 2707 s->result = f;
034c6ed7 2708
867b3b7d
LP
2709 if (s->main_command &&
2710 s->main_command->command_next &&
f42806df 2711 f == SERVICE_SUCCESS) {
034c6ed7 2712
34e9ba66
LP
2713 /* There is another command to *
2714 * execute, so let's do that. */
034c6ed7 2715
f2341e0a 2716 log_unit_debug(u, "Running next main command for state %s.", service_state_to_string(s->state));
f42806df 2717 service_run_next_main(s);
034c6ed7 2718
34e9ba66
LP
2719 } else {
2720
2721 /* The service exited, so the service is officially
2722 * gone. */
867b3b7d 2723 s->main_command = NULL;
34e9ba66
LP
2724
2725 switch (s->state) {
2726
2727 case SERVICE_START_POST:
2728 case SERVICE_RELOAD:
2729 case SERVICE_STOP:
2730 /* Need to wait until the operation is
2731 * done */
c4653a4d 2732 break;
7d55e835 2733
34e9ba66
LP
2734 case SERVICE_START:
2735 if (s->type == SERVICE_ONESHOT) {
2736 /* This was our main goal, so let's go on */
f42806df 2737 if (f == SERVICE_SUCCESS)
34e9ba66
LP
2738 service_enter_start_post(s);
2739 else
c3fda31d 2740 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
34e9ba66 2741 break;
3d474ef7
JW
2742 } else if (s->type == SERVICE_NOTIFY) {
2743 /* Only enter running through a notification, so that the
2744 * SERVICE_START state signifies that no ready notification
2745 * has been received */
2746 if (f != SERVICE_SUCCESS)
c3fda31d 2747 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3d474ef7
JW
2748 else if (!s->remain_after_exit)
2749 /* The service has never been active */
c3fda31d 2750 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3d474ef7 2751 break;
34e9ba66 2752 }
034c6ed7 2753
bfba3256
LP
2754 /* Fall through */
2755
34e9ba66 2756 case SERVICE_RUNNING:
f42806df 2757 service_enter_running(s, f);
34e9ba66 2758 break;
034c6ed7 2759
db2cb23b 2760 case SERVICE_STOP_SIGABRT:
34e9ba66
LP
2761 case SERVICE_STOP_SIGTERM:
2762 case SERVICE_STOP_SIGKILL:
5cb5a6ff 2763
34e9ba66 2764 if (!control_pid_good(s))
f42806df 2765 service_enter_stop_post(s, f);
5cb5a6ff 2766
34e9ba66
LP
2767 /* If there is still a control process, wait for that first */
2768 break;
2769
bf108e55
LP
2770 case SERVICE_STOP_POST:
2771 case SERVICE_FINAL_SIGTERM:
2772 case SERVICE_FINAL_SIGKILL:
2773
2774 if (!control_pid_good(s))
2775 service_enter_dead(s, f, true);
2776 break;
2777
34e9ba66
LP
2778 default:
2779 assert_not_reached("Uh, main process died at wrong time.");
2780 }
034c6ed7 2781 }
5cb5a6ff 2782
034c6ed7 2783 } else if (s->control_pid == pid) {
34e9ba66
LP
2784 s->control_pid = 0;
2785
b708e7ce 2786 if (s->control_command) {
8bb2d17d 2787 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
a16e1123 2788
b708e7ce 2789 if (s->control_command->ignore)
f42806df 2790 f = SERVICE_SUCCESS;
b708e7ce
LP
2791 }
2792
f2341e0a
LP
2793 log_unit_full(u, f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
2794 "Control process exited, code=%s status=%i",
2795 sigchld_code_to_string(code), status);
f42806df 2796
a0fef983 2797 if (s->result == SERVICE_SUCCESS)
f42806df 2798 s->result = f;
034c6ed7 2799
88f3e0c9
LP
2800 /* Immediately get rid of the cgroup, so that the
2801 * kernel doesn't delay the cgroup empty messages for
2802 * the service cgroup any longer than necessary */
4ad49000 2803 service_kill_control_processes(s);
88f3e0c9 2804
34e9ba66
LP
2805 if (s->control_command &&
2806 s->control_command->command_next &&
f42806df 2807 f == SERVICE_SUCCESS) {
034c6ed7
LP
2808
2809 /* There is another command to *
2810 * execute, so let's do that. */
2811
f2341e0a 2812 log_unit_debug(u, "Running next control command for state %s.", service_state_to_string(s->state));
f42806df 2813 service_run_next_control(s);
034c6ed7 2814
80876c20 2815 } else {
034c6ed7
LP
2816 /* No further commands for this step, so let's
2817 * figure out what to do next */
2818
a16e1123
LP
2819 s->control_command = NULL;
2820 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2821
f2341e0a 2822 log_unit_debug(u, "Got final SIGCHLD for state %s.", service_state_to_string(s->state));
bd982a8b 2823
034c6ed7
LP
2824 switch (s->state) {
2825
2826 case SERVICE_START_PRE:
f42806df 2827 if (f == SERVICE_SUCCESS)
034c6ed7
LP
2828 service_enter_start(s);
2829 else
c3fda31d 2830 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
2831 break;
2832
2833 case SERVICE_START:
bfba3256
LP
2834 if (s->type != SERVICE_FORKING)
2835 /* Maybe spurious event due to a reload that changed the type? */
2836 break;
034c6ed7 2837
f42806df 2838 if (f != SERVICE_SUCCESS) {
c3fda31d 2839 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
3a111838
MS
2840 break;
2841 }
034c6ed7 2842
3a111838 2843 if (s->pid_file) {
f42806df
LP
2844 bool has_start_post;
2845 int r;
2846
3a111838
MS
2847 /* Let's try to load the pid file here if we can.
2848 * The PID file might actually be created by a START_POST
2849 * script. In that case don't worry if the loading fails. */
f42806df
LP
2850
2851 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
2852 r = service_load_pid_file(s, !has_start_post);
3a111838
MS
2853 if (!has_start_post && r < 0) {
2854 r = service_demand_pid_file(s);
2855 if (r < 0 || !cgroup_good(s))
c3fda31d 2856 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_PROTOCOL);
3a111838
MS
2857 break;
2858 }
034c6ed7 2859 } else
783e05d6 2860 service_search_main_pid(s);
034c6ed7 2861
3a111838 2862 service_enter_start_post(s);
034c6ed7
LP
2863 break;
2864
2865 case SERVICE_START_POST:
f42806df 2866 if (f != SERVICE_SUCCESS) {
ce359e98 2867 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
2096e009 2868 break;
034c6ed7
LP
2869 }
2870
2096e009 2871 if (s->pid_file) {
f42806df
LP
2872 int r;
2873
2874 r = service_load_pid_file(s, true);
2096e009
MS
2875 if (r < 0) {
2876 r = service_demand_pid_file(s);
2877 if (r < 0 || !cgroup_good(s))
c35755fb 2878 service_enter_stop(s, SERVICE_FAILURE_PROTOCOL);
2096e009
MS
2879 break;
2880 }
2881 } else
783e05d6 2882 service_search_main_pid(s);
2096e009 2883
f42806df 2884 service_enter_running(s, SERVICE_SUCCESS);
3185a36b 2885 break;
034c6ed7
LP
2886
2887 case SERVICE_RELOAD:
7236ce6e
ZJS
2888 if (f == SERVICE_SUCCESS)
2889 if (service_load_pid_file(s, true) < 0)
2890 service_search_main_pid(s);
3185a36b 2891
f42806df
LP
2892 s->reload_result = f;
2893 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2894 break;
2895
2896 case SERVICE_STOP:
f42806df 2897 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
2898 break;
2899
db2cb23b 2900 case SERVICE_STOP_SIGABRT:
034c6ed7
LP
2901 case SERVICE_STOP_SIGTERM:
2902 case SERVICE_STOP_SIGKILL:
2903 if (main_pid_good(s) <= 0)
f42806df 2904 service_enter_stop_post(s, f);
034c6ed7
LP
2905
2906 /* If there is still a service
2907 * process around, wait until
2908 * that one quit, too */
2909 break;
2910
2911 case SERVICE_STOP_POST:
2912 case SERVICE_FINAL_SIGTERM:
2913 case SERVICE_FINAL_SIGKILL:
bf108e55
LP
2914 if (main_pid_good(s) <= 0)
2915 service_enter_dead(s, f, true);
034c6ed7
LP
2916 break;
2917
2918 default:
2919 assert_not_reached("Uh, control process died at wrong time.");
2920 }
2921 }
8c47c732 2922 }
c4e2ceae
LP
2923
2924 /* Notify clients about changed exit status */
2925 unit_add_to_dbus_queue(u);
a911bb9a
LP
2926
2927 /* We got one SIGCHLD for the service, let's watch all
2928 * processes that are now running of the service, and watch
2929 * that. Among the PIDs we then watch will be children
2930 * reassigned to us, which hopefully allows us to identify
2931 * when all children are gone */
2932 unit_tidy_watch_pids(u, s->main_pid, s->control_pid);
2933 unit_watch_all_pids(u);
2934
bbc85a16
EV
2935 /* If the PID set is empty now, then let's finish this off
2936 (On unified we use proper notifications) */
c22800e4 2937 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) == 0 && set_isempty(u->pids))
a911bb9a 2938 service_notify_cgroup_empty_event(u);
034c6ed7
LP
2939}
2940
718db961
LP
2941static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2942 Service *s = SERVICE(userdata);
034c6ed7
LP
2943
2944 assert(s);
718db961 2945 assert(source == s->timer_event_source);
034c6ed7
LP
2946
2947 switch (s->state) {
2948
2949 case SERVICE_START_PRE:
2950 case SERVICE_START:
f2341e0a 2951 log_unit_warning(UNIT(s), "%s operation timed out. Terminating.", s->state == SERVICE_START ? "Start" : "Start-pre");
c3fda31d 2952 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
80876c20
LP
2953 break;
2954
034c6ed7 2955 case SERVICE_START_POST:
f2341e0a 2956 log_unit_warning(UNIT(s), "Start-post operation timed out. Stopping.");
ce359e98 2957 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
2958 break;
2959
36c16a7c
LP
2960 case SERVICE_RUNNING:
2961 log_unit_warning(UNIT(s), "Service reached runtime time limit. Stopping.");
2962 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
2963 break;
2964
e2f3b44c 2965 case SERVICE_RELOAD:
089b64d5 2966 log_unit_warning(UNIT(s), "Reload operation timed out. Killing reload process.");
478b6192 2967 service_kill_control_processes(s);
f42806df
LP
2968 s->reload_result = SERVICE_FAILURE_TIMEOUT;
2969 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c
LP
2970 break;
2971
034c6ed7 2972 case SERVICE_STOP:
f2341e0a 2973 log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
f42806df 2974 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
2975 break;
2976
db2cb23b 2977 case SERVICE_STOP_SIGABRT:
f2341e0a 2978 log_unit_warning(UNIT(s), "State 'stop-sigabrt' timed out. Terminating.");
2ab2ab7b 2979 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
db2cb23b
UTL
2980 break;
2981
034c6ed7 2982 case SERVICE_STOP_SIGTERM:
4819ff03 2983 if (s->kill_context.send_sigkill) {
f2341e0a 2984 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Killing.");
f42806df 2985 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 2986 } else {
f2341e0a 2987 log_unit_warning(UNIT(s), "State 'stop-sigterm' timed out. Skipping SIGKILL.");
f42806df 2988 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
ba035df2
LP
2989 }
2990
034c6ed7
LP
2991 break;
2992
2993 case SERVICE_STOP_SIGKILL:
35b8ca3a 2994 /* Uh, we sent a SIGKILL and it is still not gone?
034c6ed7
LP
2995 * Must be something we cannot kill, so let's just be
2996 * weirded out and continue */
2997
f2341e0a 2998 log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
f42806df 2999 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3000 break;
3001
3002 case SERVICE_STOP_POST:
f2341e0a 3003 log_unit_warning(UNIT(s), "State 'stop-post' timed out. Terminating.");
f42806df 3004 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3005 break;
3006
3007 case SERVICE_FINAL_SIGTERM:
4819ff03 3008 if (s->kill_context.send_sigkill) {
f2341e0a 3009 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Killing.");
f42806df 3010 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 3011 } else {
f2341e0a 3012 log_unit_warning(UNIT(s), "State 'stop-final-sigterm' timed out. Skipping SIGKILL. Entering failed mode.");
f42806df 3013 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
ba035df2
LP
3014 }
3015
034c6ed7
LP
3016 break;
3017
3018 case SERVICE_FINAL_SIGKILL:
f2341e0a 3019 log_unit_warning(UNIT(s), "Processes still around after final SIGKILL. Entering failed mode.");
f42806df 3020 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
034c6ed7
LP
3021 break;
3022
3023 case SERVICE_AUTO_RESTART:
f2341e0a 3024 log_unit_info(UNIT(s),
ef417cfd 3025 s->restart_usec > 0 ?
f2341e0a
LP
3026 "Service hold-off time over, scheduling restart." :
3027 "Service has no hold-off time, scheduling restart.");
034c6ed7
LP
3028 service_enter_restart(s);
3029 break;
3030
3031 default:
3032 assert_not_reached("Timeout at wrong time.");
3033 }
718db961
LP
3034
3035 return 0;
3036}
3037
3038static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
3039 Service *s = SERVICE(userdata);
a7850c7d 3040 char t[FORMAT_TIMESPAN_MAX];
2787d83c 3041 usec_t watchdog_usec;
718db961
LP
3042
3043 assert(s);
3044 assert(source == s->watchdog_event_source);
3045
2787d83c
M
3046 watchdog_usec = service_get_watchdog_usec(s);
3047
f2341e0a 3048 log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
2787d83c 3049 format_timespan(t, sizeof(t), watchdog_usec, 1));
8bb2d17d 3050
db2cb23b 3051 service_enter_signal(s, SERVICE_STOP_SIGABRT, SERVICE_FAILURE_WATCHDOG);
842129f5 3052
718db961 3053 return 0;
5cb5a6ff
LP
3054}
3055
a354329f 3056static void service_notify_message(Unit *u, pid_t pid, char **tags, FDSet *fds) {
8c47c732 3057 Service *s = SERVICE(u);
308d72dc 3058 _cleanup_free_ char *cc = NULL;
30b5275a 3059 bool notify_dbus = false;
308d72dc 3060 const char *e;
8c47c732
LP
3061
3062 assert(u);
3063
308d72dc 3064 cc = strv_join(tags, ", ");
da13d4d2 3065
c952c6ec 3066 if (s->notify_access == NOTIFY_NONE) {
f2341e0a 3067 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception is disabled.", pid);
c952c6ec 3068 return;
34959677 3069 } else if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
336c6e46 3070 if (s->main_pid != 0)
f2341e0a 3071 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 3072 else
6375bd20
JW
3073 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID which is currently not known", pid);
3074 return;
3075 } else if (s->notify_access == NOTIFY_EXEC && pid != s->main_pid && pid != s->control_pid) {
3076 if (s->main_pid != 0 && s->control_pid != 0)
3077 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,
3078 pid, s->main_pid, s->control_pid);
3079 else if (s->main_pid != 0)
3080 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for main PID "PID_FMT, pid, s->main_pid);
3081 else if (s->control_pid != 0)
3082 log_unit_warning(u, "Got notification message from PID "PID_FMT", but reception only permitted for control PID "PID_FMT, pid, s->control_pid);
3083 else
3084 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 3085 return;
34959677
TG
3086 } else
3087 log_unit_debug(u, "Got notification message from PID "PID_FMT" (%s)", pid, isempty(cc) ? "n/a" : cc);
c952c6ec 3088
8c47c732 3089 /* Interpret MAINPID= */
28849dba 3090 e = strv_find_startswith(tags, "MAINPID=");
5e56b378 3091 if (e && IN_SET(s->state, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_RELOAD)) {
28849dba 3092 if (parse_pid(e, &pid) < 0)
f2341e0a 3093 log_unit_warning(u, "Failed to parse MAINPID= field in notification message: %s", e);
3c9512c7
JW
3094 else if (pid == s->control_pid)
3095 log_unit_warning(u, "A control process cannot also be the main process");
6939ce64
LP
3096 else if (pid == getpid() || pid == 1)
3097 log_unit_warning(u, "Service manager can't be main process, ignoring sd_notify() MAINPID= field");
8c47c732 3098 else {
5925dd3c 3099 service_set_main_pid(s, pid);
7400b9d2 3100 unit_watch_pid(UNIT(s), pid);
30b5275a 3101 notify_dbus = true;
8c47c732
LP
3102 }
3103 }
3104
308d72dc
LP
3105 /* Interpret RELOADING= */
3106 if (strv_find(tags, "RELOADING=1")) {
3107
308d72dc
LP
3108 s->notify_state = NOTIFY_RELOADING;
3109
3110 if (s->state == SERVICE_RUNNING)
3111 service_enter_reload_by_notify(s);
3112
3113 notify_dbus = true;
3114 }
3115
8c47c732 3116 /* Interpret READY= */
308d72dc
LP
3117 if (strv_find(tags, "READY=1")) {
3118
308d72dc
LP
3119 s->notify_state = NOTIFY_READY;
3120
3121 /* Type=notify services inform us about completed
3122 * initialization with READY=1 */
3123 if (s->type == SERVICE_NOTIFY && s->state == SERVICE_START)
3124 service_enter_start_post(s);
3125
3126 /* Sending READY=1 while we are reloading informs us
3127 * that the reloading is complete */
3128 if (s->state == SERVICE_RELOAD && s->control_pid == 0)
3129 service_enter_running(s, SERVICE_SUCCESS);
3130
3131 notify_dbus = true;
3132 }
3133
3134 /* Interpret STOPPING= */
3135 if (strv_find(tags, "STOPPING=1")) {
3136
308d72dc
LP
3137 s->notify_state = NOTIFY_STOPPING;
3138
3139 if (s->state == SERVICE_RUNNING)
3140 service_enter_stop_by_notify(s);
3141
30b5275a 3142 notify_dbus = true;
8c47c732
LP
3143 }
3144
3145 /* Interpret STATUS= */
28849dba 3146 e = strv_find_startswith(tags, "STATUS=");
7f110ff9 3147 if (e) {
28849dba 3148 _cleanup_free_ char *t = NULL;
8c47c732 3149
28849dba
LP
3150 if (!isempty(e)) {
3151 if (!utf8_is_valid(e))
f2341e0a 3152 log_unit_warning(u, "Status message in notification message is not UTF-8 clean.");
28849dba 3153 else {
28849dba
LP
3154 t = strdup(e);
3155 if (!t)
3156 log_oom();
3a2776bc 3157 }
28849dba 3158 }
8c47c732 3159
30b5275a 3160 if (!streq_ptr(s->status_text, t)) {
28849dba 3161
3b319885 3162 free_and_replace(s->status_text, t);
28849dba 3163
30b5275a 3164 notify_dbus = true;
28849dba 3165 }
8c47c732 3166 }
842129f5 3167
4774e357 3168 /* Interpret ERRNO= */
28849dba 3169 e = strv_find_startswith(tags, "ERRNO=");
4774e357
MAA
3170 if (e) {
3171 int status_errno;
3172
28849dba 3173 if (safe_atoi(e, &status_errno) < 0 || status_errno < 0)
f2341e0a 3174 log_unit_warning(u, "Failed to parse ERRNO= field in notification message: %s", e);
4774e357 3175 else {
4774e357
MAA
3176 if (s->status_errno != status_errno) {
3177 s->status_errno = status_errno;
3178 notify_dbus = true;
3179 }
3180 }
3181 }
3182
6f285378 3183 /* Interpret WATCHDOG= */
1f6b4113 3184 if (strv_find(tags, "WATCHDOG=1"))
842129f5 3185 service_reset_watchdog(s);
c4e2ceae 3186
8dd4c05b
LP
3187 if (strv_find(tags, "FDSTORE=1")) {
3188 const char *name;
3189
3190 name = strv_find_startswith(tags, "FDNAME=");
3191 if (name && !fdname_is_valid(name)) {
3192 log_unit_warning(u, "Passed FDNAME= name is invalid, ignoring.");
3193 name = NULL;
3194 }
3195
3196 service_add_fd_store_set(s, fds, name);
3197 }
a354329f 3198
2787d83c
M
3199 e = strv_find_startswith(tags, "WATCHDOG_USEC=");
3200 if (e) {
3201 usec_t watchdog_override_usec;
3202 if (safe_atou64(e, &watchdog_override_usec) < 0)
3203 log_unit_warning(u, "Failed to parse WATCHDOG_USEC=%s", e);
3204 else
3205 service_reset_watchdog_timeout(s, watchdog_override_usec);
3206 }
3207
c4e2ceae 3208 /* Notify clients about changed status or main pid */
30b5275a
LP
3209 if (notify_dbus)
3210 unit_add_to_dbus_queue(u);
8c47c732
LP
3211}
3212
7a7821c8 3213static int service_get_timeout(Unit *u, usec_t *timeout) {
68db7a3b 3214 Service *s = SERVICE(u);
7a7821c8 3215 uint64_t t;
68db7a3b
ZJS
3216 int r;
3217
3218 if (!s->timer_event_source)
3219 return 0;
3220
7a7821c8 3221 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
3222 if (r < 0)
3223 return r;
7a7821c8
LP
3224 if (t == USEC_INFINITY)
3225 return 0;
68db7a3b 3226
7a7821c8 3227 *timeout = t;
68db7a3b
ZJS
3228 return 1;
3229}
3230
05e343b7
LP
3231static void service_bus_name_owner_change(
3232 Unit *u,
3233 const char *name,
3234 const char *old_owner,
3235 const char *new_owner) {
3236
3237 Service *s = SERVICE(u);
718db961 3238 int r;
05e343b7
LP
3239
3240 assert(s);
3241 assert(name);
3242
3243 assert(streq(s->bus_name, name));
3244 assert(old_owner || new_owner);
3245
3246 if (old_owner && new_owner)
f2341e0a 3247 log_unit_debug(u, "D-Bus name %s changed owner from %s to %s", name, old_owner, new_owner);
05e343b7 3248 else if (old_owner)
f2341e0a 3249 log_unit_debug(u, "D-Bus name %s no longer registered by %s", name, old_owner);
05e343b7 3250 else
f2341e0a 3251 log_unit_debug(u, "D-Bus name %s now registered by %s", name, new_owner);
05e343b7
LP
3252
3253 s->bus_name_good = !!new_owner;
3254
d8ccf5fd
DM
3255 /* Track the current owner, so we can reconstruct changes after a daemon reload */
3256 r = free_and_strdup(&s->bus_name_owner, new_owner);
3257 if (r < 0) {
3258 log_unit_error_errno(u, r, "Unable to set new bus name owner %s: %m", new_owner);
3259 return;
3260 }
3261
05e343b7
LP
3262 if (s->type == SERVICE_DBUS) {
3263
3264 /* service_enter_running() will figure out what to
3265 * do */
3266 if (s->state == SERVICE_RUNNING)
f42806df 3267 service_enter_running(s, SERVICE_SUCCESS);
05e343b7
LP
3268 else if (s->state == SERVICE_START && new_owner)
3269 service_enter_start_post(s);
3270
3271 } else if (new_owner &&
3272 s->main_pid <= 0 &&
3273 (s->state == SERVICE_START ||
3274 s->state == SERVICE_START_POST ||
3275 s->state == SERVICE_RUNNING ||
3276 s->state == SERVICE_RELOAD)) {
3277
4afd3348 3278 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
718db961 3279 pid_t pid;
05e343b7 3280
718db961 3281 /* Try to acquire PID from bus service */
05e343b7 3282
056f95d0 3283 r = sd_bus_get_name_creds(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
5b12334d
LP
3284 if (r >= 0)
3285 r = sd_bus_creds_get_pid(creds, &pid);
718db961 3286 if (r >= 0) {
7c102d60 3287 log_unit_debug(u, "D-Bus name %s is now owned by process " PID_FMT, name, pid);
05e343b7 3288
718db961
LP
3289 service_set_main_pid(s, pid);
3290 unit_watch_pid(UNIT(s), pid);
3291 }
7400b9d2 3292 }
05e343b7
LP
3293}
3294
16115b0a 3295int service_set_socket_fd(Service *s, int fd, Socket *sock, bool selinux_context_net) {
79a98c60
LP
3296 _cleanup_free_ char *peer = NULL;
3297 int r;
57020a3a 3298
4f2d528d
LP
3299 assert(s);
3300 assert(fd >= 0);
3301
7f2fbbff
LP
3302 /* This is called by the socket code when instantiating a new service for a stream socket and the socket needs
3303 * to be configured. We take ownership of the passed fd on success. */
4f2d528d 3304
1124fe6f 3305 if (UNIT(s)->load_state != UNIT_LOADED)
4f2d528d
LP
3306 return -EINVAL;
3307
3308 if (s->socket_fd >= 0)
3309 return -EBUSY;
3310
3311 if (s->state != SERVICE_DEAD)
3312 return -EAGAIN;
3313
366b7db4 3314 if (getpeername_pretty(fd, true, &peer) >= 0) {
79a98c60
LP
3315
3316 if (UNIT(s)->description) {
3317 _cleanup_free_ char *a;
3318
605405c6 3319 a = strjoin(UNIT(s)->description, " (", peer, ")");
79a98c60
LP
3320 if (!a)
3321 return -ENOMEM;
3322
3323 r = unit_set_description(UNIT(s), a);
3324 } else
3325 r = unit_set_description(UNIT(s), peer);
3326
3327 if (r < 0)
3328 return r;
3329 }
3330
7f2fbbff
LP
3331 r = unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
3332 if (r < 0)
3333 return r;
3334
4f2d528d 3335 s->socket_fd = fd;
16115b0a 3336 s->socket_fd_selinux_context_net = selinux_context_net;
6cf6bbc2 3337
57020a3a 3338 unit_ref_set(&s->accept_socket, UNIT(sock));
7f2fbbff 3339 return 0;
4f2d528d
LP
3340}
3341
fdf20a31 3342static void service_reset_failed(Unit *u) {
5632e374
LP
3343 Service *s = SERVICE(u);
3344
3345 assert(s);
3346
fdf20a31 3347 if (s->state == SERVICE_FAILED)
5632e374
LP
3348 service_set_state(s, SERVICE_DEAD);
3349
f42806df
LP
3350 s->result = SERVICE_SUCCESS;
3351 s->reload_result = SERVICE_SUCCESS;
5632e374
LP
3352}
3353
718db961 3354static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
8a0867d6 3355 Service *s = SERVICE(u);
41efeaec 3356
814cc562 3357 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
8a0867d6
LP
3358}
3359
291d565a
LP
3360static int service_main_pid(Unit *u) {
3361 Service *s = SERVICE(u);
3362
3363 assert(s);
3364
3365 return s->main_pid;
3366}
3367
3368static int service_control_pid(Unit *u) {
3369 Service *s = SERVICE(u);
3370
3371 assert(s);
3372
3373 return s->control_pid;
3374}
3375
94f04347 3376static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
525ee6f4
LP
3377 [SERVICE_RESTART_NO] = "no",
3378 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
50caaedb 3379 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
6cfe2fde 3380 [SERVICE_RESTART_ON_ABNORMAL] = "on-abnormal",
dc99a976 3381 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
50caaedb 3382 [SERVICE_RESTART_ON_ABORT] = "on-abort",
6cfe2fde 3383 [SERVICE_RESTART_ALWAYS] = "always",
94f04347
LP
3384};
3385
3386DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3387
3388static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
94f04347 3389 [SERVICE_SIMPLE] = "simple",
0d624a78 3390 [SERVICE_FORKING] = "forking",
34e9ba66 3391 [SERVICE_ONESHOT] = "oneshot",
8c47c732 3392 [SERVICE_DBUS] = "dbus",
f2b68789
LP
3393 [SERVICE_NOTIFY] = "notify",
3394 [SERVICE_IDLE] = "idle"
94f04347
LP
3395};
3396
3397DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3398
e537352b 3399static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
94f04347
LP
3400 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3401 [SERVICE_EXEC_START] = "ExecStart",
3402 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3403 [SERVICE_EXEC_RELOAD] = "ExecReload",
3404 [SERVICE_EXEC_STOP] = "ExecStop",
3405 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3406};
3407
3408DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3409
c952c6ec
LP
3410static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3411 [NOTIFY_NONE] = "none",
3412 [NOTIFY_MAIN] = "main",
6375bd20 3413 [NOTIFY_EXEC] = "exec",
c952c6ec
LP
3414 [NOTIFY_ALL] = "all"
3415};
3416
3417DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3418
308d72dc
LP
3419static const char* const notify_state_table[_NOTIFY_STATE_MAX] = {
3420 [NOTIFY_UNKNOWN] = "unknown",
3421 [NOTIFY_READY] = "ready",
3422 [NOTIFY_RELOADING] = "reloading",
3423 [NOTIFY_STOPPING] = "stopping",
3424};
3425
3426DEFINE_STRING_TABLE_LOOKUP(notify_state, NotifyState);
3427
f42806df
LP
3428static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3429 [SERVICE_SUCCESS] = "success",
3430 [SERVICE_FAILURE_RESOURCES] = "resources",
c35755fb 3431 [SERVICE_FAILURE_PROTOCOL] = "protocol",
f42806df
LP
3432 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3433 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3434 [SERVICE_FAILURE_SIGNAL] = "signal",
bb242b7b 3435 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
8d1b002a 3436 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
07299350 3437 [SERVICE_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
f42806df
LP
3438};
3439
3440DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3441
87f0e418 3442const UnitVTable service_vtable = {
7d17cfbc 3443 .object_size = sizeof(Service),
718db961
LP
3444 .exec_context_offset = offsetof(Service, exec_context),
3445 .cgroup_context_offset = offsetof(Service, cgroup_context),
3446 .kill_context_offset = offsetof(Service, kill_context),
613b411c 3447 .exec_runtime_offset = offsetof(Service, exec_runtime),
29206d46 3448 .dynamic_creds_offset = offsetof(Service, dynamic_creds),
3ef63c31 3449
f975e971
LP
3450 .sections =
3451 "Unit\0"
3452 "Service\0"
3453 "Install\0",
4ad49000 3454 .private_section = "Service",
71645aca 3455
034c6ed7
LP
3456 .init = service_init,
3457 .done = service_done,
a16e1123 3458 .load = service_load,
a354329f 3459 .release_resources = service_release_resources,
a16e1123
LP
3460
3461 .coldplug = service_coldplug,
034c6ed7 3462
5cb5a6ff
LP
3463 .dump = service_dump,
3464
3465 .start = service_start,
3466 .stop = service_stop,
3467 .reload = service_reload,
3468
034c6ed7
LP
3469 .can_reload = service_can_reload,
3470
8a0867d6
LP
3471 .kill = service_kill,
3472
a16e1123
LP
3473 .serialize = service_serialize,
3474 .deserialize_item = service_deserialize_item,
3475
5cb5a6ff 3476 .active_state = service_active_state,
10a94420 3477 .sub_state_to_string = service_sub_state_to_string,
5cb5a6ff 3478
701cc384 3479 .check_gc = service_check_gc,
701cc384 3480
034c6ed7 3481 .sigchld_event = service_sigchld_event,
2c4104f0 3482
fdf20a31 3483 .reset_failed = service_reset_failed,
5632e374 3484
4ad49000 3485 .notify_cgroup_empty = service_notify_cgroup_empty_event,
8c47c732 3486 .notify_message = service_notify_message,
8e274523 3487
291d565a
LP
3488 .main_pid = service_main_pid,
3489 .control_pid = service_control_pid,
3490
05e343b7 3491 .bus_name_owner_change = service_bus_name_owner_change,
05e343b7 3492
718db961 3493 .bus_vtable = bus_service_vtable,
74c964d3
LP
3494 .bus_set_property = bus_service_set_property,
3495 .bus_commit_properties = bus_service_commit_properties,
4139c1b2 3496
68db7a3b 3497 .get_timeout = service_get_timeout,
718db961
LP
3498 .can_transient = true,
3499
c6918296
MS
3500 .status_message_formats = {
3501 .starting_stopping = {
3502 [0] = "Starting %s...",
3503 [1] = "Stopping %s...",
3504 },
3505 .finished_start_job = {
3506 [JOB_DONE] = "Started %s.",
3507 [JOB_FAILED] = "Failed to start %s.",
c6918296
MS
3508 },
3509 .finished_stop_job = {
3510 [JOB_DONE] = "Stopped %s.",
3511 [JOB_FAILED] = "Stopped (with error) %s.",
c6918296
MS
3512 },
3513 },
5cb5a6ff 3514};