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