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