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