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