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