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