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