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