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