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