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