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