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