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