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