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