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