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