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