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