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