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