]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/service.c
journald: port to sd-event and enable watchdog support
[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
LP
24#include <dirent.h>
25#include <unistd.h>
4b939747 26#include <sys/reboot.h>
5cb5a6ff 27
4b939747 28#include "manager.h"
87f0e418 29#include "unit.h"
5cb5a6ff
LP
30#include "service.h"
31#include "load-fragment.h"
32#include "load-dropin.h"
034c6ed7 33#include "log.h"
2c4104f0 34#include "strv.h"
9e2f7c11 35#include "unit-name.h"
41f9172f 36#include "unit-printf.h"
4139c1b2 37#include "dbus-service.h"
514f4ef5 38#include "special.h"
9a57c629 39#include "exit-status.h"
f6a6225e 40#include "def.h"
9eb977db 41#include "path-util.h"
f6a6225e 42#include "util.h"
7f110ff9 43#include "utf8.h"
4d1a6904 44#include "env-util.h"
a5c32cff 45#include "fileio.h"
718db961
LP
46#include "bus-error.h"
47#include "bus-util.h"
034c6ed7 48
07459bb6 49#ifdef HAVE_SYSV_COMPAT
f34277d9 50
f6a6225e 51#define DEFAULT_SYSV_TIMEOUT_USEC (5*USEC_PER_MINUTE)
f34277d9 52
09cd1ab1
LP
53typedef enum RunlevelType {
54 RUNLEVEL_UP,
3cdebc21 55 RUNLEVEL_DOWN
09cd1ab1
LP
56} RunlevelType;
57
58static const struct {
59 const char *path;
60 const char *target;
61 const RunlevelType type;
62} rcnd_table[] = {
9d25f5ed 63 /* Standard SysV runlevels for start-up */
514f4ef5 64 { "rc1.d", SPECIAL_RESCUE_TARGET, RUNLEVEL_UP },
fbe9f3a9
LP
65 { "rc2.d", SPECIAL_RUNLEVEL2_TARGET, RUNLEVEL_UP },
66 { "rc3.d", SPECIAL_RUNLEVEL3_TARGET, RUNLEVEL_UP },
67 { "rc4.d", SPECIAL_RUNLEVEL4_TARGET, RUNLEVEL_UP },
68 { "rc5.d", SPECIAL_RUNLEVEL5_TARGET, RUNLEVEL_UP },
fbe9f3a9 69
9d25f5ed
LP
70 /* Standard SysV runlevels for shutdown */
71 { "rc0.d", SPECIAL_POWEROFF_TARGET, RUNLEVEL_DOWN },
72 { "rc6.d", SPECIAL_REBOOT_TARGET, RUNLEVEL_DOWN }
73
74 /* Note that the order here matters, as we read the
75 directories in this order, and we want to make sure that
76 sysv_start_priority is known when we first load the
77 unit. And that value we only know from S links. Hence
3cdebc21 78 UP must be read before DOWN */
23a177ef
LP
79};
80
09cd1ab1 81#define RUNLEVELS_UP "12345"
07459bb6 82#endif
09cd1ab1 83
acbb0225 84static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
87f0e418
LP
85 [SERVICE_DEAD] = UNIT_INACTIVE,
86 [SERVICE_START_PRE] = UNIT_ACTIVATING,
87 [SERVICE_START] = UNIT_ACTIVATING,
88 [SERVICE_START_POST] = UNIT_ACTIVATING,
89 [SERVICE_RUNNING] = UNIT_ACTIVE,
80876c20 90 [SERVICE_EXITED] = UNIT_ACTIVE,
032ff4af 91 [SERVICE_RELOAD] = UNIT_RELOADING,
87f0e418
LP
92 [SERVICE_STOP] = UNIT_DEACTIVATING,
93 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
94 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
95 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
96 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
97 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
fdf20a31 98 [SERVICE_FAILED] = UNIT_FAILED,
6124958c 99 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
034c6ed7 100};
5cb5a6ff 101
e056b01d
LP
102/* For Type=idle we never want to delay any other jobs, hence we
103 * consider idle jobs active as soon as we start working on them */
104static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
105 [SERVICE_DEAD] = UNIT_INACTIVE,
106 [SERVICE_START_PRE] = UNIT_ACTIVE,
107 [SERVICE_START] = UNIT_ACTIVE,
108 [SERVICE_START_POST] = UNIT_ACTIVE,
109 [SERVICE_RUNNING] = UNIT_ACTIVE,
110 [SERVICE_EXITED] = UNIT_ACTIVE,
111 [SERVICE_RELOAD] = UNIT_RELOADING,
112 [SERVICE_STOP] = UNIT_DEACTIVATING,
113 [SERVICE_STOP_SIGTERM] = UNIT_DEACTIVATING,
114 [SERVICE_STOP_SIGKILL] = UNIT_DEACTIVATING,
115 [SERVICE_STOP_POST] = UNIT_DEACTIVATING,
116 [SERVICE_FINAL_SIGTERM] = UNIT_DEACTIVATING,
117 [SERVICE_FINAL_SIGKILL] = UNIT_DEACTIVATING,
118 [SERVICE_FAILED] = UNIT_FAILED,
119 [SERVICE_AUTO_RESTART] = UNIT_ACTIVATING
120};
121
718db961
LP
122static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
123static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
124static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
125
a16e1123
LP
126static void service_init(Unit *u) {
127 Service *s = SERVICE(u);
128
129 assert(u);
ac155bb8 130 assert(u->load_state == UNIT_STUB);
a16e1123 131
1f19a534
OS
132 s->timeout_start_usec = u->manager->default_timeout_start_usec;
133 s->timeout_stop_usec = u->manager->default_timeout_stop_usec;
134 s->restart_usec = u->manager->default_restart_usec;
0b86feac 135 s->type = _SERVICE_TYPE_INVALID;
bb242b7b 136
07459bb6 137#ifdef HAVE_SYSV_COMPAT
a16e1123 138 s->sysv_start_priority = -1;
ea87ca5a 139 s->sysv_start_priority_from_rcnd = -1;
07459bb6 140#endif
a16e1123 141 s->socket_fd = -1;
3185a36b 142 s->guess_main_pid = true;
a16e1123
LP
143
144 exec_context_init(&s->exec_context);
4819ff03 145 kill_context_init(&s->kill_context);
4ad49000 146 cgroup_context_init(&s->cgroup_context);
a16e1123 147
3f41e1e5
LN
148 RATELIMIT_INIT(s->start_limit,
149 u->manager->default_start_limit_interval,
150 u->manager->default_start_limit_burst);
a16e1123
LP
151
152 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
153}
154
5e94833f
LP
155static void service_unwatch_control_pid(Service *s) {
156 assert(s);
157
158 if (s->control_pid <= 0)
159 return;
160
161 unit_unwatch_pid(UNIT(s), s->control_pid);
162 s->control_pid = 0;
163}
164
165static void service_unwatch_main_pid(Service *s) {
166 assert(s);
167
168 if (s->main_pid <= 0)
169 return;
170
171 unit_unwatch_pid(UNIT(s), s->main_pid);
172 s->main_pid = 0;
173}
174
3e52541e
MS
175static void service_unwatch_pid_file(Service *s) {
176 if (!s->pid_file_pathspec)
177 return;
178
66870f90
ZJS
179 log_debug_unit(UNIT(s)->id, "Stopping watch for %s's PID file %s",
180 UNIT(s)->id, s->pid_file_pathspec->path);
718db961 181 path_spec_unwatch(s->pid_file_pathspec);
3e52541e
MS
182 path_spec_done(s->pid_file_pathspec);
183 free(s->pid_file_pathspec);
184 s->pid_file_pathspec = NULL;
185}
186
5925dd3c 187static int service_set_main_pid(Service *s, pid_t pid) {
e55224ca
LP
188 pid_t ppid;
189
5925dd3c
LP
190 assert(s);
191
192 if (pid <= 1)
193 return -EINVAL;
194
195 if (pid == getpid())
196 return -EINVAL;
197
7400b9d2
LP
198 if (s->main_pid == pid && s->main_pid_known)
199 return 0;
200
201 if (s->main_pid != pid) {
202 service_unwatch_main_pid(s);
203 exec_status_start(&s->main_exec_status, pid);
204 }
41efeaec 205
6dfa5494
LP
206 s->main_pid = pid;
207 s->main_pid_known = true;
208
209 if (get_parent_of_pid(pid, &ppid) >= 0 && ppid != getpid()) {
66870f90
ZJS
210 log_warning_unit(UNIT(s)->id,
211 "%s: Supervising process %lu which is not our child. We'll most likely not notice when it exits.",
212 UNIT(s)->id, (unsigned long) pid);
e55224ca 213
6dfa5494
LP
214 s->main_pid_alien = true;
215 } else
216 s->main_pid_alien = false;
5925dd3c
LP
217
218 return 0;
219}
220
4f2d528d
LP
221static void service_close_socket_fd(Service *s) {
222 assert(s);
223
224 if (s->socket_fd < 0)
225 return;
226
227 close_nointr_nofail(s->socket_fd);
228 s->socket_fd = -1;
229}
230
6cf6bbc2
LP
231static void service_connection_unref(Service *s) {
232 assert(s);
233
9444b1f2 234 if (!UNIT_ISSET(s->accept_socket))
6cf6bbc2
LP
235 return;
236
57020a3a
LP
237 socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
238 unit_ref_unset(&s->accept_socket);
6cf6bbc2
LP
239}
240
a6927d7f
MO
241static void service_stop_watchdog(Service *s) {
242 assert(s);
243
718db961
LP
244 s->watchdog_event_source = sd_event_source_unref(s->watchdog_event_source);
245 s->watchdog_timestamp = (struct dual_timestamp) { 0, 0 };
a6927d7f
MO
246}
247
9e9c3abc 248static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
bb242b7b
MO
249
250static void service_handle_watchdog(Service *s) {
718db961 251 usec_t nw;
bb242b7b
MO
252 int r;
253
254 assert(s);
255
256 if (s->watchdog_usec == 0)
257 return;
258
718db961
LP
259 nw = now(CLOCK_MONOTONIC);
260 if (nw >= s->watchdog_timestamp.monotonic + s->watchdog_usec) {
66870f90 261 log_error_unit(UNIT(s)->id, "%s watchdog timeout!", UNIT(s)->id);
af471339 262 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_WATCHDOG);
bb242b7b
MO
263 return;
264 }
265
718db961
LP
266 if (s->watchdog_event_source) {
267 r = sd_event_source_set_time(s->watchdog_event_source, s->watchdog_timestamp.monotonic + s->watchdog_usec);
268 if (r < 0) {
269 log_warning_unit(UNIT(s)->id, "%s failed to reset watchdog timer: %s", UNIT(s)->id, strerror(-r));
270 return;
271 }
272
273 r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ON);
274 } else
275 r = sd_event_add_monotonic(UNIT(s)->manager->event, s->watchdog_timestamp.monotonic + s->watchdog_usec, 0, service_dispatch_watchdog, s, &s->watchdog_event_source);
276
bb242b7b 277 if (r < 0)
66870f90
ZJS
278 log_warning_unit(UNIT(s)->id,
279 "%s failed to install watchdog timer: %s",
280 UNIT(s)->id, strerror(-r));
bb242b7b
MO
281}
282
a6927d7f
MO
283static void service_reset_watchdog(Service *s) {
284 assert(s);
285
286 dual_timestamp_get(&s->watchdog_timestamp);
bb242b7b 287 service_handle_watchdog(s);
a6927d7f
MO
288}
289
87f0e418
LP
290static void service_done(Unit *u) {
291 Service *s = SERVICE(u);
44d8db9e
LP
292
293 assert(s);
294
295 free(s->pid_file);
296 s->pid_file = NULL;
297
07459bb6 298#ifdef HAVE_SYSV_COMPAT
8309400a
LP
299 free(s->sysv_runlevels);
300 s->sysv_runlevels = NULL;
07459bb6 301#endif
8309400a 302
8c47c732
LP
303 free(s->status_text);
304 s->status_text = NULL;
305
4ad49000 306 cgroup_context_done(&s->cgroup_context);
613b411c
LP
307 exec_context_done(&s->exec_context);
308 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
e537352b 309 exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
44d8db9e 310 s->control_command = NULL;
867b3b7d 311 s->main_command = NULL;
44d8db9e 312
96342de6
LN
313 set_free(s->restart_ignore_status.code);
314 s->restart_ignore_status.code = NULL;
315 set_free(s->restart_ignore_status.signal);
316 s->restart_ignore_status.signal = NULL;
317
318 set_free(s->success_status.code);
319 s->success_status.code = NULL;
320 set_free(s->success_status.signal);
321 s->success_status.signal = NULL;
322
44d8db9e
LP
323 /* This will leak a process, but at least no memory or any of
324 * our resources */
5e94833f
LP
325 service_unwatch_main_pid(s);
326 service_unwatch_control_pid(s);
3e52541e 327 service_unwatch_pid_file(s);
44d8db9e 328
05e343b7 329 if (s->bus_name) {
ac155bb8 330 unit_unwatch_bus_name(u, s->bus_name);
05e343b7
LP
331 free(s->bus_name);
332 s->bus_name = NULL;
333 }
334
4f2d528d 335 service_close_socket_fd(s);
6cf6bbc2 336 service_connection_unref(s);
4f2d528d 337
57020a3a 338 unit_ref_unset(&s->accept_socket);
f976f3f6 339
bb242b7b
MO
340 service_stop_watchdog(s);
341
718db961
LP
342 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
343}
344
345static int service_arm_timer(Service *s, usec_t usec) {
346 int r;
347
348 assert(s);
349
718db961
LP
350 if (s->timer_event_source) {
351 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + usec);
352 if (r < 0)
353 return r;
354
355 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
356 }
357
358 return sd_event_add_monotonic(UNIT(s)->manager->event, now(CLOCK_MONOTONIC) + usec, 0, service_dispatch_timer, s, &s->timer_event_source);
44d8db9e
LP
359}
360
07459bb6 361#ifdef HAVE_SYSV_COMPAT
b7ccee3c
LP
362static char *sysv_translate_name(const char *name) {
363 char *r;
364
5d4caf56
LP
365 r = new(char, strlen(name) + sizeof(".service"));
366 if (!r)
b7ccee3c
LP
367 return NULL;
368
5b819198 369 if (endswith(name, ".sh"))
85a3fa0e 370 /* Drop .sh suffix */
5b819198 371 strcpy(stpcpy(r, name) - 3, ".service");
b7ccee3c 372 else
85a3fa0e 373 /* Normal init script name */
b7ccee3c
LP
374 strcpy(stpcpy(r, name), ".service");
375
376 return r;
377}
378
ee95669f 379static int sysv_translate_facility(const char *name, const char *filename, char **_r) {
2c4104f0 380
a7d3cc26
LP
381 /* We silently ignore the $ prefix here. According to the LSB
382 * spec it simply indicates whether something is a
383 * standardized name or a distribution-specific one. Since we
384 * just follow what already exists and do not introduce new
385 * uses or names we don't care who introduced a new name. */
386
2c4104f0 387 static const char * const table[] = {
6464aa08 388 /* LSB defined facilities */
5d4caf56 389 "local_fs", NULL,
a7d3cc26
LP
390 "network", SPECIAL_NETWORK_TARGET,
391 "named", SPECIAL_NSS_LOOKUP_TARGET,
392 "portmap", SPECIAL_RPCBIND_TARGET,
393 "remote_fs", SPECIAL_REMOTE_FS_TARGET,
5d4caf56 394 "syslog", NULL,
4466194c 395 "time", SPECIAL_TIME_SYNC_TARGET,
2c4104f0
LP
396 };
397
398 unsigned i;
399 char *r;
ee95669f 400 const char *n;
2c4104f0 401
ee95669f
LP
402 assert(name);
403 assert(_r);
a7d3cc26 404
ee95669f 405 n = *name == '$' ? name + 1 : name;
a7d3cc26 406
ee95669f 407 for (i = 0; i < ELEMENTSOF(table); i += 2) {
a7d3cc26 408
ee95669f
LP
409 if (!streq(table[i], n))
410 continue;
2c4104f0 411
ee95669f
LP
412 if (!table[i+1])
413 return 0;
414
5d4caf56
LP
415 r = strdup(table[i+1]);
416 if (!r)
417 return log_oom();
ee95669f
LP
418
419 goto finish;
420 }
2c4104f0 421
a7d3cc26 422 /* If we don't know this name, fallback heuristics to figure
0003d1ab 423 * out whether something is a target or a service alias. */
a7d3cc26 424
e83c7c0b
LP
425 if (*name == '$') {
426 if (!unit_prefix_is_valid(n))
427 return -EINVAL;
428
ee95669f
LP
429 /* Facilities starting with $ are most likely targets */
430 r = unit_name_build(n, NULL, ".target");
e83c7c0b 431 } else if (filename && streq(name, filename))
35b8ca3a 432 /* Names equaling the file name of the services are redundant */
ee95669f 433 return 0;
32159d3a 434 else
ee95669f
LP
435 /* Everything else we assume to be normal service names */
436 r = sysv_translate_name(n);
2c4104f0 437
32159d3a 438 if (!r)
2c4104f0
LP
439 return -ENOMEM;
440
441finish:
b4353094 442 *_r = r;
2c4104f0
LP
443
444 return 1;
445}
446
56d748b4 447static int sysv_fix_order(Service *s) {
ac155bb8 448 Unit *other;
2c4104f0
LP
449 int r;
450
451 assert(s);
452
453 if (s->sysv_start_priority < 0)
454 return 0;
455
23a177ef
LP
456 /* For each pair of services where at least one lacks a LSB
457 * header, we use the start priority value to order things. */
2c4104f0 458
1124fe6f 459 LIST_FOREACH(units_by_type, other, UNIT(s)->manager->units_by_type[UNIT_SERVICE]) {
2c4104f0
LP
460 Service *t;
461 UnitDependency d;
eeaafddc 462 bool special_s, special_t;
2c4104f0 463
595ed347 464 t = SERVICE(other);
2c4104f0
LP
465
466 if (s == t)
467 continue;
9f151f29 468
1124fe6f 469 if (UNIT(t)->load_state != UNIT_LOADED)
9f151f29 470 continue;
2c4104f0
LP
471
472 if (t->sysv_start_priority < 0)
473 continue;
474
51a1a79d
LP
475 /* If both units have modern headers we don't care
476 * about the priorities */
1124fe6f
MS
477 if ((UNIT(s)->fragment_path || s->sysv_has_lsb) &&
478 (UNIT(t)->fragment_path || t->sysv_has_lsb))
23a177ef
LP
479 continue;
480
eeaafddc
LP
481 special_s = s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels);
482 special_t = t->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, t->sysv_runlevels);
483
484 if (special_t && !special_s)
485 d = UNIT_AFTER;
486 else if (special_s && !special_t)
487 d = UNIT_BEFORE;
488 else if (t->sysv_start_priority < s->sysv_start_priority)
2c4104f0
LP
489 d = UNIT_AFTER;
490 else if (t->sysv_start_priority > s->sysv_start_priority)
491 d = UNIT_BEFORE;
492 else
493 continue;
494
495 /* FIXME: Maybe we should compare the name here lexicographically? */
496
da19d5c1 497 if ((r = unit_add_dependency(UNIT(s), d, UNIT(t), true)) < 0)
2c4104f0
LP
498 return r;
499 }
500
501 return 0;
502}
503
504static ExecCommand *exec_command_new(const char *path, const char *arg1) {
505 ExecCommand *c;
506
507 if (!(c = new0(ExecCommand, 1)))
508 return NULL;
509
510 if (!(c->path = strdup(path))) {
511 free(c);
512 return NULL;
513 }
514
515 if (!(c->argv = strv_new(path, arg1, NULL))) {
516 free(c->path);
517 free(c);
518 return NULL;
519 }
520
521 return c;
522}
523
37e2941d 524static int sysv_exec_commands(Service *s, const bool supports_reload) {
2c4104f0
LP
525 ExecCommand *c;
526
527 assert(s);
1b64d026
LP
528 assert(s->is_sysv);
529 assert(UNIT(s)->source_path);
2c4104f0 530
1b64d026
LP
531 c = exec_command_new(UNIT(s)->source_path, "start");
532 if (!c)
2c4104f0
LP
533 return -ENOMEM;
534 exec_command_append_list(s->exec_command+SERVICE_EXEC_START, c);
535
1b64d026
LP
536 c = exec_command_new(UNIT(s)->source_path, "stop");
537 if (!c)
2c4104f0
LP
538 return -ENOMEM;
539 exec_command_append_list(s->exec_command+SERVICE_EXEC_STOP, c);
540
37e2941d
MS
541 if (supports_reload) {
542 c = exec_command_new(UNIT(s)->source_path, "reload");
543 if (!c)
544 return -ENOMEM;
545 exec_command_append_list(s->exec_command+SERVICE_EXEC_RELOAD, c);
546 }
2c4104f0
LP
547
548 return 0;
549}
550
37e2941d
MS
551static bool usage_contains_reload(const char *line) {
552 return (strcasestr(line, "{reload|") ||
553 strcasestr(line, "{reload}") ||
554 strcasestr(line, "{reload\"") ||
555 strcasestr(line, "|reload|") ||
556 strcasestr(line, "|reload}") ||
557 strcasestr(line, "|reload\""));
558}
559
e537352b 560static int service_load_sysv_path(Service *s, const char *path) {
2c4104f0
LP
561 FILE *f;
562 Unit *u;
563 unsigned line = 0;
564 int r;
565 enum {
566 NORMAL,
567 DESCRIPTION,
568 LSB,
37e2941d
MS
569 LSB_DESCRIPTION,
570 USAGE_CONTINUATION
2c4104f0 571 } state = NORMAL;
0b5d26f9 572 char *short_description = NULL, *long_description = NULL, *chkconfig_description = NULL, *description;
5f4b19f4 573 struct stat st;
37e2941d 574 bool supports_reload = false;
23a177ef
LP
575
576 assert(s);
577 assert(path);
2c4104f0
LP
578
579 u = UNIT(s);
580
1b64d026
LP
581 f = fopen(path, "re");
582 if (!f) {
2c4104f0
LP
583 r = errno == ENOENT ? 0 : -errno;
584 goto finish;
585 }
586
5f4b19f4
LP
587 if (fstat(fileno(f), &st) < 0) {
588 r = -errno;
589 goto finish;
590 }
591
1b64d026
LP
592 free(u->source_path);
593 u->source_path = strdup(path);
594 if (!u->source_path) {
2c4104f0
LP
595 r = -ENOMEM;
596 goto finish;
597 }
1b64d026 598 u->source_mtime = timespec_load(&st.st_mtim);
5f4b19f4
LP
599
600 if (null_or_empty(&st)) {
ac155bb8 601 u->load_state = UNIT_MASKED;
5f4b19f4
LP
602 r = 0;
603 goto finish;
604 }
605
1b64d026
LP
606 s->is_sysv = true;
607
2c4104f0
LP
608 while (!feof(f)) {
609 char l[LINE_MAX], *t;
610
611 if (!fgets(l, sizeof(l), f)) {
612 if (feof(f))
613 break;
614
615 r = -errno;
66870f90
ZJS
616 log_error_unit(u->id,
617 "Failed to read configuration file '%s': %s",
618 path, strerror(-r));
2c4104f0
LP
619 goto finish;
620 }
621
622 line++;
623
624 t = strstrip(l);
37e2941d
MS
625 if (*t != '#') {
626 /* Try to figure out whether this init script supports
627 * the reload operation. This heuristic looks for
628 * "Usage" lines which include the reload option. */
629 if ( state == USAGE_CONTINUATION ||
630 (state == NORMAL && strcasestr(t, "usage"))) {
631 if (usage_contains_reload(t)) {
632 supports_reload = true;
633 state = NORMAL;
634 } else if (t[strlen(t)-1] == '\\')
635 state = USAGE_CONTINUATION;
636 else
637 state = NORMAL;
638 }
639
2c4104f0 640 continue;
37e2941d 641 }
2c4104f0
LP
642
643 if (state == NORMAL && streq(t, "### BEGIN INIT INFO")) {
644 state = LSB;
23a177ef 645 s->sysv_has_lsb = true;
2c4104f0
LP
646 continue;
647 }
648
649 if ((state == LSB_DESCRIPTION || state == LSB) && streq(t, "### END INIT INFO")) {
650 state = NORMAL;
651 continue;
652 }
653
654 t++;
655 t += strspn(t, WHITESPACE);
656
657 if (state == NORMAL) {
658
659 /* Try to parse Red Hat style chkconfig headers */
660
c2b35af6 661 if (startswith_no_case(t, "chkconfig:")) {
2c4104f0 662 int start_priority;
8309400a 663 char runlevels[16], *k;
2c4104f0
LP
664
665 state = NORMAL;
666
8309400a
LP
667 if (sscanf(t+10, "%15s %i %*i",
668 runlevels,
669 &start_priority) != 2) {
2c4104f0 670
66870f90
ZJS
671 log_warning_unit(u->id,
672 "[%s:%u] Failed to parse chkconfig line. Ignoring.",
673 path, line);
2c4104f0
LP
674 continue;
675 }
676
fbe9f3a9
LP
677 /* A start priority gathered from the
678 * symlink farms is preferred over the
679 * data from the LSB header. */
8309400a 680 if (start_priority < 0 || start_priority > 99)
66870f90
ZJS
681 log_warning_unit(u->id,
682 "[%s:%u] Start priority out of range. Ignoring.",
683 path, line);
ea87ca5a 684 else
8309400a
LP
685 s->sysv_start_priority = start_priority;
686
687 char_array_0(runlevels);
688 k = delete_chars(runlevels, WHITESPACE "-");
689
690 if (k[0]) {
691 char *d;
692
693 if (!(d = strdup(k))) {
694 r = -ENOMEM;
695 goto finish;
696 }
697
698 free(s->sysv_runlevels);
699 s->sysv_runlevels = d;
2c4104f0
LP
700 }
701
0b5d26f9 702 } else if (startswith_no_case(t, "description:")) {
2c4104f0
LP
703
704 size_t k = strlen(t);
705 char *d;
0b5d26f9 706 const char *j;
2c4104f0
LP
707
708 if (t[k-1] == '\\') {
709 state = DESCRIPTION;
710 t[k-1] = 0;
711 }
712
0b5d26f9
LP
713 if ((j = strstrip(t+12)) && *j) {
714 if (!(d = strdup(j))) {
715 r = -ENOMEM;
716 goto finish;
717 }
718 } else
719 d = NULL;
2c4104f0 720
0b5d26f9
LP
721 free(chkconfig_description);
722 chkconfig_description = d;
2c4104f0 723
c2b35af6 724 } else if (startswith_no_case(t, "pidfile:")) {
2c4104f0
LP
725
726 char *fn;
727
728 state = NORMAL;
729
730 fn = strstrip(t+8);
731 if (!path_is_absolute(fn)) {
66870f90
ZJS
732 log_warning_unit(u->id,
733 "[%s:%u] PID file not absolute. Ignoring.",
734 path, line);
2c4104f0
LP
735 continue;
736 }
737
738 if (!(fn = strdup(fn))) {
739 r = -ENOMEM;
740 goto finish;
741 }
742
743 free(s->pid_file);
744 s->pid_file = fn;
745 }
746
747 } else if (state == DESCRIPTION) {
748
749 /* Try to parse Red Hat style description
750 * continuation */
751
752 size_t k = strlen(t);
0b5d26f9 753 char *j;
2c4104f0
LP
754
755 if (t[k-1] == '\\')
756 t[k-1] = 0;
757 else
758 state = NORMAL;
759
0b5d26f9
LP
760 if ((j = strstrip(t)) && *j) {
761 char *d = NULL;
762
763 if (chkconfig_description)
b7def684 764 d = strjoin(chkconfig_description, " ", j, NULL);
0b5d26f9
LP
765 else
766 d = strdup(j);
2c4104f0 767
0b5d26f9
LP
768 if (!d) {
769 r = -ENOMEM;
770 goto finish;
771 }
772
773 free(chkconfig_description);
774 chkconfig_description = d;
775 }
2c4104f0
LP
776
777 } else if (state == LSB || state == LSB_DESCRIPTION) {
778
c2b35af6 779 if (startswith_no_case(t, "Provides:")) {
2c4104f0
LP
780 char *i, *w;
781 size_t z;
782
783 state = LSB;
784
f60f22df 785 FOREACH_WORD_QUOTED(w, z, t+9, i) {
2c4104f0
LP
786 char *n, *m;
787
788 if (!(n = strndup(w, z))) {
789 r = -ENOMEM;
790 goto finish;
791 }
792
2b6bf07d 793 r = sysv_translate_facility(n, basename(path), &m);
2c4104f0
LP
794 free(n);
795
796 if (r < 0)
797 goto finish;
798
799 if (r == 0)
800 continue;
801
bd77d0fc 802 if (unit_name_to_type(m) == UNIT_SERVICE)
ce2c2265 803 r = unit_merge_by_name(u, m);
9700edb4
LP
804 else
805 /* NB: SysV targets
806 * which are provided
807 * by a service are
808 * pulled in by the
809 * services, as an
810 * indication that the
811 * generic service is
812 * now available. This
813 * is strictly
814 * one-way. The
815 * targets do NOT pull
816 * in the SysV
817 * services! */
818 r = unit_add_two_dependencies_by_name(u, UNIT_BEFORE, UNIT_WANTS, m, NULL, true);
bd77d0fc 819
2c4104f0 820 if (r < 0)
66870f90
ZJS
821 log_error_unit(u->id,
822 "[%s:%u] Failed to add LSB Provides name %s, ignoring: %s",
823 path, line, m, strerror(-r));
42a097a2
LP
824
825 free(m);
2c4104f0
LP
826 }
827
c2b35af6
LP
828 } else if (startswith_no_case(t, "Required-Start:") ||
829 startswith_no_case(t, "Should-Start:") ||
830 startswith_no_case(t, "X-Start-Before:") ||
831 startswith_no_case(t, "X-Start-After:")) {
2c4104f0
LP
832 char *i, *w;
833 size_t z;
834
835 state = LSB;
836
f60f22df 837 FOREACH_WORD_QUOTED(w, z, strchr(t, ':')+1, i) {
2c4104f0
LP
838 char *n, *m;
839
840 if (!(n = strndup(w, z))) {
841 r = -ENOMEM;
842 goto finish;
843 }
844
2b6bf07d 845 r = sysv_translate_facility(n, basename(path), &m);
e83c7c0b 846 if (r < 0) {
66870f90
ZJS
847 log_error_unit(u->id,
848 "[%s:%u] Failed to translate LSB dependency %s, ignoring: %s",
849 path, line, n, strerror(-r));
e83c7c0b
LP
850 free(n);
851 continue;
852 }
853
854 free(n);
2c4104f0
LP
855
856 if (r == 0)
857 continue;
858
c2b35af6 859 r = unit_add_dependency_by_name(u, startswith_no_case(t, "X-Start-Before:") ? UNIT_BEFORE : UNIT_AFTER, m, NULL, true);
2c4104f0
LP
860
861 if (r < 0)
66870f90
ZJS
862 log_error_unit(u->id, "[%s:%u] Failed to add dependency on %s, ignoring: %s",
863 path, line, m, strerror(-r));
42a097a2
LP
864
865 free(m);
2c4104f0 866 }
c2b35af6 867 } else if (startswith_no_case(t, "Default-Start:")) {
8309400a
LP
868 char *k, *d;
869
870 state = LSB;
871
872 k = delete_chars(t+14, WHITESPACE "-");
873
874 if (k[0] != 0) {
875 if (!(d = strdup(k))) {
876 r = -ENOMEM;
877 goto finish;
878 }
879
880 free(s->sysv_runlevels);
881 s->sysv_runlevels = d;
882 }
2c4104f0 883
0b5d26f9
LP
884 } else if (startswith_no_case(t, "Description:")) {
885 char *d, *j;
ed4c1cc6 886
2c4104f0
LP
887 state = LSB_DESCRIPTION;
888
0b5d26f9
LP
889 if ((j = strstrip(t+12)) && *j) {
890 if (!(d = strdup(j))) {
891 r = -ENOMEM;
892 goto finish;
893 }
894 } else
895 d = NULL;
2c4104f0 896
0b5d26f9
LP
897 free(long_description);
898 long_description = d;
2c4104f0 899
ed4c1cc6 900 } else if (startswith_no_case(t, "Short-Description:")) {
0b5d26f9 901 char *d, *j;
2c4104f0 902
2c4104f0
LP
903 state = LSB;
904
0b5d26f9
LP
905 if ((j = strstrip(t+18)) && *j) {
906 if (!(d = strdup(j))) {
907 r = -ENOMEM;
908 goto finish;
909 }
910 } else
911 d = NULL;
2c4104f0 912
0b5d26f9
LP
913 free(short_description);
914 short_description = d;
2c4104f0
LP
915
916 } else if (state == LSB_DESCRIPTION) {
917
918 if (startswith(l, "#\t") || startswith(l, "# ")) {
0b5d26f9 919 char *j;
2c4104f0 920
0b5d26f9
LP
921 if ((j = strstrip(t)) && *j) {
922 char *d = NULL;
923
924 if (long_description)
b7def684 925 d = strjoin(long_description, " ", t, NULL);
0b5d26f9
LP
926 else
927 d = strdup(j);
928
929 if (!d) {
930 r = -ENOMEM;
931 goto finish;
932 }
933
934 free(long_description);
935 long_description = d;
2c4104f0
LP
936 }
937
2c4104f0
LP
938 } else
939 state = LSB;
940 }
941 }
942 }
943
37e2941d 944 if ((r = sysv_exec_commands(s, supports_reload)) < 0)
2c4104f0
LP
945 goto finish;
946
a40eb732 947 if (s->sysv_runlevels && !chars_intersect(RUNLEVELS_UP, s->sysv_runlevels)) {
0bc824be
LP
948 /* If there a runlevels configured for this service
949 * but none of the standard ones, then we assume this
950 * is some special kind of service (which might be
951 * needed for early boot) and don't create any links
952 * to it. */
953
1124fe6f 954 UNIT(s)->default_dependencies = false;
09cd1ab1 955
09cd1ab1 956 /* Don't timeout special services during boot (like fsck) */
d568a335
MS
957 s->timeout_start_usec = 0;
958 s->timeout_stop_usec = 0;
959 } else {
960 s->timeout_start_usec = DEFAULT_SYSV_TIMEOUT_USEC;
961 s->timeout_stop_usec = DEFAULT_SYSV_TIMEOUT_USEC;
962 }
963
80876c20 964 /* Special setting for all SysV services */
1f48cf56 965 s->type = SERVICE_FORKING;
f8788303 966 s->remain_after_exit = !s->pid_file;
1835f23c 967 s->guess_main_pid = false;
525ee6f4 968 s->restart = SERVICE_RESTART_NO;
353e12c2 969 s->exec_context.ignore_sigpipe = false;
4819ff03 970 s->kill_context.kill_mode = KILL_PROCESS;
80876c20 971
0b5d26f9
LP
972 /* We use the long description only if
973 * no short description is set. */
974
975 if (short_description)
976 description = short_description;
977 else if (chkconfig_description)
978 description = chkconfig_description;
979 else if (long_description)
980 description = long_description;
981 else
982 description = NULL;
983
984 if (description) {
985 char *d;
986
e527618d 987 if (!(d = strappend(s->sysv_has_lsb ? "LSB: " : "SYSV: ", description))) {
0b5d26f9
LP
988 r = -ENOMEM;
989 goto finish;
990 }
991
ac155bb8 992 u->description = d;
0b5d26f9
LP
993 }
994
ea87ca5a
LP
995 /* The priority that has been set in /etc/rcN.d/ hierarchies
996 * takes precedence over what is stored as default in the LSB
997 * header */
998 if (s->sysv_start_priority_from_rcnd >= 0)
999 s->sysv_start_priority = s->sysv_start_priority_from_rcnd;
1000
ac155bb8 1001 u->load_state = UNIT_LOADED;
23a177ef 1002 r = 0;
2c4104f0
LP
1003
1004finish:
1005
1006 if (f)
1007 fclose(f);
1008
0b5d26f9
LP
1009 free(short_description);
1010 free(long_description);
1011 free(chkconfig_description);
1012
2c4104f0
LP
1013 return r;
1014}
1015
e537352b 1016static int service_load_sysv_name(Service *s, const char *name) {
2c4104f0
LP
1017 char **p;
1018
1019 assert(s);
1020 assert(name);
1021
c2756a68 1022 /* For SysV services we strip the *.sh suffixes. */
3f95f83c 1023 if (endswith(name, ".sh.service"))
d017c6ca
LP
1024 return -ENOENT;
1025
1124fe6f 1026 STRV_FOREACH(p, UNIT(s)->manager->lookup_paths.sysvinit_path) {
2c4104f0
LP
1027 char *path;
1028 int r;
1029
b7def684 1030 path = strjoin(*p, "/", name, NULL);
44d91056 1031 if (!path)
2c4104f0
LP
1032 return -ENOMEM;
1033
1034 assert(endswith(path, ".service"));
1035 path[strlen(path)-8] = 0;
1036
e537352b 1037 r = service_load_sysv_path(s, path);
fbe9f3a9 1038
1124fe6f 1039 if (r >= 0 && UNIT(s)->load_state == UNIT_STUB) {
20771ae3 1040 /* Try *.sh source'able init scripts */
fbe9f3a9
LP
1041 strcat(path, ".sh");
1042 r = service_load_sysv_path(s, path);
1043 }
2c4104f0
LP
1044 free(path);
1045
23a177ef 1046 if (r < 0)
2c4104f0 1047 return r;
23a177ef 1048
88516c0c 1049 if (UNIT(s)->load_state != UNIT_STUB)
23a177ef 1050 break;
2c4104f0
LP
1051 }
1052
1053 return 0;
1054}
1055
e537352b 1056static int service_load_sysv(Service *s) {
2c4104f0
LP
1057 const char *t;
1058 Iterator i;
1059 int r;
1060
5cb5a6ff
LP
1061 assert(s);
1062
1063 /* Load service data from SysV init scripts, preferably with
1064 * LSB headers ... */
1065
1124fe6f 1066 if (strv_isempty(UNIT(s)->manager->lookup_paths.sysvinit_path))
2c4104f0
LP
1067 return 0;
1068
1124fe6f 1069 if ((t = UNIT(s)->id))
e537352b 1070 if ((r = service_load_sysv_name(s, t)) < 0)
2c4104f0
LP
1071 return r;
1072
1124fe6f
MS
1073 if (UNIT(s)->load_state == UNIT_STUB)
1074 SET_FOREACH(t, UNIT(s)->names, i) {
1075 if (t == UNIT(s)->id)
e537352b
LP
1076 continue;
1077
e364ad06 1078 if ((r = service_load_sysv_name(s, t)) < 0)
23a177ef
LP
1079 return r;
1080
1124fe6f 1081 if (UNIT(s)->load_state != UNIT_STUB)
23a177ef
LP
1082 break;
1083 }
2c4104f0
LP
1084
1085 return 0;
5cb5a6ff 1086}
07459bb6 1087#endif
5cb5a6ff 1088
243b1432
LP
1089static int service_verify(Service *s) {
1090 assert(s);
1091
1124fe6f 1092 if (UNIT(s)->load_state != UNIT_LOADED)
243b1432
LP
1093 return 0;
1094
1095 if (!s->exec_command[SERVICE_EXEC_START]) {
66870f90
ZJS
1096 log_error_unit(UNIT(s)->id,
1097 "%s lacks ExecStart setting. Refusing.", UNIT(s)->id);
243b1432
LP
1098 return -EINVAL;
1099 }
1100
34e9ba66
LP
1101 if (s->type != SERVICE_ONESHOT &&
1102 s->exec_command[SERVICE_EXEC_START]->command_next) {
66870f90
ZJS
1103 log_error_unit(UNIT(s)->id,
1104 "%s has more than one ExecStart setting, which is only allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
6cf6bbc2
LP
1105 return -EINVAL;
1106 }
1107
b0693d30
MW
1108 if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
1109 log_error_unit(UNIT(s)->id,
1110 "%s has Restart setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
1111 return -EINVAL;
1112 }
1113
05e343b7 1114 if (s->type == SERVICE_DBUS && !s->bus_name) {
66870f90
ZJS
1115 log_error_unit(UNIT(s)->id,
1116 "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
4d0e5dbd
LP
1117 return -EINVAL;
1118 }
1119
7e2668c6 1120 if (s->bus_name && s->type != SERVICE_DBUS)
66870f90
ZJS
1121 log_warning_unit(UNIT(s)->id,
1122 "%s has a D-Bus service name specified, but is not of type dbus. Ignoring.", UNIT(s)->id);
7e2668c6 1123
4819ff03 1124 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
66870f90
ZJS
1125 log_error_unit(UNIT(s)->id,
1126 "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
05e343b7
LP
1127 return -EINVAL;
1128 }
1129
243b1432
LP
1130 return 0;
1131}
1132
a40eb732
LP
1133static int service_add_default_dependencies(Service *s) {
1134 int r;
1135
1136 assert(s);
1137
1138 /* Add a number of automatic dependencies useful for the
1139 * majority of services. */
1140
1141 /* First, pull in base system */
67445f4e 1142 if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
117dcc57
ZJS
1143 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
1144 SPECIAL_BASIC_TARGET, NULL, true);
1145 if (r < 0)
a40eb732
LP
1146 return r;
1147
67445f4e 1148 } else if (UNIT(s)->manager->running_as == SYSTEMD_USER) {
117dcc57
ZJS
1149 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
1150 SPECIAL_SOCKETS_TARGET, NULL, true);
1151 if (r < 0)
a40eb732 1152 return r;
e3d84721
LP
1153
1154 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
1155 SPECIAL_TIMERS_TARGET, NULL, true);
1156 if (r < 0)
1157 return r;
1158
1159 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES,
1160 SPECIAL_PATHS_TARGET, NULL, true);
1161 if (r < 0)
1162 return r;
a40eb732
LP
1163 }
1164
1165 /* Second, activate normal shutdown */
117dcc57
ZJS
1166 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS,
1167 SPECIAL_SHUTDOWN_TARGET, NULL, true);
1168 return r;
a40eb732
LP
1169}
1170
4dfc092a
LP
1171static void service_fix_output(Service *s) {
1172 assert(s);
1173
1174 /* If nothing has been explicitly configured, patch default
1175 * output in. If input is socket/tty we avoid this however,
1176 * since in that case we want output to default to the same
1177 * place as we read input from. */
1178
1179 if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
1180 s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1181 s->exec_context.std_input == EXEC_INPUT_NULL)
1124fe6f 1182 s->exec_context.std_error = UNIT(s)->manager->default_std_error;
4dfc092a
LP
1183
1184 if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT &&
1185 s->exec_context.std_input == EXEC_INPUT_NULL)
1124fe6f 1186 s->exec_context.std_output = UNIT(s)->manager->default_std_output;
4dfc092a
LP
1187}
1188
e537352b
LP
1189static int service_load(Unit *u) {
1190 int r;
1191 Service *s = SERVICE(u);
1192
1193 assert(s);
1e2e8133 1194
5cb5a6ff 1195 /* Load a .service file */
c2756a68
LP
1196 r = unit_load_fragment(u);
1197 if (r < 0)
5cb5a6ff
LP
1198 return r;
1199
07459bb6 1200#ifdef HAVE_SYSV_COMPAT
bd77d0fc 1201 /* Load a classic init script as a fallback, if we couldn't find anything */
c2756a68
LP
1202 if (u->load_state == UNIT_STUB) {
1203 r = service_load_sysv(s);
1204 if (r < 0)
23a177ef 1205 return r;
c2756a68 1206 }
07459bb6 1207#endif
d46de8a1 1208
23a177ef 1209 /* Still nothing found? Then let's give up */
ac155bb8 1210 if (u->load_state == UNIT_STUB)
23a177ef 1211 return -ENOENT;
034c6ed7 1212
23a177ef 1213 /* This is a new unit? Then let's add in some extras */
ac155bb8 1214 if (u->load_state == UNIT_LOADED) {
c2756a68
LP
1215
1216 /* We were able to load something, then let's add in
1217 * the dropin directories. */
1218 r = unit_load_dropin(u);
1219 if (r < 0)
1220 return r;
1221
0b86feac
LP
1222 if (s->type == _SERVICE_TYPE_INVALID)
1223 s->type = s->bus_name ? SERVICE_DBUS : SERVICE_SIMPLE;
1224
d568a335
MS
1225 /* Oneshot services have disabled start timeout by default */
1226 if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
1227 s->timeout_start_usec = 0;
98709151 1228
4e2b0f9b
LP
1229 service_fix_output(s);
1230
117dcc57
ZJS
1231 r = unit_add_exec_dependencies(u, &s->exec_context);
1232 if (r < 0)
23a177ef
LP
1233 return r;
1234
a016b922
LP
1235 r = unit_add_default_slice(u);
1236 if (r < 0)
1237 return r;
1238
07459bb6 1239#ifdef HAVE_SYSV_COMPAT
117dcc57
ZJS
1240 r = sysv_fix_order(s);
1241 if (r < 0)
23a177ef 1242 return r;
07459bb6 1243#endif
05e343b7 1244
718db961
LP
1245 if (s->bus_name) {
1246 r = unit_watch_bus_name(u, s->bus_name);
1247 if (r < 0)
a40eb732 1248 return r;
718db961 1249 }
c952c6ec
LP
1250
1251 if (s->type == SERVICE_NOTIFY && s->notify_access == NOTIFY_NONE)
1252 s->notify_access = NOTIFY_MAIN;
a40eb732 1253
02c4ef9c
LP
1254 if (s->watchdog_usec > 0 && s->notify_access == NOTIFY_NONE)
1255 s->notify_access = NOTIFY_MAIN;
1256
117dcc57
ZJS
1257 if (s->type == SERVICE_DBUS || s->bus_name) {
1258 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES,
1259 SPECIAL_DBUS_SOCKET, NULL, true);
1260 if (r < 0)
a40eb732 1261 return r;
117dcc57 1262 }
a40eb732 1263
117dcc57
ZJS
1264 if (UNIT(s)->default_dependencies) {
1265 r = service_add_default_dependencies(s);
1266 if (r < 0)
a40eb732 1267 return r;
117dcc57 1268 }
e06c73cc 1269
cba6e062 1270 r = unit_exec_context_defaults(u, &s->exec_context);
e06c73cc
LP
1271 if (r < 0)
1272 return r;
8e274523
LP
1273 }
1274
243b1432 1275 return service_verify(s);
034c6ed7
LP
1276}
1277
87f0e418 1278static void service_dump(Unit *u, FILE *f, const char *prefix) {
5cb5a6ff 1279
5cb5a6ff 1280 ServiceExecCommand c;
87f0e418 1281 Service *s = SERVICE(u);
47be870b 1282 const char *prefix2;
7fd1b19b 1283 _cleanup_free_ char *p2 = NULL;
5cb5a6ff
LP
1284
1285 assert(s);
1286
47be870b
LP
1287 p2 = strappend(prefix, "\t");
1288 prefix2 = p2 ? p2 : prefix;
44d8db9e 1289
5cb5a6ff 1290 fprintf(f,
81a2b7ce 1291 "%sService State: %s\n"
f42806df
LP
1292 "%sResult: %s\n"
1293 "%sReload Result: %s\n"
81a2b7ce 1294 "%sPermissionsStartOnly: %s\n"
8e274523 1295 "%sRootDirectoryStartOnly: %s\n"
02ee865a 1296 "%sRemainAfterExit: %s\n"
3185a36b 1297 "%sGuessMainPID: %s\n"
c952c6ec 1298 "%sType: %s\n"
2cf3143a 1299 "%sRestart: %s\n"
c952c6ec 1300 "%sNotifyAccess: %s\n",
81a2b7ce 1301 prefix, service_state_to_string(s->state),
f42806df
LP
1302 prefix, service_result_to_string(s->result),
1303 prefix, service_result_to_string(s->reload_result),
81a2b7ce 1304 prefix, yes_no(s->permissions_start_only),
8e274523 1305 prefix, yes_no(s->root_directory_start_only),
02ee865a 1306 prefix, yes_no(s->remain_after_exit),
3185a36b 1307 prefix, yes_no(s->guess_main_pid),
c952c6ec 1308 prefix, service_type_to_string(s->type),
2cf3143a 1309 prefix, service_restart_to_string(s->restart),
c952c6ec 1310 prefix, notify_access_to_string(s->notify_access));
5cb5a6ff 1311
70123e68
LP
1312 if (s->control_pid > 0)
1313 fprintf(f,
bb00e604
LP
1314 "%sControl PID: %lu\n",
1315 prefix, (unsigned long) s->control_pid);
70123e68
LP
1316
1317 if (s->main_pid > 0)
1318 fprintf(f,
6dfa5494
LP
1319 "%sMain PID: %lu\n"
1320 "%sMain PID Known: %s\n"
1321 "%sMain PID Alien: %s\n",
1322 prefix, (unsigned long) s->main_pid,
1323 prefix, yes_no(s->main_pid_known),
1324 prefix, yes_no(s->main_pid_alien));
70123e68 1325
034c6ed7
LP
1326 if (s->pid_file)
1327 fprintf(f,
1328 "%sPIDFile: %s\n",
1329 prefix, s->pid_file);
1330
05e343b7
LP
1331 if (s->bus_name)
1332 fprintf(f,
1333 "%sBusName: %s\n"
1334 "%sBus Name Good: %s\n",
1335 prefix, s->bus_name,
1336 prefix, yes_no(s->bus_name_good));
1337
4819ff03 1338 kill_context_dump(&s->kill_context, f, prefix);
5cb5a6ff
LP
1339 exec_context_dump(&s->exec_context, f, prefix);
1340
e537352b 1341 for (c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
5cb5a6ff 1342
44d8db9e
LP
1343 if (!s->exec_command[c])
1344 continue;
1345
40d50879 1346 fprintf(f, "%s-> %s:\n",
94f04347 1347 prefix, service_exec_command_to_string(c));
44d8db9e
LP
1348
1349 exec_command_dump_list(s->exec_command[c], f, prefix2);
5cb5a6ff 1350 }
44d8db9e 1351
07459bb6 1352#ifdef HAVE_SYSV_COMPAT
1b64d026 1353 if (s->is_sysv)
2c4104f0 1354 fprintf(f,
9fff8a1f
LP
1355 "%sSysV Init Script has LSB Header: %s\n"
1356 "%sSysVEnabled: %s\n",
9fff8a1f
LP
1357 prefix, yes_no(s->sysv_has_lsb),
1358 prefix, yes_no(s->sysv_enabled));
2c4104f0
LP
1359
1360 if (s->sysv_start_priority >= 0)
1361 fprintf(f,
9fff8a1f
LP
1362 "%sSysVStartPriority: %i\n",
1363 prefix, s->sysv_start_priority);
2c4104f0 1364
8309400a
LP
1365 if (s->sysv_runlevels)
1366 fprintf(f, "%sSysVRunLevels: %s\n",
1367 prefix, s->sysv_runlevels);
07459bb6 1368#endif
23a177ef 1369
8c47c732
LP
1370 if (s->status_text)
1371 fprintf(f, "%sStatus Text: %s\n",
1372 prefix, s->status_text);
5cb5a6ff
LP
1373}
1374
c5419d42 1375static int service_load_pid_file(Service *s, bool may_warn) {
7fd1b19b 1376 _cleanup_free_ char *k = NULL;
034c6ed7 1377 int r;
5925dd3c 1378 pid_t pid;
034c6ed7
LP
1379
1380 assert(s);
1381
034c6ed7 1382 if (!s->pid_file)
13230d5d 1383 return -ENOENT;
034c6ed7 1384
117dcc57
ZJS
1385 r = read_one_line_file(s->pid_file, &k);
1386 if (r < 0) {
c5419d42 1387 if (may_warn)
66870f90
ZJS
1388 log_info_unit(UNIT(s)->id,
1389 "PID file %s not readable (yet?) after %s.",
1390 s->pid_file, service_state_to_string(s->state));
034c6ed7 1391 return r;
5375410b 1392 }
034c6ed7 1393
5925dd3c 1394 r = parse_pid(k, &pid);
bc41f93e
ZJS
1395 if (r < 0) {
1396 if (may_warn)
1397 log_info_unit(UNIT(s)->id,
1398 "Failed to read PID from file %s: %s",
1399 s->pid_file, strerror(-r));
5925dd3c 1400 return r;
bc41f93e 1401 }
406eaf93 1402
5925dd3c 1403 if (kill(pid, 0) < 0 && errno != EPERM) {
c5419d42 1404 if (may_warn)
66870f90
ZJS
1405 log_info_unit(UNIT(s)->id,
1406 "PID %lu read from file %s does not exist.",
1407 (unsigned long) pid, s->pid_file);
b8c597d5
LP
1408 return -ESRCH;
1409 }
1410
db01f8b3
MS
1411 if (s->main_pid_known) {
1412 if (pid == s->main_pid)
1413 return 0;
1414
66870f90
ZJS
1415 log_debug_unit(UNIT(s)->id,
1416 "Main PID changing: %lu -> %lu",
1417 (unsigned long) s->main_pid, (unsigned long) pid);
db01f8b3
MS
1418 service_unwatch_main_pid(s);
1419 s->main_pid_known = false;
3a111838 1420 } else
66870f90
ZJS
1421 log_debug_unit(UNIT(s)->id,
1422 "Main PID loaded: %lu", (unsigned long) pid);
db01f8b3 1423
117dcc57
ZJS
1424 r = service_set_main_pid(s, pid);
1425 if (r < 0)
16f6025e
LP
1426 return r;
1427
117dcc57 1428 r = unit_watch_pid(UNIT(s), pid);
bc41f93e 1429 if (r < 0) {
5925dd3c 1430 /* FIXME: we need to do something here */
bc41f93e
ZJS
1431 log_warning_unit(UNIT(s)->id,
1432 "Failed to watch PID %lu from service %s",
1433 (unsigned long) pid, UNIT(s)->id);
5925dd3c 1434 return r;
bc41f93e 1435 }
034c6ed7
LP
1436
1437 return 0;
1438}
1439
4fbf50b3
LP
1440static int service_search_main_pid(Service *s) {
1441 pid_t pid;
1442 int r;
1443
1444 assert(s);
1445
3185a36b
LP
1446 /* If we know it anyway, don't ever fallback to unreliable
1447 * heuristics */
4fbf50b3
LP
1448 if (s->main_pid_known)
1449 return 0;
1450
3185a36b
LP
1451 if (!s->guess_main_pid)
1452 return 0;
1453
4fbf50b3
LP
1454 assert(s->main_pid <= 0);
1455
4ad49000 1456 pid = unit_search_main_pid(UNIT(s));
117dcc57 1457 if (pid <= 0)
4fbf50b3
LP
1458 return -ENOENT;
1459
66870f90
ZJS
1460 log_debug_unit(UNIT(s)->id,
1461 "Main PID guessed: %lu", (unsigned long) pid);
117dcc57
ZJS
1462 r = service_set_main_pid(s, pid);
1463 if (r < 0)
4fbf50b3
LP
1464 return r;
1465
117dcc57
ZJS
1466 r = unit_watch_pid(UNIT(s), pid);
1467 if (r < 0)
4fbf50b3 1468 /* FIXME: we need to do something here */
a827e373
ZJS
1469 log_warning_unit(UNIT(s)->id,
1470 "Failed to watch PID %lu from service %s",
1471 (unsigned long) pid, UNIT(s)->id);
4fbf50b3
LP
1472 return r;
1473
1474 return 0;
1475}
1476
034c6ed7
LP
1477static void service_set_state(Service *s, ServiceState state) {
1478 ServiceState old_state;
e056b01d 1479 const UnitActiveState *table;
5cb5a6ff
LP
1480 assert(s);
1481
e056b01d
LP
1482 table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
1483
034c6ed7 1484 old_state = s->state;
5cb5a6ff 1485 s->state = state;
034c6ed7 1486
3a111838
MS
1487 service_unwatch_pid_file(s);
1488
034c6ed7
LP
1489 if (state != SERVICE_START_PRE &&
1490 state != SERVICE_START &&
1491 state != SERVICE_START_POST &&
1492 state != SERVICE_RELOAD &&
1493 state != SERVICE_STOP &&
1494 state != SERVICE_STOP_SIGTERM &&
1495 state != SERVICE_STOP_SIGKILL &&
1496 state != SERVICE_STOP_POST &&
1497 state != SERVICE_FINAL_SIGTERM &&
1498 state != SERVICE_FINAL_SIGKILL &&
1499 state != SERVICE_AUTO_RESTART)
718db961 1500 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
034c6ed7 1501
7d55e835
LP
1502 if (state != SERVICE_START &&
1503 state != SERVICE_START_POST &&
034c6ed7
LP
1504 state != SERVICE_RUNNING &&
1505 state != SERVICE_RELOAD &&
1506 state != SERVICE_STOP &&
1507 state != SERVICE_STOP_SIGTERM &&
867b3b7d 1508 state != SERVICE_STOP_SIGKILL) {
5e94833f 1509 service_unwatch_main_pid(s);
867b3b7d
LP
1510 s->main_command = NULL;
1511 }
034c6ed7
LP
1512
1513 if (state != SERVICE_START_PRE &&
1514 state != SERVICE_START &&
1515 state != SERVICE_START_POST &&
1516 state != SERVICE_RELOAD &&
1517 state != SERVICE_STOP &&
1518 state != SERVICE_STOP_SIGTERM &&
1519 state != SERVICE_STOP_SIGKILL &&
1520 state != SERVICE_STOP_POST &&
1521 state != SERVICE_FINAL_SIGTERM &&
e537352b 1522 state != SERVICE_FINAL_SIGKILL) {
5e94833f 1523 service_unwatch_control_pid(s);
034c6ed7 1524 s->control_command = NULL;
a16e1123 1525 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
e537352b 1526 }
034c6ed7 1527
4f2d528d
LP
1528 if (state != SERVICE_START_PRE &&
1529 state != SERVICE_START &&
6cf6bbc2
LP
1530 state != SERVICE_START_POST &&
1531 state != SERVICE_RUNNING &&
1532 state != SERVICE_RELOAD &&
1533 state != SERVICE_STOP &&
1534 state != SERVICE_STOP_SIGTERM &&
1535 state != SERVICE_STOP_SIGKILL &&
1536 state != SERVICE_STOP_POST &&
1537 state != SERVICE_FINAL_SIGTERM &&
1538 state != SERVICE_FINAL_SIGKILL &&
1124fe6f 1539 !(state == SERVICE_DEAD && UNIT(s)->job)) {
4f2d528d 1540 service_close_socket_fd(s);
6cf6bbc2
LP
1541 service_connection_unref(s);
1542 }
4f2d528d 1543
6d594baa 1544 if (state == SERVICE_STOP || state == SERVICE_STOP_SIGTERM)
a6927d7f
MO
1545 service_stop_watchdog(s);
1546
f6023656
LP
1547 /* For the inactive states unit_notify() will trim the cgroup,
1548 * but for exit we have to do that ourselves... */
1124fe6f 1549 if (state == SERVICE_EXITED && UNIT(s)->manager->n_reloading <= 0)
4ad49000 1550 unit_destroy_cgroup(UNIT(s));
f6023656 1551
9cd86184
OB
1552 /* For remain_after_exit services, let's see if we can "release" the
1553 * hold on the console, since unit_notify() only does that in case of
1554 * change of state */
1555 if (state == SERVICE_EXITED && s->remain_after_exit &&
1556 UNIT(s)->manager->n_on_console > 0) {
1557 ExecContext *ec = unit_get_exec_context(UNIT(s));
1558 if (ec && exec_context_may_touch_console(ec)) {
1559 Manager *m = UNIT(s)->manager;
1560
1561 m->n_on_console --;
1562 if (m->n_on_console == 0)
1563 /* unset no_console_output flag, since the console is free */
1564 m->no_console_output = false;
1565 }
1566 }
1567
e537352b 1568 if (old_state != state)
66870f90
ZJS
1569 log_debug_unit(UNIT(s)->id,
1570 "%s changed %s -> %s", UNIT(s)->id,
1571 service_state_to_string(old_state),
1572 service_state_to_string(state));
acbb0225 1573
e056b01d 1574 unit_notify(UNIT(s), table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
f42806df 1575 s->reload_result = SERVICE_SUCCESS;
034c6ed7
LP
1576}
1577
a16e1123
LP
1578static int service_coldplug(Unit *u) {
1579 Service *s = SERVICE(u);
1580 int r;
1581
1582 assert(s);
1583 assert(s->state == SERVICE_DEAD);
1584
1585 if (s->deserialized_state != s->state) {
1586
1587 if (s->deserialized_state == SERVICE_START_PRE ||
1588 s->deserialized_state == SERVICE_START ||
1589 s->deserialized_state == SERVICE_START_POST ||
1590 s->deserialized_state == SERVICE_RELOAD ||
1591 s->deserialized_state == SERVICE_STOP ||
1592 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1593 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1594 s->deserialized_state == SERVICE_STOP_POST ||
1595 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
92c1622e
LP
1596 s->deserialized_state == SERVICE_FINAL_SIGKILL) {
1597
1598 usec_t k;
6c12b52e 1599
92c1622e
LP
1600 k = s->deserialized_state == SERVICE_START_PRE || s->deserialized_state == SERVICE_START ||
1601 s->deserialized_state == SERVICE_START_POST || s->deserialized_state == SERVICE_RELOAD ?
1602 s->timeout_start_usec : s->timeout_stop_usec;
e558336f 1603
92c1622e
LP
1604 /* For the start/stop timeouts 0 means off */
1605 if (k > 0) {
1606 r = service_arm_timer(s, k);
36697dc0 1607 if (r < 0)
e558336f
LP
1608 return r;
1609 }
1610 }
a16e1123 1611
92c1622e
LP
1612 if (s->deserialized_state == SERVICE_AUTO_RESTART) {
1613
1614 /* The restart timeouts 0 means immediately */
1615 r = service_arm_timer(s, s->restart_usec);
1616 if (r < 0)
1617 return r;
1618 }
1619
a16e1123
LP
1620 if ((s->deserialized_state == SERVICE_START &&
1621 (s->type == SERVICE_FORKING ||
8c47c732 1622 s->type == SERVICE_DBUS ||
34e9ba66 1623 s->type == SERVICE_ONESHOT ||
8c47c732 1624 s->type == SERVICE_NOTIFY)) ||
a16e1123
LP
1625 s->deserialized_state == SERVICE_START_POST ||
1626 s->deserialized_state == SERVICE_RUNNING ||
1627 s->deserialized_state == SERVICE_RELOAD ||
1628 s->deserialized_state == SERVICE_STOP ||
1629 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1630 s->deserialized_state == SERVICE_STOP_SIGKILL)
117dcc57
ZJS
1631 if (s->main_pid > 0) {
1632 r = unit_watch_pid(UNIT(s), s->main_pid);
1633 if (r < 0)
a16e1123 1634 return r;
117dcc57 1635 }
a16e1123
LP
1636
1637 if (s->deserialized_state == SERVICE_START_PRE ||
1638 s->deserialized_state == SERVICE_START ||
1639 s->deserialized_state == SERVICE_START_POST ||
1640 s->deserialized_state == SERVICE_RELOAD ||
1641 s->deserialized_state == SERVICE_STOP ||
1642 s->deserialized_state == SERVICE_STOP_SIGTERM ||
1643 s->deserialized_state == SERVICE_STOP_SIGKILL ||
1644 s->deserialized_state == SERVICE_STOP_POST ||
1645 s->deserialized_state == SERVICE_FINAL_SIGTERM ||
1646 s->deserialized_state == SERVICE_FINAL_SIGKILL)
117dcc57
ZJS
1647 if (s->control_pid > 0) {
1648 r = unit_watch_pid(UNIT(s), s->control_pid);
1649 if (r < 0)
a16e1123 1650 return r;
117dcc57 1651 }
a16e1123 1652
bb242b7b
MO
1653 if (s->deserialized_state == SERVICE_START_POST ||
1654 s->deserialized_state == SERVICE_RUNNING)
1655 service_handle_watchdog(s);
1656
a16e1123
LP
1657 service_set_state(s, s->deserialized_state);
1658 }
92c1622e 1659
a16e1123
LP
1660 return 0;
1661}
1662
44d8db9e
LP
1663static int service_collect_fds(Service *s, int **fds, unsigned *n_fds) {
1664 Iterator i;
1665 int r;
1666 int *rfds = NULL;
1667 unsigned rn_fds = 0;
57020a3a 1668 Unit *u;
44d8db9e
LP
1669
1670 assert(s);
1671 assert(fds);
1672 assert(n_fds);
1673
6cf6bbc2
LP
1674 if (s->socket_fd >= 0)
1675 return 0;
1676
1124fe6f 1677 SET_FOREACH(u, UNIT(s)->dependencies[UNIT_TRIGGERED_BY], i) {
44d8db9e
LP
1678 int *cfds;
1679 unsigned cn_fds;
57020a3a
LP
1680 Socket *sock;
1681
ac155bb8 1682 if (u->type != UNIT_SOCKET)
57020a3a
LP
1683 continue;
1684
1685 sock = SOCKET(u);
44d8db9e 1686
117dcc57
ZJS
1687 r = socket_collect_fds(sock, &cfds, &cn_fds);
1688 if (r < 0)
44d8db9e
LP
1689 goto fail;
1690
1691 if (!cfds)
1692 continue;
1693
1694 if (!rfds) {
1695 rfds = cfds;
1696 rn_fds = cn_fds;
1697 } else {
1698 int *t;
1699
117dcc57
ZJS
1700 t = new(int, rn_fds+cn_fds);
1701 if (!t) {
44d8db9e
LP
1702 free(cfds);
1703 r = -ENOMEM;
1704 goto fail;
1705 }
1706
9c1b183c
LP
1707 memcpy(t, rfds, rn_fds * sizeof(int));
1708 memcpy(t+rn_fds, cfds, cn_fds * sizeof(int));
44d8db9e
LP
1709 free(rfds);
1710 free(cfds);
1711
1712 rfds = t;
1713 rn_fds = rn_fds+cn_fds;
1714 }
1715 }
1716
1717 *fds = rfds;
1718 *n_fds = rn_fds;
3e33402a 1719
44d8db9e
LP
1720 return 0;
1721
1722fail:
1723 free(rfds);
3e33402a 1724
44d8db9e
LP
1725 return r;
1726}
1727
81a2b7ce
LP
1728static int service_spawn(
1729 Service *s,
1730 ExecCommand *c,
1731 bool timeout,
1732 bool pass_fds,
1733 bool apply_permissions,
1734 bool apply_chroot,
1e3ad081 1735 bool apply_tty_stdin,
c952c6ec 1736 bool set_notify_socket,
ecedd90f 1737 bool is_control,
81a2b7ce
LP
1738 pid_t *_pid) {
1739
034c6ed7
LP
1740 pid_t pid;
1741 int r;
117dcc57 1742 int *fds = NULL;
7fd1b19b 1743 _cleanup_free_ int *fdsbuf = NULL;
2105e76a 1744 unsigned n_fds = 0, n_env = 0;
7fd1b19b 1745 _cleanup_strv_free_ char
117dcc57 1746 **argv = NULL, **final_env = NULL, **our_env = NULL;
4ad49000 1747 const char *path;
034c6ed7
LP
1748
1749 assert(s);
1750 assert(c);
1751 assert(_pid);
1752
4ad49000
LP
1753 unit_realize_cgroup(UNIT(s));
1754
613b411c
LP
1755 r = unit_setup_exec_runtime(UNIT(s));
1756 if (r < 0)
1757 goto fail;
1758
6cf6bbc2
LP
1759 if (pass_fds ||
1760 s->exec_context.std_input == EXEC_INPUT_SOCKET ||
1761 s->exec_context.std_output == EXEC_OUTPUT_SOCKET ||
1762 s->exec_context.std_error == EXEC_OUTPUT_SOCKET) {
1763
4f2d528d
LP
1764 if (s->socket_fd >= 0) {
1765 fds = &s->socket_fd;
1766 n_fds = 1;
6cf6bbc2 1767 } else {
117dcc57
ZJS
1768 r = service_collect_fds(s, &fdsbuf, &n_fds);
1769 if (r < 0)
6cf6bbc2
LP
1770 goto fail;
1771
1772 fds = fdsbuf;
1773 }
4f2d528d 1774 }
44d8db9e 1775
92c1622e
LP
1776 if (timeout && s->timeout_start_usec > 0) {
1777 r = service_arm_timer(s, s->timeout_start_usec);
1778 if (r < 0)
1779 goto fail;
1780 } else
1781 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
034c6ed7 1782
19f6d710
LP
1783 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1784 if (r < 0)
9e2f7c11 1785 goto fail;
9e2f7c11 1786
97ae63e2
LP
1787 our_env = new0(char*, 5);
1788 if (!our_env) {
2105e76a
LP
1789 r = -ENOMEM;
1790 goto fail;
1791 }
c952c6ec 1792
2105e76a 1793 if (set_notify_socket)
1124fe6f 1794 if (asprintf(our_env + n_env++, "NOTIFY_SOCKET=%s", UNIT(s)->manager->notify_socket) < 0) {
c952c6ec
LP
1795 r = -ENOMEM;
1796 goto fail;
1797 }
1798
2105e76a
LP
1799 if (s->main_pid > 0)
1800 if (asprintf(our_env + n_env++, "MAINPID=%lu", (unsigned long) s->main_pid) < 0) {
c952c6ec
LP
1801 r = -ENOMEM;
1802 goto fail;
1803 }
2105e76a 1804
6e0bcc98
MO
1805 if (s->watchdog_usec > 0)
1806 if (asprintf(our_env + n_env++, "WATCHDOG_USEC=%llu", (unsigned long long) s->watchdog_usec) < 0) {
1807 r = -ENOMEM;
1808 goto fail;
1809 }
1810
4ad49000 1811 if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
97ae63e2
LP
1812 if (asprintf(our_env + n_env++, "MANAGERPID=%lu", (unsigned long) getpid()) < 0) {
1813 r = -ENOMEM;
1814 goto fail;
1815 }
1816
1817 final_env = strv_env_merge(2, UNIT(s)->manager->environment, our_env, NULL);
1818 if (!final_env) {
2105e76a
LP
1819 r = -ENOMEM;
1820 goto fail;
1821 }
c952c6ec 1822
4ad49000
LP
1823 if (is_control && UNIT(s)->cgroup_path) {
1824 path = strappenda(UNIT(s)->cgroup_path, "/control");
1825 cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1826 } else
1827 path = UNIT(s)->cgroup_path;
1828
9e2f7c11
LP
1829 r = exec_spawn(c,
1830 argv,
1831 &s->exec_context,
1832 fds, n_fds,
2105e76a 1833 final_env,
9e2f7c11
LP
1834 apply_permissions,
1835 apply_chroot,
1e3ad081 1836 apply_tty_stdin,
1124fe6f 1837 UNIT(s)->manager->confirm_spawn,
13b84ec7 1838 UNIT(s)->manager->cgroup_supported,
4ad49000 1839 path,
62bca2c6 1840 UNIT(s)->id,
f2b68789 1841 s->type == SERVICE_IDLE ? UNIT(s)->manager->idle_pipe : NULL,
613b411c 1842 s->exec_runtime,
9e2f7c11 1843 &pid);
9e2f7c11 1844 if (r < 0)
034c6ed7
LP
1845 goto fail;
1846
117dcc57
ZJS
1847 r = unit_watch_pid(UNIT(s), pid);
1848 if (r < 0)
034c6ed7
LP
1849 /* FIXME: we need to do something here */
1850 goto fail;
1851
1852 *_pid = pid;
1853
5cb5a6ff 1854 return 0;
034c6ed7
LP
1855
1856fail:
1857 if (timeout)
718db961 1858 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
034c6ed7
LP
1859
1860 return r;
1861}
1862
80876c20
LP
1863static int main_pid_good(Service *s) {
1864 assert(s);
1865
1866 /* Returns 0 if the pid is dead, 1 if it is good, -1 if we
1867 * don't know */
1868
1869 /* If we know the pid file, then lets just check if it is
1870 * still valid */
6dfa5494
LP
1871 if (s->main_pid_known) {
1872
1873 /* If it's an alien child let's check if it is still
1874 * alive ... */
62220cf7 1875 if (s->main_pid_alien && s->main_pid > 0)
6dfa5494
LP
1876 return kill(s->main_pid, 0) >= 0 || errno != ESRCH;
1877
1878 /* .. otherwise assume we'll get a SIGCHLD for it,
1879 * which we really should wait for to collect exit
1880 * status and code */
80876c20 1881 return s->main_pid > 0;
6dfa5494 1882 }
80876c20
LP
1883
1884 /* We don't know the pid */
1885 return -EAGAIN;
1886}
1887
44a6b1b6 1888_pure_ static int control_pid_good(Service *s) {
80876c20
LP
1889 assert(s);
1890
1891 return s->control_pid > 0;
1892}
1893
1894static int cgroup_good(Service *s) {
1895 int r;
1896
1897 assert(s);
1898
4ad49000
LP
1899 if (!UNIT(s)->cgroup_path)
1900 return 0;
1901
1902 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, UNIT(s)->cgroup_path, true);
117dcc57 1903 if (r < 0)
80876c20
LP
1904 return r;
1905
1906 return !r;
1907}
1908
f42806df 1909static void service_enter_dead(Service *s, ServiceResult f, bool allow_restart) {
034c6ed7
LP
1910 int r;
1911 assert(s);
1912
f42806df
LP
1913 if (f != SERVICE_SUCCESS)
1914 s->result = f;
034c6ed7 1915
0c7f15b3
MS
1916 service_set_state(s, s->result != SERVICE_SUCCESS ? SERVICE_FAILED : SERVICE_DEAD);
1917
034c6ed7 1918 if (allow_restart &&
47342320 1919 !s->forbid_restart &&
034c6ed7 1920 (s->restart == SERVICE_RESTART_ALWAYS ||
f42806df
LP
1921 (s->restart == SERVICE_RESTART_ON_SUCCESS && s->result == SERVICE_SUCCESS) ||
1922 (s->restart == SERVICE_RESTART_ON_FAILURE && s->result != SERVICE_SUCCESS) ||
dc99a976 1923 (s->restart == SERVICE_RESTART_ON_WATCHDOG && s->result == SERVICE_FAILURE_WATCHDOG) ||
f42806df 1924 (s->restart == SERVICE_RESTART_ON_ABORT && (s->result == SERVICE_FAILURE_SIGNAL ||
96342de6
LN
1925 s->result == SERVICE_FAILURE_CORE_DUMP))) &&
1926 (s->result != SERVICE_FAILURE_EXIT_CODE ||
1927 !set_contains(s->restart_ignore_status.code, INT_TO_PTR(s->main_exec_status.status))) &&
1928 (s->result != SERVICE_FAILURE_SIGNAL ||
718db961 1929 !set_contains(s->restart_ignore_status.signal, INT_TO_PTR(s->main_exec_status.status)))) {
034c6ed7 1930
718db961 1931 r = service_arm_timer(s, s->restart_usec);
f42806df 1932 if (r < 0)
034c6ed7
LP
1933 goto fail;
1934
1935 service_set_state(s, SERVICE_AUTO_RESTART);
0c7f15b3 1936 }
034c6ed7 1937
47342320
LP
1938 s->forbid_restart = false;
1939
c17ec25e 1940 /* we want fresh tmpdirs in case service is started again immediately */
613b411c
LP
1941 exec_runtime_destroy(s->exec_runtime);
1942 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
c17ec25e 1943
9285c9ff
LN
1944 /* Try to delete the pid file. At this point it will be
1945 * out-of-date, and some software might be confused by it, so
1946 * let's remove it. */
1947 if (s->pid_file)
1948 unlink_noerrno(s->pid_file);
1949
034c6ed7
LP
1950 return;
1951
1952fail:
66870f90
ZJS
1953 log_warning_unit(UNIT(s)->id,
1954 "%s failed to run install restart timer: %s",
1955 UNIT(s)->id, strerror(-r));
f42806df 1956 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
1957}
1958
f42806df 1959static void service_enter_stop_post(Service *s, ServiceResult f) {
034c6ed7
LP
1960 int r;
1961 assert(s);
1962
f42806df
LP
1963 if (f != SERVICE_SUCCESS)
1964 s->result = f;
034c6ed7 1965
5e94833f
LP
1966 service_unwatch_control_pid(s);
1967
117dcc57
ZJS
1968 s->control_command = s->exec_command[SERVICE_EXEC_STOP_POST];
1969 if (s->control_command) {
867b3b7d
LP
1970 s->control_command_id = SERVICE_EXEC_STOP_POST;
1971
ecedd90f
LP
1972 r = service_spawn(s,
1973 s->control_command,
1974 true,
1975 false,
1976 !s->permissions_start_only,
1977 !s->root_directory_start_only,
1978 true,
1979 false,
1980 true,
1981 &s->control_pid);
1982 if (r < 0)
034c6ed7
LP
1983 goto fail;
1984
d6ea93e3 1985
80876c20
LP
1986 service_set_state(s, SERVICE_STOP_POST);
1987 } else
c961869a 1988 service_enter_dead(s, SERVICE_SUCCESS, true);
034c6ed7
LP
1989
1990 return;
1991
1992fail:
66870f90
ZJS
1993 log_warning_unit(UNIT(s)->id,
1994 "%s failed to run 'stop-post' task: %s",
1995 UNIT(s)->id, strerror(-r));
f42806df 1996 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
1997}
1998
f42806df 1999static void service_enter_signal(Service *s, ServiceState state, ServiceResult f) {
034c6ed7 2000 int r;
034c6ed7
LP
2001
2002 assert(s);
2003
f42806df
LP
2004 if (f != SERVICE_SUCCESS)
2005 s->result = f;
034c6ed7 2006
cd2086fe
LP
2007 r = unit_kill_context(
2008 UNIT(s),
2009 &s->kill_context,
2010 state != SERVICE_STOP_SIGTERM && state != SERVICE_FINAL_SIGTERM,
2011 s->main_pid,
2012 s->control_pid,
2013 s->main_pid_alien);
2014 if (r < 0)
2015 goto fail;
034c6ed7 2016
cd2086fe 2017 if (r > 0) {
d568a335 2018 if (s->timeout_stop_usec > 0) {
718db961 2019 r = service_arm_timer(s, s->timeout_stop_usec);
d568a335 2020 if (r < 0)
e558336f 2021 goto fail;
d568a335 2022 }
d6ea93e3 2023
80876c20
LP
2024 service_set_state(s, state);
2025 } else if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
f42806df 2026 service_enter_stop_post(s, SERVICE_SUCCESS);
80876c20 2027 else
f42806df 2028 service_enter_dead(s, SERVICE_SUCCESS, true);
034c6ed7
LP
2029
2030 return;
2031
2032fail:
66870f90
ZJS
2033 log_warning_unit(UNIT(s)->id,
2034 "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
034c6ed7 2035
80876c20 2036 if (state == SERVICE_STOP_SIGTERM || state == SERVICE_STOP_SIGKILL)
f42806df 2037 service_enter_stop_post(s, SERVICE_FAILURE_RESOURCES);
034c6ed7 2038 else
f42806df 2039 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
2040}
2041
f42806df 2042static void service_enter_stop(Service *s, ServiceResult f) {
034c6ed7 2043 int r;
5925dd3c 2044
034c6ed7
LP
2045 assert(s);
2046
f42806df
LP
2047 if (f != SERVICE_SUCCESS)
2048 s->result = f;
034c6ed7 2049
5e94833f
LP
2050 service_unwatch_control_pid(s);
2051
117dcc57
ZJS
2052 s->control_command = s->exec_command[SERVICE_EXEC_STOP];
2053 if (s->control_command) {
867b3b7d
LP
2054 s->control_command_id = SERVICE_EXEC_STOP;
2055
ecedd90f
LP
2056 r = service_spawn(s,
2057 s->control_command,
2058 true,
2059 false,
2060 !s->permissions_start_only,
2061 !s->root_directory_start_only,
2062 false,
2063 false,
2064 true,
2065 &s->control_pid);
2066 if (r < 0)
034c6ed7
LP
2067 goto fail;
2068
80876c20
LP
2069 service_set_state(s, SERVICE_STOP);
2070 } else
f42806df 2071 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
034c6ed7
LP
2072
2073 return;
2074
2075fail:
66870f90
ZJS
2076 log_warning_unit(UNIT(s)->id,
2077 "%s failed to run 'stop' task: %s", UNIT(s)->id, strerror(-r));
f42806df 2078 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2079}
2080
f42806df 2081static void service_enter_running(Service *s, ServiceResult f) {
4eab639f 2082 int main_pid_ok, cgroup_ok;
80876c20
LP
2083 assert(s);
2084
f42806df
LP
2085 if (f != SERVICE_SUCCESS)
2086 s->result = f;
80876c20 2087
4eab639f
LP
2088 main_pid_ok = main_pid_good(s);
2089 cgroup_ok = cgroup_good(s);
2090
2091 if ((main_pid_ok > 0 || (main_pid_ok < 0 && cgroup_ok != 0)) &&
05e343b7 2092 (s->bus_name_good || s->type != SERVICE_DBUS))
80876c20 2093 service_set_state(s, SERVICE_RUNNING);
02ee865a 2094 else if (s->remain_after_exit)
80876c20
LP
2095 service_set_state(s, SERVICE_EXITED);
2096 else
f42806df 2097 service_enter_stop(s, SERVICE_SUCCESS);
80876c20
LP
2098}
2099
034c6ed7
LP
2100static void service_enter_start_post(Service *s) {
2101 int r;
2102 assert(s);
2103
5e94833f
LP
2104 service_unwatch_control_pid(s);
2105
bb242b7b
MO
2106 if (s->watchdog_usec > 0)
2107 service_reset_watchdog(s);
2108
117dcc57
ZJS
2109 s->control_command = s->exec_command[SERVICE_EXEC_START_POST];
2110 if (s->control_command) {
867b3b7d
LP
2111 s->control_command_id = SERVICE_EXEC_START_POST;
2112
ecedd90f
LP
2113 r = service_spawn(s,
2114 s->control_command,
2115 true,
2116 false,
2117 !s->permissions_start_only,
2118 !s->root_directory_start_only,
2119 false,
2120 false,
2121 true,
2122 &s->control_pid);
2123 if (r < 0)
034c6ed7
LP
2124 goto fail;
2125
80876c20
LP
2126 service_set_state(s, SERVICE_START_POST);
2127 } else
f42806df 2128 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2129
2130 return;
2131
2132fail:
66870f90
ZJS
2133 log_warning_unit(UNIT(s)->id,
2134 "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
f42806df 2135 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2136}
2137
4ad49000
LP
2138static void service_kill_control_processes(Service *s) {
2139 char *p;
2140
2141 if (!UNIT(s)->cgroup_path)
2142 return;
2143
2144 p = strappenda(UNIT(s)->cgroup_path, "/control");
4ad49000
LP
2145 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, p, SIGKILL, true, true, true, NULL);
2146}
2147
034c6ed7 2148static void service_enter_start(Service *s) {
4ad49000 2149 ExecCommand *c;
034c6ed7
LP
2150 pid_t pid;
2151 int r;
2152
2153 assert(s);
2154
2155 assert(s->exec_command[SERVICE_EXEC_START]);
34e9ba66 2156 assert(!s->exec_command[SERVICE_EXEC_START]->command_next || s->type == SERVICE_ONESHOT);
034c6ed7 2157
41efeaec
LP
2158 service_unwatch_control_pid(s);
2159 service_unwatch_main_pid(s);
80876c20 2160
8f53a7b8
LP
2161 /* We want to ensure that nobody leaks processes from
2162 * START_PRE here, so let's go on a killing spree, People
2163 * should not spawn long running processes from START_PRE. */
4ad49000 2164 service_kill_control_processes(s);
8f53a7b8 2165
867b3b7d
LP
2166 if (s->type == SERVICE_FORKING) {
2167 s->control_command_id = SERVICE_EXEC_START;
2168 c = s->control_command = s->exec_command[SERVICE_EXEC_START];
2169
2170 s->main_command = NULL;
2171 } else {
2172 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
2173 s->control_command = NULL;
2174
2175 c = s->main_command = s->exec_command[SERVICE_EXEC_START];
2176 }
34e9ba66 2177
ecedd90f
LP
2178 r = service_spawn(s,
2179 c,
117dcc57
ZJS
2180 s->type == SERVICE_FORKING || s->type == SERVICE_DBUS ||
2181 s->type == SERVICE_NOTIFY || s->type == SERVICE_ONESHOT,
ecedd90f
LP
2182 true,
2183 true,
2184 true,
2185 true,
2186 s->notify_access != NOTIFY_NONE,
2187 false,
2188 &pid);
2189 if (r < 0)
034c6ed7
LP
2190 goto fail;
2191
f2b68789 2192 if (s->type == SERVICE_SIMPLE || s->type == SERVICE_IDLE) {
034c6ed7
LP
2193 /* For simple services we immediately start
2194 * the START_POST binaries. */
2195
5925dd3c 2196 service_set_main_pid(s, pid);
034c6ed7
LP
2197 service_enter_start_post(s);
2198
2199 } else if (s->type == SERVICE_FORKING) {
2200
2201 /* For forking services we wait until the start
2202 * process exited. */
2203
e55224ca 2204 s->control_pid = pid;
80876c20
LP
2205 service_set_state(s, SERVICE_START);
2206
34e9ba66 2207 } else if (s->type == SERVICE_ONESHOT ||
8c47c732
LP
2208 s->type == SERVICE_DBUS ||
2209 s->type == SERVICE_NOTIFY) {
7d55e835 2210
34e9ba66 2211 /* For oneshot services we wait until the start
7d55e835
LP
2212 * process exited, too, but it is our main process. */
2213
05e343b7 2214 /* For D-Bus services we know the main pid right away,
8c47c732
LP
2215 * but wait for the bus name to appear on the
2216 * bus. Notify services are similar. */
05e343b7 2217
5925dd3c 2218 service_set_main_pid(s, pid);
80876c20 2219 service_set_state(s, SERVICE_START);
034c6ed7
LP
2220 } else
2221 assert_not_reached("Unknown service type");
2222
2223 return;
2224
2225fail:
66870f90
ZJS
2226 log_warning_unit(UNIT(s)->id,
2227 "%s failed to run 'start' task: %s", UNIT(s)->id, strerror(-r));
f42806df 2228 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7
LP
2229}
2230
2231static void service_enter_start_pre(Service *s) {
2232 int r;
2233
2234 assert(s);
2235
5e94833f
LP
2236 service_unwatch_control_pid(s);
2237
117dcc57
ZJS
2238 s->control_command = s->exec_command[SERVICE_EXEC_START_PRE];
2239 if (s->control_command) {
8f53a7b8
LP
2240 /* Before we start anything, let's clear up what might
2241 * be left from previous runs. */
4ad49000 2242 service_kill_control_processes(s);
8f53a7b8 2243
867b3b7d
LP
2244 s->control_command_id = SERVICE_EXEC_START_PRE;
2245
ecedd90f
LP
2246 r = service_spawn(s,
2247 s->control_command,
2248 true,
2249 false,
2250 !s->permissions_start_only,
2251 !s->root_directory_start_only,
2252 true,
2253 false,
2254 true,
2255 &s->control_pid);
2256 if (r < 0)
034c6ed7
LP
2257 goto fail;
2258
80876c20
LP
2259 service_set_state(s, SERVICE_START_PRE);
2260 } else
034c6ed7
LP
2261 service_enter_start(s);
2262
2263 return;
2264
2265fail:
66870f90
ZJS
2266 log_warning_unit(UNIT(s)->id,
2267 "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
f42806df 2268 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
034c6ed7
LP
2269}
2270
2271static void service_enter_restart(Service *s) {
718db961 2272 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
034c6ed7 2273 int r;
398ef8ba 2274
034c6ed7
LP
2275 assert(s);
2276
a8bb2e65
LP
2277 if (UNIT(s)->job && UNIT(s)->job->type == JOB_STOP) {
2278 /* Don't restart things if we are going down anyway */
66870f90
ZJS
2279 log_info_unit(UNIT(s)->id,
2280 "Stop job pending for unit, delaying automatic restart.");
2edfa366 2281
718db961 2282 r = service_arm_timer(s, s->restart_usec);
a8bb2e65 2283 if (r < 0)
2edfa366 2284 goto fail;
feae8adb
DW
2285
2286 return;
2edfa366
LP
2287 }
2288
48bb5876
DW
2289 /* Any units that are bound to this service must also be
2290 * restarted. We use JOB_RESTART (instead of the more obvious
2291 * JOB_START) here so that those dependency jobs will be added
2292 * as well. */
2293 r = manager_add_job(UNIT(s)->manager, JOB_RESTART, UNIT(s), JOB_FAIL, false, &error, NULL);
2294 if (r < 0)
034c6ed7
LP
2295 goto fail;
2296
a8bb2e65
LP
2297 /* Note that we stay in the SERVICE_AUTO_RESTART state here,
2298 * it will be canceled as part of the service_stop() call that
2299 * is executed as part of JOB_RESTART. */
2300
66870f90
ZJS
2301 log_debug_unit(UNIT(s)->id,
2302 "%s scheduled restart job.", UNIT(s)->id);
034c6ed7
LP
2303 return;
2304
2305fail:
66870f90
ZJS
2306 log_warning_unit(UNIT(s)->id,
2307 "%s failed to schedule restart job: %s",
718db961 2308 UNIT(s)->id, bus_error_message(&error, -r));
f42806df 2309 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, false);
034c6ed7
LP
2310}
2311
2312static void service_enter_reload(Service *s) {
2313 int r;
2314
2315 assert(s);
2316
5e94833f
LP
2317 service_unwatch_control_pid(s);
2318
117dcc57
ZJS
2319 s->control_command = s->exec_command[SERVICE_EXEC_RELOAD];
2320 if (s->control_command) {
867b3b7d
LP
2321 s->control_command_id = SERVICE_EXEC_RELOAD;
2322
ecedd90f
LP
2323 r = service_spawn(s,
2324 s->control_command,
2325 true,
2326 false,
2327 !s->permissions_start_only,
2328 !s->root_directory_start_only,
2329 false,
2330 false,
2331 true,
2332 &s->control_pid);
2333 if (r < 0)
034c6ed7
LP
2334 goto fail;
2335
80876c20
LP
2336 service_set_state(s, SERVICE_RELOAD);
2337 } else
f42806df 2338 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2339
2340 return;
2341
2342fail:
66870f90
ZJS
2343 log_warning_unit(UNIT(s)->id,
2344 "%s failed to run 'reload' task: %s",
2345 UNIT(s)->id, strerror(-r));
f42806df
LP
2346 s->reload_result = SERVICE_FAILURE_RESOURCES;
2347 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
2348}
2349
f42806df 2350static void service_run_next_control(Service *s) {
034c6ed7
LP
2351 int r;
2352
2353 assert(s);
2354 assert(s->control_command);
2355 assert(s->control_command->command_next);
2356
34e9ba66 2357 assert(s->control_command_id != SERVICE_EXEC_START);
034c6ed7 2358
34e9ba66 2359 s->control_command = s->control_command->command_next;
5e94833f
LP
2360 service_unwatch_control_pid(s);
2361
ecedd90f
LP
2362 r = service_spawn(s,
2363 s->control_command,
2364 true,
2365 false,
2366 !s->permissions_start_only,
2367 !s->root_directory_start_only,
2368 s->control_command_id == SERVICE_EXEC_START_PRE ||
2369 s->control_command_id == SERVICE_EXEC_STOP_POST,
2370 false,
2371 true,
2372 &s->control_pid);
2373 if (r < 0)
034c6ed7
LP
2374 goto fail;
2375
2376 return;
2377
2378fail:
66870f90
ZJS
2379 log_warning_unit(UNIT(s)->id,
2380 "%s failed to run next control task: %s",
2381 UNIT(s)->id, strerror(-r));
034c6ed7 2382
80876c20 2383 if (s->state == SERVICE_START_PRE)
f42806df 2384 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
80876c20 2385 else if (s->state == SERVICE_STOP)
f42806df 2386 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
034c6ed7 2387 else if (s->state == SERVICE_STOP_POST)
f42806df 2388 service_enter_dead(s, SERVICE_FAILURE_RESOURCES, true);
e2f3b44c 2389 else if (s->state == SERVICE_RELOAD) {
f42806df
LP
2390 s->reload_result = SERVICE_FAILURE_RESOURCES;
2391 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c 2392 } else
f42806df 2393 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
5cb5a6ff
LP
2394}
2395
f42806df 2396static void service_run_next_main(Service *s) {
34e9ba66
LP
2397 pid_t pid;
2398 int r;
2399
2400 assert(s);
867b3b7d
LP
2401 assert(s->main_command);
2402 assert(s->main_command->command_next);
2403 assert(s->type == SERVICE_ONESHOT);
34e9ba66 2404
867b3b7d 2405 s->main_command = s->main_command->command_next;
34e9ba66
LP
2406 service_unwatch_main_pid(s);
2407
ecedd90f
LP
2408 r = service_spawn(s,
2409 s->main_command,
98709151 2410 true,
ecedd90f
LP
2411 true,
2412 true,
2413 true,
2414 true,
2415 s->notify_access != NOTIFY_NONE,
2416 false,
2417 &pid);
2418 if (r < 0)
34e9ba66
LP
2419 goto fail;
2420
2421 service_set_main_pid(s, pid);
2422
2423 return;
2424
2425fail:
66870f90
ZJS
2426 log_warning_unit(UNIT(s)->id,
2427 "%s failed to run next main task: %s", UNIT(s)->id, strerror(-r));
f42806df 2428 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
34e9ba66
LP
2429}
2430
4b939747
MO
2431static int service_start_limit_test(Service *s) {
2432 assert(s);
2433
2434 if (ratelimit_test(&s->start_limit))
2435 return 0;
2436
2437 switch (s->start_limit_action) {
2438
2439 case SERVICE_START_LIMIT_NONE:
66870f90
ZJS
2440 log_warning_unit(UNIT(s)->id,
2441 "%s start request repeated too quickly, refusing to start.",
2442 UNIT(s)->id);
4b939747
MO
2443 break;
2444
2445 case SERVICE_START_LIMIT_REBOOT: {
718db961 2446 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
4b939747
MO
2447 int r;
2448
66870f90
ZJS
2449 log_warning_unit(UNIT(s)->id,
2450 "%s start request repeated too quickly, rebooting.", UNIT(s)->id);
4b939747 2451
117dcc57
ZJS
2452 r = manager_add_job_by_name(UNIT(s)->manager, JOB_START,
2453 SPECIAL_REBOOT_TARGET, JOB_REPLACE,
2454 true, &error, NULL);
718db961 2455 if (r < 0)
66870f90 2456 log_error_unit(UNIT(s)->id,
718db961 2457 "Failed to reboot: %s.", bus_error_message(&error, r));
4b939747
MO
2458
2459 break;
2460 }
2461
2462 case SERVICE_START_LIMIT_REBOOT_FORCE:
66870f90
ZJS
2463 log_warning_unit(UNIT(s)->id,
2464 "%s start request repeated too quickly, forcibly rebooting.", UNIT(s)->id);
4b939747
MO
2465 UNIT(s)->manager->exit_code = MANAGER_REBOOT;
2466 break;
2467
2468 case SERVICE_START_LIMIT_REBOOT_IMMEDIATE:
66870f90
ZJS
2469 log_warning_unit(UNIT(s)->id,
2470 "%s start request repeated too quickly, rebooting immediately.", UNIT(s)->id);
0049f05a 2471 sync();
4b939747
MO
2472 reboot(RB_AUTOBOOT);
2473 break;
2474
2475 default:
66870f90
ZJS
2476 log_error_unit(UNIT(s)->id,
2477 "start limit action=%i", s->start_limit_action);
4b939747
MO
2478 assert_not_reached("Unknown StartLimitAction.");
2479 }
2480
2481 return -ECANCELED;
2482}
2483
87f0e418
LP
2484static int service_start(Unit *u) {
2485 Service *s = SERVICE(u);
4b939747 2486 int r;
5cb5a6ff
LP
2487
2488 assert(s);
2489
034c6ed7
LP
2490 /* We cannot fulfill this request right now, try again later
2491 * please! */
2492 if (s->state == SERVICE_STOP ||
2493 s->state == SERVICE_STOP_SIGTERM ||
2494 s->state == SERVICE_STOP_SIGKILL ||
2495 s->state == SERVICE_STOP_POST ||
2496 s->state == SERVICE_FINAL_SIGTERM ||
2497 s->state == SERVICE_FINAL_SIGKILL)
5cb5a6ff
LP
2498 return -EAGAIN;
2499
034c6ed7
LP
2500 /* Already on it! */
2501 if (s->state == SERVICE_START_PRE ||
2502 s->state == SERVICE_START ||
2503 s->state == SERVICE_START_POST)
2504 return 0;
2505
2e9d6c12 2506 /* A service that will be restarted must be stopped first to
7f2cddae 2507 * trigger BindsTo and/or OnFailure dependencies. If a user
2e9d6c12 2508 * does not want to wait for the holdoff time to elapse, the
d4943dc7
LP
2509 * service should be manually restarted, not started. We
2510 * simply return EAGAIN here, so that any start jobs stay
2511 * queued, and assume that the auto restart timer will
2512 * eventually trigger the restart. */
2513 if (s->state == SERVICE_AUTO_RESTART)
a8bb2e65 2514 return -EAGAIN;
2e9d6c12
DW
2515
2516 assert(s->state == SERVICE_DEAD || s->state == SERVICE_FAILED);
5cb5a6ff 2517
1e2e8133 2518 /* Make sure we don't enter a busy loop of some kind. */
4b939747 2519 r = service_start_limit_test(s);
c2f34808 2520 if (r < 0) {
8d1b002a 2521 service_enter_dead(s, SERVICE_FAILURE_START_LIMIT, false);
4b939747 2522 return r;
c2f34808 2523 }
1e2e8133 2524
f42806df
LP
2525 s->result = SERVICE_SUCCESS;
2526 s->reload_result = SERVICE_SUCCESS;
034c6ed7 2527 s->main_pid_known = false;
6dfa5494 2528 s->main_pid_alien = false;
47342320 2529 s->forbid_restart = false;
034c6ed7
LP
2530
2531 service_enter_start_pre(s);
2532 return 0;
5cb5a6ff
LP
2533}
2534
87f0e418
LP
2535static int service_stop(Unit *u) {
2536 Service *s = SERVICE(u);
5cb5a6ff
LP
2537
2538 assert(s);
2539
f0c7b229 2540 /* Don't create restart jobs from here. */
47342320 2541 s->forbid_restart = true;
034c6ed7 2542
e537352b
LP
2543 /* Already on it */
2544 if (s->state == SERVICE_STOP ||
2545 s->state == SERVICE_STOP_SIGTERM ||
2546 s->state == SERVICE_STOP_SIGKILL ||
2547 s->state == SERVICE_STOP_POST ||
2548 s->state == SERVICE_FINAL_SIGTERM ||
2549 s->state == SERVICE_FINAL_SIGKILL)
2550 return 0;
2551
f0c7b229 2552 /* A restart will be scheduled or is in progress. */
034c6ed7 2553 if (s->state == SERVICE_AUTO_RESTART) {
0c7f15b3 2554 service_set_state(s, SERVICE_DEAD);
034c6ed7
LP
2555 return 0;
2556 }
2557
3f6c78dc
LP
2558 /* If there's already something running we go directly into
2559 * kill mode. */
2560 if (s->state == SERVICE_START_PRE ||
2561 s->state == SERVICE_START ||
2562 s->state == SERVICE_START_POST ||
2563 s->state == SERVICE_RELOAD) {
f42806df 2564 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_SUCCESS);
3f6c78dc
LP
2565 return 0;
2566 }
5cb5a6ff 2567
3f6c78dc
LP
2568 assert(s->state == SERVICE_RUNNING ||
2569 s->state == SERVICE_EXITED);
3a762661 2570
f42806df 2571 service_enter_stop(s, SERVICE_SUCCESS);
5cb5a6ff
LP
2572 return 0;
2573}
2574
87f0e418
LP
2575static int service_reload(Unit *u) {
2576 Service *s = SERVICE(u);
034c6ed7
LP
2577
2578 assert(s);
2579
80876c20 2580 assert(s->state == SERVICE_RUNNING || s->state == SERVICE_EXITED);
034c6ed7
LP
2581
2582 service_enter_reload(s);
5cb5a6ff
LP
2583 return 0;
2584}
2585
44a6b1b6 2586_pure_ static bool service_can_reload(Unit *u) {
87f0e418 2587 Service *s = SERVICE(u);
034c6ed7
LP
2588
2589 assert(s);
2590
2591 return !!s->exec_command[SERVICE_EXEC_RELOAD];
2592}
2593
a16e1123
LP
2594static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
2595 Service *s = SERVICE(u);
2596
2597 assert(u);
2598 assert(f);
2599 assert(fds);
2600
2601 unit_serialize_item(u, f, "state", service_state_to_string(s->state));
f42806df
LP
2602 unit_serialize_item(u, f, "result", service_result_to_string(s->result));
2603 unit_serialize_item(u, f, "reload-result", service_result_to_string(s->reload_result));
a16e1123
LP
2604
2605 if (s->control_pid > 0)
117dcc57
ZJS
2606 unit_serialize_item_format(u, f, "control-pid", "%lu",
2607 (unsigned long) s->control_pid);
a16e1123 2608
5925dd3c
LP
2609 if (s->main_pid_known && s->main_pid > 0)
2610 unit_serialize_item_format(u, f, "main-pid", "%lu", (unsigned long) s->main_pid);
a16e1123
LP
2611
2612 unit_serialize_item(u, f, "main-pid-known", yes_no(s->main_pid_known));
2613
3a2776bc
LP
2614 if (s->status_text)
2615 unit_serialize_item(u, f, "status-text", s->status_text);
2616
cfc4eb4c
LP
2617 /* FIXME: There's a minor uncleanliness here: if there are
2618 * multiple commands attached here, we will start from the
2619 * first one again */
a16e1123 2620 if (s->control_command_id >= 0)
117dcc57
ZJS
2621 unit_serialize_item(u, f, "control-command",
2622 service_exec_command_to_string(s->control_command_id));
a16e1123
LP
2623
2624 if (s->socket_fd >= 0) {
2625 int copy;
2626
2627 if ((copy = fdset_put_dup(fds, s->socket_fd)) < 0)
2628 return copy;
2629
2630 unit_serialize_item_format(u, f, "socket-fd", "%i", copy);
2631 }
2632
ecdbca40 2633 if (s->main_exec_status.pid > 0) {
117dcc57
ZJS
2634 unit_serialize_item_format(u, f, "main-exec-status-pid", "%lu",
2635 (unsigned long) s->main_exec_status.pid);
2636 dual_timestamp_serialize(f, "main-exec-status-start",
2637 &s->main_exec_status.start_timestamp);
2638 dual_timestamp_serialize(f, "main-exec-status-exit",
2639 &s->main_exec_status.exit_timestamp);
ecdbca40 2640
799fd0fd 2641 if (dual_timestamp_is_set(&s->main_exec_status.exit_timestamp)) {
117dcc57
ZJS
2642 unit_serialize_item_format(u, f, "main-exec-status-code", "%i",
2643 s->main_exec_status.code);
2644 unit_serialize_item_format(u, f, "main-exec-status-status", "%i",
2645 s->main_exec_status.status);
ecdbca40
LP
2646 }
2647 }
a6927d7f 2648 if (dual_timestamp_is_set(&s->watchdog_timestamp))
117dcc57
ZJS
2649 dual_timestamp_serialize(f, "watchdog-timestamp",
2650 &s->watchdog_timestamp);
ecdbca40 2651
6aca9a58 2652 if (s->forbid_restart)
8d1a2802 2653 unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
6aca9a58 2654
a16e1123
LP
2655 return 0;
2656}
2657
2658static int service_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2659 Service *s = SERVICE(u);
a16e1123
LP
2660
2661 assert(u);
2662 assert(key);
2663 assert(value);
2664 assert(fds);
2665
2666 if (streq(key, "state")) {
2667 ServiceState state;
2668
117dcc57
ZJS
2669 state = service_state_from_string(value);
2670 if (state < 0)
66870f90 2671 log_debug_unit(u->id, "Failed to parse state value %s", value);
a16e1123
LP
2672 else
2673 s->deserialized_state = state;
f42806df
LP
2674 } else if (streq(key, "result")) {
2675 ServiceResult f;
2676
2677 f = service_result_from_string(value);
2678 if (f < 0)
66870f90 2679 log_debug_unit(u->id, "Failed to parse result value %s", value);
f42806df
LP
2680 else if (f != SERVICE_SUCCESS)
2681 s->result = f;
2682
2683 } else if (streq(key, "reload-result")) {
2684 ServiceResult f;
2685
2686 f = service_result_from_string(value);
2687 if (f < 0)
66870f90 2688 log_debug_unit(u->id, "Failed to parse reload result value %s", value);
f42806df
LP
2689 else if (f != SERVICE_SUCCESS)
2690 s->reload_result = f;
a16e1123 2691
a16e1123 2692 } else if (streq(key, "control-pid")) {
5925dd3c 2693 pid_t pid;
a16e1123 2694
e364ad06 2695 if (parse_pid(value, &pid) < 0)
66870f90 2696 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
a16e1123 2697 else
e55224ca 2698 s->control_pid = pid;
a16e1123 2699 } else if (streq(key, "main-pid")) {
5925dd3c 2700 pid_t pid;
a16e1123 2701
e364ad06 2702 if (parse_pid(value, &pid) < 0)
66870f90 2703 log_debug_unit(u->id, "Failed to parse main-pid value %s", value);
7400b9d2
LP
2704 else {
2705 service_set_main_pid(s, pid);
2706 unit_watch_pid(UNIT(s), pid);
2707 }
a16e1123
LP
2708 } else if (streq(key, "main-pid-known")) {
2709 int b;
2710
117dcc57
ZJS
2711 b = parse_boolean(value);
2712 if (b < 0)
66870f90 2713 log_debug_unit(u->id, "Failed to parse main-pid-known value %s", value);
a16e1123
LP
2714 else
2715 s->main_pid_known = b;
3a2776bc
LP
2716 } else if (streq(key, "status-text")) {
2717 char *t;
2718
117dcc57
ZJS
2719 t = strdup(value);
2720 if (!t)
2721 log_oom();
2722 else {
3a2776bc
LP
2723 free(s->status_text);
2724 s->status_text = t;
2725 }
2726
a16e1123
LP
2727 } else if (streq(key, "control-command")) {
2728 ServiceExecCommand id;
2729
117dcc57
ZJS
2730 id = service_exec_command_from_string(value);
2731 if (id < 0)
66870f90 2732 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
a16e1123
LP
2733 else {
2734 s->control_command_id = id;
2735 s->control_command = s->exec_command[id];
2736 }
2737 } else if (streq(key, "socket-fd")) {
2738 int fd;
2739
2740 if (safe_atoi(value, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
66870f90 2741 log_debug_unit(u->id, "Failed to parse socket-fd value %s", value);
a16e1123
LP
2742 else {
2743
2744 if (s->socket_fd >= 0)
2745 close_nointr_nofail(s->socket_fd);
2746 s->socket_fd = fdset_remove(fds, fd);
2747 }
ecdbca40
LP
2748 } else if (streq(key, "main-exec-status-pid")) {
2749 pid_t pid;
2750
e364ad06 2751 if (parse_pid(value, &pid) < 0)
66870f90 2752 log_debug_unit(u->id, "Failed to parse main-exec-status-pid value %s", value);
ecdbca40
LP
2753 else
2754 s->main_exec_status.pid = pid;
2755 } else if (streq(key, "main-exec-status-code")) {
2756 int i;
2757
e364ad06 2758 if (safe_atoi(value, &i) < 0)
66870f90 2759 log_debug_unit(u->id, "Failed to parse main-exec-status-code value %s", value);
ecdbca40
LP
2760 else
2761 s->main_exec_status.code = i;
2762 } else if (streq(key, "main-exec-status-status")) {
2763 int i;
2764
e364ad06 2765 if (safe_atoi(value, &i) < 0)
66870f90 2766 log_debug_unit(u->id, "Failed to parse main-exec-status-status value %s", value);
ecdbca40
LP
2767 else
2768 s->main_exec_status.status = i;
799fd0fd
LP
2769 } else if (streq(key, "main-exec-status-start"))
2770 dual_timestamp_deserialize(value, &s->main_exec_status.start_timestamp);
2771 else if (streq(key, "main-exec-status-exit"))
2772 dual_timestamp_deserialize(value, &s->main_exec_status.exit_timestamp);
a6927d7f
MO
2773 else if (streq(key, "watchdog-timestamp"))
2774 dual_timestamp_deserialize(value, &s->watchdog_timestamp);
613b411c 2775 else if (streq(key, "forbid-restart")) {
6aca9a58
SE
2776 int b;
2777
2778 b = parse_boolean(value);
2779 if (b < 0)
8d1a2802 2780 log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
6aca9a58
SE
2781 else
2782 s->forbid_restart = b;
c17ec25e 2783 } else
66870f90 2784 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
a16e1123
LP
2785
2786 return 0;
2787}
2788
44a6b1b6 2789_pure_ static UnitActiveState service_active_state(Unit *u) {
e056b01d
LP
2790 const UnitActiveState *table;
2791
87f0e418 2792 assert(u);
5cb5a6ff 2793
e056b01d
LP
2794 table = SERVICE(u)->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
2795
2796 return table[SERVICE(u)->state];
034c6ed7
LP
2797}
2798
10a94420
LP
2799static const char *service_sub_state_to_string(Unit *u) {
2800 assert(u);
2801
2802 return service_state_to_string(SERVICE(u)->state);
2803}
2804
701cc384
LP
2805static bool service_check_gc(Unit *u) {
2806 Service *s = SERVICE(u);
2807
2808 assert(s);
2809
6d55002a
LP
2810 /* Never clean up services that still have a process around,
2811 * even if the service is formally dead. */
2812 if (cgroup_good(s) > 0 ||
2813 main_pid_good(s) > 0 ||
2814 control_pid_good(s) > 0)
2815 return true;
2816
2817#ifdef HAVE_SYSV_COMPAT
1b64d026 2818 if (s->is_sysv)
6d55002a 2819 return true;
07459bb6 2820#endif
701cc384 2821
6d55002a
LP
2822 return false;
2823}
2824
44a6b1b6 2825_pure_ static bool service_check_snapshot(Unit *u) {
701cc384
LP
2826 Service *s = SERVICE(u);
2827
2828 assert(s);
2829
99f37ad8 2830 return (s->socket_fd < 0);
701cc384
LP
2831}
2832
3a111838
MS
2833static int service_retry_pid_file(Service *s) {
2834 int r;
2835
2836 assert(s->pid_file);
2837 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2838
2839 r = service_load_pid_file(s, false);
2840 if (r < 0)
2841 return r;
2842
2843 service_unwatch_pid_file(s);
2844
f42806df 2845 service_enter_running(s, SERVICE_SUCCESS);
3a111838
MS
2846 return 0;
2847}
2848
2849static int service_watch_pid_file(Service *s) {
2850 int r;
2851
66870f90
ZJS
2852 log_debug_unit(UNIT(s)->id,
2853 "Setting watch for %s's PID file %s",
2854 UNIT(s)->id, s->pid_file_pathspec->path);
718db961 2855 r = path_spec_watch(s->pid_file_pathspec, service_dispatch_io);
3a111838
MS
2856 if (r < 0)
2857 goto fail;
2858
2859 /* the pidfile might have appeared just before we set the watch */
bc41f93e
ZJS
2860 log_debug_unit(UNIT(s)->id,
2861 "Trying to read %s's PID file %s in case it changed",
2862 UNIT(s)->id, s->pid_file_pathspec->path);
3a111838
MS
2863 service_retry_pid_file(s);
2864
2865 return 0;
2866fail:
66870f90
ZJS
2867 log_error_unit(UNIT(s)->id,
2868 "Failed to set a watch for %s's PID file %s: %s",
2869 UNIT(s)->id, s->pid_file_pathspec->path, strerror(-r));
3a111838
MS
2870 service_unwatch_pid_file(s);
2871 return r;
2872}
2873
2874static int service_demand_pid_file(Service *s) {
2875 PathSpec *ps;
2876
2877 assert(s->pid_file);
2878 assert(!s->pid_file_pathspec);
2879
2880 ps = new0(PathSpec, 1);
2881 if (!ps)
2882 return -ENOMEM;
2883
718db961 2884 ps->unit = UNIT(s);
3a111838
MS
2885 ps->path = strdup(s->pid_file);
2886 if (!ps->path) {
2887 free(ps);
2888 return -ENOMEM;
2889 }
2890
2891 path_kill_slashes(ps->path);
2892
2893 /* PATH_CHANGED would not be enough. There are daemons (sendmail) that
2894 * keep their PID file open all the time. */
2895 ps->type = PATH_MODIFIED;
2896 ps->inotify_fd = -1;
2897
2898 s->pid_file_pathspec = ps;
2899
2900 return service_watch_pid_file(s);
2901}
2902
718db961 2903static int service_dispatch_io(sd_event_source *source, int fd, uint32_t events, void *userdata) {
e14c2802
LP
2904 PathSpec *p = userdata;
2905 Service *s;
2906
2907 assert(p);
2908
2909 s = SERVICE(p->unit);
3a111838
MS
2910
2911 assert(s);
2912 assert(fd >= 0);
2913 assert(s->state == SERVICE_START || s->state == SERVICE_START_POST);
2914 assert(s->pid_file_pathspec);
57020a3a 2915 assert(path_spec_owns_inotify_fd(s->pid_file_pathspec, fd));
3a111838 2916
718db961 2917 log_debug_unit(UNIT(s)->id, "inotify event for %s", UNIT(s)->id);
3a111838 2918
e14c2802 2919 if (path_spec_fd_event(p, events) < 0)
3a111838
MS
2920 goto fail;
2921
2922 if (service_retry_pid_file(s) == 0)
718db961 2923 return 0;
3a111838
MS
2924
2925 if (service_watch_pid_file(s) < 0)
2926 goto fail;
2927
718db961
LP
2928 return 0;
2929
3a111838
MS
2930fail:
2931 service_unwatch_pid_file(s);
f42806df 2932 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_RESOURCES);
718db961 2933 return 0;
3a111838
MS
2934}
2935
87f0e418
LP
2936static void service_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2937 Service *s = SERVICE(u);
f42806df 2938 ServiceResult f;
5cb5a6ff
LP
2939
2940 assert(s);
034c6ed7
LP
2941 assert(pid >= 0);
2942
96342de6
LN
2943 if (UNIT(s)->fragment_path ? is_clean_exit(code, status, &s->success_status) :
2944 is_clean_exit_lsb(code, status, &s->success_status))
f42806df
LP
2945 f = SERVICE_SUCCESS;
2946 else if (code == CLD_EXITED)
2947 f = SERVICE_FAILURE_EXIT_CODE;
2948 else if (code == CLD_KILLED)
2949 f = SERVICE_FAILURE_SIGNAL;
2950 else if (code == CLD_DUMPED)
2951 f = SERVICE_FAILURE_CORE_DUMP;
d06dacd0 2952 else
cfc4eb4c 2953 assert_not_reached("Unknown code");
034c6ed7
LP
2954
2955 if (s->main_pid == pid) {
db01f8b3
MS
2956 /* Forking services may occasionally move to a new PID.
2957 * As long as they update the PID file before exiting the old
2958 * PID, they're fine. */
5375410b 2959 if (service_load_pid_file(s, false) == 0)
db01f8b3 2960 return;
034c6ed7 2961
034c6ed7 2962 s->main_pid = 0;
6ea832a2 2963 exec_status_exit(&s->main_exec_status, &s->exec_context, pid, code, status);
034c6ed7 2964
867b3b7d 2965 if (s->main_command) {
fbeefb45
LP
2966 /* If this is not a forking service than the
2967 * main process got started and hence we copy
2968 * the exit status so that it is recorded both
2969 * as main and as control process exit
2970 * status */
2971
867b3b7d 2972 s->main_command->exec_status = s->main_exec_status;
b708e7ce 2973
867b3b7d 2974 if (s->main_command->ignore)
f42806df 2975 f = SERVICE_SUCCESS;
fbeefb45
LP
2976 } else if (s->exec_command[SERVICE_EXEC_START]) {
2977
2978 /* If this is a forked process, then we should
2979 * ignore the return value if this was
2980 * configured for the starter process */
2981
2982 if (s->exec_command[SERVICE_EXEC_START]->ignore)
2983 f = SERVICE_SUCCESS;
034c6ed7
LP
2984 }
2985
bbc9006e
MT
2986 log_struct_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2987 u->id,
23635a85
ZJS
2988 "MESSAGE=%s: main process exited, code=%s, status=%i/%s",
2989 u->id, sigchld_code_to_string(code), status,
2990 strna(code == CLD_EXITED
2991 ? exit_status_to_string(status, EXIT_STATUS_FULL)
2992 : signal_to_string(status)),
23635a85
ZJS
2993 "EXIT_CODE=%s", sigchld_code_to_string(code),
2994 "EXIT_STATUS=%i", status,
2995 NULL);
f42806df
LP
2996
2997 if (f != SERVICE_SUCCESS)
2998 s->result = f;
034c6ed7 2999
867b3b7d
LP
3000 if (s->main_command &&
3001 s->main_command->command_next &&
f42806df 3002 f == SERVICE_SUCCESS) {
034c6ed7 3003
34e9ba66
LP
3004 /* There is another command to *
3005 * execute, so let's do that. */
034c6ed7 3006
66870f90
ZJS
3007 log_debug_unit(u->id,
3008 "%s running next main command for state %s",
3009 u->id, service_state_to_string(s->state));
f42806df 3010 service_run_next_main(s);
034c6ed7 3011
34e9ba66
LP
3012 } else {
3013
3014 /* The service exited, so the service is officially
3015 * gone. */
867b3b7d 3016 s->main_command = NULL;
34e9ba66
LP
3017
3018 switch (s->state) {
3019
3020 case SERVICE_START_POST:
3021 case SERVICE_RELOAD:
3022 case SERVICE_STOP:
3023 /* Need to wait until the operation is
3024 * done */
c4653a4d 3025 break;
7d55e835 3026
34e9ba66
LP
3027 case SERVICE_START:
3028 if (s->type == SERVICE_ONESHOT) {
3029 /* This was our main goal, so let's go on */
f42806df 3030 if (f == SERVICE_SUCCESS)
34e9ba66
LP
3031 service_enter_start_post(s);
3032 else
f42806df 3033 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
34e9ba66 3034 break;
34e9ba66 3035 }
034c6ed7 3036
bfba3256
LP
3037 /* Fall through */
3038
34e9ba66 3039 case SERVICE_RUNNING:
f42806df 3040 service_enter_running(s, f);
34e9ba66 3041 break;
034c6ed7 3042
34e9ba66
LP
3043 case SERVICE_STOP_SIGTERM:
3044 case SERVICE_STOP_SIGKILL:
5cb5a6ff 3045
34e9ba66 3046 if (!control_pid_good(s))
f42806df 3047 service_enter_stop_post(s, f);
5cb5a6ff 3048
34e9ba66
LP
3049 /* If there is still a control process, wait for that first */
3050 break;
3051
3052 default:
3053 assert_not_reached("Uh, main process died at wrong time.");
3054 }
034c6ed7 3055 }
5cb5a6ff 3056
034c6ed7 3057 } else if (s->control_pid == pid) {
34e9ba66
LP
3058 s->control_pid = 0;
3059
b708e7ce 3060 if (s->control_command) {
117dcc57
ZJS
3061 exec_status_exit(&s->control_command->exec_status,
3062 &s->exec_context, pid, code, status);
a16e1123 3063
b708e7ce 3064 if (s->control_command->ignore)
f42806df 3065 f = SERVICE_SUCCESS;
b708e7ce
LP
3066 }
3067
66870f90
ZJS
3068 log_full_unit(f == SERVICE_SUCCESS ? LOG_DEBUG : LOG_NOTICE, u->id,
3069 "%s: control process exited, code=%s status=%i",
3070 u->id, sigchld_code_to_string(code), status);
f42806df
LP
3071
3072 if (f != SERVICE_SUCCESS)
3073 s->result = f;
034c6ed7 3074
88f3e0c9
LP
3075 /* Immediately get rid of the cgroup, so that the
3076 * kernel doesn't delay the cgroup empty messages for
3077 * the service cgroup any longer than necessary */
4ad49000 3078 service_kill_control_processes(s);
88f3e0c9 3079
34e9ba66
LP
3080 if (s->control_command &&
3081 s->control_command->command_next &&
f42806df 3082 f == SERVICE_SUCCESS) {
034c6ed7
LP
3083
3084 /* There is another command to *
3085 * execute, so let's do that. */
3086
66870f90
ZJS
3087 log_debug_unit(u->id,
3088 "%s running next control command for state %s",
3089 u->id, service_state_to_string(s->state));
f42806df 3090 service_run_next_control(s);
034c6ed7 3091
80876c20 3092 } else {
034c6ed7
LP
3093 /* No further commands for this step, so let's
3094 * figure out what to do next */
3095
a16e1123
LP
3096 s->control_command = NULL;
3097 s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
3098
66870f90
ZJS
3099 log_debug_unit(u->id,
3100 "%s got final SIGCHLD for state %s",
3101 u->id, service_state_to_string(s->state));
bd982a8b 3102
034c6ed7
LP
3103 switch (s->state) {
3104
3105 case SERVICE_START_PRE:
f42806df 3106 if (f == SERVICE_SUCCESS)
034c6ed7
LP
3107 service_enter_start(s);
3108 else
f42806df 3109 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
034c6ed7
LP
3110 break;
3111
3112 case SERVICE_START:
bfba3256
LP
3113 if (s->type != SERVICE_FORKING)
3114 /* Maybe spurious event due to a reload that changed the type? */
3115 break;
034c6ed7 3116
f42806df
LP
3117 if (f != SERVICE_SUCCESS) {
3118 service_enter_signal(s, SERVICE_FINAL_SIGTERM, f);
3a111838
MS
3119 break;
3120 }
034c6ed7 3121
3a111838 3122 if (s->pid_file) {
f42806df
LP
3123 bool has_start_post;
3124 int r;
3125
3a111838
MS
3126 /* Let's try to load the pid file here if we can.
3127 * The PID file might actually be created by a START_POST
3128 * script. In that case don't worry if the loading fails. */
f42806df
LP
3129
3130 has_start_post = !!s->exec_command[SERVICE_EXEC_START_POST];
3131 r = service_load_pid_file(s, !has_start_post);
3a111838
MS
3132 if (!has_start_post && r < 0) {
3133 r = service_demand_pid_file(s);
3134 if (r < 0 || !cgroup_good(s))
f42806df 3135 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3a111838
MS
3136 break;
3137 }
034c6ed7 3138 } else
3a111838 3139 service_search_main_pid(s);
034c6ed7 3140
3a111838 3141 service_enter_start_post(s);
034c6ed7
LP
3142 break;
3143
3144 case SERVICE_START_POST:
f42806df
LP
3145 if (f != SERVICE_SUCCESS) {
3146 service_enter_stop(s, f);
2096e009 3147 break;
034c6ed7
LP
3148 }
3149
2096e009 3150 if (s->pid_file) {
f42806df
LP
3151 int r;
3152
3153 r = service_load_pid_file(s, true);
2096e009
MS
3154 if (r < 0) {
3155 r = service_demand_pid_file(s);
3156 if (r < 0 || !cgroup_good(s))
f42806df 3157 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
2096e009
MS
3158 break;
3159 }
3160 } else
3161 service_search_main_pid(s);
3162
f42806df 3163 service_enter_running(s, SERVICE_SUCCESS);
3185a36b 3164 break;
034c6ed7
LP
3165
3166 case SERVICE_RELOAD:
f42806df 3167 if (f == SERVICE_SUCCESS) {
5375410b 3168 service_load_pid_file(s, true);
3185a36b
LP
3169 service_search_main_pid(s);
3170 }
3171
f42806df
LP
3172 s->reload_result = f;
3173 service_enter_running(s, SERVICE_SUCCESS);
034c6ed7
LP
3174 break;
3175
3176 case SERVICE_STOP:
f42806df 3177 service_enter_signal(s, SERVICE_STOP_SIGTERM, f);
034c6ed7
LP
3178 break;
3179
3180 case SERVICE_STOP_SIGTERM:
3181 case SERVICE_STOP_SIGKILL:
3182 if (main_pid_good(s) <= 0)
f42806df 3183 service_enter_stop_post(s, f);
034c6ed7
LP
3184
3185 /* If there is still a service
3186 * process around, wait until
3187 * that one quit, too */
3188 break;
3189
3190 case SERVICE_STOP_POST:
3191 case SERVICE_FINAL_SIGTERM:
3192 case SERVICE_FINAL_SIGKILL:
f42806df 3193 service_enter_dead(s, f, true);
034c6ed7
LP
3194 break;
3195
3196 default:
3197 assert_not_reached("Uh, control process died at wrong time.");
3198 }
3199 }
8c47c732 3200 }
c4e2ceae
LP
3201
3202 /* Notify clients about changed exit status */
3203 unit_add_to_dbus_queue(u);
034c6ed7
LP
3204}
3205
718db961
LP
3206static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
3207 Service *s = SERVICE(userdata);
034c6ed7
LP
3208
3209 assert(s);
718db961 3210 assert(source == s->timer_event_source);
034c6ed7
LP
3211
3212 switch (s->state) {
3213
3214 case SERVICE_START_PRE:
3215 case SERVICE_START:
718db961
LP
3216 log_warning_unit(UNIT(s)->id,
3217 "%s operation timed out. Terminating.", UNIT(s)->id);
f42806df 3218 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
80876c20
LP
3219 break;
3220
034c6ed7 3221 case SERVICE_START_POST:
718db961
LP
3222 log_warning_unit(UNIT(s)->id,
3223 "%s operation timed out. Stopping.", UNIT(s)->id);
f42806df 3224 service_enter_stop(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3225 break;
3226
e2f3b44c 3227 case SERVICE_RELOAD:
718db961
LP
3228 log_warning_unit(UNIT(s)->id,
3229 "%s operation timed out. Stopping.", UNIT(s)->id);
f42806df
LP
3230 s->reload_result = SERVICE_FAILURE_TIMEOUT;
3231 service_enter_running(s, SERVICE_SUCCESS);
e2f3b44c
LP
3232 break;
3233
034c6ed7 3234 case SERVICE_STOP:
718db961
LP
3235 log_warning_unit(UNIT(s)->id,
3236 "%s stopping timed out. Terminating.", UNIT(s)->id);
f42806df 3237 service_enter_signal(s, SERVICE_STOP_SIGTERM, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3238 break;
3239
3240 case SERVICE_STOP_SIGTERM:
4819ff03 3241 if (s->kill_context.send_sigkill) {
718db961
LP
3242 log_warning_unit(UNIT(s)->id,
3243 "%s stopping timed out. Killing.", UNIT(s)->id);
f42806df 3244 service_enter_signal(s, SERVICE_STOP_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 3245 } else {
718db961
LP
3246 log_warning_unit(UNIT(s)->id,
3247 "%s stopping timed out. Skipping SIGKILL.", UNIT(s)->id);
f42806df 3248 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
ba035df2
LP
3249 }
3250
034c6ed7
LP
3251 break;
3252
3253 case SERVICE_STOP_SIGKILL:
35b8ca3a 3254 /* Uh, we sent a SIGKILL and it is still not gone?
034c6ed7
LP
3255 * Must be something we cannot kill, so let's just be
3256 * weirded out and continue */
3257
718db961
LP
3258 log_warning_unit(UNIT(s)->id,
3259 "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
f42806df 3260 service_enter_stop_post(s, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3261 break;
3262
3263 case SERVICE_STOP_POST:
718db961
LP
3264 log_warning_unit(UNIT(s)->id,
3265 "%s stopping timed out (2). Terminating.", UNIT(s)->id);
f42806df 3266 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_TIMEOUT);
034c6ed7
LP
3267 break;
3268
3269 case SERVICE_FINAL_SIGTERM:
4819ff03 3270 if (s->kill_context.send_sigkill) {
718db961
LP
3271 log_warning_unit(UNIT(s)->id,
3272 "%s stopping timed out (2). Killing.", UNIT(s)->id);
f42806df 3273 service_enter_signal(s, SERVICE_FINAL_SIGKILL, SERVICE_FAILURE_TIMEOUT);
ba035df2 3274 } else {
718db961 3275 log_warning_unit(UNIT(s)->id,
66870f90 3276 "%s stopping timed out (2). Skipping SIGKILL. Entering failed mode.",
718db961 3277 UNIT(s)->id);
f42806df 3278 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, false);
ba035df2
LP
3279 }
3280
034c6ed7
LP
3281 break;
3282
3283 case SERVICE_FINAL_SIGKILL:
718db961
LP
3284 log_warning_unit(UNIT(s)->id,
3285 "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s)->id);
f42806df 3286 service_enter_dead(s, SERVICE_FAILURE_TIMEOUT, true);
034c6ed7
LP
3287 break;
3288
3289 case SERVICE_AUTO_RESTART:
718db961
LP
3290 log_info_unit(UNIT(s)->id,
3291 "%s holdoff time over, scheduling restart.", UNIT(s)->id);
034c6ed7
LP
3292 service_enter_restart(s);
3293 break;
3294
3295 default:
3296 assert_not_reached("Timeout at wrong time.");
3297 }
718db961
LP
3298
3299 return 0;
3300}
3301
3302static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
3303 Service *s = SERVICE(userdata);
3304
3305 assert(s);
3306 assert(source == s->watchdog_event_source);
3307
3308 service_handle_watchdog(s);
3309 return 0;
5cb5a6ff
LP
3310}
3311
4ad49000 3312static void service_notify_cgroup_empty_event(Unit *u) {
8e274523
LP
3313 Service *s = SERVICE(u);
3314
3315 assert(u);
3316
6c12b52e 3317 log_debug_unit(u->id, "%s: cgroup is empty", u->id);
8e274523
LP
3318
3319 switch (s->state) {
3320
3321 /* Waiting for SIGCHLD is usually more interesting,
3322 * because it includes return codes/signals. Which is
3323 * why we ignore the cgroup events for most cases,
3324 * except when we don't know pid which to expect the
3325 * SIGCHLD for. */
3326
3a111838
MS
3327 case SERVICE_START:
3328 case SERVICE_START_POST:
3329 /* If we were hoping for the daemon to write its PID file,
3330 * we can give up now. */
3331 if (s->pid_file_pathspec) {
66870f90
ZJS
3332 log_warning_unit(u->id,
3333 "%s never wrote its PID file. Failing.", UNIT(s)->id);
3a111838
MS
3334 service_unwatch_pid_file(s);
3335 if (s->state == SERVICE_START)
f42806df 3336 service_enter_signal(s, SERVICE_FINAL_SIGTERM, SERVICE_FAILURE_RESOURCES);
3a111838 3337 else
f42806df 3338 service_enter_stop(s, SERVICE_FAILURE_RESOURCES);
3a111838
MS
3339 }
3340 break;
3341
8e274523 3342 case SERVICE_RUNNING:
f42806df
LP
3343 /* service_enter_running() will figure out what to do */
3344 service_enter_running(s, SERVICE_SUCCESS);
8e274523
LP
3345 break;
3346
28708d8a
LP
3347 case SERVICE_STOP_SIGTERM:
3348 case SERVICE_STOP_SIGKILL:
6dfa5494 3349
28708d8a 3350 if (main_pid_good(s) <= 0 && !control_pid_good(s))
f42806df 3351 service_enter_stop_post(s, SERVICE_SUCCESS);
28708d8a
LP
3352
3353 break;
3354
7f97f0fe
LP
3355 case SERVICE_FINAL_SIGTERM:
3356 case SERVICE_FINAL_SIGKILL:
3357 if (main_pid_good(s) <= 0 && !control_pid_good(s))
e201a038 3358 service_enter_dead(s, SERVICE_SUCCESS, true);
7f97f0fe
LP
3359
3360 break;
3361
8e274523
LP
3362 default:
3363 ;
3364 }
3365}
3366
c952c6ec 3367static void service_notify_message(Unit *u, pid_t pid, char **tags) {
8c47c732
LP
3368 Service *s = SERVICE(u);
3369 const char *e;
3370
3371 assert(u);
3372
c952c6ec 3373 if (s->notify_access == NOTIFY_NONE) {
66870f90
ZJS
3374 log_warning_unit(u->id,
3375 "%s: Got notification message from PID %lu, but reception is disabled.",
3376 u->id, (unsigned long) pid);
c952c6ec
LP
3377 return;
3378 }
3379
3380 if (s->notify_access == NOTIFY_MAIN && pid != s->main_pid) {
66870f90
ZJS
3381 log_warning_unit(u->id,
3382 "%s: Got notification message from PID %lu, but reception only permitted for PID %lu",
3383 u->id, (unsigned long) pid, (unsigned long) s->main_pid);
c952c6ec
LP
3384 return;
3385 }
3386
66870f90
ZJS
3387 log_debug_unit(u->id,
3388 "%s: Got message", u->id);
8c47c732
LP
3389
3390 /* Interpret MAINPID= */
3391 if ((e = strv_find_prefix(tags, "MAINPID=")) &&
3392 (s->state == SERVICE_START ||
3393 s->state == SERVICE_START_POST ||
3394 s->state == SERVICE_RUNNING ||
3395 s->state == SERVICE_RELOAD)) {
8c47c732 3396
5925dd3c 3397 if (parse_pid(e + 8, &pid) < 0)
66870f90
ZJS
3398 log_warning_unit(u->id,
3399 "Failed to parse notification message %s", e);
8c47c732 3400 else {
66870f90
ZJS
3401 log_debug_unit(u->id,
3402 "%s: got %s", u->id, e);
5925dd3c 3403 service_set_main_pid(s, pid);
7400b9d2 3404 unit_watch_pid(UNIT(s), pid);
8c47c732
LP
3405 }
3406 }
3407
3408 /* Interpret READY= */
3409 if (s->type == SERVICE_NOTIFY &&
3410 s->state == SERVICE_START &&
3411 strv_find(tags, "READY=1")) {
66870f90
ZJS
3412 log_debug_unit(u->id,
3413 "%s: got READY=1", u->id);
8c47c732
LP
3414
3415 service_enter_start_post(s);
3416 }
3417
3418 /* Interpret STATUS= */
7f110ff9
LP
3419 e = strv_find_prefix(tags, "STATUS=");
3420 if (e) {
8c47c732
LP
3421 char *t;
3422
3a2776bc 3423 if (e[7]) {
7f110ff9
LP
3424
3425 if (!utf8_is_valid(e+7)) {
66870f90
ZJS
3426 log_warning_unit(u->id,
3427 "Status message in notification is not UTF-8 clean.");
7f110ff9
LP
3428 return;
3429 }
3430
3431 t = strdup(e+7);
3432 if (!t) {
66870f90
ZJS
3433 log_error_unit(u->id,
3434 "Failed to allocate string.");
3a2776bc
LP
3435 return;
3436 }
3437
66870f90
ZJS
3438 log_debug_unit(u->id,
3439 "%s: got %s", u->id, e);
8c47c732 3440
3a2776bc
LP
3441 free(s->status_text);
3442 s->status_text = t;
3443 } else {
3444 free(s->status_text);
3445 s->status_text = NULL;
3446 }
8c47c732 3447
8c47c732 3448 }
a6927d7f 3449 if (strv_find(tags, "WATCHDOG=1")) {
66870f90
ZJS
3450 log_debug_unit(u->id,
3451 "%s: got WATCHDOG=1", u->id);
90527fbb
MO
3452 if (dual_timestamp_is_set(&s->watchdog_timestamp))
3453 service_reset_watchdog(s);
a6927d7f 3454 }
c4e2ceae
LP
3455
3456 /* Notify clients about changed status or main pid */
3457 unit_add_to_dbus_queue(u);
8c47c732
LP
3458}
3459
07459bb6 3460#ifdef HAVE_SYSV_COMPAT
de3910a3 3461
2c4104f0 3462static int service_enumerate(Manager *m) {
2c4104f0
LP
3463 char **p;
3464 unsigned i;
7fd1b19b
HH
3465 _cleanup_closedir_ DIR *d = NULL;
3466 _cleanup_free_ char *path = NULL, *fpath = NULL, *name = NULL;
b92bea5d 3467 Set *runlevel_services[ELEMENTSOF(rcnd_table)] = {};
7fd1b19b 3468 _cleanup_set_free_ Set *shutdown_services = NULL;
c68364b7
LP
3469 Unit *service;
3470 Iterator j;
2c4104f0
LP
3471 int r;
3472
3473 assert(m);
3474
67445f4e 3475 if (m->running_as != SYSTEMD_SYSTEM)
b1bc08e5
LP
3476 return 0;
3477
84e3543e 3478 STRV_FOREACH(p, m->lookup_paths.sysvrcnd_path)
09cd1ab1 3479 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++) {
2c4104f0
LP
3480 struct dirent *de;
3481
3482 free(path);
b7def684 3483 path = strjoin(*p, "/", rcnd_table[i].path, NULL);
70132bd0 3484 if (!path) {
2c4104f0
LP
3485 r = -ENOMEM;
3486 goto finish;
3487 }
3488
3489 if (d)
3490 closedir(d);
3491
117dcc57
ZJS
3492 d = opendir(path);
3493 if (!d) {
2c4104f0 3494 if (errno != ENOENT)
f5f6d0e2 3495 log_warning("opendir(%s) failed: %m", path);
2c4104f0
LP
3496
3497 continue;
3498 }
3499
3500 while ((de = readdir(d))) {
db06e3b6 3501 int a, b;
2c4104f0
LP
3502
3503 if (ignore_file(de->d_name))
3504 continue;
3505
3506 if (de->d_name[0] != 'S' && de->d_name[0] != 'K')
3507 continue;
3508
3509 if (strlen(de->d_name) < 4)
3510 continue;
3511
db06e3b6
LP
3512 a = undecchar(de->d_name[1]);
3513 b = undecchar(de->d_name[2]);
3514
3515 if (a < 0 || b < 0)
3516 continue;
3517
2c4104f0 3518 free(fpath);
b7def684 3519 fpath = strjoin(path, "/", de->d_name, NULL);
8ea913b2 3520 if (!fpath) {
2c4104f0
LP
3521 r = -ENOMEM;
3522 goto finish;
3523 }
3524
3525 if (access(fpath, X_OK) < 0) {
3526
3527 if (errno != ENOENT)
f5f6d0e2 3528 log_warning("access() failed on %s: %m", fpath);
2c4104f0
LP
3529
3530 continue;
3531 }
3532
3533 free(name);
117dcc57
ZJS
3534 name = sysv_translate_name(de->d_name + 3);
3535 if (!name) {
3536 r = log_oom();
2c4104f0
LP
3537 goto finish;
3538 }
3539
66870f90
ZJS
3540 r = manager_load_unit_prepare(m, name, NULL, NULL, &service);
3541 if (r < 0) {
fbe9f3a9
LP
3542 log_warning("Failed to prepare unit %s: %s", name, strerror(-r));
3543 continue;
3544 }
2c4104f0 3545
c68364b7
LP
3546 if (de->d_name[0] == 'S') {
3547
3cdebc21 3548 if (rcnd_table[i].type == RUNLEVEL_UP) {
ea87ca5a
LP
3549 SERVICE(service)->sysv_start_priority_from_rcnd =
3550 MAX(a*10 + b, SERVICE(service)->sysv_start_priority_from_rcnd);
db06e3b6 3551
c68364b7 3552 SERVICE(service)->sysv_enabled = true;
f73d93a4 3553 }
db06e3b6 3554
117dcc57
ZJS
3555 r = set_ensure_allocated(&runlevel_services[i],
3556 trivial_hash_func, trivial_compare_func);
3557 if (r < 0)
c68364b7 3558 goto finish;
2c4104f0 3559
117dcc57
ZJS
3560 r = set_put(runlevel_services[i], service);
3561 if (r < 0)
2c4104f0 3562 goto finish;
23a177ef 3563
fc5df99e 3564 } else if (de->d_name[0] == 'K' &&
3cdebc21 3565 (rcnd_table[i].type == RUNLEVEL_DOWN)) {
6542952f 3566
117dcc57
ZJS
3567 r = set_ensure_allocated(&shutdown_services,
3568 trivial_hash_func, trivial_compare_func);
3569 if (r < 0)
c68364b7
LP
3570 goto finish;
3571
117dcc57
ZJS
3572 r = set_put(shutdown_services, service);
3573 if (r < 0)
2c4104f0
LP
3574 goto finish;
3575 }
3576 }
3577 }
3578
c68364b7
LP
3579 /* Now we loaded all stubs and are aware of the lowest
3580 start-up priority for all services, not let's actually load
3581 the services, this will also tell us which services are
3582 actually native now */
3583 manager_dispatch_load_queue(m);
3584
3585 /* If this is a native service, rely on native ways to pull in
3586 * a service, don't pull it in via sysv rcN.d links. */
3587 for (i = 0; i < ELEMENTSOF(rcnd_table); i ++)
3588 SET_FOREACH(service, runlevel_services[i], j) {
3589 service = unit_follow_merge(service);
3590
ac155bb8 3591 if (service->fragment_path)
c68364b7
LP
3592 continue;
3593
117dcc57
ZJS
3594 r = unit_add_two_dependencies_by_name_inverse(
3595 service, UNIT_AFTER, UNIT_WANTS,
3596 rcnd_table[i].target, NULL, true);
3597 if (r < 0)
c68364b7
LP
3598 goto finish;
3599 }
3600
3601 /* We honour K links only for halt/reboot. For the normal
3602 * runlevels we assume the stop jobs will be implicitly added
35b8ca3a 3603 * by the core logic. Also, we don't really distinguish here
c68364b7 3604 * between the runlevels 0 and 6 and just add them to the
3cdebc21 3605 * special shutdown target. */
c68364b7
LP
3606 SET_FOREACH(service, shutdown_services, j) {
3607 service = unit_follow_merge(service);
3608
ac155bb8 3609 if (service->fragment_path)
c68364b7
LP
3610 continue;
3611
117dcc57
ZJS
3612 r = unit_add_two_dependencies_by_name(
3613 service, UNIT_BEFORE, UNIT_CONFLICTS,
3614 SPECIAL_SHUTDOWN_TARGET, NULL, true);
3615 if (r < 0)
c68364b7
LP
3616 goto finish;
3617 }
3618
2c4104f0
LP
3619 r = 0;
3620
3621finish:
fbe9f3a9 3622
c68364b7
LP
3623 for (i = 0; i < ELEMENTSOF(rcnd_table); i++)
3624 set_free(runlevel_services[i]);
2c4104f0
LP
3625
3626 return r;
3627}
07459bb6 3628#endif
2c4104f0 3629
05e343b7
LP
3630static void service_bus_name_owner_change(
3631 Unit *u,
3632 const char *name,
3633 const char *old_owner,
3634 const char *new_owner) {
3635
3636 Service *s = SERVICE(u);
718db961 3637 int r;
05e343b7
LP
3638
3639 assert(s);
3640 assert(name);
3641
3642 assert(streq(s->bus_name, name));
3643 assert(old_owner || new_owner);
3644
3645 if (old_owner && new_owner)
66870f90
ZJS
3646 log_debug_unit(u->id,
3647 "%s's D-Bus name %s changed owner from %s to %s",
3648 u->id, name, old_owner, new_owner);
05e343b7 3649 else if (old_owner)
66870f90
ZJS
3650 log_debug_unit(u->id,
3651 "%s's D-Bus name %s no longer registered by %s",
3652 u->id, name, old_owner);
05e343b7 3653 else
66870f90
ZJS
3654 log_debug_unit(u->id,
3655 "%s's D-Bus name %s now registered by %s",
3656 u->id, name, new_owner);
05e343b7
LP
3657
3658 s->bus_name_good = !!new_owner;
3659
3660 if (s->type == SERVICE_DBUS) {
3661
3662 /* service_enter_running() will figure out what to
3663 * do */
3664 if (s->state == SERVICE_RUNNING)
f42806df 3665 service_enter_running(s, SERVICE_SUCCESS);
05e343b7
LP
3666 else if (s->state == SERVICE_START && new_owner)
3667 service_enter_start_post(s);
3668
3669 } else if (new_owner &&
3670 s->main_pid <= 0 &&
3671 (s->state == SERVICE_START ||
3672 s->state == SERVICE_START_POST ||
3673 s->state == SERVICE_RUNNING ||
3674 s->state == SERVICE_RELOAD)) {
3675
5b12334d 3676 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
718db961 3677 pid_t pid;
05e343b7 3678
718db961 3679 /* Try to acquire PID from bus service */
05e343b7 3680
49b832c5 3681 r = sd_bus_get_owner(u->manager->api_bus, name, SD_BUS_CREDS_PID, &creds);
5b12334d
LP
3682 if (r >= 0)
3683 r = sd_bus_creds_get_pid(creds, &pid);
718db961
LP
3684 if (r >= 0) {
3685 log_debug_unit(u->id, "%s's D-Bus name %s is now owned by process %u", u->id, name, (unsigned) pid);
05e343b7 3686
718db961
LP
3687 service_set_main_pid(s, pid);
3688 unit_watch_pid(UNIT(s), pid);
3689 }
7400b9d2 3690 }
05e343b7
LP
3691}
3692
6cf6bbc2 3693int service_set_socket_fd(Service *s, int fd, Socket *sock) {
57020a3a 3694
4f2d528d
LP
3695 assert(s);
3696 assert(fd >= 0);
3697
3698 /* This is called by the socket code when instantiating a new
3699 * service for a stream socket and the socket needs to be
3700 * configured. */
3701
1124fe6f 3702 if (UNIT(s)->load_state != UNIT_LOADED)
4f2d528d
LP
3703 return -EINVAL;
3704
3705 if (s->socket_fd >= 0)
3706 return -EBUSY;
3707
3708 if (s->state != SERVICE_DEAD)
3709 return -EAGAIN;
3710
3711 s->socket_fd = fd;
6cf6bbc2 3712
57020a3a
LP
3713 unit_ref_set(&s->accept_socket, UNIT(sock));
3714
3715 return unit_add_two_dependencies(UNIT(sock), UNIT_BEFORE, UNIT_TRIGGERS, UNIT(s), false);
4f2d528d
LP
3716}
3717
fdf20a31 3718static void service_reset_failed(Unit *u) {
5632e374
LP
3719 Service *s = SERVICE(u);
3720
3721 assert(s);
3722
fdf20a31 3723 if (s->state == SERVICE_FAILED)
5632e374
LP
3724 service_set_state(s, SERVICE_DEAD);
3725
f42806df
LP
3726 s->result = SERVICE_SUCCESS;
3727 s->reload_result = SERVICE_SUCCESS;
451b34cc
LP
3728
3729 RATELIMIT_RESET(s->start_limit);
5632e374
LP
3730}
3731
718db961 3732static int service_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
8a0867d6 3733 Service *s = SERVICE(u);
41efeaec 3734
814cc562 3735 return unit_kill_common(u, who, signo, s->main_pid, s->control_pid, error);
8a0867d6
LP
3736}
3737
94f04347
LP
3738static const char* const service_state_table[_SERVICE_STATE_MAX] = {
3739 [SERVICE_DEAD] = "dead",
3740 [SERVICE_START_PRE] = "start-pre",
3741 [SERVICE_START] = "start",
3742 [SERVICE_START_POST] = "start-post",
3743 [SERVICE_RUNNING] = "running",
80876c20 3744 [SERVICE_EXITED] = "exited",
94f04347
LP
3745 [SERVICE_RELOAD] = "reload",
3746 [SERVICE_STOP] = "stop",
3747 [SERVICE_STOP_SIGTERM] = "stop-sigterm",
3748 [SERVICE_STOP_SIGKILL] = "stop-sigkill",
3749 [SERVICE_STOP_POST] = "stop-post",
3750 [SERVICE_FINAL_SIGTERM] = "final-sigterm",
3751 [SERVICE_FINAL_SIGKILL] = "final-sigkill",
fdf20a31 3752 [SERVICE_FAILED] = "failed",
94f04347
LP
3753 [SERVICE_AUTO_RESTART] = "auto-restart",
3754};
3755
3756DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState);
3757
3758static const char* const service_restart_table[_SERVICE_RESTART_MAX] = {
525ee6f4
LP
3759 [SERVICE_RESTART_NO] = "no",
3760 [SERVICE_RESTART_ON_SUCCESS] = "on-success",
50caaedb 3761 [SERVICE_RESTART_ON_FAILURE] = "on-failure",
dc99a976 3762 [SERVICE_RESTART_ON_WATCHDOG] = "on-watchdog",
50caaedb
LP
3763 [SERVICE_RESTART_ON_ABORT] = "on-abort",
3764 [SERVICE_RESTART_ALWAYS] = "always"
94f04347
LP
3765};
3766
3767DEFINE_STRING_TABLE_LOOKUP(service_restart, ServiceRestart);
3768
3769static const char* const service_type_table[_SERVICE_TYPE_MAX] = {
94f04347 3770 [SERVICE_SIMPLE] = "simple",
0d624a78 3771 [SERVICE_FORKING] = "forking",
34e9ba66 3772 [SERVICE_ONESHOT] = "oneshot",
8c47c732 3773 [SERVICE_DBUS] = "dbus",
f2b68789
LP
3774 [SERVICE_NOTIFY] = "notify",
3775 [SERVICE_IDLE] = "idle"
94f04347
LP
3776};
3777
3778DEFINE_STRING_TABLE_LOOKUP(service_type, ServiceType);
3779
e537352b 3780static const char* const service_exec_command_table[_SERVICE_EXEC_COMMAND_MAX] = {
94f04347
LP
3781 [SERVICE_EXEC_START_PRE] = "ExecStartPre",
3782 [SERVICE_EXEC_START] = "ExecStart",
3783 [SERVICE_EXEC_START_POST] = "ExecStartPost",
3784 [SERVICE_EXEC_RELOAD] = "ExecReload",
3785 [SERVICE_EXEC_STOP] = "ExecStop",
3786 [SERVICE_EXEC_STOP_POST] = "ExecStopPost",
3787};
3788
3789DEFINE_STRING_TABLE_LOOKUP(service_exec_command, ServiceExecCommand);
3790
c952c6ec
LP
3791static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = {
3792 [NOTIFY_NONE] = "none",
3793 [NOTIFY_MAIN] = "main",
3794 [NOTIFY_ALL] = "all"
3795};
3796
3797DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess);
3798
f42806df
LP
3799static const char* const service_result_table[_SERVICE_RESULT_MAX] = {
3800 [SERVICE_SUCCESS] = "success",
3801 [SERVICE_FAILURE_RESOURCES] = "resources",
3802 [SERVICE_FAILURE_TIMEOUT] = "timeout",
3803 [SERVICE_FAILURE_EXIT_CODE] = "exit-code",
3804 [SERVICE_FAILURE_SIGNAL] = "signal",
bb242b7b 3805 [SERVICE_FAILURE_CORE_DUMP] = "core-dump",
8d1b002a
LP
3806 [SERVICE_FAILURE_WATCHDOG] = "watchdog",
3807 [SERVICE_FAILURE_START_LIMIT] = "start-limit"
f42806df
LP
3808};
3809
3810DEFINE_STRING_TABLE_LOOKUP(service_result, ServiceResult);
3811
4b939747
MO
3812static const char* const start_limit_action_table[_SERVICE_START_LIMIT_MAX] = {
3813 [SERVICE_START_LIMIT_NONE] = "none",
3814 [SERVICE_START_LIMIT_REBOOT] = "reboot",
3815 [SERVICE_START_LIMIT_REBOOT_FORCE] = "reboot-force",
3816 [SERVICE_START_LIMIT_REBOOT_IMMEDIATE] = "reboot-immediate"
3817};
3818DEFINE_STRING_TABLE_LOOKUP(start_limit_action, StartLimitAction);
3819
87f0e418 3820const UnitVTable service_vtable = {
7d17cfbc 3821 .object_size = sizeof(Service),
718db961
LP
3822 .exec_context_offset = offsetof(Service, exec_context),
3823 .cgroup_context_offset = offsetof(Service, cgroup_context),
3824 .kill_context_offset = offsetof(Service, kill_context),
613b411c 3825 .exec_runtime_offset = offsetof(Service, exec_runtime),
3ef63c31 3826
f975e971
LP
3827 .sections =
3828 "Unit\0"
3829 "Service\0"
3830 "Install\0",
4ad49000 3831 .private_section = "Service",
71645aca 3832
034c6ed7
LP
3833 .init = service_init,
3834 .done = service_done,
a16e1123
LP
3835 .load = service_load,
3836
3837 .coldplug = service_coldplug,
034c6ed7 3838
5cb5a6ff
LP
3839 .dump = service_dump,
3840
3841 .start = service_start,
3842 .stop = service_stop,
3843 .reload = service_reload,
3844
034c6ed7
LP
3845 .can_reload = service_can_reload,
3846
8a0867d6
LP
3847 .kill = service_kill,
3848
a16e1123
LP
3849 .serialize = service_serialize,
3850 .deserialize_item = service_deserialize_item,
3851
5cb5a6ff 3852 .active_state = service_active_state,
10a94420 3853 .sub_state_to_string = service_sub_state_to_string,
5cb5a6ff 3854
701cc384
LP
3855 .check_gc = service_check_gc,
3856 .check_snapshot = service_check_snapshot,
3857
034c6ed7 3858 .sigchld_event = service_sigchld_event,
2c4104f0 3859
fdf20a31 3860 .reset_failed = service_reset_failed,
5632e374 3861
4ad49000 3862 .notify_cgroup_empty = service_notify_cgroup_empty_event,
8c47c732 3863 .notify_message = service_notify_message,
8e274523 3864
05e343b7 3865 .bus_name_owner_change = service_bus_name_owner_change,
05e343b7 3866
c4e2ceae 3867 .bus_interface = "org.freedesktop.systemd1.Service",
718db961
LP
3868 .bus_vtable = bus_service_vtable,
3869 .bus_changing_properties = bus_service_changing_properties,
74c964d3
LP
3870 .bus_set_property = bus_service_set_property,
3871 .bus_commit_properties = bus_service_commit_properties,
4139c1b2 3872
07459bb6 3873#ifdef HAVE_SYSV_COMPAT
c6918296 3874 .enumerate = service_enumerate,
07459bb6 3875#endif
718db961
LP
3876
3877 .can_transient = true,
3878
c6918296
MS
3879 .status_message_formats = {
3880 .starting_stopping = {
3881 [0] = "Starting %s...",
3882 [1] = "Stopping %s...",
3883 },
3884 .finished_start_job = {
3885 [JOB_DONE] = "Started %s.",
3886 [JOB_FAILED] = "Failed to start %s.",
3887 [JOB_DEPENDENCY] = "Dependency failed for %s.",
3888 [JOB_TIMEOUT] = "Timed out starting %s.",
3889 },
3890 .finished_stop_job = {
3891 [JOB_DONE] = "Stopped %s.",
3892 [JOB_FAILED] = "Stopped (with error) %s.",
3893 [JOB_TIMEOUT] = "Timed out stopping %s.",
3894 },
3895 },
5cb5a6ff 3896};