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