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