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