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