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