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